wobblyhead hg > minor_monsters
comparison tools/masks.py @ 1:5492efd60e2c
first prototype + updated art sheet
| author | ark |
|---|---|
| date | 2026-10-18 14:50 +0200 |
| parents | |
| children | 53f015966118 |
comparison
equal
deleted
inserted
replaced
| 0:7af9dd4e2595 | 1:5492efd60e2c |
|---|---|
| 1 """ | |
| 2 mask steps of the build: pixel classes, placement grid and routes. | |
| 3 | |
| 4 a mask is a map-sized image with a red path, blue entrances and green exits | |
| 5 on a transparent background. pixels are indexed as y * width + x throughout. | |
| 6 """ | |
| 7 | |
| 8 import math | |
| 9 from collections import deque | |
| 10 | |
| 11 from PIL import Image, ImageDraw | |
| 12 | |
| 13 FREE, PATH, ENTRANCE, EXIT = 0, 1, 2, 3 | |
| 14 | |
| 15 # 8-neighbour offsets in the order n, ne, e, se, s, sw, w, nw | |
| 16 NEIGHBOURS = ((0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1)) | |
| 17 | |
| 18 | |
| 19 class Mask: | |
| 20 """pixel classes of one map mask.""" | |
| 21 | |
| 22 def __init__(self, path): | |
| 23 im = Image.open(path).convert("RGBA") | |
| 24 self.w, self.h = im.size | |
| 25 data = im.tobytes() | |
| 26 cls = bytearray(self.w * self.h) | |
| 27 # the edges are soft: a pixel counts when it is at least half covered, | |
| 28 # and belongs to its strongest colour channel | |
| 29 for i in range(self.w * self.h): | |
| 30 j = i * 4 | |
| 31 if data[j + 3] >= 128: | |
| 32 r, g, b = data[j], data[j + 1], data[j + 2] | |
| 33 if r >= g and r >= b: | |
| 34 cls[i] = PATH | |
| 35 elif b >= g: | |
| 36 cls[i] = ENTRANCE | |
| 37 else: | |
| 38 cls[i] = EXIT | |
| 39 self.cls = cls | |
| 40 | |
| 41 def count(self, kind): | |
| 42 return self.cls.count(kind) | |
| 43 | |
| 44 def blobs(self, kind): | |
| 45 """ | |
| 46 return the connected areas of one class, largest first, as a list | |
| 47 of (centre x, centre y, radius, pixel count). radius is that of a | |
| 48 disc with the same area. | |
| 49 """ | |
| 50 w, h, cls = self.w, self.h, self.cls | |
| 51 seen = bytearray(w * h) | |
| 52 out = [] | |
| 53 for start in range(w * h): | |
| 54 if cls[start] != kind or seen[start]: | |
| 55 continue | |
| 56 seen[start] = 1 | |
| 57 queue = deque([start]) | |
| 58 sx = sy = n = 0 | |
| 59 while queue: | |
| 60 i = queue.popleft() | |
| 61 x, y = i % w, i // w | |
| 62 sx += x | |
| 63 sy += y | |
| 64 n += 1 | |
| 65 for dx, dy in NEIGHBOURS: | |
| 66 nx, ny = x + dx, y + dy | |
| 67 if 0 <= nx < w and 0 <= ny < h: | |
| 68 k = ny * w + nx | |
| 69 if cls[k] == kind and not seen[k]: | |
| 70 seen[k] = 1 | |
| 71 queue.append(k) | |
| 72 out.append((sx / n, sy / n, math.sqrt(n / math.pi), n)) | |
| 73 out.sort(key=lambda b: -b[3]) | |
| 74 return out | |
| 75 | |
| 76 def grown(self, kinds, radius): | |
| 77 """ | |
| 78 return an L image, 255 on pixels of the given classes and on every | |
| 79 pixel within radius of one. drawn as discs around the edge pixels | |
| 80 of the area, which is the same as a distance test. | |
| 81 """ | |
| 82 w, h, cls = self.w, self.h, self.cls | |
| 83 im = Image.new("L", (w, h), 0) | |
| 84 draw = ImageDraw.Draw(im) | |
| 85 inside = bytes(255 if c in kinds else 0 for c in cls) | |
| 86 im.paste(Image.frombytes("L", (w, h), inside)) | |
| 87 for y in range(h): | |
| 88 row = y * w | |
| 89 for x in range(w): | |
| 90 if not inside[row + x]: | |
| 91 continue | |
| 92 edge = (x == 0 or x == w - 1 or y == 0 or y == h - 1 | |
| 93 or not inside[row + x - 1] or not inside[row + x + 1] | |
| 94 or not inside[row + x - w] or not inside[row + x + w]) | |
| 95 if edge: | |
| 96 draw.ellipse((x - radius, y - radius, x + radius, y + radius), fill=255) | |
| 97 return im | |
| 98 | |
| 99 | |
| 100 def placement_grid(mask, p): | |
| 101 """ | |
| 102 return (cols, rows, grid string) for placement table p. a cell is legal | |
| 103 when a tower footprint centred on it does not overlap the path, | |
| 104 entrances or exits, comes within max_gap of the path, and keeps | |
| 105 edge_distance from the map edge. the string has one '1' or '0' per | |
| 106 cell, row by row. | |
| 107 """ | |
| 108 cell = p["grid_cell"] | |
| 109 r = p["footprint_radius"] | |
| 110 blocked = mask.grown((PATH, ENTRANCE, EXIT), r).tobytes() | |
| 111 near = mask.grown((PATH,), r + p["max_gap"]).tobytes() | |
| 112 edge = p["edge_distance"] | |
| 113 w, h = mask.w, mask.h | |
| 114 cols, rows = w // cell, h // cell | |
| 115 out = [] | |
| 116 for cy in range(rows): | |
| 117 y = cy * cell + cell // 2 | |
| 118 for cx in range(cols): | |
| 119 x = cx * cell + cell // 2 | |
| 120 i = y * w + x | |
| 121 ok = (near[i] and not blocked[i] | |
| 122 and edge <= x <= w - edge and edge <= y <= h - edge) | |
| 123 out.append("1" if ok else "0") | |
| 124 return cols, rows, "".join(out) | |
| 125 | |
| 126 | |
| 127 def thin(shape, w, h): | |
| 128 """ | |
| 129 reduce a 0/1 bytearray shape to a one pixel wide centre line | |
| 130 (zhang-suen thinning). the shape must not touch the image border. | |
| 131 only pixels next to removed ones are re-examined, which keeps the | |
| 132 pure python loop fast. returns the thinned bytearray. | |
| 133 """ | |
| 134 img = bytearray(shape) | |
| 135 offs = [dy * w + dx for dx, dy in NEIGHBOURS] | |
| 136 | |
| 137 def touches_background(i): | |
| 138 return any(not img[i + o] for o in offs) | |
| 139 | |
| 140 cand = {i for i in range(w * h) if img[i] and touches_background(i)} | |
| 141 while True: | |
| 142 removed_any = False | |
| 143 for step in (0, 1): | |
| 144 remove = [] | |
| 145 for i in cand: | |
| 146 if not img[i]: | |
| 147 continue | |
| 148 p = [img[i + o] for o in offs] | |
| 149 b = sum(p) | |
| 150 if b < 2 or b > 6: | |
| 151 continue | |
| 152 a = sum(1 for k in range(8) if not p[k] and p[(k + 1) % 8]) | |
| 153 if a != 1: | |
| 154 continue | |
| 155 n, e, s, wst = p[0], p[2], p[4], p[6] | |
| 156 if step == 0: | |
| 157 if n and e and s or e and s and wst: | |
| 158 continue | |
| 159 else: | |
| 160 if n and e and wst or n and s and wst: | |
| 161 continue | |
| 162 remove.append(i) | |
| 163 if remove: | |
| 164 removed_any = True | |
| 165 nxt = set() | |
| 166 for i in remove: | |
| 167 img[i] = 0 | |
| 168 for i in remove: | |
| 169 for o in offs: | |
| 170 if img[i + o]: | |
| 171 nxt.add(i + o) | |
| 172 cand = (cand | nxt) - set(remove) | |
| 173 if not removed_any: | |
| 174 return img | |
| 175 | |
| 176 | |
| 177 class Graph: | |
| 178 """ | |
| 179 the centre line as a graph. nodes are junctions and line ends, edges | |
| 180 the pixel chains between them. | |
| 181 | |
| 182 nodes: id -> (x, y) | |
| 183 edges: id -> [node a, node b, [(x, y), ...] from a to b] | |
| 184 """ | |
| 185 | |
| 186 def __init__(self, skel, w): | |
| 187 self.w = w | |
| 188 pix = {i for i, v in enumerate(skel) if v} | |
| 189 offs = [dy * w + dx for dx, dy in NEIGHBOURS] | |
| 190 | |
| 191 def nbrs(i): | |
| 192 return [i + o for o in offs if i + o in pix] | |
| 193 | |
| 194 # line pixels have exactly two neighbours, all others belong to nodes | |
| 195 nodepix = {i for i in pix if len(nbrs(i)) != 2} | |
| 196 node_of = {} | |
| 197 self.nodes = {} | |
| 198 for i in nodepix: | |
| 199 if i in node_of: | |
| 200 continue | |
| 201 nid = len(self.nodes) | |
| 202 members = [] | |
| 203 queue = deque([i]) | |
| 204 node_of[i] = nid | |
| 205 while queue: | |
| 206 j = queue.popleft() | |
| 207 members.append(j) | |
| 208 for k in nbrs(j): | |
| 209 if k in nodepix and k not in node_of: | |
| 210 node_of[k] = nid | |
| 211 queue.append(k) | |
| 212 self.nodes[nid] = (sum(m % w for m in members) / len(members), | |
| 213 sum(m // w for m in members) / len(members)) | |
| 214 self.edges = {} | |
| 215 seen = set() | |
| 216 for i in nodepix: | |
| 217 for j in nbrs(i): | |
| 218 if j in nodepix or j in seen: | |
| 219 continue | |
| 220 chain = [i, j] | |
| 221 seen.add(j) | |
| 222 prev, cur = i, j | |
| 223 while True: | |
| 224 nxt = [k for k in nbrs(cur) if k != prev] | |
| 225 if not nxt: | |
| 226 break | |
| 227 k = nxt[0] | |
| 228 chain.append(k) | |
| 229 if k in nodepix: | |
| 230 break | |
| 231 seen.add(k) | |
| 232 prev, cur = cur, k | |
| 233 if chain[-1] not in nodepix: | |
| 234 continue | |
| 235 a, b = node_of[i], node_of[chain[-1]] | |
| 236 if a == b and len(chain) < 8: | |
| 237 continue | |
| 238 self.add_edge(a, b, [(c % w, c // w) for c in chain]) | |
| 239 | |
| 240 def add_edge(self, a, b, pts): | |
| 241 eid = max(self.edges, default=-1) + 1 | |
| 242 self.edges[eid] = [a, b, pts] | |
| 243 return eid | |
| 244 | |
| 245 def degree(self, n): | |
| 246 return sum((e[0] == n) + (e[1] == n) for e in self.edges.values()) | |
| 247 | |
| 248 def incident(self, n): | |
| 249 return [eid for eid, e in self.edges.items() if n in (e[0], e[1])] | |
| 250 | |
| 251 def nearest_end(self, x, y): | |
| 252 """return the node of degree 1 nearest to a point.""" | |
| 253 ends = [n for n in self.nodes if self.degree(n) == 1] | |
| 254 return min(ends, key=lambda n: math.dist(self.nodes[n], (x, y))) | |
| 255 | |
| 256 def prune(self, keep, min_len): | |
| 257 """drop dead ends shorter than min_len, except at nodes in keep.""" | |
| 258 changed = True | |
| 259 while changed: | |
| 260 changed = False | |
| 261 for n in list(self.nodes): | |
| 262 if n in keep or self.degree(n) != 1: | |
| 263 continue | |
| 264 eid = self.incident(n)[0] | |
| 265 if polyline_length(self.edges[eid][2]) < min_len: | |
| 266 del self.edges[eid] | |
| 267 del self.nodes[n] | |
| 268 changed = True | |
| 269 changed |= self.merge() | |
| 270 | |
| 271 def contract(self, keep, min_len): | |
| 272 """ | |
| 273 join junctions closer than min_len along an edge into one node, | |
| 274 except nodes in keep. thinning splits a wide crossing into several | |
| 275 nearby junctions; a loop attached to one of them could otherwise | |
| 276 not be walked without visiting a junction twice. | |
| 277 """ | |
| 278 changed = True | |
| 279 while changed: | |
| 280 changed = False | |
| 281 # shortest first, so a chain of nearby junctions joins around its middle | |
| 282 for eid, (a, b, pts) in sorted(self.edges.items(), | |
| 283 key=lambda e: polyline_length(e[1][2])): | |
| 284 if a == b or a in keep or b in keep or polyline_length(pts) >= min_len: | |
| 285 continue | |
| 286 del self.edges[eid] | |
| 287 # reattach the edges of b to a, extended by the joining pixels | |
| 288 for f in self.edges.values(): | |
| 289 if f[0] == b: | |
| 290 f[0], f[2] = a, pts[:-1] + f[2] | |
| 291 if f[1] == b: | |
| 292 f[1], f[2] = a, f[2] + pts[::-1][1:] | |
| 293 del self.nodes[b] | |
| 294 changed = True | |
| 295 break | |
| 296 | |
| 297 def merge(self): | |
| 298 """join the two edges at every node of degree 2. returns True on change.""" | |
| 299 changed = False | |
| 300 for n in list(self.nodes): | |
| 301 inc = self.incident(n) | |
| 302 if len(inc) != 2 or inc[0] == inc[1]: | |
| 303 continue | |
| 304 e1, e2 = (self.edges[i] for i in inc) | |
| 305 p1 = e1[2] if e1[1] == n else e1[2][::-1] | |
| 306 a = e1[0] if e1[1] == n else e1[1] | |
| 307 p2 = e2[2] if e2[0] == n else e2[2][::-1] | |
| 308 b = e2[1] if e2[0] == n else e2[0] | |
| 309 if a == n or b == n: | |
| 310 continue | |
| 311 del self.edges[inc[0]], self.edges[inc[1]] | |
| 312 del self.nodes[n] | |
| 313 self.add_edge(a, b, p1 + p2[1:]) | |
| 314 changed = True | |
| 315 return changed | |
| 316 | |
| 317 def paths(self, start, goal): | |
| 318 """ | |
| 319 list every route from start to goal that visits no node twice, as | |
| 320 a list of (points, key) pairs. a loop that leaves a node and comes | |
| 321 back to it (a self-loop edge) may be walked once, in either | |
| 322 direction; key names the edges taken without the loop directions, | |
| 323 so the two directions of the same route share a key. | |
| 324 """ | |
| 325 out = [] | |
| 326 | |
| 327 def walk(n, visited, used, pts, key): | |
| 328 if n == goal: | |
| 329 out.append((pts, tuple(key))) | |
| 330 return | |
| 331 for eid in self.incident(n): | |
| 332 a, b, epts = self.edges[eid] | |
| 333 if a == b: | |
| 334 if eid in used: | |
| 335 continue | |
| 336 for seg in (epts, epts[::-1]): | |
| 337 walk(n, visited, used | {eid}, pts + seg[1:], key + [("loop", eid)]) | |
| 338 continue | |
| 339 if a == n: | |
| 340 m, seg = b, epts | |
| 341 else: | |
| 342 m, seg = a, epts[::-1] | |
| 343 if m in visited: | |
| 344 continue | |
| 345 walk(m, visited | {m}, used, pts + seg[1:], key + [eid]) | |
| 346 | |
| 347 walk(start, {start}, frozenset(), [self.nodes[start]], []) | |
| 348 return out | |
| 349 | |
| 350 | |
| 351 def polyline_length(pts): | |
| 352 return sum(math.dist(pts[i], pts[i + 1]) for i in range(len(pts) - 1)) | |
| 353 | |
| 354 | |
| 355 def turning(pts): | |
| 356 """sum of direction changes along a polyline, in degrees.""" | |
| 357 total = 0.0 | |
| 358 for i in range(1, len(pts) - 1): | |
| 359 a1 = math.atan2(pts[i][1] - pts[i - 1][1], pts[i][0] - pts[i - 1][0]) | |
| 360 a2 = math.atan2(pts[i + 1][1] - pts[i][1], pts[i + 1][0] - pts[i][0]) | |
| 361 d = (a2 - a1 + math.pi) % (2 * math.pi) - math.pi | |
| 362 total += abs(d) | |
| 363 return math.degrees(total) | |
| 364 | |
| 365 | |
| 366 def resample(pts, step): | |
| 367 """return points spaced step apart along the polyline, ends kept.""" | |
| 368 out = [pts[0]] | |
| 369 carry = 0.0 | |
| 370 for i in range(len(pts) - 1): | |
| 371 (x0, y0), (x1, y1) = pts[i], pts[i + 1] | |
| 372 seg = math.dist(pts[i], pts[i + 1]) | |
| 373 d = step - carry | |
| 374 while d <= seg: | |
| 375 t = d / seg | |
| 376 out.append((x0 + (x1 - x0) * t, y0 + (y1 - y0) * t)) | |
| 377 d += step | |
| 378 carry = seg - (d - step) | |
| 379 if math.dist(out[-1], pts[-1]) > step * 0.25: | |
| 380 out.append(pts[-1]) | |
| 381 else: | |
| 382 out[-1] = pts[-1] | |
| 383 return out | |
| 384 | |
| 385 | |
| 386 def smooth(pts, half): | |
| 387 """moving average over 2 * half + 1 points; the window shrinks at the ends.""" | |
| 388 n = len(pts) | |
| 389 out = [] | |
| 390 for i in range(n): | |
| 391 k = min(half, i, n - 1 - i) | |
| 392 xs = pts[i - k:i + k + 1] | |
| 393 out.append((sum(p[0] for p in xs) / len(xs), sum(p[1] for p in xs) / len(xs))) | |
| 394 return out | |
| 395 | |
| 396 | |
| 397 def simplify(pts, tol): | |
| 398 """ramer-douglas-peucker: drop points closer than tol to the line.""" | |
| 399 if len(pts) < 3: | |
| 400 return list(pts) | |
| 401 (x0, y0), (x1, y1) = pts[0], pts[-1] | |
| 402 dx, dy = x1 - x0, y1 - y0 | |
| 403 norm = math.hypot(dx, dy) or 1.0 | |
| 404 best, idx = 0.0, 0 | |
| 405 for i in range(1, len(pts) - 1): | |
| 406 d = abs(dy * (pts[i][0] - x0) - dx * (pts[i][1] - y0)) / norm | |
| 407 if d > best: | |
| 408 best, idx = d, i | |
| 409 if best <= tol: | |
| 410 return [pts[0], pts[-1]] | |
| 411 return simplify(pts[:idx + 1], tol)[:-1] + simplify(pts[idx:], tol) | |
| 412 | |
| 413 | |
| 414 def path_width(mask, skel_len): | |
| 415 """average path width: path area divided by centre line length.""" | |
| 416 return mask.count(PATH) / skel_len if skel_len else 0.0 | |
| 417 | |
| 418 | |
| 419 def extract_routes(mask, smooth_half, tol): | |
| 420 """ | |
| 421 find the routes of a mask. returns a dict with the graph, the | |
| 422 entrance and exit blobs, the measured path width and the routes as | |
| 423 point lists, entrance to exit, smoothed and simplified. | |
| 424 """ | |
| 425 w, h = mask.w, mask.h | |
| 426 shape = bytearray(1 if c != FREE else 0 for c in mask.cls) | |
| 427 # keep a free border so the thinning never reads past the image | |
| 428 for x in range(w): | |
| 429 shape[x] = shape[(h - 1) * w + x] = 0 | |
| 430 for y in range(h): | |
| 431 shape[y * w] = shape[y * w + w - 1] = 0 | |
| 432 skel = thin(shape, w, h) | |
| 433 graph = Graph(skel, w) | |
| 434 | |
| 435 entrances = mask.blobs(ENTRANCE) | |
| 436 exits = mask.blobs(EXIT) | |
| 437 # specks of colour from the soft edges are not entrances or exits | |
| 438 entrances = [b for b in entrances if b[3] >= 50] | |
| 439 exits = [b for b in exits if b[3] >= 50] | |
| 440 width = path_width(mask, sum(polyline_length(e[2]) for e in graph.edges.values())) | |
| 441 terminals = [graph.nearest_end(b[0], b[1]) for b in entrances + exits] | |
| 442 graph.prune(set(terminals), 0.8 * width) | |
| 443 graph.contract(set(terminals), 0.75 * width) | |
| 444 graph.merge() | |
| 445 starts = terminals[:len(entrances)] | |
| 446 goals = terminals[len(entrances):] | |
| 447 | |
| 448 routes = [] | |
| 449 for s in starts: | |
| 450 for g in goals: | |
| 451 # of the two directions around a loop, keep the one that turns less | |
| 452 best = {} | |
| 453 for raw, key in graph.paths(s, g): | |
| 454 pts = resample(raw, 1.0) | |
| 455 pts = simplify(smooth(smooth(pts, smooth_half), smooth_half), tol) | |
| 456 if key not in best or turning(pts) < turning(best[key]): | |
| 457 best[key] = pts | |
| 458 routes.extend(best.values()) | |
| 459 return { | |
| 460 "graph": graph, | |
| 461 "entrances": entrances, | |
| 462 "exits": exits, | |
| 463 "width": width, | |
| 464 "routes": routes, | |
| 465 } |
