feat(cameras): crossing line editor in Setup (A→B / B→A / A↔B)

Our own line-crossing rule for cameras that have none: draw a segment over
the camera's live picture, sides A and B, and pick which crossing counts.
Stored as camera config.crossing (CrossingLine in @parking/shared, points
normalised to the frame, side A on the screen-left of p1→p2), validated on
save; null clears it. Nothing consumes it yet (passage confirmation).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RZgP5oMncSaVmKRKk1UvN4
This commit is contained in:
2026-11-19 12:38:53 +01:00
parent ef2c9f9f45
commit ee0e1ff575
9 changed files with 430 additions and 3 deletions
@@ -0,0 +1,72 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { devices, eq, type Db } from "@parking/db";
import { createTestDb } from "@parking/db/testing";
import type { FastifyInstance } from "fastify";
import { buildServer } from "../server.js";
import { seedUser, login } from "../test-helpers.js";
// A camera's crossing line (passage confirmation) rides in its config as `crossing`. The
// save validates it (the driver never reads it), and since an edit MERGES onto the stored
// config, clearing it must be an explicit `null`.
let db: Db;
let close: () => void;
let app: FastifyInstance;
const CAM = "cam-1";
const line = { p1: { x: 0.1, y: 0.6 }, p2: { x: 0.9, y: 0.55 }, direction: "a-to-b" };
beforeEach(async () => {
({ db, close } = createTestDb());
db.insert(devices).values({
id: CAM,
category: "camera",
driverId: "dahua",
config: { host: "127.0.0.1", port: 80, username: "u", password: "p" },
enabled: true,
}).run();
app = await buildServer({ db });
await app.ready();
auth = undefined;
});
afterEach(async () => {
await app.close();
close();
});
let auth: { cookie: string; csrf: string } | undefined;
async function edit(config: Record<string, unknown>) {
if (!auth) {
await seedUser(db, { username: "admin", password: "pw" });
auth = await login(app, "admin", "pw");
}
return app.inject({
method: "PATCH",
url: `/api/setup/assign/${CAM}`,
headers: { cookie: auth.cookie, "x-csrf-token": auth.csrf },
payload: { config: { host: "127.0.0.1", port: 80, username: "u", password: "p", ...config } },
});
}
const stored = () => db.select().from(devices).where(eq(devices.id, CAM)).get()!.config as Record<string, unknown>;
describe("camera crossing line on save", () => {
it("stores a valid line", async () => {
const res = await edit({ crossing: line });
expect(res.statusCode).toBe(200);
expect(stored().crossing).toEqual(line);
});
it("keeps the stored line when the edit doesn't mention it, and clears it on null", async () => {
await edit({ crossing: line });
await edit({});
expect(stored().crossing).toEqual(line);
const res = await edit({ crossing: null });
expect(res.statusCode).toBe(200);
expect(stored()).not.toHaveProperty("crossing");
});
it("rejects an invalid line and leaves the stored config alone", async () => {
const res = await edit({ crossing: { ...line, p2: { x: 1.4, y: 0.5 } } });
expect(res.statusCode).toBe(400);
expect(stored()).not.toHaveProperty("crossing");
});
});
+12 -1
View File
@@ -16,7 +16,7 @@ import {
type DeviceCategory, type DeviceCategory,
type DeviceConfig, type DeviceConfig,
} from "@parking/devices"; } from "@parking/devices";
import { reasonPayload } from "@parking/shared"; import { parseCrossingLine, reasonPayload } from "@parking/shared";
import { requirePermission } from "../auth.js"; import { requirePermission } from "../auth.js";
import type { EventLog } from "../event-log.js"; import type { EventLog } from "../event-log.js";
import { backendIpCandidates, backendIpForDevice, backendPort } from "../net.js"; import { backendIpCandidates, backendIpForDevice, backendPort } from "../net.js";
@@ -147,6 +147,17 @@ async function configureDevice(
// webPasswordCurrent is an input-only credential (the OLD password used to // webPasswordCurrent is an input-only credential (the OLD password used to
// authorize the change) — never persist it as typed. // authorize the change) — never persist it as typed.
delete fullConfig.webPasswordCurrent; delete fullConfig.webPasswordCurrent;
// Camera crossing line (passage confirmation): validated here, since the driver doesn't
// read it. `null` clears it — the merge above would otherwise keep the stored line.
if ("crossing" in config) {
if (config.crossing === null) {
delete fullConfig.crossing;
} else {
const line = parseCrossingLine(config.crossing);
if (!line) return { error: { code: 400, message: "invalid crossing line" } };
fullConfig.crossing = { ...line };
}
}
// Residual-risk warnings from device hardening (shown to the admin; the // Residual-risk warnings from device hardening (shown to the admin; the
// save still succeeds — these are "configured, but note X" advisories). // save still succeeds — these are "configured, but note X" advisories).
const hardenWarnings: string[] = []; const hardenWarnings: string[] = [];
+15
View File
@@ -32,6 +32,8 @@ import {
fetchUsbPrinters, fetchUsbPrinters,
} from "./api.js"; } from "./api.js";
import { Modal } from "./ui/Modal.js"; import { Modal } from "./ui/Modal.js";
import { CrossingLineEditor } from "./ui/CrossingLineEditor.js";
import { parseCrossingLine, type CrossingLine } from "@parking/shared";
// First-run setup wizard. The pool-of-spaces model: a parking lot is one pool with // First-run setup wizard. The pool-of-spaces model: a parking lot is one pool with
// a flexible set of entry/exit points — NO lane. The admin adds CONTROLLERS (each // a flexible set of entry/exit points — NO lane. The admin adds CONTROLLERS (each
@@ -534,6 +536,8 @@ function DeviceForm({
// back-plate read would otherwise phantom-exit the car that just entered). Defaults ON // back-plate read would otherwise phantom-exit the car that just entered). Defaults ON
// when anpr is on (back-compat). (config.anprAutoTrigger). // when anpr is on (back-compat). (config.anprAutoTrigger).
const [anprAuto, setAnprAuto] = useState<boolean>(editCfg?.anprAutoTrigger !== false); const [anprAuto, setAnprAuto] = useState<boolean>(editCfg?.anprAutoTrigger !== false);
// Crossing line drawn over this camera's view (passage confirmation). (config.crossing)
const [crossing, setCrossing] = useState<CrossingLine | null>(() => parseCrossingLine(editCfg?.crossing));
// Pre-fill scalar config fields from the existing assignment when editing. // Pre-fill scalar config fields from the existing assignment when editing.
// (relays/controllerId/relay are model fields handled by their own state below.) // (relays/controllerId/relay are model fields handled by their own state below.)
@@ -735,6 +739,8 @@ function DeviceForm({
// park can explicitly DISABLE auto-open on a camera (e.g. the exit cam of a shared lane) // park can explicitly DISABLE auto-open on a camera (e.g. the exit cam of a shared lane)
// while keeping recognition. Absent ⇒ defaults ON (back-compat for existing cameras). // while keeping recognition. Absent ⇒ defaults ON (back-compat for existing cameras).
if (isCamera && anpr) out.anprAutoTrigger = anprAuto; if (isCamera && anpr) out.anprAutoTrigger = anprAuto;
// Crossing line: always sent for a camera, `null` to clear (the server merges configs).
if (isCamera) out.crossing = crossing ? { p1: { ...crossing.p1 }, p2: { ...crossing.p2 }, direction: crossing.direction } : null;
return out; return out;
} }
@@ -1085,6 +1091,15 @@ function DeviceForm({
</label> </label>
)} )}
{/* CAMERA: the crossing line (passage confirmation), drawn over the live picture.
Needs a saved camera — the live stream is addressed by its device id. */}
{isCamera &&
(editing?.id ? (
<CrossingLineEditor deviceId={editing.id} value={crossing} onChange={setCrossing} />
) : (
<p className="hint my-2">{t("setup.crossingSaveFirst")}</p>
))}
{/* CAMERA + Alarm Server push ON: show the camera's Alarm Server settings, {/* CAMERA + Alarm Server push ON: show the camera's Alarm Server settings,
ready to copy, so the operator never has to find the deviceId or memorise the ready to copy, so the operator never has to find the deviceId or memorise the
endpoint. The CAMERA reaches us over the device VLAN, NOT via the browser's endpoint. The CAMERA reaches us over the device VLAN, NOT via the browser's
+9
View File
@@ -626,6 +626,15 @@ export const en: Catalog = {
anprHint: anprHint:
"Read plates on this camera: the vision service reads the plate from each snapshot and records it (both entry and exit). Requires the vision service running.", "Read plates on this camera: the vision service reads the plate from each snapshot and records it (both entry and exit). Requires the vision service running.",
anprAuto: "Auto open/close on subscriber plate", anprAuto: "Auto open/close on subscriber plate",
crossingTitle: "Crossing line",
crossingHint:
"Drag across the picture to draw the line a vehicle must cross; drag an end to move it. Choose which crossing counts: A → B, B → A, or either.",
crossingDirection: "Direction",
crossingSwap: "Swap A/B",
crossingClear: "Clear",
crossingNone: "No line drawn.",
crossingWaiting: "Waiting for the camera…",
crossingSaveFirst: "Save the camera first to draw its crossing line.",
anprAutoHint: anprAutoHint:
"Let THIS camera auto-open the barrier when it recognises a subscriber's plate. Turn OFF on a shared entry/exit lane's exit camera, so a car driving IN isn't auto-EXITed by its back plate (recognition still runs — only the auto-trigger is off).", "Let THIS camera auto-open the barrier when it recognises a subscriber's plate. Turn OFF on a shared entry/exit lane's exit camera, so a car driving IN isn't auto-EXITed by its back plate (recognition still runs — only the auto-trigger is off).",
testAnpr: "Test ANPR", testAnpr: "Test ANPR",
+9
View File
@@ -636,6 +636,15 @@ export const sq = {
anprHint: anprHint:
"Lexo targat në këtë aparat: shërbimi i vizionit lexon targën nga çdo pamje dhe e regjistron (hyrje dhe dalje). Kërkon shërbimin e vizionit aktiv.", "Lexo targat në këtë aparat: shërbimi i vizionit lexon targën nga çdo pamje dhe e regjistron (hyrje dhe dalje). Kërkon shërbimin e vizionit aktiv.",
anprAuto: "Hapje/mbyllje automatike me targën e abonentit", anprAuto: "Hapje/mbyllje automatike me targën e abonentit",
crossingTitle: "Vija e kalimit",
crossingHint:
"Tërhiq mbi pamje për të vizatuar vijën që duhet të kalojë mjeti; tërhiq një skaj për ta lëvizur. Zgjidh cili kalim numërohet: A → B, B → A, ose të dyja.",
crossingDirection: "Drejtimi",
crossingSwap: "Ndërro A/B",
crossingClear: "Pastro",
crossingNone: "Nuk ka vijë të vizatuar.",
crossingWaiting: "Në pritje të kamerës…",
crossingSaveFirst: "Ruaje kamerën fillimisht për të vizatuar vijën e kalimit.",
anprAutoHint: anprAutoHint:
"Lejo që KY aparat të hapë vetë barrierën kur njeh targën e një abonenti. ÇAKTIVIZOJE te aparati i daljes në një korsi të përbashkët hyrje/dalje, që një makinë që HYN të mos DALË automatikisht nga targa e pasme (njohja vazhdon — fiket vetëm hapja automatike).", "Lejo që KY aparat të hapë vetë barrierën kur njeh targën e një abonenti. ÇAKTIVIZOJE te aparati i daljes në një korsi të përbashkët hyrje/dalje, që një makinë që HYN të mos DALË automatikisht nga targa e pasme (njohja vazhdon — fiket vetëm hapja automatike).",
testAnpr: "Testo ANPR", testAnpr: "Testo ANPR",
+2 -2
View File
@@ -409,7 +409,7 @@ function useSnapshotPicture(want: CameraSnapshotMeta | null): SnapshotPicture {
* unmounts; reconnects after a drop while still active. The server shares one camera * unmounts; reconnects after a drop while still active. The server shares one camera
* session between every viewer and skips frames for a slow one. * session between every viewer and skips frames for a slow one.
*/ */
function useLiveFrames(deviceId: string, active: boolean) { export function useLiveFrames(deviceId: string, active: boolean) {
// Every <img> showing this camera (the tile, and the large view while open) gets each // Every <img> showing this camera (the tile, and the large view while open) gets each
// frame; a view that mounts between frames is given the newest one at once. // frame; a view that mounts between frames is given the newest one at once.
const imgs = useRef(new Map<string, HTMLImageElement>()); const imgs = useRef(new Map<string, HTMLImageElement>());
@@ -423,7 +423,7 @@ function useLiveFrames(deviceId: string, active: boolean) {
imgs.current.delete(name); imgs.current.delete(name);
} }
}; };
return { tile: slot("tile"), modal: slot("modal") }; return { tile: slot("tile"), modal: slot("modal"), editor: slot("editor") };
}, []); }, []);
const [status, setStatus] = useState<LiveState>({ state: "connecting" }); const [status, setStatus] = useState<LiveState>({ state: "connecting" });
const [hasFrame, setHasFrame] = useState(false); const [hasFrame, setHasFrame] = useState(false);
+225
View File
@@ -0,0 +1,225 @@
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import {
CROSSING_MIN_LENGTH,
type CrossingDirection,
type CrossingLine,
type FramePoint,
} from "@parking/shared";
import { useLiveFrames } from "./CameraDock.js";
// Draws a camera's crossing line over its live picture — our own version of a Hikvision
// Line Crossing rule, for cameras that have none: a segment, sides A and B, and which
// crossing counts (A→B, B→A, A↔B). Points are normalised to the frame, so the line holds
// at any display size. Side A is the screen-left of p1→p2 (see crossingSide in shared).
type Drag = { end: "p1" | "p2" } | null;
const HANDLE_PX = 14; // grab radius around an end point
export function CrossingLineEditor({
deviceId,
value,
onChange,
}: {
deviceId: string;
value: CrossingLine | null;
onChange: (next: CrossingLine | null) => void;
}) {
const { t } = useTranslation();
const live = useLiveFrames(deviceId, true);
const surface = useRef<SVGSVGElement | null>(null);
const [size, setSize] = useState({ w: 0, h: 0 });
const [drag, setDrag] = useState<Drag>(null);
// While drawing a new line it lives here, so a click-length line never reaches the form.
const [draft, setDraft] = useState<CrossingLine | null>(null);
const line = draft ?? value;
// The overlay sits exactly on the picture (the wrapper is sized by the <img>), so its
// rectangle IS the frame: no letterbox offset to correct for.
useEffect(() => {
const el = surface.current;
if (!el) return;
const ro = new ResizeObserver(([e]) => e && setSize({ w: e.contentRect.width, h: e.contentRect.height }));
ro.observe(el);
return () => ro.disconnect();
}, [live.hasFrame]);
const toFrame = (ev: React.PointerEvent): FramePoint => {
const r = surface.current!.getBoundingClientRect();
const clamp = (v: number) => Math.min(1, Math.max(0, v));
return { x: clamp((ev.clientX - r.left) / r.width), y: clamp((ev.clientY - r.top) / r.height) };
};
const px = (p: FramePoint) => ({ x: p.x * size.w, y: p.y * size.h });
function onDown(ev: React.PointerEvent<SVGSVGElement>) {
if (!live.hasFrame) return;
ev.currentTarget.setPointerCapture(ev.pointerId);
const at = toFrame(ev);
if (value) {
for (const end of ["p1", "p2"] as const) {
const e = px(value[end]);
const a = px(at);
if (Math.hypot(e.x - a.x, e.y - a.y) <= HANDLE_PX) {
setDrag({ end });
return;
}
}
}
// Anywhere else: draw a new line from here, keeping the chosen direction.
setDraft({ p1: at, p2: at, direction: value?.direction ?? "a-to-b" });
setDrag({ end: "p2" });
}
function onMove(ev: React.PointerEvent<SVGSVGElement>) {
if (!drag) return;
const at = toFrame(ev);
if (draft) setDraft({ ...draft, [drag.end]: at });
else if (value) onChange({ ...value, [drag.end]: at });
}
function onUp() {
if (draft && Math.hypot(draft.p2.x - draft.p1.x, draft.p2.y - draft.p1.y) >= CROSSING_MIN_LENGTH) {
onChange(draft);
}
setDraft(null);
setDrag(null);
}
const directions: [CrossingDirection, string][] = [
["a-to-b", "A → B"],
["b-to-a", "B → A"],
["both", "A ↔ B"],
];
return (
<div className="my-2 rounded-term border border-term-border bg-term-bg p-2 text-[0.75rem]">
<div className="font-semibold text-term-text">{t("setup.crossingTitle")}</div>
<p className="hint mt-0.5">{t("setup.crossingHint")}</p>
<div className="relative mt-2 inline-block w-full select-none">
<img
ref={live.imgRefs.editor}
alt=""
draggable={false}
className={live.hasFrame ? "block h-auto w-full" : "hidden"}
/>
{!live.hasFrame && (
<div className="flex aspect-video w-full items-center justify-center rounded bg-term-panel text-term-muted">
{live.status.state === "unavailable" || live.status.state === "retrying"
? live.status.reason
: t("setup.crossingWaiting")}
</div>
)}
{live.hasFrame && (
<svg
ref={surface}
className="absolute inset-0 h-full w-full cursor-crosshair touch-none"
onPointerDown={onDown}
onPointerMove={onMove}
onPointerUp={onUp}
onPointerCancel={onUp}
>
{line && size.w > 0 && <LineOverlay line={line} p1={px(line.p1)} p2={px(line.p2)} />}
</svg>
)}
</div>
<div className="mt-2 flex flex-wrap items-center gap-2">
<div className="flex gap-1" role="radiogroup" aria-label={t("setup.crossingDirection")}>
{directions.map(([d, label]) => (
<button
key={d}
type="button"
role="radio"
aria-checked={value?.direction === d}
disabled={!value}
className={`btn btn-sm ${value?.direction === d ? "btn-primary" : ""}`}
onClick={() => value && onChange({ ...value, direction: d })}
>
{label}
</button>
))}
</div>
<button
type="button"
className="btn btn-sm"
disabled={!value}
onClick={() => value && onChange({ ...value, p1: value.p2, p2: value.p1 })}
>
{t("setup.crossingSwap")}
</button>
<button type="button" className="btn btn-sm" disabled={!value} onClick={() => onChange(null)}>
{t("setup.crossingClear")}
</button>
</div>
{!value && <p className="hint mt-1">{t("setup.crossingNone")}</p>}
</div>
);
}
/** The segment, its end handles, the A/B labels either side, and an arrow across the
* middle pointing the way that counts (double-headed for A↔B). Pixel space. */
function LineOverlay({ line, p1, p2 }: { line: CrossingLine; p1: FramePoint; p2: FramePoint }) {
const dx = p2.x - p1.x;
const dy = p2.y - p1.y;
const len = Math.hypot(dx, dy) || 1;
// Unit normal toward side A: the screen-left of p1→p2 (y down) is (dy, -dx).
const nA = { x: dy / len, y: -dx / len };
const mid = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 };
const at = (k: number) => ({ x: mid.x + nA.x * k, y: mid.y + nA.y * k });
const aSide = at(22);
const bSide = at(-22);
const labelA = at(40);
const labelB = at(-40);
// Arrow runs from the side crossings start on to the side they end on.
const [from, to] = line.direction === "b-to-a" ? [bSide, aSide] : [aSide, bSide];
const both = line.direction === "both";
const stroke = "rgb(250 204 21)"; // amber, readable over daylight and night pictures
return (
<g>
<defs>
<marker id="crossing-head" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="5" markerHeight="5" orient="auto-start-reverse">
<path d="M0,0 L10,5 L0,10 z" fill={stroke} />
</marker>
</defs>
<line x1={p1.x} y1={p1.y} x2={p2.x} y2={p2.y} stroke="black" strokeOpacity={0.5} strokeWidth={5} />
<line x1={p1.x} y1={p1.y} x2={p2.x} y2={p2.y} stroke={stroke} strokeWidth={3} />
<line
x1={from.x}
y1={from.y}
x2={to.x}
y2={to.y}
stroke={stroke}
strokeWidth={3}
markerEnd="url(#crossing-head)"
markerStart={both ? "url(#crossing-head)" : undefined}
/>
{[p1, p2].map((p, i) => (
<circle key={i} cx={p.x} cy={p.y} r={6} fill={stroke} stroke="black" strokeWidth={1.5} />
))}
{(
[
["A", labelA],
["B", labelB],
] as const
).map(([txt, p]) => (
<text
key={txt}
x={p.x}
y={p.y}
textAnchor="middle"
dominantBaseline="central"
fontSize={16}
fontWeight={700}
fill={stroke}
stroke="black"
strokeWidth={3}
paintOrder="stroke"
>
{txt}
</text>
))}
</g>
);
}
+32
View File
@@ -0,0 +1,32 @@
import { describe, expect, it } from "vitest";
import { crossingSide, parseCrossingLine, type CrossingLine } from "./index.js";
// A horizontal line drawn left→right across the middle of the frame.
const line: CrossingLine = { p1: { x: 0.1, y: 0.5 }, p2: { x: 0.9, y: 0.5 }, direction: "a-to-b" };
describe("crossingSide", () => {
it("puts the screen-left of p1→p2 on side A (above a left→right line)", () => {
expect(crossingSide(line, { x: 0.5, y: 0.2 })).toBe("a");
expect(crossingSide(line, { x: 0.5, y: 0.8 })).toBe("b");
});
it("swapping the points swaps the sides", () => {
const swapped = { ...line, p1: line.p2, p2: line.p1 };
expect(crossingSide(swapped, { x: 0.5, y: 0.2 })).toBe("b");
});
it("is null exactly on the line", () => {
expect(crossingSide(line, { x: 0.3, y: 0.5 })).toBeNull();
});
});
describe("parseCrossingLine", () => {
it("accepts a valid line", () => {
expect(parseCrossingLine(line)).toEqual(line);
});
it("rejects out-of-frame points, unknown directions and a click-length line", () => {
expect(parseCrossingLine({ ...line, p1: { x: -0.1, y: 0.5 } })).toBeNull();
expect(parseCrossingLine({ ...line, direction: "up" })).toBeNull();
expect(parseCrossingLine({ ...line, p2: { x: 0.11, y: 0.5 } })).toBeNull();
expect(parseCrossingLine(null)).toBeNull();
expect(parseCrossingLine({ p1: { x: "0.1", y: 0.5 }, p2: line.p2, direction: "both" })).toBeNull();
});
});
+54
View File
@@ -2211,3 +2211,57 @@ export function effectiveModules(entitled: readonly ModuleId[], activated: reado
} }
return MODULE_IDS.filter((id) => on.has(id)); return MODULE_IDS.filter((id) => on.has(id));
} }
// --- Passage confirmation: a crossing line drawn over a camera's view ---------
// The fleet cameras have no line-crossing rule of their own, so Setup draws one (like a
// Hikvision Line Crossing rule: a segment, sides A and B, and the direction that counts),
// and the booth's own tracker judges the crossing. See wiki/concepts/passage-confirmation.md.
/** Which crossing counts as a passage: A→B, B→A, or either (A↔B). */
export const CROSSING_DIRECTIONS = ["a-to-b", "b-to-a", "both"] as const;
export type CrossingDirection = (typeof CROSSING_DIRECTIONS)[number];
/** A point normalised to the camera frame: x right, y down, both 0..1. */
export interface FramePoint {
x: number;
y: number;
}
/** Stored as camera `config.crossing`. Side A is on the LEFT of p1→p2 as seen on screen;
* swapping the sides is swapping the two points. */
export interface CrossingLine {
p1: FramePoint;
p2: FramePoint;
direction: CrossingDirection;
}
/** Shortest line accepted (normalised length) — a click, not a drawn line. */
export const CROSSING_MIN_LENGTH = 0.03;
/** A valid `CrossingLine` from untrusted JSON, or null. */
export function parseCrossingLine(v: unknown): CrossingLine | null {
if (!v || typeof v !== "object") return null;
const o = v as Record<string, unknown>;
const pt = (p: unknown): FramePoint | null => {
if (!p || typeof p !== "object") return null;
const { x, y } = p as Record<string, unknown>;
if (typeof x !== "number" || typeof y !== "number") return null;
if (!(x >= 0 && x <= 1 && y >= 0 && y <= 1)) return null;
return { x, y };
};
const p1 = pt(o.p1);
const p2 = pt(o.p2);
const direction = o.direction;
if (!p1 || !p2) return null;
if (!CROSSING_DIRECTIONS.includes(direction as CrossingDirection)) return null;
if (Math.hypot(p2.x - p1.x, p2.y - p1.y) < CROSSING_MIN_LENGTH) return null;
return { p1, p2, direction: direction as CrossingDirection };
}
/** Which side of the (infinite) line a point lies on, or null exactly on it. Note the
* frame's y axis points down: the left of p1→p2 on screen has a negative cross product. */
export function crossingSide(line: CrossingLine, pt: FramePoint): "a" | "b" | null {
const { p1, p2 } = line;
const cross = (p2.x - p1.x) * (pt.y - p1.y) - (p2.y - p1.y) * (pt.x - p1.x);
return cross < 0 ? "a" : cross > 0 ? "b" : null;
}