diff --git a/src/app/(frontend)/intelligence/factions/relations/page.tsx b/src/app/(frontend)/intelligence/factions/relations/page.tsx index e612340a..eb974c7e 100644 --- a/src/app/(frontend)/intelligence/factions/relations/page.tsx +++ b/src/app/(frontend)/intelligence/factions/relations/page.tsx @@ -2,8 +2,10 @@ import config from "@payload-config"; import { getPayload } from "payload"; import { headers as nextHeaders } from "next/headers"; import Link from "next/link"; -import { ArrowLeftIcon, ScaleIcon } from "lucide-react"; +import { ArrowLeftIcon, ScaleIcon, Share2Icon, TableIcon } from "lucide-react"; +import { FactionRelationGraph } from "@/components/frontend/intelligence/FactionRelationGraph"; import { getRelationContext } from "@/lib/intelligence/factionRelationLedger"; +import type { GraphScore } from "@/lib/intelligence/factionGraphLayout"; import { formatScore, pairKey, @@ -24,7 +26,12 @@ const TYPE_ORDER: Record = { special: 4, }; -export default async function FactionRelationsPage() { +export default async function FactionRelationsPage({ + searchParams, +}: { + searchParams: Promise<{ view?: string }>; +}) { + const { view } = await searchParams; const payload = await getPayload({ config }); const { user } = await payload.auth({ headers: await nextHeaders(), @@ -32,6 +39,7 @@ export default async function FactionRelationsPage() { }); const context = await getRelationContext(payload, user); + const showGraph = view === "graph"; // Player faction first, then majors down to specials, so the matrix reads in // the same order the faction list uses. @@ -39,6 +47,13 @@ export default async function FactionRelationsPage() { (a, b) => (TYPE_ORDER[a.type] ?? 99) - (TYPE_ORDER[b.type] ?? 99), ); + // The graph wants a flat directed list; the matrix wants the map. Both come + // from the same derived scores, so the two views cannot disagree. + const graphScores: GraphScore[] = [...context.scores].map(([key, score]) => { + const [subjectId, targetId] = key.split(":").map(Number); + return { subjectId, targetId, score }; + }); + return (
@@ -49,29 +64,61 @@ export default async function FactionRelationsPage() { Back to Factions -
- -

Faction Relations

+
+
+ +

Faction Relations

+
+
+ + + Matrix + + + + Graph + +

- Each row reads how that faction currently regards each column, accumulated from recorded - events. The two directions of a relationship are independent, so one faction can respect - another that despises it. + {showGraph + ? "The player faction sits at the center, with everyone else on rings by classification. Each line is one faction's attitude toward another; hover a faction to isolate its web." + : "Each row reads how that faction currently regards each column, accumulated from recorded events. The two directions of a relationship are independent, so one faction can respect another that despises it."}

-
- Scale - {RELATION_BANDS.map((band) => ( - - - {band.label} - - ))} -
+ {showGraph ? ( + + ) : ( + <> +
+ Scale + {RELATION_BANDS.map((band) => ( + + + {band.label} + + ))} +
{factions.length === 0 ? (
@@ -150,10 +197,12 @@ export default async function FactionRelationsPage() {
)} + + )}

- Entries are recorded from the admin panel under Intelligence, Relation Entries. Scores are - clamped to -100..100, and a zero can mean a clean slate or events that cancelled out. + Scores are clamped to -100..100, and a zero can mean a clean slate or events that cancelled + out.

); diff --git a/src/components/frontend/intelligence/FactionRelationGraph.tsx b/src/components/frontend/intelligence/FactionRelationGraph.tsx new file mode 100644 index 00000000..989bafa1 --- /dev/null +++ b/src/components/frontend/intelligence/FactionRelationGraph.tsx @@ -0,0 +1,428 @@ +"use client"; + +import React from "react"; +import { useRouter } from "next/navigation"; +import { MaximizeIcon, RotateCcwIcon } from "lucide-react"; + +import { + BAND_COLORS, + layoutFactionGraph, + linkStrokeWidth, + type GraphFaction, + type GraphScore, +} from "@/lib/intelligence/factionGraphLayout"; +import { formatScore, RELATION_BANDS } from "@/lib/intelligence/factionRelations"; +import { cn } from "@/lib/utils"; + +interface FactionRelationGraphProps { + factions: GraphFaction[]; + scores: GraphScore[]; +} + +const TYPE_LABELS: Record = { + playerFaction: "Player faction", + majorFaction: "Major faction", + minorFaction: "Minor faction", + corporation: "Corporation", + special: "Special", +}; + +const MIN_ZOOM = 0.4; +const MAX_ZOOM = 4; + +function clamp(value: number, min: number, max: number): number { + return Math.max(min, Math.min(max, value)); +} + +function truncateLabel(name: string): string { + return name.length > 20 ? `${name.slice(0, 18)}…` : name; +} + +/** + * Where a node's label goes, as an offset from the node's own center (the group + * around it is already translated): outward along its radius for ring members, + * below for the hub, and to the side when the outward direction is mostly + * horizontal. + */ +function labelPlacement( + node: { x: number; y: number; radius: number }, + center: { x: number; y: number }, + isHub: boolean, +): { dx: number; dy: number; anchor: "start" | "middle" | "end" } { + if (isHub) return { dx: 0, dy: node.radius + 15, anchor: "middle" }; + + const dx = node.x - center.x; + const dy = node.y - center.y; + const length = Math.hypot(dx, dy) || 1; + const ux = dx / length; + const uy = dy / length; + + if (Math.abs(uy) >= 0.5) { + // Mostly above or below the center: keep the label centered and push it out + // vertically, so the baseline clears the node. + return { dx: 0, dy: uy > 0 ? node.radius + 15 : -(node.radius + 8), anchor: "middle" }; + } + + return { + dx: ux > 0 ? node.radius + 9 : -(node.radius + 9), + dy: 4, + anchor: ux > 0 ? "start" : "end", + }; +} + +/** + * Radial directed graph of faction relations. + * + * Hand-drawn SVG rather than a graph library: the whole picture is one arc per + * direction between two fixed points, so the only thing a library would add is + * drag-to-rearrange, which this view deliberately does not want (positions are + * meaningful). Pan, zoom, hover focus and click-through are all local. + */ +export function FactionRelationGraph({ factions, scores }: FactionRelationGraphProps) { + const router = useRouter(); + const svgRef = React.useRef(null); + const dragRef = React.useRef<{ x: number; y: number; moved: boolean } | null>(null); + const [view, setView] = React.useState({ x: 0, y: 0, k: 1 }); + const [hoveredId, setHoveredId] = React.useState(null); + const [panning, setPanning] = React.useState(false); + + const layout = React.useMemo(() => layoutFactionGraph(factions, scores), [factions, scores]); + + const nodeById = React.useMemo( + () => new Map(layout.nodes.map((node) => [node.id, node])), + [layout.nodes], + ); + + const hoveredRelations = React.useMemo(() => { + if (hoveredId == null) return null; + const outgoing = scores + .filter((score) => score.subjectId === hoveredId && score.score !== 0) + .sort((a, b) => Math.abs(b.score) - Math.abs(a.score)); + const incoming = scores + .filter((score) => score.targetId === hoveredId && score.score !== 0) + .sort((a, b) => Math.abs(b.score) - Math.abs(a.score)); + return { outgoing, incoming }; + }, [hoveredId, scores]); + + const clientToViewBox = React.useCallback((clientX: number, clientY: number) => { + const svg = svgRef.current; + const ctm = svg?.getScreenCTM(); + if (!svg || !ctm) return null; + const point = svg.createSVGPoint(); + point.x = clientX; + point.y = clientY; + const mapped = point.matrixTransform(ctm.inverse()); + return { x: mapped.x, y: mapped.y }; + }, []); + + React.useEffect(() => { + const svg = svgRef.current; + if (!svg) return; + const onWheel = (event: WheelEvent) => { + event.preventDefault(); + const anchor = clientToViewBox(event.clientX, event.clientY); + if (!anchor) return; + setView((current) => { + const factor = event.deltaY < 0 ? 1.12 : 1 / 1.12; + const nextZoom = clamp(current.k * factor, MIN_ZOOM, MAX_ZOOM); + const ratio = nextZoom / current.k; + return { + k: nextZoom, + x: anchor.x - (anchor.x - current.x) * ratio, + y: anchor.y - (anchor.y - current.y) * ratio, + }; + }); + }; + svg.addEventListener("wheel", onWheel, { passive: false }); + return () => svg.removeEventListener("wheel", onWheel); + }, [clientToViewBox]); + + const handlePointerDown = (event: React.PointerEvent) => { + dragRef.current = { x: event.clientX, y: event.clientY, moved: false }; + setPanning(true); + }; + + const handlePointerMove = (event: React.PointerEvent) => { + const drag = dragRef.current; + if (!drag) return; + const dxClient = event.clientX - drag.x; + const dyClient = event.clientY - drag.y; + if (!drag.moved && Math.hypot(dxClient, dyClient) < 4) return; + drag.moved = true; + // Screen pixels to viewBox units: the CTM scale is stable while panning. + const scale = svgRef.current?.getScreenCTM()?.a || 1; + drag.x = event.clientX; + drag.y = event.clientY; + setView((current) => ({ ...current, x: current.x + dxClient / scale, y: current.y + dyClient / scale })); + }; + + const endDrag = () => { + dragRef.current = null; + setPanning(false); + }; + + const openFaction = (id: number) => { + if (dragRef.current?.moved) return; + router.push(`/intelligence/factions/${id}`); + }; + + const resetView = () => { + setView({ x: 0, y: 0, k: 1 }); + setHoveredId(null); + }; + + if (layout.nodes.length === 0) { + return ( +
+

No factions found.

+
+ ); + } + + return ( +
+
+
+ + + {layout.rings.map((radius) => ( + + ))} + {layout.links.map((link) => { + const focus = + hoveredId == null || + link.halves.some( + (half) => half.subjectId === hoveredId || half.targetId === hoveredId, + ); + return ( + + {link.halves.map((half) => { + const color = BAND_COLORS[half.band.key]; + return ( + + + + + ); + })} + + ); + })} + + {layout.nodes.map((node) => { + const connected = + hoveredId == null || + node.id === hoveredId || + layout.links.some( + (link) => + link.halves.some((half) => half.subjectId === hoveredId) && + link.halves.some((half) => half.targetId === hoveredId) && + (link.halves.some((half) => half.subjectId === node.id) || + link.halves.some((half) => half.targetId === node.id)), + ); + const isHub = node.type === "playerFaction"; + const isHovered = node.id === hoveredId; + // Labels sit on the outward side of a node, away from the center, + // so converging segments do not run through them. + const label = labelPlacement(node, layout.center, isHub); + return ( + setHoveredId(node.id)} + onMouseLeave={() => setHoveredId((current) => (current === node.id ? null : current))} + onFocus={() => setHoveredId(node.id)} + onBlur={() => setHoveredId((current) => (current === node.id ? null : current))} + onClick={() => openFaction(node.id)} + onKeyDown={(event) => { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + openFaction(node.id); + } + }} + tabIndex={0} + role="link" + aria-label={`${node.name}, ${TYPE_LABELS[node.type] ?? node.type}, ${node.degree} recorded relations`} + > + + + + {truncateLabel(node.name)} + + + ); + })} + + + +
+ + + +
+ + {hoveredRelations ? ( +
+

{nodeById.get(hoveredId!)?.name}

+

+ {TYPE_LABELS[nodeById.get(hoveredId!)?.type ?? ""] ?? + nodeById.get(hoveredId!)?.type} +

+ nodeById.get(id)?.name ?? `Faction #${id}`} + pick={(score) => score.targetId} + /> + nodeById.get(id)?.name ?? `Faction #${id}`} + pick={(score) => score.subjectId} + /> +
+ ) : null} +
+ +
+ {RELATION_BANDS.map((band) => ( + + + {band.label} + + ))} + + Each line is one faction's attitude toward another. Where both sides have an opinion the + lines run side by side; arrows point at the faction being regarded. + +
+
+ ); +} + +function RelationList({ + title, + scores, + nameOf, + pick, +}: { + title: string; + scores: { subjectId: number; targetId: number; score: number }[]; + nameOf: (id: number) => string; + pick: (score: { subjectId: number; targetId: number; score: number }) => number; +}) { + if (scores.length === 0) return null; + return ( +
+

{title}

+
    + {scores.slice(0, 5).map((score) => { + const otherId = pick(score); + const color = + score.score >= 50 + ? "text-emerald-400" + : score.score >= 20 + ? "text-green-400" + : score.score > -20 + ? "text-muted-foreground" + : score.score > -50 + ? "text-amber-400" + : "text-red-400"; + return ( +
  • + {nameOf(otherId)} + + {formatScore(score.score)} + +
  • + ); + })} +
+
+ ); +} diff --git a/src/lib/intelligence/factionGraphLayout.ts b/src/lib/intelligence/factionGraphLayout.ts new file mode 100644 index 00000000..0552d1cb --- /dev/null +++ b/src/lib/intelligence/factionGraphLayout.ts @@ -0,0 +1,417 @@ +/** + * Radial layout for the faction relation graph (pure, client-safe). + * + * The graph answers a question the matrix cannot: who is tied to whom, and how + * that web holds together. Layout choices worth knowing: + * + * - The player faction sits at the center when one exists, so every relation + * it holds reads as a spoke. Everyone else is placed on concentric rings by + * classification (majors innermost, then minors, corporations, specials). + * - Positions are deterministic: rings are ordered by type, members by name, + * and the ring starts at the top. The picture is the same on every visit, so + * "the faction at two o'clock" means something from one session to the next. + * - Relations are straight segments. The two directions of one relationship + * run parallel, side by side on either side of the axis: each line spans the + * full distance between the factions, is colored and weighted by its own + * score, and carries an arrowhead at the faction being regarded. A pair with + * only one direction stays centered on the axis. + * - A segment that would run through an unrelated faction is nudged sideways + * just far enough to clear it. Straight lines stay straight; they only step + * aside when something is genuinely in the way. + */ + +import { relationBand, type RelationBand } from "./factionRelations"; + +export interface GraphFaction { + id: number; + name: string; + type: string; + discovered: boolean; +} + +/** One directed score: how `subjectId` regards `targetId`. */ +export interface GraphScore { + subjectId: number; + targetId: number; + score: number; +} + +export interface FactionGraphNode { + id: number; + name: string; + type: string; + discovered: boolean; + /** Center of the node in canvas coordinates. */ + x: number; + y: number; + radius: number; + /** How many directed relations touch this node. */ + degree: number; + ring: number; +} + +/** + * One direction of a pair: the line from its subject to its target, offset to + * one side when both directions are present, colored and weighted by that + * direction's score, arrowed at the faction being regarded. + */ +export interface FactionGraphHalf { + key: string; + subjectId: number; + targetId: number; + score: number; + band: RelationBand; + x1: number; + y1: number; + x2: number; + y2: number; + /** SVG polygon points for the arrowhead at (x2, y2). */ + arrowPoints: string; +} + +/** One pair of factions, holding whichever directions currently carry a score. */ +export interface FactionGraphLink { + key: string; + halves: FactionGraphHalf[]; +} + +export interface FactionGraphLayout { + nodes: FactionGraphNode[]; + links: FactionGraphLink[]; + width: number; + height: number; + /** Canvas coordinates of the hub, or of the ring system's origin when there is none. */ + center: { x: number; y: number }; + /** Radii of the rings actually used, outermost last. */ + rings: number[]; + /** True when a player faction was found and placed at the center. */ + hasHub: boolean; +} + +/** Stroke and marker colors per band. SVG cannot use Tailwind classes here. */ +export const BAND_COLORS: Record = { + allied: "#34d399", + friendly: "#4ade80", + neutral: "#94a3b8", + tense: "#fbbf24", + hostile: "#f87171", +}; + +/** Ring order, innermost first. Unknown types append at the end. */ +const TYPE_ORDER = ["majorFaction", "minorFaction", "corporation", "special"]; + +const RING_STEP = 210; +const BASE_NODE_RADIUS = 13; +const MAX_DEGREE_BONUS = 10; +const HUB_BONUS = 4; +const ARROW_LENGTH = 16; +const ARROW_HALF_WIDTH = 9; +/** How far the back edge is notched forward, giving the head barbs. */ +const ARROW_NOTCH = 5; +/** Breathing room between an arrowhead's tip and the node it points at. */ +const ARROW_GAP = 3; +const CANVAS_PADDING = 90; +/** Gap left between a segment and a node it is dodging. */ +const DODGE_CLEARANCE = 10; +/** Upper bound on how far a segment may be nudged, so it still reads as straight. */ +const MAX_DODGE = 40; +/** Perpendicular distance from the axis for each of a pair's two directions. */ +const PARALLEL_OFFSET = 7; + +interface Point { + x: number; + y: number; +} + +function degreeMap(scores: GraphScore[], ids: Set): Map { + const degree = new Map(); + for (const score of scores) { + if (score.score === 0) continue; + if (!ids.has(score.subjectId) || !ids.has(score.targetId)) continue; + degree.set(score.subjectId, (degree.get(score.subjectId) ?? 0) + 1); + degree.set(score.targetId, (degree.get(score.targetId) ?? 0) + 1); + } + return degree; +} + +function nodeRadius(degree: number, isHub: boolean): number { + const bonus = Math.min(MAX_DEGREE_BONUS, degree * 1.4); + return BASE_NODE_RADIUS + bonus + (isHub ? HUB_BONUS : 0); +} + +interface Geometry { + id: number; + x: number; + y: number; + radius: number; +} + +function round(value: number): number { + return Math.round(value * 100) / 100; +} + +/** + * Arrowhead at `tip`, pointing along (ux, uy). A solid triangle reads as a + * spike, so the back edge is notched: the barbs sweep back past the center, + * which is what makes a shape read as an arrowhead rather than a wedge. + */ +function arrowAt(tip: Point, ux: number, uy: number): string { + const baseX = tip.x - ux * ARROW_LENGTH; + const baseY = tip.y - uy * ARROW_LENGTH; + // The notch sits forward of the barb line, cutting into the head's back. + const notchX = tip.x - ux * (ARROW_LENGTH - ARROW_NOTCH); + const notchY = tip.y - uy * (ARROW_LENGTH - ARROW_NOTCH); + return [ + `${round(tip.x)},${round(tip.y)}`, + `${round(baseX - uy * ARROW_HALF_WIDTH)},${round(baseY + ux * ARROW_HALF_WIDTH)}`, + `${round(notchX)},${round(notchY)}`, + `${round(baseX + uy * ARROW_HALF_WIDTH)},${round(baseY - ux * ARROW_HALF_WIDTH)}`, + ].join(" "); +} + +/** + * The straight segment between two factions, trimmed to both node edges and + * nudged sideways if it would cut through a third node. `extraOffset` displaces + * the line perpendicular to the axis, which is how a pair's two directions run + * side by side instead of on top of each other. + */ +function segmentBetween( + a: Geometry, + b: Geometry, + obstacles: Geometry[], + extraOffset = 0, +): { start: Point; end: Point } { + const dx = b.x - a.x; + const dy = b.y - a.y; + const length = Math.hypot(dx, dy) || 1; + const ux = dx / length; + const uy = dy / length; + const nx = -uy; + const ny = ux; + + // Push the line off any node it would cross. The sign is whichever side the + // biggest obstruction sits on, so the segment moves away from it. + let dodge = 0; + let side = a.id < b.id ? 1 : -1; + for (const obstacle of obstacles) { + if (obstacle.id === a.id || obstacle.id === b.id) continue; + // Only nodes alongside the segment matter: one behind either end cannot be + // in the way, however close it is to the infinite line. + const along = (obstacle.x - a.x) * ux + (obstacle.y - a.y) * uy; + if (along <= 0 || along >= length) continue; + const signed = (obstacle.x - a.x) * nx + (obstacle.y - a.y) * ny; + const clearance = obstacle.radius + DODGE_CLEARANCE; + if (Math.abs(signed) >= clearance) continue; + const needed = clearance - Math.abs(signed); + if (needed > dodge) { + dodge = Math.min(MAX_DODGE, needed); + side = signed === 0 ? side : -Math.sign(signed); + } + } + + const total = side * dodge + extraOffset; + const ax = a.x + nx * total; + const ay = a.y + ny * total; + const bx = b.x + nx * total; + const by = b.y + ny * total; + + // On the shifted line, the perpendicular offset from each node center is the + // same `total`, so the trim distance follows directly from the radius. + const startOffset = Math.sqrt(Math.max(0, a.radius ** 2 - total ** 2)); + const endOffset = Math.sqrt(Math.max(0, b.radius ** 2 - total ** 2)); + + return { + start: { x: ax + ux * startOffset, y: ay + uy * startOffset }, + end: { x: bx - ux * endOffset, y: by - uy * endOffset }, + }; +} + +/** Stroke width grows with the magnitude of the score, capped so it stays legible. */ +export function linkStrokeWidth(score: number): number { + return round(1.2 + Math.min(3.2, Math.abs(score) / 22)); +} + +/** + * Lay out every faction and every relation. + * + * `scores` is the full directed map; zero and self scores are ignored. + */ +export function layoutFactionGraph( + factions: GraphFaction[], + scores: GraphScore[], +): FactionGraphLayout { + if (factions.length === 0) { + return { + nodes: [], + links: [], + width: 0, + height: 0, + center: { x: 0, y: 0 }, + rings: [], + hasHub: false, + }; + } + + const byId = new Map(factions.map((faction) => [faction.id, faction])); + const degree = degreeMap(scores, new Set(byId.keys())); + + const hub = factions.find((faction) => faction.type === "playerFaction"); + const rest = factions + .filter((faction) => !hub || faction.id !== hub.id) + .sort((a, b) => a.name.localeCompare(b.name) || a.id - b.id); + + const rings = new Map(); + for (const faction of rest) { + const list = rings.get(faction.type) ?? []; + list.push(faction); + rings.set(faction.type, list); + } + const ringOrder = [ + ...TYPE_ORDER.filter((type) => rings.has(type)), + ...[...rings.keys()].filter((type) => !TYPE_ORDER.includes(type)).sort(), + ]; + + const raw: { faction: GraphFaction; x: number; y: number; ring: number }[] = []; + if (hub) raw.push({ faction: hub, x: 0, y: 0, ring: 0 }); + + const ringsUsed: number[] = []; + ringOrder.forEach((type, ringIndex) => { + const members = rings.get(type) ?? []; + if (members.length === 0) return; + const radius = RING_STEP * (ringIndex + 1); + ringsUsed.push(radius); + // Outer rings fan slightly so a single-member ring does not sit on the same + // spoke as an inner one. + const ringOffset = ringIndex * 0.35; + members.forEach((faction, index) => { + // Start at the top and go clockwise so the first ring member sits at + // twelve o'clock, where it is easiest to read. + const angle = -Math.PI / 2 + ringOffset + (index * 2 * Math.PI) / members.length; + raw.push({ + faction, + x: Math.cos(angle) * radius, + y: Math.sin(angle) * radius, + ring: ringIndex + 1, + }); + }); + }); + + const radii = new Map( + raw.map((entry) => [ + entry.faction.id, + nodeRadius(degree.get(entry.faction.id) ?? 0, hub ? entry.faction.id === hub.id : false), + ]), + ); + + // Square canvas, content centered: a radial graph reads as a circle, and a + // square viewBox keeps it from being stretched by a wide container. + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const entry of raw) { + const radius = radii.get(entry.faction.id) ?? BASE_NODE_RADIUS; + minX = Math.min(minX, entry.x - radius); + minY = Math.min(minY, entry.y - radius); + maxX = Math.max(maxX, entry.x + radius); + maxY = Math.max(maxY, entry.y + radius); + } + const contentWidth = maxX - minX; + const contentHeight = maxY - minY; + const side = Math.max(contentWidth, contentHeight) + CANVAS_PADDING * 2; + const offsetX = (side - contentWidth) / 2 - minX; + const offsetY = (side - contentHeight) / 2 - minY; + + const nodes: FactionGraphNode[] = raw.map((entry) => ({ + id: entry.faction.id, + name: entry.faction.name, + type: entry.faction.type, + discovered: entry.faction.discovered, + x: round(entry.x + offsetX), + y: round(entry.y + offsetY), + radius: radii.get(entry.faction.id) ?? BASE_NODE_RADIUS, + degree: degree.get(entry.faction.id) ?? 0, + ring: entry.ring, + })); + + const geometry = new Map( + nodes.map((node) => [node.id, { id: node.id, x: node.x, y: node.y, radius: node.radius }]), + ); + + // Group the directed scores by pair so one segment can carry both directions. + const pairScores = new Map(); + for (const score of scores) { + if (score.score === 0 || score.subjectId === score.targetId) continue; + if (!geometry.has(score.subjectId) || !geometry.has(score.targetId)) continue; + const pair = `${Math.min(score.subjectId, score.targetId)}:${Math.max(score.subjectId, score.targetId)}`; + const list = pairScores.get(pair) ?? []; + list.push(score); + pairScores.set(pair, list); + } + + const links: FactionGraphLink[] = []; + const obstacleList = [...geometry.values()]; + for (const [pair, pairEntries] of [...pairScores].sort(([a], [b]) => a.localeCompare(b))) { + const [firstId, secondId] = pair.split(":").map(Number); + const a = geometry.get(firstId); + const b = geometry.get(secondId); + if (!a || !b) continue; + + const axisDx = b.x - a.x; + const axisDy = b.y - a.y; + const axisLength = Math.hypot(axisDx, axisDy) || 1; + const ux = axisDx / axisLength; + const uy = axisDy / axisLength; + + // A pair's two directions run parallel, one on each side of the axis, each + // spanning the full distance between the factions. A lone direction stays + // centered on the axis. + const sorted = [...pairEntries].sort((left, right) => left.subjectId - right.subjectId); + const halves: FactionGraphHalf[] = sorted.map((entry, index) => { + const offset = sorted.length > 1 ? (index === 0 ? -PARALLEL_OFFSET : PARALLEL_OFFSET) : 0; + const { start, end } = segmentBetween(a, b, obstacleList, offset); + const forward = entry.subjectId === firstId; + const from = forward ? start : end; + const edge = forward ? end : start; + const dirX = forward ? ux : -ux; + const dirY = forward ? uy : -uy; + // Sit the head just off the node's edge rather than over its ring. + const tip = { x: edge.x - dirX * ARROW_GAP, y: edge.y - dirY * ARROW_GAP }; + // Stop the stroke at the notch in the head's back, one unit in, so the + // shaft meets the head with no seam and the barbs stay unfilled. + const strokeEnd = { + x: tip.x - dirX * (ARROW_LENGTH - ARROW_NOTCH - 1), + y: tip.y - dirY * (ARROW_LENGTH - ARROW_NOTCH - 1), + }; + return { + key: `${entry.subjectId}:${entry.targetId}`, + subjectId: entry.subjectId, + targetId: entry.targetId, + score: entry.score, + band: relationBand(entry.score), + x1: round(from.x), + y1: round(from.y), + x2: round(strokeEnd.x), + y2: round(strokeEnd.y), + arrowPoints: arrowAt(tip, dirX, dirY), + }; + }); + + links.push({ key: pair, halves }); + } + + return { + nodes, + links, + width: round(side), + height: round(side), + center: { + // The hub sits at the origin before the offset; without one, the ring + // system still radiates from the same point. + x: round(offsetX), + y: round(offsetY), + }, + rings: ringsUsed, + hasHub: hub != null, + }; +} diff --git a/tests/int/faction-graph-layout.int.spec.ts b/tests/int/faction-graph-layout.int.spec.ts new file mode 100644 index 00000000..710762b6 --- /dev/null +++ b/tests/int/faction-graph-layout.int.spec.ts @@ -0,0 +1,195 @@ +import { describe, expect, it } from "vitest"; + +import { + BAND_COLORS, + layoutFactionGraph, + linkStrokeWidth, + type GraphFaction, + type GraphScore, +} from "@/lib/intelligence/factionGraphLayout"; + +const FACTION = ( + id: number, + name: string, + type: string, + discovered = true, +): GraphFaction => ({ id, name, type, discovered }); + +describe("faction relation graph layout", () => { + const factions: GraphFaction[] = [ + FACTION(1, "Batch 41-7", "playerFaction"), + FACTION(2, "Worldmark", "majorFaction"), + FACTION(3, "Autonomous Remnant", "majorFaction"), + FACTION(4, "Harbor Guild", "minorFaction"), + FACTION(5, "Vertex Corp", "corporation"), + ]; + + it("puts the player faction at the center and everyone else on rings", () => { + const layout = layoutFactionGraph(factions, []); + const hub = layout.nodes.find((node) => node.id === 1)!; + const majors = layout.nodes.filter((node) => node.type === "majorFaction"); + const minor = layout.nodes.find((node) => node.type === "minorFaction")!; + const corp = layout.nodes.find((node) => node.type === "corporation")!; + + expect(layout.hasHub).toBe(true); + expect(hub.ring).toBe(0); + expect(majors.every((node) => node.ring === 1)).toBe(true); + expect(minor.ring).toBe(2); + expect(corp.ring).toBe(3); + + const distance = (node: { x: number; y: number }) => + Math.hypot(node.x - hub.x, node.y - hub.y); + expect(distance(majors[0])).toBeCloseTo(distance(majors[1]), 5); + expect(distance(minor)).toBeGreaterThan(distance(majors[0])); + expect(distance(corp)).toBeGreaterThan(distance(minor)); + }); + + it("keeps positions stable regardless of input order", () => { + const forward = layoutFactionGraph(factions, []); + const shuffled = layoutFactionGraph([...factions].reverse(), []); + const positions = (layout: ReturnType) => + new Map(layout.nodes.map((node) => [node.id, `${node.x},${node.y}`])); + + expect(positions(shuffled)).toEqual(positions(forward)); + }); + + it("draws one straight line per direction, running side by side", () => { + const scores: GraphScore[] = [ + { subjectId: 3, targetId: 1, score: -100 }, + { subjectId: 1, targetId: 3, score: 0 }, + { subjectId: 2, targetId: 1, score: 25 }, + { subjectId: 1, targetId: 2, score: 40 }, + { subjectId: 4, targetId: 4, score: 60 }, + { subjectId: 99, targetId: 1, score: 10 }, + ]; + const layout = layoutFactionGraph(factions, scores); + + // Zero scores, self scores and unknown factions never produce a link. + expect(layout.links).toHaveLength(2); + + const pair = layout.links.find((link) => link.halves.length === 2)!; + expect(pair.halves.map((half) => half.key).sort()).toEqual(["1:2", "2:1"]); + + // Each direction spans the whole pair, and the two lines are parallel and + // separated, rather than overlapping or meeting at a midpoint. + const forward = pair.halves.find((half) => half.key === "1:2")!; + const backward = pair.halves.find((half) => half.key === "2:1")!; + const forwardLength = Math.hypot(forward.x2 - forward.x1, forward.y2 - forward.y1); + const backwardLength = Math.hypot(backward.x2 - backward.x1, backward.y2 - backward.y1); + expect(forwardLength).toBeCloseTo(backwardLength, 0); + + // Perpendicular distance between the two lines. + const dx = forward.x2 - forward.x1; + const dy = forward.y2 - forward.y1; + const length = Math.hypot(dx, dy) || 1; + const separation = Math.abs( + (backward.x1 - forward.x1) * (dy / length) - (backward.y1 - forward.y1) * (dx / length), + ); + expect(separation).toBeGreaterThan(6); + expect(separation).toBeLessThan(16); + expect(forward.band.label).toBe("Friendly"); + expect(backward.band.label).toBe("Friendly"); + + const single = layout.links.find((link) => link.halves.length === 1)!; + expect(single.halves[0].key).toBe("3:1"); + expect(single.halves[0].band.label).toBe("Hostile"); + expect(BAND_COLORS[single.halves[0].band.key]).toBe("#f87171"); + }); + + it("keeps lines straight and trims them to the node edges", () => { + const layout = layoutFactionGraph(factions, [ + { subjectId: 2, targetId: 3, score: -20 }, + { subjectId: 1, targetId: 4, score: 30 }, + ]); + const hub = layout.nodes.find((node) => node.id === 1)!; + const minor = layout.nodes.find((node) => node.id === 4)!; + const half = layout.links.find((link) => link.halves[0].key === "1:4")!.halves[0]; + + // Coordinates are rounded to two decimals, hence the small tolerance. + const startDistance = Math.hypot(half.x1 - hub.x, half.y1 - hub.y); + expect(startDistance).toBeGreaterThanOrEqual(hub.radius - 0.05); + + // The half ends at the segment's midpoint, which lies on the straight line + // between the trimmed start and the target's center. + const vx = half.x2 - half.x1; + const vy = half.y2 - half.y1; + const cross = vx * (minor.y - half.y1) - vy * (minor.x - half.x1); + // Perpendicular deviation of the far node from the half's line, in pixels. + const deviation = Math.abs(cross) / (Math.hypot(vx, vy) || 1); + expect(deviation).toBeLessThan(0.5); + + // The far end stops at the target's edge, not its center. + const endDistance = Math.hypot(minor.x - half.x2, minor.y - half.y2); + expect(endDistance).toBeGreaterThanOrEqual(minor.radius - 0.05); + expect(Math.hypot(half.x2 - half.x1, half.y2 - half.y1)).toBeGreaterThan(startDistance); + }); + + it("nudges a segment aside instead of drawing it through another faction", () => { + // Worldmark and Harbor Guild sit on opposite sides of the hub on the same + // spoke: a straight Worldmark-to-Harbor segment would cut through the hub. + const lineThroughHub: GraphScore[] = [{ subjectId: 2, targetId: 4, score: 30 }]; + const layout = layoutFactionGraph(factions, lineThroughHub); + const hub = layout.nodes.find((node) => node.id === 1)!; + const half = layout.links[0].halves[0]; + + const start = { x: half.x1, y: half.y1 }; + const end = layout.nodes.find((node) => node.id === 4)!; + const dx = end.x - start.x; + const dy = end.y - start.y; + const length = Math.hypot(dx, dy) || 1; + // Distance from the hub center to the infinite line through the segment. + const distance = + Math.abs((hub.x - start.x) * (dy / length) - (hub.y - start.y) * (dx / length)); + expect(distance).toBeGreaterThanOrEqual(hub.radius); + }); + + it("scales stroke width with magnitude and caps it", () => { + expect(linkStrokeWidth(5)).toBeLessThan(linkStrokeWidth(60)); + expect(linkStrokeWidth(100)).toBe(linkStrokeWidth(400)); + expect(linkStrokeWidth(-60)).toBe(linkStrokeWidth(60)); + }); + + it("reports a square canvas with one guide ring per used ring", () => { + const layout = layoutFactionGraph(factions, []); + expect(layout.width).toBe(layout.height); + expect(layout.rings).toHaveLength(3); + expect(layout.rings).toEqual([...layout.rings].sort((a, b) => a - b)); + for (const node of layout.nodes) { + if (node.ring === 0) continue; + const distance = Math.hypot(node.x - layout.center.x, node.y - layout.center.y); + expect(distance).toBeCloseTo(layout.rings[node.ring - 1], 0); + } + }); + + it("keeps every node inside the reported canvas", () => { + const layout = layoutFactionGraph(factions, []); + for (const node of layout.nodes) { + expect(node.x - node.radius).toBeGreaterThanOrEqual(0); + expect(node.y - node.radius).toBeGreaterThanOrEqual(0); + expect(node.x + node.radius).toBeLessThanOrEqual(layout.width); + expect(node.y + node.radius).toBeLessThanOrEqual(layout.height); + } + }); + + it("returns an empty layout when there are no factions", () => { + expect(layoutFactionGraph([], [])).toEqual({ + nodes: [], + links: [], + width: 0, + height: 0, + center: { x: 0, y: 0 }, + rings: [], + hasHub: false, + }); + }); + + it("still lays out factions when none is the player faction", () => { + const layout = layoutFactionGraph( + factions.filter((faction) => faction.type !== "playerFaction"), + [{ subjectId: 2, targetId: 3, score: 12 }], + ); + expect(layout.hasHub).toBe(false); + expect(layout.nodes).toHaveLength(4); + expect(layout.links).toHaveLength(1); + }); +});