// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later // collision against blocks, shared by the client's entities and the server's, so both move things the same way import { TICK_DELTA } from "./constants.ts"; import { COLLISION_TOP, EMPTY_SHAPE, FULL_SHAPE, type Shape } from "./block_shapes.ts"; // how far inside a block face still counts as touching it, so boxes resting exactly on a face don't snag const EPSILON = 1e-7; // the two axes that aren't the one being moved along const OTHER_AXES = [[1, 2], [0, 2], [0, 1]] as const; // what a body bumps into at a block: its collision shape (see common/block_shapes.ts), or true for a full block and // false for nothing export type BlockCollision = (x: number, y: number, z: number) => boolean | Shape; function shape_of(collision: boolean | Shape): Shape { return collision === true ? FULL_SHAPE : collision === false ? EMPTY_SHAPE : collision; } // the lowest block whose shape can reach up to a box starting at min along an axis: on y that's one more below, // since a collision shape can be taller than its block, like a fence's function lowest(axis: number, min: number) { return Math.floor(min + EPSILON) - (axis === 1 ? Math.ceil(COLLISION_TOP) - 1 : 0); } // something with a box that moves. position is the middle of its feet, velocity is in blocks per second export interface Body { x: number; y: number; z: number; vx: number; vy: number; vz: number; // width is used for both x and z width: number; height: number; } // which way the body hit something on each axis: 1 or -1, 0 for nothing. 1 on y means it landed on something export interface Collisions { x: number; y: number; z: number; } // falls and moves a body by its velocity for one tick. like minecraft it moves along y first, then along whichever // of x and z it's moving more on, so walking diagonally past a corner slides along it instead of snagging. each time // only as far as it can before touching a block, and stops its velocity on the axes it hit something. // blocks it's already inside don't stop it, so it can get out of them. // with a step height, a body that was on the ground (or lands during this move) and walks into something at most // that tall steps up onto it, like minecraft's Entity.collide. that also covers the tick it starts to fall: it has // already dropped a little, so the next block's top is a small step up instead of a wall to slide down export function move_body( body: Body, gravity: number, is_solid: BlockCollision, step_height = 0, on_ground = false, ) { // the average of this tick's start and end speed, so the arc is the same at any tick rate const wanted_y = (body.vy + gravity * TICK_DELTA / 2) * TICK_DELTA; body.vy += gravity * TICK_DELTA; const wanted = [body.vx * TICK_DELTA, wanted_y, body.vz * TICK_DELTA]; const half = body.width / 2; const min = [body.x - half, body.y, body.z - half]; const max = [body.x + half, body.y + body.height, body.z + half]; let moved = sweep([...min], [...max], wanted, [1, ...horizontal_order(wanted)], is_solid); const blocked_sideways = moved[0] !== wanted[0] || moved[2] !== wanted[2]; const landed = moved[1] !== wanted[1] && wanted[1] < 0; if (step_height > 0 && blocked_sideways && (on_ground || landed)) { const stepped = step_up([...min], [...max], wanted, step_height, is_solid); if (stepped[0] ** 2 + stepped[2] ** 2 > moved[0] ** 2 + moved[2] ** 2) { moved = stepped; } } const hit = (axis: number) => moved[axis] !== wanted[axis] ? -Math.sign(wanted[axis]) : 0; const collisions: Collisions = { x: hit(0), y: hit(1), z: hit(2) }; if (collisions.x !== 0) body.vx = 0; if (collisions.y !== 0) body.vy = 0; if (collisions.z !== 0) body.vz = 0; body.x += moved[0]; body.y += moved[1]; body.z += moved[2]; return collisions; } // x then z, or z then x when it's moving more along z function horizontal_order(wanted: number[]) { return Math.abs(wanted[0]) < Math.abs(wanted[2]) ? [2, 0] : [0, 2]; } // moves the box along each axis in turn, as far as it can. returns how far it went on each function sweep( min: number[], max: number[], wanted: number[], axes: number[], is_solid: BlockCollision, ) { const moved = [0, 0, 0]; for (const axis of axes) { const distance = clip(min, max, axis, wanted[axis], is_solid); min[axis] += distance; max[axis] += distance; moved[axis] = distance; } return moved; } // up by the step height (or to the ceiling), across, then back down onto whatever it's standing on, as far as it // would have gone down anyway function step_up( min: number[], max: number[], wanted: number[], step_height: number, is_solid: BlockCollision, ) { const up = sweep(min, max, [0, step_height, 0], [1], is_solid)[1]; const across = sweep(min, max, wanted, horizontal_order(wanted), is_solid); const down = sweep(min, max, [0, wanted[1] - up, 0], [1], is_solid)[1]; return [across[0], up + down, across[2]]; } // how far the box can go along an axis before it runs into a block's shape function clip( min: number[], max: number[], axis: number, distance: number, is_solid: BlockCollision, ) { if (distance === 0) { return 0; } const [a, b] = OTHER_AXES[axis]; const from = lowest(axis, Math.min(min[axis], min[axis] + distance) - EPSILON); const to = Math.floor(Math.max(max[axis], max[axis] + distance)); const position = [0, 0, 0]; for (let i = from; i <= to; i++) { for (let j = lowest(a, min[a]); j <= Math.floor(max[a] - EPSILON); j++) { for (let k = lowest(b, min[b]); k <= Math.floor(max[b] - EPSILON); k++) { position[axis] = i; position[a] = j; position[b] = k; for (const box of shape_of(is_solid(position[0], position[1], position[2]))) { // only boxes beside the body on the other two axes are in the way if ( position[a] + box[a] >= max[a] - EPSILON || position[a] + box[a + 3] <= min[a] + EPSILON || position[b] + box[b] >= max[b] - EPSILON || position[b] + box[b + 3] <= min[b] + EPSILON ) { continue; } const box_min = i + box[axis]; const box_max = i + box[axis + 3]; if (distance > 0 && box_min >= max[axis] - EPSILON) { distance = Math.min(distance, box_min - max[axis]); } else if (distance < 0 && box_max <= min[axis] + EPSILON) { distance = Math.max(distance, box_max - min[axis]); } } } } } return distance; } // how far a sneaking body on the ground can move this tick without walking off an edge, like minecraft's // Player.maybeBackOffFromEdge: each axis is cut back until there's something within `drop` below the moved box export function back_off_from_edge( body: Body, dx: number, dz: number, drop: number, is_solid: BlockCollision, ): [number, number] { const step = 0.05; const toward_zero = (d: number) => Math.abs(d) <= step ? 0 : d - Math.sign(d) * step; const falls = (mx: number, mz: number) => { const half = body.width / 2; const min = [body.x - half + mx, body.y - drop, body.z - half + mz]; const max = [body.x + half + mx, body.y, body.z + half + mz]; return !overlaps_solid(min, max, is_solid); }; while (dx !== 0 && falls(dx, 0)) dx = toward_zero(dx); while (dz !== 0 && falls(0, dz)) dz = toward_zero(dz); while (dx !== 0 && dz !== 0 && falls(dx, dz)) { dx = toward_zero(dx); dz = toward_zero(dz); } return [dx, dz]; } // whether the body's box, moved by dx, dy and dz, would touch nothing blocked, like minecraft's Entity.isFree export function box_is_free( body: Body, dx: number, dy: number, dz: number, is_blocked: BlockCollision, ): boolean { const half = body.width / 2; const min = [body.x - half + dx, body.y + dy, body.z - half + dz]; const max = [body.x + half + dx, body.y + body.height + dy, body.z + half + dz]; return !overlaps_solid(min, max, is_blocked); } function overlaps_solid(min: number[], max: number[], is_solid: BlockCollision) { for (let x = lowest(0, min[0]); x <= Math.floor(max[0] - EPSILON); x++) { for (let y = lowest(1, min[1]); y <= Math.floor(max[1] - EPSILON); y++) { for (let z = lowest(2, min[2]); z <= Math.floor(max[2] - EPSILON); z++) { for (const box of shape_of(is_solid(x, y, z))) { if ( x + box[0] < max[0] - EPSILON && x + box[3] > min[0] + EPSILON && y + box[1] < max[1] - EPSILON && y + box[4] > min[1] + EPSILON && z + box[2] < max[2] - EPSILON && z + box[5] > min[2] + EPSILON ) { return true; } } } } } return false; } // in water like minecraft's wasTouchingWater, close enough: its feet or the middle of its box are in fluid export function in_water(body: Body, is_fluid: (x: number, y: number, z: number) => boolean): boolean { const x = Math.floor(body.x); const z = Math.floor(body.z); return is_fluid(x, Math.floor(body.y), z) || is_fluid(x, Math.floor(body.y + body.height / 2), z); } // its eyes are in fluid, so it can't breathe export function eyes_in_water( body: Body, eye_height: number, is_fluid: (x: number, y: number, z: number) => boolean, ): boolean { return is_fluid(Math.floor(body.x), Math.floor(body.y + eye_height), Math.floor(body.z)); } // a fluid in a cell, for fluids pushing things along export interface FluidInCell { // which fluid, its block's id. a fluid's flow only goes by cells of the same one id: string; // its surface, 0 to 1 (see fluid_height), not counting more of it above height: number; } // the fluid in a cell, undefined for none export type FluidAt = (x: number, y: number, z: number) => FluidInCell | undefined; const HORIZONTAL = [[1, 0], [-1, 0], [0, 1], [0, -1]]; // blocks per second added each tick, minecraft's water 0.014 blocks per tick per tick const FLUID_PUSH = 0.014 * 20; // moving slower than this sideways, a push is at least FLUID_MIN_PUSH, so things still drift off flat-ish water const FLUID_STILL_SPEED = 0.003 * 20; const FLUID_MIN_PUSH = 0.0045 * 20; function blocks_motion(collision: boolean | Shape) { return shape_of(collision).length > 0; } function normalized(x: number, y: number, z: number): [number, number, number] { const length = Math.hypot(x, y, z); return length < 1e-5 ? [0, 0, 0] : [x / length, y / length, z / length]; } // which way the fluid at x y z flows, a length 1 vector or nothing, like minecraft's FlowingFluid.getFlow: towards // lower cells of it beside it, and towards drops where it pours over an edge. falling down a wall it goes down too export function fluid_flow( x: number, y: number, z: number, fluid_at: FluidAt, is_solid: BlockCollision, ): [number, number, number] { const here = fluid_at(x, y, z); if (!here) return [0, 0, 0]; let fx = 0; let fz = 0; for (const [dx, dz] of HORIZONTAL) { const neighbor = fluid_at(x + dx, y, z + dz); // another fluid doesn't change this one's flow if (neighbor && neighbor.id !== here.id) continue; let drop = 0; if (neighbor) { drop = here.height - neighbor.height; } else if (!blocks_motion(is_solid(x + dx, y, z + dz))) { // an edge it pours over, onto more of itself const below = fluid_at(x + dx, y - 1, z + dz); if (below?.id === here.id) drop = here.height - (below.height - 1); } fx += dx * drop; fz += dz * drop; } [fx, , fz] = normalized(fx, 0, fz); // falling: flowing, not a source, with more of it above. a deep pool of sources isn't let fy = 0; if (here.height < 1 && fluid_at(x, y + 1, z)?.id === here.id) { const against_wall = HORIZONTAL.some(([dx, dz]) => blocks_motion(is_solid(x + dx, y, z + dz)) || blocks_motion(is_solid(x + dx, y + 1, z + dz)) ); if (against_wall) fy = -6; } return normalized(fx, fy, fz); } // fluid the body is in pushes it the way it flows, like minecraft's Entity.updateFluidHeightAndDoFluidPushing: the // flow of every cell of it the box reaches, averaged, weaker where it's shallow. players get that average as it is, // other things are pushed at full strength whichever way it points. changes the body's velocity export function push_by_fluid(body: Body, fluid_at: FluidAt, is_solid: BlockCollision, is_player: boolean) { const half = body.width / 2 - 0.001; const min_y = body.y + 0.001; const max_y = body.y + body.height - 0.001; let px = 0; let py = 0; let pz = 0; let count = 0; let depth = 0; for (let x = Math.floor(body.x - half); x <= Math.floor(body.x + half); x++) { for (let y = Math.floor(min_y); y <= Math.floor(max_y); y++) { for (let z = Math.floor(body.z - half); z <= Math.floor(body.z + half); z++) { const fluid = fluid_at(x, y, z); if (!fluid) continue; const surface = y + (fluid_at(x, y + 1, z)?.id === fluid.id ? 1 : fluid.height); if (surface < min_y) continue; depth = Math.max(depth, surface - min_y); let [fx, fy, fz] = fluid_flow(x, y, z, fluid_at, is_solid); // minecraft's, which goes by the deepest cell so far if (depth < 0.4) { fx *= depth; fy *= depth; fz *= depth; } px += fx; py += fy; pz += fz; count++; } } } if (Math.hypot(px, py, pz) === 0) return; [px, py, pz] = is_player ? [px / count, py / count, pz / count] : normalized(px, py, pz); px *= FLUID_PUSH; py *= FLUID_PUSH; pz *= FLUID_PUSH; if ( Math.abs(body.vx) < FLUID_STILL_SPEED && Math.abs(body.vz) < FLUID_STILL_SPEED && Math.hypot(px, py, pz) < FLUID_MIN_PUSH ) { [px, py, pz] = normalized(px, py, pz).map((n) => n * FLUID_MIN_PUSH); } body.vx += px; body.vy += py; body.vz += pz; } // how far the body's feet are under the surface of fluid it's in, 0 for none, like minecraft's getFluidHeight export function fluid_depth(body: Body, fluid_at: FluidAt): number { const half = body.width / 2 - 0.001; const min_y = body.y + 0.001; let depth = 0; for (let x = Math.floor(body.x - half); x <= Math.floor(body.x + half); x++) { for (let y = Math.floor(min_y); y <= Math.floor(body.y + body.height - 0.001); y++) { for (let z = Math.floor(body.z - half); z <= Math.floor(body.z + half); z++) { const fluid = fluid_at(x, y, z); if (!fluid) continue; const surface = y + (fluid_at(x, y + 1, z)?.id === fluid.id ? 1 : fluid.height); depth = Math.max(depth, surface - min_y); } } } return depth; } // what the engine calls through, so engine access mods can hook these like methods (module exports can't be // reassigned). see docs/modding/misc/engine.md export const physics = { move_body, back_off_from_edge, box_is_free, in_water, eyes_in_water, fluid_flow, push_by_fluid, fluid_depth, };