PlotDirector/PlotLine/wwwroot/js/relationship-main-layout.js

756 lines
24 KiB
JavaScript

// Main Relationships only. Pure deterministic geometry; no persistence, DOM, data writes or AI.
(() => {
"use strict";
const order = (a, b) => a.id - b.id,
key = (a, b) => (a < b ? a + ":" + b : b + ":" + a);
const rect = (n, p, pad = 0) => ({
x1: p.x - n.w / 2 - pad,
y1: p.y - n.h / 2 - pad,
x2: p.x + n.w / 2 + pad,
y2: p.y + n.h / 2 + pad,
});
const intersects = (a, b) =>
a.x1 < b.x2 && a.x2 > b.x1 && a.y1 < b.y2 && a.y2 > b.y1;
function adjacency(nodes, edges) {
const a = new Map(nodes.map((n) => [n.id, new Map()]));
for (const e of edges)
if (e.a !== e.b && a.has(e.a) && a.has(e.b)) {
a.get(e.a).set(e.b, (a.get(e.a).get(e.b) || 0) + 1);
a.get(e.b).set(e.a, (a.get(e.b).get(e.a) || 0) + 1);
}
return a;
}
function components(nodes, adj) {
const byId = new Map(nodes.map((n) => [n.id, n])),
seen = new Set(),
groups = [];
for (const node of [...nodes].sort(order)) {
if (seen.has(node.id)) continue;
const ids = [node.id],
group = [];
seen.add(node.id);
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
group.push(byId.get(id));
for (const next of [...adj.get(id).keys()].sort((a, b) => a - b))
if (!seen.has(next)) {
seen.add(next);
ids.push(next);
}
}
groups.push(group);
}
return groups.sort((a, b) => b.length - a.length || a[0].id - b[0].id);
}
// Greedy modularity refinement reveals recorded dense subgroups within connected components.
function communities(nodes, adj) {
const ids = new Set(nodes.map((n) => n.id)),
degree = new Map(
nodes.map((n) => [
n.id,
[...adj.get(n.id)]
.filter(([id]) => ids.has(id))
.reduce((sum, [, w]) => sum + w, 0),
]),
),
mass = [...degree.values()].reduce((a, b) => a + b, 0) || 1,
labels = new Map(nodes.map((n) => [n.id, n.id])),
totals = new Map(degree);
for (let round = 0; round < 16; round++) {
let changed = false;
for (const n of [...nodes].sort(order)) {
const old = labels.get(n.id),
d = degree.get(n.id);
totals.set(old, (totals.get(old) || 0) - d);
const weights = new Map();
for (const [id, w] of adj.get(n.id))
if (ids.has(id)) {
const label = labels.get(id);
weights.set(label, (weights.get(label) || 0) + w);
}
let best = old,
score = (weights.get(old) || 0) - (d * (totals.get(old) || 0)) / mass;
for (const [label, w] of [...weights].sort((a, b) => a[0] - b[0])) {
const next = w - (d * (totals.get(label) || 0)) / mass;
if (next > score + 1e-8) {
best = label;
score = next;
}
}
labels.set(n.id, best);
totals.set(best, (totals.get(best) || 0) + d);
changed ||= best !== old;
}
if (!changed) break;
}
const groups = new Map();
for (const n of nodes) {
const label = labels.get(n.id);
if (!groups.has(label)) groups.set(label, []);
groups.get(label).push(n);
}
return [...groups.values()].sort(
(a, b) => b.length - a.length || a[0].id - b[0].id,
);
}
function noOverlap(nodes, positions, pins = {}, gap = 28) {
const placed = [];
for (const n of [...nodes].sort(
(a, b) => Number(!!pins[b.id]) - Number(!!pins[a.id]) || order(a, b),
)) {
let p = { ...(pins[n.id] || positions[n.id] || { x: 0, y: 0 }) };
if (!pins[n.id]) {
const origin = { ...p },
stepX = n.w + gap,
stepY = n.h + gap;
let found = false;
for (
let ring = 0;
ring < Math.max(100, nodes.length) && !found;
ring++
) {
const candidates = [];
if (!ring) candidates.push(origin);
else
for (let x = -ring; x <= ring; x++)
for (const y of [-ring, ring])
candidates.push({
x: origin.x + (x * stepX) / 2,
y: origin.y + (y * stepY) / 2,
});
if (ring)
for (let y = -ring + 1; y < ring; y++)
for (const x of [-ring, ring])
candidates.push({
x: origin.x + (x * stepX) / 2,
y: origin.y + (y * stepY) / 2,
});
candidates.sort(
(a, b) =>
(a.x - origin.x) ** 2 +
(a.y - origin.y) ** 2 -
((b.x - origin.x) ** 2 + (b.y - origin.y) ** 2) ||
a.y - b.y ||
a.x - b.x,
);
for (const candidate of candidates)
if (
!placed.some((other) =>
intersects(rect(n, candidate, gap / 2), other),
)
) {
p = candidate;
found = true;
break;
}
}
}
positions[n.id] = p;
placed.push(rect(n, p, gap / 2));
}
return positions;
}
function bounds(nodes, p) {
if (!nodes.length) return { x1: 0, y1: 0, w: 0, h: 0 };
const rs = nodes.map((n) => rect(n, p[n.id]));
const x1 = Math.min(...rs.map((x) => x.x1)),
y1 = Math.min(...rs.map((x) => x.y1));
return {
x1,
y1,
w: Math.max(...rs.map((x) => x.x2)) - x1,
h: Math.max(...rs.map((x) => x.y2)) - y1,
};
}
function pack(blocks, aspect = 1.8, gap = 100) {
const area = blocks.reduce(
(s, b) => s + (b.box.w + gap) * (b.box.h + gap),
0,
),
target = Math.max(
...blocks.map((b) => b.box.w),
Math.sqrt(area * Math.max(0.6, Math.min(3, aspect))),
);
let x = 0,
y = 0,
row = 0;
const p = {};
for (const b of blocks) {
if (x && x + b.box.w > target) {
x = 0;
y += row + gap;
row = 0;
}
for (const n of b.nodes)
p[n.id] = {
x: b.p[n.id].x - b.box.x1 + x,
y: b.p[n.id].y - b.box.y1 + y,
};
x += b.box.w + gap;
row = Math.max(row, b.box.h);
}
return p;
}
function force(nodes, adj) {
const p = {},
ids = new Set(nodes.map((n) => n.id));
for (const [i, n] of [...nodes].sort(order).entries()) {
const angle = i * 2.399963229728653,
r = 90 * Math.sqrt(i);
p[n.id] = { x: Math.cos(angle) * r, y: Math.sin(angle) * r };
}
for (let pass = 0; pass < 100; pass++) {
const delta = new Map(
nodes.map((n) => [
n.id,
{ x: -p[n.id].x * 0.005, y: -p[n.id].y * 0.005 },
]),
);
for (let i = 0; i < nodes.length; i++)
for (let j = i + 1; j < nodes.length; j++) {
const a = nodes[i],
b = nodes[j],
dx = p[b.id].x - p[a.id].x || 0.01,
dy = p[b.id].y - p[a.id].y || 0.02,
d = Math.max(10, Math.hypot(dx, dy)),
desired = Math.hypot((a.w + b.w) / 2 + 36, (a.h + b.h) / 2 + 28),
f = Math.min(28, ((desired * desired) / (d * d)) * 7);
delta.get(a.id).x -= (dx / d) * f;
delta.get(a.id).y -= (dy / d) * f;
delta.get(b.id).x += (dx / d) * f;
delta.get(b.id).y += (dy / d) * f;
}
for (const n of nodes)
for (const [id] of adj.get(n.id))
if (ids.has(id) && id > n.id) {
const dx = p[id].x - p[n.id].x,
dy = p[id].y - p[n.id].y,
d = Math.hypot(dx, dy) || 1,
f =
(d - (n.w + nodes.find((n) => n.id === id).w) / 2 - 70) * 0.04;
delta.get(n.id).x += (dx / d) * f;
delta.get(n.id).y += (dy / d) * f;
delta.get(id).x -= (dx / d) * f;
delta.get(id).y -= (dy / d) * f;
}
for (const n of nodes) {
const d = delta.get(n.id),
cool = 1 - pass / 125;
p[n.id].x += Math.max(-25, Math.min(25, d.x)) * cool;
p[n.id].y += Math.max(-25, Math.min(25, d.y)) * cool;
}
}
const box = bounds(nodes, p),
area = nodes.reduce((sum, n) => sum + (n.w + 36) * (n.h + 32), 0),
sx = Math.min(1, Math.sqrt(area * 1.8) / Math.max(1, box.w)),
sy = Math.min(1, Math.sqrt(area / 1.8) / Math.max(1, box.h));
for (const point of Object.values(p)) {
point.x *= sx;
point.y *= sy;
}
return noOverlap(nodes, p);
}
function clustered(nodes, adj, aspect) {
const blocks = [],
groups = [];
const isolated = [];
for (const component of components(nodes, adj)) {
if (component.length === 1) {
isolated.push(component[0]);
continue;
}
const communitiesInComponent = communities(component, adj),
inner = [];
for (const group of communitiesInComponent) {
const p = force(group, adj);
inner.push({ nodes: group, p, box: bounds(group, p) });
groups.push(group.map((n) => n.id));
}
let p;
if (inner.length < 2) p = inner[0].p;
else {
const membership = new Map(
inner.flatMap((block, index) =>
block.nodes.map((n) => [n.id, index + 1]),
),
),
virtual = inner.map((block, index) => ({
id: index + 1,
w: block.box.w + 50,
h: block.box.h + 50,
})),
bridges = [];
for (const n of component)
for (const [id, weight] of adj.get(n.id))
if (
id > n.id &&
membership.has(id) &&
membership.get(n.id) !== membership.get(id)
)
for (let count = 0; count < Math.min(4, weight); count++)
bridges.push({
a: membership.get(n.id),
b: membership.get(id),
});
const centres = force(virtual, adjacency(virtual, bridges));
const scale = Math.sqrt(Math.max(0.7, Math.min(2.6, aspect)));
for (const centre of Object.values(centres)) {
centre.x *= scale;
centre.y /= scale;
}
noOverlap(virtual, centres, {}, 60);
p = {};
inner.forEach((block, index) => {
const centre = centres[index + 1];
for (const n of block.nodes)
p[n.id] = {
x: block.p[n.id].x - block.box.x1 - block.box.w / 2 + centre.x,
y: block.p[n.id].y - block.box.y1 - block.box.h / 2 + centre.y,
};
});
}
blocks.push({ nodes: component, p, box: bounds(component, p) });
}
if (isolated.length) {
const p = {},
columns = Math.max(
1,
Math.ceil(Math.sqrt(isolated.length * aspect * 0.45)),
),
w = Math.max(...isolated.map((n) => n.w)) + 36,
h = Math.max(...isolated.map((n) => n.h)) + 32;
isolated.sort(order).forEach(
(n, i) =>
(p[n.id] = {
x: (i % columns) * w,
y: Math.floor(i / columns) * h,
}),
);
blocks.push({ nodes: isolated, p, box: bounds(isolated, p) });
}
return { positions: pack(blocks, aspect, 130), communities: groups };
}
function radial(nodes, adj, focus, depth) {
if (!nodes.length) return { positions: {}, distances: {} };
focus = nodes.some((n) => n.id === focus)
? focus
: [...nodes].sort(
(a, b) => adj.get(b.id).size - adj.get(a.id).size || order(a, b),
)[0].id;
const distance = new Map([[focus, 0]]),
branch = new Map([[focus, focus]]),
queue = [focus];
for (let i = 0; i < queue.length; i++) {
const id = queue[i];
if (distance.get(id) >= depth) continue;
for (const next of [...adj.get(id).keys()].sort((a, b) => a - b))
if (!distance.has(next)) {
distance.set(next, distance.get(id) + 1);
branch.set(next, id === focus ? next : branch.get(id));
queue.push(next);
}
}
const p = { [focus]: { x: 0, y: 0 } },
rings = new Map();
for (const n of nodes)
if (n.id !== focus && distance.has(n.id)) {
const d = distance.get(n.id);
if (!rings.has(d)) rings.set(d, []);
rings.get(d).push(n);
}
let previous = 0;
for (const [d, ring] of rings) {
const maxW = Math.max(...ring.map((n) => n.w)),
maxH = Math.max(...ring.map((n) => n.h)),
radius = Math.max(
previous + Math.hypot(maxW, maxH) + 75,
(ring.length * (Math.hypot(maxW, maxH) + 45)) / (2 * Math.PI),
);
ring
.sort((a, b) => branch.get(a.id) - branch.get(b.id) || order(a, b))
.forEach((n, i) => {
const angle = -Math.PI / 2 + (2 * Math.PI * i) / ring.length;
p[n.id] = {
x: Math.cos(angle) * radius,
y: Math.sin(angle) * radius,
};
});
previous = radius;
}
const unrelated = nodes.filter((n) => !distance.has(n.id));
if (unrelated.length) {
const w = Math.max(...unrelated.map((n) => n.w)) + 35,
h = Math.max(...unrelated.map((n) => n.h)) + 35,
cols = Math.max(1, Math.ceil(Math.sqrt(unrelated.length)));
unrelated.sort(order).forEach(
(n, i) =>
(p[n.id] = {
x: previous + w + (i % cols) * w,
y: Math.floor(i / cols) * h,
}),
);
}
return { positions: p, distances: Object.fromEntries(distance), focus };
}
function tiers(nodes, adj, aspect) {
const community = new Map(
communities(nodes, adj).flatMap((group, index) =>
group.map((n) => [n.id, index]),
),
),
p = {},
levels = [
(n) => n.importance >= 8,
(n) => n.importance >= 4 && n.importance < 8,
(n) => n.importance >= 1 && n.importance < 4,
(n) => !(n.importance >= 1),
];
let y = 0;
for (const test of levels) {
const group = nodes.filter(test);
if (!group.length) continue;
const degree = (n) =>
[...adj.get(n.id).values()].reduce((a, b) => a + b, 0);
const bary = (n) => {
const neighbours = [...adj.get(n.id).keys()].filter((id) => p[id]);
return neighbours.length
? neighbours.reduce((sum, id) => sum + p[id].x, 0) / neighbours.length
: 0;
};
group.sort(
(a, b) =>
(community.get(a.id) || 0) - (community.get(b.id) || 0) ||
bary(a) - bary(b) ||
degree(b) - degree(a) ||
order(a, b),
);
const cols = Math.max(
1,
Math.ceil(Math.sqrt(group.length * aspect * 0.4)),
),
w = Math.max(...group.map((n) => n.w)) + 46,
h = Math.max(...group.map((n) => n.h)) + 40;
group.forEach(
(n, i) =>
(p[n.id] = { x: (i % cols) * w, y: y + Math.floor(i / cols) * h }),
);
y += Math.ceil(group.length / cols) * h + 100;
}
return p;
}
function layout(input) {
const nodes = [...input.nodes].sort(order),
edges = input.edges,
adj = adjacency(nodes, edges),
aspect =
(input.viewport?.width || 1200) /
Math.max(200, input.viewport?.height || 700);
let result;
if (!nodes.length) return { positions: {}, communities: [], warnings: [] };
switch (input.layout) {
case "radial":
result = radial(nodes, adj, input.focus, input.depth || 2);
break;
case "importance":
result = { positions: tiers(nodes, adj, aspect) };
break;
case "family": {
const engine = globalThis.PlotDirectorContextRelationshipLayout;
const family = engine.family(
nodes.map((n) => ({
id: n.id,
name: n.name,
birthDate: n.birthDate,
})),
edges.map((e) => ({
id: e.id,
a: e.a,
b: e.b,
type: e.type,
reciprocal: e.reciprocal,
})),
);
result = {
...family,
positions: Object.fromEntries(
Object.entries(family.positions).map(([id, p]) => [
id,
{ x: p.x + family.nodeWidth / 2, y: p.y + family.nodeHeight / 2 },
]),
),
};
break;
}
case "circle": {
const radius = Math.max(
180,
(nodes.length * Math.max(...nodes.map((n) => Math.hypot(n.w, n.h)))) /
(2 * Math.PI),
);
result = {
positions: Object.fromEntries(
nodes.map((n, i) => [
n.id,
{
x: Math.cos((2 * Math.PI * i) / nodes.length) * radius,
y: Math.sin((2 * Math.PI * i) / nodes.length) * radius,
},
]),
),
};
break;
}
default:
result = clustered(nodes, adj, aspect);
}
result.positions = noOverlap(
nodes,
result.positions,
input.pins || {},
input.layout === "family" ? 12 : 28,
);
const pinnedNodes = nodes.filter((n) => input.pins?.[n.id]);
if (
pinnedNodes.some((n, i) =>
pinnedNodes
.slice(i + 1)
.some((other) =>
intersects(
rect(n, result.positions[n.id]),
rect(other, result.positions[other.id]),
),
),
)
)
result.warnings = [
...(result.warnings || []),
"Pinned character positions overlap. Unpin or move them to separate the cards.",
];
result.preferredCenter =
input.focus && result.positions[input.focus]
? input.focus
: [...nodes].sort(
(a, b) => adj.get(b.id).size - adj.get(a.id).size || order(a, b),
)[0].id;
return { ...result, bounds: bounds(nodes, result.positions) };
}
function crosses(a, b, r) {
let lo = 0,
hi = 1;
const dx = b.x - a.x,
dy = b.y - a.y;
for (const [p, q] of [
[-dx, a.x - r.x1],
[dx, r.x2 - a.x],
[-dy, a.y - r.y1],
[dy, r.y2 - a.y],
]) {
if (!p) {
if (q < 0) return false;
} else {
const t = q / p;
if (p < 0) lo = Math.max(lo, t);
else hi = Math.min(hi, t);
if (lo > hi) return false;
}
}
return true;
}
function orthogonal(a, b, obstacles, lane = 0) {
const gap = 28 + Math.abs(lane),
mx = (a.x + b.x) / 2 + lane,
my = (a.y + b.y) / 2 + lane,
horizontal = Math.abs(b.x - a.x) >= Math.abs(b.y - a.y),
preferred = horizontal
? [a, { x: a.x, y: my }, { x: b.x, y: my }, b]
: [a, { x: mx, y: a.y }, { x: mx, y: b.y }, b];
const score = (path) => {
let hits = 0,
length = 0;
for (let i = 1; i < path.length; i++) {
length += Math.hypot(
path[i].x - path[i - 1].x,
path[i].y - path[i - 1].y,
);
hits += obstacles.filter((r) =>
crosses(path[i - 1], path[i], r),
).length;
}
return hits * 1e7 + length;
};
if (lane && score(preferred) < 1e7) return preferred;
const candidates = [
preferred,
[a, { x: mx, y: a.y }, { x: mx, y: b.y }, b],
[a, { x: a.x, y: my }, { x: b.x, y: my }, b],
],
blocked = obstacles.filter((r) => crosses(a, b, r));
for (const r of blocked)
for (const x of [r.x1 - gap + lane, r.x2 + gap + lane])
candidates.push([a, { x, y: a.y }, { x, y: b.y }, b]);
for (const r of blocked)
for (const y of [r.y1 - gap + lane, r.y2 + gap + lane])
candidates.push([a, { x: a.x, y }, { x: b.x, y }, b]);
let best = candidates
.map((p, i) => ({ p, i, s: score(p) }))
.sort((a, b) => a.s - b.s || a.i - b.i)[0];
const seen = new Set();
for (let pass = 0; pass < 12 && best.s >= 1e7; pass++) {
const signature = JSON.stringify(best.p);
if (seen.has(signature)) break;
seen.add(signature);
let conflict;
for (let i = 1; i < best.p.length && !conflict; i++) {
const hit = obstacles.find((r) => crosses(best.p[i - 1], best.p[i], r));
if (hit) conflict = { i, r: hit };
}
if (!conflict) break;
const { i, r } = conflict,
p = best.p[i - 1],
q = best.p[i],
detours =
p.y === q.y
? [r.y1 - gap + lane, r.y2 + gap + lane].map((y) => [
p,
{ x: p.x, y },
{ x: q.x, y },
q,
])
: [r.x1 - gap + lane, r.x2 + gap + lane].map((x) => [
p,
{ x, y: p.y },
{ x, y: q.y },
q,
]);
const alternatives = detours
.map((points, n) => {
const path = [
...best.p.slice(0, i - 1),
...points,
...best.p.slice(i + 1),
];
return { p: path, i: n, s: score(path) };
})
.sort((a, b) => a.s - b.s || a.i - b.i);
if (alternatives[0].s >= best.s) break;
best = alternatives[0];
}
return best.p;
}
function route(nodes, edge, style, lane = 0, familyPath) {
const byId = new Map(nodes.map((n) => [n.id, n])),
a = byId.get(edge.a),
b = byId.get(edge.b);
if (!a || !b) return null;
const obstacles = nodes
.filter((n) => n !== a && n !== b)
.map((n) => rect(n, n, 10));
if (style === "straight") {
const dx = b.x - a.x,
dy = b.y - a.y,
clamp = (v, min, max) => Math.max(min, Math.min(max, v));
return {
style: "straight",
sourceEndpoint: lane
? Math.abs(dx) >= Math.abs(dy)
? {
x: (Math.sign(dx) * a.w) / 2,
y: clamp(lane, -a.h / 2 + 6, a.h / 2 - 6),
}
: {
x: clamp(lane, -a.w / 2 + 6, a.w / 2 - 6),
y: (Math.sign(dy) * a.h) / 2,
}
: null,
targetEndpoint: lane
? Math.abs(dx) >= Math.abs(dy)
? {
x: (-Math.sign(dx) * b.w) / 2,
y: clamp(lane, -b.h / 2 + 6, b.h / 2 - 6),
}
: {
x: clamp(lane, -b.w / 2 + 6, b.w / 2 - 6),
y: (-Math.sign(dy) * b.h) / 2,
}
: null,
};
}
if (style === "orthogonal") {
if (familyPath && !lane) {
let current = { x: 0, y: 0 };
const points = [];
for (const part of familyPath.matchAll(
/([MHV])\s*(-?[\d.]+)(?:\s+(-?[\d.]+))?/g,
)) {
current =
part[1] === "M"
? { x: +part[2], y: +part[3] }
: part[1] === "H"
? { x: +part[2], y: current.y }
: { x: current.x, y: +part[2] };
points.push(current);
}
if (points.length > 2) {
if (
Math.hypot(points[0].x - b.x, points[0].y - b.y) <
Math.hypot(points[0].x - a.x, points[0].y - a.y)
)
points.reverse();
return { style: "segments", points: points.slice(1, -1) };
}
}
return {
style: "segments",
points: orthogonal(a, b, obstacles, lane).slice(1, -1),
};
}
const dx = b.x - a.x,
dy = b.y - a.y,
length = Math.hypot(dx, dy) || 1,
nx = -dy / length,
ny = dx / length;
let best = { distance: lane || 22, hits: Infinity };
for (const distance of [
lane || 22,
60 + lane,
-60 + lane,
130 + lane,
-130 + lane,
240 + lane,
-240 + lane,
]) {
const control = {
x: (a.x + b.x) / 2 + nx * distance,
y: (a.y + b.y) / 2 + ny * distance,
};
let hits = 0,
previous = a;
for (let i = 1; i <= 16; i++) {
const t = i / 16,
p = {
x: (1 - t) ** 2 * a.x + 2 * (1 - t) * t * control.x + t * t * b.x,
y: (1 - t) ** 2 * a.y + 2 * (1 - t) * t * control.y + t * t * b.y,
};
hits += obstacles.filter((r) => crosses(previous, p, r)).length;
previous = p;
}
if (hits < best.hits) {
best = { distance, hits };
if (!hits) break;
}
}
return { style: "unbundled-bezier", distance: best.distance };
}
globalThis.PlotDirectorMainRelationshipLayout = {
layout,
route,
adjacency,
communities,
components,
noOverlap,
rect,
intersects,
key,
};
})();