mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 08:58:36 +00:00
bvh_geometry_check: catch NaN leaf bounds, infinite-bound override tolerance blow-up, invalid --geom, and strict JSON (BVH-GEOMETRY-CHECK-NAN-INF-GEOM)
This commit is contained in:
@ -5,11 +5,14 @@ fails the check that should catch it. No game data is read.
|
||||
"""
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, os.path.join(ROOT, "tools"))
|
||||
@ -108,6 +111,97 @@ class TestChecks(unittest.TestCase):
|
||||
self.assertEqual(rc, 2)
|
||||
self.assertIn("must not overwrite", err.getvalue())
|
||||
|
||||
def test_nan_leaf_bounds_fails_consistency_even_when_other_leaf_covers_bounds(self):
|
||||
# Leaf 0 covers BOUNDS; leaf 1 has all-NaN vertices. Previously NaN comparison
|
||||
# returned False and min(finite, NaN) kept finite, falsely reporting consistent=True.
|
||||
vb = VB + struct.pack("<9f", *([math.nan] * 9))
|
||||
ib = struct.pack("<6I", 0, 1, 2, 4, 5, 6)
|
||||
geom = R.Geometry(vb, indices=ib)
|
||||
leaves = [(0, 0x01, 0, None, 0x09), (0, 0x01, 1, None, 0x09)]
|
||||
src, _, _ = build(leaves, bounds=(0, 0, 0, 1, 1, 0))
|
||||
r = C.check(src, [geom])
|
||||
self.assertEqual(r["leaves_outside"], 1)
|
||||
self.assertTrue(math.isinf(r["bounds_gap"]))
|
||||
self.assertFalse(r["consistent"])
|
||||
|
||||
def test_nonfinite_scene_bounds_fails_consistency(self):
|
||||
src, _, _ = build(LEAVES, bounds=(0.0, 0.0, 0.0, math.inf, 1.0, 0.0))
|
||||
r = C.check(src, [TRUE])
|
||||
self.assertEqual(r["leaves_outside"], 1)
|
||||
self.assertTrue(math.isinf(r["bounds_gap"]))
|
||||
self.assertFalse(r["consistent"])
|
||||
|
||||
def test_infinite_child_bound_does_not_bypass_override_range_check(self):
|
||||
# If child min_x is -inf and max_x is 10.0, a min_x override of 1000.0 (> max_x)
|
||||
# must be rejected rather than passing because tol blew up to +inf.
|
||||
src, _, _ = build(
|
||||
[(0, 0x01, 0, None, 0x09), (0, 0x01, 1, None, 0x09)],
|
||||
overrides={0: 1000.0},
|
||||
bounds=BOUNDS,
|
||||
)
|
||||
hdr = R.Header(src, 0)
|
||||
with mock.patch.object(C.R, "node_bounds", return_value=[-math.inf, 0.0, 0.0, 10.0, 1.0, 0.0]):
|
||||
good, bad = C.check_overrides(src, hdr, bytearray(hdr.total_bytes))
|
||||
self.assertEqual((good, bad), (0, 1))
|
||||
|
||||
src_ok, _, _ = build(
|
||||
[(0, 0x01, 0, None, 0x09), (0, 0x01, 1, None, 0x09)],
|
||||
overrides={0: 5.0},
|
||||
bounds=BOUNDS,
|
||||
)
|
||||
hdr_ok = R.Header(src_ok, 0)
|
||||
with mock.patch.object(C.R, "node_bounds", return_value=[-math.inf, 0.0, 0.0, 10.0, 1.0, 0.0]):
|
||||
good, bad = C.check_overrides(src_ok, hdr_ok, bytearray(hdr_ok.total_bytes))
|
||||
self.assertEqual((good, bad), (1, 0))
|
||||
|
||||
def test_invalid_geom_spec_and_json_directory_rejected(self):
|
||||
src, _, _ = build(LEAVES, bounds=BOUNDS)
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
in_path = os.path.join(d, "in.bin")
|
||||
vb_path = os.path.join(d, "vb.bin")
|
||||
ib_path = os.path.join(d, "ib.bin")
|
||||
out_dir = os.path.join(d, "out_dir")
|
||||
os.makedirs(out_dir)
|
||||
for p, data in ((in_path, src), (vb_path, VB), (ib_path, IB)):
|
||||
with open(p, "wb") as f:
|
||||
f.write(data)
|
||||
for bad_spec in (f"{vb_path},{ib_path},extra", f",{ib_path}", ""):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as err:
|
||||
rc = C.main([in_path, "--geom", bad_spec])
|
||||
self.assertEqual(rc, 2, bad_spec)
|
||||
self.assertIn("--geom", err.getvalue())
|
||||
with contextlib.redirect_stderr(io.StringIO()) as err:
|
||||
rc = C.main([in_path, "--geom", f"{vb_path},{ib_path}", "--json", out_dir])
|
||||
self.assertEqual(rc, 2)
|
||||
self.assertIn("directory", err.getvalue())
|
||||
|
||||
def test_json_report_strict_rfc8259_with_nonfinite_gap(self):
|
||||
vb = VB + struct.pack("<9f", *([math.nan] * 9))
|
||||
ib = struct.pack("<6I", 0, 1, 2, 4, 5, 6)
|
||||
leaves = [(0, 0x01, 0, None, 0x09), (0, 0x01, 1, None, 0x09)]
|
||||
src, _, _ = build(leaves, bounds=BOUNDS)
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
in_path = os.path.join(d, "in.bin")
|
||||
vb_path = os.path.join(d, "vb.bin")
|
||||
ib_path = os.path.join(d, "ib.bin")
|
||||
rep_path = os.path.join(d, "report.json")
|
||||
for p, data in ((in_path, src), (vb_path, vb), (ib_path, ib)):
|
||||
with open(p, "wb") as f:
|
||||
f.write(data)
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
rc = C.main([in_path, "--geom", f"{vb_path},{ib_path}", "--json", rep_path])
|
||||
self.assertEqual(rc, 1)
|
||||
with open(rep_path, "r", encoding="utf-8") as f:
|
||||
raw = f.read()
|
||||
|
||||
def _reject(tok):
|
||||
raise ValueError(f"non-standard JSON token {tok}")
|
||||
|
||||
parsed = json.loads(raw, parse_constant=_reject)
|
||||
self.assertFalse(parsed["consistent"])
|
||||
self.assertEqual(parsed["leaves_outside"], 1)
|
||||
self.assertIsNone(parsed["bounds_gap"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@ -48,17 +48,27 @@ def check_bounds(hdr, out):
|
||||
frame = R.LeafFrame(hdr)
|
||||
lo, hi = hdr.bounds[:3], hdr.bounds[3:]
|
||||
corners = [frame.apply((x, y, z)) for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])]
|
||||
if any(not math.isfinite(coord) for corner in corners for coord in corner):
|
||||
return hdr.num_elements, math.inf if hdr.num_elements else 0.0
|
||||
box = [min(c[a] for c in corners) for a in range(3)] + [max(c[a] for c in corners) for a in range(3)]
|
||||
extent = max(max(box[a + 3] - box[a] for a in range(3)), 1e-30)
|
||||
union = [math.inf] * 3 + [-math.inf] * 3
|
||||
outside = 0
|
||||
has_nonfinite = False
|
||||
for off in leaf_offsets(hdr):
|
||||
b = R.node_bounds(out, (off >> 6) << 3 | R.TRI0)
|
||||
if any(not math.isfinite(v) for v in b):
|
||||
outside += 1
|
||||
has_nonfinite = True
|
||||
continue
|
||||
if max([box[a] - b[a] for a in range(3)] + [b[a] - box[a] for a in range(3, 6)]) > OUTSIDE_TOLERANCE * extent:
|
||||
outside += 1
|
||||
for a in range(3):
|
||||
union[a], union[a + 3] = min(union[a], b[a]), max(union[a + 3], b[a + 3])
|
||||
gap = max(abs(union[a] - box[a]) for a in range(6)) / extent if hdr.num_elements else 0.0
|
||||
if has_nonfinite:
|
||||
gap = math.inf
|
||||
else:
|
||||
gap = max(abs(union[a] - box[a]) for a in range(6)) / extent if hdr.num_elements else 0.0
|
||||
return outside, gap
|
||||
|
||||
|
||||
@ -89,15 +99,23 @@ def stored_overrides(src, hdr):
|
||||
yield children[bit // 6], bit % 6, value
|
||||
|
||||
|
||||
def _ulp_tol(value, ref):
|
||||
if math.isfinite(value) and math.isfinite(ref):
|
||||
return OVERRIDE_ULPS * 2.0 ** -23 * max(abs(value), abs(ref), 1e-30)
|
||||
return 0.0
|
||||
|
||||
|
||||
def check_overrides(src, hdr, out):
|
||||
"""(consistent, inconsistent) stored override components."""
|
||||
good = bad = 0
|
||||
for child, comp, value in stored_overrides(src, hdr):
|
||||
b = R.node_bounds(out, child)
|
||||
lo, hi = b[comp % 3], b[comp % 3 + 3]
|
||||
tol = OVERRIDE_ULPS * 2.0 ** -23 * max(abs(value), abs(b[comp]), 1e-30) if math.isfinite(value) else 0.0
|
||||
tighter = value >= b[comp] - tol if comp < 3 else value <= b[comp] + tol
|
||||
if tighter and lo - tol <= value <= hi + tol:
|
||||
tighter_tol = _ulp_tol(value, b[comp])
|
||||
lo_tol = _ulp_tol(value, lo)
|
||||
hi_tol = _ulp_tol(value, hi)
|
||||
tighter = value >= b[comp] - tighter_tol if comp < 3 else value <= b[comp] + tighter_tol
|
||||
if tighter and lo - lo_tol <= value <= hi + hi_tol:
|
||||
good += 1
|
||||
else:
|
||||
bad += 1
|
||||
@ -162,8 +180,14 @@ def main(argv=None):
|
||||
geom_paths = []
|
||||
for spec in a.geom:
|
||||
parts = spec.split(",")
|
||||
if len(parts) > 2 or not parts[0]:
|
||||
print("error: --geom expects VB[,IB]: %r" % spec, file=sys.stderr)
|
||||
return 2
|
||||
geom_paths.append((parts[0], parts[1] if len(parts) > 1 else ""))
|
||||
if a.json:
|
||||
if os.path.isdir(a.json):
|
||||
print("error: --json is a directory: %s" % a.json, file=sys.stderr)
|
||||
return 2
|
||||
if same_report_path(a.json, a.dehydrated):
|
||||
print("error: --json %s must not overwrite the dehydrated input" % a.json, file=sys.stderr)
|
||||
return 2
|
||||
@ -195,10 +219,14 @@ def main(argv=None):
|
||||
print("internal box area: %.6g" % report["internal_area"])
|
||||
print("consistent" if report["consistent"] else "NOT consistent")
|
||||
if a.json:
|
||||
json_report = {
|
||||
k: (None if isinstance(v, float) and not math.isfinite(v) else v)
|
||||
for k, v in report.items()
|
||||
}
|
||||
try:
|
||||
_publish(a.json, lambda f: json.dump(report, f, indent=1), "\n")
|
||||
except OSError as e:
|
||||
print("error: cannot write %s: %s" % (a.json, e.strerror or e), file=sys.stderr)
|
||||
_publish(a.json, lambda f: json.dump(json_report, f, indent=1, allow_nan=False), "\n")
|
||||
except (OSError, ValueError) as e:
|
||||
print("error: cannot write %s: %s" % (a.json, getattr(e, "strerror", None) or e), file=sys.stderr)
|
||||
return 2
|
||||
return 0 if report["consistent"] else 1
|
||||
|
||||
|
||||
Reference in New Issue
Block a user