File size: 6,216 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
"""Prepare bound static collision evidence from a fresh saved-scene mesh export."""
import argparse
import gzip
import hashlib
import json
import math
from pathlib import Path
import sys

sys.path.insert(0, str(Path(__file__).resolve().parent))
from floor_support import physical_floor_support, audit_route_floor
from rug_route import analyze_rugs
from collision_usd import build as build_usd


def digest(path):
    value = hashlib.sha256()
    with Path(path).open('rb') as stream:
        for chunk in iter(lambda: stream.read(1024 * 1024), b''):
            value.update(chunk)
    return value.hexdigest()


def audit_floor_sweep(points, support, base_radius_m=.3):
    from shapely.geometry import LineString
    if not math.isfinite(base_radius_m) or base_radius_m < .3:
        raise ValueError('Full base radius must be at least .3 m')
    # Square joins and round caps cover every turning point and both endpoints.
    # GEOS round caps are inscribed polygons; enlarge by their apothem ratio so
    # the audited shape conservatively includes the true circular base sweep.
    sweep = LineString(points).buffer(base_radius_m / math.cos(math.pi / 256), resolution=64, join_style=2)
    missing = sweep.difference(support.buffer(1e-6, join_style=2))
    return dict(schema='rhg.actual-floor-full-radius-sweep.v1', base_radius_m=base_radius_m,
                coordinate_epsilon_m=1e-6, unsupported_sweep_area_m2=missing.area,
                passed=missing.is_empty, whole_task_acceptance=False)


def write(path, data):
    path.write_text(json.dumps(data, indent=2, allow_nan=False) + '\n')


def prepare(scene, task_path, out):
    scene, task_path, out = Path(scene).resolve(), Path(task_path).resolve(), Path(out).resolve()
    if out.exists() and (not out.is_dir() or set(p.name for p in out.iterdir()) != {'physical_meshes.json.gz'}):
        raise ValueError('Output must be new or contain only fresh physical_meshes.json.gz')
    if out == scene or scene in out.parents:
        raise ValueError('Output cannot be inside source scene')
    mesh_path = out / 'physical_meshes.json.gz'
    runtime_path = scene / 'composition_manifest.runtime.json'
    runtime = json.loads(runtime_path.read_text())
    blend = scene / (runtime['scene_id'] + '.blend')
    with gzip.open(mesh_path, 'rt') as stream:
        payload = json.load(stream)
    if Path(payload['source_blend']).resolve() != blend or payload['source_blend_sha256'] != digest(blend):
        raise ValueError('Source blend differs from exported meshes')
    if payload.get('source_runtime_sha256') != digest(runtime_path):
        raise ValueError('Source runtime differs from exported meshes')
    if payload.get('geometry_modified') is not False or payload.get('blend_saved') is not False:
        raise ValueError('Export must be read-only exact saved geometry')
    paths = list(scene.rglob('*')) + [task_path, mesh_path]
    before = {str(p): digest(p) for p in paths if p.is_file()}
    task = json.loads(task_path.read_text())
    points = task['route_waypoints_xy_m']
    if len(points) < 2 or any(len(p) != 2 or any(not math.isfinite(v) for v in p) for p in points):
        raise ValueError('Route must have finite XY waypoints')
    support, floor_rows = physical_floor_support(payload)
    center = audit_route_floor(points, support)
    sweep = audit_floor_sweep(points, support)
    bindings = dict(source_blend_sha256=digest(blend), task_sha256=digest(task_path),
                    source_meshes_sha256=digest(mesh_path), runtime_sha256=digest(runtime_path))
    floor = dict(schema='rhg.actual-floor-support-audit.v1', actual_floor_meshes=floor_rows,
                 dense_and_continuous_route_audit=center, passed=center['continuous_centerline_supported'],
                 whole_task_acceptance=False, **bindings)
    write(out / 'floor_support_validation.json', floor)
    write(out / 'floor_sweep_validation.json', dict(sweep, **bindings))
    if not floor['passed'] or not sweep['passed']:
        write(out / 'geometry_report.json', dict(passed=False, whole_task_acceptance=False,
              failure='Actual full-radius physical floor support failed', **bindings))
        raise ValueError('Actual full-radius physical floor support failed')
    manifest = build_usd(mesh_path, out / 'collision_usd')
    bindings['collision_usd_sha256'] = manifest['usd_sha256']
    contract = analyze_rugs(payload, task)
    unchanged = {p: digest(p) == sha for p, sha in before.items()}
    if not all(unchanged.values()) or set(str(p) for p in scene.rglob('*') if p.is_file()) != set(p for p in before if Path(p).is_relative_to(scene)):
        raise ValueError('Source inputs changed during preparation')
    contract.update(schema='rhg.saved-mesh-rug-route-contract.v1', passed=True,
                    route_waypoints_xy_m=points, all_source_inputs_unchanged=True,
                    source_hash_checks=unchanged, source_bindings={'verified': True},
                    whole_task_acceptance=False, navigation_or_manipulation_accepted=False,
                    passed_scope='Contract input integrity and requirement derivation only', **bindings)
    write(out / 'rug_route_contract.json', contract)
    report = dict(schema='rhg.sim2real-geometry.v1', passed=True, all_source_inputs_unchanged=True,
                  evidence_sha256={name: digest(out / name) for name in (
                      'floor_support_validation.json', 'floor_sweep_validation.json',
                      'collision_usd/manifest.json', 'rug_route_contract.json')},
                  input_sha256=before, source_hash_checks=unchanged, whole_task_acceptance=False,
                  material_acceptance=False, dynamics_acceptance=False,
                  scope='static collision/navigation geometry only', **bindings)
    write(out / 'geometry_report.json', report)
    return report


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--scene', required=True, type=Path)
    parser.add_argument('--task', required=True, type=Path)
    parser.add_argument('--out', required=True, type=Path)
    args = parser.parse_args()
    print(json.dumps(prepare(args.scene, args.task, args.out)))