File size: 16,310 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
"""Export and measure an existing saved Blender scene; never run generation.

Example measurement_refresh.command argv (use absolute interpreter/script paths):
  python measure_saved_scene.py --manifest {manifest} --scene {scene}
    --output {output} --source-root {source_root} --requirements {requirements}
    --blender /path/to/blender

Requires NumPy and Shapely >=2 in this Python runtime. Blender only exports
meshes using source_root/packages/sim2real/geometry/export_meshes.py. The saved
scene is opened read-only via a symlink in a separate export input directory.
Task regions are unions of actual coplanar top triangles, without seam filling,
buffers, hulls or bounding-box substitution. Existing task anchors stay fixed.
Approach widths have no native measurement contract here and remain pending.
Prior rectangles are certified inside measured local-frame triangle unions;
child occupancy bounds conservatively enclose actual projected mesh vertices.
All results concern static geometry only, never physics or task acceptance.
"""
from __future__ import annotations

import argparse
import copy
import gzip
import json
import math
from pathlib import Path
import shutil
import sys
import time

if __package__ and '.' in __package__:
    from ..measurement_refresh import file_sha256, load_json
    from ..process_control import execute_command
else:
    sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
    from measurement_refresh import file_sha256, load_json
    from process_control import execute_command


def _geometry():
    import numpy as np
    import shapely
    from shapely.geometry import Polygon, box, mapping, shape
    from shapely.ops import unary_union
    if int(shapely.__version__.split('.')[0]) < 2:
        raise RuntimeError('Saved-scene measurement requires Shapely >=2')
    return np, Polygon, box, mapping, shape, unary_union


def measure_triangle_surface(triangles):
    """Measure the highest horizontal triangle plane, retaining every hole."""
    np, Polygon, _, mapping, _, unary_union = _geometry()
    values = np.asarray(triangles, dtype=np.float64)
    if (values.ndim != 3 or values.shape[1:] != (3, 3) or not len(values)
            or not np.isfinite(values).all()):
        raise ValueError('Support requires finite Nx3x3 saved mesh triangles')
    normals = np.cross(values[:, 1] - values[:, 0], values[:, 2] - values[:, 0])
    # This tolerance only selects a plane; no polygon is enlarged or repaired.
    horizontal = (np.ptp(values[:, :, 2], axis=1) <= 1e-6) & (abs(normals[:, 2]) > 1e-12)
    if not horizontal.any():
        raise ValueError('No horizontal saved support triangles')
    top = float(values[horizontal, :, 2].max())
    selected = values[horizontal & (values[:, :, 2].min(axis=1) >= top - 1e-6)]
    region = unary_union([Polygon(triangle[:, :2]) for triangle in selected])
    if (region.geom_type not in ('Polygon', 'MultiPolygon') or region.is_empty
            or not region.is_valid or not math.isfinite(region.area) or region.area <= 0):
        raise ValueError('Top triangles have no valid measured surface union')
    # JSON round-trip makes arrays match task_precheck's existing contract.
    return dict(region=json.loads(json.dumps(mapping(region))), height_m=top)


def measured_rectangle(region):
    """Return a rectangle certified inside the polygon, including its holes."""
    _, _, box, _, shape, _ = _geometry()
    polygon = shape(region)
    if polygon.is_empty or not polygon.is_valid or polygon.area <= 0:
        raise ValueError('Cannot measure a rectangle inside an invalid region')
    bounds = list(polygon.bounds)
    if polygon.covers(box(*bounds)):
        return bounds
    point = polygon.representative_point()
    half = point.distance(polygon.boundary) / (2 * math.sqrt(2))
    bounds = [point.x - half, point.y - half, point.x + half, point.y + half]
    if (half <= 0 or not bounds[0] < bounds[2] or not bounds[1] < bounds[3]
            or not polygon.covers(box(*bounds))):
        raise ValueError('No finite interior measured rectangle')
    return bounds


def _triangles(payload):
    np, *_ = _geometry()
    result = {}
    if payload.get('world_vertices') is not True:
        raise ValueError('Exporter must supply world-space saved vertices')
    for mesh in payload['meshes']:
        vertices = np.asarray(mesh['vertices'], dtype=np.float64)
        indices = mesh['triangles']
        if (vertices.ndim != 2 or vertices.shape[1] != 3 or not np.isfinite(vertices).all()
                or not isinstance(indices, list) or not indices
                or any(not isinstance(row, list) or len(row) != 3 or
                       any(type(i) is not int or i < 0 or i >= len(vertices) for i in row)
                       for row in indices)):
            raise ValueError('Invalid physical mesh triangle inventory')
        identifier = mesh.get('entity_id')
        if identifier is not None:
            result.setdefault(identifier, []).append(vertices[np.asarray(indices, dtype=int)])
    return {identifier: np.concatenate(rows) for identifier, rows in result.items()}


def _local(triangles, entity):
    np, *_ = _geometry()
    triangles = np.asarray(triangles, dtype=np.float64)
    if (triangles.ndim != 3 or triangles.shape[1:] != (3, 3) or not len(triangles)
            or not np.isfinite(triangles).all()):
        raise ValueError('Missing finite saved entity triangles')
    center = entity.get('actual_center_xy_m') or entity.get('center_xy_m')
    yaw = entity.get('yaw_deg')
    if (not isinstance(center, list) or len(center) != 2 or
            any(type(v) not in (int, float) or not math.isfinite(v) for v in center) or
            type(yaw) not in (int, float) or not math.isfinite(yaw)):
        raise ValueError('Measured prior needs a verified entity center and yaw')
    result = np.array(triangles, copy=True)
    angle = math.radians(yaw)
    c, s = math.cos(angle), math.sin(angle)
    x, y = result[:, :, 0] - center[0], result[:, :, 1] - center[1]
    result[:, :, 0], result[:, :, 1] = x * c + y * s, -x * s + y * c
    return result


def _evidence(requirements, manifest, payload, scene_sha):
    entities = {entity['entity_id']: entity for entity in manifest['entities']}
    if len(entities) != len(manifest['entities']):
        raise ValueError('Ambiguous manifest entity inventory')
    triangles = _triangles(payload)
    result, pending = {}, []

    def source(identifier):
        return entities[identifier].get('asset_sha256') or scene_sha

    task = requirements.get('task')
    if isinstance(task, dict):
        result['task'] = dict(measured_supports=[])
        old = {row['entity_id']: row for row in task.get('measured_supports', [])}
        wanted = list(dict.fromkeys(task.get('support_entity_ids', []) + list(old)))
        for identifier in wanted:
            if identifier not in entities:
                raise ValueError('Unknown task support entity: ' + identifier)
            try:
                surface = measure_triangle_surface(triangles.get(identifier, []))
                surface['source_sha256'] = source(identifier)
                result['task']['measured_supports'].append(dict(entity_id=identifier, surface=surface))
                if 'xy_m' not in old.get(identifier, {}).get('surface', {}):
                    pending.append('task.anchor:' + identifier)
            except ValueError as error:
                pending.append('task.surface:' + identifier + ': ' + str(error))
            if 'minimum_approach_width_m' in task:
                pending.append('task.approach:' + identifier)
    priors = requirements.get('priors')
    if isinstance(priors, dict):
        # Motifs/reservations are retained by the adapter, never reinterpreted.
        result['priors'] = {}
        reserved = {row['support_entity_id'] for row in priors.get('reservations', [])}
        surfaces = {row['entity_id']: row for row in priors.get('surfaces', [])}
        for identifier in sorted(set(surfaces) | reserved):
            if identifier not in entities:
                raise ValueError('Unknown prior support entity: ' + identifier)
            try:
                local = _local(triangles.get(identifier, []), entities[identifier])
                region = measure_triangle_surface(local)['region']
                bounds = measured_rectangle(region)
                # Preserve a requested usable rectangle when current triangles cover it.
                previous = surfaces.get(identifier, {}).get('bounds_xy_m')
                if previous is not None:
                    _, _, box, _, shape, _ = _geometry()
                    if shape(region).covers(box(*previous)):
                        bounds = copy.deepcopy(previous)
                result['priors'].setdefault('surfaces', []).append(dict(
                    entity_id=identifier, bounds_xy_m=bounds, source_sha256=source(identifier)))
            except ValueError as error:
                pending.append('priors.surface:' + identifier + ': ' + str(error))
        footprints = {row['entity_id']: row for row in priors.get('footprints', [])}
        for identifier, entity in entities.items():
            parents = {entity[k] for k in ('supported_by_entity_id', 'support_entity_id',
                       'parent_entity_id') if entity.get(k) is not None}
            if len(parents) == 1 and next(iter(parents)) in reserved:
                footprints.setdefault(identifier, dict(entity_id=identifier,
                    support_entity_id=next(iter(parents))))
        for identifier, row in footprints.items():
            support = row['support_entity_id']
            if identifier not in entities or support not in entities:
                raise ValueError('Unknown measured footprint entity or support')
            try:
                local = _local(triangles.get(identifier, []), entities[support])
                points = local[:, :, :2].reshape(-1, 2)
                bounds = [*points.min(axis=0).tolist(), *points.max(axis=0).tolist()]
                if not bounds[0] < bounds[2] or not bounds[1] < bounds[3]:
                    raise ValueError('Degenerate measured child footprint')
                result['priors'].setdefault('footprints', []).append(dict(entity_id=identifier,
                    support_entity_id=support, bounds_xy_m=bounds, source_sha256=source(identifier)))
            except (ValueError, IndexError) as error:
                pending.append('priors.footprint:' + identifier + ': ' + str(error))
    return result, pending


def measure_saved_scene(manifest_path, scene_path, output_path, *, source_root,
                        requirements_path=None, blender=None, timeout_s=1800):
    """Retain actual exporter output and write rhg.measured-refresh.v1 JSON."""
    started = time.monotonic()
    if type(timeout_s) not in (int, float) or not math.isfinite(timeout_s) or timeout_s <= 0:
        raise ValueError('timeout_s must be finite and positive')
    manifest_path, scene_path = Path(manifest_path).resolve(), Path(scene_path).resolve()
    output_path, source_root = Path(output_path).resolve(), Path(source_root).resolve()
    requirements_path = (Path(requirements_path).resolve() if requirements_path else
                         output_path.parent / 'measurement_request.json')
    if output_path.exists():
        raise ValueError('Evidence output already exists')
    exporter = source_root / 'packages/sim2real/geometry/export_meshes.py'
    pins = {str(path): file_sha256(path) for path in (manifest_path, scene_path,
            requirements_path, Path(__file__).resolve(), exporter,
            exporter.with_name('collision_policy.py'), exporter.with_name('measured_pose.py'))}
    collision_identity = source_root/'scripts/internal/scene_generation/real_assets/collision_frame_identity.py'
    if collision_identity.is_file():
        pins[str(collision_identity)] = file_sha256(collision_identity)
    manifest, requirements = load_json(manifest_path), load_json(requirements_path)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    identifier = manifest.get('scene_id', scene_path.stem)
    if not isinstance(identifier, str) or not identifier or Path(identifier).name != identifier:
        raise ValueError('Require a scene_id basename for read-only mesh export')
    staging = output_path.parent / 'saved_scene_input'
    staging.mkdir(exist_ok=False)
    runtime = dict(manifest, scene_id=identifier)
    with (staging / 'composition_manifest.runtime.json').open('x') as stream:
        json.dump(runtime, stream, allow_nan=False)
    (staging / (identifier + '.blend')).symlink_to(scene_path)
    if blender is None:
        blender = shutil.which('blender')
        if blender is None and Path('/Applications/Blender.app/Contents/MacOS/Blender').is_file():
            blender = '/Applications/Blender.app/Contents/MacOS/Blender'
    if not blender:
        raise ValueError('Specify the existing Blender executable with --blender')
    executable = Path(blender).resolve()
    pins[str(executable)] = file_sha256(executable)
    meshes = output_path.parent / 'geometry/physical_meshes.json.gz'
    command = [str(executable), '--background', '--python-exit-code', '1', '--python', str(exporter),
               '--', '--scene', str(staging), '--out', str(meshes)]
    remaining = timeout_s - (time.monotonic() - started)
    if remaining <= 0:
        raise TimeoutError('Measurement export deadline exhausted')
    receipt = execute_command(command, source_root, output_path.parent / 'mesh_export.log', remaining)
    with (output_path.parent / 'mesh_export_receipt.json').open('x') as stream:
        json.dump(receipt, stream, indent=2, allow_nan=False)
    if receipt['exit_code'] != 0 or receipt['timed_out'] or not receipt['cleanup_passed']:
        raise ValueError('Saved mesh export failed; inspect retained exporter log/receipt')
    with gzip.open(meshes, 'rt') as stream:
        payload = json.load(stream)
    if (payload.get('source_blend_sha256') != pins[str(scene_path)] or
            payload.get('source_runtime_sha256') != file_sha256(staging / 'composition_manifest.runtime.json')):
        raise ValueError('Mesh export is not bound to the current saved scene and manifest')
    patches, pending = _evidence(requirements, manifest, payload, pins[str(scene_path)])
    if any(file_sha256(path) != sha for path, sha in pins.items()):
        raise ValueError('Saved measurement input or implementation changed')
    if time.monotonic() - started > timeout_s:
        raise TimeoutError('Saved measurement deadline exhausted')
    result = dict(schema='rhg.measured-refresh.v1', status='pending' if pending else 'measured',
                  passed=not pending, manifest_sha256=pins[str(manifest_path)],
                  scene_sha256=pins[str(scene_path)], input_sha256=pins,
                  physical_qualified=False, whole_task_acceptance=False,
                  pending_fields=pending, **patches)
    with output_path.open('x') as stream:
        json.dump(result, stream, indent=2, allow_nan=False)
    return result


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--manifest', type=Path, required=True)
    parser.add_argument('--scene', type=Path, required=True)
    parser.add_argument('--output', type=Path, required=True)
    parser.add_argument('--source-root', type=Path, required=True)
    parser.add_argument('--requirements', type=Path)
    parser.add_argument('--blender')
    parser.add_argument('--timeout-s', type=float, default=1800)
    args = parser.parse_args()
    try:
        result = measure_saved_scene(args.manifest, args.scene, args.output,
            source_root=args.source_root, requirements_path=args.requirements,
            blender=args.blender, timeout_s=args.timeout_s)
    except Exception as error:
        print(json.dumps(dict(status='failed', error_type=type(error).__name__, error=str(error))), flush=True)
        return 1
    print(json.dumps(dict(status=result['status'], output=str(args.output),
                         pending_fields=result['pending_fields'])), flush=True)
    return 0  # A retained partial measurement is a successful runner, not acceptance.


if __name__ == '__main__':
    raise SystemExit(main())