comparison tools/masks.py @ 9:53f015966118

map, path, tower placement adjustments
author ark
date 2026-10-19 15:55 +0200
parents 5492efd60e2c
children
comparison
equal deleted inserted replaced
8:2c4fed8baed9 9:53f015966118
1 """ 1 """
2 mask steps of the build: pixel classes, placement grid and routes. 2 mask steps of the build: pixel classes, placement grid and routes.
3 3
4 a mask is a map-sized image with a red path, blue entrances and green exits 4 a mask is a map-sized image with a red path centre line, blue entrances and
5 on a transparent background. pixels are indexed as y * width + x throughout. 5 green exits on a transparent background. edges are hard: every pixel is
6 either fully transparent or opaque pure red, blue or green. pixels are
7 indexed as y * width + x throughout.
6 """ 8 """
7 9
8 import math 10 import math
9 from collections import deque 11 from collections import deque
10 12
11 from PIL import Image, ImageDraw 13 from PIL import Image, ImageChops, ImageDraw
12 14
13 FREE, PATH, ENTRANCE, EXIT = 0, 1, 2, 3 15 FREE, PATH, ENTRANCE, EXIT = 0, 1, 2, 3
16 # rgba bytes of the opaque mask colours
17 COLOURS = {b"\xff\x00\x00\xff": PATH, b"\x00\x00\xff\xff": ENTRANCE,
18 b"\x00\xff\x00\xff": EXIT}
14 19
15 # 8-neighbour offsets in the order n, ne, e, se, s, sw, w, nw 20 # 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)) 21 NEIGHBOURS = ((0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1))
17 22
18 23
19 class Mask: 24 class Mask:
20 """pixel classes of one map mask.""" 25 """
26 pixel classes of one map mask. raises ValueError when a pixel is
27 neither transparent nor one of the mask colours.
28 """
21 29
22 def __init__(self, path): 30 def __init__(self, path):
23 im = Image.open(path).convert("RGBA") 31 im = Image.open(path).convert("RGBA")
24 self.w, self.h = im.size 32 self.w, self.h = im.size
25 data = im.tobytes() 33 data = im.tobytes()
26 cls = bytearray(self.w * self.h) 34 cls = bytearray(self.w * self.h)
27 # the edges are soft: a pixel counts when it is at least half covered, 35 bad = []
28 # and belongs to its strongest colour channel
29 for i in range(self.w * self.h): 36 for i in range(self.w * self.h):
30 j = i * 4 37 j = i * 4
31 if data[j + 3] >= 128: 38 if data[j + 3] == 0:
32 r, g, b = data[j], data[j + 1], data[j + 2] 39 continue
33 if r >= g and r >= b: 40 c = COLOURS.get(data[j:j + 4])
34 cls[i] = PATH 41 if c is None:
35 elif b >= g: 42 bad.append(i)
36 cls[i] = ENTRANCE 43 else:
37 else: 44 cls[i] = c
38 cls[i] = EXIT 45 if bad:
46 raise ValueError(f"{path}: {len(bad)} pixels are not transparent, red, blue or"
47 f" green, the first at {bad[0] % self.w}, {bad[0] // self.w}")
39 self.cls = cls 48 self.cls = cls
40 49
41 def count(self, kind): 50 def count(self, kind):
42 return self.cls.count(kind) 51 return self.cls.count(kind)
43 52
95 if edge: 104 if edge:
96 draw.ellipse((x - radius, y - radius, x + radius, y + radius), fill=255) 105 draw.ellipse((x - radius, y - radius, x + radius, y + radius), fill=255)
97 return im 106 return im
98 107
99 108
100 def placement_grid(mask, p): 109 def discs(w, h, points, radius):
101 """ 110 """return an L image of size w x h, 255 within radius of any of the points."""
102 return (cols, rows, grid string) for placement table p. a cell is legal 111 im = Image.new("L", (w, h), 0)
103 when a tower footprint centred on it does not overlap the path, 112 draw = ImageDraw.Draw(im)
104 entrances or exits, comes within max_gap of the path, and keeps 113 for x, y in points:
105 edge_distance from the map edge. the string has one '1' or '0' per 114 draw.ellipse((x - radius, y - radius, x + radius, y + radius), fill=255)
106 cell, row by row. 115 return im
116
117
118 def placement_grid(mask, p, centre, half_width, spaces):
119 """
120 return (cols, rows, grid string) for placement table p. the road is
121 taken as half_width either side of the centre line, given as a list of
122 pixels. spaces is a list of (points, space). a cell is legal when a
123 tower footprint centred on it does not overlap the road, entrances or
124 exits, comes within max_gap of the road, keeps each space from its
125 points and keeps edge_distance from the map edge. the string has one
126 '1' or '0' per cell, row by row.
107 """ 127 """
108 cell = p["grid_cell"] 128 cell = p["grid_cell"]
109 r = p["footprint_radius"] 129 r = p["footprint_radius"]
110 blocked = mask.grown((PATH, ENTRANCE, EXIT), r).tobytes() 130 w, h = mask.w, mask.h
111 near = mask.grown((PATH,), r + p["max_gap"]).tobytes() 131 # the centre line inside entrance and exit areas does not count as road
132 road = [(x, y) for x, y in centre if mask.cls[y * w + x] == PATH]
133 blocked = ImageChops.lighter(mask.grown((ENTRANCE, EXIT), r),
134 discs(w, h, road, r + half_width))
135 for points, space in spaces:
136 blocked = ImageChops.lighter(blocked, discs(w, h, points, r + space))
137 blocked = blocked.tobytes()
138 near = discs(w, h, road, r + half_width + p["max_gap"]).tobytes()
112 edge = p["edge_distance"] 139 edge = p["edge_distance"]
113 w, h = mask.w, mask.h
114 cols, rows = w // cell, h // cell 140 cols, rows = w // cell, h // cell
115 out = [] 141 out = []
116 for cy in range(rows): 142 for cy in range(rows):
117 y = cy * cell + cell // 2 143 y = cy * cell + cell // 2
118 for cx in range(cols): 144 for cx in range(cols):
409 if best <= tol: 435 if best <= tol:
410 return [pts[0], pts[-1]] 436 return [pts[0], pts[-1]]
411 return simplify(pts[:idx + 1], tol)[:-1] + simplify(pts[idx:], tol) 437 return simplify(pts[:idx + 1], tol)[:-1] + simplify(pts[idx:], tol)
412 438
413 439
414 def path_width(mask, skel_len): 440 def line_width(mask, skel_len):
415 """average path width: path area divided by centre line length.""" 441 """average width of the drawn centre line: its area divided by its length."""
416 return mask.count(PATH) / skel_len if skel_len else 0.0 442 return mask.count(PATH) / skel_len if skel_len else 0.0
417 443
418 444
445 def leave_point(graph, mask, n, kind):
446 """
447 return the first centre line pixel outside the area of class kind,
448 walking from the line end n.
449 """
450 a, b, pts = graph.edges[graph.incident(n)[0]]
451 if a != n:
452 pts = pts[::-1]
453 for x, y in pts:
454 if mask.cls[y * mask.w + x] != kind:
455 return (x, y)
456 return pts[-1]
457
458
419 def extract_routes(mask, smooth_half, tol): 459 def extract_routes(mask, smooth_half, tol):
420 """ 460 """
421 find the routes of a mask. returns a dict with the graph, the 461 find the routes of a mask. returns a dict with the graph, the entrance
422 entrance and exit blobs, the measured path width and the routes as 462 and exit blobs, the measured line width, the centre line pixels, the
423 point lists, entrance to exit, smoothed and simplified. 463 spawn points where the centre line leaves each entrance, the exit
464 points where it enters each exit, and the routes
465 as point lists, entrance to exit, smoothed and simplified.
424 """ 466 """
425 w, h = mask.w, mask.h 467 w, h = mask.w, mask.h
426 shape = bytearray(1 if c != FREE else 0 for c in mask.cls) 468 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 469 # keep a free border so the thinning never reads past the image
428 for x in range(w): 470 for x in range(w):
432 skel = thin(shape, w, h) 474 skel = thin(shape, w, h)
433 graph = Graph(skel, w) 475 graph = Graph(skel, w)
434 476
435 entrances = mask.blobs(ENTRANCE) 477 entrances = mask.blobs(ENTRANCE)
436 exits = mask.blobs(EXIT) 478 exits = mask.blobs(EXIT)
437 # specks of colour from the soft edges are not entrances or exits 479 width = line_width(mask, sum(polyline_length(e[2]) for e in graph.edges.values()))
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] 480 terminals = [graph.nearest_end(b[0], b[1]) for b in entrances + exits]
442 graph.prune(set(terminals), 0.8 * width) 481 graph.prune(set(terminals), 0.8 * width)
443 graph.contract(set(terminals), 0.75 * width) 482 graph.contract(set(terminals), 0.75 * width)
444 graph.merge() 483 graph.merge()
445 starts = terminals[:len(entrances)] 484 starts = terminals[:len(entrances)]
459 return { 498 return {
460 "graph": graph, 499 "graph": graph,
461 "entrances": entrances, 500 "entrances": entrances,
462 "exits": exits, 501 "exits": exits,
463 "width": width, 502 "width": width,
503 "centre": [p for e in graph.edges.values() for p in e[2]],
504 "spawns": [leave_point(graph, mask, s, ENTRANCE) for s in starts],
505 "exit_points": [leave_point(graph, mask, g, EXIT) for g in goals],
464 "routes": routes, 506 "routes": routes,
465 } 507 }