#!/usr/bin/env python3
"""Check that no triangle spans a forbidden (cut-out) region.

Usage: check_gap.py file.stl X0 X1 Y0 Y1
Fails if any triangle has an interior sample point strictly inside the
open rectangle (X0,X1)x(Y0,Y1) in the XY plane -- i.e. if decimation
bridged a hole. Vertices on the hole boundary are fine (margin 0.05).
"""
import struct
import sys


def main():
    path, x0, x1, y0, y1 = sys.argv[1], *map(float, sys.argv[2:6])
    margin = 0.05
    fx0, fx1, fy0, fy1 = x0 + margin, x1 - margin, y0 + margin, y1 - margin

    data = open(path, "rb").read()
    n = struct.unpack_from("<I", data, 80)[0]
    bad = 0
    for i in range(n):
        off = 84 + 50 * i + 12
        v = struct.unpack_from("<9f", data, off)
        # barycentric samples on a small grid, interior only
        for a in range(1, 5):
            for b in range(1, 5 - a):
                c = 10 - a - b
                px = (a * v[0] + b * v[3] + c * v[6]) / 10.0
                py = (a * v[1] + b * v[4] + c * v[7]) / 10.0
                if fx0 < px < fx1 and fy0 < py < fy1:
                    bad += 1
                    break
    if bad:
        print(f"GAP-CHECK FAIL: {bad} of {n} triangles cross the "
              f"forbidden region [{x0},{x1}]x[{y0},{y1}]")
        return 1
    print(f"gap-check ok: no triangle crosses "
          f"[{x0},{x1}]x[{y0},{y1}] ({n} facets)")
    return 0


if __name__ == "__main__":
    sys.exit(main())
