// 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), the generators that turn it (the hand crank, // the creative motor and the water wheel), the mechanical press and the basin import type { BlockRef, EntityRef, FluidVariant, Id, ItemStack, ServerContext } from "bworld/server"; import { actual_speed, along, face_axis, FACE_OFFSETS, FACINGS, kinetic_shape, type KineticParams, OPPOSITE, type Pos, positive, source_face, } from "./kinetics/connections.ts"; import { flow_score, motor_step } from "./kinetics/generators.ts"; import { handle_added, handle_removed, type KineticWorld, update_generated } from "./kinetics/spreading.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"; import { type BasinTank, drain, fill, insert_item } from "./processing/basin.ts"; interface Config { max_speed: number; crank_hunger: number; // by block id, what each block takes per rpm and what each generator makes per rpm, like create's CStress. 0 for a // block that isn't there stress: { impact: Record; capacity: Record }; } // a kinetic block's tile data, see KineticNode. its speed is its "speed" client data, and whether its network is // overstressed its "overstressed" client data, which its visual turns it by interface KineticData { source?: Pos; network?: string; } // a generator's params, for create:hand_crank, create:creative_motor and create:water_wheel: the rpm it turns at, or // the motor's to start with interface GeneratorParams { 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; } interface MotorData extends KineticData { // rpm, counterclockwise seen from its shaft's end. its params' speed until it's scrolled speed?: number; } interface WheelData extends KineticData { // which way the water turns it, see flow_score flow?: number; } 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 const pressing = processing_recipes(ctx.recipes.list(PRESSING.id), PRESSING, { expand: (choice) => ctx.tags.expand(choice), item_exists: (id) => ctx.items.exists(id), }); ctx.components.register_block("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]); }, // states that change how it turns things, like a clutch being powered or a chain drive joining a line, take it // out and put it back, like Create's detachKinetics and attachKinetics on a change that isn't // areStatesKineticallyEquivalent on_state_change(block, params, before) { const now = kinetic_shape(params, (name) => ctx.world.get_state(block.x, block.y, block.z, name)); if (JSON.stringify(now) === JSON.stringify(kinetic_shape(params, (name) => before[name]))) return; handle_removed(world, [block.x, block.y, block.z]); handle_added(world, [block.x, block.y, block.z]); }, }); // a shaft or cog right clicked with a casing becomes the encased one, by the casing's id, turned the same way. an // encased cog gets an axle out of its casing toward each axle beside it. the casing isn't used up. like // EncasableBlock.tryEncase and handleEncasing ctx.components.register_block>("create:encasable", { on_interact(block, params, player) { const into = params[player.held_item?.id ?? ""]; const node = world.get(block.x, block.y, block.z); if (!into || !node) return false; const own = ctx.blocks.components(block.id)["create:kinetic"] as KineticParams; const encased = ctx.blocks.components(into)["create:kinetic"] as KineticParams; const states = { [encased.axis ?? "axis"]: ctx.world.get_state(block.x, block.y, block.z, own.axis ?? "axis")!, }; for (const side of FACINGS) { if (!encased.shaft_states || face_axis(side) !== node.axis) continue; const [dx, dy, dz] = FACE_OFFSETS[side]; const axle = world.get(block.x + dx, block.y + dy, block.z + dz)?.shafts.includes(OPPOSITE[side]); states[encased.shaft_states[positive(side) ? 0 : 1]] = axle ? 1 : 0; } ctx.world.set_block(block.x, block.y, block.z, into, states); return true; }, }); // 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("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]); }, }); // turns at any speed, set by scrolling the mouse wheel at it, finer while sneaking, like create's // CreativeMotorBlockEntity with the 0.5 step ctx.components.register_block("create:creative_motor", { on_create(block) { update_generated(world, [block.x, block.y, block.z]); }, on_scroll(block, params, player, scroll) { const data: MotorData = block.data ?? {}; let speed = data.speed ?? params.speed; for (let i = 0; i < Math.abs(scroll.amount); i++) { speed = motor_step(speed, scroll.amount > 0, player.is_sneaking(), config.max_speed); } player.send_message(`Speed: ${speed} rpm`, { overlay: true }); if (speed === (data.speed ?? params.speed)) return; block.data = { ...data, speed }; update_generated(world, [block.x, block.y, block.z]); }, }); // turned by fluid flowing past its sides, see flow_score. it looks again when something beside it changes, a tick // later once that's settled, and every second, since water can change which way it flows without that, like // WaterWheelBlock and WaterWheelBlockEntity's lazy tick const update_flow = (block: BlockRef) => { const { axis } = world.get(block.x, block.y, block.z)!; const flow = flow_score(axis, [block.x, block.y, block.z], (x, y, z) => ctx.world.fluid_flow(x, y, z)); const data: WheelData = block.data ?? {}; // kept even when it's 0, so the wheel has data and ticks if (data.flow === flow) return; block.data = { ...data, flow }; update_generated(world, [block.x, block.y, block.z]); }; ctx.components.register_block("create:water_wheel", { on_create: update_flow, on_neighbor_change(block) { if (!ctx.world.has_scheduled_tick(block.x, block.y, block.z)) { ctx.world.schedule_tick(block.x, block.y, block.z, 1); } }, on_scheduled_tick: update_flow, on_second: update_flow, }); register_press(ctx, pressing); register_basin(ctx); } // holds items dropped into it and fluid poured in, like create's BasinBlock: an item that lands in it goes in, a full // fluid container used on it empties into it and an empty one fills from it, and an empty hand takes every item out. // what's in it is its "items" and "tanks" client data, kept nowhere else, which its visual draws. breaking it drops // the items, and the fluid is lost function register_basin(ctx: ServerContext) { const items_of = (block: BlockRef) => block.get_client_data("items") ?? []; const tanks_of = (block: BlockRef) => block.get_client_data("tanks") ?? []; const set_items = (block: BlockRef, items: readonly ItemStack[]) => block.set_client_data("items", items.length > 0 ? items : undefined); const set_tanks = (block: BlockRef, tanks: BasinTank[]) => block.set_client_data("tanks", tanks.length > 0 ? tanks : undefined); ctx.components.register_block("create:basin", { on_entity_stand(block, _params, entity) { const stack = entity.get_item(); if (!stack) return; const { items, inserted } = insert_item(items_of(block), stack, ctx.items.max_stack(stack.id, stack.data)); if (inserted === 0) return; set_items(block, items); entity.set_item({ ...stack, count: stack.count - inserted }); }, on_interact(block, _params, player) { const held = player.held_item; if (!held) { for (const item of items_of(block)) player.give_item(item.id, item.count, item.data); set_items(block, []); return true; } const capacity = ctx.items.fluid_capacity(held.id); // anything else is used or placed as if the basin weren't there if (capacity === undefined) return false; const fluid = (held.data as { fluid?: FluidVariant } | undefined)?.fluid; if (fluid) { const tanks = fill(tanks_of(block), fluid, capacity, (a, b) => ctx.fluids.same(a, b)); if (tanks) { set_tanks(block, tanks); player.exchange_held({ id: held.id, count: 1 }); } } else { const drained = drain(tanks_of(block), capacity); if (drained) { set_tanks(block, drained.tanks); player.exchange_held({ id: held.id, count: 1, data: { fluid: drained.fluid } }); } } // a fluid container is used up on the basin even when nothing fits, like create's return true; }, on_break(block) { for (const item of items_of(block)) ctx.world.drop_item(block.x, block.y, block.z, item); }, }); } // 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(actual_speed(block)); 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("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 and whether they're overstressed in // client data, and where their speed 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?: GeneratorParams; motor?: GeneratorParams; wheel?: GeneratorParams } >(); 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 GeneratorParams | undefined, motor: components["create:creative_motor"] as GeneratorParams | undefined, wheel: components["create:water_wheel"] as GeneratorParams | 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, motor, wheel } = 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 & MotorData & WheelData = block.data ?? {}; // a crank turns counterclockwise seen from its handle, or the other way while sneaking, and a motor seen // from its shaft const generated = crank && data.in_use && shape.facing ? along(shape.facing, data.backwards ? -crank.speed : crank.speed) : motor && shape.facing ? along(shape.facing, data.speed ?? motor.speed) : wheel ? (data.flow ?? 0) * wheel.speed : 0; return { x, y, z, ...shape, speed: block.get_client_data("speed") ?? 0, source: data.source, network: data.network, generated, impact: config.stress.impact[block.id] ?? 0, capacity: config.stress.capacity[block.id] ?? 0, overstressed: block.get_client_data("overstressed") ?? false, }; }, 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); // the side its speed comes from decides how a gearbox's or clutch's axles turn, which its visual shows const { gearbox, split } = params_of(block.id).kinetic!; if (gearbox || split) { block.set_client_data("source", source_face({ x: at[0], y: at[1], z: at[2], source })); } const { source: _, network: __, ...rest }: KineticData = block.data ?? {}; block.data = { ...rest, ...(source && { source }), ...(network !== undefined && { network }) }; }, break(at) { ctx.world.break_block(...at); }, set_overstressed(at, overstressed) { const block = block_at(at); // like a block that starts turning, see set if (!overstressed && block.get_client_data("speed")) block.set_ticking(true); block.set_client_data("overstressed", overstressed || undefined); }, max_speed: config.max_speed, }; }