Compare commits
9
Commits
e1c2b13d1f
...
94463b3cea
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
94463b3cea | ||
|
|
2563ec3f69 | ||
|
|
b4f07272d8 | ||
|
|
357f8f2bd4 | ||
|
|
0f58a9cbfe | ||
|
|
dd53613758 | ||
|
|
277664d2d9 | ||
|
|
e72932456a | ||
|
|
edce5bac29 |
@@ -51,7 +51,8 @@ deno task build && deno task server # packs the mods and starts a se
|
||||
|
||||
**Entities**
|
||||
|
||||
- [Entities](docs/modding/entities/index.md): animals, monsters, natural spawning, scripted entities and entity models
|
||||
- [Entities](docs/modding/entities/index.md): animals, monsters, custom behaviors and their goals, how mobs get around,
|
||||
natural spawning, scripted entities and entity models
|
||||
- [Players](docs/modding/entities/players.md): the player API, health and hunger
|
||||
|
||||
**Inventories**
|
||||
|
||||
@@ -249,7 +249,7 @@ export interface BuiltinGoals {
|
||||
nearest_attackable_player(): BuiltinGoal;
|
||||
}
|
||||
|
||||
// a mob, the way its behavior's goals see it. refs are made fresh, so compare them by id
|
||||
// a mob, the way its behavior's goals see it. each mob has one, so a target can be compared with ===
|
||||
export interface MobRef extends LivingRef {
|
||||
readonly type: Id;
|
||||
readonly position: Readonly<Position>;
|
||||
@@ -266,9 +266,17 @@ export interface MobRef extends LivingRef {
|
||||
readonly last_attacker: Player | MobRef | undefined;
|
||||
// a number from 0 to 1, from the mob's own random, which tests replace
|
||||
random(): number;
|
||||
// walks toward x y z until it's there or stop is called. speed multiplies its movement_speed
|
||||
move_to(x: number, y: number, z: number, speed?: number): void;
|
||||
// finds a way to x y z around what's in between and walks it, see PATHFINDING.md. when the whole way isn't there it
|
||||
// walks as close as it can get. false when it can't get any closer, or when it searched in vain less than a second
|
||||
// ago, keeping the way it had. speed multiplies its movement_speed
|
||||
move_to(x: number, y: number, z: number, speed?: number): boolean;
|
||||
// stops walking its way
|
||||
stop(): void;
|
||||
// whether it's still on its way
|
||||
readonly moving: boolean;
|
||||
// a solid block in its way that its way goes through, tagged #cubi:mobs_path_through, which it's pressed against.
|
||||
// it waits there for as long as the block is solid and in its way, instead of giving up
|
||||
readonly blocked_by: { readonly x: number; readonly y: number; readonly z: number; readonly id: Id } | undefined;
|
||||
// turns its head, and its body after it, toward a point. it stops after a couple of ticks, so a goal that keeps
|
||||
// looking at something calls this every tick
|
||||
look_at(x: number, y: number, z: number): void;
|
||||
|
||||
@@ -444,6 +444,11 @@ const entity_schema = z.object({
|
||||
max_health: z.number().min(0).optional(),
|
||||
// minecraft's per tick speed, 0.25 for most animals
|
||||
movement_speed: z.number().min(0).optional(),
|
||||
// whether it jumps, onto blocks in its way and up its path, true when not set. one that doesn't still steps up its
|
||||
// step height, and swims up in water. see PATHFINDING.md
|
||||
jumps: z.boolean().optional(),
|
||||
// how many blocks it drops on its way, 3 when not set. 0 never walks off an edge, so it keeps out of pits
|
||||
max_fall: z.number().int().min(0).optional(),
|
||||
// what its hits do, for monsters. 2 when not set, like minecraft's
|
||||
attack_damage: z.number().min(0).optional(),
|
||||
// protection from physical and from arcane damage, not used yet
|
||||
|
||||
+2
-1
@@ -212,7 +212,8 @@ export function box_is_free(
|
||||
return !overlaps_solid(min, max, is_blocked);
|
||||
}
|
||||
|
||||
function overlaps_solid(min: number[], max: number[], is_solid: BlockCollision) {
|
||||
// whether the box between min and max (x, y, z) touches anything solid
|
||||
export function overlaps_solid(min: number[], max: number[], is_solid: BlockCollision) {
|
||||
for (let x = lowest(0, min[0]); x <= Math.floor(max[0] - EPSILON); x++) {
|
||||
for (let y = lowest(1, min[1]); y <= Math.floor(max[1] - EPSILON); y++) {
|
||||
for (let z = lowest(2, min[2]); z <= Math.floor(max[2] - EPSILON); z++) {
|
||||
|
||||
@@ -27,11 +27,13 @@ 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"`, `"monster"` or `"scripted"`, see below. |
|
||||
| `behavior` | `"animal"` | `"animal"`, `"monster"`, `"scripted"`, or a [custom behavior](#custom-behaviors)'s id. |
|
||||
| `category` | see below | `"monster"` or `"creature"`, see [Natural Spawning](#natural-spawning). |
|
||||
| `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. |
|
||||
| `jumps` | `true` | Whether it jumps onto blocks in its way. Without, it still steps up 0.6 blocks and swims up in water. |
|
||||
| `max_fall` | `3` | How many blocks it drops on its way. `0` never walks off an edge, to keep monsters out of pits. |
|
||||
| `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. |
|
||||
@@ -49,8 +51,9 @@ heart) whatever they hold. The hit pushes them away, and like any damage it can'
|
||||
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:
|
||||
They find their way to it (see [Getting Around](#getting-around)) and hit it 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
|
||||
{
|
||||
@@ -88,6 +91,120 @@ the world, so a script never finds one it doesn't know about after a restart. Th
|
||||
}
|
||||
```
|
||||
|
||||
## Custom Behaviors
|
||||
|
||||
A mob can get its goals from a script instead, like NeoForge's `registerGoals`. Its json names a behavior id, and the
|
||||
server phase registers a function under that id, which runs once for each mob of that kind before it first thinks:
|
||||
|
||||
```json
|
||||
"behavior": "my_mod:sentry"
|
||||
```
|
||||
|
||||
```ts
|
||||
export function server(ctx: ServerContext) {
|
||||
const chase = ctx.entities.goals.melee_attack({ speed: 1.25 });
|
||||
ctx.entities.register_behavior("my_mod:sentry", (mob, goals) => {
|
||||
// stands still at night, taking every control from the goals after it
|
||||
goals.add(0, {
|
||||
flags: ["move", "look", "jump"],
|
||||
can_use: () => ctx.world.hour < 6 || ctx.world.hour >= 18,
|
||||
start: () => mob.stop(),
|
||||
});
|
||||
goals.add(1, chase);
|
||||
goals.add_target(0, ctx.entities.goals.nearest_attackable_player());
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
A server won't start with an entity whose behavior nothing registered.
|
||||
|
||||
Every tick, running goals that can't continue stop, then the ones that can start do, most important (lowest priority
|
||||
number) first, then every running goal ticks. A goal only starts once each of its `flags` is free or held by a less
|
||||
important goal, which then stops: `"move"`, `"look"`, `"jump"`, and `"target"` for the goals in `add_target` that pick
|
||||
who the mob goes after.
|
||||
|
||||
| Goal field | Meaning |
|
||||
| ----------------------- | ---------------------------------------------------------------------- |
|
||||
| `flags` | The controls it needs while it runs. None when not given. |
|
||||
| `can_use()` | Whether it wants to start. The only one it needs. |
|
||||
| `can_continue_to_use()` | Whether it wants to keep going. `can_use` when not given. |
|
||||
| `is_interruptable()` | Whether a more important goal can take its flags. True when not given. |
|
||||
| `start()`, `stop()` | When it starts and stops running. |
|
||||
| `tick()` | Every tick while it runs. |
|
||||
|
||||
A goal that throws is logged once and never runs again, and the mob's other goals go on. What a mob's goals have to
|
||||
remember goes in the behavior function's closures, which each mob gets its own of.
|
||||
|
||||
`ctx.entities.goals` has the goals animals and monsters are made of, to add next to your own. One can be added to many
|
||||
mobs:
|
||||
|
||||
| Goal | What it does |
|
||||
| ------------------------------------------------- | ------------------------------------------------------------------- |
|
||||
| `float()` | Swims up in water. |
|
||||
| `random_stroll({ speed?, interval?, range? })` | Walks to a random spot within `range` every `interval` ticks or so. |
|
||||
| `panic({ speed? })` | Runs around after being hurt or while burning. |
|
||||
| `look_at_player({ range?, probability? })` | Looks at a nearby player for a couple of seconds now and then. |
|
||||
| `random_look_around()` | Looks around at nothing in particular. |
|
||||
| `melee_attack({ speed?, interval? })` | Goes after its target and hits it, at most every `interval` ticks. |
|
||||
| `hurt_by_target()`, `nearest_attackable_player()` | Target goals: whoever hurt it last, the nearest player. |
|
||||
|
||||
Speeds multiply its `movement_speed`. The mob a behavior gets is a `MobRef`, a [living entity](effects.md) with:
|
||||
|
||||
```ts
|
||||
interface MobRef extends LivingRef {
|
||||
readonly type: Id;
|
||||
readonly position: Readonly<Position>;
|
||||
readonly eye_position: Readonly<Position>; // where it sees from
|
||||
readonly look_direction: Readonly<Position>; // a vector 1 long
|
||||
readonly velocity: Readonly<Position>; // in blocks a second
|
||||
readonly on_ground: boolean;
|
||||
readonly in_water: boolean;
|
||||
target: Player | MobRef | undefined; // who it's after, undefined once they're dead or gone
|
||||
readonly last_attacker: Player | MobRef | undefined;
|
||||
random(): number; // 0 to 1, from the mob's own random
|
||||
move_to(x: number, y: number, z: number, speed?: number): boolean; // see Getting Around
|
||||
stop(): void;
|
||||
readonly moving: boolean;
|
||||
readonly blocked_by: { x: number; y: number; z: number; id: Id } | undefined;
|
||||
look_at(x: number, y: number, z: number): void; // for a couple of ticks, so call it every tick
|
||||
jump(): void; // this tick, or swims up in water
|
||||
attack(target: Player | MobRef): void; // swings and hits with its attack_damage
|
||||
}
|
||||
```
|
||||
|
||||
Each mob has one `MobRef`, so `mob.target === player` works.
|
||||
|
||||
## Getting Around
|
||||
|
||||
Mobs find their way around walls and through gaps, like Minecraft's pathfinding. `move_to` searches for a way and the
|
||||
mob walks it, and it's how strolling, panicking and going after a target get anywhere:
|
||||
|
||||
- A way only goes where the mob's box fits, so a 2 tall mob doesn't fit under a 2 high gap. It steps onto anything up to
|
||||
0.6 high, like a slab, jumps up 1 block when its `jumps` is on, and drops up to `max_fall` blocks. With `max_fall` 0
|
||||
it never walks off an edge either, like a sneaking player, though something that knocks it into the air can still
|
||||
knock it off.
|
||||
- It looks up to its `follow_range` (16 blocks unless an attribute changes it) from where it is. When it can't get to
|
||||
the spot, it goes as close as it can and `move_to` still returns true. It returns false when it can't get any closer.
|
||||
- A search that didn't get the whole way is the slow kind, so for a second after one, `move_to` doesn't search again.
|
||||
- Stuck with no closer to its way for two seconds, it searches once more, then stops.
|
||||
|
||||
Blocks in the [`#cubi:mobs_path_through`](../resources/tags.md#the-engines-tags) tag count as empty, solid or not, so a
|
||||
way can go through them. A mob pressed against a solid one on its way stops there with `blocked_by` set to it, and waits
|
||||
for as long as it stays solid and in the way. It's up to the behavior what happens then, like a goal without flags, so
|
||||
the mob keeps its way, that breaks the block after two seconds:
|
||||
|
||||
```ts
|
||||
let waited = 0;
|
||||
goals.add(0, {
|
||||
can_use: () => mob.blocked_by !== undefined,
|
||||
start: () => waited = 0,
|
||||
tick: () => {
|
||||
const { x, y, z } = mob.blocked_by!;
|
||||
if (++waited === 40) ctx.world.break_block(x, y, z);
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## Natural Spawning
|
||||
|
||||
An entity's `category` is what natural spawning counts it as, like Minecraft's mob categories. Monsters can spawn on
|
||||
|
||||
@@ -78,6 +78,14 @@ back. Depend on the mod whose tag you change, so your file loads after its. chec
|
||||
| `#bworld:leaves` | blocks | Every kind of leaves. |
|
||||
| `#c:ingots` | items | `#c:ingots/copper`, `#c:ingots/tin`, `#c:ingots/iron`, `#c:ingots/gold`. |
|
||||
|
||||
## The Engine's Tags
|
||||
|
||||
The engine reads these by name. No mod owns `cubi`, so adding to them needs no dependency.
|
||||
|
||||
| Tag | Registry | What's in it |
|
||||
| ------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `#cubi:mobs_path_through` | blocks | Blocks mobs' paths go through, solid or not. A mob pressed against a solid one waits there, see [Entities](../entities/index.md). |
|
||||
|
||||
## Using Tags in Data
|
||||
|
||||
- **Recipes**: anywhere a recipe takes an item (shaped `key` values, smelting `input`, fuel `item`) it can take an item
|
||||
|
||||
@@ -6,9 +6,11 @@
|
||||
"texture": "dangerous_business:coilhead",
|
||||
"behavior": "dangerous_business:coilhead",
|
||||
"width": 0.8,
|
||||
"height": 2.5,
|
||||
"height": 1.9,
|
||||
"max_health": 40,
|
||||
"movement_speed": 0.23,
|
||||
"jumps": false,
|
||||
"max_fall": 0,
|
||||
"attack_damage": 5,
|
||||
"physical_shielding": 3
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"minecraft:geometry": [
|
||||
{
|
||||
"description": {
|
||||
"identifier": "geometry.unknown",
|
||||
"identifier": "geometry.CoilHead",
|
||||
"texture_width": 128,
|
||||
"texture_height": 128,
|
||||
"visible_bounds_width": 3,
|
||||
@@ -12,77 +12,191 @@
|
||||
},
|
||||
"bones": [
|
||||
{
|
||||
"name": "root",
|
||||
"name": "coilhead",
|
||||
"pivot": [0, 0, 0]
|
||||
},
|
||||
{
|
||||
"name": "Torso",
|
||||
"parent": "root",
|
||||
"pivot": [0.5, 17, 0],
|
||||
"name": "body",
|
||||
"parent": "coilhead",
|
||||
"pivot": [0, 0, 0],
|
||||
"cubes": [
|
||||
{"origin": [-4.5, 17, -3.5], "size": [9, 14, 5], "uv": [0, 0]},
|
||||
{"origin": [5.5, 20, -5.499], "size": [0, 1, 1], "pivot": [4.5, 17.5, -4.499], "rotation": [0, -90, 0], "uv": [1, 1]},
|
||||
{"origin": [10.5, 23, -5.499], "size": [0, 1, 1], "pivot": [4.5, 17.5, -4.499], "rotation": [0, -90, 0], "uv": [1, 1]},
|
||||
{"origin": [-1.5, 20.05952, -5.5], "size": [0, 1, 2], "uv": [0, 0]},
|
||||
{"origin": [-0.5, 26.05952, -5.5], "size": [0, 1, 2], "uv": [0, 0]},
|
||||
{"origin": [-0.5, 24.05952, 1.5], "size": [0, 1, 2], "uv": [0, 0]},
|
||||
{"origin": [-2.5, 19.05952, 1.5], "size": [0, 1, 2], "uv": [0, 0]}
|
||||
{"origin": [-4, 19, 1.3], "size": [8, 5, 6], "uv": [0, 25]},
|
||||
{"origin": [-4.5, 24, 0.8], "size": [9, 3, 7], "uv": [0, 15]},
|
||||
{"origin": [-5.5, 27, 0.3], "size": [11, 7, 8], "uv": [0, 0]},
|
||||
{"origin": [-20.5, 24, 2.3], "size": [8, 3, 3], "pivot": [0, 0, 0], "rotation": [0, 0, 45], "uv": [35, 12]},
|
||||
{"origin": [11.5, 24, 2.3], "size": [9, 3, 3], "pivot": [0, 0, 0], "rotation": [0, 0, -45], "uv": [30, 0]},
|
||||
{"origin": [-4.5, 33.3, 1.3], "size": [9, 2, 6], "uv": [26, 19]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "RightArm",
|
||||
"parent": "Torso",
|
||||
"pivot": [-5, 28, -1.5],
|
||||
"name": "left_leg",
|
||||
"parent": "body",
|
||||
"pivot": [3, 20, 4.7],
|
||||
"rotation": [7.5, 0, 0],
|
||||
"cubes": [
|
||||
{"origin": [-8.5, 20, -3], "size": [4, 10, 4], "uv": [0, 34]},
|
||||
{"origin": [-5.5, 28.05952, -5], "size": [0, 1, 2], "uv": [0, 0]},
|
||||
{"origin": [-5.5, 28.05952, 1], "size": [0, 1, 2], "uv": [0, 0]}
|
||||
{"origin": [1.5, 0, -2], "size": [3, 2, 3], "uv": [33, 55]},
|
||||
{"origin": [1.5, 0, 0.5], "size": [3, 2, 3], "inflate": -0.1, "pivot": [-2.5, 0, 0], "rotation": [17.5, 0, 0], "uv": [21, 54]},
|
||||
{"origin": [1.5, 0.9, 1.5], "size": [3, 7, 3], "pivot": [-2.5, -0.2, 0], "rotation": [5, 0, 0], "uv": [44, 39]},
|
||||
{"origin": [1.5, 7.8, 0.7], "size": [3, 5, 3], "inflate": 0.2, "pivot": [-2.5, -0.2, 0], "rotation": [0, 0, 0], "uv": [12, 48]},
|
||||
{"origin": [1, 12.5, -3.7], "size": [4, 8, 4], "inflate": 0.2, "pivot": [-2.5, -0.2, 0], "rotation": [-17.5, 0, 0], "uv": [16, 36]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "LeftArm",
|
||||
"parent": "Torso",
|
||||
"pivot": [5, 28.66032, -0.66633],
|
||||
"name": "nail2",
|
||||
"parent": "left_leg",
|
||||
"pivot": [3.8, 6, 1.7],
|
||||
"rotation": [64.46949, 11.31255, -5.35254],
|
||||
"cubes": [
|
||||
{"origin": [4.5, 22, -3], "size": [4, 8, 4], "uv": [40, 38]},
|
||||
{"origin": [6.5, 27.05952, -4.5], "size": [0, 1, 2], "uv": [0, 0]},
|
||||
{"origin": [8.5, 27, -10.499], "size": [0, 1, 2], "pivot": [4.5, 17.5, -4.499], "rotation": [0, -90, 0], "uv": [0, 0]}
|
||||
{"origin": [2.8, 6, 0.7], "size": [1, 2, 1], "uv": [0, 3]},
|
||||
{"origin": [2.3, 8, 0.2], "size": [2, 1, 2], "uv": [0, 0]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Neck",
|
||||
"parent": "Torso",
|
||||
"pivot": [-1.5, 31, 0],
|
||||
"name": "nail3",
|
||||
"parent": "left_leg",
|
||||
"pivot": [4.5, 14.7, 1.9],
|
||||
"rotation": [74.30716, -16.88547, 4.6653],
|
||||
"cubes": [
|
||||
{"origin": [-2, 30.75, -3], "size": [4, 9, 4], "uv": [16, 38]}
|
||||
{"origin": [3.5, 14.7, 0.9], "size": [1, 2, 1], "uv": [0, 3]},
|
||||
{"origin": [3, 16.7, 0.4], "size": [2, 1, 2], "uv": [0, 0]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Head",
|
||||
"parent": "Neck",
|
||||
"pivot": [0, 39.75, -1],
|
||||
"name": "right_leg",
|
||||
"parent": "body",
|
||||
"pivot": [-3, 20, 4.7],
|
||||
"rotation": [7.5, 0, 0],
|
||||
"cubes": [
|
||||
{"origin": [-3.5, 39.75, -4.5], "size": [7, 8, 7], "uv": [0, 19]}
|
||||
{"origin": [-4.5, 0, -2], "size": [3, 2, 3], "uv": [53, 24]},
|
||||
{"origin": [-4.5, 0, 0.5], "size": [3, 2, 3], "inflate": -0.1, "pivot": [2.5, 0, 0], "rotation": [17.5, 0, 0], "uv": [50, 7]},
|
||||
{"origin": [-4.5, 0.9, 1.5], "size": [3, 7, 3], "pivot": [2.5, -0.2, 0], "rotation": [5, 0, 0], "uv": [32, 39]},
|
||||
{"origin": [-4.5, 7.8, 0.7], "size": [3, 5, 3], "inflate": 0.2, "pivot": [2.5, -0.2, 0], "rotation": [0, 0, 0], "uv": [0, 48]},
|
||||
{"origin": [-5, 12.5, -3.7], "size": [4, 8, 4], "inflate": 0.2, "pivot": [2.5, -0.2, 0], "rotation": [-17.5, 0, 0], "uv": [0, 36]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "RightLeg",
|
||||
"parent": "root",
|
||||
"pivot": [-1, 16, -0.833],
|
||||
"name": "nail4",
|
||||
"parent": "right_leg",
|
||||
"pivot": [-3.2, 3.2, 1.8],
|
||||
"rotation": [75.65143, 69.40933, -13.46639],
|
||||
"cubes": [
|
||||
{"origin": [-4, 0, -3], "size": [4, 17, 4], "uv": [28, 21]},
|
||||
{"origin": [-1.5, 10.05952, -5], "size": [0, 1, 2], "uv": [0, 0]},
|
||||
{"origin": [8.5, 10, 4], "size": [0, 1, 2], "pivot": [4.5, 17.5, -4.499], "rotation": [0, -90, 0], "uv": [0, 0]}
|
||||
{"origin": [-4.2, 3.2, 0.8], "size": [1, 2, 1], "uv": [0, 3]},
|
||||
{"origin": [-4.7, 5.2, 0.3], "size": [2, 1, 2], "uv": [0, 0]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "LeftLeg",
|
||||
"parent": "root",
|
||||
"pivot": [0.167, 16, -0.833],
|
||||
"name": "nail5",
|
||||
"parent": "right_leg",
|
||||
"pivot": [-1.8, 15, 1.5],
|
||||
"rotation": [63.60782, 18.05776, -8.74472],
|
||||
"cubes": [
|
||||
{"origin": [0, 0, -3], "size": [4, 17, 4], "uv": [28, 0]},
|
||||
{"origin": [2.5, 8.05952, -5], "size": [0, 1, 2], "uv": [0, 0]},
|
||||
{"origin": [8.5, 12, -6], "size": [0, 1, 2], "pivot": [4.5, 17.5, -4.499], "rotation": [0, -90, 0], "uv": [0, 0]}
|
||||
{"origin": [-2.8, 15, 0.5], "size": [1, 2, 1], "uv": [0, 3]},
|
||||
{"origin": [-3.3, 17, 0], "size": [2, 1, 2], "uv": [0, 0]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "nail6",
|
||||
"parent": "right_leg",
|
||||
"pivot": [-4.1, 19.5, 3.7],
|
||||
"rotation": [29.03199, 61.09544, -57.62441],
|
||||
"cubes": [
|
||||
{"origin": [-5.1, 19.5, 2.7], "size": [1, 2, 1], "uv": [0, 3]},
|
||||
{"origin": [-5.6, 21.5, 2.2], "size": [2, 1, 2], "uv": [0, 0]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "spring",
|
||||
"parent": "body",
|
||||
"pivot": [0, 35.3, 4.5],
|
||||
"cubes": [
|
||||
{"origin": [1.5, 35.3, 1.8], "size": [1, 1, 5], "uv": [52, 33]},
|
||||
{"origin": [-2.4, 36.2, 1.6], "size": [1, 1, 5], "uv": [51, 44]},
|
||||
{"origin": [-2.7, 35.8, 5.7], "size": [5, 1, 1], "uv": [56, 4]},
|
||||
{"origin": [-2.7, 36.6, 1.7], "size": [5, 1, 1], "uv": [56, 2]},
|
||||
{"origin": [-2.7, 38.6, 1.7], "size": [5, 1, 1], "uv": [0, 56]},
|
||||
{"origin": [1.5, 37.3, 1.8], "size": [1, 1, 5], "uv": [50, 18]},
|
||||
{"origin": [-2.7, 37.8, 5.7], "size": [5, 1, 1], "uv": [56, 0]},
|
||||
{"origin": [-2.4, 38.2, 1.6], "size": [1, 1, 5], "uv": [50, 50]},
|
||||
{"origin": [-2.7, 40.6, 1.7], "size": [5, 1, 1], "uv": [53, 39]},
|
||||
{"origin": [1.5, 39.3, 1.8], "size": [1, 1, 5], "uv": [31, 49]},
|
||||
{"origin": [-2.7, 39.8, 5.7], "size": [5, 1, 1], "uv": [54, 12]},
|
||||
{"origin": [-2.4, 40.2, 1.6], "size": [1, 1, 5], "uv": [43, 49]},
|
||||
{"origin": [-2.7, 42.6, 1.7], "size": [5, 1, 1], "uv": [30, 6]},
|
||||
{"origin": [1.5, 41.3, 1.8], "size": [1, 1, 5], "uv": [24, 48]},
|
||||
{"origin": [-2.7, 41.8, 5.7], "size": [5, 1, 1], "uv": [53, 29]},
|
||||
{"origin": [-2.4, 42.2, 1.6], "size": [1, 1, 5], "uv": [49, 1]},
|
||||
{"origin": [-2.7, 44.6, 1.7], "size": [5, 1, 1], "uv": [22, 27]},
|
||||
{"origin": [1.5, 43.3, 1.8], "size": [1, 1, 5], "uv": [38, 6]},
|
||||
{"origin": [-2.7, 43.8, 5.7], "size": [5, 1, 1], "uv": [22, 29]},
|
||||
{"origin": [-2.4, 44.2, 1.6], "size": [1, 1, 5], "uv": [46, 27]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "head",
|
||||
"parent": "spring",
|
||||
"pivot": [0, 45.5, 2.2],
|
||||
"cubes": [
|
||||
{"origin": [-3.2, 45.4, 1.3], "size": [6, 6, 6], "uv": [28, 27]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "nail7",
|
||||
"parent": "body",
|
||||
"pivot": [-0.6, 22.4, 2.2],
|
||||
"rotation": [82.32005, 12.39135, -1.6575],
|
||||
"cubes": [
|
||||
{"origin": [-1.6, 22.4, 1.2], "size": [1, 2, 1], "uv": [0, 3]},
|
||||
{"origin": [-2.1, 24.4, 0.7], "size": [2, 1, 2], "uv": [0, 0]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "nail8",
|
||||
"parent": "body",
|
||||
"pivot": [3.9, 31.6, 1.6],
|
||||
"rotation": [97.7614, -14.8687, -2.00307],
|
||||
"cubes": [
|
||||
{"origin": [2.9, 31.6, 0.6], "size": [1, 2, 1], "uv": [0, 3]},
|
||||
{"origin": [2.4, 33.6, 0.1], "size": [2, 1, 2], "uv": [0, 0]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "nail10",
|
||||
"parent": "body",
|
||||
"pivot": [0.9, 31.6, 7.4],
|
||||
"rotation": [-97.7614, 14.8687, -2.00307],
|
||||
"cubes": [
|
||||
{"origin": [-0.1, 31.6, 7.4], "size": [1, 2, 1], "uv": [0, 3]},
|
||||
{"origin": [-0.6, 33.6, 6.9], "size": [2, 1, 2], "uv": [0, 0]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "nail11",
|
||||
"parent": "body",
|
||||
"pivot": [-1.5, 22.5, 6.2],
|
||||
"rotation": [-97.7614, 14.8687, -2.00307],
|
||||
"cubes": [
|
||||
{"origin": [-2.5, 22.5, 6.2], "size": [1, 2, 1], "uv": [0, 3]},
|
||||
{"origin": [-3, 24.5, 5.7], "size": [2, 1, 2], "uv": [0, 0]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "nail9",
|
||||
"parent": "body",
|
||||
"pivot": [-3.4, 33.5, 1.2],
|
||||
"rotation": [98.44236, 27.24513, 3.88714],
|
||||
"cubes": [
|
||||
{"origin": [-4.4, 33.5, 0.2], "size": [1, 2, 1], "uv": [0, 3]},
|
||||
{"origin": [-4.9, 35.5, -0.3], "size": [2, 1, 2], "uv": [0, 0]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "nail",
|
||||
"parent": "body",
|
||||
"pivot": [-4, 33.5, 6.1],
|
||||
"rotation": [10, 0, -30],
|
||||
"cubes": [
|
||||
{"origin": [-5, 33.5, 5.1], "size": [1, 2, 1], "uv": [0, 3]},
|
||||
{"origin": [-5.5, 35.5, 4.6], "size": [2, 1, 2], "uv": [0, 0]}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
"elements": [
|
||||
{
|
||||
"from": [0, 0, 0],
|
||||
"to": [3, 16, 16],
|
||||
"to": [1, 16, 16],
|
||||
"faces": {
|
||||
"bottom": {
|
||||
"texture": "#bottom",
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
"elements": [
|
||||
{
|
||||
"from": [0, 0, 0],
|
||||
"to": [3, 16, 16],
|
||||
"to": [1, 16, 16],
|
||||
"faces": {
|
||||
"bottom": {
|
||||
"texture": "#bottom",
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
"elements": [
|
||||
{
|
||||
"from": [0, 0, 0],
|
||||
"to": [3, 16, 16],
|
||||
"to": [1, 16, 16],
|
||||
"faces": {
|
||||
"top": {
|
||||
"texture": "#bottom",
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
"elements": [
|
||||
{
|
||||
"from": [0, 0, 0],
|
||||
"to": [3, 16, 16],
|
||||
"to": [1, 16, 16],
|
||||
"faces": {
|
||||
"top": {
|
||||
"texture": "#bottom",
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
// the coilhead: it goes after players like any monster, but can't move while one of them is looking at it
|
||||
import type { MobRef, Player, Position, ScriptGoal, ServerContext } from "cubi/server";
|
||||
import { DOOR, type DoorParams, set_door_open } from "./shared.ts";
|
||||
|
||||
// how far away a player still freezes it
|
||||
const SEEN_RANGE = 48;
|
||||
// how far from where a player looks it can be and still be seen, as the cosine of the angle: 0.5 is 60 degrees each
|
||||
// way, about what fits on the screen
|
||||
const VIEW_COS = 0.5;
|
||||
// how much faster than its movement_speed it runs at its target
|
||||
const CHASE_SPEED = 2;
|
||||
// how long it stands at a closed door on its way before opening it, in ticks
|
||||
const OPEN_DOOR_TICKS = 20 * 20;
|
||||
|
||||
export function register_coilhead(ctx: ServerContext) {
|
||||
const builtin = ctx.entities.goals;
|
||||
const chase = builtin.melee_attack({ speed: CHASE_SPEED });
|
||||
const stroll = builtin.random_stroll({ speed: 0.6 });
|
||||
const look_around = builtin.random_look_around();
|
||||
const hurt_by = builtin.hurt_by_target();
|
||||
const nearest_player = builtin.nearest_attackable_player();
|
||||
|
||||
ctx.entities.register_behavior("dangerous_business:coilhead", (mob, goals) => {
|
||||
// takes every control from the goals after it, so it doesn't walk, turn, jump or hit while seen
|
||||
goals.add(0, {
|
||||
flags: ["move", "look", "jump"],
|
||||
can_use: () => ctx.players.all().some((player) => sees(ctx, player, mob)),
|
||||
start: () => mob.stop(),
|
||||
});
|
||||
goals.add(1, chase);
|
||||
goals.add(2, stroll);
|
||||
goals.add(3, look_around);
|
||||
goals.add(4, opens_doors(ctx, mob, OPEN_DOOR_TICKS));
|
||||
goals.add_target(0, hurt_by);
|
||||
goals.add_target(1, nearest_player);
|
||||
});
|
||||
}
|
||||
|
||||
// opens a door on the mob's way after it's stood at it for ticks. without flags, so the goal going after its target
|
||||
// keeps its way and the mob stays at the door. the door's in the mobs_path_through tag, so its way goes through it
|
||||
export function opens_doors(ctx: ServerContext, mob: MobRef, ticks: number): ScriptGoal {
|
||||
let waited = 0;
|
||||
const door = () => {
|
||||
const blocked = mob.blocked_by;
|
||||
return blocked && DOOR in ctx.blocks.components(blocked.id) ? blocked : undefined;
|
||||
};
|
||||
return {
|
||||
can_use: () => door() !== undefined,
|
||||
start: () => waited = 0,
|
||||
tick: () => {
|
||||
// a goal that started this tick, like being seen, can stop the mob's way and with it what blocks it
|
||||
const blocked = door();
|
||||
if (!blocked) return;
|
||||
const { x, y, z, id } = blocked;
|
||||
if (++waited !== ticks) return;
|
||||
set_door_open(ctx, x, y, z, 1, ctx.blocks.components(id)[DOOR] as DoorParams);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// whether the player is looking its way with nothing in between, at its head or its middle
|
||||
function sees(ctx: ServerContext, player: Player, mob: MobRef) {
|
||||
if (player.health <= 0) return false;
|
||||
const eye = player.eye_position;
|
||||
const look = player.look_direction;
|
||||
const head = mob.eye_position;
|
||||
const feet = mob.position;
|
||||
const middle = { x: feet.x, y: (feet.y + head.y) / 2, z: feet.z };
|
||||
return [head, middle].some((point: Position) => {
|
||||
const dx = point.x - eye.x;
|
||||
const dy = point.y - eye.y;
|
||||
const dz = point.z - eye.z;
|
||||
const distance = Math.hypot(dx, dy, dz);
|
||||
if (distance > SEEN_RANGE) return false;
|
||||
if (distance > 0 && (dx * look.x + dy * look.y + dz * look.z) / distance < VIEW_COS) return false;
|
||||
return ctx.world.raycast(eye, point) === undefined;
|
||||
});
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import type { ClientContext, Color } from "cubi/client";
|
||||
import type { ServerContext } from "cubi/server";
|
||||
import { DOOR, FACILITY_DOOR } from "./shared.ts";
|
||||
import { Alea } from "@paulaboks/rng";
|
||||
import { register_coilhead } from "./coilhead.ts";
|
||||
import { DOORWAY, MAIN_TILE, type Marker, type PlacedTile, plan_interior, tile_type, TILES } from "./interior.ts";
|
||||
|
||||
export { shared } from "./shared.ts";
|
||||
@@ -13,6 +14,7 @@ export function server(ctx: ServerContext) {
|
||||
register_door(ctx);
|
||||
register_death(ctx);
|
||||
register_commands(ctx);
|
||||
register_coilhead(ctx);
|
||||
}
|
||||
|
||||
export function client(ctx: ClientContext) {
|
||||
|
||||
@@ -110,52 +110,63 @@ function register_facility_door(ctx: SharedContext) {
|
||||
});
|
||||
}
|
||||
|
||||
interface DoorParams {
|
||||
// the door component's params: "pairs_with" is the tag of doors it makes double doors with
|
||||
export interface DoorParams {
|
||||
pairs_with: string;
|
||||
}
|
||||
|
||||
function register_door(ctx: SharedContext) {
|
||||
// a door's lower half there, of the kind this one pairs with
|
||||
const door_at = (x: number, y: number, z: number, params: DoorParams) => {
|
||||
const id = ctx.world.get_block(x, y, z);
|
||||
return id !== undefined && ctx.tags.has("blocks", params.pairs_with, id) &&
|
||||
ctx.world.get_state(x, y, z, "half") === 0;
|
||||
};
|
||||
// opens or closes both halves of the door whose lower half is there
|
||||
const set_open = (x: number, y: number, z: number, open: number) => {
|
||||
if (ctx.world.get_block(x, y + 1, z) === ctx.world.get_block(x, y, z)) {
|
||||
ctx.world.set_state(x, y + 1, z, "open", open);
|
||||
}
|
||||
return ctx.world.set_state(x, y, z, "open", open);
|
||||
};
|
||||
// what set_door_open needs, which shared, server and client phases all have
|
||||
type DoorContext = Pick<SharedContext, "tags"> & {
|
||||
world: Pick<SharedContext["world"], "get_block" | "get_state" | "set_state">;
|
||||
};
|
||||
|
||||
// a door's lower half there, of the kind a door with params pairs with
|
||||
function door_at(ctx: DoorContext, x: number, y: number, z: number, params: DoorParams) {
|
||||
const id = ctx.world.get_block(x, y, z);
|
||||
return id !== undefined && ctx.tags.has("blocks", params.pairs_with, id) &&
|
||||
ctx.world.get_state(x, y, z, "half") === 0;
|
||||
}
|
||||
|
||||
// opens (open 1) or closes (open 0) the door with a half at x y z: both its halves, and the other door of a double
|
||||
// door with it when it's open or closed like this one. players do it by clicking, monsters from their goals. returns
|
||||
// whether it changed
|
||||
export function set_door_open(ctx: DoorContext, x: number, y: number, z: number, open: number, params: DoorParams) {
|
||||
const lower = ctx.world.get_state(x, y, z, "half") ? y - 1 : y;
|
||||
const state = (name: string, at_x = x, at_z = z) => ctx.world.get_state(at_x, lower, at_z, name);
|
||||
// both halves of the door whose lower half is at x z
|
||||
const set_halves = (at_x: number, at_z: number) => {
|
||||
if (ctx.world.get_block(at_x, lower + 1, at_z) === ctx.world.get_block(at_x, lower, at_z)) {
|
||||
ctx.world.set_state(at_x, lower + 1, at_z, "open", open);
|
||||
}
|
||||
return ctx.world.set_state(at_x, lower, at_z, "open", open);
|
||||
};
|
||||
// the other door of a double door is beside its free edge, facing the same way, hinged the other way, and open or
|
||||
// closed like it
|
||||
const facing = state("facing")!;
|
||||
const [step_x, step_z] = FACING_STEPS[(facing + (state("hinge") ? 3 : 1)) % 4];
|
||||
const [px, pz] = [x + step_x, z + step_z];
|
||||
if (
|
||||
door_at(ctx, px, lower, pz, params) && state("facing", px, pz) === facing &&
|
||||
state("hinge", px, pz) !== state("hinge") && state("open", px, pz) === state("open")
|
||||
) {
|
||||
set_halves(px, pz);
|
||||
}
|
||||
return set_halves(x, z);
|
||||
}
|
||||
|
||||
function register_door(ctx: SharedContext) {
|
||||
ctx.components.register_block<DoorParams>("dangerous_business:door", {
|
||||
on_interact(block, params) {
|
||||
const { x, z } = block;
|
||||
const y = ctx.world.get_state(x, block.y, z, "half") ? block.y - 1 : block.y;
|
||||
const state = (name: string, at_x = x, at_z = z) => ctx.world.get_state(at_x, y, at_z, name);
|
||||
const was_open = state("open");
|
||||
const open = was_open ? 0 : 1;
|
||||
// the other door of a double door is beside its free edge, facing the same way, hinged the other way, and
|
||||
// open or closed like it
|
||||
const facing = state("facing")!;
|
||||
const [step_x, step_z] = FACING_STEPS[(facing + (state("hinge") ? 3 : 1)) % 4];
|
||||
const [px, pz] = [x + step_x, z + step_z];
|
||||
if (
|
||||
door_at(px, y, pz, params) && state("facing", px, pz) === facing &&
|
||||
state("hinge", px, pz) !== state("hinge") && state("open", px, pz) === was_open
|
||||
) {
|
||||
set_open(px, y, pz, open);
|
||||
}
|
||||
return set_open(x, y, z, open);
|
||||
const open = ctx.world.get_state(block.x, block.y, block.z, "open") ? 0 : 1;
|
||||
return set_door_open(ctx, block.x, block.y, block.z, open, params);
|
||||
},
|
||||
state_for_placement(placement, params): Record<string, number> {
|
||||
const facing = FACINGS.indexOf(placement.facing);
|
||||
const { x, y, z } = placement;
|
||||
const [left_x, left_z] = FACING_STEPS[(facing + 3) % 4];
|
||||
const [right_x, right_z] = FACING_STEPS[(facing + 1) % 4];
|
||||
const door_left = door_at(x + left_x, y, z + left_z, params);
|
||||
const door_right = door_at(x + right_x, y, z + right_z, params);
|
||||
const door_left = door_at(ctx, x + left_x, y, z + left_z, params);
|
||||
const door_right = door_at(ctx, x + right_x, y, z + right_z, params);
|
||||
if (door_left !== door_right) return { facing, half: 0, hinge: door_left ? 1 : 0 };
|
||||
const [step_x, step_z] = FACING_STEPS[facing];
|
||||
const [hit_x, , hit_z] = placement.hit;
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"format_version": 1,
|
||||
"tag": {
|
||||
"values": [
|
||||
"dangerous_business:factory_door"
|
||||
]
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 17 KiB |
@@ -72,6 +72,10 @@ export interface EntityLevel {
|
||||
// the bottom of the world, see WorldShape
|
||||
readonly min_y: number;
|
||||
has_collision(x: number, y: number, z: number): boolean;
|
||||
// whether the chunk is kept, see World.has_chunk. reading blocks in one that isn't builds it, which takes a while
|
||||
has_chunk(chunk_x: number, chunk_z: number): boolean;
|
||||
// whether mobs' paths go through the block, see MOBS_PATH_THROUGH in pathfinding.ts
|
||||
passes_through(x: number, y: number, z: number): boolean;
|
||||
// what it bumps into at a block, see common/physics.ts
|
||||
collision_shape(x: number, y: number, z: number): boolean | Shape;
|
||||
// water, and other blocks you're in instead of on
|
||||
|
||||
@@ -8,6 +8,7 @@ import { CHUNK_SIZE } from "@/common/constants.ts";
|
||||
import { is_within_view } from "@/common/chunk_streaming.ts";
|
||||
import { fluid_block, fluid_in_cell } from "@/common/utils.ts";
|
||||
import { biome_season } from "@/common/worldgen/biomes.ts";
|
||||
import { Tags } from "@/common/tags.ts";
|
||||
import type { ItemStack } from "@/common/inventory.ts";
|
||||
import type { EntityEvent, EntityInfo, ServerMessage } from "@/common/protocol.ts";
|
||||
import type { ServerPlayer } from "../player.ts";
|
||||
@@ -15,6 +16,7 @@ import type { ServerWorld } from "../world.ts";
|
||||
import type { DamageSource, Entity, EntityLevel, SavedEntity } from "./entity.ts";
|
||||
import { load_entity } from "./entity_types.ts";
|
||||
import { ItemEntity } from "./item_entity.ts";
|
||||
import { MOBS_PATH_THROUGH } from "./pathfinding.ts";
|
||||
import type { LivingEntity } from "./living_entity.ts";
|
||||
|
||||
// everything the entities need from the game server
|
||||
@@ -105,6 +107,15 @@ export class EntityManager implements EntityLevel {
|
||||
return this.#host.world.has_collision(x, y, z);
|
||||
}
|
||||
|
||||
has_chunk(chunk_x: number, chunk_z: number) {
|
||||
return this.#host.world.has_chunk(chunk_x, chunk_z);
|
||||
}
|
||||
|
||||
passes_through(x: number, y: number, z: number) {
|
||||
const block = this.#host.world.get_block_info(x, y, z);
|
||||
return block !== undefined && Tags.has("blocks", MOBS_PATH_THROUGH, block.id);
|
||||
}
|
||||
|
||||
collision_shape(x: number, y: number, z: number) {
|
||||
return this.#host.world.collision_shape(x, y, z);
|
||||
}
|
||||
|
||||
+25
-20
@@ -11,6 +11,9 @@ import type { GoalFlag } from "@/common/mod_api/server.ts";
|
||||
|
||||
export type { GoalFlag };
|
||||
|
||||
// how often a mob going after its target searches for a new way to it, at most
|
||||
const RECALCULATE_TICKS = 10;
|
||||
|
||||
export abstract class Goal {
|
||||
flags: GoalFlag[] = [];
|
||||
|
||||
@@ -119,11 +122,9 @@ export class FloatGoal extends Goal {
|
||||
}
|
||||
}
|
||||
|
||||
// wanders to a random spot nearby every now and then, staying near home
|
||||
// wanders to a random spot nearby every now and then, staying near home, along a path to it
|
||||
export class RandomStrollGoal extends Goal {
|
||||
override flags: GoalFlag[] = ["move"];
|
||||
// there's no pathfinding, so it gives up on a spot it can't get to
|
||||
#ticks = 0;
|
||||
#wanted: { x: number; y: number; z: number } | undefined;
|
||||
|
||||
// interval is how many ticks it waits between strolls on average
|
||||
@@ -137,25 +138,19 @@ export class RandomStrollGoal extends Goal {
|
||||
return this.#wanted !== undefined;
|
||||
}
|
||||
|
||||
// until it gets there, or as close as it can
|
||||
override can_continue_to_use() {
|
||||
const wanted = this.#wanted;
|
||||
return wanted !== undefined && this.#ticks < 200 &&
|
||||
(wanted.x - this.mob.x) ** 2 + (wanted.z - this.mob.z) ** 2 > 0.25;
|
||||
return this.mob.navigation.moving;
|
||||
}
|
||||
|
||||
override start() {
|
||||
this.#ticks = 0;
|
||||
const { x, y, z } = this.#wanted!;
|
||||
this.mob.move_control.move_to(x, y, z, this.speed_modifier);
|
||||
}
|
||||
|
||||
override tick() {
|
||||
this.#ticks += 1;
|
||||
this.mob.navigation.move_to(x, y, z, this.speed_modifier);
|
||||
}
|
||||
|
||||
override stop() {
|
||||
this.#wanted = undefined;
|
||||
this.mob.move_control.stop();
|
||||
this.mob.navigation.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,18 +175,17 @@ export class PanicGoal extends Goal {
|
||||
}
|
||||
|
||||
override can_continue_to_use() {
|
||||
const wanted = this.#wanted;
|
||||
return wanted !== undefined && (wanted.x - this.mob.x) ** 2 + (wanted.z - this.mob.z) ** 2 > 0.25;
|
||||
return this.mob.navigation.moving;
|
||||
}
|
||||
|
||||
override start() {
|
||||
const { x, y, z } = this.#wanted!;
|
||||
this.mob.move_control.move_to(x, y, z, this.speed_modifier);
|
||||
this.mob.navigation.move_to(x, y, z, this.speed_modifier);
|
||||
}
|
||||
|
||||
override stop() {
|
||||
this.#wanted = undefined;
|
||||
this.mob.move_control.stop();
|
||||
this.mob.navigation.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -264,10 +258,13 @@ export class RandomLookAroundGoal extends Goal {
|
||||
}
|
||||
}
|
||||
|
||||
// walks to its target and hits it when close, like minecraft's MeleeAttackGoal without the pathfinding
|
||||
// follows a path to its target and hits it when close, like minecraft's MeleeAttackGoal. it searches again at most
|
||||
// every RECALCULATE_TICKS, and only once the target is in another block than the one it last searched for
|
||||
export class MeleeAttackGoal extends Goal {
|
||||
override flags: GoalFlag[] = ["move", "look"];
|
||||
#cooldown = 0;
|
||||
#recalculate = 0;
|
||||
#searched_for: string | undefined;
|
||||
|
||||
constructor(readonly mob: Mob, readonly speed_modifier = 1, readonly attack_interval = 20) {
|
||||
super();
|
||||
@@ -280,17 +277,25 @@ export class MeleeAttackGoal extends Goal {
|
||||
|
||||
override start() {
|
||||
this.#cooldown = 0;
|
||||
this.#recalculate = 0;
|
||||
this.#searched_for = undefined;
|
||||
}
|
||||
|
||||
override stop() {
|
||||
this.mob.move_control.stop();
|
||||
this.mob.navigation.stop();
|
||||
}
|
||||
|
||||
override tick() {
|
||||
const mob = this.mob;
|
||||
const target = mob.target!;
|
||||
mob.look_control.look_at_entity(target);
|
||||
mob.move_control.move_to(target.x, target.y, target.z, this.speed_modifier);
|
||||
this.#recalculate -= 1;
|
||||
const block = `${Math.floor(target.x)},${Math.floor(target.y)},${Math.floor(target.z)}`;
|
||||
if (this.#recalculate <= 0 && block !== this.#searched_for) {
|
||||
this.#searched_for = block;
|
||||
this.#recalculate = RECALCULATE_TICKS;
|
||||
mob.navigation.move_to(target.x, target.y, target.z, this.speed_modifier);
|
||||
}
|
||||
this.#cooldown = Math.max(0, this.#cooldown - 1);
|
||||
// minecraft's reach: its width doubled, squared, plus the target's width
|
||||
const reach = (mob.width * 2) ** 2 + target.width;
|
||||
|
||||
@@ -72,6 +72,8 @@ export abstract class LivingEntity extends Entity {
|
||||
// minecraft's per tick movement speed, see travel
|
||||
speed = 0;
|
||||
jumping = false;
|
||||
// whether jumping lifts it off the ground. one that doesn't still steps up its step height and swims up in water
|
||||
jumps = true;
|
||||
#jump_delay = 0;
|
||||
|
||||
// the attributes this kind has and their base values, like minecraft's default attribute suppliers. kinds add
|
||||
@@ -188,7 +190,7 @@ export abstract class LivingEntity extends Entity {
|
||||
if (this.jumping) {
|
||||
if (this.in_water) {
|
||||
this.vy += SWIM_UP * TICKS_PER_SECOND;
|
||||
} else if (this.on_ground && this.#jump_delay === 0) {
|
||||
} else if (this.jumps && this.on_ground && this.#jump_delay === 0) {
|
||||
this.jump_from_ground();
|
||||
this.#jump_delay = JUMP_DELAY;
|
||||
}
|
||||
|
||||
@@ -6,11 +6,14 @@
|
||||
import { ATTRIBUTES, type AttributeType } from "./attributes.ts";
|
||||
import { type DamageSource, Entity, finite } from "./entity.ts";
|
||||
import { GoalSelector } from "./goals.ts";
|
||||
import { PathNavigation } from "./navigation.ts";
|
||||
import { ItemEntity } from "./item_entity.ts";
|
||||
import { EQUIPMENT_SLOTS, type EquipmentSlot, LivingEntity, type SavedLivingEntity } from "./living_entity.ts";
|
||||
import type { EntityData } from "@/common/protocol.ts";
|
||||
import type { ItemStack } from "@/common/inventory.ts";
|
||||
import { wrap_angle } from "@/common/utils.ts";
|
||||
import { TICK_DELTA } from "@/common/constants.ts";
|
||||
import { physics } from "@/common/physics.ts";
|
||||
|
||||
// minecraft's despawning distances: gone at once past the first, maybe after a while past the second
|
||||
const DESPAWN_DISTANCE = 128;
|
||||
@@ -58,6 +61,8 @@ export abstract class Mob extends LivingEntity {
|
||||
no_action_time = 0;
|
||||
// Math.random, tests replace it
|
||||
random: () => number = Math.random;
|
||||
// how many blocks it drops on its way, see PATHFINDING.md. 0 never walks off an edge
|
||||
max_fall = 3;
|
||||
|
||||
// what it does, most important first. target goals pick who to go after, like minecraft's targetSelector
|
||||
goals = new GoalSelector();
|
||||
@@ -68,6 +73,8 @@ export abstract class Mob extends LivingEntity {
|
||||
last_attacker: LivingEntity | undefined;
|
||||
times_hurt_by_attacker = 0;
|
||||
|
||||
// follows paths, giving the move control one waypoint at a time
|
||||
navigation = new PathNavigation(this);
|
||||
move_control = new MoveControl(this);
|
||||
look_control = new LookControl(this);
|
||||
jump_control = new JumpControl(this);
|
||||
@@ -106,7 +113,25 @@ export abstract class Mob extends LivingEntity {
|
||||
}
|
||||
}
|
||||
|
||||
// the goals, then the controls, like minecraft's Mob.serverAiStep
|
||||
// a mob that never drops stops at edges like a sneaking player, still stepping down its step height. not while it's
|
||||
// off the ground, so something that knocks it into the air can still knock it off
|
||||
override move() {
|
||||
if (this.max_fall === 0 && this.on_ground && this.vy <= 0) {
|
||||
const is_solid = (x: number, y: number, z: number) => this.level.collision_shape(x, y, z);
|
||||
const [dx, dz] = physics.back_off_from_edge(
|
||||
this,
|
||||
this.vx * TICK_DELTA,
|
||||
this.vz * TICK_DELTA,
|
||||
this.step_height,
|
||||
is_solid,
|
||||
);
|
||||
this.vx = dx / TICK_DELTA;
|
||||
this.vz = dz / TICK_DELTA;
|
||||
}
|
||||
return super.move();
|
||||
}
|
||||
|
||||
// the goals, then the path they asked for, then the controls, like minecraft's Mob.serverAiStep
|
||||
override server_ai_step() {
|
||||
if (!this.#registered_goals) {
|
||||
this.#registered_goals = true;
|
||||
@@ -115,6 +140,7 @@ export abstract class Mob extends LivingEntity {
|
||||
this.no_action_time += 1;
|
||||
this.target_goals.tick();
|
||||
this.goals.tick();
|
||||
this.navigation.tick();
|
||||
this.move_control.tick();
|
||||
this.look_control.tick();
|
||||
this.jump_control.tick();
|
||||
|
||||
@@ -21,13 +21,18 @@ import {
|
||||
import { Mob, type MobCategory } 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 {
|
||||
// set, so each kind gets its own class that has its json already. behaviors are mods' (see ctx.entities), looked up
|
||||
// when a mob first thinks, after every script has registered its own
|
||||
export function mod_entity_factory(
|
||||
json: EntityJson,
|
||||
behaviors: ReadonlyMap<string, (mob: Mob) => void>,
|
||||
): EntityFactory {
|
||||
if (json.behavior === "scripted") {
|
||||
return (level) => new ScriptedEntity(level, json);
|
||||
}
|
||||
|
||||
const monster = json.behavior === "monster";
|
||||
const behavior = json.behavior?.includes(":") ? json.behavior : undefined;
|
||||
const category = entity_category(json);
|
||||
|
||||
class ModEntity extends Mob {
|
||||
@@ -35,6 +40,8 @@ export function mod_entity_factory(json: EntityJson): EntityFactory {
|
||||
override width = json.width;
|
||||
override height = json.height;
|
||||
override eye_height = json.height * 0.85;
|
||||
override jumps = json.jumps ?? true;
|
||||
override max_fall = json.max_fall ?? 3;
|
||||
|
||||
override get category(): MobCategory {
|
||||
return category;
|
||||
@@ -52,6 +59,10 @@ export function mod_entity_factory(json: EntityJson): EntityFactory {
|
||||
}
|
||||
|
||||
override register_goals() {
|
||||
if (behavior) {
|
||||
behaviors.get(behavior)!(this);
|
||||
return;
|
||||
}
|
||||
if (monster) {
|
||||
// like undergarden's rotspawn and minecraft's zombies
|
||||
this.goals.add_goal(0, new FloatGoal(this));
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// a mob following a path, like minecraft's PathNavigation: it searches for a way (see pathfinding.ts) and walks it one
|
||||
// waypoint at a time through the move control. see PATHFINDING.md
|
||||
import { ATTRIBUTES } from "./attributes.ts";
|
||||
import type { Mob } from "./mob.ts";
|
||||
import { find_path, type Path, type Point } from "./pathfinding.ts";
|
||||
import { overlaps_solid } from "@/common/physics.ts";
|
||||
|
||||
// ticks with no closer to its waypoint before it searches again, and then gives up
|
||||
const STUCK_TICKS = 40;
|
||||
// ticks without getting closer before a solid block its path goes through counts as blocking it
|
||||
const BLOCKED_TICKS = 10;
|
||||
// ticks a mob waits after a search that didn't find the whole way before it searches again, since those are the
|
||||
// searches that cost the most
|
||||
const FAILED_SEARCH_DELAY = 20;
|
||||
const EPSILON = 1e-4;
|
||||
|
||||
// a solid block in the mob's way that its path goes through, see MOBS_PATH_THROUGH
|
||||
export interface BlockedBy {
|
||||
x: number;
|
||||
y: number;
|
||||
z: number;
|
||||
id: string;
|
||||
}
|
||||
|
||||
export class PathNavigation {
|
||||
readonly mob: Mob;
|
||||
#path: Path | undefined;
|
||||
// the waypoint it's walking to
|
||||
#index = 0;
|
||||
#speed = 1;
|
||||
#target: Point | undefined;
|
||||
// the closest it's been to its waypoint, and for how many ticks it's been no closer
|
||||
#closest = Infinity;
|
||||
#stuck = 0;
|
||||
// whether it searched again because it was stuck, so the next time it gives up
|
||||
#searched_again = false;
|
||||
// the tick before which it doesn't search again, after a search that didn't find the whole way
|
||||
#search_after = -Infinity;
|
||||
// the solid block tagged mobs_path_through it's pressed against on its way, if any
|
||||
blocked_by: BlockedBy | undefined;
|
||||
|
||||
constructor(mob: Mob) {
|
||||
this.mob = mob;
|
||||
}
|
||||
|
||||
// whether it's still on its way
|
||||
get moving() {
|
||||
return this.#path !== undefined;
|
||||
}
|
||||
|
||||
// where it's going, when it is
|
||||
get target(): Readonly<Point> | undefined {
|
||||
return this.#target;
|
||||
}
|
||||
|
||||
// searches for a way to x y z and starts walking it, speed times its movement_speed. it walks to as close as it can
|
||||
// get when the whole way isn't there. false when there's no way closer at all, or when a search that didn't find the
|
||||
// whole way was too recent to search again, keeping whatever way it had
|
||||
move_to(x: number, y: number, z: number, speed = 1): boolean {
|
||||
const now = this.mob.level.current_tick;
|
||||
if (now < this.#search_after) {
|
||||
if (!this.#path) return false;
|
||||
this.#speed = speed;
|
||||
return true;
|
||||
}
|
||||
const path = this.#search({ x, y, z });
|
||||
if (!path?.reached) this.#search_after = now + FAILED_SEARCH_DELAY;
|
||||
if (!path) {
|
||||
this.stop();
|
||||
return false;
|
||||
}
|
||||
this.#follow(path, { x, y, z }, speed);
|
||||
return true;
|
||||
}
|
||||
|
||||
stop() {
|
||||
this.#path = undefined;
|
||||
this.#target = undefined;
|
||||
this.blocked_by = undefined;
|
||||
this.mob.move_control.stop();
|
||||
}
|
||||
|
||||
tick() {
|
||||
const path = this.#path;
|
||||
if (!path) return;
|
||||
const mob = this.mob;
|
||||
const points = path.points;
|
||||
while (this.#index < points.length && this.#close_to(points[this.#index])) {
|
||||
this.#index += 1;
|
||||
this.#closest = Infinity;
|
||||
this.#stuck = 0;
|
||||
}
|
||||
if (this.#index >= points.length) {
|
||||
this.stop();
|
||||
return;
|
||||
}
|
||||
const next = points[this.#index];
|
||||
mob.move_control.move_to(next.x, next.y, next.z, this.#speed);
|
||||
|
||||
// it stays blocked for as long as the block is solid and in its way, even when its path is searched again, so a
|
||||
// goal can count how long it's been there
|
||||
if (this.blocked_by) {
|
||||
this.blocked_by = this.#solid_block_toward(next);
|
||||
if (this.blocked_by) return;
|
||||
this.#closest = Infinity;
|
||||
this.#stuck = 0;
|
||||
}
|
||||
const distance = Math.hypot(next.x - mob.x, next.z - mob.z);
|
||||
if (distance < this.#closest - 0.01) {
|
||||
this.#closest = distance;
|
||||
this.#stuck = 0;
|
||||
return;
|
||||
}
|
||||
this.#stuck += 1;
|
||||
// pressed against a block its path goes through, it waits there instead of giving up, for its behavior to do
|
||||
// something about it
|
||||
if (this.#stuck >= BLOCKED_TICKS) {
|
||||
this.blocked_by = this.#solid_block_toward(next);
|
||||
if (this.blocked_by) return;
|
||||
}
|
||||
if (this.#stuck >= STUCK_TICKS) {
|
||||
const again = !this.#searched_again && this.#target ? this.#search(this.#target) : undefined;
|
||||
if (again) this.#follow(again, this.#target!, this.#speed, true);
|
||||
else this.stop();
|
||||
}
|
||||
}
|
||||
|
||||
#search(target: Point) {
|
||||
const mob = this.mob;
|
||||
const range = mob.attribute(ATTRIBUTES.follow_range);
|
||||
const body = {
|
||||
x: mob.x,
|
||||
y: mob.y,
|
||||
z: mob.z,
|
||||
width: mob.width,
|
||||
height: mob.height,
|
||||
max_rise: mob.jumps ? 1 : mob.step_height,
|
||||
max_fall: mob.max_fall,
|
||||
};
|
||||
return find_path(mob.level, body, target, { max_nodes: Math.floor(range * 16), range });
|
||||
}
|
||||
|
||||
#follow(path: Path, target: Point, speed: number, searched_again = false) {
|
||||
this.#path = path;
|
||||
this.#target = target;
|
||||
this.#speed = speed;
|
||||
this.#index = 0;
|
||||
this.#closest = Infinity;
|
||||
this.#stuck = 0;
|
||||
this.#searched_again = searched_again;
|
||||
}
|
||||
|
||||
// close enough to a waypoint to go on to the next, like minecraft's maxDistanceToWaypoint
|
||||
#close_to(point: Point) {
|
||||
const mob = this.mob;
|
||||
const reach = mob.width > 0.75 ? mob.width / 2 : 0.75 - mob.width / 2;
|
||||
return Math.hypot(point.x - mob.x, point.z - mob.z) < reach && Math.abs(point.y - mob.y) < 1;
|
||||
}
|
||||
|
||||
// a block its path goes through whose shape is in the way of its box, between where it is and its next waypoint
|
||||
#solid_block_toward(next: Point): BlockedBy | undefined {
|
||||
const mob = this.mob;
|
||||
const level = mob.level;
|
||||
const half = mob.width / 2;
|
||||
const min = [Math.min(mob.x, next.x) - half, Math.min(mob.y, next.y), Math.min(mob.z, next.z) - half];
|
||||
const max = [
|
||||
Math.max(mob.x, next.x) + half,
|
||||
Math.max(mob.y, next.y) + mob.height,
|
||||
Math.max(mob.z, next.z) + half,
|
||||
];
|
||||
for (let x = Math.floor(min[0]); x <= Math.floor(max[0] - EPSILON); x++) {
|
||||
for (let z = Math.floor(min[2]); z <= Math.floor(max[2] - EPSILON); z++) {
|
||||
for (let y = Math.floor(min[1]); y <= Math.floor(max[1] - EPSILON); y++) {
|
||||
if (!level.passes_through(x, y, z)) continue;
|
||||
const shape = level.collision_shape(x, y, z);
|
||||
const only_here = (bx: number, by: number, bz: number) => bx === x && by === y && bz === z && shape;
|
||||
if (overlaps_solid(min, max, only_here)) return { x, y, z, id: level.get_block_info(x, y, z)!.id };
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// how mobs find their way, like minecraft's PathFinder with its WalkNodeEvaluator: an A* search over the blocks a
|
||||
// mob's feet can be in. whether it fits in each one comes from its box against the blocks' collision shapes, so
|
||||
// partial blocks need nothing of their own: it steps up onto a slab, and goes through a block when its box fits
|
||||
// beside what's in it. see PATHFINDING.md
|
||||
import type { Shape } from "@/common/block_shapes.ts";
|
||||
import { CHUNK_SIZE } from "@/common/constants.ts";
|
||||
import { overlaps_solid } from "@/common/physics.ts";
|
||||
|
||||
export interface Point {
|
||||
x: number;
|
||||
y: number;
|
||||
z: number;
|
||||
}
|
||||
|
||||
// blocks the search goes through as if they weren't there, solid or not. a mob pressed against a solid one on its way
|
||||
// waits there, for its behavior to do something about it, see PathNavigation.blocked_by
|
||||
export const MOBS_PATH_THROUGH = "cubi:mobs_path_through";
|
||||
|
||||
// what the search reads, the entity manager is one
|
||||
export interface PathLevel {
|
||||
collision_shape(x: number, y: number, z: number): boolean | Shape;
|
||||
is_fluid(x: number, y: number, z: number): boolean;
|
||||
has_chunk(chunk_x: number, chunk_z: number): boolean;
|
||||
// whether the block is tagged MOBS_PATH_THROUGH
|
||||
passes_through(x: number, y: number, z: number): boolean;
|
||||
}
|
||||
|
||||
// the mob: its feet's middle, its box, and how far up and down it goes from one block to the next. max_rise is 1 for
|
||||
// a mob that jumps, or its step height for one that doesn't. max_fall is in blocks, 0 never drops, so it keeps out of
|
||||
// pits, like minecraft's getMaxFallDistance
|
||||
export interface PathBody extends Point {
|
||||
width: number;
|
||||
height: number;
|
||||
max_rise: number;
|
||||
max_fall: number;
|
||||
}
|
||||
|
||||
export interface PathOptions {
|
||||
// how many blocks it goes on from before settling for the closest it got, like minecraft's maxVisitedNodes
|
||||
max_nodes: number;
|
||||
// how far from where it starts it can go
|
||||
range: number;
|
||||
}
|
||||
|
||||
export interface Path {
|
||||
// where to go, one after another, not counting where it starts: the middle of its feet in each block
|
||||
points: Point[];
|
||||
// whether it gets to the target's block, or only as close as it could
|
||||
reached: boolean;
|
||||
}
|
||||
|
||||
// what going through water costs on top of the way, like minecraft's PathType.WATER malus
|
||||
const WATER_COST = 8;
|
||||
// how far under its feet something holds it up
|
||||
const SUPPORT = 0.1;
|
||||
const EPSILON = 1e-4;
|
||||
|
||||
const SIDES = [[1, 0], [-1, 0], [0, 1], [0, -1]] as const;
|
||||
const DIAGONALS = [[1, 1], [1, -1], [-1, 1], [-1, -1]] as const;
|
||||
|
||||
interface Node {
|
||||
// the block its feet are in
|
||||
x: number;
|
||||
y: number;
|
||||
z: number;
|
||||
point: Point;
|
||||
// the cost of the way here, and the distance left
|
||||
g: number;
|
||||
h: number;
|
||||
parent: Node | undefined;
|
||||
closed: boolean;
|
||||
}
|
||||
|
||||
// where it stands in a block and whether that's in water, or why it can't: "blocked" when its box doesn't fit there,
|
||||
// "air" when it fits but nothing holds it up
|
||||
type Probe = { point: Point; water: boolean } | "blocked" | "air";
|
||||
|
||||
// a way from the body to the target's block, or to as close as it can get when it can't. undefined when it can't get
|
||||
// any closer than it is
|
||||
export function find_path(level: PathLevel, body: PathBody, target: Point, options: PathOptions): Path | undefined {
|
||||
// the blocks it reads, once each. chunks that aren't kept are solid, so the search never builds one, and blocks it
|
||||
// passes through are empty
|
||||
const shapes = new Map<string, boolean | Shape>();
|
||||
const shape = (x: number, y: number, z: number) => {
|
||||
const key = `${x},${y},${z}`;
|
||||
let found = shapes.get(key);
|
||||
if (found === undefined) {
|
||||
const kept = level.has_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
|
||||
found = !kept ? true : level.passes_through(x, y, z) ? false : level.collision_shape(x, y, z);
|
||||
shapes.set(key, found);
|
||||
}
|
||||
return found;
|
||||
};
|
||||
const free = (min: number[], max: number[]) => !overlaps_solid(min, max, shape);
|
||||
|
||||
const half = body.width / 2;
|
||||
const height = body.height;
|
||||
const fits = (p: Point) => free([p.x - half, p.y, p.z - half], [p.x + half, p.y + height, p.z + half]);
|
||||
const held_up = (p: Point) => !free([p.x - half, p.y - SUPPORT, p.z - half], [p.x + half, p.y, p.z + half]);
|
||||
|
||||
const probes = new Map<string, Probe>();
|
||||
const probe = (x: number, y: number, z: number): Probe => {
|
||||
const key = `${x},${y},${z}`;
|
||||
let found = probes.get(key);
|
||||
if (found === undefined) {
|
||||
found = probe_block(x, y, z);
|
||||
probes.set(key, found);
|
||||
}
|
||||
return found;
|
||||
};
|
||||
const probe_block = (x: number, y: number, z: number): Probe => {
|
||||
const own = shape(x, y, z);
|
||||
const top = own === true ? 1 : own === false ? 0 : Math.max(0, ...own.map((box) => box[4]));
|
||||
// on top of something low in the block, like a slab, otherwise on its floor, beside whatever's there
|
||||
const point = { x: x + 0.5, y: top < 1 ? y + top : y, z: z + 0.5 };
|
||||
if (!fits(point)) return "blocked";
|
||||
const water = level.is_fluid(x, y, z);
|
||||
return water || held_up(point) ? { point, water } : "air";
|
||||
};
|
||||
|
||||
// whether it can go straight from one spot to the next: up first when it climbs, then across at the higher of the
|
||||
// two, then down when it drops. a diagonal step sweeps across both blocks beside it, so it can't cut a corner
|
||||
const can_move = (from: Point, to: Point) => {
|
||||
if (to.y - from.y > body.max_rise + EPSILON) return false;
|
||||
const top = Math.max(from.y, to.y);
|
||||
// the box swept from a to b, from y up to its head at the top of the move
|
||||
const sweep = (a: Point, b: Point, y: number) =>
|
||||
free(
|
||||
[Math.min(a.x, b.x) - half, y, Math.min(a.z, b.z) - half],
|
||||
[Math.max(a.x, b.x) + half, top + height, Math.max(a.z, b.z) + half],
|
||||
);
|
||||
return sweep(from, from, from.y) && sweep(from, to, top) && sweep(to, to, to.y);
|
||||
};
|
||||
|
||||
// the blocks it can get to from a node, and where it'd stand in them
|
||||
const neighbors = (node: Node) => {
|
||||
const found: { x: number; y: number; z: number; point: Point; water: boolean }[] = [];
|
||||
const add = (x: number, y: number, z: number) => {
|
||||
const result = probe(x, y, z);
|
||||
if (typeof result === "object") found.push({ x, y, z, ...result });
|
||||
return result;
|
||||
};
|
||||
for (const [dx, dz] of SIDES) {
|
||||
const x = node.x + dx;
|
||||
const z = node.z + dz;
|
||||
const same = add(x, node.y, z);
|
||||
if (same === "blocked") {
|
||||
add(x, node.y + 1, z);
|
||||
} else if (same === "air") {
|
||||
for (let drop = 1; drop <= body.max_fall; drop++) {
|
||||
if (add(x, node.y - drop, z) !== "air") break;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const [dx, dz] of DIAGONALS) add(node.x + dx, node.y, node.z + dz);
|
||||
return found;
|
||||
};
|
||||
|
||||
const start: Node = {
|
||||
x: Math.floor(body.x),
|
||||
y: Math.floor(body.y + EPSILON),
|
||||
z: Math.floor(body.z),
|
||||
point: { x: body.x, y: body.y, z: body.z },
|
||||
g: 0,
|
||||
h: distance(body, target),
|
||||
parent: undefined,
|
||||
closed: false,
|
||||
};
|
||||
const goal = { x: Math.floor(target.x), y: Math.floor(target.y + EPSILON), z: Math.floor(target.z) };
|
||||
const nodes = new Map<string, Node>([[`${start.x},${start.y},${start.z}`, start]]);
|
||||
const open = new Heap();
|
||||
open.push(start.h, start);
|
||||
let best = start;
|
||||
let visited = 0;
|
||||
|
||||
while (open.size > 0) {
|
||||
const node = open.pop()!;
|
||||
if (node.closed) continue;
|
||||
node.closed = true;
|
||||
if (node.x === goal.x && node.y === goal.y && node.z === goal.z) return path_to(node, true);
|
||||
if (node.h < best.h) best = node;
|
||||
if (++visited >= options.max_nodes) break;
|
||||
|
||||
for (const next of neighbors(node)) {
|
||||
if (distance(next.point, start.point) > options.range) continue;
|
||||
const key = `${next.x},${next.y},${next.z}`;
|
||||
const known = nodes.get(key);
|
||||
if (known?.closed) continue;
|
||||
const g = node.g + distance(node.point, next.point) + (next.water ? WATER_COST : 0);
|
||||
if (known && known.g <= g) continue;
|
||||
if (!can_move(node.point, next.point)) continue;
|
||||
const child = known ?? {
|
||||
x: next.x,
|
||||
y: next.y,
|
||||
z: next.z,
|
||||
point: next.point,
|
||||
g,
|
||||
h: distance(next.point, target),
|
||||
parent: node,
|
||||
closed: false,
|
||||
};
|
||||
child.g = g;
|
||||
child.parent = node;
|
||||
nodes.set(key, child);
|
||||
open.push(g + child.h, child);
|
||||
}
|
||||
}
|
||||
return best === start ? undefined : path_to(best, false);
|
||||
}
|
||||
|
||||
function path_to(node: Node, reached: boolean): Path {
|
||||
const points: Point[] = [];
|
||||
for (let at: Node | undefined = node; at?.parent; at = at.parent) points.push(at.point);
|
||||
return { points: points.reverse(), reached };
|
||||
}
|
||||
|
||||
function distance(a: Point, b: Point) {
|
||||
return Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
|
||||
}
|
||||
|
||||
// the open nodes, cheapest first. a node whose cost went down is pushed again, and its old place is skipped once
|
||||
// it's closed
|
||||
class Heap {
|
||||
#items: [number, Node][] = [];
|
||||
|
||||
get size() {
|
||||
return this.#items.length;
|
||||
}
|
||||
|
||||
push(cost: number, node: Node) {
|
||||
const items = this.#items;
|
||||
items.push([cost, node]);
|
||||
let i = items.length - 1;
|
||||
while (i > 0) {
|
||||
const parent = (i - 1) >> 1;
|
||||
if (items[parent][0] <= items[i][0]) break;
|
||||
[items[parent], items[i]] = [items[i], items[parent]];
|
||||
i = parent;
|
||||
}
|
||||
}
|
||||
|
||||
pop(): Node | undefined {
|
||||
const items = this.#items;
|
||||
const first = items[0];
|
||||
const last = items.pop();
|
||||
if (items.length > 0 && last) {
|
||||
items[0] = last;
|
||||
let i = 0;
|
||||
while (true) {
|
||||
const left = i * 2 + 1;
|
||||
const right = left + 1;
|
||||
let smallest = i;
|
||||
if (left < items.length && items[left][0] < items[smallest][0]) smallest = left;
|
||||
if (right < items.length && items[right][0] < items[smallest][0]) smallest = right;
|
||||
if (smallest === i) break;
|
||||
[items[smallest], items[i]] = [items[i], items[smallest]];
|
||||
i = smallest;
|
||||
}
|
||||
}
|
||||
return first?.[1];
|
||||
}
|
||||
}
|
||||
@@ -38,8 +38,11 @@ export async function start_game(
|
||||
expose_engine({ common: common_engine(), server: server_engine() });
|
||||
|
||||
const recipes = register_mod_data(mods.map((mod) => ({ id: mod.listing.id, data: mod.data })));
|
||||
const runtime = new ModRuntime();
|
||||
for (const mod of mods) {
|
||||
for (const json of mod.data.entities) register_entity_type(json.id, mod_entity_factory(json));
|
||||
for (const json of mod.data.entities) {
|
||||
register_entity_type(json.id, mod_entity_factory(json, runtime.entity_behaviors));
|
||||
}
|
||||
}
|
||||
|
||||
const dimension = default_dimension(mods);
|
||||
@@ -59,7 +62,6 @@ export async function start_game(
|
||||
const problem = cell_height_problem(shape, [terrain.cell_height, caves.cell_height]);
|
||||
if (problem) throw new Error(`dimension ${dimension.id} can't be generated by ${generator}: ${problem}`);
|
||||
|
||||
const runtime = new ModRuntime();
|
||||
// before the world loads, its mobs can have effects
|
||||
set_effect_types(runtime.effect_types());
|
||||
const game = new GameServer(host, save, default_seed, {
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// mods' mob behaviors, see EntityApi in common/mod_api/server.ts: the goals scripts write, run by the same goal
|
||||
// selectors as the engine's own, and the engine's goals made for scripts to add
|
||||
import type { BuiltinGoal, BuiltinGoals, GoalFlag, MobGoals, ScriptGoal } from "@/common/mod_api/server.ts";
|
||||
import {
|
||||
FloatGoal,
|
||||
Goal,
|
||||
type GoalSelector,
|
||||
HurtByTargetGoal,
|
||||
LookAtPlayerGoal,
|
||||
MeleeAttackGoal,
|
||||
NearestAttackablePlayerGoal,
|
||||
PanicGoal,
|
||||
RandomLookAroundGoal,
|
||||
RandomStrollGoal,
|
||||
} from "./entity/goals.ts";
|
||||
import type { Mob } from "./entity/mob.ts";
|
||||
import { run_guarded } from "./mod_runtime.ts";
|
||||
|
||||
const GOAL_FLAGS: readonly GoalFlag[] = ["move", "look", "jump", "target"];
|
||||
|
||||
// a script's goal, with each call guarded. one that throws is dropped: it never runs again, so it doesn't log every
|
||||
// tick, and the mob's other goals go on
|
||||
class ScriptedGoal extends Goal {
|
||||
#broken = false;
|
||||
|
||||
constructor(readonly mod: string, readonly behavior: string, readonly goal: ScriptGoal) {
|
||||
super();
|
||||
this.flags = [...(goal.flags ?? [])];
|
||||
}
|
||||
|
||||
#call<T>(what: string, fn: () => T, fallback: T): T {
|
||||
if (this.#broken) return fallback;
|
||||
let done = false;
|
||||
const result = run_guarded(this.mod, `${this.behavior} goal ${what}`, () => {
|
||||
const result = fn();
|
||||
done = true;
|
||||
return result;
|
||||
});
|
||||
if (!done) this.#broken = true;
|
||||
return done ? result as T : fallback;
|
||||
}
|
||||
|
||||
can_use() {
|
||||
return this.#call("can_use", () => Boolean(this.goal.can_use()), false);
|
||||
}
|
||||
|
||||
override can_continue_to_use() {
|
||||
const goal = this.goal;
|
||||
return this.#call(
|
||||
"can_continue_to_use",
|
||||
() => Boolean(goal.can_continue_to_use ? goal.can_continue_to_use() : goal.can_use()),
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
override is_interruptable() {
|
||||
if (!this.goal.is_interruptable) return true;
|
||||
return this.#call("is_interruptable", () => Boolean(this.goal.is_interruptable!()), true);
|
||||
}
|
||||
|
||||
override start() {
|
||||
if (this.goal.start) this.#call("start", () => this.goal.start!(), undefined);
|
||||
}
|
||||
|
||||
override stop() {
|
||||
if (this.goal.stop) this.#call("stop", () => this.goal.stop!(), undefined);
|
||||
}
|
||||
|
||||
override tick() {
|
||||
if (this.goal.tick) this.#call("tick", () => this.goal.tick!(), undefined);
|
||||
}
|
||||
}
|
||||
|
||||
// what makes each BuiltinGoal for a mob. one BuiltinGoal can be added to many mobs, each gets its own
|
||||
const builders = new WeakMap<BuiltinGoal, (mob: Mob) => Goal>();
|
||||
|
||||
function builtin(kind: string, build: (mob: Mob) => Goal): BuiltinGoal {
|
||||
const goal = Object.freeze({ kind });
|
||||
builders.set(goal, build);
|
||||
return goal;
|
||||
}
|
||||
|
||||
// undefined leaves the goal's own default
|
||||
function option(options: Record<string, unknown> | undefined, name: string): number | undefined {
|
||||
const value = options?.[name];
|
||||
if (value === undefined) return undefined;
|
||||
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
|
||||
throw new Error(`a goal's ${name} must be a number, 0 or more`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export const BUILTIN_GOALS = Object.freeze<BuiltinGoals>({
|
||||
float: () => builtin("float", (mob) => new FloatGoal(mob)),
|
||||
random_stroll(options) {
|
||||
const [speed, interval, range] = ["speed", "interval", "range"].map((name) => option(options, name));
|
||||
return builtin("random_stroll", (mob) => new RandomStrollGoal(mob, speed, interval, range));
|
||||
},
|
||||
panic(options) {
|
||||
const speed = option(options, "speed");
|
||||
return builtin("panic", (mob) => new PanicGoal(mob, speed));
|
||||
},
|
||||
look_at_player(options) {
|
||||
const [range, probability] = ["range", "probability"].map((name) => option(options, name));
|
||||
return builtin("look_at_player", (mob) => new LookAtPlayerGoal(mob, range, probability));
|
||||
},
|
||||
random_look_around: () => builtin("random_look_around", (mob) => new RandomLookAroundGoal(mob)),
|
||||
melee_attack(options) {
|
||||
const [speed, interval] = ["speed", "interval"].map((name) => option(options, name));
|
||||
return builtin("melee_attack", (mob) => new MeleeAttackGoal(mob, speed, interval));
|
||||
},
|
||||
hurt_by_target: () => builtin("hurt_by_target", (mob) => new HurtByTargetGoal(mob)),
|
||||
nearest_attackable_player: () =>
|
||||
builtin("nearest_attackable_player", (mob) => new NearestAttackablePlayerGoal(mob)),
|
||||
});
|
||||
|
||||
// what a behavior adds the mob's goals to
|
||||
export function mob_goals(mod: string, behavior: string, mob: Mob): MobGoals {
|
||||
const adder = (selector: GoalSelector) => (priority: number, goal: ScriptGoal | BuiltinGoal) => {
|
||||
if (typeof priority !== "number" || !Number.isFinite(priority)) {
|
||||
throw new Error("a goal's priority must be a number");
|
||||
}
|
||||
selector.add_goal(priority, engine_goal(mod, behavior, mob, goal));
|
||||
};
|
||||
return { add: adder(mob.goals), add_target: adder(mob.target_goals) };
|
||||
}
|
||||
|
||||
function engine_goal(mod: string, behavior: string, mob: Mob, goal: ScriptGoal | BuiltinGoal): Goal {
|
||||
const build = builders.get(goal as BuiltinGoal);
|
||||
if (build) return build(mob);
|
||||
const script_goal = goal as ScriptGoal;
|
||||
if (typeof script_goal?.can_use !== "function") {
|
||||
throw new Error("a goal needs a can_use function, or has to come from ctx.entities.goals");
|
||||
}
|
||||
const flags = script_goal.flags ?? [];
|
||||
if (!Array.isArray(flags) || flags.some((flag) => !GOAL_FLAGS.includes(flag))) {
|
||||
throw new Error(`a goal's flags must be some of ${GOAL_FLAGS.map((flag) => `"${flag}"`).join(", ")}`);
|
||||
}
|
||||
return new ScriptedGoal(mod, behavior, script_goal);
|
||||
}
|
||||
+125
-7
@@ -46,6 +46,7 @@ import type {
|
||||
MenuBuilder,
|
||||
MenuHandle,
|
||||
MenuType,
|
||||
MobRef,
|
||||
Player,
|
||||
PlayerMenuBuilder,
|
||||
Position,
|
||||
@@ -86,7 +87,9 @@ import type { ServerPlayer } from "./player.ts";
|
||||
import { Menu, type MenuFluidSlot, type MenuSlot } from "./menu.ts";
|
||||
import { damage_source, type DamageSource, type Entity } from "./entity/entity.ts";
|
||||
import type { LivingEntity } from "./entity/living_entity.ts";
|
||||
import type { EffectJson } from "@/common/mod_data.ts";
|
||||
import type { EffectJson, EntityJson } from "@/common/mod_data.ts";
|
||||
import { Mob } from "./entity/mob.ts";
|
||||
import { BUILTIN_GOALS, mob_goals } from "./mob_behaviors.ts";
|
||||
import { create_entity } from "./entity/entity_types.ts";
|
||||
import { BLOCK_DROP_PICKUP_DELAY, ItemEntity } from "./entity/item_entity.ts";
|
||||
import { attribute_type, type AttributeType, MODIFIER_OPERATIONS } from "./entity/attributes.ts";
|
||||
@@ -178,6 +181,8 @@ export class ModRuntime {
|
||||
fluid_rules = new FluidRules(run_guarded);
|
||||
item_components = new Map<string, { mod: string; component: ItemComponent }>();
|
||||
effect_components = new Map<string, { mod: string; component: EffectComponent }>();
|
||||
// mods' mob behaviors by id, each adding its goals to a mob, see mod_entity.ts
|
||||
entity_behaviors = new Map<string, (mob: Mob) => void>();
|
||||
// every command, the engine's and mods', see common/commands.ts
|
||||
commands = new CommandDispatcher<ServerCommandSource>();
|
||||
// who registered each command name: "cubi" or a mod's id
|
||||
@@ -247,6 +252,9 @@ export class ModRuntime {
|
||||
|
||||
// the other way, for apis that take a player
|
||||
#server_players = new WeakMap<Player, ServerPlayer>();
|
||||
// mob refs, one for each mob so scripts can compare them, and the other way
|
||||
#mob_refs = new WeakMap<Mob, MobRef>();
|
||||
#mobs = new WeakMap<MobRef, Mob>();
|
||||
// menu types by id, every mod's
|
||||
#menu_types = new Set<string>();
|
||||
// what each mod adds to the player's own menu, in load order
|
||||
@@ -390,6 +398,16 @@ export class ModRuntime {
|
||||
|
||||
this.loot.check();
|
||||
|
||||
for (const [id, entity] of EverythingRegistry.entries<EntityJson>("entities")) {
|
||||
const behavior = entity.behavior;
|
||||
if (behavior?.includes(":") && !this.entity_behaviors.has(behavior)) {
|
||||
throw new ModLoadError(
|
||||
id.split(":")[0],
|
||||
`entity ${id} has behavior ${behavior}, which nothing registered`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for (const [id, block] of EverythingRegistry.entries<{ components?: Record<string, unknown> }>("blocks")) {
|
||||
for (const component of Object.keys(block.components ?? {})) {
|
||||
if (!this.block_components.has(component) && !this.rules.has(component)) {
|
||||
@@ -651,6 +669,91 @@ export class ModRuntime {
|
||||
return api;
|
||||
}
|
||||
|
||||
mob(mob: Mob): MobRef {
|
||||
let ref = this.#mob_refs.get(mob);
|
||||
if (!ref) {
|
||||
ref = this.#mob_ref(mob);
|
||||
this.#mob_refs.set(mob, ref);
|
||||
this.#mobs.set(ref, mob);
|
||||
}
|
||||
return ref;
|
||||
}
|
||||
|
||||
// a player or a mob the way scripts see them, undefined once they're dead or gone
|
||||
#living_ref(entity: LivingEntity | undefined): Player | MobRef | undefined {
|
||||
if (!entity?.alive) return undefined;
|
||||
return entity instanceof Mob ? this.mob(entity) : this.player(entity as ServerPlayer);
|
||||
}
|
||||
|
||||
// the other way, for apis that take a player or a mob
|
||||
#living_entity(ref: Player | MobRef, what: string): LivingEntity {
|
||||
const entity = this.#server_players.get(ref as Player) ?? this.#mobs.get(ref as MobRef);
|
||||
if (!entity) throw new Error(`${what} must be a player or a mob`);
|
||||
return entity;
|
||||
}
|
||||
|
||||
#mob_ref(mob: Mob): MobRef {
|
||||
const runtime = this;
|
||||
const extra: Omit<MobRef, keyof LivingRef> = {
|
||||
type: mob.type,
|
||||
get position() {
|
||||
return { x: mob.x, y: mob.y, z: mob.z };
|
||||
},
|
||||
get eye_position() {
|
||||
return { x: mob.x, y: mob.y + mob.eye_height, z: mob.z };
|
||||
},
|
||||
get look_direction() {
|
||||
return look_direction(mob.head_yaw, mob.pitch);
|
||||
},
|
||||
get velocity() {
|
||||
return { x: mob.vx, y: mob.vy, z: mob.vz };
|
||||
},
|
||||
get on_ground() {
|
||||
return mob.on_ground;
|
||||
},
|
||||
get in_water() {
|
||||
return mob.in_water;
|
||||
},
|
||||
get target() {
|
||||
return runtime.#living_ref(mob.target);
|
||||
},
|
||||
set target(target) {
|
||||
mob.target = target === undefined ? undefined : runtime.#living_entity(target, "a target");
|
||||
},
|
||||
get last_attacker() {
|
||||
return runtime.#living_ref(mob.last_attacker);
|
||||
},
|
||||
random: () => mob.random(),
|
||||
move_to(x, y, z, speed = 1) {
|
||||
if (![x, y, z, speed].every(Number.isFinite)) throw new Error("move_to takes a position and a speed");
|
||||
return mob.navigation.move_to(x, y, z, speed);
|
||||
},
|
||||
stop() {
|
||||
mob.navigation.stop();
|
||||
},
|
||||
get moving() {
|
||||
return mob.navigation.moving;
|
||||
},
|
||||
get blocked_by() {
|
||||
const blocked = mob.navigation.blocked_by;
|
||||
return blocked && { ...blocked };
|
||||
},
|
||||
look_at(x, y, z) {
|
||||
if (![x, y, z].every(Number.isFinite)) throw new Error("look_at takes a position");
|
||||
mob.look_control.look_at(x, y, z);
|
||||
},
|
||||
jump() {
|
||||
mob.jump_control.jump();
|
||||
},
|
||||
attack(target) {
|
||||
const entity = runtime.#living_entity(target, "what a mob attacks");
|
||||
mob.level.entity_event(mob, "swing");
|
||||
mob.do_hurt_target(entity);
|
||||
},
|
||||
};
|
||||
return Object.defineProperties(living_ref(mob), Object.getOwnPropertyDescriptors(extra)) as MobRef;
|
||||
}
|
||||
|
||||
block_ref(x: number, y: number, z: number, id: string): BlockRef {
|
||||
const game = this.game;
|
||||
return {
|
||||
@@ -718,6 +821,20 @@ export class ModRuntime {
|
||||
this.effect_components.set(id, { mod, component: component as EffectComponent });
|
||||
},
|
||||
},
|
||||
entities: {
|
||||
register_behavior: (id, behavior) => {
|
||||
register.new_id("entity behavior", id, this.entity_behaviors.has(id));
|
||||
if (typeof behavior !== "function") register.fail(`entity behavior ${id} must be a function`);
|
||||
this.entity_behaviors.set(id, (mob) => {
|
||||
run_guarded(
|
||||
mod,
|
||||
`entity behavior ${id}`,
|
||||
() => behavior(this.mob(mob), mob_goals(mod, id, mob)),
|
||||
);
|
||||
});
|
||||
},
|
||||
goals: BUILTIN_GOALS,
|
||||
},
|
||||
commands: {
|
||||
register: (name_or_node: string | CommandNode<CommandSource>, command?: Command) => {
|
||||
register.running("command");
|
||||
@@ -1486,12 +1603,7 @@ function player_api(game: GameServer, player: ServerPlayer): Player {
|
||||
},
|
||||
// the same way the client aims, see ClientLevel.pick
|
||||
get look_direction() {
|
||||
const cos_pitch = Math.cos(player.pitch);
|
||||
return {
|
||||
x: -Math.sin(player.yaw) * cos_pitch,
|
||||
y: Math.sin(player.pitch),
|
||||
z: -Math.cos(player.yaw) * cos_pitch,
|
||||
};
|
||||
return look_direction(player.yaw, player.pitch);
|
||||
},
|
||||
get biome() {
|
||||
return game.world.biome_at(Math.floor(player.x), Math.floor(player.y), Math.floor(player.z));
|
||||
@@ -1624,6 +1736,12 @@ function effect_of(entity: LivingEntity, id: string) {
|
||||
return effect && { amplifier: effect.amplifier, duration: effect.duration };
|
||||
}
|
||||
|
||||
// which way yaw and pitch face, a vector 1 long
|
||||
function look_direction(yaw: number, pitch: number): Position {
|
||||
const cos_pitch = Math.cos(pitch);
|
||||
return { x: -Math.sin(yaw) * cos_pitch, y: Math.sin(pitch), z: -Math.cos(yaw) * cos_pitch };
|
||||
}
|
||||
|
||||
export function living_ref(entity: LivingEntity): LivingRef {
|
||||
return {
|
||||
id: entity.id,
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
|
||||
// dangerous business's placement components: slabs and other blocks that go in the top or bottom half, blocks that
|
||||
// join the same block beside them, blocks that pick some of their looks when placed, and pipes that stand up or lie
|
||||
// down. and the death block
|
||||
import { assert, assertEquals, assertNotEquals } from "@std/assert";
|
||||
// down. the death block, and the coilhead
|
||||
import { assert, assertAlmostEquals, assertEquals, assertNotEquals } from "@std/assert";
|
||||
import { ItemStack } from "@/common/inventory.ts";
|
||||
import { get_state_value } from "@/common/utils.ts";
|
||||
import { copy_dir, test_game } from "./helpers.ts";
|
||||
import { get_state_value, set_state_value } from "@/common/utils.ts";
|
||||
import { create_entity } from "@/server/game/entity/entity_types.ts";
|
||||
import type { Mob } from "@/server/game/entity/mob.ts";
|
||||
import { copy_dir, errors_during, test_game, test_mob } from "./helpers.ts";
|
||||
|
||||
const HALF = "dangerous_business:concrete_wall_slab";
|
||||
const CONNECTS = "dangerous_business:floor_grate";
|
||||
@@ -15,6 +17,8 @@ const RANDOM_LOOK = "dangerous_business:water_puddle";
|
||||
const FLOOR = "dangerous_business:concrete_floor";
|
||||
const DEATH = "dangerous_business:death";
|
||||
const PIPE = "dangerous_business:double_steel_pipes";
|
||||
const COILHEAD = "dangerous_business:coilhead";
|
||||
const FACTORY_DOOR = "dangerous_business:factory_door";
|
||||
|
||||
// alice on a concrete floor at y 100, south of 0 100 0 and looking north, holding each of the blocks. it's a game of
|
||||
// its own, which tests playing mods/ leave out
|
||||
@@ -123,3 +127,127 @@ Deno.test("the death block takes away an item falling into it", async () => {
|
||||
for (let i = 0; i < 40 && !item.removed; i++) t.game.tick();
|
||||
assert(item.removed);
|
||||
});
|
||||
|
||||
// a coilhead 6 blocks north of alice, right where she's looking
|
||||
function spawn_coilhead(t: Awaited<ReturnType<typeof setup>>["t"]) {
|
||||
const coilhead = create_entity(t.game.entities, COILHEAD)!;
|
||||
coilhead.set_position(0.5, 100, -2.5);
|
||||
t.game.entities.add_entity(coilhead);
|
||||
return coilhead;
|
||||
}
|
||||
|
||||
Deno.test("a coilhead can't move while a player looks at it, and comes for them once they look away", async () => {
|
||||
const { t } = await setup();
|
||||
const coilhead = spawn_coilhead(t);
|
||||
for (let i = 0; i < 100; i++) t.game.tick();
|
||||
assertAlmostEquals(coilhead.x, 0.5, 1e-6);
|
||||
assertAlmostEquals(coilhead.z, -2.5, 1e-6);
|
||||
|
||||
// looking south, with it behind her
|
||||
t.send(1, { type: "move", x: 0.5, y: 100, z: 3.5, yaw: Math.PI, pitch: 0 });
|
||||
for (let i = 0; i < 100; i++) t.game.tick();
|
||||
assert(coilhead.z > 0, `it only got to z ${coilhead.z}`);
|
||||
});
|
||||
|
||||
Deno.test("a player can't stop a coilhead through a wall", async () => {
|
||||
const { t } = await setup();
|
||||
for (let x = -3; x <= 3; x++) {
|
||||
for (let y = 100; y < 103; y++) t.game.set_block(x, y, 0, FLOOR);
|
||||
}
|
||||
const coilhead = spawn_coilhead(t);
|
||||
for (let i = 0; i < 100; i++) t.game.tick();
|
||||
// up against the wall, still on its way to her
|
||||
assert(coilhead.z > -1.5, `it only got to z ${coilhead.z}`);
|
||||
});
|
||||
|
||||
// a wall along z 0 with a closed factory door at x 0, facing so it's across the way. open says whether both its halves
|
||||
// are open, open_door opens them
|
||||
function door_in_wall(
|
||||
t: Awaited<ReturnType<typeof setup>>["t"],
|
||||
state: (x: number, y: number, z: number, name: string) => number | undefined,
|
||||
) {
|
||||
const world = t.game.world;
|
||||
const set_state = (x: number, y: number, z: number, name: string, value: number) =>
|
||||
t.game.set_block_state(
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
set_state_value(world.get_block_value(x, y, z), world.get_block_info(x, y, z)!, name, value)! >>> 16,
|
||||
);
|
||||
for (let x = -3; x <= 3; x++) {
|
||||
for (let y = 100; y < 103; y++) t.game.set_block(x, y, 0, FLOOR);
|
||||
}
|
||||
for (const [y, half] of [[100, 0], [101, 1]]) {
|
||||
t.game.set_block(0, y, 0, FACTORY_DOOR);
|
||||
set_state(0, y, 0, "facing", 0);
|
||||
set_state(0, y, 0, "half", half);
|
||||
}
|
||||
return {
|
||||
open: () => state(0, 100, 0, "open") === 1 && state(0, 101, 0, "open") === 1,
|
||||
open_door: () => [100, 101].forEach((y) => set_state(0, y, 0, "open", 1)),
|
||||
};
|
||||
}
|
||||
|
||||
Deno.test("a mob's path goes through a closed factory door, and it waits there until the door opens", async () => {
|
||||
const { t, state } = await setup();
|
||||
const { open_door } = door_in_wall(t, state);
|
||||
|
||||
// thin enough to get past the door once it's open
|
||||
const mob = test_mob(t.game, {}, 0.5, 100, -2.5);
|
||||
assert(mob.navigation.move_to(0.5, 100, 2.5));
|
||||
for (let i = 0; i < 60; i++) t.game.tick();
|
||||
assertEquals(mob.navigation.blocked_by, { x: 0, y: 100, z: 0, id: FACTORY_DOOR });
|
||||
assert(mob.z < 1);
|
||||
|
||||
open_door();
|
||||
for (let i = 0; i < 200 && mob.navigation.moving; i++) t.game.tick();
|
||||
assert(!mob.navigation.moving);
|
||||
assert(mob.z > 1.5, `it only got to z ${mob.z}`);
|
||||
assertEquals(mob.navigation.blocked_by, undefined);
|
||||
});
|
||||
|
||||
Deno.test("a coilhead going after a player opens a closed door in its way after standing at it a while", async () => {
|
||||
const { t, state } = await setup();
|
||||
const { open } = door_in_wall(t, state);
|
||||
// alice looks away from the door, so nothing freezes it
|
||||
t.send(1, { type: "move", x: 0.5, y: 100, z: 3.5, yaw: Math.PI, pitch: 0 });
|
||||
const coilhead = spawn_coilhead(t) as Mob;
|
||||
|
||||
let blocked_at: number | undefined;
|
||||
let tick = 0;
|
||||
for (; tick < 300 && !open(); tick++) {
|
||||
t.game.tick();
|
||||
if (blocked_at === undefined && coilhead.navigation.blocked_by) blocked_at = tick;
|
||||
}
|
||||
assert(open(), "it never opened the door");
|
||||
assert(blocked_at !== undefined && tick - blocked_at >= 40, `it opened it at ${tick}, blocked from ${blocked_at}`);
|
||||
});
|
||||
|
||||
Deno.test("a coilhead seen while it waits at a closed door stops waiting, and doesn't open it", async () => {
|
||||
const { t, state } = await setup();
|
||||
const { open } = door_in_wall(t, state);
|
||||
// a window 2 wide at head height beside the door, too low to get through
|
||||
for (const x of [1, 2]) t.game.set_block(x, 101, 0, "cubi:air");
|
||||
// alice beside the window, looking away
|
||||
t.send(1, { type: "move", x: 3.5, y: 100, z: 1.5, yaw: -Math.PI / 2, pitch: 0 });
|
||||
const coilhead = spawn_coilhead(t) as Mob;
|
||||
for (let i = 0; i < 300 && !coilhead.navigation.blocked_by; i++) t.game.tick();
|
||||
assert(coilhead.navigation.blocked_by, "it never got to the door");
|
||||
for (let i = 0; i < 10; i++) t.game.tick();
|
||||
|
||||
// she turns to look at it through the window, before it's waited long enough to open the door
|
||||
const errors = await errors_during(() => {
|
||||
t.send(1, {
|
||||
type: "move",
|
||||
x: 3.5,
|
||||
y: 100,
|
||||
z: 1.5,
|
||||
yaw: Math.atan2(3.5 - coilhead.x, 1.5 - coilhead.z),
|
||||
pitch: 0,
|
||||
});
|
||||
for (let i = 0; i < 60; i++) t.game.tick();
|
||||
});
|
||||
assertEquals(errors, []);
|
||||
assert(!open(), "it opened the door while it was seen");
|
||||
assertEquals(coilhead.navigation.blocked_by, undefined);
|
||||
});
|
||||
|
||||
@@ -16,7 +16,7 @@ import { LocalPlayer } from "@/client/entity/local_player.ts";
|
||||
import { Options } from "@/client/options.ts";
|
||||
import type { Client } from "@/client/client.ts";
|
||||
import type { ModListing } from "@/common/mod_loader.ts";
|
||||
import { copy_dir, test_game } from "./helpers.ts";
|
||||
import { copy_dir, errors_during, test_game } from "./helpers.ts";
|
||||
import { game_with_pool } from "./chunk_loading.ts";
|
||||
|
||||
const [MAJOR, MINOR] = GAME_VERSION.split(".");
|
||||
@@ -61,19 +61,6 @@ function as_mod<T>(mod: string, fn: () => T, engine_access = true): Promise<T> {
|
||||
return loading_mod(mod, engine_access, () => Promise.resolve(fn()));
|
||||
}
|
||||
|
||||
// what console.error got while fn ran
|
||||
async function errors_during(fn: () => unknown): Promise<string[]> {
|
||||
const errors: string[] = [];
|
||||
const original = console.error;
|
||||
console.error = (...args: unknown[]) => errors.push(args.map(String).join(" "));
|
||||
try {
|
||||
await fn();
|
||||
} finally {
|
||||
console.error = original;
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
Deno.test("a server mod hooks GameServer to drop twice, like the plan's example", async () => {
|
||||
const dir = mods_dir((dir) =>
|
||||
write_mod(
|
||||
|
||||
@@ -33,6 +33,9 @@ import type { Face, SharedWorld } from "@/common/mod_api/shared.ts";
|
||||
import { shared as setup_shared } from "@/mods/bworld/scripts/shared.ts";
|
||||
import { shared_context } from "@/common/shared_context.ts";
|
||||
import { RecipeBook } from "@/common/mod_loader.ts";
|
||||
import type { EntityJson } from "@/common/mod_data.ts";
|
||||
import { mod_entity_factory } from "@/server/game/entity/mod_entity.ts";
|
||||
import type { Mob } from "@/server/game/entity/mob.ts";
|
||||
|
||||
// the repo's own mods/, read once: reading and checking every mod's files is most of starting a game in a test. only
|
||||
// mods/ is kept, since tests change the temporary folders they make between games
|
||||
@@ -445,3 +448,33 @@ export function client_of(game: GameServer, area: Area) {
|
||||
blocks: () => blocks_in(area, (x, y, z) => at(x, y, z)!),
|
||||
};
|
||||
}
|
||||
|
||||
// a mob made straight from entity json fields, with no goals, so it only does what a test makes it do. 0.6 wide and
|
||||
// 1.8 tall unless fields say otherwise, with its feet at x y z
|
||||
export function test_mob(game: GameServer, fields: Partial<EntityJson>, x: number, y: number, z: number): Mob {
|
||||
const json: EntityJson = {
|
||||
id: "test:mob",
|
||||
texture: "cubi:missing",
|
||||
behavior: "test:still",
|
||||
width: 0.6,
|
||||
height: 1.8,
|
||||
...fields,
|
||||
};
|
||||
const mob = mod_entity_factory(json, new Map([["test:still", () => {}]]))(game.entities) as Mob;
|
||||
mob.set_position(x, y, z);
|
||||
game.entities.add_entity(mob);
|
||||
return mob;
|
||||
}
|
||||
|
||||
// what console.error got while fn ran
|
||||
export async function errors_during(fn: () => unknown): Promise<string[]> {
|
||||
const errors: string[] = [];
|
||||
const original = console.error;
|
||||
console.error = (...args: unknown[]) => errors.push(args.map(String).join(" "));
|
||||
try {
|
||||
await fn();
|
||||
} finally {
|
||||
console.error = original;
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
@@ -3,13 +3,19 @@
|
||||
|
||||
// mobs mods define in entities/<name>.json, drawn with a bedrock model from models/<name>.geo.json
|
||||
import { assert, assertAlmostEquals, assertEquals, assertNotEquals, assertStringIncludes } from "@std/assert";
|
||||
import { entity_category, entity_model_from_geo, type EntityBoneJson, validate_entity } from "@/common/mod_data.ts";
|
||||
import {
|
||||
entity_category,
|
||||
entity_model_from_geo,
|
||||
type EntityBoneJson,
|
||||
type EntityJson,
|
||||
validate_entity,
|
||||
} from "@/common/mod_data.ts";
|
||||
import type { Texture } from "@/client/renderer/mod.ts";
|
||||
import { IDENTITY } from "@/client/rendering/model_math.ts";
|
||||
import { push_model } from "@/client/rendering/model_renderer.ts";
|
||||
import { Mob } from "@/server/game/entity/mob.ts";
|
||||
import { create_entity } from "@/server/game/entity/entity_types.ts";
|
||||
import { container_items, test_game } from "./helpers.ts";
|
||||
import { container_items, test_game, test_mob } 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"));
|
||||
@@ -87,6 +93,13 @@ Deno.test("an entity without a model is drawn as its texture, and a scripted one
|
||||
assertEquals(validate_entity({ id: "a:b", texture: "a:b", behavior: "a:flying", width: 0.25, height: 0.25 }), []);
|
||||
});
|
||||
|
||||
Deno.test("an entity can say it doesn't jump and how far it drops, in whole blocks", () => {
|
||||
const entity = { id: "a:b", texture: "a:b", width: 1, height: 1 };
|
||||
assertEquals(validate_entity({ ...entity, jumps: false, max_fall: 0 }), []);
|
||||
assertEquals(validate_entity({ ...entity, max_fall: 1.5 }).length, 1);
|
||||
assertEquals(validate_entity({ ...entity, max_fall: -1 }).length, 1);
|
||||
});
|
||||
|
||||
Deno.test("an entity's category is monster for monsters unless it says otherwise", () => {
|
||||
const entity = { id: "a:b", texture: "a:b", width: 1, height: 1 };
|
||||
assertEquals(entity_category(entity), "creature");
|
||||
@@ -157,3 +170,53 @@ Deno.test("solid blocks can't be placed where a mob or player is", async () => {
|
||||
send(1, { type: "use_block", x: 3, y: 100, z: 3, face: "top" });
|
||||
assertEquals(game.world.get_block_id(3, 101, 3), "cubi:air");
|
||||
});
|
||||
|
||||
// a mob with no goals, so it only walks where it's sent, at 0.5 100 0.5 on a stone floor that ends at x 3 with a deep
|
||||
// pit beyond, and a wall at x 2 when wall is set. alice is there too, so the mob thinks
|
||||
async function walker(fields: Partial<EntityJson>, wall = false) {
|
||||
const t = await test_game("mods");
|
||||
for (let x = -4; x <= 8; x++) {
|
||||
for (let z = -4; z <= 4; z++) {
|
||||
for (let y = 90; y < 104; y++) t.game.set_block(x, y, z, y === 99 && x <= 3 ? "bworld:stone" : "cubi:air");
|
||||
if (wall && x === 2) t.game.set_block(x, 100, z, "bworld:stone");
|
||||
}
|
||||
}
|
||||
t.join(1, "alice");
|
||||
t.send(1, { type: "move", x: -3.5, y: 100, z: -3.5, yaw: 0, pitch: 0 });
|
||||
return { game: t.game, mob: test_mob(t.game, fields, 0.5, 100, 0.5) };
|
||||
}
|
||||
|
||||
// the highest and lowest its feet got over ticks, walking to x
|
||||
function walk(game: { tick(): void }, mob: Mob, x: number, ticks: number) {
|
||||
let [lowest, highest] = [mob.y, mob.y];
|
||||
for (let i = 0; i < ticks; i++) {
|
||||
mob.move_control.move_to(x, 100, 0.5, 1);
|
||||
game.tick();
|
||||
lowest = Math.min(lowest, mob.y);
|
||||
highest = Math.max(highest, mob.y);
|
||||
}
|
||||
return { lowest, highest };
|
||||
}
|
||||
|
||||
Deno.test("a mob that doesn't jump stays down at a wall a mob that jumps gets onto", async () => {
|
||||
const jumper = await walker({}, true);
|
||||
assert(walk(jumper.game, jumper.mob, 2.5, 60).highest >= 101);
|
||||
|
||||
const stays = await walker({ jumps: false }, true);
|
||||
assertAlmostEquals(walk(stays.game, stays.mob, 2.5, 60).highest, 100, 1e-6);
|
||||
});
|
||||
|
||||
Deno.test("a mob that doesn't drop stops at an edge, unless something knocks it off", async () => {
|
||||
const faller = await walker({});
|
||||
assert(walk(faller.game, faller.mob, 6.5, 100).lowest < 99);
|
||||
|
||||
const { game, mob } = await walker({ max_fall: 0 });
|
||||
assertAlmostEquals(walk(game, mob, 6.5, 100).lowest, 100, 1e-6);
|
||||
// like a sneaking player, it can lean out until only the edge of its box is over the floor
|
||||
assert(mob.x - mob.width / 2 < 4, `it got to x ${mob.x}`);
|
||||
|
||||
// hit from the side away from the pit
|
||||
mob.knockback(0.4, -1, 0);
|
||||
for (let i = 0; i < 40; i++) game.tick();
|
||||
assert(mob.y < 99, `it's still at y ${mob.y}`);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// mobs following paths, see server/game/entity/navigation.ts
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import { test_game, test_mob } from "./helpers.ts";
|
||||
|
||||
// two rooms on a stone floor at y 99, split by a wall at x 3 with a doorway 2 high at z 4. a goal-less mob in the
|
||||
// west room at 0.5 100 0.5, and alice in its corner, so it thinks
|
||||
async function rooms() {
|
||||
const t = await test_game("mods");
|
||||
for (let x = -6; x <= 10; x++) {
|
||||
for (let z = -6; z <= 6; z++) {
|
||||
t.game.set_block(x, 99, z, "bworld:stone");
|
||||
for (let y = 100; y < 105; y++) t.game.set_block(x, y, z, "cubi:air");
|
||||
if (x === 3) {
|
||||
for (let y = 100; y < 103; y++) {
|
||||
if (z !== 4 || y === 102) t.game.set_block(x, y, z, "bworld:stone");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
t.join(1, "alice");
|
||||
t.send(1, { type: "move", x: -5.5, y: 100, z: -5.5, yaw: 0, pitch: 0 });
|
||||
return { game: t.game, mob: test_mob(t.game, {}, 0.5, 100, 0.5) };
|
||||
}
|
||||
|
||||
function tick_while_moving(game: { tick(): void }, mob: { navigation: { moving: boolean } }, ticks: number) {
|
||||
for (let i = 0; i < ticks && mob.navigation.moving; i++) game.tick();
|
||||
}
|
||||
|
||||
Deno.test("a mob goes through a doorway to get to the next room", async () => {
|
||||
const { game, mob } = await rooms();
|
||||
assert(mob.navigation.move_to(6.5, 100, 0.5));
|
||||
tick_while_moving(game, mob, 400);
|
||||
assert(!mob.navigation.moving);
|
||||
assert(Math.hypot(mob.x - 6.5, mob.z - 0.5) < 1, `it got to ${mob.x} ${mob.z}`);
|
||||
});
|
||||
|
||||
Deno.test("a mob shut in has nowhere to go", async () => {
|
||||
const { game, mob } = await rooms();
|
||||
for (let x = -1; x <= 1; x++) {
|
||||
for (let z = -1; z <= 1; z++) {
|
||||
if (x !== 0 || z !== 0) { for (let y = 100; y < 103; y++) game.set_block(x, y, z, "bworld:stone"); }
|
||||
}
|
||||
}
|
||||
assertEquals(mob.navigation.move_to(6.5, 100, 0.5), false);
|
||||
assert(!mob.navigation.moving);
|
||||
});
|
||||
|
||||
Deno.test("a mob whose way gets walled up searches again, and gives up when there's no other way", async () => {
|
||||
const { game, mob } = await rooms();
|
||||
assert(mob.navigation.move_to(6.5, 100, 0.5));
|
||||
for (let i = 0; i < 5; i++) game.tick();
|
||||
game.set_block(3, 100, 4, "bworld:stone");
|
||||
game.set_block(3, 101, 4, "bworld:stone");
|
||||
tick_while_moving(game, mob, 400);
|
||||
assert(!mob.navigation.moving);
|
||||
assert(mob.x < 3);
|
||||
});
|
||||
|
||||
Deno.test("a monster finds its way around a wall to the player it's after", async () => {
|
||||
const { game } = await rooms();
|
||||
const alice = game.players()[0];
|
||||
alice.set_position(8.5, 100, 0.5);
|
||||
const monster = test_mob(game, { behavior: "monster" }, 0.5, 100, 0.5);
|
||||
for (let i = 0; i < 400 && Math.hypot(monster.x - 8.5, monster.z - 0.5) > 2; i++) game.tick();
|
||||
assert(Math.hypot(monster.x - 8.5, monster.z - 0.5) <= 2, `it got to ${monster.x} ${monster.z}`);
|
||||
});
|
||||
|
||||
Deno.test("a script's mob walks its way, and stops when told", async () => {
|
||||
const { game, mob } = await rooms();
|
||||
const ref = game.mods.mob(mob);
|
||||
assert(ref.move_to(6.5, 100, 0.5));
|
||||
assert(ref.moving);
|
||||
for (let i = 0; i < 20; i++) game.tick();
|
||||
ref.stop();
|
||||
assert(!ref.moving);
|
||||
const { x, z } = ref.position;
|
||||
for (let i = 0; i < 20; i++) game.tick();
|
||||
assert(Math.hypot(ref.position.x - x, ref.position.z - z) < 0.5);
|
||||
assertEquals(ref.blocked_by, undefined);
|
||||
});
|
||||
@@ -0,0 +1,177 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// the search mobs find their way with, see server/game/entity/pathfinding.ts, on small made up worlds
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import type { Shape } from "@/common/block_shapes.ts";
|
||||
import { find_path, type PathBody, type PathOptions, type Point } from "@/server/game/entity/pathfinding.ts";
|
||||
|
||||
// a world that's empty except for what's put in it
|
||||
function world() {
|
||||
const blocks = new Map<string, boolean | Shape>();
|
||||
const water = new Set<string>();
|
||||
const through = new Set<string>();
|
||||
const key = (x: number, y: number, z: number) => `${x},${y},${z}`;
|
||||
const w = {
|
||||
kept: (_chunk_x: number, _chunk_z: number) => true,
|
||||
set(x: number, y: number, z: number, shape: boolean | Shape = true) {
|
||||
blocks.set(key(x, y, z), shape);
|
||||
return w;
|
||||
},
|
||||
fill(x0: number, y0: number, z0: number, x1: number, y1: number, z1: number, shape: boolean | Shape = true) {
|
||||
for (let x = x0; x <= x1; x++) {
|
||||
for (let y = y0; y <= y1; y++) {
|
||||
for (let z = z0; z <= z1; z++) w.set(x, y, z, shape);
|
||||
}
|
||||
}
|
||||
return w;
|
||||
},
|
||||
// tagged for mobs to path through
|
||||
through(x: number, y: number, z: number) {
|
||||
through.add(key(x, y, z));
|
||||
return w;
|
||||
},
|
||||
water(x: number, y: number, z: number) {
|
||||
water.add(key(x, y, z));
|
||||
blocks.delete(key(x, y, z));
|
||||
return w;
|
||||
},
|
||||
collision_shape: (x: number, y: number, z: number) => blocks.get(key(x, y, z)) ?? false,
|
||||
is_fluid: (x: number, y: number, z: number) => water.has(key(x, y, z)),
|
||||
has_chunk: (chunk_x: number, chunk_z: number) => w.kept(chunk_x, chunk_z),
|
||||
passes_through: (x: number, y: number, z: number) => through.has(key(x, y, z)),
|
||||
};
|
||||
return w;
|
||||
}
|
||||
|
||||
// a floor from -8 to 8 at y 0, so feet stand at y 1
|
||||
const floor = () => world().fill(-8, 0, -8, 8, 0, 8);
|
||||
|
||||
const OPTIONS: PathOptions = { max_nodes: 2000, range: 32 };
|
||||
|
||||
// a mob that jumps 1 block and drops up to 3
|
||||
function walker(x: number, z: number, width = 0.6, height = 1.8): PathBody {
|
||||
return { x: x + 0.5, y: 1, z: z + 0.5, width, height, max_rise: 1, max_fall: 3 };
|
||||
}
|
||||
|
||||
// one that doesn't jump, only steps up, and doesn't drop at all
|
||||
const careful = (x: number, z: number): PathBody => ({ ...walker(x, z, 0.8, 1.9), max_rise: 0.6, max_fall: 0 });
|
||||
|
||||
const target = (x: number, y: number, z: number): Point => ({ x: x + 0.5, y, z: z + 0.5 });
|
||||
|
||||
const blocks_on = (points: Point[]) => points.map((p) => `${Math.floor(p.x)},${Math.floor(p.y)},${Math.floor(p.z)}`);
|
||||
|
||||
Deno.test("a mob on open ground goes straight to the target", () => {
|
||||
const path = find_path(floor(), walker(0, 0), target(5, 1, 0), OPTIONS)!;
|
||||
assert(path.reached);
|
||||
assertEquals(blocks_on(path.points), ["1,1,0", "2,1,0", "3,1,0", "4,1,0", "5,1,0"]);
|
||||
});
|
||||
|
||||
Deno.test("a mob goes through a doorway in a wall, and around a corner", () => {
|
||||
// a wall along x = 2 with a gap at z = 4, two blocks high so it can't be jumped
|
||||
const w = floor().fill(2, 1, -8, 2, 2, 8).fill(2, 1, 4, 2, 2, 4, false);
|
||||
const path = find_path(w, walker(0, 0), target(5, 1, 0), OPTIONS)!;
|
||||
assert(path.reached);
|
||||
assert(blocks_on(path.points).includes("2,1,4"));
|
||||
});
|
||||
|
||||
Deno.test("a mob that can't get there goes as close as it can, and nowhere when it's shut in", () => {
|
||||
const walled = floor().fill(2, 1, -8, 2, 2, 8);
|
||||
const partial = find_path(walled, walker(0, 0), target(5, 1, 0), OPTIONS)!;
|
||||
assert(!partial.reached);
|
||||
assertEquals(blocks_on(partial.points).at(-1), "1,1,0");
|
||||
|
||||
const shut_in = floor().fill(-1, 1, -1, 1, 2, 1).fill(0, 1, 0, 0, 2, 0, false);
|
||||
assertEquals(find_path(shut_in, walker(0, 0), target(5, 1, 0), OPTIONS), undefined);
|
||||
});
|
||||
|
||||
Deno.test("a mob jumps up one block but not two, and drops three but not four", () => {
|
||||
const step = floor().set(2, 1, 0).fill(3, 1, -8, 8, 1, 8);
|
||||
assert(find_path(step, walker(0, 0), target(5, 2, 0), OPTIONS)!.reached);
|
||||
const wall = floor().fill(2, 1, -8, 8, 2, 8);
|
||||
assert(!find_path(wall, walker(0, 0), target(5, 3, 0), OPTIONS)?.reached);
|
||||
|
||||
// standing on a ledge at y 3 (feet at 4), the ground beyond it 3 or 4 blocks down
|
||||
const ledge = (drop: number) => world().fill(-8, 3, -8, 1, 3, 8).fill(2, 3 - drop, -8, 8, 3 - drop, 8);
|
||||
const from_ledge = { ...walker(0, 0), y: 4 };
|
||||
assert(find_path(ledge(3), from_ledge, target(5, 1, 0), OPTIONS)!.reached);
|
||||
assert(!find_path(ledge(4), from_ledge, target(5, 0, 0), OPTIONS)?.reached);
|
||||
});
|
||||
|
||||
Deno.test("a mob steps onto a slab", () => {
|
||||
const slab: Shape = [[0, 0, 0, 1, 0.5, 1]];
|
||||
const w = floor().set(2, 1, 0, slab);
|
||||
const path = find_path(w, walker(0, 0), target(2, 1.5, 0), OPTIONS)!;
|
||||
assert(path.reached);
|
||||
assertEquals(path.points.at(-1)!.y, 1.5);
|
||||
});
|
||||
|
||||
Deno.test("a mob gets past a thin open door, but not a closed one or a doorway too low for it", () => {
|
||||
// a wall 3 high along z = 2 with a doorway 2 high at x = 0, the door 1/16 thick
|
||||
const doorway = (door: Shape) => floor().fill(-8, 1, 2, 8, 3, 2).set(0, 1, 2, door).set(0, 2, 2, door);
|
||||
const open: Shape = [[0, 0, 0, 0.0625, 1, 1]];
|
||||
const closed: Shape = [[0, 0, 0, 1, 1, 0.0625]];
|
||||
const coilhead = walker(0, 0, 0.8, 1.9);
|
||||
assert(find_path(doorway(open), coilhead, target(0, 1, 5), OPTIONS)!.reached);
|
||||
assert(!find_path(doorway(closed), coilhead, target(0, 1, 5), OPTIONS)?.reached);
|
||||
assert(!find_path(doorway([]), walker(0, 0, 0.8, 2.5), target(0, 1, 5), OPTIONS)?.reached);
|
||||
});
|
||||
|
||||
Deno.test("a mob that doesn't jump steps onto a slab but not a block", () => {
|
||||
const slab: Shape = [[0, 0, 0, 1, 0.5, 1]];
|
||||
assert(find_path(floor().set(2, 1, 0, slab), careful(0, 0), target(2, 1.5, 0), OPTIONS)!.reached);
|
||||
const step = floor().set(2, 1, 0).fill(3, 1, -8, 8, 1, 8);
|
||||
assert(!find_path(step, careful(0, 0), target(5, 2, 0), OPTIONS)?.reached);
|
||||
});
|
||||
|
||||
Deno.test("a mob that doesn't drop goes around a pit, and stops at one it can't get around", () => {
|
||||
// a pit 3 deep at 2, 0, right in the way
|
||||
const pit = floor().fill(2, -2, 0, 2, 0, 0, false).set(2, -3, 0);
|
||||
const around = find_path(pit, careful(0, 0), target(4, 1, 0), OPTIONS)!;
|
||||
assert(around.reached);
|
||||
assert(!blocks_on(around.points).some((block) => block.startsWith("2,") && block.endsWith(",0")));
|
||||
|
||||
const trench = floor().fill(2, -2, -8, 2, 0, 8, false).fill(2, -3, -8, 2, -3, 8);
|
||||
const stopped = find_path(trench, careful(0, 0), target(4, 1, 0), OPTIONS)!;
|
||||
assert(!stopped.reached);
|
||||
assertEquals(blocks_on(stopped.points).at(-1), "1,1,0");
|
||||
});
|
||||
|
||||
Deno.test("a mob's path goes through blocks tagged for it, like a closed door", () => {
|
||||
const closed: Shape = [[0, 0, 0, 1, 1, 0.0625]];
|
||||
const door = () => floor().fill(-8, 1, 2, 8, 3, 2).set(0, 1, 2, closed).set(0, 2, 2, closed);
|
||||
assert(!find_path(door(), careful(0, 0), target(0, 1, 5), OPTIONS)?.reached);
|
||||
const tagged = door().through(0, 1, 2).through(0, 2, 2);
|
||||
const path = find_path(tagged, careful(0, 0), target(0, 1, 5), OPTIONS)!;
|
||||
assert(path.reached);
|
||||
assert(blocks_on(path.points).includes("0,1,2"));
|
||||
});
|
||||
|
||||
Deno.test("a mob doesn't cut between two blocks that meet at a corner", () => {
|
||||
// the only way to 1, 1 is the gap between the corners of 1, 0 and 0, 1
|
||||
const w = world().fill(-1, 0, -1, 1, 0, 1).fill(1, 1, 0, 1, 2, 0).fill(0, 1, 1, 0, 2, 1);
|
||||
const path = find_path(w, walker(0, 0), target(1, 1, 1), OPTIONS);
|
||||
assert(!path?.reached);
|
||||
});
|
||||
|
||||
Deno.test("a mob swims across water in its way", () => {
|
||||
// a strip of water across the way
|
||||
const pool = floor().fill(2, 0, -8, 2, 0, 8, false);
|
||||
for (let z = -8; z <= 8; z++) pool.water(2, 0, z).water(2, 1, z);
|
||||
pool.set(2, -1, 0);
|
||||
assert(find_path(pool, walker(0, 0), target(4, 1, 0), OPTIONS)!.reached);
|
||||
});
|
||||
|
||||
Deno.test("chunks that aren't kept count as solid", () => {
|
||||
const w = world().fill(-8, 0, -8, 24, 0, 8);
|
||||
w.kept = (chunk_x) => chunk_x < 1;
|
||||
const path = find_path(w, walker(0, 0), target(20, 1, 0), OPTIONS)!;
|
||||
assert(!path.reached);
|
||||
assert(path.points.every((p) => p.x < 16));
|
||||
});
|
||||
|
||||
Deno.test("a mob only looks so far", () => {
|
||||
const path = find_path(floor(), walker(0, 0), target(8, 1, 0), { max_nodes: 2000, range: 4 })!;
|
||||
assert(!path.reached);
|
||||
assert(path.points.every((p) => Math.hypot(p.x - 0.5, p.z - 0.5) <= 4));
|
||||
});
|
||||
Reference in New Issue
Block a user