VEHwang's picture
Upload CoCogni4D-Bench (questions, media, scripts, render records, code) (part 4)
9d57416 verified
Raw History Blame Contribute Delete
2.35 kB
"""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