Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c7a2392591 | ||
|
|
b43e8fe8b8 |
@@ -5,9 +5,9 @@ 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
|
||||
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.
|
||||
R8, S0, S4, S7, S12, stonecutting from S9, the start of P1's kinetics (shafts and cogwheels turned by a hand crank),
|
||||
Create's pressing recipes, and the mechanical press pressing items on the ground. Facts about Create come from reading
|
||||
`ports/create1.21.1` and `ports/create1.19.3`, and facts about bworld from its source.
|
||||
|
||||
## Sources
|
||||
|
||||
@@ -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.
|
||||
@@ -536,6 +547,15 @@ Check: new worlds have zinc and Create's stones, and casings join up.
|
||||
Check: ores go through crushing, washing and smelting into more ingots than a furnace alone gives, and brass is mixed in
|
||||
a heated basin.
|
||||
|
||||
As built so far: the mechanical press, pressing items lying on the ground under it (`PressingBehaviour`'s world mode, in
|
||||
`scripts/processing/press.ts` and the server script). While it turns it looks for an item with a pressing recipe every
|
||||
10 ticks, then runs its 240 step cycle at Create's speed for its rpm and presses at the bottom: a lone item turns into
|
||||
its result, and from a stack one is pressed and its results land beside it, like `bulkPressing` off. It stops ticking
|
||||
while it's still, and a kinetic block that starts turning ticks again. Clients get the step the cycle was at and its
|
||||
rate as `press` client data whenever the rate changes, and the visual moves the head from those, so nothing is sent
|
||||
while it runs at a steady speed. Pressing on belts, depots and basins, its stress impact, sound and particles come with
|
||||
those.
|
||||
|
||||
### P4: Logistics
|
||||
|
||||
- R3's `scrolling` type.
|
||||
|
||||
@@ -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,19 @@ 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>;
|
||||
// standing or lying on something, like an item that's landed, like minecraft's onGround
|
||||
readonly on_ground: boolean;
|
||||
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 +396,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 +477,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,42 @@ 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
|
||||
readonly on_ground: boolean; // standing or lying on something
|
||||
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
|
||||
|
||||
@@ -16,6 +16,10 @@
|
||||
"render_layer": "cutout",
|
||||
"mining": { "toughness": 1 },
|
||||
"drops": "create:mechanical_press",
|
||||
"item_model": "create:item_mechanical_press"
|
||||
"item_model": "create:item_mechanical_press",
|
||||
"components": {
|
||||
"create:kinetic": { "facing": "facing", "horizontal": true },
|
||||
"create:mechanical_press": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,12 @@
|
||||
"create:kinetic": { "axis": "axis", "cog": "large" }
|
||||
}
|
||||
},
|
||||
"create:mechanical_press": {
|
||||
"components": {
|
||||
"create:kinetic": { "facing": "facing", "horizontal": true },
|
||||
"create:mechanical_press": {}
|
||||
}
|
||||
},
|
||||
"create:hand_crank": {
|
||||
"interactive": true,
|
||||
"components": {
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
// as rotating instances, so a block turning steadily costs nothing per frame
|
||||
import type { ClientContext, Instances, ModelRef, Visual, VisualBlock } from "bworld/client";
|
||||
import type { Face } from "bworld/shared";
|
||||
import { type Axis, kinetic_shape, type KineticParams, type KineticShape } from "./kinetics/connections.ts";
|
||||
import { type Axis, FACINGS, kinetic_shape, type KineticParams, type KineticShape } from "./kinetics/connections.ts";
|
||||
import { head_offset, type PressShown } from "./processing/press.ts";
|
||||
|
||||
// the crank's handle model has its hub on its south side and its grip reaching north, so it's turned to put north
|
||||
// where the crank faces
|
||||
@@ -56,6 +57,37 @@ export function setup(ctx: ClientContext) {
|
||||
};
|
||||
}, { replaces_model: true });
|
||||
|
||||
// its casing is its block's model. the shaft through it turns like any other, and the head comes down and goes back
|
||||
// up through the cycle from where the server last said it was, like PressVisual
|
||||
ctx.render.register_visual("create:mechanical_press", (block, instances) => {
|
||||
const shape = shape_of(block);
|
||||
const turn = turning(block, instances, shape, { model: "create:block_shaft", ...AXIS_TURNS[shape.axis] });
|
||||
const head = instances.transformed({
|
||||
model: "create:block_mechanical_press_head",
|
||||
y: FACINGS.indexOf(shape.facing!) * 90,
|
||||
});
|
||||
let shown = block.get_client_data<PressShown>("press");
|
||||
// when this client heard of it, in the time on_frame gets
|
||||
let since: number | undefined;
|
||||
let offset: number | undefined;
|
||||
return {
|
||||
update() {
|
||||
turn();
|
||||
const press = block.get_client_data<PressShown>("press");
|
||||
if (JSON.stringify(press) === JSON.stringify(shown)) return;
|
||||
shown = press;
|
||||
since = undefined;
|
||||
},
|
||||
on_frame(time) {
|
||||
since ??= time;
|
||||
const now = shown ? head_offset(shown.steps + (time - since) * shown.rate) : 0;
|
||||
if (now === offset) return;
|
||||
offset = now;
|
||||
head.set_transform([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, -offset, 0, 1]);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// the half shaft turns with the speed like any kinetic block, and the handle catches up with it and slows down
|
||||
// with it, like HandCrankVisual's independent angle
|
||||
ctx.render.register_visual("create:hand_crank", (block, instances) => {
|
||||
|
||||
@@ -18,6 +18,8 @@ export interface KineticParams {
|
||||
// which ends of its axis have an axle that turns the block there: both, or for one with a facing only the end it
|
||||
// faces ("front") or the other ("back"). both when not given
|
||||
shaft?: "both" | "front" | "back";
|
||||
// its facing is only north, east, south or west, a 2 bit state, like HorizontalKineticBlock's
|
||||
horizontal?: boolean;
|
||||
// a cogwheel: a small one turns the small ones beside it on the same axis, a large one turns small ones on the same
|
||||
// axis at its corners, and large ones on other axes across its edges, like create's ICogWheel
|
||||
cog?: "small" | "large";
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// the mechanical press's cycle, like create's PressingBehaviour: the head comes down, presses at the bottom halfway
|
||||
// through, and goes back up. it counts CYCLE steps, more of them a tick the faster the press turns. no ctx, the server
|
||||
// runs the cycle and visuals draw it from the same numbers
|
||||
|
||||
export const CYCLE = 240;
|
||||
// where it presses, at the bottom
|
||||
export const PRESS_AT = CYCLE / 2;
|
||||
// how often a still press looks for something to press, in ticks
|
||||
export const SCAN_TICKS = 10;
|
||||
|
||||
// a pressing press's "press" client data, what its visual moves the head by: the step of the cycle it was at when this
|
||||
// was set, and how many steps a tick it's going
|
||||
export interface PressShown {
|
||||
steps: number;
|
||||
rate: number;
|
||||
}
|
||||
|
||||
// steps of the cycle a tick at a speed in rpm, like getRunningTickSpeed: 1 almost still, up to 60 at 512 rpm
|
||||
export function cycle_rate(speed: number): number {
|
||||
if (speed === 0) return 0;
|
||||
return Math.floor(1 + 59 * Math.min(1, Math.abs(speed) / 512));
|
||||
}
|
||||
|
||||
// how far down the head is that far through the cycle, 0 up to 1 at the bottom, like getRenderedHeadOffset: it
|
||||
// speeds up on the way down, stays down a moment after pressing, and goes up at a steady speed
|
||||
export function head_offset(steps: number): number {
|
||||
const clamp = (value: number) => Math.max(0, Math.min(1, value));
|
||||
if (steps < CYCLE * 2 / 3) return clamp((steps / CYCLE * 2) ** 3);
|
||||
return clamp((CYCLE - steps) / CYCLE * 3);
|
||||
}
|
||||
@@ -92,3 +92,17 @@ export function parse_processing(
|
||||
if (json?.heat_requirement !== undefined) problems.push(`${type.id} can't have a heat_requirement`);
|
||||
return problems.length > 0 ? { problems } : { ingredients, results };
|
||||
}
|
||||
|
||||
// the first recipe that takes the item, like a machine's getRecipe
|
||||
export function processing_for(recipes: ProcessingRecipe[], item: Id): ProcessingRecipe | undefined {
|
||||
return recipes.find((recipe) => recipe.ingredients[0]?.includes(item));
|
||||
}
|
||||
|
||||
// what one go of a recipe makes: each result, with each of its count kept by its chance, like rollResults
|
||||
export function roll_results(recipe: ProcessingRecipe, random = Math.random): { id: Id; count: number }[] {
|
||||
return recipe.results.flatMap(({ id, count, chance }) => {
|
||||
let kept = count;
|
||||
if (chance < 1) { for (let i = 0; i < count; i++) if (random() > chance) kept--; }
|
||||
return kept > 0 ? [{ id, count: kept }] : [];
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// create's blocks that do something: so far what turns (create:kinetic) and the hand crank that turns it. and its
|
||||
// recipe types' checks
|
||||
import type { BlockRef, Id, ServerContext } from "bworld/server";
|
||||
// create's blocks that do something: so far what turns (create:kinetic), the hand crank that turns it, and the
|
||||
// mechanical press
|
||||
import type { BlockRef, EntityRef, Id, ServerContext } from "bworld/server";
|
||||
import { along, kinetic_shape, type KineticParams } from "./kinetics/connections.ts";
|
||||
import { handle_added, handle_removed, type KineticWorld, type Pos, update_generated } from "./kinetics/spreading.ts";
|
||||
import { PRESSING, processing_recipes } from "./recipes/processing.ts";
|
||||
import {
|
||||
PRESSING,
|
||||
processing_for,
|
||||
processing_recipes,
|
||||
type ProcessingRecipe,
|
||||
roll_results,
|
||||
} from "./recipes/processing.ts";
|
||||
import { CYCLE, cycle_rate, PRESS_AT, type PressShown, SCAN_TICKS } from "./processing/press.ts";
|
||||
|
||||
interface Config {
|
||||
max_speed: number;
|
||||
@@ -34,12 +41,19 @@ interface CrankData extends KineticData {
|
||||
backwards?: boolean;
|
||||
}
|
||||
|
||||
interface PressData extends KineticData {
|
||||
// steps through the cycle while it's pressing, see processing/press.ts
|
||||
pressing?: number;
|
||||
// ticks until it looks for something to press again
|
||||
scan?: number;
|
||||
}
|
||||
|
||||
export function setup(ctx: ServerContext) {
|
||||
const config: Config = ctx.config;
|
||||
const world = kinetic_world(ctx, config);
|
||||
|
||||
// checked now, so a broken recipe stops the server rather than a press later
|
||||
processing_recipes(ctx.recipes.list(PRESSING.id), PRESSING, {
|
||||
const pressing = processing_recipes(ctx.recipes.list(PRESSING.id), PRESSING, {
|
||||
expand: (choice) => ctx.tags.expand(choice),
|
||||
item_exists: (id) => ctx.items.exists(id),
|
||||
});
|
||||
@@ -75,6 +89,78 @@ export function setup(ctx: ServerContext) {
|
||||
update_generated(world, [block.x, block.y, block.z]);
|
||||
},
|
||||
});
|
||||
|
||||
register_press(ctx, pressing);
|
||||
}
|
||||
|
||||
// presses items lying on the ground under it while it turns, like create's MechanicalPressBlockEntity pressing in the
|
||||
// world: it looks for one it has a recipe for every SCAN_TICKS, then comes down on it, faster the faster it turns. a
|
||||
// lone item turns into what it's pressed into, and from a stack one at a time is, landing beside the rest. it only
|
||||
// ticks while it turns
|
||||
function register_press(ctx: ServerContext, recipes: ProcessingRecipe[]) {
|
||||
// the items lying in the block under it, a bit in from its sides when looking for one, like create's
|
||||
const items_under = (block: BlockRef, inset: number) =>
|
||||
ctx.world.entities_in(
|
||||
{ x: block.x + inset, y: block.y - 1 + inset, z: block.z + inset },
|
||||
{ x: block.x + 1 - inset, y: block.y - inset, z: block.z + 1 - inset },
|
||||
"bworld:item",
|
||||
).filter((item) => item.on_ground && processing_for(recipes, item.get_item()!.id));
|
||||
|
||||
const press = (item: EntityRef) => {
|
||||
const stack = item.get_item()!;
|
||||
const results = roll_results(processing_for(recipes, stack.id)!);
|
||||
const { x, y, z } = item.position;
|
||||
if (stack.count === 1) {
|
||||
const [first, ...rest] = results;
|
||||
item.set_item(first);
|
||||
for (const extra of rest) {
|
||||
const { x: vx, y: vy, z: vz } = item.velocity;
|
||||
ctx.world.spawn_item(x, y, z, extra).push(vx, vy, vz);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const scatter = () => (Math.random() - 0.5) * 2;
|
||||
for (const result of results) ctx.world.spawn_item(x, y, z, result).push(scatter(), scatter(), scatter());
|
||||
item.set_item({ ...stack, count: stack.count - 1 });
|
||||
};
|
||||
|
||||
ctx.components.register_block("create:mechanical_press", {
|
||||
on_tick(block) {
|
||||
const data: PressData = block.data ?? {};
|
||||
const rate = cycle_rate(block.get_client_data<number>("speed") ?? 0);
|
||||
if (data.pressing === undefined) {
|
||||
// a block that starts turning ticks again, see kinetic_world
|
||||
if (rate === 0) {
|
||||
block.set_ticking(false);
|
||||
return;
|
||||
}
|
||||
const scan = (data.scan ?? 1) - 1;
|
||||
const found = scan <= 0 && items_under(block, 0.125).length > 0;
|
||||
block.data = { ...data, scan: scan <= 0 ? SCAN_TICKS : scan, ...(found && { pressing: 0 }) };
|
||||
if (found) block.set_client_data("press", { steps: 0, rate } satisfies PressShown);
|
||||
return;
|
||||
}
|
||||
const steps = data.pressing;
|
||||
if (steps === PRESS_AT && rate > 0) {
|
||||
const [item] = items_under(block, 0);
|
||||
if (item) press(item);
|
||||
}
|
||||
// done, and it looks again straight away, for the rest of a stack
|
||||
if (steps > CYCLE) {
|
||||
const { pressing: _, scan: __, ...rest } = data;
|
||||
block.data = rest;
|
||||
block.set_client_data("press", undefined);
|
||||
return;
|
||||
}
|
||||
// it stops at the bottom to press on the next tick, however fast it's going
|
||||
const next = steps < PRESS_AT && steps + rate >= PRESS_AT ? PRESS_AT : steps + rate;
|
||||
block.data = { ...data, pressing: next };
|
||||
if (block.get_client_data<PressShown>("press")?.rate !== rate) {
|
||||
block.set_client_data("press", { steps: next, rate } satisfies PressShown);
|
||||
}
|
||||
if (rate === 0) block.set_ticking(false);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// the world as rotation spreading sees it: blocks with create:kinetic, their speed in client data and where it comes
|
||||
@@ -125,6 +211,8 @@ function kinetic_world(ctx: ServerContext, config: Config): KineticWorld {
|
||||
},
|
||||
set(at, speed, source, network) {
|
||||
const block = block_at(at);
|
||||
// machines stop ticking while they're still, like a press, and start again once they turn
|
||||
if (speed !== 0 && !block.get_client_data("speed")) block.set_ticking(true);
|
||||
block.set_client_data("speed", speed === 0 ? undefined : speed);
|
||||
const { source: _, network: __, ...rest }: KineticData = block.data ?? {};
|
||||
block.data = { ...rest, ...(source && { source }), ...(network !== undefined && { network }) };
|
||||
|
||||
@@ -30,11 +30,11 @@ export function setup(ctx: SharedContext) {
|
||||
return kinetic_at(x + dx, y + dy, z + dz);
|
||||
};
|
||||
|
||||
// the side of x y z with an axle pointing at it, like getPreferredFacing. undefined when there's none, or when
|
||||
// axles point at it along two axes, since it can't line up with both
|
||||
const axle_beside = (x: number, y: number, z: number): Face | undefined => {
|
||||
// the side of x y z with an axle pointing at it, like getPreferredFacing, of the sides given. undefined when there's
|
||||
// none, or when axles point at it along two axes, since it can't line up with both
|
||||
const axle_beside = (x: number, y: number, z: number, sides = FACINGS): Face | undefined => {
|
||||
let found: Face | undefined;
|
||||
for (const side of FACINGS) {
|
||||
for (const side of sides) {
|
||||
if (!beside(x, y, z, side)?.shafts.includes(OPPOSITE[side])) continue;
|
||||
if (found && face_axis(found) !== face_axis(side)) return undefined;
|
||||
found = side;
|
||||
@@ -73,6 +73,11 @@ export function setup(ctx: SharedContext) {
|
||||
if (!cog_fits(placement.x, placement.y, placement.z, axis, params.cog)) return false;
|
||||
return { [params.axis ?? "axis"]: AXES.indexOf(axis) };
|
||||
}
|
||||
// along an axle beside it, or else facing the player, like HorizontalKineticBlock and MechanicalPressBlock
|
||||
if (params.facing !== undefined && params.horizontal) {
|
||||
const side = axle_beside(placement.x, placement.y, placement.z, FACINGS.slice(0, 4));
|
||||
return { [params.facing]: FACINGS.indexOf(side ?? OPPOSITE[placement.facing]) };
|
||||
}
|
||||
const side = axle_beside(placement.x, placement.y, placement.z);
|
||||
if (params.facing !== undefined) {
|
||||
const facing = side && !placement.sneaking
|
||||
|
||||
@@ -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,30 @@ export function entity_ref(entity: Entity): EntityRef {
|
||||
get removed() {
|
||||
return entity.removed;
|
||||
},
|
||||
get velocity() {
|
||||
return { x: entity.vx, y: entity.vy, z: entity.vz };
|
||||
},
|
||||
get on_ground() {
|
||||
return entity.on_ground;
|
||||
},
|
||||
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,83 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { type BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
||||
import { AIR_ID } from "$/common/protocol.ts";
|
||||
import { get_state_value, set_state_value } from "$/common/utils.ts";
|
||||
import type { Face } from "$/common/mod_api/shared.ts";
|
||||
import type { ClientContext, Instances, ModelRef, Visual, VisualBlock } from "$/common/mod_api/client.ts";
|
||||
import { setup as setup_client } from "$/mods/create/scripts/client.ts";
|
||||
import { stone_floor, test_game } from "../helpers.ts";
|
||||
|
||||
// facing and axis states, in the order the importer numbers them
|
||||
export const FACING = { north: 0, east: 1, south: 2, west: 3, up: 4, down: 5 };
|
||||
export const AXIS = { x: 0, y: 1, z: 2 };
|
||||
|
||||
// alice standing south of 0 100 0 on a stone floor, looking north, with nothing in her hands. config changes create's
|
||||
export async function setup(config: Record<string, unknown> = {}) {
|
||||
const t = await test_game("mods", undefined, undefined, { create: config });
|
||||
const { game } = t;
|
||||
t.join(1, "alice");
|
||||
stone_floor(game, 6);
|
||||
for (let x = -6; x <= 6; x++) {
|
||||
for (let z = -6; z <= 6; z++) for (let y = 100; y < 104; y++) game.set_block(x, y, z, AIR_ID);
|
||||
}
|
||||
const move = (sneaking = false, pitch = 0) =>
|
||||
t.send(1, { type: "move", x: 0.5, y: 100, z: 2.5, yaw: 0, pitch, ...(sneaking && { sneaking }) });
|
||||
move();
|
||||
|
||||
// a block with one state set, the way a player would have placed it
|
||||
const place = (x: number, y: number, z: number, id: string, state?: string, value = 0) => {
|
||||
const info = EverythingRegistry.get<BlockRegistry>("blocks", id)!;
|
||||
game.set_block(x, y, z, id, undefined, state ? set_state_value(0, info, state, value)! >>> 16 : 0);
|
||||
};
|
||||
const speed = (x: number, y: number, z: number) => game.world.get_tile(x, y, z)?.client_data?.speed as number ?? 0;
|
||||
const state = (x: number, y: number, z: number, name: string) =>
|
||||
get_state_value(game.world.get_block_value(x, y, z), game.world.get_block_info(x, y, z)!, name);
|
||||
const use = (x: number, y: number, z: number, face: Face = "south") =>
|
||||
t.send(1, { type: "use_block", x, y, z, face, hit: [0.5, 0.5, 1] });
|
||||
const ticks = (n: number) => {
|
||||
for (let i = 0; i < n; i++) game.tick();
|
||||
};
|
||||
// the rpm a crank turns at
|
||||
const crank =
|
||||
(EverythingRegistry.get<BlockRegistry>("blocks", "create:hand_crank")!.components!["create:hand_crank"] as {
|
||||
speed: number;
|
||||
}).speed;
|
||||
return { ...t, move, place, speed, state, use, ticks, crank };
|
||||
}
|
||||
|
||||
// create's client script with only what its visuals need, and a block for one to draw that records what its instances
|
||||
// do, by model ("own" for the block's own model): how rotating ones turn, and where transformed ones are moved
|
||||
export async function visual_for(
|
||||
id: string,
|
||||
states: Record<string, number>,
|
||||
data: Record<string, unknown>,
|
||||
[x, y, z] = [0, 100, 0],
|
||||
) {
|
||||
await test_game("mods");
|
||||
const visuals = new Map<string, (block: VisualBlock, instances: Instances) => Visual>();
|
||||
setup_client({
|
||||
blocks: {
|
||||
components: (id: string) =>
|
||||
structuredClone(EverythingRegistry.get<BlockRegistry>("blocks", id)!.components),
|
||||
},
|
||||
render: { register_visual: (id: string, create: never) => visuals.set(id, create) },
|
||||
} as unknown as ClientContext);
|
||||
const key = (model?: ModelRef) => model === undefined ? "own" : JSON.stringify(model);
|
||||
const turns = new Map<string, [string, number, number]>();
|
||||
const transforms = new Map<string, number[]>();
|
||||
const instances = {
|
||||
rotating: (model?: ModelRef) => ({
|
||||
set_rotation: (axis: string, rpm: number, offset = 0) => turns.set(key(model), [axis, rpm, offset]),
|
||||
delete() {},
|
||||
}),
|
||||
transformed: (model?: ModelRef) => ({
|
||||
set_transform: (matrix: ArrayLike<number>) => transforms.set(key(model), Array.from(matrix)),
|
||||
delete() {},
|
||||
}),
|
||||
} as unknown as Instances;
|
||||
const block = { id, x, y, z, states, get_client_data: (field: string) => structuredClone(data[field]) as never };
|
||||
const visual = visuals.get(id)!(block, instances);
|
||||
return { visual, turns, transforms, data };
|
||||
}
|
||||
@@ -4,51 +4,9 @@
|
||||
// create's kinetics: shafts take the speed of what turns them, a hand crank turns them while it's being clicked, and a
|
||||
// block that would turn two ways at once breaks
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import { type BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
|
||||
import { AIR_ID } from "$/common/protocol.ts";
|
||||
import { get_state_value, set_state_value } from "$/common/utils.ts";
|
||||
import type { Face } from "$/common/mod_api/shared.ts";
|
||||
import type { ClientContext, Instances, ModelRef, Visual, VisualBlock } from "$/common/mod_api/client.ts";
|
||||
import { setup as setup_client } from "$/mods/create/scripts/client.ts";
|
||||
import { stone_floor, test_game } from "../helpers.ts";
|
||||
|
||||
// facing and axis states, in the order the importer numbers them
|
||||
const FACING = { north: 0, east: 1, south: 2, west: 3, up: 4, down: 5 };
|
||||
const AXIS = { x: 0, y: 1, z: 2 };
|
||||
|
||||
// alice standing south of 0 100 0 on a stone floor, looking north, with nothing in her hands. config changes create's
|
||||
async function setup(config: Record<string, unknown> = {}) {
|
||||
const t = await test_game("mods", undefined, undefined, { create: config });
|
||||
const { game } = t;
|
||||
t.join(1, "alice");
|
||||
stone_floor(game, 6);
|
||||
for (let x = -6; x <= 6; x++) {
|
||||
for (let z = -6; z <= 6; z++) for (let y = 100; y < 104; y++) game.set_block(x, y, z, AIR_ID);
|
||||
}
|
||||
const move = (sneaking = false, pitch = 0) =>
|
||||
t.send(1, { type: "move", x: 0.5, y: 100, z: 2.5, yaw: 0, pitch, ...(sneaking && { sneaking }) });
|
||||
move();
|
||||
|
||||
// a block with one state set, the way a player would have placed it
|
||||
const place = (x: number, y: number, z: number, id: string, state?: string, value = 0) => {
|
||||
const info = EverythingRegistry.get<BlockRegistry>("blocks", id)!;
|
||||
game.set_block(x, y, z, id, undefined, state ? set_state_value(0, info, state, value)! >>> 16 : 0);
|
||||
};
|
||||
const speed = (x: number, y: number, z: number) => game.world.get_tile(x, y, z)?.client_data?.speed as number ?? 0;
|
||||
const state = (x: number, y: number, z: number, name: string) =>
|
||||
get_state_value(game.world.get_block_value(x, y, z), game.world.get_block_info(x, y, z)!, name);
|
||||
const use = (x: number, y: number, z: number, face: Face = "south") =>
|
||||
t.send(1, { type: "use_block", x, y, z, face, hit: [0.5, 0.5, 1] });
|
||||
const ticks = (n: number) => {
|
||||
for (let i = 0; i < n; i++) game.tick();
|
||||
};
|
||||
// the rpm a crank turns at
|
||||
const crank =
|
||||
(EverythingRegistry.get<BlockRegistry>("blocks", "create:hand_crank")!.components!["create:hand_crank"] as {
|
||||
speed: number;
|
||||
}).speed;
|
||||
return { ...t, move, place, speed, state, use, ticks, crank };
|
||||
}
|
||||
import { test_game } from "../helpers.ts";
|
||||
import { AXIS, FACING, setup, visual_for } from "./helpers.ts";
|
||||
|
||||
// a crank at 0 100 0 facing west, its axle in a line of shafts along x from 1 to length
|
||||
async function crank_and_line(length = 4, config?: Record<string, unknown>) {
|
||||
@@ -287,34 +245,6 @@ Deno.test("a cog lines up with the cog it's placed against, and can't go where i
|
||||
assertEquals(t.state(1, 100, 1, "axis"), AXIS.y);
|
||||
});
|
||||
|
||||
// create's client script with only what its visuals need, and a block for one to draw that records how its instances
|
||||
// turn, by model: "own" for the block's own model
|
||||
async function visual_for(
|
||||
id: string,
|
||||
states: Record<string, number>,
|
||||
data: Record<string, unknown>,
|
||||
[x, y, z] = [0, 100, 0],
|
||||
) {
|
||||
await test_game("mods");
|
||||
const visuals = new Map<string, (block: VisualBlock, instances: Instances) => Visual>();
|
||||
setup_client({
|
||||
blocks: {
|
||||
components: (id: string) =>
|
||||
structuredClone(EverythingRegistry.get<BlockRegistry>("blocks", id)!.components),
|
||||
},
|
||||
render: { register_visual: (id: string, create: never) => visuals.set(id, create) },
|
||||
} as unknown as ClientContext);
|
||||
const turns = new Map<string, [string, number, number]>();
|
||||
const rotating = (model?: ModelRef) => ({
|
||||
set_rotation: (axis: string, rpm: number, offset = 0) =>
|
||||
turns.set(model === undefined ? "own" : JSON.stringify(model), [axis, rpm, offset]),
|
||||
delete() {},
|
||||
});
|
||||
const block = { id, x, y, z, states, get_client_data: (field: string) => data[field] as never };
|
||||
const visual = visuals.get(id)!(block, { rotating, transformed: () => ({}) } as unknown as Instances);
|
||||
return { visual, turns, data };
|
||||
}
|
||||
|
||||
Deno.test("a shaft is drawn turning around its axis at the speed its client data says", async () => {
|
||||
const { visual, turns, data } = await visual_for("create:shaft", { axis: AXIS.z }, { speed: 16 });
|
||||
// its own model, the way its states draw it
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// the mechanical press: turned, it slams down on items lying on the ground under it and presses them with create's
|
||||
// pressing recipes, one at a time, and it only ticks while it turns
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import { ItemStack } from "$/common/inventory.ts";
|
||||
import { FACING, setup, visual_for } from "./helpers.ts";
|
||||
|
||||
// a press at 1 101 0 along x, turned by a crank on its west side, with the floor two blocks under it
|
||||
async function press_with_crank() {
|
||||
const t = await setup();
|
||||
t.place(0, 101, 0, "create:hand_crank", "facing", FACING.west);
|
||||
t.place(1, 101, 0, "create:mechanical_press", "facing", FACING.east);
|
||||
// holding use on the crank, which clicks it every 4 ticks
|
||||
const crank = (ticks: number) => {
|
||||
for (let i = 0; i < ticks; i += 4) {
|
||||
t.use(0, 101, 0);
|
||||
t.ticks(4);
|
||||
}
|
||||
};
|
||||
// what's lying around, added up by item
|
||||
const lying = () => {
|
||||
const counts: Record<string, number> = {};
|
||||
for (const { item } of t.game.item_entities()) counts[item.type_id] = (counts[item.type_id] ?? 0) + item.amount;
|
||||
return counts;
|
||||
};
|
||||
const ingots = (count: number) => t.game.spawn_item(1.5, 100, 0.5, new ItemStack("bworld:iron_ingot", count));
|
||||
return { ...t, crank, lying, ingots };
|
||||
}
|
||||
|
||||
Deno.test("a turning press slams down on an ingot lying under it and presses it into a sheet", async () => {
|
||||
const t = await press_with_crank();
|
||||
t.ingots(1);
|
||||
// still, it waits
|
||||
t.ticks(100);
|
||||
assertEquals(t.lying(), { "bworld:iron_ingot": 1 });
|
||||
|
||||
t.crank(200);
|
||||
assertEquals(t.lying(), { "create:iron_sheet": 1 });
|
||||
});
|
||||
|
||||
Deno.test("from a stack, a press presses one at a time, and each lands beside the rest", async () => {
|
||||
const t = await press_with_crank();
|
||||
t.ingots(3);
|
||||
for (let i = 0; i < 100 && !t.lying()["create:iron_sheet"]; i++) t.crank(4);
|
||||
assertEquals(t.lying(), { "bworld:iron_ingot": 2, "create:iron_sheet": 1 });
|
||||
assertEquals(t.game.item_entities().length, 2);
|
||||
|
||||
t.crank(600);
|
||||
assertEquals(t.lying(), { "create:iron_sheet": 3 });
|
||||
});
|
||||
|
||||
Deno.test("a press only ticks while it turns", async () => {
|
||||
const t = await press_with_crank();
|
||||
const ticking = () => {
|
||||
const tile = t.game.world.get_tile(1, 101, 0);
|
||||
return tile !== undefined && t.game.world.ticks(tile);
|
||||
};
|
||||
assertEquals(ticking(), false);
|
||||
t.crank(8);
|
||||
assertEquals(ticking(), true);
|
||||
// the crank lets go and the press stops, nothing under it to press
|
||||
t.ticks(40);
|
||||
assertEquals(ticking(), false);
|
||||
});
|
||||
|
||||
Deno.test("a press lines up with an axle beside it, and otherwise faces the player", async () => {
|
||||
const t = await setup();
|
||||
t.send(1, { type: "chat", text: "/give create:mechanical_press 64" });
|
||||
t.send(1, { type: "select_slot", slot: 0 });
|
||||
// alice looks north
|
||||
t.use(-2, 99, 0, "top");
|
||||
assertEquals(t.state(-2, 100, 0, "facing"), FACING.south);
|
||||
t.place(2, 100, 0, "create:shaft", "axis", 0);
|
||||
t.use(3, 99, 0, "top");
|
||||
assertEquals(t.state(3, 100, 0, "facing"), FACING.west);
|
||||
});
|
||||
|
||||
Deno.test("a press's head comes down to press halfway through its cycle and goes back up, as the server says", async () => {
|
||||
const { visual, turns, transforms, data } = await visual_for(
|
||||
"create:mechanical_press",
|
||||
{ facing: FACING.east },
|
||||
{ speed: 32 },
|
||||
);
|
||||
// the shaft through it turns along its facing
|
||||
const shaft = [...turns].find(([model]) => model.includes("shaft"))![1];
|
||||
assertEquals(shaft.slice(0, 2), ["x", 32]);
|
||||
// how far down the head is, from its transform
|
||||
const down = () => -([...transforms].find(([model]) => model.includes("head"))?.[1][13] ?? 0);
|
||||
|
||||
visual.on_frame!(5);
|
||||
assertEquals(down(), 0);
|
||||
// the server says a cycle started, 4 steps of 240 a tick
|
||||
data.press = { steps: 0, rate: 4 };
|
||||
visual.update!();
|
||||
visual.on_frame!(10);
|
||||
assertEquals(down(), 0);
|
||||
visual.on_frame!(25);
|
||||
assert(down() > 0 && down() < 1, `${down()}`);
|
||||
visual.on_frame!(40);
|
||||
assertEquals(down(), 1);
|
||||
visual.on_frame!(70);
|
||||
assertEquals(down(), 0);
|
||||
});
|
||||
@@ -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