Compare commits

..
2 Commits
Author SHA1 Message Date
paula 74c315bdfc Cog wheels 2026-10-15 12:01:46 -03:00
paula a0596ed0ef Hand crank and shafts 2026-10-15 11:45:12 -03:00
29 changed files with 1282 additions and 67 deletions
+25 -5
View File
@@ -5,8 +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, and stonecutting from S9. Facts about Create come from reading `ports/create1.21.1` and
`ports/create1.19.3`, and facts about bworld from its source.
R8, S0, S7, S12, stonecutting from S9, and the start of P1's kinetics: shafts and cogwheels turned by a hand crank.
Facts about Create come from reading `ports/create1.21.1` and `ports/create1.19.3`, and facts about bworld from its
source.
## Sources
@@ -123,7 +124,8 @@ shared tags to `c`, which is what bworld calls them. A mod's remap file is where
Block properties (shape, tool, toughness) aren't in any data file: Java mods set them in code. `mod` writes a block for
each blockstate with placeholder properties, and a per-mod table fills them in. For Create that table is
`mods/create/import/blocks.json`.
`mods/create/import/blocks.json`. Built for `blockstate` as `--blocks FILE`: each block's fields in it, like its
`components`, replace the ones the importer would write, and a block it names that isn't made is an error.
**What `model` does today.** It keeps `parent`, since the engine merges parents in when it loads (see
[Parents](docs/modding/resources/models.md#parents)), and remaps it like any id. Minecraft's template parents (`cube`,
@@ -175,8 +177,8 @@ Create 0.5.0.j's data gives 89 tags: 45 of Create's and 44 of Forge's shared one
skipped. Of its 531 stonecutting recipes, 423 are converted. The other 108 cut granite, diorite, deepslate, calcite,
tuff and dripstone, which bworld doesn't have yet. Re-importing once it does brings them in.
**For Create**, `mods/create/import/` keeps the remap file and the commands, and later the block table. Re-running the
import is one command, and hand-written files are never in the folders it writes.
**For Create**, `mods/create/import/` keeps the remap file, the block table and the commands. Re-running the import is
one command, and hand-written files are never in the folders it writes.
**Vanilla ids in recipes.** Create's recipes use 447 distinct Minecraft ids, like dyes, `minecraft:cobblestone` and
`minecraft:netherrack`. Each becomes the bworld id of the same name, or another with the remap file's `ids`. A recipe
@@ -465,6 +467,24 @@ visual makes a `rotating` instance with the axis, rpm and an offset that keeps c
when the block's coordinates on the two axes that aren't its axis add up to an even number, otherwise 11.25° for large
cogs and 0 for the rest. A speed change updates one instance, and nothing else happens per frame.
**As built** (`scripts/kinetics/`: the shaft, both cogwheels and the hand crank). `create:kinetic` takes `axis` (the
state with x, y or z) or `facing` (the state with the 6 faces), `shaft` (`both`, `front` or `back`) and `cog` (`small`
or `large`), and its shared rules place blocks like `RotatedPillarKineticBlock`, `DirectionalKineticBlock` and
`CogWheelBlock`, lining up with an axle or cog beside them. A cog that would cut into another isn't placed, like
`isValidCogwheelPosition`, by `state_for_placement` returning `false`. Connections are the table's first four rows.
Spreading is `RotationPropagator`'s, with queues: a block's speed is its `speed` client data, and the block it gets it
from and the generator it comes from (`source` and `network`) are tile data. Two things differ: on_break runs while the
block is still there, so the walk after a removal treats its place as empty, and generators that stop with what turned
them start again right after the walk instead of a tick later (`reActivateSource`). Create's flicker score and its
periodic `validateKinetics` aren't ported, since shafts don't tick. `create:hand_crank` turns while it's clicked, for 10
ticks after each click, the other way while sneaking, and costs hunger by the config's `crank_hunger`. Its visual turns
the half shaft as a `rotating` instance and eases the handle in `on_frame`, like `HandCrankVisual`. A large cog is drawn
as its shaftless model and a separate shaft, offset apart, like `LargeCogVisual`. The crank doesn't pop off when its
block is taken away yet, and cogs have no placement helper (`CogwheelBlockItem`'s ghost offsets). It needed four engine
additions: `looking` in `state_for_placement` (`getNearestLookingDirection`), `false` from it to not place
(`getStateForPlacement` returning null), `ctx.blocks` in shared scripts, and `ctx.world.get_block_ref` for changing
another block's data (`getBlockEntity`).
**Chunk borders.** Tile data keeps speeds across unloading. Create tracks unloaded members' stress separately
(`KineticNetwork`'s unloaded stress). Do the same, so a network across an unloaded chunk counts right.
+16 -12
View File
@@ -107,20 +107,24 @@ export class MultiPlayerGameMode {
const place_block = place_id !== undefined
? EverythingRegistry.get<BlockRegistry>("blocks", place_id)
: undefined;
// with the states the server will give it, see BlockRules.placement_value, and holding the liquid it goes into
const place_value = place_block &&
waterlog_placement(
block_rules.placement_value(place_block, this.client.player.yaw, {
...target,
face: hit.face,
hit: hit.hit,
sneaking,
}),
place_block,
// with the states the server will give it, see BlockRules.placement_value, and holding the liquid it goes into.
// undefined when its rules say it can't go there
const ruled_value = place_block &&
block_rules.placement_value(place_block, this.client.player.yaw, this.client.player.pitch, {
...target,
face: hit.face,
hit: hit.hit,
sneaking,
});
const place_value = ruled_value !== undefined
? waterlog_placement(
ruled_value,
place_block!,
level.get_block_value(target.x, target.y, target.z),
EverythingRegistry.get_by_id<BlockRegistry>("blocks", current),
);
const placeable = place_id !== undefined && can_place(
)
: undefined;
const placeable = place_value !== undefined && place_id !== undefined && can_place(
place_block,
current === AIR ? undefined : EverythingRegistry.get_by_id<BlockRegistry>("blocks", current),
level.get_block_value(target.x, target.y, target.z),
+14 -8
View File
@@ -196,12 +196,25 @@ function script_url(code: string) {
return code_url(new TextEncoder().encode(code));
}
// ctx.blocks, the same in shared and client scripts
function blocks_api(mod: string): SharedContext["blocks"] {
return {
exists: (id) => EverythingRegistry.get("blocks", id) !== undefined,
components(id) {
const block = EverythingRegistry.get<BlockRegistry>("blocks", id);
if (!block) throw new Error(`[${mod}] unknown block ${id}`);
return structuredClone(block.components ?? {});
},
};
}
function shared_context(listing: ModListing): SharedContext {
const mod = listing.id;
return {
mod: { id: mod, version: listing.version },
side: "client",
tags: tag_api(),
blocks: blocks_api(mod),
world: rules_world,
components: {
register_block(id, rules) {
@@ -323,14 +336,7 @@ function client_context(listing: ModListing): ClientContext {
EverythingRegistry.get<ItemRegistry>("items", id)?.components ?? {},
)),
},
blocks: {
exists: (id) => EverythingRegistry.get("blocks", id) !== undefined,
components(id) {
const block = EverythingRegistry.get<BlockRegistry>("blocks", id);
if (!block) throw new Error(`[${mod}] unknown block ${id}`);
return structuredClone(block.components ?? {});
},
},
blocks: blocks_api(mod),
loot: {
table: (id) => structuredClone(EverythingRegistry.get<LootTableJson>("loot_tables", id)),
},
+29 -5
View File
@@ -4,7 +4,7 @@
// the block rules shared scripts register (see BlockRules in mod_api/shared.ts), run the same way on the server and on
// clients: what states a placed block gets, and how blocks change with the blocks beside them. each side has its own
// BlockRules, with its own world: the server's is the real one, a client's is what it shows and guesses ahead with
import type { BlockInteraction, BlockPlacement, BlockRules as Rules, SharedWorld } from "./mod_api/shared.ts";
import type { BlockInteraction, BlockPlacement, BlockRules as Rules, Face, SharedWorld } from "./mod_api/shared.ts";
import { type BlockRegistry, EverythingRegistry } from "./everything_registry.ts";
import { default_block_value, set_state_value } from "./utils.ts";
@@ -20,6 +20,19 @@ export function horizontal_facing(yaw: number): typeof FACINGS[number] {
return FACINGS[((quarter % 4) + 4) % 4];
}
// the face of the six someone looking at yaw and pitch looks most toward, like minecraft's getNearestLookingDirection.
// pitch above 0 looks up, the way the camera aims
export function looking_face(yaw: number, pitch: number): Face {
const cos_pitch = Math.cos(pitch);
const x = -Math.sin(yaw) * cos_pitch;
const y = Math.sin(pitch);
const z = -Math.cos(yaw) * cos_pitch;
const [ax, ay, az] = [Math.abs(x), Math.abs(y), Math.abs(z)];
if (ay >= ax && ay >= az) return y > 0 ? "top" : "bottom";
if (ax >= az) return x > 0 ? "east" : "west";
return z > 0 ? "south" : "north";
}
// a block's value as a player looking at yaw places it before any rules: its default states, and a 2 bit facing
// turned towards them, like a furnace
export function default_placement_value(block: BlockRegistry, yaw: number): number {
@@ -52,11 +65,21 @@ export class BlockRules {
});
}
// the block's value with the states a player placing it gets: its defaults facing them (default_placement_value),
// then what its rules' state_for_placement say. states that don't exist or don't fit are left alone
placement_value(block: BlockRegistry, yaw: number, where: Omit<BlockPlacement, "facing">): number {
// the block's value with the states a player looking at yaw and pitch placing it gets: its defaults facing them
// (default_placement_value), then what its rules' state_for_placement say. states that don't exist or don't fit are
// left alone. undefined when a rule says it can't go there
placement_value(
block: BlockRegistry,
yaw: number,
pitch: number,
where: Omit<BlockPlacement, "facing" | "looking">,
): number | undefined {
let value = default_placement_value(block, yaw);
const placement: BlockPlacement = { ...where, facing: horizontal_facing(yaw) };
const placement: BlockPlacement = {
...where,
facing: horizontal_facing(yaw),
looking: looking_face(yaw, pitch),
};
for (const { mod, id, rules, params } of this.#of(block)) {
if (!rules.state_for_placement) continue;
const states = this.run(
@@ -64,6 +87,7 @@ export class BlockRules {
`${id} state_for_placement`,
() => rules.state_for_placement!(placement, params),
);
if (states === false) return undefined;
for (const [name, state] of Object.entries(states ?? {})) {
const known = block.states?.find((s) => s.name === name);
if (known && Number.isInteger(state) && state >= 0 && state < 2 ** known.bits) {
+3
View File
@@ -242,6 +242,9 @@ export interface ServerWorld {
// shape covers the whole face. false for air, plants, water and the sides of a slab
is_face_sturdy(x: number, y: number, z: number, face: Face): boolean;
get_block_data<T>(x: number, y: number, z: number): T | undefined;
// the block the way its components' handlers get it, for changing another block's data or client data, like
// minecraft's getBlockEntity. undefined for air
get_block_ref(x: number, y: number, z: number): BlockRef | undefined;
// BlockRef.set_ticking for a block, for waking one from somewhere else, like a machine getting something to work on
set_block_ticking(x: number, y: number, z: number, ticking: boolean): void;
// the item a block with item_display shows on top of it, like a block entity renderer: its "item" client data, see
+14 -4
View File
@@ -66,6 +66,13 @@ export interface SharedContext {
// the world rules look at and change. on a client it's what that client sees, and what rules change there is a
// guess until the server says what really happened. only for use in rules, not during setup
readonly world: SharedWorld;
// every block any mod registered, like the server's and clients' ctx.blocks. for rules that look at what's around,
// like a shaft lining up with the axle of the block it's placed against
readonly blocks: {
exists(id: Id): boolean;
// the components its json lists and their params, a copy
components(id: Id): Record<Id, unknown>;
};
readonly components: {
// the rules of a block component, the same id the server script registers the rest of it under
// deno-lint-ignore no-explicit-any
@@ -93,12 +100,14 @@ export interface SharedBlock extends Position {
}
// a player placing a block at x y z by clicking face of the block next to it, at hit (0 to 1 on each axis of that
// block), like minecraft's BlockPlaceContext. facing is the way the player looks, along the ground, and sneaking
// whether they hold the sneak key, for blocks placed another way round when they do
// block), like minecraft's BlockPlaceContext. facing is the way the player looks along the ground, and looking the face
// of the six they look most toward, up and down too, like getNearestLookingDirection. sneaking is whether they hold the
// sneak key, for blocks placed another way round when they do
export interface BlockPlacement extends Position {
readonly face: Face;
readonly hit: readonly [number, number, number];
readonly facing: "north" | "east" | "south" | "west";
readonly looking: Face;
readonly sneaking: boolean;
}
@@ -116,8 +125,9 @@ export interface BlockInteraction {
// deno-lint-ignore no-explicit-any
export interface BlockRules<P = any> {
// the states it's placed with when a player places it, like minecraft's getStateForPlacement. states it doesn't
// return keep their defaults, and a 2 bit "facing" faces the player
state_for_placement?(placement: BlockPlacement, params: P): Record<string, number> | void;
// return keep their defaults, and a 2 bit "facing" faces the player. false when it can't go there, so it isn't
// placed, like getStateForPlacement returning null
state_for_placement?(placement: BlockPlacement, params: P): Record<string, number> | false | void;
// a block next to it (on any of the 6 sides) was placed, broken or changed its states, like minecraft's
// updateShape. neighbor is where, and what's there now
on_neighbor_change?(block: SharedBlock, params: P, neighbor: SharedBlock): void;
+16 -11
View File
@@ -93,15 +93,17 @@ export function setup(ctx: SharedContext) {
}
```
| Rule | Called when | Returns |
| --------------------------------------------- | ---------------------------------------------------------------------- | -------------------------- |
| `state_for_placement(placement, params)` | A player is about to place it. | States to place it with |
| `on_neighbor_change(block, params, neighbor)` | A block on one of its 6 sides is placed, broken or changes its states. | |
| `on_interact(block, params, interaction)` | A player right clicks it. | `true` if it did something |
| Rule | Called when | Returns |
| --------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------- |
| `state_for_placement(placement, params)` | A player is about to place it. | States to place it with, or `false` when it can't go there |
| `on_neighbor_change(block, params, neighbor)` | A block on one of its 6 sides is placed, broken or changes its states. | |
| `on_interact(block, params, interaction)` | A player right clicks it. | `true` if it did something |
Here `block` is `{ id, x, y, z }`, without tile data, which clients never have. `ctx.world` in a shared script has
`get_block`, `get_state`, `set_state`, `is_face_sturdy`, `biome_at` and `season_at` (see
[Seasons](../worldgen/biomes.md#seasons)), and only works inside rules.
[Seasons](../worldgen/biomes.md#seasons)), and only works inside rules. `ctx.blocks.components(id)` gives any block's
components and their params, like on the server, for rules that look at what's around them, like a shaft lining up with
the axle of the block it's placed against.
### Neighbors
@@ -116,12 +118,15 @@ a slab's sides and plants aren't.
### Placing
`state_for_placement` picks the states a block is placed with, like Minecraft's `getStateForPlacement`. `placement` is
`{ x, y, z, face, hit, facing, sneaking }`: where it's going, the face of the block that was clicked, where on that
block the click was (from 0 to 1 on each axis), the way the player looks along the ground, and whether they're
`{ x, y, z, face, hit, facing, looking, sneaking }`: where it's going, the face of the block that was clicked, where on
that block the click was (from 0 to 1 on each axis), the way the player looks along the ground, the face of the six they
look most toward, `"top"` or `"bottom"` too, like `getNearestLookingDirection`, and whether they're
[sneaking](../entities/players.md#sneaking), for blocks that sneaking places the other way round. It returns states by
name, and the rest keep their defaults, except that a 2 bit `facing` already faces the player. It runs before the server
checks that no one is in the way, so that's checked against the shape the block will really have. A trapdoor clicked
onto the upper half of a block's side hangs in the top half:
name, and the rest keep their defaults, except that a 2 bit `facing` already faces the player. Returning `false` means
it can't go there at all, like a large cogwheel right beside another cogwheel, and nothing is placed, like
`getStateForPlacement` returning `null`. It runs before the server checks that no one is in the way, so that's checked
against the shape the block will really have. A trapdoor clicked onto the upper half of a block's side hangs in the top
half:
```ts
state_for_placement(placement): Record<string, number> {
+3 -1
View File
@@ -22,7 +22,9 @@ ctx.components.register_block("copper_tools:counter", {
});
```
Outside a handler, `ctx.world.get_block_data<T>(x, y, z)` reads it.
Outside a handler, `ctx.world.get_block_data<T>(x, y, z)` reads it. To change another block's data, like a shaft passing
its speed to the next one, `ctx.world.get_block_ref(x, y, z)` gives that block the way its own handlers get it, like
Minecraft's `getBlockEntity`, or `undefined` for air.
- Tile data is saved with the world, and goes away when the block is broken or replaced.
- It's **never sent to clients**. To show it to a player, give it [client data](#client-data), open a
+4 -1
View File
@@ -15,6 +15,9 @@
"render_layer": "cutout",
"mining": { "toughness": 1 },
"drops": "create:cogwheel",
"item_model": "create:item_cogwheel"
"item_model": "create:item_cogwheel",
"components": {
"create:kinetic": { "axis": "axis", "cog": "small" }
}
}
}
+6 -1
View File
@@ -18,6 +18,11 @@
"render_layer": "cutout",
"mining": { "toughness": 1 },
"drops": "create:hand_crank",
"item_model": "create:item_hand_crank"
"item_model": "create:item_hand_crank",
"interactive": true,
"components": {
"create:kinetic": { "facing": "facing", "shaft": "back" },
"create:hand_crank": { "speed": 32 }
}
}
}
+4 -1
View File
@@ -15,6 +15,9 @@
"render_layer": "cutout",
"mining": { "toughness": 1 },
"drops": "create:large_cogwheel",
"item_model": "create:item_large_cogwheel"
"item_model": "create:item_large_cogwheel",
"components": {
"create:kinetic": { "axis": "axis", "cog": "large" }
}
}
}
+4 -1
View File
@@ -15,6 +15,9 @@
"render_layer": "cutout",
"mining": { "toughness": 1 },
"drops": "create:shaft",
"item_model": "create:item_shaft"
"item_model": "create:item_shaft",
"components": {
"create:kinetic": { "axis": "axis" }
}
}
}
+7
View File
@@ -0,0 +1,7 @@
{
"format_version": 1,
"config": {
"max_speed": 256,
"crank_hunger": 0.01
}
}
+5 -1
View File
@@ -8,7 +8,7 @@ importer or `remap.json` and import again:
rm -rf mods/create/textures mods/create/models mods/create/blocks mods/create/items mods/create/tags mods/create/recipes
deno task import texture ports/create1.19.3/src --namespace create --output mods/create/textures --remap mods/create/import/remap.json
deno task import model ports/create1.19.3/src --namespace create --output mods/create/models --remap mods/create/import/remap.json
deno task import blockstate ports/create1.19.3/src --namespace create --output mods/create/blocks --remap mods/create/import/remap.json
deno task import blockstate ports/create1.19.3/src --namespace create --output mods/create/blocks --remap mods/create/import/remap.json --blocks mods/create/import/blocks.json
deno task import item ports/create1.19.3/src --namespace create --output mods/create/items --remap mods/create/import/remap.json
deno task import tag ports/create1.19.3/src/generated --namespace create --output mods/create/tags --remap mods/create/import/remap.json
deno task import tag ports/create1.19.3/src/generated --namespace forge --output mods/create/tags --remap mods/create/import/remap.json
@@ -21,6 +21,10 @@ then tags, then recipes. Forge's shared tags, like `forge:ingots/brass`, become
Create's stonecutting ones so far, and the ones that cut a stone bworld doesn't have yet (granite, diorite, deepslate,
calcite, tuff, dripstone) are left out until it does.
Java sets what blocks do in code, so every block gets placeholders (a second to mine with anything, dropping itself).
`blocks.json` gives blocks what they have instead, by id, like the components that make a shaft turn and a hand crank
turn it. Each block's fields there replace the ones the importer would write.
`remap.json` gives three of Create's models other names, since `block/radial_chassis/side_x` and
`block/radial_chassis_side_x` would both be `create:block_radial_chassis_side_x`.
+24
View File
@@ -0,0 +1,24 @@
{
"create:shaft": {
"components": {
"create:kinetic": { "axis": "axis" }
}
},
"create:cogwheel": {
"components": {
"create:kinetic": { "axis": "axis", "cog": "small" }
}
},
"create:large_cogwheel": {
"components": {
"create:kinetic": { "axis": "axis", "cog": "large" }
}
},
"create:hand_crank": {
"interactive": true,
"components": {
"create:kinetic": { "facing": "facing", "shaft": "back" },
"create:hand_crank": { "speed": 32 }
}
}
}
+7 -2
View File
@@ -2,7 +2,7 @@
"format_version": 1,
"id": "create",
"name": "Create",
"description": "A port of the Create team's Create. So far its blocks and items, which can be placed and look like Create's, but don't do anything yet.",
"description": "A port of the Create team's Create. So far its blocks and items, which can be placed and look like Create's, and shafts turned by a hand crank.",
"version": "0.1.0",
"authors": [
"simibubi and the Create team (original)",
@@ -15,5 +15,10 @@
"version": "*"
}
],
"credits": "CREDITS.md"
"credits": "CREDITS.md",
"scripts": {
"server": "scripts/server.ts",
"client": "scripts/client.ts",
"shared": "scripts/shared.ts"
}
}
+100
View File
@@ -0,0 +1,100 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// how create's moving blocks are drawn: kinetic blocks turn by the speed the server puts in their "speed" client data,
// 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";
// 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
const HANDLE = "create:block_hand_crank_handle";
const HANDLE_TURNS: Record<Face, ModelRef> = {
north: HANDLE,
east: { model: HANDLE, y: 90 },
south: { model: HANDLE, y: 180 },
west: { model: HANDLE, y: 270 },
top: { model: HANDLE, x: 270 },
bottom: { model: HANDLE, x: 90 },
};
// how a model made along y is turned to an axis, the way the kinetic blocks' variants turn theirs
const AXIS_TURNS: Record<Axis, { x?: number; y?: number }> = { x: { x: 90, y: 90 }, y: {}, z: { x: 90, y: 180 } };
export function setup(ctx: ClientContext) {
const shape_of = (block: VisualBlock): KineticShape => {
const params = ctx.blocks.components(block.id)["create:kinetic"] as KineticParams;
return kinetic_shape(params, (name) => block.states[name]);
};
const plain = (block: VisualBlock, instances: Instances): Visual => ({
update: turning(block, instances, shape_of(block)),
});
ctx.render.register_visual("create:shaft", plain, { replaces_model: true });
ctx.render.register_visual("create:cogwheel", plain, { replaces_model: true });
// a large cog's teeth are half as far apart as a small one's, so on the blocks where small cogs aren't offset it's
// offset by half of one of its own teeth. its shaft is apart from it and offset like any other, so it lines up with
// the shafts next to it. like BracketedKineticBlockEntityVisual.LargeCogVisual
ctx.render.register_visual("create:large_cogwheel", (block, instances) => {
const shape = shape_of(block);
const turns = AXIS_TURNS[shape.axis];
const cog = turning(
block,
instances,
shape,
{ model: "create:block_large_cogwheel_shaftless", ...turns },
11.25,
);
const shaft = turning(block, instances, shape, { model: "create:block_cogwheel_shaft", ...turns });
return {
update() {
cog();
shaft();
},
};
}, { replaces_model: true });
// 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) => {
const shape = shape_of(block);
const turn = turning(block, instances, shape);
const handle = instances.rotating(HANDLE_TURNS[shape.facing!]);
// in degrees, and degrees a tick
let angle = 0;
let velocity = 0;
let last: number | undefined;
return {
update: turn,
on_frame(time) {
const ticks = last === undefined ? 0 : time - last;
last = time;
// a quarter of the way to the shaft's speed each tick
velocity += (speed_of(block) * 0.3 - velocity) * Math.min(1, ticks / 4);
angle = (angle + velocity * ticks) % 360;
handle.set_rotation(shape.axis, 0, angle);
},
};
}, { replaces_model: true });
}
const speed_of = (block: VisualBlock) => block.get_client_data<number>("speed") ?? 0;
// a model turning around the block's axis at its speed, the block's own when not given. returns what turns it again
// when the speed changes. on every other block it's offset by half a small cog's tooth, so cogs mesh with the ones
// beside them, and on the rest by offset, like KineticBlockEntityVisual.rotationOffset
function turning(block: VisualBlock, instances: Instances, shape: KineticShape, model?: ModelRef, offset = 0) {
const instance = instances.rotating(model);
const angle = should_offset(shape.axis, block) ? 22.5 : offset;
const turn = () => instance.set_rotation(shape.axis, speed_of(block), angle);
turn();
return turn;
}
// whether the coordinates across the axis add up to an even number, like KineticBlockEntityVisual.shouldOffset
function should_offset(axis: Axis, { x, y, z }: VisualBlock) {
const across = (axis === "x" ? 0 : x) + (axis === "y" ? 0 : y) + (axis === "z" ? 0 : z);
return across % 2 === 0;
}
+157
View File
@@ -0,0 +1,157 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// what turns, and what turns what: a kinetic block's axis and the ends of it with an axle, and how fast one block turns
// the one next to it, like create's IRotate and RotationPropagator.getRotationSpeedModifier. no ctx, so placement
// rules, the server and visuals all read blocks the same way
import type { Face } from "bworld/shared";
export type Axis = "x" | "y" | "z";
// the create:kinetic component's params, from a block's json
export interface KineticParams {
// the 2 bit state that says its axis, x, y or z, like a shaft's
axis?: string;
// or the 3 bit state that says which way it faces, north, east, south, west, up or down, its axis going through
// that face, like a crank's
facing?: string;
// 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";
// 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";
}
// a 3 bit facing state's values, in the order the importer numbers java's facing
export const FACINGS: readonly Face[] = ["north", "east", "south", "west", "top", "bottom"];
// a 2 bit axis state's values
export const AXES: readonly Axis[] = ["x", "y", "z"];
export const FACE_OFFSETS: Readonly<Record<Face, readonly [number, number, number]>> = {
west: [-1, 0, 0],
east: [1, 0, 0],
bottom: [0, -1, 0],
top: [0, 1, 0],
north: [0, 0, -1],
south: [0, 0, 1],
};
export const OPPOSITE: Readonly<Record<Face, Face>> = {
west: "east",
east: "west",
bottom: "top",
top: "bottom",
north: "south",
south: "north",
};
const FACE_AXIS: Readonly<Record<Face, Axis>> = {
west: "x",
east: "x",
bottom: "y",
top: "y",
north: "z",
south: "z",
};
// the faces at the positive and negative ends of an axis
const AXIS_FACES: Readonly<Record<Axis, readonly [Face, Face]>> = {
x: ["east", "west"],
y: ["top", "bottom"],
z: ["south", "north"],
};
// how a block turns
export interface KineticShape {
axis: Axis;
// the faces with an axle
shafts: readonly Face[];
// the way it faces, for a block with a facing
facing?: Face;
cog?: "small" | "large";
}
// a kinetic block where it is
export interface Kinetic extends KineticShape {
readonly x: number;
readonly y: number;
readonly z: number;
}
// a block's shape from its params and its states, read by name
export function kinetic_shape(params: KineticParams, state: (name: string) => number | undefined): KineticShape {
if (params.facing !== undefined) {
const facing = FACINGS[state(params.facing) ?? 0];
const shaft = params.shaft ?? "both";
const shafts = shaft === "front"
? [facing]
: shaft === "back"
? [OPPOSITE[facing]]
: [facing, OPPOSITE[facing]];
return { axis: FACE_AXIS[facing], shafts, facing };
}
const axis = AXES[state(params.axis ?? "axis") ?? 1];
return { axis, shafts: AXIS_FACES[axis], ...(params.cog && { cog: params.cog }) };
}
export function face_axis(face: Face): Axis {
return FACE_AXIS[face];
}
// a speed turning counterclockwise seen from face, as rpm around face's axis, which is counterclockwise seen from its
// positive end. like KineticBlockEntity.convertToDirection
export function along(face: Face, speed: number): number {
return AXIS_FACES[FACE_AXIS[face]][0] === face ? speed : -speed;
}
// the face of from that to is beside, undefined when they aren't beside each other
function face_toward([dx, dy, dz]: readonly number[]): Face | undefined {
return (Object.keys(FACE_OFFSETS) as Face[]).find((face) => {
const [ox, oy, oz] = FACE_OFFSETS[face];
return ox === dx && oy === dy && oz === dz;
});
}
// how much faster to turns than from when from turns it, 0 when from doesn't turn it, like
// RotationPropagator.getRotationSpeedModifier: 1 for axles that meet, and the other way round for cogs, at the ratio of
// their sizes
export function speed_ratio(from: Kinetic, to: Kinetic): number {
const diff = [to.x - from.x, to.y - from.y, to.z - from.z];
const along = (axis: Axis) => diff[AXES.indexOf(axis)];
const face = face_toward(diff);
if (face && from.shafts.includes(face) && to.shafts.includes(OPPOSITE[face])) return 1;
// large cogs on different axes meet across an edge, off along both their axes. whether they turn the same way
// around their own axes depends on which side of each other they're on
if (from.cog === "large" && to.cog === "large") {
if (from.axis === to.axis || along(from.axis) === 0 || along(to.axis) === 0) return 0;
if (AXES.some((axis) => axis !== from.axis && axis !== to.axis && along(axis) !== 0)) return 0;
return along(from.axis) > 0 !== along(to.axis) > 0 ? -1 : 1;
}
// a large cog meets a small one on the same axis at one of its corners, level with it along the axis
const at_corner = from.axis === to.axis && along(from.axis) === 0 &&
AXES.every((axis) => axis === from.axis || Math.abs(along(axis)) === 1);
if (from.cog === "large" && to.cog === "small" && at_corner) return -2;
if (from.cog === "small" && to.cog === "large" && at_corner) return -0.5;
// small cogs side by side on the same axis
if (from.cog === "small" && to.cog === "small" && face && face_axis(face) !== from.axis && from.axis === to.axis) {
return -1;
}
return 0;
}
// the offsets of the 12 blocks that share an edge with one
const EDGES = [-1, 0, 1].flatMap((dx) => [-1, 0, 1].flatMap((dy) => [-1, 0, 1].map((dz) => [dx, dy, dz])))
.filter((offset) => offset.filter((d) => d !== 0).length === 2);
// where the blocks it could turn are, like getPotentialNeighbourLocations: the 6 beside it, and for cogs the ones
// across their edges, in their own plane for small ones
export function neighbour_positions(block: Kinetic): [number, number, number][] {
const offsets: readonly (readonly number[])[] = [
...Object.values(FACE_OFFSETS),
...block.cog === "large" ? EDGES : [],
...block.cog === "small" ? EDGES.filter((offset) => offset[AXES.indexOf(block.axis)] === 0) : [],
];
return offsets.map(([dx, dy, dz]) => [block.x + dx, block.y + dy, block.z + dz]);
}
+176
View File
@@ -0,0 +1,176 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// rotation spreading through what's connected, like create's RotationPropagator: a block that's placed takes the speed
// of what turns it, a generator's speed spreads to everything it turns, the faster of two takes the other's blocks
// over, and a block that would turn two ways at once breaks. each walk is a queue, not recursion, and runs only when
// something changes. no ctx, the world is anything that keeps these, so tests can give their own
import { type Kinetic, neighbour_positions, speed_ratio } from "./connections.ts";
export type Pos = readonly [number, number, number];
// a kinetic block as the world keeps it
export interface KineticNode extends Kinetic {
// rpm around its axis, counterclockwise seen from the axis's positive end, like getTheoreticalSpeed
readonly speed: number;
// the block next to it it gets its speed from. undefined for a still block, and for a generator turning it
readonly source?: Pos;
// the generator its speed comes from, as "x y z", for telling a loop apart from another network meeting it
readonly network?: string;
// the speed it makes itself, 0 for anything that isn't a generator or one that's still, like getGeneratedSpeed
readonly generated: number;
}
export interface KineticWorld {
// undefined when what's there isn't kinetic
get(x: number, y: number, z: number): KineticNode | undefined;
set(at: Pos, speed: number, source: Pos | undefined, network: string | undefined): void;
// breaks it and drops it, like a shaft turned two ways at once. its on_break runs handle_removed
break(at: Pos): void;
// the fastest anything can turn, like the maxRotationSpeed config
readonly max_speed: number;
}
// a block was placed: it takes the speed of what turns it, and passes it on, like RotationPropagator.handleAdded
export function handle_added(world: KineticWorld, at: Pos) {
spread(world, at);
}
// a block is going: what it turned stops, then what's still turning around that spreads back in, like handleRemoved.
// on_break runs while it's still there, so the walks don't see it
export function handle_removed(world: KineticWorld, at: Pos) {
const node = world.get(...at);
if (!node || node.speed === 0) return;
const without: KineticWorld = {
get: (x, y, z) => x === at[0] && y === at[1] && z === at[2] ? undefined : world.get(x, y, z),
set: (...args) => world.set(...args),
break: (where) => world.break(where),
max_speed: world.max_speed,
};
restart(without, detach(without, node));
}
// a generator's speed changed, like a crank being turned or let go. like GeneratingKineticBlockEntity's
// updateGeneratedRotation
export function update_generated(world: KineticWorld, at: Pos) {
const node = world.get(...at);
if (!node || node.generated === node.speed) return;
const speed = node.generated;
if (speed === 0) {
// something else turns it, so it goes on turning with that
if (node.source) return;
world.set(at, 0, undefined, undefined);
restart(world, detach(world, node));
return;
}
if (node.source && node.speed !== 0 && Math.abs(node.speed) >= Math.abs(speed)) {
// something as fast or faster turns it: it goes along, unless it's turning the other way
if (Math.sign(node.speed) !== Math.sign(speed)) world.break(at);
return;
}
// it turns everything it's connected to, at its own speed. what it turned before stops first, so its old speed
// doesn't meet its new one
world.set(at, speed, undefined, network_of(at));
const stopped = node.speed !== 0 ? detach(world, node) : [];
spread(world, at);
restart(world, stopped);
}
const same = (a: Pos | undefined, b: Pos) => a !== undefined && a[0] === b[0] && a[1] === b[1] && a[2] === b[2];
const pos_of = (node: Kinetic): Pos => [node.x, node.y, node.z];
const network_of = (at: Pos) => at.join(" ");
// the kinetic blocks next to node that turn it or that it turns, like getConnectedNeighbours
function connected(world: KineticWorld, node: Kinetic): KineticNode[] {
return neighbour_positions(node).flatMap(([x, y, z]) => {
const neighbour = world.get(x, y, z);
const turns = neighbour && (speed_ratio(node, neighbour) !== 0 || speed_ratio(neighbour, node) !== 0);
return turns ? [neighbour] : [];
});
}
// spreads the speed at start to what it's connected to, and on through whatever that changes, like
// propagateNewSource
function spread(world: KineticWorld, start: Pos) {
const queue: Pos[] = [start];
for (let i = 0; i < queue.length; i++) {
const at = queue[i];
const current = world.get(...at);
if (!current) continue;
for (const neighbour of connected(world, current)) {
const new_speed = current.speed * speed_ratio(current, neighbour);
const opposite_speed = neighbour.speed * speed_ratio(neighbour, current);
if (new_speed === 0 && opposite_speed === 0) continue;
const against = new_speed !== 0 && neighbour.speed !== 0 &&
Math.sign(new_speed) !== Math.sign(neighbour.speed);
const too_fast = Math.abs(new_speed) > world.max_speed || Math.abs(opposite_speed) > world.max_speed;
if (against || too_fast) {
world.break(at);
break;
}
// the neighbour is faster, so it turns this one, which passes that on from here
if (Math.abs(opposite_speed) > Math.abs(current.speed)) {
world.set(at, opposite_speed, pos_of(neighbour), neighbour.network);
queue.push(at);
break;
}
// this one is at least as fast, so it takes over everything the neighbour turns. unless the same generator
// turns both, which is a loop: fine while the speeds agree, and this breaks when they don't
const loop = current.network === undefined || current.network === neighbour.network;
if (Math.abs(new_speed) >= Math.abs(neighbour.speed) && loop) {
if (Math.abs(new_speed) > Math.abs(neighbour.speed) * (1 + 1 / 65536)) {
world.break(at);
break;
}
continue;
}
if (Math.abs(new_speed) < Math.abs(neighbour.speed) && Math.abs(neighbour.speed - new_speed) <= 1e-4) {
continue;
}
world.set(pos_of(neighbour), new_speed, at, current.network);
queue.push(pos_of(neighbour));
}
}
}
// the blocks node turned stop, like the removed or stopped block's part of RotationPropagator.handleRemoved. returns
// the generators among them, see restart
function detach(world: KineticWorld, node: Kinetic): Pos[] {
const at = pos_of(node);
return neighbour_positions(node).flatMap((where) =>
same(world.get(...where)?.source, at) ? clear(world, where) : []
);
}
// generators that stopped with what turned them start again with their own speed, like reActivateSource. that's a
// tick later in create, so here it's after the walk that stopped them, when what's turning around them has settled
function restart(world: KineticWorld, generators: Pos[]) {
for (const at of generators) update_generated(world, at);
}
// stops start and everything that got its speed through it, then lets what's still turning at the edges spread back
// in, like propagateMissingSource. returns the generators in it
function clear(world: KineticWorld, start: Pos): Pos[] {
const missing = world.get(...start)?.source;
const edges: Pos[] = [];
const generators: Pos[] = [];
const frontier: Pos[] = [start];
for (let i = 0; i < frontier.length; i++) {
const at = frontier[i];
const current = world.get(...at);
if (!current) continue;
world.set(at, 0, undefined, undefined);
if (current.generated !== 0) generators.push(at);
for (const neighbour of connected(world, current)) {
const where = pos_of(neighbour);
if (same(missing, where) || !neighbour.source) continue;
if (same(neighbour.source, at)) frontier.push(where);
else edges.push(where);
}
}
// an edge can turn out to be part of what stopped, found from another side later
const edge = edges.find((at) => world.get(...at)?.source !== undefined);
if (edge) spread(world, edge);
return generators;
}
+129
View File
@@ -0,0 +1,129 @@
// 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
import type { BlockRef, 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";
interface Config {
max_speed: number;
crank_hunger: number;
}
// a kinetic block's tile data, see KineticNode. its speed is its "speed" client data, which its visual turns it by
interface KineticData {
source?: Pos;
network?: string;
}
// the create:hand_crank component's params: the rpm it turns at
interface CrankParams {
speed: number;
}
// how long a crank keeps turning after each click, in ticks. holding use clicks every 4
const CRANK_USE_TICKS = 10;
interface CrankData extends KineticData {
// ticks left turning
in_use?: number;
// turned the other way, by sneaking
backwards?: boolean;
}
export function setup(ctx: ServerContext) {
const config: Config = ctx.config;
const world = kinetic_world(ctx, config);
ctx.components.register_block<KineticParams>("create:kinetic", {
on_create(block) {
handle_added(world, [block.x, block.y, block.z]);
},
on_break(block) {
handle_removed(world, [block.x, block.y, block.z]);
},
});
// turns while it's being clicked, a little longer each click, and the other way while sneaking, like create's
// HandCrankBlock and HandCrankBlockEntity. turning it makes the player hungry
ctx.components.register_block<CrankParams>("create:hand_crank", {
on_interact(block, params, player) {
const data: CrankData = block.data ?? {};
const backwards = player.is_sneaking();
const changed = !data.in_use || backwards !== (data.backwards ?? false);
block.data = { ...data, in_use: CRANK_USE_TICKS, backwards };
block.set_ticking(true);
if (changed) update_generated(world, [block.x, block.y, block.z]);
player.add_exhaustion(params.speed * config.crank_hunger);
return true;
},
on_tick(block) {
const data: CrankData = block.data ?? {};
const in_use = Math.max(0, (data.in_use ?? 0) - 1);
block.data = { ...data, in_use };
if (in_use > 0) return;
block.set_ticking(false);
update_generated(world, [block.x, block.y, block.z]);
},
});
}
// the world as rotation spreading sees it: blocks with create:kinetic, their speed in client data and where it comes
// from in tile data
function kinetic_world(ctx: ServerContext, config: Config): KineticWorld {
// components never change once loaded, so each block's are looked up once
const params = new Map<Id, { kinetic?: KineticParams; crank?: CrankParams }>();
const params_of = (id: Id) => {
let found = params.get(id);
if (!found) {
const components = ctx.blocks.components(id);
found = {
kinetic: components["create:kinetic"] as KineticParams | undefined,
crank: components["create:hand_crank"] as CrankParams | undefined,
};
params.set(id, found);
}
return found;
};
const block_at = (at: Pos): BlockRef => {
const block = ctx.world.get_block_ref(...at);
if (!block) throw new Error(`there's no kinetic block at ${at.join(" ")}`);
return block;
};
return {
get(x, y, z) {
const block = ctx.world.get_block_ref(x, y, z);
if (!block) return undefined;
const { kinetic, crank } = params_of(block.id);
if (!kinetic) return undefined;
const shape = kinetic_shape(kinetic, (name) => ctx.world.get_state(x, y, z, name));
const data: CrankData = block.data ?? {};
// a crank turns counterclockwise seen from its handle, or the other way while sneaking
const generated = crank && data.in_use && shape.facing
? along(shape.facing, data.backwards ? -crank.speed : crank.speed)
: 0;
return {
x,
y,
z,
...shape,
speed: block.get_client_data<number>("speed") ?? 0,
source: data.source,
network: data.network,
generated,
};
},
set(at, speed, source, network) {
const block = block_at(at);
block.set_client_data("speed", speed === 0 ? undefined : speed);
const { source: _, network: __, ...rest }: KineticData = block.data ?? {};
block.data = { ...rest, ...(source && { source }), ...(network !== undefined && { network }) };
},
break(at) {
ctx.world.break_block(...at);
},
max_speed: config.max_speed,
};
}
+101
View File
@@ -0,0 +1,101 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// how create's blocks are placed, on the server and on every client: kinetic blocks line up with the axles they're
// placed against
import type { BlockPlacement, Face, SharedContext } from "bworld/shared";
import {
AXES,
type Axis,
face_axis,
FACE_OFFSETS,
FACINGS,
kinetic_shape,
type KineticParams,
type KineticShape,
OPPOSITE,
} from "./kinetics/connections.ts";
export function setup(ctx: SharedContext) {
// what turns at x y z, undefined when nothing does
const kinetic_at = (x: number, y: number, z: number): KineticShape | undefined => {
const id = ctx.world.get_block(x, y, z);
const params = id && ctx.blocks.exists(id)
? ctx.blocks.components(id)["create:kinetic"] as KineticParams | undefined
: undefined;
return params && kinetic_shape(params, (name) => ctx.world.get_state(x, y, z, name));
};
const beside = (x: number, y: number, z: number, side: Face) => {
const [dx, dy, dz] = FACE_OFFSETS[side];
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 => {
let found: Face | undefined;
for (const side of FACINGS) {
if (!beside(x, y, z, side)?.shafts.includes(OPPOSITE[side])) continue;
if (found && face_axis(found) !== face_axis(side)) return undefined;
found = side;
}
return found;
};
// a cog lines up with the small cog it's placed against, or the axle beside it, or else the face it's clicked onto,
// which is all sneaking looks at, like CogWheelBlock.getAxisForPlacement
const cog_axis = (placement: BlockPlacement): Axis => {
const { x, y, z, face } = placement;
if (placement.sneaking) return face_axis(face);
const against = beside(x, y, z, OPPOSITE[face]);
if (against?.cog === "small") return against.axis;
const side = axle_beside(x, y, z);
return face_axis(side ?? face);
};
// whether a cog on axis at x y z keeps clear of the cogs beside it: a large one's teeth would cut into any cog
// beside it across its axis, and a small one's into a large one, unless that one's axis points at it. like
// isValidCogwheelPosition
const cog_fits = (x: number, y: number, z: number, axis: Axis, cog: "small" | "large") =>
FACINGS.every((side) => {
const other = beside(x, y, z, side);
if (face_axis(side) === axis || !other?.cog || other.axis === face_axis(side)) return true;
return other.cog === "small" && cog === "small";
});
// a block with an axis lines up with the axle it's placed against, or sneaking, with the face it's clicked onto.
// otherwise it points the way the player looks, like RotatedPillarKineticBlock. a block with a facing faces away
// from the axle, or toward the player, or away from them while sneaking, like DirectionalKineticBlock. cogs are
// placed their own way, see cog_axis
ctx.components.register_block<KineticParams>("create:kinetic", {
state_for_placement(placement, params) {
if (params.cog) {
const axis = cog_axis(placement);
if (!cog_fits(placement.x, placement.y, placement.z, axis, params.cog)) return false;
return { [params.axis ?? "axis"]: AXES.indexOf(axis) };
}
const side = axle_beside(placement.x, placement.y, placement.z);
if (params.facing !== undefined) {
const facing = side && !placement.sneaking
? OPPOSITE[side]
: placement.sneaking
? placement.looking
: OPPOSITE[placement.looking];
return { [params.facing]: FACINGS.indexOf(facing) };
}
const axis = side && !placement.sneaking
? face_axis(side)
: side
? face_axis(placement.face)
: face_axis(placement.looking);
return { [params.axis ?? "axis"]: AXES.indexOf(axis) };
},
});
// a crank faces away from what it's placed on, unless there's an axle beside it to turn, like HandCrankBlock
ctx.components.register_block("create:hand_crank", {
state_for_placement(placement) {
const side = axle_beside(placement.x, placement.y, placement.z);
return { facing: FACINGS.indexOf(side && !placement.sneaking ? OPPOSITE[side] : placement.face) };
},
});
}
+14 -8
View File
@@ -1212,16 +1212,22 @@ export class GameServer {
}
// solid blocks can't go where a mob or player is, the one placing it included, like minecraft
const placing = EverythingRegistry.get<BlockRegistry>("blocks", held.block_id)!;
const ruled_value = this.mods.rules.placement_value(placing, player.yaw, player.pitch, {
x: tx,
y: ty,
z: tz,
face,
hit: [hit[0], hit[1], hit[2]],
sneaking: player.sneaking,
});
// its rules say it can't go there
if (ruled_value === undefined) {
this.#correct(player, tx, ty, tz);
return;
}
// put into a source of the liquid it can hold, it holds it
const placed_value = waterlog_placement(
this.mods.rules.placement_value(placing, player.yaw, {
x: tx,
y: ty,
z: tz,
face,
hit: [hit[0], hit[1], hit[2]],
sneaking: player.sneaking,
}),
ruled_value,
placing,
this.world.get_block_value(tx, ty, tz),
this.world.get_block_info(tx, ty, tz),
+6 -1
View File
@@ -254,11 +254,12 @@ export class ModRuntime {
if (typeof module.setup !== "function") {
throw new ModLoadError(mod, "the shared script doesn't export a setup function");
}
const { world } = this.#context(mod, version, config);
const { world, blocks } = this.#context(mod, version, config);
const ctx: SharedContext = {
mod: { id: mod, version },
side: "server",
tags: tag_api(),
blocks,
world: {
get_block: world.get_block,
get_state: world.get_state,
@@ -697,6 +698,10 @@ export class ModRuntime {
},
is_face_sturdy: (x, y, z, face) => covers_face(game().world.collision_shape(x, y, z), face),
get_block_data: (x, y, z) => game().world.get_tile(x, y, z)?.mod_data as never,
get_block_ref: (x, y, z) => {
const id = game().world.get_block_id(x, y, z);
return id === AIR_ID ? undefined : this.block_ref(x, y, z, id);
},
set_block_ticking: (x, y, z, ticking) => game().set_tile_ticking(x, y, z, ticking),
set_block_item: (x, y, z, item) => {
const shown = item && item.count > 0 ? new_stack(item).to_data() : undefined;
+373
View File
@@ -0,0 +1,373 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// 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 };
}
// 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>) {
const t = await setup(config);
t.place(0, 100, 0, "create:hand_crank", "facing", FACING.west);
for (let x = 1; x <= length; x++) t.place(x, 100, 0, "create:shaft", "axis", AXIS.x);
return t;
}
const line = (t: { speed: (x: number, y: number, z: number) => number }, from: number, to: number) =>
Array.from({ length: to - from + 1 }, (_, i) => t.speed(from + i, 100, 0));
Deno.test("a hand crank turns the line of shafts on its axle while it's being clicked, then it stops", async () => {
const t = await crank_and_line();
// a shaft across the line, and one past a gap, aren't turned
t.place(2, 100, 1, "create:shaft", "axis", AXIS.z);
t.place(6, 100, 0, "create:shaft", "axis", AXIS.x);
// facing west, it turns counterclockwise seen from the west, which is clockwise around x
t.use(0, 100, 0);
assertEquals(line(t, 0, 4), [-t.crank, -t.crank, -t.crank, -t.crank, -t.crank]);
assertEquals([t.speed(2, 100, 1), t.speed(6, 100, 0)], [0, 0]);
// holding use clicks every 4 ticks, which keeps it going
for (let i = 0; i < 10; i++) {
t.ticks(4);
t.use(0, 100, 0);
}
assertEquals(t.speed(4, 100, 0), -t.crank);
t.ticks(40);
assertEquals(line(t, 0, 4), [0, 0, 0, 0, 0]);
// still, nothing ticks
assertEquals(t.game.world.ticks(t.game.world.get_tile(0, 100, 0)!), false);
});
Deno.test("sneaking turns a crank the other way", async () => {
const t = await crank_and_line();
t.move(true);
t.use(0, 100, 0);
assertEquals(line(t, 0, 4), [t.crank, t.crank, t.crank, t.crank, t.crank]);
// turning it the other way while it turns turns the whole line around
t.move(false);
t.use(0, 100, 0);
assertEquals(line(t, 0, 4), [-t.crank, -t.crank, -t.crank, -t.crank, -t.crank]);
});
Deno.test("a shaft placed on a turning line turns with it, and breaking one stops what's past it", async () => {
const t = await crank_and_line();
t.use(0, 100, 0);
t.place(5, 100, 0, "create:shaft", "axis", AXIS.x);
assertEquals(t.speed(5, 100, 0), -t.crank);
t.game.destroy_block(2, 100, 0);
assertEquals(line(t, 0, 5), [-t.crank, -t.crank, 0, 0, 0, 0]);
// put back, it joins them up again
t.place(2, 100, 0, "create:shaft", "axis", AXIS.x);
assertEquals(line(t, 0, 5), [-t.crank, -t.crank, -t.crank, -t.crank, -t.crank, -t.crank]);
// breaking the crank stops all of it
t.game.destroy_block(0, 100, 0);
assertEquals(line(t, 1, 5), [0, 0, 0, 0, 0]);
});
Deno.test("a crank turned against a line another one turns breaks, and drops", async () => {
const t = await crank_and_line(4);
// at the other end, facing east, where turning it turns the line the other way around x
t.place(5, 100, 0, "create:hand_crank", "facing", FACING.east);
t.use(0, 100, 0);
t.use(5, 100, 0);
assertEquals(t.game.world.get_block_id(5, 100, 0), AIR_ID);
assert(t.game.item_entities().some((e) => e.item.type_id === "create:hand_crank"));
assertEquals(line(t, 0, 4), [-t.crank, -t.crank, -t.crank, -t.crank, -t.crank]);
});
Deno.test("two cranks turning a line the same way turn it together, and either keeps it going", async () => {
const t = await crank_and_line(4);
t.place(5, 100, 0, "create:hand_crank", "facing", FACING.east);
t.use(0, 100, 0);
// sneaking turns this one the same way around x as the first
t.move(true);
t.use(5, 100, 0);
assertEquals(t.game.world.get_block_id(5, 100, 0), "create:hand_crank");
assertEquals(line(t, 0, 5), [-t.crank, -t.crank, -t.crank, -t.crank, -t.crank, -t.crank]);
// the first one let go, the second keeps the line turning on its own
for (let i = 0; i < 10; i++) {
t.ticks(4);
t.use(5, 100, 0);
}
assertEquals(line(t, 0, 5), [-t.crank, -t.crank, -t.crank, -t.crank, -t.crank, -t.crank]);
t.ticks(40);
assertEquals(line(t, 0, 5), [0, 0, 0, 0, 0, 0]);
});
Deno.test("a crank that would turn things faster than create's max_speed breaks", async () => {
const t = await crank_and_line(2, { max_speed: 16 });
t.use(0, 100, 0);
assertEquals(t.game.world.get_block_id(0, 100, 0), AIR_ID);
assertEquals(line(t, 1, 2), [0, 0]);
});
Deno.test("turning a crank makes the player hungry", async () => {
const t = await crank_and_line();
const player = t.game.mods.player(t.game.players()[0]);
const before = player.saturation + player.food;
for (let i = 0; i < 100; i++) {
t.use(0, 100, 0);
t.ticks(4);
}
assert(player.saturation + player.food < before);
});
Deno.test("speeds are saved, and a crank still stops after the world is loaded", async () => {
const t = await crank_and_line();
t.use(0, 100, 0);
const loaded = await test_game("mods", t.game.save());
loaded.join(1, "alice");
const speed = (x: number) => loaded.game.world.get_tile(x, 100, 0)?.client_data?.speed as number ?? 0;
assertEquals(speed(3), -t.crank);
for (let i = 0; i < 40; i++) loaded.game.tick();
assertEquals(speed(3), 0);
});
Deno.test("a shaft lines up with the axle it's placed against, and otherwise points the way the player looks", async () => {
const t = await setup();
t.send(1, { type: "chat", text: "/give create:shaft 64" });
t.send(1, { type: "chat", text: "/give create:hand_crank 64" });
t.send(1, { type: "select_slot", slot: 0 });
// on the floor, looking north and then down
t.use(-2, 99, 0, "top");
assertEquals(t.state(-2, 100, 0, "axis"), AXIS.z);
t.move(false, -1.4);
t.use(-3, 99, 0, "top");
assertEquals(t.state(-3, 100, 0, "axis"), AXIS.y);
// beside the back of a crank facing west, along its axle
t.move();
t.place(0, 100, 0, "create:hand_crank", "facing", FACING.west);
t.use(1, 99, 0, "top");
assertEquals(t.state(1, 100, 0, "axis"), AXIS.x);
// a crank faces away from what it's placed on, or away from an axle beside it, so it turns it
t.send(1, { type: "select_slot", slot: 1 });
t.use(-1, 99, 1, "top");
assertEquals(t.state(-1, 100, 1, "facing"), FACING.up);
t.use(2, 99, 0, "top");
assertEquals(t.state(2, 100, 0, "facing"), FACING.east);
});
Deno.test("small cogs side by side on the same axis turn each other the other way", async () => {
const t = await setup();
t.place(0, 100, 0, "create:hand_crank", "facing", FACING.west);
// a square of them across the crank's axle, and one on another axis beside it
for (const [y, z] of [[100, 0], [101, 0], [100, 1], [101, 1]]) t.place(1, y, z, "create:cogwheel", "axis", AXIS.x);
t.place(1, 100, -1, "create:cogwheel", "axis", AXIS.z);
t.use(0, 100, 0);
const c = t.crank;
assertEquals([t.speed(1, 100, 0), t.speed(1, 101, 0), t.speed(1, 100, 1), t.speed(1, 101, 1)], [-c, c, c, -c]);
assertEquals(t.speed(1, 100, -1), 0);
// the square is a loop that agrees with itself, so it stops cleanly too
t.ticks(40);
assertEquals([t.speed(1, 100, 0), t.speed(1, 101, 0), t.speed(1, 100, 1), t.speed(1, 101, 1)], [0, 0, 0, 0]);
assertEquals(t.game.world.get_block_id(1, 101, 1), "create:cogwheel");
});
Deno.test("a large cog turns a small one at its corner twice as fast, and a small one turns it half as fast", async () => {
const t = await setup();
t.place(0, 100, 0, "create:hand_crank", "facing", FACING.west);
t.place(1, 100, 0, "create:large_cogwheel", "axis", AXIS.x);
t.place(1, 101, 1, "create:cogwheel", "axis", AXIS.x);
// at another corner, but on another axis
t.place(1, 101, -1, "create:cogwheel", "axis", AXIS.y);
t.use(0, 100, 0);
assertEquals([t.speed(1, 100, 0), t.speed(1, 101, 1), t.speed(1, 101, -1)], [-t.crank, 2 * t.crank, 0]);
const u = await setup();
u.place(0, 100, 0, "create:hand_crank", "facing", FACING.west);
u.place(1, 100, 0, "create:cogwheel", "axis", AXIS.x);
u.place(1, 101, 1, "create:large_cogwheel", "axis", AXIS.x);
u.use(0, 100, 0);
assertEquals([u.speed(1, 100, 0), u.speed(1, 101, 1)], [-u.crank, u.crank / 2]);
});
Deno.test("large cogs on different axes turn each other across an edge", async () => {
const t = await setup();
t.place(0, 100, 0, "create:hand_crank", "facing", FACING.west);
t.place(1, 100, 0, "create:large_cogwheel", "axis", AXIS.x);
t.place(2, 101, 0, "create:large_cogwheel", "axis", AXIS.y);
// on the same axis they don't
t.place(1, 101, 1, "create:large_cogwheel", "axis", AXIS.x);
t.use(0, 100, 0);
assertEquals(Math.abs(t.speed(2, 101, 0)), t.crank);
assertEquals(t.speed(1, 101, 1), 0);
});
Deno.test("cogs that would turn something faster than create's max_speed break", async () => {
const t = await setup({ max_speed: 48 });
t.place(0, 100, 0, "create:hand_crank", "facing", FACING.west);
t.place(1, 100, 0, "create:large_cogwheel", "axis", AXIS.x);
t.place(1, 101, 1, "create:cogwheel", "axis", AXIS.x);
t.use(0, 100, 0);
const blocks = [[0, 100, 0], [1, 100, 0], [1, 101, 1]] as const;
assert(blocks.some(([x, y, z]) => t.game.world.get_block_id(x, y, z) === AIR_ID));
for (const [x, y, z] of blocks) assert(Math.abs(t.speed(x, y, z)) <= 48);
});
Deno.test("a cog lines up with the cog it's placed against, and can't go where it would cut into another", async () => {
const t = await setup();
t.send(1, { type: "chat", text: "/give create:cogwheel 64" });
t.send(1, { type: "chat", text: "/give create:large_cogwheel 64" });
t.send(1, { type: "select_slot", slot: 0 });
const held = () => t.game.players()[0].held_item?.amount;
// on the floor it lies flat, and one placed against its side lies flat with it
t.use(0, 99, 0, "top");
assertEquals(t.state(0, 100, 0, "axis"), AXIS.y);
t.use(0, 100, 0, "west");
assertEquals(t.state(-1, 100, 0, "axis"), AXIS.y);
// sneaking, it takes the axis of the face it's clicked onto
t.move(true);
t.use(0, 100, 0, "north");
assertEquals(t.state(0, 100, -1, "axis"), AXIS.z);
t.move();
// a large cog's teeth would cut into the small one beside it, but at its corner they mesh
t.send(1, { type: "select_slot", slot: 1 });
t.use(1, 99, 0, "top");
assertEquals(t.game.world.get_block_id(1, 100, 0), AIR_ID);
assertEquals(held(), 64);
t.use(1, 99, 1, "top");
assertEquals(t.game.world.get_block_id(1, 100, 1), "create:large_cogwheel");
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
assertEquals(turns.get("own")!.slice(0, 2), ["z", 16]);
data.speed = -64;
visual.update!();
assertEquals(turns.get("own")!.slice(0, 2), ["z", -64]);
});
Deno.test("a crank's handle catches up with the speed it turns at, and slows to a stop", async () => {
const { visual, turns, data } = await visual_for("create:hand_crank", { facing: FACING.west }, { speed: -32 });
assertEquals(turns.get("own")!.slice(0, 2), ["x", -32]);
const handle = () => [...turns].find(([model]) => model.includes("handle"))![1];
// degrees it turned by in a tick, after time ticks
let time = 0;
const step = () => {
const before = handle()[2];
visual.on_frame!(++time);
return ((handle()[2] - before) % 360 + 540) % 360 - 180;
};
visual.on_frame!(time);
const first = step();
for (let i = 0; i < 40; i++) step();
// it turns the same way as the shaft, around x, faster once it's caught up
assertEquals(handle()[0], "x");
assert(first < 0 && step() < first, `${first}`);
data.speed = undefined;
visual.update!();
const slowing = step();
assert(slowing < 0, `${slowing}`);
for (let i = 0; i < 100; i++) step();
assert(Math.abs(step()) < 0.01);
});
Deno.test("small cogs beside each other are turned half a tooth apart, so they mesh", async () => {
const offset = async (x: number) =>
(await visual_for("create:cogwheel", { axis: AXIS.y }, {}, [x, 100, 0])).turns.get("own")![2];
assertEquals(Math.abs(await offset(0) - await offset(1)), 22.5);
});
Deno.test("a large cog is drawn as its cog and its shaft, both turning at its speed", async () => {
const { visual, turns, data } = await visual_for("create:large_cogwheel", { axis: AXIS.z }, { speed: 8 }, [
1,
0,
0,
]);
const [cog, shaft] = ["shaftless", 'shaft"'].map((part) => [...turns].find(([model]) => model.includes(part))![1]);
assertEquals([cog.slice(0, 2), shaft.slice(0, 2)], [["z", 8], ["z", 8]]);
// where a small cog wouldn't be offset, it's offset by half its own tooth, and its shaft lines up with other shafts
assertEquals([cog[2], shaft[2]], [11.25, 0]);
data.speed = -8;
visual.update!();
assertEquals(turns.size, 2);
assert([...turns.values()].every(([, rpm]) => rpm === -8));
});
+22
View File
@@ -294,6 +294,28 @@ Deno.test("a blockstate's variants become numbered states, each drawn with its m
assertEquals(block.drops, "gears:shaft");
});
Deno.test("a block table gives blocks what java sets in code, over the placeholders", () => {
const files = {
"blockstates/crank": { variants: { "": { model: "gears:block/crank" } } },
"models/block/crank": GEAR,
};
const output = Deno.makeTempDirSync();
const components = { "gears:turns": { speed: 32 } };
const report = import_blocks(assets(files), {
output,
blocks: { "gears:crank": { components, mining: { toughness: 2 } } },
});
assertEquals(report.errors, []);
const { block } = JSON.parse(Deno.readTextFileSync(`${output}/crank.json`));
assertEquals(validate_block(block), []);
assertEquals(block.components, components);
assertEquals(block.mining, { toughness: 2 });
// a block the table names that wasn't made is an error, so a typo can't go unnoticed
const typo = import_blocks(assets(files), { output, blocks: { "gears:cranck": { components } } });
assertEquals(typo.errors.map(({ location }) => location), ["gears:cranck"]);
});
Deno.test("uvlock carries over, so turned textures stay where they are on an unturned block", () => {
const { block, report } = import_block({
"blockstates/steps": {
+6 -2
View File
@@ -77,6 +77,10 @@ function client_of(t: Game) {
mod: { id: "bworld", version: "test" },
side: "client",
tags: tag_api(),
blocks: {
exists: (id) => info(id) !== undefined,
components: (id) => structuredClone(info(id)!.components ?? {}),
},
world,
components: { register_block: (id, block_rules) => rules.register("bworld", id, block_rules) },
});
@@ -84,8 +88,8 @@ function client_of(t: Game) {
return {
// what game_mode does when this client places held against face of x y z, at hit
place(id: string, x: number, y: number, z: number, yaw: number, face: Face, hit: [number, number, number]) {
const value = rules.placement_value(info(id)!, yaw, { x, y, z, face, hit, sneaking: false });
copy.set(`${x} ${y} ${z}`, [id, value >>> 16]);
const value = rules.placement_value(info(id)!, yaw, 0, { x, y, z, face, hit, sneaking: false });
copy.set(`${x} ${y} ${z}`, [id, value! >>> 16]);
rules.notify_neighbors(world.get_block, x, y, z);
},
// what game_mode does when this client right clicks face of x y z, at hit. whether the rules did something
+5 -2
View File
@@ -46,7 +46,9 @@ options:
{ "textures": { "minecraft:block/": "bworld:" }, "models": {}, "ids": {}, "tags": {},
"skip": ["crimson"] }
minecraft's block and item textures, blocks, items and tags become bworld's of the same name,
and forge's shared tags c's, unless it says otherwise`;
and forge's shared tags c's, unless it says otherwise
--blocks FILE json of fields blocks get by id, over the placeholders, for blockstate. what java sets in
code, like components and mining: { "gears:shaft": { "components": {...} } }`;
function parse_args(args: string[]) {
const positional: string[] = [];
@@ -70,7 +72,8 @@ function parse_args(args: string[]) {
tags: { ...DEFAULT_REMAPS.tags, ...remap.tags },
...(remap.skip ? { skip: remap.skip } : {}),
};
} else if (arg.startsWith("--")) throw new Error(`unknown option ${arg}`);
} else if (arg === "--blocks") options.blocks = JSON.parse(Deno.readTextFileSync(value()));
else if (arg.startsWith("--")) throw new Error(`unknown option ${arg}`);
else positional.push(arg);
}
return { positional, options };
+9 -1
View File
@@ -4,7 +4,7 @@
// java blockstates (assets/<namespace>/blockstates/*.json) to bworld's blocks/, so a mod's blocks can be placed and look
// right: their states, and the model each state is drawn with, turned. how a block behaves isn't in any data file (java
// mods set mining, sounds and what blocks do in code), so every block gets the same placeholders: a second to break with
// anything, dropping itself
// anything, dropping itself. --blocks gives some of them more, see ImportOptions.blocks
import { dirname, join } from "@std/path";
import { FORMAT_VERSION } from "$/common/mod_data.ts";
import { is_empty, made_by, model_source, type ModelSource } from "./models.ts";
@@ -95,11 +95,19 @@ export function import_blocks(input: string, options: ImportOptions = {}): Impor
const result = convert_blockstate(location, json, read, remaps);
if (result.kind === "error") report.errors.push({ location, problems: result.problems });
else if (claim(result.id, location)) {
Object.assign(result.json.block, options.blocks?.[result.id]);
for (const warning of result.warnings) report.warnings.push({ location, warning });
const text = format_json(result.json) + "\n";
report.written.push({ location, id: result.id, file: join(options.output, `${where.path}.json`), text });
}
}
// a typo in the table would otherwise quietly give a block nothing
const written = new Set(report.written.map(({ id }) => id));
for (const id of Object.keys(options.blocks ?? {})) {
if (!written.has(id)) {
report.errors.push({ location: id, problems: ["--blocks has it, but no block was made for it"] });
}
}
write_report(report);
return report;
}
+3
View File
@@ -253,6 +253,9 @@ export interface ImportOptions {
// more folders to look things up in, like parent models from another mod
parents?: string[];
remaps?: Remaps;
// fields blocks get by id, over the placeholders, like their components or how long they take to mine. java sets
// those in code, so a mod's import keeps them in a table, like mods/create/import/blocks.json
blocks?: Record<string, Record<string, unknown>>;
}
// one file an import makes: text to write, or a file to copy