File size: 2,346 Bytes
5afd2f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
"""Capability-only geometry and PNG compilation, independent of a script."""


def contours(mask, origin, cell):
    """Exact cell-edge loops, including holes. Remove collinear vertices.

    All directed edges keep occupied cells on the same side. At diagonal
    contacts choose the rightmost continuation to keep individual loops.
    The SVG consumer uses evenodd fill, so holes retain their meaning.
    """
    import numpy as np
    a = np.pad(mask.astype(bool), 1)
    edges = {}
    def add(start, end):
        edges.setdefault(start, []).append(end)
    for i, j in zip(*np.nonzero(mask & ~a[:-2, 1:-1])):
        add((int(j), int(i)), (int(j + 1), int(i)))
    for i, j in zip(*np.nonzero(mask & ~a[1:-1, 2:])):
        add((int(j + 1), int(i)), (int(j + 1), int(i + 1)))
    for i, j in zip(*np.nonzero(mask & ~a[2:, 1:-1])):
        add((int(j + 1), int(i + 1)), (int(j), int(i + 1)))
    for i, j in zip(*np.nonzero(mask & ~a[1:-1, :-2])):
        add((int(j), int(i + 1)), (int(j), int(i)))
    loops = []
    while edges:
        start = next(iter(edges))
        point, previous, points = start, None, []
        while True:
            points.append(point)
            choices = edges[point]
            if previous is None or len(choices) == 1:
                following = choices[0]
            else:
                dx, dy = point[0] - previous[0], point[1] - previous[1]
                def rank(q):
                    ex, ey = q[0] - point[0], q[1] - point[1]
                    cross, dot = dx * ey - dy * ex, dx * ex + dy * ey
                    return {1: 0, 0: 1, -1: 2}.get(cross, 3) if dot >= 0 else 3
                following = min(choices, key=rank)
            choices.remove(following)
            if not choices:
                del edges[point]
            previous, point = point, following
            if point == start:
                break
        reduced = []
        for k, p in enumerate(points):
            before, after = points[k - 1], points[(k + 1) % len(points)]
            if (p[0] - before[0]) * (after[1] - p[1]) != (p[1] - before[1]) * (after[0] - p[0]):
                reduced.append([float(round(origin[0] + p[0] * cell, 5)),
                                float(round(origin[1] + p[1] * cell, 5))])
        if len(reduced) >= 3:
            loops.append(reduced)
    return loops