Files
bworld/mods/create/scripts/kinetics/chains.ts
T
2026-11-04 21:51:26 -03:00

45 lines
2.0 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// how chain drives join into lines: each keeps where it is in its line (start, middle, end, or none on its own) and
// which way the line goes, and changes them as chain drives beside it come and go, like ChainDriveBlock.updateShape.
// no ctx, so placing and neighbor rules both use it
import type { Face } from "cubi/shared";
import { type Axis, chain_axis, type ChainPart, face_axis, positive } from "./connections.ts";
// a chain drive's states that matter for its line
export interface ChainState {
axis: Axis;
part: ChainPart;
// its line goes along the first of the axes that aren't its own, see chain_axis
along_first: boolean;
}
// a chain drive's line once the block toward face is other, undefined when that isn't a chain drive. one on its own
// starts a line with a chain drive beside it across its axis, and one in a line only joins more along that line, and
// is the end of it again when the one past it goes
export function chain_update(state: ChainState, face: Face, other: ChainState | undefined): ChainState {
const { axis } = state;
const toward = face_axis(face);
if (axis === toward) return state;
const facing_along_first = axis === "x" ? toward === "y" : toward === "x";
const ahead = positive(face);
if (!other) {
if (facing_along_first !== state.along_first || state.part === "none") return state;
if (state.part === "middle") return { ...state, part: ahead ? "end" : "start" };
if ((state.part === "start") === ahead) return { ...state, part: "none" };
return state;
}
if (other.axis === toward) return state;
if (other.part !== "none" && chain_axis(other.axis, other.along_first) !== toward) return state;
let { part, along_first } = state;
if (part === "none") {
part = ahead ? "start" : "end";
along_first = facing_along_first;
} else if (chain_axis(axis, along_first) !== toward) {
return state;
}
if ((part === "start") !== ahead) part = "middle";
return { axis, part, along_first };
}