diff --git a/src/components/admin/npc-dialogue/NpcDialogueEditor.tsx b/src/components/admin/npc-dialogue/NpcDialogueEditor.tsx index 8ab2eda6..e755adea 100644 --- a/src/components/admin/npc-dialogue/NpcDialogueEditor.tsx +++ b/src/components/admin/npc-dialogue/NpcDialogueEditor.tsx @@ -12,6 +12,7 @@ import { Background, type Connection, type Edge, + MarkerType, type Node, ReactFlow, ReactFlowProvider, @@ -34,6 +35,7 @@ import type { import { deriveEdges, validateGraph } from "@/lib/npc-dialogue/dialogue"; import { NpcDialogueNode } from "./NpcDialogueNode"; import { NodeEditDialog } from "./NodeEditDialog"; +import { RoutedFlowEdge } from "./RoutedFlowEdge"; const nodeTypes = { dialogue: NpcDialogueNode, @@ -44,6 +46,11 @@ const nodeTypes = { end: NpcDialogueNode, }; +const edgeTypes = { routed: RoutedFlowEdge }; + +/** Arrowhead tinted to match the animated cyan edge stroke. */ +const EDGE_MARKER = { type: MarkerType.ArrowClosed, width: 14, height: 14, color: "#67e8f9" }; + const defaultFlow: FlowData = { nodes: [], edges: [] }; type ContextMenu = { x: number; y: number; nodeId: string } | null; @@ -90,8 +97,16 @@ function FlowEditor() { const canvasRef = useRef(null); // Edges are a derived projection of the node data, never edited directly. + // Every edge renders through the routed edge type so lines bend around + // unrelated cards instead of slicing through them. const syncedEdges = useMemo( - () => deriveEdges(nodes as DialogueNode[]), + () => + deriveEdges(nodes as DialogueNode[]).map((edge) => ({ + ...edge, + type: "routed", + animated: true, + markerEnd: EDGE_MARKER, + })), [nodes], ); @@ -461,10 +476,10 @@ function FlowEditor() { onPaneClick={onPaneClick} onPaneContextMenu={onPaneContextMenu} nodeTypes={nodeTypes} + edgeTypes={edgeTypes} fitView zoomOnDoubleClick={false} colorMode="dark" - defaultEdgeOptions={{ animated: true }} proOptions={{ hideAttribution: true }} > diff --git a/src/components/admin/npc-dialogue/RoutedFlowEdge.tsx b/src/components/admin/npc-dialogue/RoutedFlowEdge.tsx new file mode 100644 index 00000000..f92ffd7f --- /dev/null +++ b/src/components/admin/npc-dialogue/RoutedFlowEdge.tsx @@ -0,0 +1,132 @@ +"use client"; + +/** + * Flow edge that routes around node cards instead of cutting through them. + * + * The dialogue graph loops back a lot (a choice returning to an earlier + * line), and plain Bezier connectors sliced straight through unrelated + * cards, which made return paths impossible to trace. This edge builds a + * short orthogonal base polyline (perpendicular stubs at each handle so + * lines leave cards at right angles) and hands it to the shared detour + * router (`@/lib/flow-edge-routing`), then renders the result with rounded + * corners, an arrowhead, and the condition label as a chip at the path + * midpoint so text stays readable over other geometry. + */ +import { useMemo } from "react"; +import { BaseEdge, EdgeLabelRenderer, Position, useStore, type EdgeProps } from "@xyflow/react"; + +import { + buildRoutePath, + polylineMidpoint, + routeAroundObstacles, + segmentCrossesRect, + type RoutePoint, + type RouteRect, +} from "@/lib/flow-edge-routing"; + +/** How far the line leaves a handle before it may bend (px). */ +const STUB = 24; + +function stubFor(point: RoutePoint, position: Position | null, length: number): RoutePoint { + switch (position) { + case Position.Left: + return { x: point.x - length, y: point.y }; + case Position.Right: + return { x: point.x + length, y: point.y }; + case Position.Top: + return { x: point.x, y: point.y - length }; + case Position.Bottom: + return { x: point.x, y: point.y + length }; + default: + return point; + } +} + +export function RoutedFlowEdge({ + id, + source, + target, + sourceX, + sourceY, + targetX, + targetY, + sourcePosition, + targetPosition, + markerEnd, + label, +}: EdgeProps) { + const nodeLookup = useStore((s) => s.nodeLookup); + + // For left-to-right edges the two endpoint cards never sit in the path, so + // they stay out of the obstacle list. Back edges do cross their own ends, + // so there every card (including ours) is an obstacle and the line loops + // around the cards instead of through them. + const { forwardObstacles, allObstacles } = useMemo(() => { + const all: RouteRect[] = []; + nodeLookup.forEach((node) => { + const width = node.measured?.width ?? 0; + const height = node.measured?.height ?? 0; + if (!width || !height) return; + const { x, y } = node.internals.positionAbsolute; + all.push({ id: node.id, x, y, width, height }); + }); + const forward = all.filter((r) => r.id !== source && r.id !== target); + return { forwardObstacles: forward, allObstacles: all }; + }, [nodeLookup, source, target]); + + const start: RoutePoint = { x: sourceX, y: sourceY }; + const end: RoutePoint = { x: targetX, y: targetY }; + const isBackEdge = end.x < start.x; + + const base: RoutePoint[] = (() => { + if (isBackEdge) { + // Stub out of each handle, then a direct run the router bends around + // every card in between. + return [start, stubFor(start, sourcePosition, STUB), stubFor(end, targetPosition, STUB), end]; + } + const sStub = stubFor(start, sourcePosition, STUB); + const tStub = stubFor(end, targetPosition, STUB); + const midX = (sStub.x + tStub.x) / 2; + const orthogonal: RoutePoint[] = [ + start, + sStub, + { x: midX, y: sStub.y }, + { x: midX, y: tStub.y }, + tStub, + end, + ]; + const crossesCard = (points: RoutePoint[]) => + points.some((p, i) => + i < points.length - 1 ? forwardObstacles.some((r) => segmentCrossesRect(p, points[i + 1], r)) : false, + ); + // The Z-shaped step looks best, but when it slices through cards a plain + // stubbed straight line routes cleaner after detouring. + return crossesCard(orthogonal) ? [start, sStub, tStub, end] : orthogonal; + })(); + + const obstacles = isBackEdge ? allObstacles : forwardObstacles; + const routed = routeAroundObstacles(base, obstacles); + const path = buildRoutePath(routed); + const mid = polylineMidpoint(routed.length >= 2 ? routed : [start, end]); + + const labelText = typeof label === "string" || typeof label === "number" ? String(label) : null; + + return ( + <> + + {labelText ? ( + +
+ {labelText} +
+
+ ) : null} + + ); +} diff --git a/src/components/admin/tech-tree/edgeRoutes.ts b/src/components/admin/tech-tree/edgeRoutes.ts index 3cb1cb76..acd5fd6f 100644 --- a/src/components/admin/tech-tree/edgeRoutes.ts +++ b/src/components/admin/tech-tree/edgeRoutes.ts @@ -8,9 +8,14 @@ * Storage is per-browser (localStorage): routing is a personal viewing aid * rather than shared tree data. Promoting it to a persisted field on the * target technology is a small change once the schema settles. + * + * The path builder itself is shared (`@/lib/flow-edge-routing`); this module + * keeps only the per-browser persistence. */ +import { type RouteWaypoint } from "@/lib/flow-edge-routing"; + +export { buildRoutePath, ROUTE_CORNER_RADIUS, type RouteWaypoint } from "@/lib/flow-edge-routing"; -export type RouteWaypoint = { x: number; y: number }; export type EdgeRouteMap = Record; const STORAGE_KEY = "ptf:tech-tree:edge-routes"; @@ -40,46 +45,3 @@ export function saveEdgeRoutes(routes: EdgeRouteMap): void { // Storage can be unavailable (private mode); routing just won't persist. } } - -/** Corner rounding radius (px) at each waypoint. */ -export const ROUTE_CORNER_RADIUS = 14; - -function distance(a: RouteWaypoint, b: RouteWaypoint): number { - return Math.hypot(b.x - a.x, b.y - a.y); -} - -/** - * SVG path through the given points. Each interior corner is cut with a - * quadratic curve so bends read as smooth corners instead of hard angles; the - * radius shrinks automatically on short segments so curves never overshoot. - */ -export function buildRoutePath(points: RouteWaypoint[], radius = ROUTE_CORNER_RADIUS): string { - if (points.length < 2) return ""; - const start = points[0]; - let d = `M ${start.x},${start.y}`; - - for (let i = 1; i < points.length - 1; i += 1) { - const prev = points[i - 1]; - const cur = points[i]; - const next = points[i + 1]; - const inLen = distance(prev, cur); - const outLen = distance(cur, next); - if (inLen === 0 || outLen === 0) { - d += ` L ${cur.x},${cur.y}`; - continue; - } - const r = Math.min(radius, inLen / 2, outLen / 2); - const a = { - x: cur.x - ((cur.x - prev.x) / inLen) * r, - y: cur.y - ((cur.y - prev.y) / inLen) * r, - }; - const b = { - x: cur.x + ((next.x - cur.x) / outLen) * r, - y: cur.y + ((next.y - cur.y) / outLen) * r, - }; - d += ` L ${a.x},${a.y} Q ${cur.x},${cur.y} ${b.x},${b.y}`; - } - - const end = points[points.length - 1]; - return `${d} L ${end.x},${end.y}`; -} diff --git a/src/components/admin/tech-tree/edgeRouting.ts b/src/components/admin/tech-tree/edgeRouting.ts index fedcf645..a25d946b 100644 --- a/src/components/admin/tech-tree/edgeRouting.ts +++ b/src/components/admin/tech-tree/edgeRouting.ts @@ -1,133 +1,8 @@ /** * Obstacle-avoiding routing for Tech Tree edges. * - * A prerequisite edge should not cut through technologies it is not connected - * to. Given the polyline an edge would take (source -> optional waypoints -> - * target) and the rectangles of every OTHER node, this inserts detour points - * so each segment swings around the boxes it would otherwise cross. - * - * The detour is greedy: for the first box a segment hits, it tries that box's - * four (inflated) corners and picks the one with the shortest total bend, - * recursing on the two halves. Bounded depth keeps it cheap and terminating. + * The generic router now lives in `@/lib/flow-edge-routing` (shared with the + * NPC dialogue flow editor); this module re-exports it so tech-tree imports + * stay stable. */ - -export type RouteRect = { id: number; x: number; y: number; width: number; height: number }; -export type RoutePoint = { x: number; y: number }; - -/** Clearance kept around a node when routing around it. */ -export const ROUTE_CLEARANCE = 22; -const MAX_DEPTH = 3; -const EPS = 1; - -/** Does segment a->b cross the interior of rect r? (exported for tests) */ -export function segmentCrossesRect(a: RoutePoint, b: RoutePoint, r: RouteRect): boolean { - const x1 = r.x + EPS; - const y1 = r.y + EPS; - const x2 = r.x + r.width - EPS; - const y2 = r.y + r.height - EPS; - if (x2 <= x1 || y2 <= y1) return false; - - // Liang-Barsky clip of the segment against the (slightly inset) box. - let t0 = 0; - let t1 = 1; - const dx = b.x - a.x; - const dy = b.y - a.y; - const p = [-dx, dx, -dy, dy]; - const q = [a.x - x1, x2 - a.x, a.y - y1, y2 - a.y]; - for (let i = 0; i < 4; i += 1) { - if (p[i] === 0) { - if (q[i] < 0) return false; - } else { - const t = q[i] / p[i]; - if (p[i] < 0) { - if (t > t1) return false; - if (t > t0) t0 = t; - } else { - if (t < t0) return false; - if (t < t1) t1 = t; - } - } - } - return true; -} - -const crosses = segmentCrossesRect; - -function corners(r: RouteRect, margin: number): RoutePoint[] { - const x1 = r.x - margin; - const y1 = r.y - margin; - const x2 = r.x + r.width + margin; - const y2 = r.y + r.height + margin; - return [ - { x: x1, y: y1 }, - { x: x2, y: y1 }, - { x: x2, y: y2 }, - { x: x1, y: y2 }, - ]; -} - -function inside(p: RoutePoint, r: RouteRect, margin: number): boolean { - return ( - p.x > r.x - margin && p.x < r.x + r.width + margin && p.y > r.y - margin && p.y < r.y + r.height + margin - ); -} - -function dist(a: RoutePoint, b: RoutePoint): number { - return Math.hypot(b.x - a.x, b.y - a.y); -} - -/** Detour points from a to b (excluding a, ending with b). */ -function detour( - a: RoutePoint, - b: RoutePoint, - obstacles: RouteRect[], - margin: number, - depth: number, -): RoutePoint[] { - if (depth >= MAX_DEPTH) return [b]; - const hit = obstacles.find((r) => crosses(a, b, r)); - if (!hit) return [b]; - - let best: RoutePoint | null = null; - let bestLen = Number.POSITIVE_INFINITY; - for (const c of corners(hit, margin)) { - // Skip a corner inside another box, or one not reachable from `a` without - // still cutting through the box. The second half is left to the recursion, - // which chains a second corner for wide boxes. - if (obstacles.some((r) => r.id !== hit.id && inside(c, r, 0))) continue; - if (crosses(a, c, hit)) continue; - // A corner at the current point or the destination makes no progress. - if (dist(a, c) < 1 || dist(c, b) < 1) continue; - const len = dist(a, c) + dist(c, b); - if (len < bestLen) { - bestLen = len; - best = c; - } - } - if (!best) return [b]; - - return [ - ...detour(a, best, obstacles, margin, depth + 1), - ...detour(best, b, obstacles, margin, depth + 1), - ]; -} - -/** - * Route a polyline around the given obstacle boxes. Returns a new point list; - * returns the input unchanged when there is nothing to avoid. - */ -export function routeAroundObstacles( - points: RoutePoint[], - obstacles: RouteRect[], - margin = ROUTE_CLEARANCE, -): RoutePoint[] { - if (points.length < 2 || obstacles.length === 0) return points; - const out: RoutePoint[] = [points[0]]; - for (let i = 0; i < points.length - 1; i += 1) { - for (const p of detour(points[i], points[i + 1], obstacles, margin, 0)) { - const last = out[out.length - 1]; - if (Math.abs(p.x - last.x) > 0.5 || Math.abs(p.y - last.y) > 0.5) out.push(p); - } - } - return out; -} +export * from "@/lib/flow-edge-routing"; diff --git a/src/lib/flow-edge-routing.ts b/src/lib/flow-edge-routing.ts new file mode 100644 index 00000000..9fe15b54 --- /dev/null +++ b/src/lib/flow-edge-routing.ts @@ -0,0 +1,212 @@ +/** + * Obstacle-avoiding edge routing shared by the admin flow canvases + * (tech tree, NPC dialogue flow editor). + * + * An edge should not cut through nodes it is not connected to. Given the + * polyline an edge would take (source -> optional waypoints -> target) and + * the rectangles of every other node, this inserts detour points so each + * segment swings around the boxes it would otherwise cross. + * + * The detour is greedy: for the first box a segment hits, it tries that box's + * four (inflated) corners and picks the one with the shortest total bend, + * recursing on the two halves. Bounded depth keeps it cheap and terminating. + * + * Pure module: no React/Payload imports, safe on client and server. + */ + +export type RoutePoint = { x: number; y: number }; +/** A node rectangle to route around. Ids may be numeric or string. */ +export type RouteRect = { + id: number | string; + x: number; + y: number; + width: number; + height: number; +}; + +/** Clearance kept around a node when routing around it. */ +export const ROUTE_CLEARANCE = 22; +const MAX_DEPTH = 3; +const EPS = 1; + +/** Does segment a->b cross the interior of rect r? (exported for tests) */ +export function segmentCrossesRect(a: RoutePoint, b: RoutePoint, r: RouteRect): boolean { + const x1 = r.x + EPS; + const y1 = r.y + EPS; + const x2 = r.x + r.width - EPS; + const y2 = r.y + r.height - EPS; + if (x2 <= x1 || y2 <= y1) return false; + + // Liang-Barsky clip of the segment against the (slightly inset) box. + let t0 = 0; + let t1 = 1; + const dx = b.x - a.x; + const dy = b.y - a.y; + const p = [-dx, dx, -dy, dy]; + const q = [a.x - x1, x2 - a.x, a.y - y1, y2 - a.y]; + for (let i = 0; i < 4; i += 1) { + if (p[i] === 0) { + if (q[i] < 0) return false; + } else { + const t = q[i] / p[i]; + if (p[i] < 0) { + if (t > t1) return false; + if (t > t0) t0 = t; + } else { + if (t < t0) return false; + if (t < t1) t1 = t; + } + } + } + return true; +} + +const crosses = segmentCrossesRect; + +function corners(r: RouteRect, margin: number): RoutePoint[] { + const x1 = r.x - margin; + const y1 = r.y - margin; + const x2 = r.x + r.width + margin; + const y2 = r.y + r.height + margin; + return [ + { x: x1, y: y1 }, + { x: x2, y: y1 }, + { x: x2, y: y2 }, + { x: x1, y: y2 }, + ]; +} + +function inside(p: RoutePoint, r: RouteRect, margin: number): boolean { + return ( + p.x > r.x - margin && + p.x < r.x + r.width + margin && + p.y > r.y - margin && + p.y < r.y + r.height + margin + ); +} + +function dist(a: RoutePoint, b: RoutePoint): number { + return Math.hypot(b.x - a.x, b.y - a.y); +} + +/** Detour points from a to b (excluding a, ending with b). */ +function detour( + a: RoutePoint, + b: RoutePoint, + obstacles: RouteRect[], + margin: number, + depth: number, +): RoutePoint[] { + if (depth >= MAX_DEPTH) return [b]; + const hit = obstacles.find((r) => crosses(a, b, r)); + if (!hit) return [b]; + + let best: RoutePoint | null = null; + let bestLen = Number.POSITIVE_INFINITY; + for (const c of corners(hit, margin)) { + // Skip a corner inside another box, or one not reachable from `a` without + // still cutting through the box. The second half is left to the recursion, + // which chains a second corner for wide boxes. + if (obstacles.some((r) => r.id !== hit.id && inside(c, r, 0))) continue; + if (crosses(a, c, hit)) continue; + // A corner at the current point or the destination makes no progress. + if (dist(a, c) < 1 || dist(c, b) < 1) continue; + const len = dist(a, c) + dist(c, b); + if (len < bestLen) { + bestLen = len; + best = c; + } + } + if (!best) return [b]; + + return [ + ...detour(a, best, obstacles, margin, depth + 1), + ...detour(best, b, obstacles, margin, depth + 1), + ]; +} + +/** + * Route a polyline around the given obstacle boxes. Returns a new point list; + * returns the input unchanged when there is nothing to avoid. + */ +export function routeAroundObstacles( + points: RoutePoint[], + obstacles: RouteRect[], + margin = ROUTE_CLEARANCE, +): RoutePoint[] { + if (points.length < 2 || obstacles.length === 0) return points; + const out: RoutePoint[] = [points[0]]; + for (let i = 0; i < points.length - 1; i += 1) { + for (const p of detour(points[i], points[i + 1], obstacles, margin, 0)) { + const last = out[out.length - 1]; + if (Math.abs(p.x - last.x) > 0.5 || Math.abs(p.y - last.y) > 0.5) out.push(p); + } + } + return out; +} + +// --------------------------------------------------------------------------- +// Path building +// --------------------------------------------------------------------------- + +export type RouteWaypoint = RoutePoint; + +/** Corner rounding radius (px) at each waypoint. */ +export const ROUTE_CORNER_RADIUS = 14; + +/** + * SVG path through the given points. Each interior corner is cut with a + * quadratic curve so bends read as smooth corners instead of hard angles; the + * radius shrinks automatically on short segments so curves never overshoot. + */ +export function buildRoutePath(points: RouteWaypoint[], radius = ROUTE_CORNER_RADIUS): string { + if (points.length < 2) return ""; + const start = points[0]; + let d = `M ${start.x},${start.y}`; + + for (let i = 1; i < points.length - 1; i += 1) { + const prev = points[i - 1]; + const cur = points[i]; + const next = points[i + 1]; + const inLen = dist(prev, cur); + const outLen = dist(cur, next); + if (inLen === 0 || outLen === 0) { + d += ` L ${cur.x},${cur.y}`; + continue; + } + const r = Math.min(radius, inLen / 2, outLen / 2); + const a = { + x: cur.x - ((cur.x - prev.x) / inLen) * r, + y: cur.y - ((cur.y - prev.y) / inLen) * r, + }; + const b = { + x: cur.x + ((next.x - cur.x) / outLen) * r, + y: cur.y + ((next.y - cur.y) / outLen) * r, + }; + d += ` L ${a.x},${a.y} Q ${cur.x},${cur.y} ${b.x},${b.y}`; + } + + const end = points[points.length - 1]; + return `${d} L ${end.x},${end.y}`; +} + +/** Point at half the total polyline length, for placing edge labels. */ +export function polylineMidpoint(points: RoutePoint[]): RoutePoint { + if (points.length === 0) return { x: 0, y: 0 }; + if (points.length === 1) return points[0]; + let total = 0; + for (let i = 0; i < points.length - 1; i += 1) total += dist(points[i], points[i + 1]); + let target = total / 2; + for (let i = 0; i < points.length - 1; i += 1) { + const seg = dist(points[i], points[i + 1]); + if (target <= seg) { + const t = seg === 0 ? 0 : target / seg; + return { + x: points[i].x + (points[i + 1].x - points[i].x) * t, + y: points[i].y + (points[i + 1].y - points[i].y) * t, + }; + } + target -= seg; + } + return points[points.length - 1]; +}