Blocks interacting on the world api
This commit is contained in:
@@ -5,7 +5,7 @@ redstone, contraptions, trains, equipment, decoration and schematics. It aims to
|
||||
possible, and to stay fast on both the server and the client when a world has thousands of moving parts.
|
||||
|
||||
Built so far: the importer and Create's imported blocks and items, R1, R2, R3 (`transformed` and `rotating`), R4, R5,
|
||||
R8, S0, S7, S12, stonecutting from S9, the start of P1's kinetics (shafts and cogwheels turned by a hand crank), and
|
||||
R8, S0, S4, S7, S12, stonecutting from S9, the start of P1's kinetics (shafts and cogwheels turned by a hand crank), and
|
||||
Create's pressing recipes. Facts about Create come from reading `ports/create1.21.1` and `ports/create1.19.3`, and facts
|
||||
about bworld from its source.
|
||||
|
||||
@@ -333,7 +333,7 @@ fluid stacks with amounts in millibuckets, a `"fluids"` capability, and fluid co
|
||||
torch, repeater, comparator, lamp. Create reads and makes signals in about 40 blocks, and bworld has no redstone at all
|
||||
today.
|
||||
|
||||
**S4. Machines acting on the world** (P3).
|
||||
**S4. Machines acting on the world** (P3, built).
|
||||
|
||||
- `liquid_flow(x, y, z)` (wraps `common/physics.ts`), for water wheels and fans.
|
||||
- Item entities in a box, which can be changed and removed, for the press, fans and belts picking items up.
|
||||
@@ -341,6 +341,17 @@ today.
|
||||
- Breaking a block over time with progress shown, and its drops, for drills and saws.
|
||||
- A fake player using an item on a block, for the deployer (`DeployerFakePlayer`).
|
||||
|
||||
As built, all in `ctx.world` (see the modding docs for each): `liquid_flow`, `entities_in(from, to, type?)` with
|
||||
`EntityRef.get_item`, `set_item`, `velocity` and `push`, `spawn_item` for an item lying still where it's put (the
|
||||
press's extra results), and `player.push`, which is sent to their client since it moves them. `set_break_progress` shows
|
||||
cracks to the players who have the chunk, sending only a change of stage, and `ctx.blocks.toughness` gives what breaking
|
||||
time is measured against. `break_block` takes `harvest` (drops what the right tool would, like
|
||||
`BlockHelper.destroyBlockAs` ignoring tool requirements) and `collect` (returns the drops without dropping them), and
|
||||
returns the drops. `use_item_on(item, x, y, z, face)` runs a player's whole right click (the block's `on_interact`, the
|
||||
item's `on_use`, placing) as one `[machine]` player that's never online, standing in front of the face, and returns what
|
||||
it holds after and anything it was given. The deployer's left click (punching and breaking) isn't there yet, and neither
|
||||
is a fan pushing players on their client every tick, which Create does on both sides.
|
||||
|
||||
**S5. Scripted entities** (P7). Mods can define an entity's behaviour in server scripts (tick, data, interaction) and
|
||||
how it's drawn in client scripts. Needed for the contraption entity, seats, potato cannon projectiles, trains and
|
||||
packages.
|
||||
|
||||
@@ -146,6 +146,9 @@ export class ClientLevel {
|
||||
// the client data of blocks that have some, see BlockRef.set_client_data, by chunk_key then position_key "x,y,z"
|
||||
block_data = new Map<number, Map<string, BlockData>>();
|
||||
visuals = new Visuals(this);
|
||||
// cracks on blocks machines are breaking, the stage to draw by position_key "x,y,z", see break_progress in
|
||||
// common/protocol.ts
|
||||
break_progress = new Map<string, { x: number; y: number; z: number; stage: number }>();
|
||||
|
||||
// server_blocks is the server's block id for each of its numeric ids
|
||||
constructor(server_blocks: string[], view_distance: number) {
|
||||
@@ -533,6 +536,17 @@ export class ClientLevel {
|
||||
this.#dirty.delete(chunk);
|
||||
this.block_data.delete(key);
|
||||
this.visuals.unload(cx, cz);
|
||||
for (const [position, { x, z }] of this.break_progress) {
|
||||
if (Math.floor(x / CHUNK_SIZE) === cx && Math.floor(z / CHUNK_SIZE) === cz) {
|
||||
this.break_progress.delete(position);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// see break_progress in common/protocol.ts
|
||||
set_break_progress(x: number, y: number, z: number, stage: number | undefined) {
|
||||
if (stage === undefined) this.break_progress.delete(`${x},${y},${z}`);
|
||||
else this.break_progress.set(`${x},${y},${z}`, { x, y, z, stage });
|
||||
}
|
||||
|
||||
// see block_data in common/protocol.ts
|
||||
|
||||
@@ -189,6 +189,16 @@ export class ClientPacketListener {
|
||||
case "block_data":
|
||||
level.set_block_data(message.x, message.y, message.z, message.data);
|
||||
break;
|
||||
case "break_progress":
|
||||
level.set_break_progress(message.x, message.y, message.z, message.stage);
|
||||
break;
|
||||
case "push": {
|
||||
const player = client.player;
|
||||
player.vx += message.motion[0];
|
||||
player.vy += message.motion[1];
|
||||
player.vz += message.motion[2];
|
||||
break;
|
||||
}
|
||||
case "chunk_batch_start":
|
||||
this.#chunk_batch.on_batch_start();
|
||||
break;
|
||||
|
||||
@@ -31,7 +31,7 @@ import {
|
||||
} from "$/client/renderer/mod.ts";
|
||||
import { type BlockRegistry, EverythingRegistry, type RenderLayer } from "$/common/everything_registry.ts";
|
||||
import { bake_block, type BakedQuad, FACE_INDEX, looks_by_state, type ModelJson } from "$/common/block_models.ts";
|
||||
import { ID_MASK } from "$/common/constants.ts";
|
||||
import { BREAK_STAGES, ID_MASK } from "$/common/constants.ts";
|
||||
import { type Shape, shape_at } from "$/common/block_shapes.ts";
|
||||
import type { BlockHitResult } from "$/client/level/client_level.ts";
|
||||
import { FACE_GROUPS, UNALIGNED_GROUP } from "$/client/workers/chunk_messages.ts";
|
||||
@@ -157,30 +157,29 @@ export class LevelRenderer {
|
||||
draw_visuals(level.visuals, level.image);
|
||||
}
|
||||
|
||||
// the cracks on the block being broken, drawn over its model's faces like minecraft's crumbling overlay, so a slab
|
||||
// or a plant cracks where it is and not on a whole cube around it
|
||||
// the cracks on the block being broken, and on the ones machines are breaking, drawn over their models' faces like
|
||||
// minecraft's crumbling overlay, so a slab or a plant cracks where it is and not on a whole cube around it
|
||||
render_destroy_progress(level: ClientLevel, game_mode: MultiPlayerGameMode) {
|
||||
for (const { x, y, z, stage } of level.break_progress.values()) this.#draw_cracks(level, x, y, z, stage);
|
||||
const block = game_mode.destroy_pos;
|
||||
if (!block) {
|
||||
return;
|
||||
}
|
||||
|
||||
const progress = Math.max(0, Math.min(1, game_mode.destroy_progress / game_mode.destroy_time));
|
||||
const stage = Math.round(progress * 8);
|
||||
if (Number.isNaN(stage)) {
|
||||
return;
|
||||
}
|
||||
const stage = Math.round(progress * BREAK_STAGES);
|
||||
if (!Number.isNaN(stage)) this.#draw_cracks(level, block.x, block.y, block.z, stage);
|
||||
}
|
||||
|
||||
const value = level.get_block_value(block.x, block.y, block.z);
|
||||
#draw_cracks(level: ClientLevel, x: number, y: number, z: number, stage: number) {
|
||||
const value = level.get_block_value(x, y, z);
|
||||
const info = EverythingRegistry.get_by_id<BlockRegistry>("blocks", value & ID_MASK);
|
||||
if (!info) {
|
||||
return;
|
||||
}
|
||||
|
||||
const tex = AssetManager.instance.get<Texture>("bworld:textures");
|
||||
const region = get_sprite_region(`engine:break_${stage}`);
|
||||
for (const quad of this.#destroy_quads(info, value)) {
|
||||
push_decal_quad(tex, quad, block.x, block.y, block.z, region);
|
||||
push_decal_quad(tex, quad, x, y, z, region);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -49,6 +49,9 @@ export const PLAYER_EYE_HEIGHT = 1.69;
|
||||
export const PLAYER_SWIM_HEIGHT = 0.8;
|
||||
export const PLAYER_SWIM_EYE_HEIGHT = 0.6;
|
||||
|
||||
// the stages of cracks on a block being broken, 0 to this, each drawn with engine:break_<stage>
|
||||
export const BREAK_STAGES = 8;
|
||||
|
||||
// where a block placed against each face of another block goes
|
||||
export const FACE_OFFSETS: Record<Faces, { x: number; y: number; z: number }> = {
|
||||
top: { x: 0, y: 1, z: 0 },
|
||||
|
||||
@@ -234,8 +234,12 @@ export interface ServerAfterEvents {
|
||||
export interface ServerWorld {
|
||||
get_block(x: number, y: number, z: number): Id | undefined; // undefined when the chunk isn't loaded
|
||||
set_block(x: number, y: number, z: number, id: Id): boolean; // runs on_break / on_create, synced to everyone
|
||||
// like breaking it by hand without a tool: on_break, then its drops. false when there was nothing to break
|
||||
break_block(x: number, y: number, z: number): boolean;
|
||||
// like breaking it by hand without a tool: on_break, then its drops, which it returns (copies). undefined when there
|
||||
// was nothing to break. see BreakOptions for machines breaking it
|
||||
break_block(x: number, y: number, z: number, options?: BreakOptions): ItemStack[] | undefined;
|
||||
// cracks on the block, 0 to 1 of the way to breaking, shown to everyone who sees it, like minecraft's
|
||||
// destroyBlockProgress: a drill getting through it. undefined takes them off, and so does the block changing
|
||||
set_break_progress(x: number, y: number, z: number, progress: number | undefined): void;
|
||||
get_state(x: number, y: number, z: number, name: string): number | undefined;
|
||||
set_state(x: number, y: number, z: number, name: string, value: number): boolean;
|
||||
// whether the block's side is a full square things can attach to, like minecraft's isFaceSturdy: its collision
|
||||
@@ -254,11 +258,27 @@ export interface ServerWorld {
|
||||
get_block_item(x: number, y: number, z: number): ItemStack | undefined;
|
||||
// pops an item out of the block at x y z, like a broken block's drops
|
||||
drop_item(x: number, y: number, z: number, item: ItemStack): void;
|
||||
// an item lying still at x y z, which players can pick up after half a second, like a new minecraft ItemEntity
|
||||
spawn_item(x: number, y: number, z: number, item: ItemStack): EntityRef;
|
||||
// the entities whose boxes touch the box between two corners, like minecraft's getEntitiesOfClass. only ones of type
|
||||
// when given, like "bworld:item" for items lying around. players aren't among them, they're in ctx.players
|
||||
entities_in(from: Position, to: Position, type?: Id): EntityRef[];
|
||||
// uses item on face of the block at x y z the way a player holding it would, like a deployer: the block's
|
||||
// on_interact, or the item's on_use, or placing it. a player that isn't anyone does it, standing in the block in
|
||||
// front of that face and looking at it, like neoforge's FakePlayer. returns what it's holding after (what's left of
|
||||
// item, or what it turned into) and anything else it was given, like a bucket filled from a stack of them
|
||||
use_item_on(item: ItemStack, x: number, y: number, z: number, face: Face): {
|
||||
item: ItemStack | undefined;
|
||||
given: ItemStack[];
|
||||
};
|
||||
// an entity from entities/ with its feet at x y z. throws for kinds that don't exist
|
||||
spawn_entity(id: Id, x: number, y: number, z: number): EntityRef;
|
||||
// the first block on the line from one point to another, like minecraft's Level.clip. it hits what entities bump
|
||||
// into, so it goes through plants and other blocks without collision. undefined when nothing is in the way
|
||||
raycast(from: Position, to: Position, options?: RaycastOptions): RaycastHit | undefined;
|
||||
// which way the liquid at x y z flows, a vector 1 long, or 0 0 0 where it's still or there's none, like minecraft's
|
||||
// FluidState.getFlow: toward lower cells of it beside it, and down where it falls. for what it pushes, like a wheel
|
||||
liquid_flow(x: number, y: number, z: number): Position;
|
||||
is_loaded(x: number, z: number): boolean;
|
||||
// the column's biome, like "bworld:plains", and that biome's season. in chunks that aren't loaded it's what
|
||||
// generation makes there, which takes a while the first time
|
||||
@@ -274,6 +294,14 @@ export interface ServerWorld {
|
||||
set_time(time: number): void;
|
||||
}
|
||||
|
||||
// how a machine breaks a block, see ServerWorld.break_block
|
||||
export interface BreakOptions {
|
||||
// it drops what it would for the right tool, though nothing holds one, like create's drills and saws
|
||||
harvest?: boolean;
|
||||
// the drops are only returned, not dropped, for a machine to put somewhere, like a saw onto a belt
|
||||
collect?: boolean;
|
||||
}
|
||||
|
||||
export interface RaycastOptions {
|
||||
// like minecraft's ClipContext.Fluid: "none" (the default) goes through liquids, "source_only" hits their sources
|
||||
// and goes through where they flow, "any" hits all of them. a liquid is hit at its surface
|
||||
@@ -301,8 +329,17 @@ export interface EntityRef {
|
||||
readonly biome: Id;
|
||||
readonly season: Season;
|
||||
readonly removed: boolean;
|
||||
// how fast it's moving, in blocks a second
|
||||
readonly velocity: Readonly<Position>;
|
||||
teleport(x: number, y: number, z: number): void;
|
||||
// adds to how fast it's moving, in blocks a second, like minecraft's Entity.push: a fan blowing it along
|
||||
push(x: number, y: number, z: number): void;
|
||||
remove(): void;
|
||||
// what an item lying around is, a copy. undefined for every other kind of entity
|
||||
get_item(): ItemStack | undefined;
|
||||
// changes what an item lying around is, like ItemEntity.setItem. undefined or a count of 0 removes it. throws for
|
||||
// every other kind of entity
|
||||
set_item(item: ItemStack | undefined): void;
|
||||
}
|
||||
|
||||
export interface Player {
|
||||
@@ -357,6 +394,9 @@ export interface Player {
|
||||
is_swimming(): boolean;
|
||||
// holding the sneak key, flying or not, like minecraft's isShiftKeyDown. their client says when
|
||||
is_sneaking(): boolean;
|
||||
// adds to how fast they're moving, in blocks a second, like minecraft's Entity.push: a fan blowing them along. their
|
||||
// client moves them, so it's sent there and added to theirs
|
||||
push(x: number, y: number, z: number): void;
|
||||
// keeps using the held item while they hold use, like minecraft's startUsingItem: its components' on_use_tick runs
|
||||
// every tick, then on_finish_using after ticks, or on_release_using if they let go first. -1 uses it until they let
|
||||
// go, like a bow. it slows them down like sneaking. for an on_use to call. switching away from it stops it
|
||||
@@ -435,6 +475,9 @@ export interface ItemApi {
|
||||
|
||||
export interface BlockApi {
|
||||
exists(id: Id): boolean;
|
||||
// how long breaking it by hand takes without a tool, in seconds, from the block's mining. Infinity for one that
|
||||
// can't be broken. for machines that break blocks, like a drill
|
||||
toughness(id: Id): number;
|
||||
// the components its json lists and their params, a copy, like ItemApi.components
|
||||
components(id: Id): Record<Id, unknown>;
|
||||
}
|
||||
|
||||
+6
-1
@@ -10,7 +10,7 @@ export const AIR_ID = "bworld:air";
|
||||
|
||||
// bump when a client and server of different versions can't play together.
|
||||
// the server rejects a different version before the client downloads anything
|
||||
export const PROTOCOL_VERSION = 22;
|
||||
export const PROTOCOL_VERSION = 23;
|
||||
|
||||
export interface PlayerInfo {
|
||||
id: string;
|
||||
@@ -228,6 +228,11 @@ export type ServerMessage =
|
||||
// the player is here now. with motion, they're moving that fast (blocks per second) too: the server is moving them,
|
||||
// like when knocked back, and the client keeps going that way until the next one. id counts up, see move
|
||||
| { type: "teleport"; id: number; x: number; y: number; z: number; motion?: [number, number, number] }
|
||||
// something pushed the player, like a fan: add this to how fast they're moving, in blocks per second
|
||||
| { type: "push"; motion: [number, number, number] }
|
||||
// cracks on a block a machine is breaking, from 0 to BREAK_STAGES, to the players who have its chunk. none without
|
||||
// a stage, and when the block changes
|
||||
| { type: "break_progress"; x: number; y: number; z: number; stage?: number }
|
||||
| { type: "container"; container: ContainerKey; items: (ItemData | null)[] }
|
||||
| { type: "cursor"; item: ItemData | null }
|
||||
// a menu opened, replacing any other. id counts 1 to 100 and around, type is the menu type whose screen draws it.
|
||||
|
||||
@@ -83,6 +83,27 @@ faster. The client times breaking itself, and the server checks the result.
|
||||
When it breaks, the block's components' `on_break` runs and it drops `drops` or what its `loot_table` gives, unless it
|
||||
has `requires_tool` and the player's tool is the wrong type or a tier below `mining.tier`.
|
||||
|
||||
### Breaking From Scripts
|
||||
|
||||
`ctx.world.break_block(x, y, z)` breaks a block like a player with nothing in their hand, and returns what it dropped,
|
||||
or `undefined` when there was nothing there. A machine that breaks blocks over time, like a drill, shows its progress
|
||||
and passes options for how it breaks them:
|
||||
|
||||
```ts
|
||||
const toughness = ctx.blocks.toughness(id); // seconds by hand, Infinity for one that can't be broken
|
||||
ctx.world.set_break_progress(x, y, z, progress); // cracks, 0 to 1, that every player who sees it sees
|
||||
// once it's through: drops what the right tool would, and hands them back instead of dropping them
|
||||
const drops = ctx.world.break_block(x, y, z, { harvest: true, collect: true });
|
||||
```
|
||||
|
||||
`set_break_progress` is like Minecraft's `destroyBlockProgress`. Only a change in the stage the cracks are drawn at is
|
||||
sent, so setting it every tick costs little. `undefined` takes the cracks off, and so does the block being broken or
|
||||
replaced. Players who load the chunk later don't see cracks set before, so keep setting it while it's being broken.
|
||||
|
||||
`harvest` drops what the right tool would, though nothing holds one, like Create's drills and saws: stone gives
|
||||
cobblestone. `collect` returns the drops without dropping them, for a machine that puts them somewhere, like onto a
|
||||
belt.
|
||||
|
||||
## Placement
|
||||
|
||||
Players place a block by right clicking a face of another block with its item. It goes next to the face they clicked, or
|
||||
@@ -151,6 +172,11 @@ So it spreads one block a step, falls off edges and spreads again where it lands
|
||||
its source is gone. It only flows into air, and stops at chunks that aren't loaded. Buckets only pick up sources. Flows
|
||||
still going when the server stops don't carry on after it starts again until something next to them changes.
|
||||
|
||||
`ctx.world.liquid_flow(x, y, z)` says which way the liquid in a block flows, like Minecraft's `FluidState.getFlow`: a
|
||||
vector 1 long toward the lower liquid beside it, and down where it falls against a wall, or `{ x: 0, y: 0, z: 0 }` where
|
||||
it's still or there's none. It's the same flow that pushes players and items along, for machines it turns, like a water
|
||||
wheel.
|
||||
|
||||
### Waterlogging
|
||||
|
||||
A block that isn't a liquid can hold one, like Minecraft's waterlogged fences. `waterloggable` names the liquid:
|
||||
|
||||
@@ -150,14 +150,41 @@ interface EntityRef {
|
||||
readonly biome: string; // where its feet are, see ../worldgen/biomes.md#seasons
|
||||
readonly season: Season; // that biome's
|
||||
readonly removed: boolean;
|
||||
readonly velocity: { x: number; y: number; z: number }; // in blocks a second
|
||||
teleport(x: number, y: number, z: number): void;
|
||||
push(x: number, y: number, z: number): void; // adds to its velocity
|
||||
remove(): void;
|
||||
get_item(): ItemStack | undefined; // for an item lying around, a copy
|
||||
set_item(item: ItemStack | undefined): void; // for an item lying around, undefined takes it away
|
||||
}
|
||||
```
|
||||
|
||||
Once an entity is removed, by a script or anything else, it stays removed, and teleporting it does nothing. Check
|
||||
`removed` before relying on one you kept from earlier.
|
||||
|
||||
`push` adds to how fast it's moving, like Minecraft's `Entity.push`: a fan blowing it along does it every tick. Players
|
||||
have a `push` too, see [Players](players.md#pushing).
|
||||
|
||||
## Finding Entities
|
||||
|
||||
`ctx.world.entities_in(from, to, type?)` finds the entities whose boxes overlap the box between two corners, like
|
||||
Minecraft's `getEntitiesOfClass`, only the ones of `type` when it's given. Players aren't among them, they're in
|
||||
`ctx.players`.
|
||||
|
||||
Items lying around are entities of type `bworld:item`. A machine that works on them, like a press, finds them, changes
|
||||
them with `set_item`, and adds what it made with `ctx.world.spawn_item`, which lays an item down still where it's put,
|
||||
unlike `drop_item`, which pops it out of a block:
|
||||
|
||||
```ts
|
||||
const [item] = ctx.world.entities_in({ x, y: y - 1, z }, { x: x + 1, y, z: z + 1 }, "bworld:item");
|
||||
const stack = item?.get_item();
|
||||
if (stack?.id === "bworld:iron_ingot") {
|
||||
item.set_item(stack.count > 1 ? { ...stack, count: stack.count - 1 } : undefined);
|
||||
const { x: ix, y: iy, z: iz } = item.position;
|
||||
ctx.world.spawn_item(ix, iy, iz, { id: "create:iron_sheet", count: 1 });
|
||||
}
|
||||
```
|
||||
|
||||
## Entity Models
|
||||
|
||||
Entity models are `models/<name>.geo.json`, as Blockbench exports them for Bedrock (the "Bedrock Entity" format), and
|
||||
|
||||
@@ -200,6 +200,11 @@ starts it with `player.start_using(ticks)`, and the item's components hear how i
|
||||
[Using Over Time](../items/index.md#using-over-time). `stop_using()` ends it without either ending, and `is_using()`
|
||||
says whether they're using one. While they are, they walk at a fifth of their speed and can't sprint.
|
||||
|
||||
## Pushing
|
||||
|
||||
`player.push(x, y, z)` adds to how fast they're moving, in blocks a second, like Minecraft's `Entity.push`: a fan
|
||||
blowing them along does it every tick. Their client moves them, so it's sent there and added to theirs.
|
||||
|
||||
## Death
|
||||
|
||||
When a player dies, everything they carried falls out where they died, and their tools lose durability (see
|
||||
|
||||
@@ -199,6 +199,19 @@ ctx.components.register_item("copper_tools:sling", {
|
||||
});
|
||||
```
|
||||
|
||||
## Machines Using Items
|
||||
|
||||
`ctx.world.use_item_on(item, x, y, z, face)` uses an item on the face of a block the way a player holding it would, like
|
||||
Create's deployer: the block's `on_interact`, or the item's `on_use` with the block as its target, or placing it. A
|
||||
player that isn't anyone, named `[machine]`, does it, standing in the block in front of that face and looking at it,
|
||||
like NeoForge's `FakePlayer`. It's never online, so nothing sent to it goes anywhere.
|
||||
|
||||
```ts
|
||||
const { item, given } = ctx.world.use_item_on({ id: "bworld:cobblestone", count: 5 }, x, y, z, "top");
|
||||
// item is what it holds after, { id: "bworld:cobblestone", count: 4 } once one is placed, undefined when used up.
|
||||
// given is anything else it was given, like a stick from a wand's on_use
|
||||
```
|
||||
|
||||
## Server Script Helpers
|
||||
|
||||
```ts
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import {
|
||||
BREAK_STAGES,
|
||||
CHUNK_HEIGHT,
|
||||
CHUNK_SIZE,
|
||||
FACE_OFFSETS,
|
||||
@@ -64,7 +65,7 @@ import { biome_ids, get_biome } from "$/common/worldgen/biomes.ts";
|
||||
import type { GameLoop } from "./game_loop.ts";
|
||||
import { update_crafting_result } from "./crafting.ts";
|
||||
import type { Menu } from "./menu.ts";
|
||||
import { SavedPlayer, ServerPlayer } from "./player.ts";
|
||||
import { MACHINE_CONN, SavedPlayer, ServerPlayer } from "./player.ts";
|
||||
import { encode_skin, MAX_SKIN_BYTES, skin_problem } from "./skins.ts";
|
||||
import { ServerWorld, SPAWN_AREA_CHUNKS, Tile } from "./world.ts";
|
||||
import type { WorldSave, WorldSource } from "./saves.ts";
|
||||
@@ -596,6 +597,7 @@ export class GameServer {
|
||||
|
||||
set_block(x: number, y: number, z: number, id: string, player?: ServerPlayer, state?: number) {
|
||||
const old_id = this.world.get_block_id(x, y, z);
|
||||
if (this.#break_stages.size > 0) this.set_break_progress(x, y, z, undefined);
|
||||
if (old_id !== AIR_ID) {
|
||||
const components = this.mods.components_of(old_id).filter(({ component }) => component.on_break);
|
||||
if (components.length > 0) {
|
||||
@@ -629,6 +631,61 @@ export class GameServer {
|
||||
}
|
||||
}
|
||||
|
||||
// the cracks machines are making on blocks, as the stage clients draw, by position. see set_break_progress
|
||||
#break_stages = new Map<string, number>();
|
||||
|
||||
// cracks on the block at x y z, 0 to 1 of the way to broken, for every player who has its chunk. undefined takes them
|
||||
// off. only a change of stage is sent, so a drill can set it every tick
|
||||
set_break_progress(x: number, y: number, z: number, progress: number | undefined) {
|
||||
const key = `${x} ${y} ${z}`;
|
||||
const stage = progress === undefined
|
||||
? undefined
|
||||
: Math.round(Math.max(0, Math.min(1, progress)) * BREAK_STAGES);
|
||||
if (this.#break_stages.get(key) === stage) return;
|
||||
if (stage === undefined) this.#break_stages.delete(key);
|
||||
else this.#break_stages.set(key, stage);
|
||||
const message: ServerMessage = { type: "break_progress", x, y, z, ...(stage !== undefined && { stage }) };
|
||||
for (const player of this.#players.values()) {
|
||||
if (player.chunks.has_block(x, z)) this.#send(player, message);
|
||||
}
|
||||
}
|
||||
|
||||
// a script pushing a player, see Player.push. their client moves them, so it's added there, unless the server is
|
||||
// moving them while they're knocked back
|
||||
push_player(player: ServerPlayer, x: number, y: number, z: number) {
|
||||
if (player.knockback_ticks === undefined) {
|
||||
this.#send(player, { type: "push", motion: [x, y, z] });
|
||||
return;
|
||||
}
|
||||
player.vx += x;
|
||||
player.vy += y;
|
||||
player.vz += z;
|
||||
}
|
||||
|
||||
// the player machines use items as, made the first time. it's never online or in the world
|
||||
#machine_player: ServerPlayer | undefined;
|
||||
|
||||
// uses stack on face of the block at x y z like a player holding it would, see ServerWorld.use_item_on: as a player
|
||||
// standing in the middle of the block in front of that face, looking at it. what it holds after, and anything else
|
||||
// it was given
|
||||
use_item_on(stack: ItemStack, x: number, y: number, z: number, face: Faces) {
|
||||
const player = this.#machine_player ??= new ServerPlayer(this.entities, MACHINE_CONN, "[machine]", 0);
|
||||
const { x: dx, y: dy, z: dz } = FACE_OFFSETS[face];
|
||||
player.set_position(x + 0.5 + dx, y + 0.5 + dy - player.eye_height, z + 0.5 + dz);
|
||||
// facing back the other way, see horizontal_facing
|
||||
player.yaw = dx || dz ? Math.atan2(dx, dz) : 0;
|
||||
player.pitch = -dy * Math.PI / 2;
|
||||
player.sneaking = false;
|
||||
player.using = undefined;
|
||||
player.selected_slot = 0;
|
||||
player.inventory.clear();
|
||||
player.inventory.set_item(0, stack);
|
||||
this.#use_block(player, x, y, z, face, [0.5 + dx / 2, 0.5 + dy / 2, 0.5 + dz / 2]);
|
||||
const items = Array.from({ length: player.inventory.size }, (_, slot) => player.inventory.get_item(slot));
|
||||
player.inventory.clear();
|
||||
return { held: items[0], given: items.slice(1).filter((item) => item !== undefined) };
|
||||
}
|
||||
|
||||
// what a loot table gives, ready to drop. a table that can't be rolled is logged and gives nothing, so a broken
|
||||
// table never stops a block breaking or a mob dying
|
||||
roll_loot(table: string, context: LootContext): ItemStack[] {
|
||||
@@ -640,17 +697,24 @@ export class GameServer {
|
||||
}
|
||||
}
|
||||
|
||||
// breaks a block the way breaking it by hand does: its components' on_break, then what it drops. without the
|
||||
// right tool of a high enough tier (or without a player) blocks that need one drop nothing
|
||||
destroy_block(x: number, y: number, z: number, player?: ServerPlayer) {
|
||||
// breaks a block the way breaking it by hand does: its components' on_break, then what it drops, which it returns.
|
||||
// without the right tool of a high enough tier (or without a player) blocks that need one drop nothing, unless a
|
||||
// machine breaks it as if it had one (harvest). collect returns the drops without dropping them
|
||||
destroy_block(
|
||||
x: number,
|
||||
y: number,
|
||||
z: number,
|
||||
player?: ServerPlayer,
|
||||
how: { harvest?: boolean; collect?: boolean } = {},
|
||||
): ItemStack[] | undefined {
|
||||
const info = this.world.get_block_info(x, y, z);
|
||||
if (!info) {
|
||||
return;
|
||||
return undefined;
|
||||
}
|
||||
const held = EverythingRegistry.get<ItemRegistry>("items", player?.held_item?.type_id ?? "");
|
||||
const tool = held?.tool;
|
||||
const right_tool = tool !== undefined && tool.type === info.tool_to_break && tool.tier >= (info.tool_tier ?? 0);
|
||||
const drops = !info.requires_tool || right_tool;
|
||||
const drops = how.harvest || !info.requires_tool || right_tool;
|
||||
const value = this.world.get_block_value(x, y, z);
|
||||
// rolled while it's still there, for its states
|
||||
const loot = drops && info.loot_table
|
||||
@@ -666,7 +730,8 @@ export class GameServer {
|
||||
// a waterlogged block leaves its liquid behind, a source
|
||||
const liquid = is_waterlogged(value, info) ? liquid_block(value, info) : undefined;
|
||||
this.set_block(x, y, z, liquid?.id ?? AIR_ID, player);
|
||||
for (const stack of loot) this.pop_item(x, y, z, stack);
|
||||
if (!how.collect) { for (const stack of loot) this.pop_item(x, y, z, stack); }
|
||||
return loot;
|
||||
}
|
||||
|
||||
get_or_create_tile(x: number, y: number, z: number): Tile {
|
||||
@@ -2219,6 +2284,7 @@ export class GameServer {
|
||||
}
|
||||
|
||||
#send(player: ServerPlayer, message: ServerMessage) {
|
||||
if (player.conn === MACHINE_CONN) return;
|
||||
this.#host.send(player.conn, JSON.stringify(message));
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,8 @@ import { Container as EngineContainer, ItemStack as EngineItemStack } from "$/co
|
||||
import { block_states, get_state_value, is_waterlogged, liquid_block, set_state_value } from "$/common/utils.ts";
|
||||
import { LootTables } from "./loot.ts";
|
||||
import { collision_shape_at, covers_face, raycast_blocks, type Shape } from "$/common/block_shapes.ts";
|
||||
import { AIR, ID_MASK } from "$/common/constants.ts";
|
||||
import { AIR, faces, ID_MASK } from "$/common/constants.ts";
|
||||
import { physics } from "$/common/physics.ts";
|
||||
import { clock } from "$/common/time.ts";
|
||||
import { BlockRules } from "$/common/block_rules.ts";
|
||||
import type { SharedContext } from "$/common/mod_api/shared.ts";
|
||||
@@ -62,6 +63,7 @@ import { damage_source, type Entity } from "./entity/entity.ts";
|
||||
import type { LivingEntity } from "./entity/living_entity.ts";
|
||||
import type { EffectJson } from "$/common/mod_data.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";
|
||||
import { effect_type, EffectInstance, type EffectType } from "./entity/effects.ts";
|
||||
import { biome_season } from "$/common/worldgen/biomes.ts";
|
||||
@@ -673,10 +675,18 @@ export class ModRuntime {
|
||||
game().set_block(x, y, z, id);
|
||||
return true;
|
||||
},
|
||||
break_block: (x, y, z) => {
|
||||
if (game().world.get_block_id(x, y, z) === AIR_ID) return false;
|
||||
game().destroy_block(x, y, z);
|
||||
return true;
|
||||
break_block: (x, y, z, options = {}) => {
|
||||
if (game().world.get_block_id(x, y, z) === AIR_ID) return undefined;
|
||||
const how = { harvest: options.harvest === true, collect: options.collect === true };
|
||||
return game().destroy_block(x, y, z, undefined, how)?.map(item_copy);
|
||||
},
|
||||
set_break_progress: (x, y, z, progress) => {
|
||||
if (progress !== undefined && !Number.isFinite(progress)) {
|
||||
throw new Error(
|
||||
`break progress is 0 to 1, or undefined to take the cracks off, not ${progress}`,
|
||||
);
|
||||
}
|
||||
game().set_break_progress(x, y, z, progress);
|
||||
},
|
||||
get_state: (x, y, z, name) => {
|
||||
const id = game().world.get_block_id(x, y, z);
|
||||
@@ -710,6 +720,28 @@ export class ModRuntime {
|
||||
get_block_item: (x, y, z) =>
|
||||
structuredClone(game().world.get_tile(x, y, z)?.client_data?.item as ItemStack),
|
||||
drop_item: (x, y, z, item) => void game().pop_item(x, y, z, new_stack(item)),
|
||||
spawn_item: (x, y, z, item) => {
|
||||
if (!(item.count > 0)) throw new Error("an item lying around needs a count of 1 or more");
|
||||
return entity_ref(game().spawn_item(x, y, z, new_stack(item), BLOCK_DROP_PICKUP_DELAY));
|
||||
},
|
||||
entities_in: (from, to, type) => {
|
||||
const [x0, x1] = [Math.min(from.x, to.x), Math.max(from.x, to.x)];
|
||||
const [y0, y1] = [Math.min(from.y, to.y), Math.max(from.y, to.y)];
|
||||
const [z0, z1] = [Math.min(from.z, to.z), Math.max(from.z, to.z)];
|
||||
return game().entities.all().filter((entity) => {
|
||||
const half = entity.width / 2;
|
||||
return (type === undefined || entity.type === type) &&
|
||||
entity.x - half < x1 && entity.x + half > x0 && entity.y < y1 &&
|
||||
entity.y + entity.height > y0 &&
|
||||
entity.z - half < z1 && entity.z + half > z0;
|
||||
}).map(entity_ref);
|
||||
},
|
||||
use_item_on: (item, x, y, z, face) => {
|
||||
if (!faces.includes(face)) throw new Error(`a face is one of ${faces.join(", ")}, not ${face}`);
|
||||
if (!(item.count > 0)) throw new Error("using an item needs a count of 1 or more");
|
||||
const { held, given } = game().use_item_on(new_stack(item), x, y, z, face);
|
||||
return { item: held && item_copy(held), given: given.map(item_copy) };
|
||||
},
|
||||
spawn_entity: (id, x, y, z) => {
|
||||
const entity = EverythingRegistry.get("entities", id)
|
||||
? create_entity(game().entities, id)
|
||||
@@ -754,6 +786,17 @@ export class ModRuntime {
|
||||
},
|
||||
};
|
||||
},
|
||||
liquid_flow: (x, y, z) => {
|
||||
const [fx, fy, fz] = physics.liquid_flow(
|
||||
Math.floor(x),
|
||||
Math.floor(y),
|
||||
Math.floor(z),
|
||||
(x, y, z) => game().entities.liquid_at(x, y, z),
|
||||
(x, y, z) => game().world.collision_shape(x, y, z),
|
||||
);
|
||||
// without any -0
|
||||
return { x: fx + 0, y: fy + 0, z: fz + 0 };
|
||||
},
|
||||
is_loaded: () => true,
|
||||
biome_at: (x, z) => game().world.biome_at(Math.floor(x), Math.floor(z)),
|
||||
season_at: (x, z) =>
|
||||
@@ -815,6 +858,11 @@ export class ModRuntime {
|
||||
},
|
||||
blocks: {
|
||||
exists: (id) => EverythingRegistry.get("blocks", id) !== undefined,
|
||||
toughness: (id) => {
|
||||
const block = EverythingRegistry.get<BlockRegistry>("blocks", id);
|
||||
if (!block) throw new Error(`unknown block ${id}`);
|
||||
return block.toughness ?? Infinity;
|
||||
},
|
||||
components: (id) => {
|
||||
const block = EverythingRegistry.get<BlockRegistry>("blocks", id);
|
||||
if (!block) throw new Error(`unknown block ${id}`);
|
||||
@@ -1129,6 +1177,11 @@ export function item_api(stack: EngineItemStack): ItemStack {
|
||||
};
|
||||
}
|
||||
|
||||
// an engine stack as a script's item, a copy
|
||||
export function item_copy(stack: EngineItemStack): ItemStack {
|
||||
return structuredClone(stack.to_data());
|
||||
}
|
||||
|
||||
export function new_stack(item: ItemStack): EngineItemStack {
|
||||
if (!EverythingRegistry.get("items", item.id)) throw new Error(`unknown item ${item.id}`);
|
||||
const stack = new EngineItemStack(item.id, item.count);
|
||||
@@ -1347,6 +1400,10 @@ function player_api(game: GameServer, player: ServerPlayer): Player {
|
||||
remove_effect: (id) => player.remove_effect(known_effect(id).id),
|
||||
is_swimming: () => player.swimming,
|
||||
is_sneaking: () => player.sneaking,
|
||||
push(x, y, z) {
|
||||
if (![x, y, z].every(Number.isFinite)) throw new Error("a push is three numbers, in blocks a second");
|
||||
game.push_player(player, x, y, z);
|
||||
},
|
||||
start_using(ticks) {
|
||||
if (!Number.isInteger(ticks) || (ticks < 1 && ticks !== -1)) {
|
||||
throw new Error("start_using takes a whole number of ticks, or -1 until they let go");
|
||||
@@ -1408,11 +1465,27 @@ export function entity_ref(entity: Entity): EntityRef {
|
||||
get removed() {
|
||||
return entity.removed;
|
||||
},
|
||||
get velocity() {
|
||||
return { x: entity.vx, y: entity.vy, z: entity.vz };
|
||||
},
|
||||
teleport(x, y, z) {
|
||||
if (!entity.removed) entity.set_position(x, y, z);
|
||||
},
|
||||
push(x, y, z) {
|
||||
if (![x, y, z].every(Number.isFinite)) throw new Error("a push is three numbers, in blocks a second");
|
||||
entity.vx += x;
|
||||
entity.vy += y;
|
||||
entity.vz += z;
|
||||
},
|
||||
remove() {
|
||||
entity.remove();
|
||||
},
|
||||
get_item: () => entity instanceof ItemEntity ? item_copy(entity.item) : undefined,
|
||||
set_item(item) {
|
||||
if (!(entity instanceof ItemEntity)) throw new Error(`${entity.type} isn't an item lying around`);
|
||||
if (entity.removed) return;
|
||||
if (!item || item.count <= 0) entity.remove();
|
||||
else entity.item = new_stack(item);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -40,6 +40,9 @@ export interface SavedPlayer {
|
||||
flying?: boolean;
|
||||
}
|
||||
|
||||
// the connection of the player machines use items as, see GameServer.use_item_on. nothing is ever sent to it
|
||||
export const MACHINE_CONN = -1;
|
||||
|
||||
// the most ticks the server moves a knocked back player, in case they never land, like in water
|
||||
const MAX_KNOCKBACK_TICKS = 20;
|
||||
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// what machines do to the world through server scripts: read which way water flows, find items lying around and
|
||||
// change them, push things, break blocks over time, and use items on blocks like a player would
|
||||
import { assert, assertEquals, assertThrows } from "@std/assert";
|
||||
import type { ServerContext } from "bworld/server";
|
||||
import { AIR_ID } from "$/common/protocol.ts";
|
||||
import { copy_dir, stone_floor, test_game } from "./helpers.ts";
|
||||
|
||||
// hands the test its context, and has a block that says who right clicked it and an item that gives a stick when used
|
||||
const SERVER_SCRIPT = `
|
||||
import type { ServerContext } from "bworld/server";
|
||||
export function setup(ctx: ServerContext) {
|
||||
(globalThis as any).machines_ctx = ctx;
|
||||
ctx.components.register_block("testmod:button", {
|
||||
on_interact(block, _params, player) {
|
||||
block.data = { pressed_by: player.name };
|
||||
return true;
|
||||
},
|
||||
});
|
||||
ctx.components.register_item("testmod:wand", {
|
||||
on_use(_item, _params, player, target) {
|
||||
if (target) player.give_item("bworld:stick", 1);
|
||||
},
|
||||
});
|
||||
}
|
||||
`;
|
||||
|
||||
async function setup() {
|
||||
const dir = Deno.makeTempDirSync({ prefix: "bworld_machines_" });
|
||||
copy_dir("mods/bworld", `${dir}/bworld`);
|
||||
const mod = `${dir}/testmod`;
|
||||
for (const folder of ["blocks", "items", "scripts"]) Deno.mkdirSync(`${mod}/${folder}`, { recursive: true });
|
||||
const write = (path: string, json: unknown) => Deno.writeTextFileSync(`${mod}/${path}`, JSON.stringify(json));
|
||||
write("manifest.json", {
|
||||
format_version: 1,
|
||||
id: "testmod",
|
||||
name: "Test",
|
||||
version: "1.0.0",
|
||||
dependencies: [{ id: "bworld", version: "*" }],
|
||||
scripts: { server: "scripts/server.ts" },
|
||||
});
|
||||
write("blocks/button.json", {
|
||||
format_version: 1,
|
||||
block: {
|
||||
id: "testmod:button",
|
||||
textures: "bworld:stone",
|
||||
mining: { toughness: 1 },
|
||||
interactive: true,
|
||||
components: { "testmod:button": {} },
|
||||
},
|
||||
});
|
||||
write("items/wand.json", {
|
||||
format_version: 1,
|
||||
item: { id: "testmod:wand", texture: "bworld:stick", components: { "testmod:wand": {} } },
|
||||
});
|
||||
Deno.writeTextFileSync(`${mod}/scripts/server.ts`, SERVER_SCRIPT);
|
||||
const t = await test_game(dir);
|
||||
Deno.removeSync(dir, { recursive: true });
|
||||
t.join(1, "alice");
|
||||
stone_floor(t.game, 6);
|
||||
for (let x = -6; x <= 6; x++) {
|
||||
for (let z = -6; z <= 6; z++) for (let y = 100; y < 104; y++) t.game.set_block(x, y, z, AIR_ID);
|
||||
}
|
||||
t.send(1, { type: "move", x: 0.5, y: 100, z: 5.5, yaw: 0, pitch: 0 });
|
||||
for (let i = 0; i < 5; i++) t.game.tick();
|
||||
t.take(1);
|
||||
const ctx = (globalThis as unknown as { machines_ctx: ServerContext }).machines_ctx;
|
||||
return { ...t, ctx };
|
||||
}
|
||||
|
||||
Deno.test("which way water flows, from where it's higher to where it's lower", async () => {
|
||||
const { game, ctx } = await setup();
|
||||
game.set_block(0, 100, 0, "bworld:water");
|
||||
for (let i = 0; i < 40; i++) game.tick();
|
||||
assertEquals(ctx.world.liquid_flow(2, 100, 0), { x: 1, y: 0, z: 0 });
|
||||
assertEquals(ctx.world.liquid_flow(0, 100, -2), { x: 0, y: 0, z: -1 });
|
||||
// a source with water all around is still, and so is air
|
||||
assertEquals(ctx.world.liquid_flow(0, 100, 0), { x: 0, y: 0, z: 0 });
|
||||
assertEquals(ctx.world.liquid_flow(0, 102, 0), { x: 0, y: 0, z: 0 });
|
||||
});
|
||||
|
||||
Deno.test("items lying in a box are found, changed and taken away", async () => {
|
||||
const { game, ctx } = await setup();
|
||||
const iron = ctx.world.spawn_item(0.5, 100, 0.5, { id: "bworld:iron_ingot", count: 3 });
|
||||
ctx.world.spawn_item(3.5, 100, 0.5, { id: "bworld:gold_ingot", count: 1 });
|
||||
// it lies where it was put, still
|
||||
game.tick();
|
||||
assertEquals(iron.position, { x: 0.5, y: 100, z: 0.5 });
|
||||
|
||||
const found = ctx.world.entities_in({ x: 0, y: 99.5, z: 0 }, { x: 1, y: 101, z: 1 }, "bworld:item");
|
||||
assertEquals(found.map((entity) => entity.get_item()), [{ id: "bworld:iron_ingot", count: 3 }]);
|
||||
assertEquals(ctx.world.entities_in({ x: 0, y: 99.5, z: 0 }, { x: 1, y: 101, z: 1 }, "bworld:chicken"), []);
|
||||
|
||||
// pressed into something else, one at a time
|
||||
found[0].set_item({ id: "bworld:iron_ingot", count: 2 });
|
||||
assertEquals(iron.get_item(), { id: "bworld:iron_ingot", count: 2 });
|
||||
const copy = iron.get_item()!;
|
||||
copy.count = 64;
|
||||
assertEquals(iron.get_item()?.count, 2);
|
||||
found[0].set_item(undefined);
|
||||
assert(iron.removed);
|
||||
assertEquals(game.item_entities().map((entity) => entity.item.type_id), ["bworld:gold_ingot"]);
|
||||
});
|
||||
|
||||
Deno.test("entities are pushed, players by their client", async () => {
|
||||
const { game, ctx, take } = await setup();
|
||||
const item = ctx.world.spawn_item(0.5, 101, 0.5, { id: "bworld:stick", count: 1 });
|
||||
item.push(4, 0, 0);
|
||||
assertEquals(item.velocity, { x: 4, y: 0, z: 0 });
|
||||
game.tick();
|
||||
assert(item.position.x > 0.5);
|
||||
|
||||
const chicken = ctx.world.spawn_entity("bworld:chicken", 2.5, 100, 2.5);
|
||||
assertThrows(() => chicken.set_item({ id: "bworld:stick", count: 1 }));
|
||||
assertEquals(chicken.get_item(), undefined);
|
||||
|
||||
ctx.players.by_name("alice")!.push(0, 5, 0);
|
||||
assertEquals(take(1).filter((m) => m.type === "push"), [{ type: "push", motion: [0, 5, 0] }]);
|
||||
});
|
||||
|
||||
Deno.test("a block breaking over time shows its cracks to players, and machines get its drops", async () => {
|
||||
const { game, ctx, take } = await setup();
|
||||
const cracks = () => take(1).filter((m) => m.type === "break_progress");
|
||||
ctx.world.set_break_progress(0, 99, 0, 0.5);
|
||||
assertEquals(cracks(), [{ type: "break_progress", x: 0, y: 99, z: 0, stage: 4 }]);
|
||||
// the same stage isn't sent again, and breaking the block takes them off
|
||||
ctx.world.set_break_progress(0, 99, 0, 0.52);
|
||||
assertEquals(cracks(), []);
|
||||
|
||||
// stone needs a pickaxe by hand, but a drill gets cobblestone
|
||||
assert(ctx.blocks.toughness("bworld:stone") > 0);
|
||||
assertEquals(ctx.blocks.toughness("bworld:light"), Infinity);
|
||||
assertEquals(ctx.world.break_block(0, 99, 0), []);
|
||||
assertEquals(cracks(), [{ type: "break_progress", x: 0, y: 99, z: 0 }]);
|
||||
assertEquals(ctx.world.break_block(1, 99, 0, { harvest: true }), [{ id: "bworld:cobblestone", count: 1 }]);
|
||||
assertEquals(game.item_entities().length, 1);
|
||||
// collected, it's only returned
|
||||
assertEquals(ctx.world.break_block(2, 99, 0, { harvest: true, collect: true }), [
|
||||
{ id: "bworld:cobblestone", count: 1 },
|
||||
]);
|
||||
assertEquals(game.item_entities().length, 1);
|
||||
assertEquals(ctx.world.break_block(2, 99, 0), undefined);
|
||||
});
|
||||
|
||||
Deno.test("a machine uses items on blocks like a player holding them would", async () => {
|
||||
const { game, ctx } = await setup();
|
||||
// placing: the block goes in front of the face, and one fewer is left
|
||||
const placed = ctx.world.use_item_on({ id: "bworld:cobblestone", count: 5 }, 0, 99, 0, "top");
|
||||
assertEquals(game.world.get_block_id(0, 100, 0), "bworld:cobblestone");
|
||||
assertEquals(placed, { item: { id: "bworld:cobblestone", count: 4 }, given: [] });
|
||||
assertEquals(ctx.world.use_item_on({ id: "bworld:cobblestone", count: 1 }, 0, 100, 0, "east").item, undefined);
|
||||
assertEquals(game.world.get_block_id(1, 100, 0), "bworld:cobblestone");
|
||||
|
||||
// right clicking a block, as a player that isn't anyone
|
||||
game.set_block(3, 100, 0, "testmod:button");
|
||||
ctx.world.use_item_on({ id: "bworld:stick", count: 1 }, 3, 100, 0, "west");
|
||||
assertEquals(ctx.world.get_block_data<{ pressed_by: string }>(3, 100, 0)?.pressed_by, "[machine]");
|
||||
|
||||
// an item used on a block, which gives it something
|
||||
const used = ctx.world.use_item_on({ id: "testmod:wand", count: 1 }, -3, 99, 0, "top");
|
||||
assertEquals(used, { item: { id: "testmod:wand", count: 1 }, given: [{ id: "bworld:stick", count: 1 }] });
|
||||
// none of it is anyone's: no player got anything, and nothing was dropped
|
||||
assertEquals(game.players()[0].inventory.get_item(0), undefined);
|
||||
assertEquals(game.item_entities(), []);
|
||||
});
|
||||
Reference in New Issue
Block a user