Open History to see the last commit
1import { collision, validPart } from "../shared/geometry";
2import type { Connection, Edit, Part, Position } from "../shared/types";
3
4export type MoveAxis = "x" | "y" | "z";
5export type MoveSnapshot = {
6 parts: Part[];
7 connections: NonNullable<Edit["connections"]>;
8 generation: number;
9 delta: Position;
10};
11
12// Capture the preconditions at pickup, including an empty connection set.
13export function captureMove(
14 parts: Part[],
15 connections: Connection[],
16 generation: number,
17): MoveSnapshot {
18 const ids = new Set(parts.map((p) => p.id));
19 return {
20 parts: parts.map((p) => ({ ...p, position: { ...p.position } })),
21 connections: connections
22 .filter((c) => ids.has(c.a) || ids.has(c.b))
23 .map((c) => ({ id: c.id, revision: c.revision })),
24 generation,
25 delta: { x: 0, y: 0, z: 0 },
26 };
27}
28
29export function snapMovement(
30 delta: Position,
31 axis?: MoveAxis,
32 fine = false,
33): Position {
34 return Object.fromEntries(
35 (["x", "y", "z"] as const).map((a) => {
36 const enabled = axis ? axis === a : a !== "y";
37 const step = fine ? 1 : a === "y" ? 2 : 6;
38 return [a, enabled ? Math.round(delta[a] / step) * step || 0 : 0];
39 }),
40 ) as Position;
41}
42
43export function movedParts(move: MoveSnapshot): Part[] {
44 return move.parts.map((p) => ({
45 ...p,
46 position: {
47 x: p.position.x + move.delta.x,
48 y: p.position.y + move.delta.y,
49 z: p.position.z + move.delta.z,
50 },
51 }));
52}
53
54export function fitsScene(
55 candidates: Part[],
56 scene: Part[],
57 excluded: string[] = [],
58): boolean {
59 const ignore = new Set(excluded);
60 return candidates.every(
61 (p, i) =>
62 validPart(p) &&
63 !scene.some((other) => !ignore.has(other.id) && collision(p, other)) &&
64 !candidates.slice(0, i).some((other) => collision(p, other)),
65 );
66}
67
68export function moveRequest(
69 move: MoveSnapshot,
70): Omit<Edit, "operationId" | "generation"> {
71 return {
72 action: "edit",
73 connections: move.connections,
74 changes: movedParts(move).map((p) => ({
75 id: p.id,
76 expected: p.revision,
77 position: p.position,
78 rotation: p.rotation,
79 })),
80 };
81}