Mechanical press !

This commit is contained in:
2026-10-15 13:07:09 -03:00
parent b43e8fe8b8
commit c7a2392591
15 changed files with 403 additions and 86 deletions
+33 -1
View File
@@ -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";
+33
View File
@@ -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);
}
+14
View File
@@ -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 }] : [];
});
}
+93 -5
View File
@@ -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 }) };
+9 -4
View File
@@ -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