skilltree-lab 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- skilltree_lab/__init__.py +0 -0
- skilltree_lab/cli.py +82 -0
- skilltree_lab/data/LICENSE.d3-celestial +12 -0
- skilltree_lab/data/NOTICE +14 -0
- skilltree_lab/data/asterisms.lines.json +1 -0
- skilltree_lab/data/snt.lines.json +1 -0
- skilltree_lab/editor.html +418 -0
- skilltree_lab/editor.py +311 -0
- skilltree_lab/figures.py +201 -0
- skilltree_lab/shapes.py +1053 -0
- skilltree_lab/svg.py +61 -0
- skilltree_lab-0.1.0.dist-info/METADATA +266 -0
- skilltree_lab-0.1.0.dist-info/RECORD +18 -0
- skilltree_lab-0.1.0.dist-info/WHEEL +4 -0
- skilltree_lab-0.1.0.dist-info/entry_points.txt +2 -0
- skilltree_lab-0.1.0.dist-info/licenses/LICENSE +21 -0
- skilltree_lab-0.1.0.dist-info/licenses/skilltree_lab/data/LICENSE.d3-celestial +12 -0
- skilltree_lab-0.1.0.dist-info/licenses/skilltree_lab/data/NOTICE +14 -0
skilltree_lab/shapes.py
ADDED
|
@@ -0,0 +1,1053 @@
|
|
|
1
|
+
"""Skill tree shapes: each one lays out nodes and the edges between them.
|
|
2
|
+
|
|
3
|
+
A shape is a function (params, rng) -> Tree. Every count is a parameter; the
|
|
4
|
+
defaults make a small tree. Coordinates are abstract units (about one node
|
|
5
|
+
apart); the preview scales them. Tiers are worked out afterwards for every
|
|
6
|
+
shape the same way: steps from the start node.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
13
|
+
import random
|
|
14
|
+
import re
|
|
15
|
+
from collections import deque
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
|
|
18
|
+
from . import figures
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class Node:
|
|
23
|
+
id: int
|
|
24
|
+
x: float
|
|
25
|
+
y: float
|
|
26
|
+
tier: int = 0
|
|
27
|
+
label: str = "" # a1, b3...: fixed by the shape, not by joins, so joins can be named by it
|
|
28
|
+
look: str = "circle" # the mark drawn for the node: circle, square, triangle... or "5" for 5 sides
|
|
29
|
+
ratio: tuple[float, float] = (1, 1) # its width to height: [2, 1] makes a square a wide rectangle
|
|
30
|
+
cost: float = 1 # points to take it
|
|
31
|
+
need_all: bool = False # every node with a line into it first, not just one
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class Tree:
|
|
36
|
+
shape: str
|
|
37
|
+
nodes: list[Node] = field(default_factory=list)
|
|
38
|
+
edges: list[tuple[int, int]] = field(default_factory=list)
|
|
39
|
+
starts: list[int] = field(default_factory=lambda: [0]) # where a player may begin; tier 0
|
|
40
|
+
warnings: list[str] = field(default_factory=list)
|
|
41
|
+
depth_first: bool = False # number along each line to its end before the next (star figures)
|
|
42
|
+
|
|
43
|
+
def add(self, x: float, y: float, parent: int | None = None) -> int:
|
|
44
|
+
n = Node(len(self.nodes), x, y)
|
|
45
|
+
self.nodes.append(n)
|
|
46
|
+
if parent is not None:
|
|
47
|
+
self.edges.append((parent, n.id))
|
|
48
|
+
return n.id
|
|
49
|
+
|
|
50
|
+
def link(self, a: int, b: int) -> None:
|
|
51
|
+
self.edges.append((a, b))
|
|
52
|
+
|
|
53
|
+
def set_tiers(self, strict: bool = True) -> None:
|
|
54
|
+
"""Tier = steps from the nearest start; a node no start reaches is an error, or tier -1 when not strict."""
|
|
55
|
+
near: dict[int, list[int]] = {n.id: [] for n in self.nodes}
|
|
56
|
+
for a, b in self.edges:
|
|
57
|
+
near[a].append(b)
|
|
58
|
+
near[b].append(a)
|
|
59
|
+
seen, todo = {s: 0 for s in self.starts}, deque(self.starts)
|
|
60
|
+
while todo:
|
|
61
|
+
a = todo.popleft()
|
|
62
|
+
for b in near[a]:
|
|
63
|
+
if b not in seen:
|
|
64
|
+
seen[b] = seen[a] + 1
|
|
65
|
+
todo.append(b)
|
|
66
|
+
if strict and len(seen) != len(self.nodes):
|
|
67
|
+
raise ValueError(f"{self.shape}: {len(self.nodes) - len(seen)} node(s) not reachable from a start")
|
|
68
|
+
for n in self.nodes:
|
|
69
|
+
n.tier = seen.get(n.id, -1)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _range(v) -> tuple[int, int]:
|
|
73
|
+
"""A count given as 3, [3] or [1, 3]."""
|
|
74
|
+
return (v, v) if isinstance(v, int) else (int(v[0]), int(v[-1]))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _span(v) -> tuple[float, float]:
|
|
78
|
+
"""A size given as 0.8 or [0.4, 1.0]."""
|
|
79
|
+
return (v, v) if isinstance(v, (int, float)) else (float(v[0]), float(v[-1]))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
MAX_ARMS = 16 # a to p: past that a tree is more tangle than tree
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _arms(v) -> int | None:
|
|
86
|
+
"""arms = 5 or arms = "e" (a to e); at most MAX_ARMS."""
|
|
87
|
+
if v is None:
|
|
88
|
+
return None
|
|
89
|
+
if isinstance(v, str):
|
|
90
|
+
if len(v) != 1 or not "a" <= v <= "z":
|
|
91
|
+
raise ValueError(f"arms = {v!r}: a number or one letter")
|
|
92
|
+
v = ord(v) - 96
|
|
93
|
+
if not 1 <= int(v) <= MAX_ARMS:
|
|
94
|
+
raise ValueError(f"arms = {v}: from 1 to {MAX_ARMS} (a to {_letters(MAX_ARMS - 1)})")
|
|
95
|
+
return int(v)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _per_arm(v, arm: int, default):
|
|
99
|
+
"""A setting given once for every arm, or per arm by letter: {a = 12, c = 20}; arms not named keep default."""
|
|
100
|
+
return v.get(_letters(arm), default) if isinstance(v, dict) else v
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _coin(v, rng: random.Random) -> bool:
|
|
104
|
+
"""true, false, or a chance such as 0.2."""
|
|
105
|
+
return v is True or (not isinstance(v, bool) and bool(v) and rng.random() < v)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _fan_angles(n: int, fan: float) -> list[float]:
|
|
109
|
+
"""n directions spread over `fan` degrees around straight down (360: all the way round)."""
|
|
110
|
+
if fan >= 360:
|
|
111
|
+
return [math.pi / 2 + 2 * math.pi * i / n for i in range(n)]
|
|
112
|
+
half = math.radians(fan) / 2
|
|
113
|
+
return [math.pi / 2 + (-half + 2 * half * i / (n - 1) if n > 1 else 0.0) for i in range(n)]
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _per_tier(v, tiers: int) -> list[tuple[int, int]]:
|
|
117
|
+
"""children = 2, [1, 3], or one of those per tier: [[2, 3], 2, [1, 2]] (the last repeats)."""
|
|
118
|
+
if isinstance(v, list) and v and not (len(v) == 2 and all(isinstance(x, int) for x in v)):
|
|
119
|
+
out = [_range(x) for x in v]
|
|
120
|
+
return (out + [out[-1]] * tiers)[:tiers]
|
|
121
|
+
return [_range(v)] * tiers
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def branch(p: dict, rng: random.Random) -> Tree:
|
|
125
|
+
"""Diablo-style tree on a grid: rows that split, never join, and can end in one capstone."""
|
|
126
|
+
tiers_v, width = p.get("tiers", 4), p.get("max_width", 8) # tiers: 4, or per arm {a = 6, b = 3}
|
|
127
|
+
widths = p.get("widths") # optional: nodes in each row by hand, e.g. [2, 3, 3, 2]
|
|
128
|
+
capstone = _coin(p.get("capstone", False), rng) # one last node every end leads to
|
|
129
|
+
sx, sy = p.get("spacing_x", 1.0), p.get("spacing_y", 1.0)
|
|
130
|
+
arms = _arms(p.get("arms")) # lines out of the first node
|
|
131
|
+
deep = max([4, *tiers_v.values()]) if isinstance(tiers_v, dict) else tiers_v
|
|
132
|
+
per_tier = _per_tier(p.get("children", [1, 3]), deep)
|
|
133
|
+
t = Tree("branch")
|
|
134
|
+
row = [t.add(0, 0)]
|
|
135
|
+
kids: dict[int, list[int]] = {} # own children of each node, left to right
|
|
136
|
+
arm_of: dict[int, int] = {}
|
|
137
|
+
for depth in range(1, (len(widths) if widths else deep) + 1):
|
|
138
|
+
if widths: # fixed sizes: each node hangs off the parent at the same share across
|
|
139
|
+
n = widths[depth - 1]
|
|
140
|
+
parents = [row[min(len(row) - 1, i * len(row) // n)] for i in range(n)]
|
|
141
|
+
elif depth == 1:
|
|
142
|
+
lo, hi = per_tier[0]
|
|
143
|
+
parents = row * (arms or min(width, rng.randint(lo, hi)))
|
|
144
|
+
else: # max_width counts each arm on its own, so deep tiers still split
|
|
145
|
+
lo, hi = per_tier[depth - 1]
|
|
146
|
+
grow = [q for q in row if depth <= _per_arm(tiers_v, arm_of[q], 4)]
|
|
147
|
+
parents, room = [], {}
|
|
148
|
+
for i, parent in enumerate(grow):
|
|
149
|
+
arm = arm_of[parent]
|
|
150
|
+
room.setdefault(arm, width)
|
|
151
|
+
left = sum(1 for q in grow[i + 1:] if arm_of[q] == arm) # one child kept for each still to come
|
|
152
|
+
k = max(1, min(rng.randint(lo, hi), room[arm] - left))
|
|
153
|
+
parents += [parent] * k
|
|
154
|
+
room[arm] -= k
|
|
155
|
+
nxt = []
|
|
156
|
+
for parent in parents:
|
|
157
|
+
nid = t.add(0, depth * sy, parent)
|
|
158
|
+
kids.setdefault(parent, []).append(nid)
|
|
159
|
+
arm_of[nid] = arm_of.get(parent, len(nxt))
|
|
160
|
+
nxt.append(nid)
|
|
161
|
+
row = nxt
|
|
162
|
+
if not row:
|
|
163
|
+
break
|
|
164
|
+
# each node sits over its own children, so a lone child hangs straight down; leaves get one slot each
|
|
165
|
+
slot = 0
|
|
166
|
+
|
|
167
|
+
def place(a: int) -> None:
|
|
168
|
+
nonlocal slot
|
|
169
|
+
if a in kids:
|
|
170
|
+
for c in kids[a]:
|
|
171
|
+
place(c)
|
|
172
|
+
t.nodes[a].x = (t.nodes[kids[a][0]].x + t.nodes[kids[a][-1]].x) / 2
|
|
173
|
+
else:
|
|
174
|
+
t.nodes[a].x, slot = slot * sx, slot + 1
|
|
175
|
+
|
|
176
|
+
place(0)
|
|
177
|
+
mid = t.nodes[0].x # read once: the loop moves node 0 first
|
|
178
|
+
for nd in t.nodes:
|
|
179
|
+
nd.x -= mid
|
|
180
|
+
fan = p.get("fan", 0) # 0: straight down; else degrees spread around the first node
|
|
181
|
+
if fan:
|
|
182
|
+
if capstone:
|
|
183
|
+
raise ValueError("branch: capstone needs fan = 0")
|
|
184
|
+
lo = min(nd.x for nd in t.nodes)
|
|
185
|
+
width = max(nd.x for nd in t.nodes) - lo
|
|
186
|
+
span = 2 * math.pi if fan >= 360 else math.radians(fan)
|
|
187
|
+
slots = width + sx if fan >= 360 else max(width, sx) # all the way round leaves one slot free
|
|
188
|
+
per = span * sx / slots # angle between neighbouring leaves
|
|
189
|
+
k = max(sy, 0.9 * sx / per) # rings far enough out that neighbours keep apart
|
|
190
|
+
for nd in t.nodes:
|
|
191
|
+
a = math.pi / 2 + ((nd.x - lo) / slots * span if fan >= 360 else ((nd.x - lo) / slots - 0.5) * span)
|
|
192
|
+
r = nd.y / sy * k
|
|
193
|
+
nd.x, nd.y = r * math.cos(a), r * math.sin(a)
|
|
194
|
+
if capstone:
|
|
195
|
+
ends = [nd for nd in t.nodes if nd.id and nd.id not in kids]
|
|
196
|
+
cap = t.add(0, max(nd.y for nd in ends) + sy)
|
|
197
|
+
for nd in ends:
|
|
198
|
+
t.link(nd.id, cap)
|
|
199
|
+
return t
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def zigzag(p: dict, rng: random.Random) -> Tree:
|
|
203
|
+
"""Chains that swing left and right as they go down; several can run side by side, never joined."""
|
|
204
|
+
length, lanes = p.get("length", 8), _arms(p.get("arms", 1)) # length: 8, [6, 9], or per arm {a = 12}
|
|
205
|
+
swing, step = _span(p.get("swing", [0.4, 1.0])), _span(p.get("step", [0.8, 1.2]))
|
|
206
|
+
twigs = p.get("twigs", 0.0) # chance a bend grows a small cluster on its outer side
|
|
207
|
+
leaves = _range(p.get("twig_leaves", [2, 3])) # nodes fanning out at the end of a twig
|
|
208
|
+
stem = _range(p.get("twig_stem", [0, 1])) # nodes between the bend and that fan
|
|
209
|
+
reach = stem[1] * 0.9 + 0.8 if twigs else 0.0
|
|
210
|
+
gap = p.get("lane_gap", 2 * (swing[1] + reach) + 1.2) # wider than two full swings, so lanes never touch
|
|
211
|
+
fan = p.get("fan", 0) # 0: lanes side by side; else degrees they spread around 0
|
|
212
|
+
t = Tree("zigzag")
|
|
213
|
+
if fan:
|
|
214
|
+
dirs = _fan_angles(lanes, fan)
|
|
215
|
+
apart = min(abs(b - a) for a, b in zip(dirs, dirs[1:] + [dirs[0] + 2 * math.pi])) if lanes > 1 else 1.0
|
|
216
|
+
bare = p.get("lane_gap", 2 * swing[1] + 0.6) # twigs wait until there is room, so arms start close
|
|
217
|
+
r0 = max(1.0, bare / apart)
|
|
218
|
+
|
|
219
|
+
def room(v: float) -> bool:
|
|
220
|
+
return lanes == 1 or (v + r0) * apart >= gap
|
|
221
|
+
|
|
222
|
+
def at(lane: int, u: float, v: float) -> tuple[float, float]:
|
|
223
|
+
d = dirs[lane]
|
|
224
|
+
return (v + r0) * math.cos(d) - u * math.sin(d), (v + r0) * math.sin(d) + u * math.cos(d)
|
|
225
|
+
start = t.add(0.0, 0.0)
|
|
226
|
+
else:
|
|
227
|
+
def at(lane: int, u: float, v: float) -> tuple[float, float]:
|
|
228
|
+
return lane * gap + u, v
|
|
229
|
+
start = t.add((lanes - 1) * gap / 2, -1.0)
|
|
230
|
+
for lane in range(lanes):
|
|
231
|
+
prev, v, side, last = start, 0.0, rng.choice((-1, 1)), -9
|
|
232
|
+
for i in range(rng.randint(*_range(_per_arm(length, lane, 8)))):
|
|
233
|
+
u = side * rng.uniform(*swing)
|
|
234
|
+
prev = t.add(*at(lane, u, v), prev)
|
|
235
|
+
if twigs and i > 0 and i - last > 2 and (not fan or room(v)) and rng.random() < twigs: # never two twigs close on one side
|
|
236
|
+
last, cu, base = i, u, prev
|
|
237
|
+
for _ in range(rng.randint(*stem)):
|
|
238
|
+
cu += side * 0.9
|
|
239
|
+
base = t.add(*at(lane, cu, v), base)
|
|
240
|
+
k = rng.randint(*leaves)
|
|
241
|
+
for n in range(k):
|
|
242
|
+
f = math.radians(-50 + 100 * n / (k - 1)) if k > 1 else 0.0
|
|
243
|
+
t.add(*at(lane, cu + side * 0.8 * math.cos(f), v + 0.8 * math.sin(f)), base)
|
|
244
|
+
v += rng.uniform(*step)
|
|
245
|
+
side = -side
|
|
246
|
+
return t
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def spine(p: dict, rng: random.Random) -> Tree:
|
|
250
|
+
"""A straight trunk with side branches beside the node they grow from; the trunk spreads to make room."""
|
|
251
|
+
length, count = p.get("length", 8), p.get("branches", 3)
|
|
252
|
+
lo, hi = _range(p.get("branch_length", [1, 3]))
|
|
253
|
+
plo, phi = _range(p.get("per_node", 1)) # branches on one trunk node
|
|
254
|
+
clo, chi = _range(p.get("branch_children", 1)) # 1: a plain line; 2+: the branch forks
|
|
255
|
+
sides = {"left": [-1], "right": [1]}.get(p.get("sides", "both"), [-1, 1])
|
|
256
|
+
step, out = p.get("step", 1.0), p.get("branch_step", 1.0) # least trunk spacing; sideways per branch node
|
|
257
|
+
row = p.get("branch_row", 0.7) # vertical room one branch tip takes
|
|
258
|
+
capstone = _coin(p.get("capstone", False), rng) # one last node below the trunk
|
|
259
|
+
|
|
260
|
+
def grow(left: int) -> list:
|
|
261
|
+
"""A branch as nested lists: each node is the list of its children."""
|
|
262
|
+
return [] if left <= 0 else [grow(left - 1) for _ in range(rng.randint(clo, chi))]
|
|
263
|
+
|
|
264
|
+
def leaves(sub: list) -> int:
|
|
265
|
+
return max(1, sum(leaves(c) for c in sub))
|
|
266
|
+
|
|
267
|
+
# decide every branch first, so each trunk node's band can be as tall as what hangs off it
|
|
268
|
+
hangs: dict[int, list[tuple[int, list]]] = {}
|
|
269
|
+
k = 0
|
|
270
|
+
for at in sorted(rng.sample(range(1, length), min(count, length - 1))):
|
|
271
|
+
for _ in range(rng.randint(plo, phi)):
|
|
272
|
+
hangs.setdefault(at, []).append((sides[k % len(sides)], [grow(rng.randint(lo, hi) - 1)]))
|
|
273
|
+
k += 1
|
|
274
|
+
need = [max([sum(leaves(b) * row for s, b in hangs.get(i, []) if s == side) for side in (-1, 1)] + [step])
|
|
275
|
+
for i in range(length)]
|
|
276
|
+
|
|
277
|
+
t = Tree("spine")
|
|
278
|
+
trunk, y = [], 0.0
|
|
279
|
+
for i in range(length):
|
|
280
|
+
if i:
|
|
281
|
+
y += (need[i - 1] + need[i]) / 2 # half of each neighbouring band
|
|
282
|
+
trunk.append(t.add(0, y, trunk[-1] if trunk else None))
|
|
283
|
+
|
|
284
|
+
def place(sub: list, parent: int, side: int, depth: int, top: float) -> None:
|
|
285
|
+
"""Each node sits in the middle of the rows its leaves take, so nothing overlaps."""
|
|
286
|
+
for c in sub:
|
|
287
|
+
h = leaves(c) * row
|
|
288
|
+
nid = t.add(side * depth * out, top + h / 2 - row / 2, parent)
|
|
289
|
+
place(c, nid, side, depth + 1, top)
|
|
290
|
+
top += h
|
|
291
|
+
|
|
292
|
+
for at, items in hangs.items():
|
|
293
|
+
for side in (-1, 1):
|
|
294
|
+
mine = [b for s, b in items if s == side]
|
|
295
|
+
top = t.nodes[trunk[at]].y - (sum(leaves(b) for b in mine) * row - row) / 2
|
|
296
|
+
for b in mine:
|
|
297
|
+
place(b, trunk[at], side, 1, top)
|
|
298
|
+
top += leaves(b) * row
|
|
299
|
+
if capstone:
|
|
300
|
+
t.add(0, y + max(step, need[-1]), trunk[-1])
|
|
301
|
+
return t
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def grid(p: dict, rng: random.Random) -> Tree:
|
|
305
|
+
"""Diablo II-style: skills on a sparse grid, prerequisites mostly straight down, several starts."""
|
|
306
|
+
cols, rows = p.get("columns", 3), p.get("rows", 6)
|
|
307
|
+
per_row = _range(p.get("per_row", [1, 2])) # skills in one row
|
|
308
|
+
skip = p.get("skip", 1) # most empty rows a line straight down may jump
|
|
309
|
+
capstone = _coin(p.get("capstone", False), rng)
|
|
310
|
+
sx, sy = p.get("spacing_x", 1.5), p.get("spacing_y", 1.0)
|
|
311
|
+
t = Tree("grid", starts=[])
|
|
312
|
+
cell: dict[tuple[int, int], int] = {}
|
|
313
|
+
used = [0] * cols
|
|
314
|
+
for r in range(rows):
|
|
315
|
+
picked, free = [], list(range(cols))
|
|
316
|
+
for _ in range(min(cols, rng.randint(*per_row))): # emptier columns are likelier, so no column runs dry
|
|
317
|
+
c = rng.choices(free, [1 / (1 + used[c]) ** 2 for c in free])[0]
|
|
318
|
+
free.remove(c)
|
|
319
|
+
picked.append(c)
|
|
320
|
+
used[c] += 1
|
|
321
|
+
picked.sort()
|
|
322
|
+
for c in picked:
|
|
323
|
+
nid = t.add((c - (cols - 1) / 2) * sx, r * sy)
|
|
324
|
+
cell[r, c] = nid
|
|
325
|
+
above = [rr for rr in range(r - 1, max(-1, r - 2 - skip), -1) if (rr, c) in cell]
|
|
326
|
+
if above: # straight down from the nearest skill in the column
|
|
327
|
+
t.link(cell[above[0], c], nid)
|
|
328
|
+
for side in (-1, 1) if not above else (): # else a diagonal from the row just above, never crossing
|
|
329
|
+
src = (r - 1, c + side)
|
|
330
|
+
crossing = (r - 1, c) in cell and (r, c + side) in cell and \
|
|
331
|
+
(cell[r - 1, c], cell[r, c + side]) in t.edges
|
|
332
|
+
if src in cell and not crossing:
|
|
333
|
+
t.link(cell[src], nid)
|
|
334
|
+
break
|
|
335
|
+
if not any(e[1] == nid for e in t.edges):
|
|
336
|
+
t.starts.append(nid) # nothing above: a skill open from the start
|
|
337
|
+
if capstone:
|
|
338
|
+
cap = t.add(0, rows * sy)
|
|
339
|
+
last = max(r for r, _ in cell)
|
|
340
|
+
for (r, c), nid in cell.items():
|
|
341
|
+
if r == last:
|
|
342
|
+
t.link(nid, cap)
|
|
343
|
+
return t
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _spread(pts: list[tuple[float, float]], least: float) -> list[tuple[float, float]]:
|
|
347
|
+
"""Nudge stars apart until none sit closer than `least`; real figures pack some stars tight."""
|
|
348
|
+
pts = [list(q) for q in pts]
|
|
349
|
+
for _ in range(200):
|
|
350
|
+
moved = False
|
|
351
|
+
for i in range(len(pts)):
|
|
352
|
+
for j in range(i + 1, len(pts)):
|
|
353
|
+
dx, dy = pts[j][0] - pts[i][0], pts[j][1] - pts[i][1]
|
|
354
|
+
d = math.hypot(dx, dy)
|
|
355
|
+
if d < least:
|
|
356
|
+
if d < 1e-9:
|
|
357
|
+
dx, dy, d = 1.0, 0.0, 1.0
|
|
358
|
+
push = (least - d) / 2 + 1e-6
|
|
359
|
+
pts[i][0] -= dx / d * push
|
|
360
|
+
pts[i][1] -= dy / d * push
|
|
361
|
+
pts[j][0] += dx / d * push
|
|
362
|
+
pts[j][1] += dy / d * push
|
|
363
|
+
moved = True
|
|
364
|
+
if not moved:
|
|
365
|
+
break
|
|
366
|
+
return [(x, y) for x, y in pts]
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def constellation(p: dict, rng: random.Random) -> Tree:
|
|
370
|
+
"""Star figures scattered over the sky, each a wandering chain from its own first star."""
|
|
371
|
+
figs = figures.pick(p["figure"], rng) if p.get("figure") is not None else None # real or drawn figures
|
|
372
|
+
groups = len(figs) if figs else _arms(p.get("arms", 5))
|
|
373
|
+
stars = p.get("stars", [4, 7]) # stars in one figure; or per arm {a = 9}
|
|
374
|
+
fork = p.get("fork", 0.3) # chance a star starts a short side chain
|
|
375
|
+
bend = p.get("bend", 60) # most degrees a chain turns at one star
|
|
376
|
+
room = p.get("room", 5.0) # sky each figure gets
|
|
377
|
+
gap = p.get("star_gap", 1.0) # distance between linked stars
|
|
378
|
+
fan = p.get("fan", 0) # 0: figures scattered; else around one first star, 0
|
|
379
|
+
t = Tree("constellation", starts=[])
|
|
380
|
+
side = room * math.ceil(math.sqrt(groups))
|
|
381
|
+
if fan:
|
|
382
|
+
if groups > 2: # more than two figures on one start reads as a cross, not a constellation
|
|
383
|
+
raise ValueError(f"constellation: arms = {groups} with fan; one start holds at most 2")
|
|
384
|
+
hub = t.add(0.0, 0.0)
|
|
385
|
+
t.starts.append(hub)
|
|
386
|
+
dirs = _fan_angles(groups, fan)
|
|
387
|
+
span = 2 * math.pi if fan >= 360 else math.radians(fan)
|
|
388
|
+
out = gap # the start sits one star gap from each first star
|
|
389
|
+
wedge = span / groups / 2 * 0.85
|
|
390
|
+
|
|
391
|
+
def free(x: float, y: float, d: float) -> bool:
|
|
392
|
+
return all((n.x - x) ** 2 + (n.y - y) ** 2 >= d * d for n in t.nodes)
|
|
393
|
+
|
|
394
|
+
if figs:
|
|
395
|
+
t.depth_first = True
|
|
396
|
+
cursor = 0.0
|
|
397
|
+
for g, (pts, strokes, s0) in enumerate(figs):
|
|
398
|
+
lines = [(a, b) for st in strokes for a, b in zip(st, st[1:])]
|
|
399
|
+
lengths = sorted(math.dist(pts[a], pts[b]) for a, b in lines)
|
|
400
|
+
k = gap / lengths[len(lengths) // 2] if lengths else 1.0 # a typical line is one star gap
|
|
401
|
+
pts = _spread([((x - pts[s0][0]) * k, (y - pts[s0][1]) * k) for x, y in pts], 0.7 * gap)
|
|
402
|
+
if fan: # turn the figure to lie outward along its direction, its start one gap from 0
|
|
403
|
+
cx, cy = sum(x for x, _ in pts) / len(pts), sum(y for _, y in pts) / len(pts)
|
|
404
|
+
turn = dirs[g] - math.atan2(cy, cx) if (cx, cy) != (0, 0) else 0.0
|
|
405
|
+
c, sn = math.cos(turn), math.sin(turn)
|
|
406
|
+
ox, oy = gap * math.cos(dirs[g]), gap * math.sin(dirs[g])
|
|
407
|
+
pts = [(x * c - y * sn + ox, x * sn + y * c + oy) for x, y in pts]
|
|
408
|
+
else: # side by side, tops level
|
|
409
|
+
left, top = min(x for x, _ in pts), min(y for _, y in pts)
|
|
410
|
+
pts = [(x - left + cursor, y - top) for x, y in pts]
|
|
411
|
+
cursor = max(x for x, _ in pts) + room * 0.6
|
|
412
|
+
# walk the strokes in the order they were drawn, so numbers run along the real lines;
|
|
413
|
+
# only real lines are used, and a piece drawn apart gets its own start
|
|
414
|
+
ids = {s0: t.add(*pts[s0], hub if fan else None)}
|
|
415
|
+
if not fan:
|
|
416
|
+
t.starts.append(ids[s0])
|
|
417
|
+
while len(ids) < len(pts):
|
|
418
|
+
grew = True
|
|
419
|
+
while grew:
|
|
420
|
+
grew = False
|
|
421
|
+
for st in strokes:
|
|
422
|
+
for seq in (st, st[::-1]):
|
|
423
|
+
for a, b in zip(seq, seq[1:]):
|
|
424
|
+
if a in ids and b not in ids:
|
|
425
|
+
ids[b] = t.add(*pts[b], ids[a])
|
|
426
|
+
grew = True
|
|
427
|
+
if len(ids) < len(pts):
|
|
428
|
+
s1 = next(i for st in strokes for i in st if i not in ids)
|
|
429
|
+
ids[s1] = t.add(*pts[s1])
|
|
430
|
+
t.starts.append(ids[s1])
|
|
431
|
+
for a, b in lines: # lines that close a loop
|
|
432
|
+
if (ids[a], ids[b]) not in t.edges and (ids[b], ids[a]) not in t.edges:
|
|
433
|
+
t.link(ids[a], ids[b])
|
|
434
|
+
return t
|
|
435
|
+
|
|
436
|
+
for g in range(groups):
|
|
437
|
+
lo, hi = _range(_per_arm(stars, g, [4, 7]))
|
|
438
|
+
if fan: # each figure starts out along its own direction from 0
|
|
439
|
+
head = t.add(out * math.cos(dirs[g]), out * math.sin(dirs[g]), hub)
|
|
440
|
+
chains = [(head, dirs[g], rng.randint(lo, hi) - 1)]
|
|
441
|
+
else:
|
|
442
|
+
for _ in range(200): # a first star well away from every other star
|
|
443
|
+
x, y = rng.uniform(0, side), rng.uniform(0, side)
|
|
444
|
+
if free(x, y, room * 0.6):
|
|
445
|
+
break
|
|
446
|
+
head = t.add(x, y)
|
|
447
|
+
t.starts.append(head)
|
|
448
|
+
chains = [(head, rng.uniform(0, 2 * math.pi), rng.randint(lo, hi) - 1)]
|
|
449
|
+
while chains:
|
|
450
|
+
prev, ang, left = chains.pop()
|
|
451
|
+
while left > 0:
|
|
452
|
+
for _ in range(12): # a few tries at a spot that is not on another star
|
|
453
|
+
na = ang + math.radians(rng.uniform(-bend, bend))
|
|
454
|
+
nx = t.nodes[prev].x + gap * math.cos(na)
|
|
455
|
+
ny = t.nodes[prev].y + gap * math.sin(na)
|
|
456
|
+
inside = not fan or (math.hypot(nx, ny) >= 0.9 * out and # around 0: its own wedge, never back in
|
|
457
|
+
abs((math.atan2(ny, nx) - dirs[g] + math.pi) % (2 * math.pi) - math.pi) <= wedge)
|
|
458
|
+
if inside and free(nx, ny, 0.75 * gap):
|
|
459
|
+
break
|
|
460
|
+
else:
|
|
461
|
+
break # boxed in: the chain ends here
|
|
462
|
+
prev, ang, left = t.add(nx, ny, prev), na, left - 1
|
|
463
|
+
if left > 1 and rng.random() < fork:
|
|
464
|
+
chains.append((prev, ang + math.radians(rng.choice([-70, 70])), rng.randint(1, left - 1)))
|
|
465
|
+
left -= 1
|
|
466
|
+
return t
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def ring(p: dict, rng: random.Random) -> Tree:
|
|
470
|
+
"""A hub with arms fanning out like wedges, and bridges filling the gaps between neighbouring arms."""
|
|
471
|
+
a_v = p.get("arms", 5)
|
|
472
|
+
arms = rng.randint(*_range(a_v)) if isinstance(a_v, list) else _arms(a_v)
|
|
473
|
+
arm_tiers = p.get("arm_tiers", [3, 6, 6, 9, 9, 9]) # nodes across an arm, tier by tier; [6, 9] picks per arm
|
|
474
|
+
bridge_tiers = p.get("bridge_tiers", [1, 1, 2, 3]) # nodes across a bridge, tier by tier ([] for none)
|
|
475
|
+
width = lambda v: _range(v)[1] # the most a tier can hold sets its radius
|
|
476
|
+
hang_v = p.get("bridge_from", 2) # the arm tier a bridge starts beside; [2, 4] picks per bridge
|
|
477
|
+
ties_v = p.get("bridge_ties", 1) # bridge rows, from the first, that touch both arms
|
|
478
|
+
bridges = p.get("bridges", True) # every gap gets a bridge, none, or each by this chance
|
|
479
|
+
spread = p.get("arm_spread", 0.55) # share of an arm's slice the arm itself takes
|
|
480
|
+
slice_ = 2 * math.pi / arms
|
|
481
|
+
first, gap_r, gap_n = p.get("first_radius", 1.5), p.get("tier_gap", 1.0), p.get("node_gap", 1.0)
|
|
482
|
+
fixed = p.get("radii") # optional: every arm tier's radius by hand
|
|
483
|
+
t = Tree("ring")
|
|
484
|
+
hub = t.add(0, 0)
|
|
485
|
+
|
|
486
|
+
def fan(n: int, r: float, mid: float, width: float) -> list[tuple[float, float]]:
|
|
487
|
+
"""n spots on radius r across an angle centred on mid, about one unit apart, never wider than width."""
|
|
488
|
+
step = min(gap_n / r, width / max(n - 1, 1))
|
|
489
|
+
return [(r * math.cos(a), r * math.sin(a))
|
|
490
|
+
for a in (mid + (i - (n - 1) / 2) * step for i in range(n))]
|
|
491
|
+
|
|
492
|
+
def join(prev: list[int], cur: list[int]) -> None:
|
|
493
|
+
"""Each node links back to the node of the row before that stands at the same share of the way across."""
|
|
494
|
+
for i, nid in enumerate(cur):
|
|
495
|
+
t.link(prev[min(len(prev) - 1, i * len(prev) // len(cur))], nid)
|
|
496
|
+
|
|
497
|
+
# each tier goes out far enough for its row to fit its wedge one unit apart, and at least one unit past the last
|
|
498
|
+
arm_w, bridge_w = slice_ * spread, slice_ * (1 - spread) * p.get("bridge_width", 0.8)
|
|
499
|
+
radii: list[float] = []
|
|
500
|
+
for n in map(width, arm_tiers):
|
|
501
|
+
if fixed:
|
|
502
|
+
radii.append(float(fixed[min(len(radii), len(fixed) - 1)]))
|
|
503
|
+
else:
|
|
504
|
+
radii.append(max(radii[-1] + gap_r if radii else first, (n - 1) * gap_n / arm_w))
|
|
505
|
+
|
|
506
|
+
def bridge_radii(hang: int) -> list[float]:
|
|
507
|
+
out: list[float] = []
|
|
508
|
+
for j, n in enumerate(map(width, bridge_tiers)):
|
|
509
|
+
k = hang + j # sits between arm tiers k-1 and k
|
|
510
|
+
base = (radii[k - 1] + radii[k]) / 2 if k < len(radii) else radii[-1] + gap_r * (k - len(radii) + 1.5)
|
|
511
|
+
out.append(max(base, out[-1] + gap_r if out else 0, (n - 1) * gap_n / bridge_w))
|
|
512
|
+
return out
|
|
513
|
+
|
|
514
|
+
arm_rows: list[list[list[int]]] = []
|
|
515
|
+
for a in range(arms):
|
|
516
|
+
mid = a * slice_ - math.pi / 2
|
|
517
|
+
rows, prev = [], [hub]
|
|
518
|
+
for k, n in enumerate(arm_tiers):
|
|
519
|
+
row = [t.add(x, y) for x, y in fan(rng.randint(*_range(n)), radii[k], mid, arm_w)]
|
|
520
|
+
join(prev, row)
|
|
521
|
+
rows.append(row)
|
|
522
|
+
prev = row
|
|
523
|
+
arm_rows.append(rows)
|
|
524
|
+
if arms > 1 and bridge_tiers:
|
|
525
|
+
for a in range(arms):
|
|
526
|
+
b = (a + 1) % arms
|
|
527
|
+
mid = (a + 0.5) * slice_ - math.pi / 2
|
|
528
|
+
if not _coin(bridges, rng):
|
|
529
|
+
continue
|
|
530
|
+
hang = max(1, min(rng.randint(*_range(hang_v)), len(arm_tiers)))
|
|
531
|
+
ties = rng.randint(*_range(ties_v))
|
|
532
|
+
prev = None
|
|
533
|
+
for j, (n, r) in enumerate(zip(bridge_tiers, bridge_radii(hang))):
|
|
534
|
+
row = [t.add(x, y) for x, y in fan(rng.randint(*_range(n)), r, mid, bridge_w)]
|
|
535
|
+
k = hang - 1 + j # the arm tier just inside this row
|
|
536
|
+
if prev is None: # the first row: its near half to each arm, so no lines cross
|
|
537
|
+
half = (len(row) - 1) / 2
|
|
538
|
+
for i, nid in enumerate(row):
|
|
539
|
+
if i <= half:
|
|
540
|
+
t.link(arm_rows[a][k][-1], nid)
|
|
541
|
+
if i >= half:
|
|
542
|
+
t.link(arm_rows[b][k][0], nid)
|
|
543
|
+
else:
|
|
544
|
+
join(prev, row)
|
|
545
|
+
if j < ties and k < len(arm_tiers): # tied again further out: its ends reach the arms too
|
|
546
|
+
t.link(arm_rows[a][k][-1], row[0])
|
|
547
|
+
t.link(arm_rows[b][k][0], row[-1])
|
|
548
|
+
prev = row
|
|
549
|
+
return t
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def _line_warnings(t: Tree, a: int, b: int, what: str) -> None:
|
|
553
|
+
"""A new line a-b that crosses another line or runs over a third node reads wrong: say so."""
|
|
554
|
+
pos = {n.id: (n.x, n.y) for n in t.nodes}
|
|
555
|
+
for c, d in t.edges:
|
|
556
|
+
if not {c, d} & {a, b} and _cross(pos[a], pos[b], pos[c], pos[d]):
|
|
557
|
+
t.warnings.append(f"{what} crosses {t.nodes[c].label}-{t.nodes[d].label}")
|
|
558
|
+
for n in t.nodes:
|
|
559
|
+
if n.id not in (a, b) and pos[a] != pos[b] and _off_line(pos[n.id], pos[a], pos[b]) < 0.35:
|
|
560
|
+
t.warnings.append(f"{what} runs over {n.label}")
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def _cross(A, B, C, D) -> bool:
|
|
564
|
+
def ccw(P, Q, R):
|
|
565
|
+
return (Q[0] - P[0]) * (R[1] - P[1]) - (Q[1] - P[1]) * (R[0] - P[0])
|
|
566
|
+
return ccw(A, B, C) * ccw(A, B, D) < 0 and ccw(C, D, A) * ccw(C, D, B) < 0
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def _off_line(P, A, B) -> float:
|
|
570
|
+
"""Distance from point P to the segment A-B."""
|
|
571
|
+
ax, ay, bx, by = B[0] - A[0], B[1] - A[1], P[0] - A[0], P[1] - A[1]
|
|
572
|
+
k = max(0.0, min(1.0, (ax * bx + ay * by) / (ax * ax + ay * ay)))
|
|
573
|
+
return math.dist(P, (A[0] + k * ax, A[1] + k * ay))
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def add_merges(t: Tree, chance: float, first: int, reach: float, rng: random.Random) -> None:
|
|
577
|
+
"""Join lines: a node may also need a nearby node one tier above it, whose tier is at least `first`.
|
|
578
|
+
|
|
579
|
+
The line is at most `reach` typical line lengths long, comes from the same side as the node's own
|
|
580
|
+
line, crosses no line, passes no node, leaves every line it meets at a clear angle, and keeps one
|
|
581
|
+
node away from any other join, so it reads as a second prerequisite, not a ladder or a tangle.
|
|
582
|
+
"""
|
|
583
|
+
t.set_tiers()
|
|
584
|
+
pos = {n.id: (n.x, n.y) for n in t.nodes}
|
|
585
|
+
lengths = sorted(math.dist(pos[a], pos[b]) for a, b in t.edges)
|
|
586
|
+
unit = lengths[len(lengths) // 2]
|
|
587
|
+
|
|
588
|
+
def clear(a: int, b: int) -> bool:
|
|
589
|
+
A, B = pos[a], pos[b]
|
|
590
|
+
for c, d in t.edges:
|
|
591
|
+
if {c, d} & {a, b}:
|
|
592
|
+
shared = a if a in (c, d) else b # lines meeting at a node must not lie along each other
|
|
593
|
+
other = pos[d if c == shared else c]
|
|
594
|
+
far_end = B if shared == a else A
|
|
595
|
+
u = (far_end[0] - pos[shared][0], far_end[1] - pos[shared][1])
|
|
596
|
+
v = (other[0] - pos[shared][0], other[1] - pos[shared][1])
|
|
597
|
+
cos = (u[0] * v[0] + u[1] * v[1]) / (math.hypot(*u) * math.hypot(*v))
|
|
598
|
+
if cos > math.cos(math.radians(25)):
|
|
599
|
+
return False
|
|
600
|
+
elif _cross(A, B, pos[c], pos[d]):
|
|
601
|
+
return False
|
|
602
|
+
return all(_off_line(pos[n], A, B) > 0.35 * unit for n in pos if n not in (a, b))
|
|
603
|
+
|
|
604
|
+
parent = {b: a for a, b in reversed(t.edges)} # each node's own (first) line in
|
|
605
|
+
touch: dict[int, set[int]] = {n.id: {n.id} for n in t.nodes}
|
|
606
|
+
for a, b in t.edges:
|
|
607
|
+
touch[a].add(b)
|
|
608
|
+
touch[b].add(a)
|
|
609
|
+
busy: set[int] = set() # joins and the nodes next to them
|
|
610
|
+
|
|
611
|
+
def piece(n: int) -> int: # the arm a node grew on; arms never join
|
|
612
|
+
while n in parent and parent[n] not in t.starts:
|
|
613
|
+
n = parent[n]
|
|
614
|
+
return n
|
|
615
|
+
|
|
616
|
+
def same_side(m: int, n: int) -> bool:
|
|
617
|
+
P, M, N = pos[parent[n]], pos[m], pos[n]
|
|
618
|
+
return (N[0] - M[0]) * (N[0] - P[0]) + (N[1] - M[1]) * (N[1] - P[1]) > 0
|
|
619
|
+
|
|
620
|
+
for n in t.nodes:
|
|
621
|
+
if n.tier - 1 < first or n.id in busy or n.id not in parent or rng.random() >= chance:
|
|
622
|
+
continue
|
|
623
|
+
near = [m for m in t.nodes if m.tier == n.tier - 1 and (m.id, n.id) not in t.edges and m.id not in busy
|
|
624
|
+
and piece(m.id) == piece(n.id) and math.dist(pos[m.id], pos[n.id]) <= reach * unit and same_side(m.id, n.id)]
|
|
625
|
+
near.sort(key=lambda m: math.dist(pos[m.id], pos[n.id]))
|
|
626
|
+
for m in near:
|
|
627
|
+
if clear(m.id, n.id):
|
|
628
|
+
t.link(m.id, n.id)
|
|
629
|
+
busy |= touch[m.id] | touch[n.id]
|
|
630
|
+
break
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
def _letters(i: int) -> str:
|
|
634
|
+
"""0 -> a, 25 -> z, 26 -> aa."""
|
|
635
|
+
out = ""
|
|
636
|
+
i += 1
|
|
637
|
+
while i:
|
|
638
|
+
i, r = divmod(i - 1, 26)
|
|
639
|
+
out = chr(97 + r) + out
|
|
640
|
+
return out
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
def set_labels(t: Tree) -> None:
|
|
644
|
+
"""One start: it is 0, each line out of it is a letter. Several starts: each start is a letter, itself x0.
|
|
645
|
+
Within a letter, nodes count 1, 2, 3... outward along their own lines (first line in), nearest first."""
|
|
646
|
+
kids: dict[int, list[int]] = {}
|
|
647
|
+
has_parent: set[int] = set()
|
|
648
|
+
for a, b in t.edges:
|
|
649
|
+
if b not in has_parent and b not in t.starts:
|
|
650
|
+
has_parent.add(b)
|
|
651
|
+
kids.setdefault(a, []).append(b)
|
|
652
|
+
if len(t.starts) == 1:
|
|
653
|
+
t.nodes[t.starts[0]].label = "0"
|
|
654
|
+
heads = kids.get(t.starts[0], [])
|
|
655
|
+
else:
|
|
656
|
+
heads = t.starts
|
|
657
|
+
for i, head in enumerate(heads):
|
|
658
|
+
letter, k = _letters(i), 0
|
|
659
|
+
todo = deque([head])
|
|
660
|
+
if len(t.starts) > 1:
|
|
661
|
+
t.nodes[head].label = letter + "0"
|
|
662
|
+
todo = deque(kids.get(head, []))
|
|
663
|
+
while todo:
|
|
664
|
+
n = todo.popleft()
|
|
665
|
+
k += 1
|
|
666
|
+
t.nodes[n].label = f"{letter}{k}"
|
|
667
|
+
if t.depth_first:
|
|
668
|
+
todo.extendleft(reversed(kids.get(n, [])))
|
|
669
|
+
else:
|
|
670
|
+
todo.extend(kids.get(n, []))
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
def hand_nodes(t: Tree, grow: list, meet: list) -> None:
|
|
674
|
+
"""grow = [{at = "b5", nodes = 2, side = "left"}] adds nodes on b5 (side: out, left or right, as seen on
|
|
675
|
+
the page when the line runs down); meet = [["c5", "b12"]] adds one node both lead to. New nodes carry on
|
|
676
|
+
the labels: b5's arm counts on, a meeting node takes both letters (bc1)."""
|
|
677
|
+
if not grow and not meet:
|
|
678
|
+
return
|
|
679
|
+
by = {n.label: n.id for n in t.nodes}
|
|
680
|
+
pos = {n.id: (n.x, n.y) for n in t.nodes}
|
|
681
|
+
lengths = sorted(math.dist(pos[a], pos[b]) for a, b in t.edges)
|
|
682
|
+
unit = lengths[len(lengths) // 2] if lengths else 1.0
|
|
683
|
+
parent = {b: a for a, b in reversed(t.edges)}
|
|
684
|
+
|
|
685
|
+
def node(label: str) -> int:
|
|
686
|
+
if label not in by:
|
|
687
|
+
raise ValueError(f"{label!r}: no such node (labels look like 0, a1, b3)")
|
|
688
|
+
return by[label]
|
|
689
|
+
|
|
690
|
+
def heading(n: int) -> tuple[float, float]: # which way the line into n runs; down for a start
|
|
691
|
+
if n not in parent:
|
|
692
|
+
return 0.0, 1.0
|
|
693
|
+
(px, py), (x, y) = pos[parent[n]], pos[n]
|
|
694
|
+
d = math.hypot(x - px, y - py) or 1.0
|
|
695
|
+
return (x - px) / d, (y - py) / d
|
|
696
|
+
|
|
697
|
+
def next_label(prefix: str) -> str:
|
|
698
|
+
used = [int(lb[len(prefix):]) for lb in by if lb.startswith(prefix) and lb[len(prefix):].isdigit()]
|
|
699
|
+
return f"{prefix}{max(used, default=0) + 1}"
|
|
700
|
+
|
|
701
|
+
def put(x: float, y: float, froms: list[int], label: str) -> None:
|
|
702
|
+
if any(math.dist((x, y), q) < 0.5 * unit for q in pos.values()):
|
|
703
|
+
t.warnings.append(f"{label} sits on another node")
|
|
704
|
+
for f in froms:
|
|
705
|
+
if any(not {f} & {c, d} and _cross(pos[f], (x, y), pos[c], pos[d]) for c, d in t.edges):
|
|
706
|
+
t.warnings.append(f"the line {t.nodes[f].label}-{label} crosses another")
|
|
707
|
+
nid = t.add(x, y, froms[0])
|
|
708
|
+
for f in froms[1:]:
|
|
709
|
+
t.link(f, nid)
|
|
710
|
+
t.nodes[nid].label, by[label], pos[nid] = label, nid, (x, y)
|
|
711
|
+
|
|
712
|
+
for g in grow:
|
|
713
|
+
extra = set(g) - {"at", "nodes", "side"}
|
|
714
|
+
if "at" not in g or extra:
|
|
715
|
+
raise ValueError(f"grow {g}: needs at, may have nodes and side")
|
|
716
|
+
n, k, side = node(g["at"]), int(g.get("nodes", 1)), g.get("side", "out")
|
|
717
|
+
dx, dy = heading(n)
|
|
718
|
+
turn = {"out": (dx, dy), "left": (-dy, dx), "right": (dy, -dx)}
|
|
719
|
+
if side not in turn:
|
|
720
|
+
raise ValueError(f"grow {g}: side is out, left or right")
|
|
721
|
+
ux, uy = turn[side]
|
|
722
|
+
base = math.atan2(uy, ux)
|
|
723
|
+
spread = min(60.0, 25.0 * (k - 1))
|
|
724
|
+
prefix = g["at"].rstrip("0123456789") or _letters(len({lb.rstrip("0123456789") for lb in by}) - 1)
|
|
725
|
+
for i in range(k):
|
|
726
|
+
a = base + math.radians(-spread + 2 * spread * i / (k - 1) if k > 1 else 0.0)
|
|
727
|
+
x, y = pos[n][0] + unit * math.cos(a), pos[n][1] + unit * math.sin(a)
|
|
728
|
+
put(x, y, [n], next_label(prefix))
|
|
729
|
+
for pair in meet:
|
|
730
|
+
if len(pair) != 2:
|
|
731
|
+
raise ValueError(f"meet {pair}: two labels, such as [\"c5\", \"b12\"]")
|
|
732
|
+
a, b = node(pair[0]), node(pair[1])
|
|
733
|
+
(ax, ay), (bx, by_) = pos[a], pos[b]
|
|
734
|
+
hx, hy = [(u + v) / 2 for u, v in zip(heading(a), heading(b))]
|
|
735
|
+
h = math.hypot(hx, hy) or 1.0
|
|
736
|
+
x, y = (ax + bx) / 2 + unit * hx / h, (ay + by_) / 2 + unit * hy / h
|
|
737
|
+
prefix = "".join(sorted({c for lb in pair for c in lb.rstrip("0123456789")})) or "m"
|
|
738
|
+
put(x, y, [a, b], next_label(prefix))
|
|
739
|
+
|
|
740
|
+
|
|
741
|
+
def hand_moves(t: Tree, move: dict, shift: dict, place: dict) -> None:
|
|
742
|
+
"""Fix positions by label, after the shape: move = {a3 = [0.5, -0.2]} nudges one node,
|
|
743
|
+
shift = {b2 = [1, 0]} nudges a node with everything hanging off it, place = {c1 = [4, 2]} puts one
|
|
744
|
+
node at a spot. Distances are node widths, y grows downward."""
|
|
745
|
+
if not (move or shift or place):
|
|
746
|
+
return
|
|
747
|
+
by = {n.label: n for n in t.nodes}
|
|
748
|
+
kids: dict[int, list[int]] = {}
|
|
749
|
+
seen_in: set[int] = set()
|
|
750
|
+
for a, b in t.edges:
|
|
751
|
+
if b not in seen_in:
|
|
752
|
+
seen_in.add(b)
|
|
753
|
+
kids.setdefault(a, []).append(b)
|
|
754
|
+
|
|
755
|
+
def node(label: str, xy) -> Node:
|
|
756
|
+
if label not in by:
|
|
757
|
+
raise ValueError(f"{label!r}: no such node (labels look like 0, a1, b3)")
|
|
758
|
+
if not (isinstance(xy, list) and len(xy) == 2):
|
|
759
|
+
raise ValueError(f"{label} = {xy!r}: give [x, y]")
|
|
760
|
+
return by[label]
|
|
761
|
+
|
|
762
|
+
for label, (dx, dy) in shift.items():
|
|
763
|
+
todo = [node(label, [dx, dy]).id]
|
|
764
|
+
while todo:
|
|
765
|
+
n = t.nodes[todo.pop()]
|
|
766
|
+
n.x, n.y = n.x + dx, n.y + dy
|
|
767
|
+
todo += kids.get(n.id, [])
|
|
768
|
+
for label, (dx, dy) in move.items():
|
|
769
|
+
n = node(label, [dx, dy])
|
|
770
|
+
n.x, n.y = n.x + dx, n.y + dy
|
|
771
|
+
for label, (x, y) in place.items():
|
|
772
|
+
n = node(label, [x, y])
|
|
773
|
+
n.x, n.y = float(x), float(y)
|
|
774
|
+
moved = set(move) | set(place) | set(shift)
|
|
775
|
+
for n in t.nodes:
|
|
776
|
+
if n.label in moved and any((m.x - n.x) ** 2 + (m.y - n.y) ** 2 < 0.25 for m in t.nodes if m is not n):
|
|
777
|
+
t.warnings.append(f"{n.label} now sits on another node")
|
|
778
|
+
pos = {n.id: (n.x, n.y) for n in t.nodes}
|
|
779
|
+
for i, (a, b) in enumerate(t.edges):
|
|
780
|
+
for c, d in t.edges[i + 1:]:
|
|
781
|
+
if not {a, b} & {c, d} and _cross(pos[a], pos[b], pos[c], pos[d]) and \
|
|
782
|
+
{t.nodes[x].label for x in (a, b, c, d)} & moved:
|
|
783
|
+
t.warnings.append(f"{t.nodes[a].label}-{t.nodes[b].label} now crosses {t.nodes[c].label}-{t.nodes[d].label}")
|
|
784
|
+
|
|
785
|
+
|
|
786
|
+
def hand_joins(t: Tree, add: list, drop: list) -> None:
|
|
787
|
+
"""joins = [["a3", "b2"]] adds a line; no_joins = [["a2", "a5"]] takes away one a join made."""
|
|
788
|
+
if not add and not drop:
|
|
789
|
+
return
|
|
790
|
+
t.set_tiers(strict=False)
|
|
791
|
+
by = {n.label: n.id for n in t.nodes}
|
|
792
|
+
pos = {n.id: (n.x, n.y) for n in t.nodes}
|
|
793
|
+
|
|
794
|
+
def ids(pair) -> tuple[int, int]:
|
|
795
|
+
if len(pair) != 2 or any(x not in by for x in pair):
|
|
796
|
+
raise ValueError(f"join {pair}: no such node (labels look like 0, a1, b3)")
|
|
797
|
+
return by[pair[0]], by[pair[1]]
|
|
798
|
+
|
|
799
|
+
first_in: set[tuple[int, int]] = set()
|
|
800
|
+
seen_in: set[int] = set()
|
|
801
|
+
for a, b in t.edges:
|
|
802
|
+
if b not in seen_in:
|
|
803
|
+
first_in.add((a, b))
|
|
804
|
+
seen_in.add(b)
|
|
805
|
+
for pair in drop:
|
|
806
|
+
a, b = ids(pair)
|
|
807
|
+
e = (a, b) if (a, b) in t.edges else (b, a)
|
|
808
|
+
if e not in t.edges or e in first_in:
|
|
809
|
+
raise ValueError(f"no_joins {pair}: not a join (a node's own line cannot be taken away)")
|
|
810
|
+
t.edges.remove(e)
|
|
811
|
+
for pair in add:
|
|
812
|
+
a, b = ids(pair)
|
|
813
|
+
if (a, b) in t.edges or (b, a) in t.edges:
|
|
814
|
+
raise ValueError(f"joins {pair}: already linked")
|
|
815
|
+
far = lambda i: t.nodes[i].tier if t.nodes[i].tier >= 0 else math.inf # a loose node is furthest out
|
|
816
|
+
if far(b) < far(a): # the line runs from the nearer node out, so a loose node's first line is its own, not a join
|
|
817
|
+
a, b = b, a
|
|
818
|
+
_line_warnings(t, a, b, f"joins {pair}")
|
|
819
|
+
t.link(a, b)
|
|
820
|
+
|
|
821
|
+
|
|
822
|
+
LOOKS = {"circle": 0, "triangle": 3, "square": 4, "diamond": 4, "pentagon": 5, "hexagon": 6, "octagon": 8}
|
|
823
|
+
|
|
824
|
+
|
|
825
|
+
def hand_looks(t: Tree, look, ratio, per: dict) -> None:
|
|
826
|
+
"""node_shape / node_ratio for every node; node_shapes = {a3 = "square", "0" = {shape = "hexagon", ratio = [2, 1]}} for some."""
|
|
827
|
+
def check(where, lk, r):
|
|
828
|
+
lk = str(lk)
|
|
829
|
+
if lk not in LOOKS and not (lk.isdigit() and int(lk) >= 3):
|
|
830
|
+
raise ValueError(f"{where}: shape {lk!r}; one of {', '.join(LOOKS)}, or a number of sides (3 or more)")
|
|
831
|
+
if not isinstance(r, (list, tuple)) or len(r) != 2 or not all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in r) or min(r) <= 0:
|
|
832
|
+
raise ValueError(f"{where}: ratio is two numbers above 0, width and height, e.g. [2, 1]")
|
|
833
|
+
return lk, (float(r[0]), float(r[1]))
|
|
834
|
+
base = check("node_shape", look, ratio)
|
|
835
|
+
by = {n.label: n for n in t.nodes}
|
|
836
|
+
for n in t.nodes:
|
|
837
|
+
n.look, n.ratio = base
|
|
838
|
+
for label, v in per.items():
|
|
839
|
+
if label not in by:
|
|
840
|
+
raise ValueError(f"node_shapes {label}: no such node (labels look like 0, a1, b3)")
|
|
841
|
+
if isinstance(v, dict):
|
|
842
|
+
if set(v) - {"shape", "ratio"}:
|
|
843
|
+
raise ValueError(f"node_shapes {label}: only shape and ratio")
|
|
844
|
+
v = check(f"node_shapes {label}", v.get("shape", base[0]), v.get("ratio", base[1]))
|
|
845
|
+
else:
|
|
846
|
+
v = check(f"node_shapes {label}", v, base[1])
|
|
847
|
+
by[label].look, by[label].ratio = v
|
|
848
|
+
|
|
849
|
+
|
|
850
|
+
def hand_add(t: Tree, add: dict) -> None:
|
|
851
|
+
"""add = {n1 = [3, 2]} puts a new node there with no line yet; joins = [["a3", "n1"]] then links it."""
|
|
852
|
+
by = {n.label for n in t.nodes}
|
|
853
|
+
for label, xy in add.items():
|
|
854
|
+
if label in by:
|
|
855
|
+
raise ValueError(f"add {label}: that label is taken")
|
|
856
|
+
if not (isinstance(xy, list) and len(xy) == 2):
|
|
857
|
+
raise ValueError(f"add {label} = {xy!r}: give [x, y]")
|
|
858
|
+
t.nodes[t.add(float(xy[0]), float(xy[1]))].label = label
|
|
859
|
+
by.add(label)
|
|
860
|
+
|
|
861
|
+
|
|
862
|
+
def hand_remove(t: Tree, remove: list, cut: list) -> None:
|
|
863
|
+
"""cut = [["a2", "a3"]] takes away any line; remove = ["b4"] takes away a node with its lines.
|
|
864
|
+
The other nodes keep their labels; one left without a way to a start is warned about, not dropped."""
|
|
865
|
+
if not remove and not cut:
|
|
866
|
+
return
|
|
867
|
+
by = {n.label: n.id for n in t.nodes}
|
|
868
|
+
|
|
869
|
+
def node(label: str) -> int:
|
|
870
|
+
if label not in by:
|
|
871
|
+
raise ValueError(f"{label!r}: no such node (labels look like 0, a1, b3)")
|
|
872
|
+
return by[label]
|
|
873
|
+
|
|
874
|
+
for pair in cut:
|
|
875
|
+
if len(pair) != 2:
|
|
876
|
+
raise ValueError(f"cut {pair}: two labels, such as [\"a2\", \"a3\"]")
|
|
877
|
+
a, b = node(pair[0]), node(pair[1])
|
|
878
|
+
e = (a, b) if (a, b) in t.edges else (b, a)
|
|
879
|
+
if e not in t.edges:
|
|
880
|
+
raise ValueError(f"cut {pair}: no line there")
|
|
881
|
+
t.edges.remove(e)
|
|
882
|
+
gone = {node(lb) for lb in remove}
|
|
883
|
+
if gone & set(t.starts):
|
|
884
|
+
raise ValueError("remove: a start cannot be taken away")
|
|
885
|
+
keep = [n for n in t.nodes if n.id not in gone]
|
|
886
|
+
new = {n.id: i for i, n in enumerate(keep)}
|
|
887
|
+
for n in keep:
|
|
888
|
+
n.id = new[n.id]
|
|
889
|
+
t.edges = [(new[a], new[b]) for a, b in t.edges if a in new and b in new]
|
|
890
|
+
t.starts = [new[s] for s in t.starts]
|
|
891
|
+
t.nodes = keep
|
|
892
|
+
|
|
893
|
+
|
|
894
|
+
SHAPES = {"ring": ring, "branch": branch, "grid": grid, "zigzag": zigzag, "spine": spine, "constellation": constellation} # ring is the main one and the default
|
|
895
|
+
|
|
896
|
+
|
|
897
|
+
# settings that name nodes by label, or only change how they look: neither moves a label, so a stamp leaves them out
|
|
898
|
+
BY_LABEL = {"grow", "meet", "move", "shift", "place", "joins", "no_joins", "add", "remove", "cut",
|
|
899
|
+
"node_shapes", "node_costs", "need_all", "made_with"}
|
|
900
|
+
LOOK_ONLY = {"node_shape", "node_ratio", "cost"}
|
|
901
|
+
|
|
902
|
+
|
|
903
|
+
def stamp(settings: dict) -> str:
|
|
904
|
+
"""A short fingerprint of the settings that decide the labels (shape, seed, counts...). The editor writes it as
|
|
905
|
+
made_with beside the hand fixes, so a later change of seed or counts, which renames nodes, is caught."""
|
|
906
|
+
keep = {k: v for k, v in settings.items() if k not in BY_LABEL | LOOK_ONLY | {"name", "at"}}
|
|
907
|
+
keep.setdefault("seed", 0)
|
|
908
|
+
return hashlib.sha1(json.dumps(keep, sort_keys=True).encode("utf-8")).hexdigest()[:8]
|
|
909
|
+
|
|
910
|
+
|
|
911
|
+
def hand_costs(t: Tree, cost, per: dict, every: list) -> None:
|
|
912
|
+
"""cost = 1, or a list by tier ([1, 1, 2, 3]: the last goes on); node_costs = {a3 = 5} for some;
|
|
913
|
+
need_all = ["bc1"]: nodes that want every line into them taken first (by default one is enough)."""
|
|
914
|
+
tiers = cost if isinstance(cost, list) else [cost]
|
|
915
|
+
num = lambda c: isinstance(c, (int, float)) and not isinstance(c, bool)
|
|
916
|
+
if not tiers or not all(num(c) and c >= 0 for c in tiers):
|
|
917
|
+
raise ValueError("cost: a number of 0 or more, or a list of them by tier")
|
|
918
|
+
by = {n.label: n for n in t.nodes}
|
|
919
|
+
for n in t.nodes:
|
|
920
|
+
n.cost = tiers[min(max(n.tier, 0), len(tiers) - 1)]
|
|
921
|
+
for label, c in per.items():
|
|
922
|
+
if label not in by:
|
|
923
|
+
raise ValueError(f"node_costs {label}: no such node (labels look like 0, a1, b3)")
|
|
924
|
+
if not num(c) or c < 0:
|
|
925
|
+
raise ValueError(f"node_costs {label}: a number of 0 or more")
|
|
926
|
+
by[label].cost = c
|
|
927
|
+
for label in every:
|
|
928
|
+
if label not in by:
|
|
929
|
+
raise ValueError(f"need_all {label}: no such node (labels look like 0, a1, b3)")
|
|
930
|
+
by[label].need_all = True
|
|
931
|
+
|
|
932
|
+
|
|
933
|
+
def build(shape: str, params: dict, seed: int = 0) -> Tree:
|
|
934
|
+
if shape not in SHAPES:
|
|
935
|
+
raise ValueError(f"unknown shape {shape!r}; one of {', '.join(SHAPES)}")
|
|
936
|
+
seen = _Seen(params)
|
|
937
|
+
rng = random.Random(seed)
|
|
938
|
+
t = SHAPES[shape](seen, rng)
|
|
939
|
+
t.set_tiers() # a shape that leaves a node unreachable is a bug: stop here
|
|
940
|
+
set_labels(t)
|
|
941
|
+
if shape == "constellation" and params.get("figure") is not None and params.get("merge"):
|
|
942
|
+
raise ValueError("constellation: a figure keeps its own lines only; merge is off")
|
|
943
|
+
if shape not in ("ring", "zigzag") and params.get("figure") is None: # ring bridges and figures have their lines
|
|
944
|
+
m = seen.get("merge", False)
|
|
945
|
+
chance = 0.3 if m is True else float(m or 0)
|
|
946
|
+
if chance:
|
|
947
|
+
add_merges(t, chance, seen.get("merge_from", 2), seen.get("merge_reach", 2.0), rng)
|
|
948
|
+
hand_nodes(t, seen.get("grow", []), seen.get("meet", []))
|
|
949
|
+
hand_add(t, seen.get("add", {}))
|
|
950
|
+
hand_moves(t, seen.get("move", {}), {}, {})
|
|
951
|
+
hand_joins(t, seen.get("joins", []), seen.get("no_joins", []))
|
|
952
|
+
# shift after the hand lines, so a node added and linked by hand hangs off its node and goes along with it;
|
|
953
|
+
# place last, so a placed node stays where it was put
|
|
954
|
+
hand_moves(t, {}, seen.get("shift", {}), seen.get("place", {}))
|
|
955
|
+
hand_looks(t, seen.get("node_shape", "circle"), seen.get("node_ratio", [1, 1]), seen.get("node_shapes", {}))
|
|
956
|
+
hand_remove(t, seen.get("remove", []), seen.get("cut", []))
|
|
957
|
+
cost, node_costs, need_all = seen.get("cost", 1), seen.get("node_costs", {}), seen.get("need_all", [])
|
|
958
|
+
made = seen.get("made_with")
|
|
959
|
+
unknown = sorted(set(params) - seen.asked)
|
|
960
|
+
if unknown: # a misspelt setting would otherwise be ignored without a word
|
|
961
|
+
raise ValueError(f"{shape}: unknown setting(s) {', '.join(unknown)}")
|
|
962
|
+
t.set_tiers(strict=False) # only hand edits can leave a node loose: the shape itself was checked above
|
|
963
|
+
t.warnings += [f"{n.label} has no way to a start (tier -1)" for n in t.nodes if n.tier < 0]
|
|
964
|
+
own_lines_first(t)
|
|
965
|
+
hand_costs(t, cost, node_costs, need_all)
|
|
966
|
+
if made is not None and made != stamp({"shape": shape, "seed": seed, **params}):
|
|
967
|
+
t.warnings.append("seed, counts or shape settings changed since the hand fixes were made (made_with): "
|
|
968
|
+
"labels may now name other nodes; check the picture, then save from skilltree edit")
|
|
969
|
+
return t
|
|
970
|
+
|
|
971
|
+
|
|
972
|
+
def own_lines_first(t: Tree) -> None:
|
|
973
|
+
"""Lines run outward, and each node's own line (from one tier nearer) comes before its joins, so 'a second
|
|
974
|
+
line in is a join' holds however hand lines were drawn: n1-n2 drawn before n3-n1 must not make n3-n1 a join."""
|
|
975
|
+
tier = {n.id: n.tier for n in t.nodes}
|
|
976
|
+
far = lambda i: tier[i] if tier[i] >= 0 else math.inf
|
|
977
|
+
edges = [(b, a) if far(a) > far(b) else (a, b) for a, b in t.edges]
|
|
978
|
+
own: dict[int, int] = {}
|
|
979
|
+
for i, (a, b) in enumerate(edges):
|
|
980
|
+
if b not in own and tier[b] > 0 and tier[a] == tier[b] - 1:
|
|
981
|
+
own[b] = i
|
|
982
|
+
firsts = set(own.values())
|
|
983
|
+
t.edges = [e for i, e in enumerate(edges) if i in firsts] + [e for i, e in enumerate(edges) if i not in firsts]
|
|
984
|
+
|
|
985
|
+
|
|
986
|
+
def build_file(cfg: dict) -> Tree:
|
|
987
|
+
"""A whole settings file: one tree, or [[tree]] blocks (each with a name and an at = [x, y]) joined by
|
|
988
|
+
links = [["fire.a3", "ice.b2"]]. Labels of a tree in a block carry its name: fire.a3."""
|
|
989
|
+
cfg = dict(cfg)
|
|
990
|
+
if "tree" not in cfg:
|
|
991
|
+
shape, seed = cfg.pop("shape", "ring"), cfg.pop("seed", 0)
|
|
992
|
+
if not shape:
|
|
993
|
+
raise ValueError(f"no shape (one of {', '.join(SHAPES)})")
|
|
994
|
+
return build(shape, cfg, seed)
|
|
995
|
+
links = cfg.pop("links", [])
|
|
996
|
+
if set(cfg) - {"tree"}:
|
|
997
|
+
raise ValueError(f"with [[tree]] blocks only links stays at the top, not {', '.join(sorted(set(cfg) - {'tree'}))}")
|
|
998
|
+
out = Tree("trees", starts=[])
|
|
999
|
+
for i, tc in enumerate(cfg["tree"]):
|
|
1000
|
+
tc = dict(tc)
|
|
1001
|
+
name, at = tc.pop("name", None), tc.pop("at", [0, 0])
|
|
1002
|
+
if not isinstance(name, str) or not re.match(r"^[A-Za-z0-9_-]+$", name):
|
|
1003
|
+
raise ValueError(f"tree {i + 1}: give it a name of letters, digits, _ or -")
|
|
1004
|
+
if any(n.label.startswith(name + ".") for n in out.nodes):
|
|
1005
|
+
raise ValueError(f"tree {name}: the name is used twice")
|
|
1006
|
+
if not (isinstance(at, list) and len(at) == 2):
|
|
1007
|
+
raise ValueError(f"tree {name}: at = [x, y]")
|
|
1008
|
+
shape, seed = tc.pop("shape", "ring"), tc.pop("seed", 0)
|
|
1009
|
+
if not shape:
|
|
1010
|
+
raise ValueError(f"tree {name}: no shape (one of {', '.join(SHAPES)})")
|
|
1011
|
+
try:
|
|
1012
|
+
t = build(shape, tc, seed)
|
|
1013
|
+
except ValueError as e:
|
|
1014
|
+
raise ValueError(f"tree {name}: {e}") from None
|
|
1015
|
+
base = len(out.nodes)
|
|
1016
|
+
for n in t.nodes:
|
|
1017
|
+
n.id, n.x, n.y, n.label = n.id + base, n.x + at[0], n.y + at[1], f"{name}.{n.label}"
|
|
1018
|
+
out.nodes += t.nodes
|
|
1019
|
+
out.edges += [(a + base, b + base) for a, b in t.edges]
|
|
1020
|
+
out.starts += [s + base for s in t.starts]
|
|
1021
|
+
out.warnings += [f"{name}: {w}" for w in t.warnings]
|
|
1022
|
+
for i, n in enumerate(out.nodes): # trees standing on each other
|
|
1023
|
+
tn = n.label.split(".")[0]
|
|
1024
|
+
hit = next((m for m in out.nodes[i + 1:] if m.label.split(".")[0] != tn
|
|
1025
|
+
and (m.x - n.x) ** 2 + (m.y - n.y) ** 2 < 0.25), None)
|
|
1026
|
+
if hit and not any(w.startswith(f"trees {tn} and {hit.label.split('.')[0]}") for w in out.warnings):
|
|
1027
|
+
out.warnings.append(f"trees {tn} and {hit.label.split('.')[0]} overlap ({n.label} on {hit.label}); move one with at")
|
|
1028
|
+
by = {n.label: n.id for n in out.nodes}
|
|
1029
|
+
for pair in links:
|
|
1030
|
+
if len(pair) != 2 or any(x not in by for x in pair):
|
|
1031
|
+
raise ValueError(f"links {pair}: no such node (labels look like fire.a3)")
|
|
1032
|
+
if pair[0].split(".")[0] == pair[1].split(".")[0]:
|
|
1033
|
+
raise ValueError(f"links {pair}: both in one tree; use that tree's joins")
|
|
1034
|
+
a, b = by[pair[0]], by[pair[1]]
|
|
1035
|
+
if (a, b) in out.edges or (b, a) in out.edges:
|
|
1036
|
+
raise ValueError(f"links {pair}: already linked")
|
|
1037
|
+
if b in out.starts and a not in out.starts: # a start never waits on another tree: the line runs out of it
|
|
1038
|
+
a, b = b, a
|
|
1039
|
+
_line_warnings(out, a, b, f"links {pair}")
|
|
1040
|
+
out.link(a, b)
|
|
1041
|
+
return out # tiers stay each tree's own: a link between trees is a join, not a way in
|
|
1042
|
+
|
|
1043
|
+
|
|
1044
|
+
class _Seen(dict):
|
|
1045
|
+
"""The settings, remembering which ones the shape asked for."""
|
|
1046
|
+
|
|
1047
|
+
def __init__(self, d: dict):
|
|
1048
|
+
super().__init__(d)
|
|
1049
|
+
self.asked: set[str] = set()
|
|
1050
|
+
|
|
1051
|
+
def get(self, key, default=None):
|
|
1052
|
+
self.asked.add(key)
|
|
1053
|
+
return super().get(key, default)
|