File size: 23,759 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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
"""Read-only saved-mesh gravity diagnostic using Blender's CPU Bullet engine.

Run with cached Blender --background --factory-startup --disable-autoexec
--threads 2 --python-exit-code 1 --python this_file -- --scene saved.blend
--manifest composition_manifest.runtime.json --entity-id supported_cup
--mass-kg 0.3 --output /separate/evidence/report.json.
Exit 0 means the narrow settling check passed, 2 means completed but rejected,
and 1 means a runtime/input error. Initial placement has its own stricter flag.

Only the selected supported cup/mug/lamp is dynamic. All other saved collision
meshes are fixed, including walls, support and doors. Exact evaluated triangles
are copied into an isolated, unsaved physics scene. No convex-hull/box collision
substitutes, support patches, pose repair, source save or rendering are used.
Convex hull is used ONLY to diagnose dynamic-mesh concavity, never as collider.

The motion is Bullet's, not an integrated gravity approximation. Velocities
are finite differences of consecutive evaluated engine poses, not inaccessible
Bullet contact/velocity telemetry. Surface intersections and downward mesh rays
are geometric diagnostics, not a full penetration-depth or impulse solver.
Nonclosed/multipart/concave active meshes fail fidelity even if Bullet moves
them. Unmeasured mass, friction, inertia, dynamic triangle stability and fixed
surroundings limit this to one prop under declared model assumptions. Native
joint motion, robot tasks, current geometry and whole-house physical acceptance
are NEVER qualified here. Parent owns their separately bound integration.
"""
from __future__ import annotations

import argparse
import hashlib
import importlib.util
import json
import math
from pathlib import Path
import sys
import traceback

sys.dont_write_bytecode = True


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


def arguments(argv):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--scene', type=Path, required=True)
    parser.add_argument('--manifest', type=Path, required=True)
    parser.add_argument('--entity-id', required=True)
    parser.add_argument('--output', type=Path, required=True)
    parser.add_argument('--mass-kg', type=float, required=True)
    parser.add_argument('--friction', type=float, default=.5)
    parser.add_argument('--restitution', type=float, default=0.)
    parser.add_argument('--frames', type=int, default=241)
    parser.add_argument('--fps', type=int, default=60)
    parser.add_argument('--substeps', type=int, default=10)
    parser.add_argument('--solver-iterations', type=int, default=40)
    args = parser.parse_args(argv)
    args.scene, args.manifest, args.output = (p.resolve() for p in (args.scene, args.manifest, args.output))
    if (args.output.exists() or args.output == args.scene or args.output == args.manifest
            or args.scene.parent in args.output.parents or args.manifest.parent in args.output.parents):
        raise ValueError('Require a new output outside the saved input directories')
    if (not math.isfinite(args.mass_kg) or args.mass_kg <= 0 or args.mass_kg > 100
            or any(not math.isfinite(v) or not 0 <= v <= 1 for v in (args.friction, args.restitution))
            or not 31 <= args.frames <= 3601 or not 30 <= args.fps <= 240
            or not 1 <= args.substeps <= 1000 or not 1 <= args.solver_iterations <= 1000):
        raise ValueError('Invalid bounded physics configuration')
    return args


def target(manifest, identifier):
    entities = {row['entity_id']: row for row in manifest['entities']}
    if len(entities) != len(manifest['entities']):
        raise ValueError('Duplicate manifest entity inventory')
    if identifier not in entities:
        raise ValueError('Unknown selected entity')
    child = entities[identifier]
    if child.get('role') not in ('cup', 'mug', 'lamp'):
        raise ValueError('Only explicitly selected supported movable cup/mug/lamp is allowed')
    parents = {child[k] for k in ('support_entity_id', 'supported_by_entity_id', 'parent_entity_id') if child.get(k)}
    if len(parents) != 1:
        raise ValueError('Missing or ambiguous support for selected prop')
    parent = next(iter(parents))
    if parent not in entities or parent == identifier:
        raise ValueError('Unknown or self support')
    if any(child.get(key) for key in ('joints', 'articulation', 'native_articulation', 'fixed', 'wall_mounted')):
        raise ValueError('Selected prop has fixed/articulated semantics; no safe movable contract')
    return child, parent


def angular_speed(before, after, fps):
    """Shortest pose difference; atan2 retains tiny rotations lost by acos(w)."""
    difference = before.rotation_difference(after)
    return 2 * math.atan2(math.hypot(difference.x, difference.y, difference.z), abs(difference.w)) * fps


def geometry_facts(vertices, triangles, *, audit_convex=True):
    """Audit topology and homogeneous solid centroid without editing geometry."""
    import bmesh
    from mathutils import Vector
    bm = bmesh.new()
    try:
        for co in vertices:
            bm.verts.new(co)
        bm.verts.ensure_lookup_table()
        for triangle in triangles:
            bm.faces.new([bm.verts[i] for i in triangle])
        bm.normal_update()
        boundary = sum(not edge.is_manifold for edge in bm.edges)
        inconsistent = sum(edge.is_manifold and not edge.is_contiguous for edge in bm.edges)
        unseen = set(bm.verts)
        components = 0
        while unseen:
            components += 1
            pending = [unseen.pop()]
            while pending:
                for edge in pending.pop().link_edges:
                    for vertex in edge.verts:
                        if vertex in unseen:
                            unseen.remove(vertex)
                            pending.append(vertex)
        volume = abs(bm.calc_volume(signed=True))
        center = sum((Vector(v) for v in vertices), Vector()) / len(vertices)
        # Reference-shifted tetrahedra reduce cancellation far from the origin.
        signed, weighted = 0., Vector()
        for a, b, c in triangles:
            a, b, c = (Vector(vertices[i])-center for i in (a, b, c))
            weight = a.dot(b.cross(c))
            signed += weight
            weighted += (a+b+c) * weight
        if boundary == 0 and inconsistent == 0 and abs(signed) > 1e-12:
            center += weighted / (4*signed)
        hull = bmesh.new()
        try:
            if audit_convex:
                for v in vertices:
                    hull.verts.new(v)
                bmesh.ops.convex_hull(hull, input=list(hull.verts), use_existing_faces=False)
                hull_volume = abs(hull.calc_volume(signed=True))
            else:
                hull_volume = 0.
        finally:
            hull.free()
        convex = (volume > 1e-12 and hull_volume > 1e-12
                  and abs(hull_volume-volume) <= max(1e-10, hull_volume*1e-5))
        return dict(nonmanifold_edges=boundary, inconsistently_oriented_edges=inconsistent,
                    connected_components=components, signed_volume_m3=signed/6,
                    mesh_volume_m3=volume, diagnostic_convex_hull_volume_m3=hull_volume,
                    convex=convex, center_of_mass_model_m=list(center))
    finally:
        bm.free()


def extract(args, child, parent, report):
    import bpy
    from mathutils import Vector
    bpy.ops.wm.open_mainfile(filepath=str(args.scene), load_ui=False, use_scripts=False)
    original = bpy.context.scene
    if bpy.data.libraries:
        raise ValueError('Linked external mesh libraries require separate byte binding')
    if abs(original.unit_settings.scale_length-1.) > 1e-9:
        raise ValueError('Saved scene must use metre scale_length=1')
    if any(o.rigid_body or o.rigid_body_constraint for o in original.objects):
        raise ValueError('Existing rigid bodies/joints need a separate preservation adapter')
    policy_path = Path(__file__).resolve().parents[1] / 'source/packages/sim2real/geometry/collision_policy.py'
    report['input_sha256'][str(policy_path)] = digest(policy_path)
    spec = importlib.util.spec_from_file_location('gravity_collision_policy', policy_path)
    policy = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(policy)
    depsgraph = bpy.context.evaluated_depsgraph_get()
    if any(instance.is_instance for instance in depsgraph.object_instances):
        raise ValueError('Instanced meshes require explicit evaluated instance inventory')
    rows, excluded = [], []
    for obj in original.objects:
        if obj.type != 'MESH':
            continue
        decision = policy.classify_collision_mesh(obj.name, obj.get('kind'),
            hidden_render=obj.hide_render, hidden_viewport=obj.hide_viewport)
        if not decision['include_in_physical_collision']:
            excluded.append(decision)
            continue
        if (obj.animation_data or obj.constraints or any(m.type == 'ARMATURE' for m in obj.modifiers)):
            raise ValueError('Animated/constrained mesh must not silently become fixed: '+obj.name)
        evaluated = obj.evaluated_get(depsgraph)
        mesh = evaluated.to_mesh()
        try:
            mesh.calc_loop_triangles()
            vertices = [list(evaluated.matrix_world @ v.co) for v in mesh.vertices]
            triangles = [list(t.vertices) for t in mesh.loop_triangles]
            if not vertices or not triangles:
                raise ValueError('Empty physical mesh: '+obj.name)
            if any(not math.isfinite(v) for co in vertices for v in co):
                raise ValueError('Nonfinite saved mesh: '+obj.name)
            if any((Vector(vertices[b])-Vector(vertices[a])).cross(
                    Vector(vertices[c])-Vector(vertices[a])).length < 1e-12 for a,b,c in triangles):
                report['uncertain_meshes'].append(dict(name=obj.name, reason='degenerate_saved_triangles'))
            row = dict(name=obj.name, entity_id=obj.get('entity_id'), vertices=vertices, triangles=triangles)
            rows.append(row)
        finally:
            evaluated.to_mesh_clear()
    active = [r for r in rows if r['entity_id'] == child['entity_id']]
    supports = [r for r in rows if r['entity_id'] == parent]
    if not active or not supports:
        raise ValueError('Missing actual saved prop/support meshes')
    vertices, triangles = [], []
    for row in active:
        offset = len(vertices)
        vertices.extend(row['vertices'])
        triangles.extend([[i+offset for i in t] for t in row['triangles']])
    if len(vertices) > 100000:
        raise ValueError('Selected prop exceeds bounded mesh audit budget')
    facts = geometry_facts(vertices, triangles)
    report['dynamic_mesh'] = dict(facts, source_meshes=[r['name'] for r in active],
                                  vertices=len(vertices), triangles=len(triangles))
    report['support_meshes'] = []
    for row in supports:
        # Static concave triangles are preserved; closure remains a fidelity gate.
        support_facts = geometry_facts(row['vertices'], row['triangles'], audit_convex=False)
        report['support_meshes'].append(dict(name=row['name'], **support_facts))
    report['excluded_planning_meshes'] = excluded
    report['saved_nonmesh_objects_untouched'] = sum(o.type != 'MESH' for o in original.objects)
    return dict(name='dynamic:'+child['entity_id'], entity_id=child['entity_id'],
                vertices=vertices, triangles=triangles), [r for r in rows if r['entity_id'] != child['entity_id']]


def physics_scene(args, active, fixed, report):
    import bpy
    from mathutils import Vector
    bpy.ops.wm.read_factory_settings(use_empty=True)
    scene = bpy.context.scene
    scene.unit_settings.system = 'METRIC'
    scene.unit_settings.scale_length = 1.
    scene.gravity = (0, 0, -9.81)
    scene.render.fps, scene.render.fps_base = args.fps, 1.
    scene.frame_start, scene.frame_end = 1, args.frames
    center = Vector(report['dynamic_mesh']['center_of_mass_model_m'])
    body = None
    for row in [active, *fixed]:
        dynamic = row is active
        mesh = bpy.data.meshes.new(row['name'])
        offset = center if dynamic else Vector()
        mesh.from_pydata([Vector(v)-offset for v in row['vertices']], [], row['triangles'])
        mesh.update()
        obj = bpy.data.objects.new(row['name'], mesh)
        scene.collection.objects.link(obj)
        obj.location = offset
        bpy.context.view_layer.objects.active = obj
        obj.select_set(True)
        bpy.ops.rigidbody.object_add()
        obj.select_set(False)
        rb = obj.rigid_body
        rb.type = 'ACTIVE' if dynamic else 'PASSIVE'
        rb.collision_shape, rb.mesh_source = 'MESH', 'BASE'
        rb.use_margin, rb.collision_margin = True, .0005
        rb.friction, rb.restitution = args.friction, args.restitution
        rb.use_deactivation, rb.kinematic = False, False
        rb.linear_damping, rb.angular_damping = .04, .1
        if dynamic:
            rb.mass = args.mass_kg
            body = obj
        report['colliders'].append(dict(name=row['name'], entity_id=row['entity_id'],
            type=rb.type, collision_shape=rb.collision_shape, mesh_source=rb.mesh_source,
            vertex_count=len(mesh.vertices), triangle_count=len(mesh.polygons),
            collision_margin_m=rb.collision_margin))
    world = scene.rigidbody_world
    world.substeps_per_frame, world.solver_iterations = args.substeps, args.solver_iterations
    world.time_scale = 1.
    world.point_cache.frame_start, world.point_cache.frame_end = 1, args.frames
    bpy.context.view_layer.update()
    return scene, body


def mesh_diagnostics(vertices, triangles, fixed, parent):
    """Exact triangle surface intersections and sampled downward support rays."""
    from mathutils import Vector
    from mathutils.bvhtree import BVHTree
    moving = BVHTree.FromPolygons(vertices, triangles, all_triangles=True, epsilon=0.)
    collisions, contacts, gaps = [], 0, []
    bottom = min(v[2] for v in vertices)
    sample_vertices = [Vector(v) for v in vertices if v[2] <= bottom+.003]
    for row, tree in fixed:
        overlaps = tree.overlap(moving)
        if overlaps:
            collisions.append(dict(name=row['name'], entity_id=row['entity_id'],
                                   triangle_pairs=len(overlaps)))
        if row['entity_id'] == parent:
            for v in sample_vertices:
                hit, normal, index, distance = tree.ray_cast(v+Vector((0,0,.00001)),
                                                            Vector((0,0,-1)), .00301)
                if hit is not None and abs(normal.z) >= .5:
                    contacts += 1
                    gaps.append(distance-.00001)
    return dict(triangle_surface_intersections=sum(r['triangle_pairs'] for r in collisions),
                intersected_fixed_meshes=collisions, support_contact_samples=contacts,
                sampled_bottom_vertices=len(sample_vertices),
                minimum_sampled_downward_gap_m=min(gaps) if gaps else None,
                penetration_depth_measured=False, containment_tested=False,
                engine_contact_impulses_available=False)


def simulate(args, active, fixed, parent, report):
    import bpy
    from mathutils.bvhtree import BVHTree
    static_trees = [(r, BVHTree.FromPolygons(r['vertices'], r['triangles'], all_triangles=True)) for r in fixed]
    report['before'] = mesh_diagnostics(active['vertices'], active['triangles'], static_trees, parent)
    scene, body = physics_scene(args, active, fixed, report)
    fixed_poses = [(obj, obj.matrix_world.copy()) for obj in scene.objects if obj is not body]
    report['engine_executed'] = True
    previous = None
    matrices = []
    for frame in range(1, args.frames+1):
        scene.frame_set(frame)
        bpy.context.view_layer.update()
        matrix = body.evaluated_get(bpy.context.evaluated_depsgraph_get()).matrix_world.copy()
        position, rotation, _ = matrix.decompose()
        rotation.normalize()
        velocity = (position-previous[0])*args.fps if previous else position*0
        angular = angular_speed(previous[1], rotation, args.fps) if previous else 0.
        row = dict(frame=frame, time_s=(frame-1)/args.fps, position_m=list(position),
                   quaternion_wxyz=list(rotation), linear_velocity_m_s=list(velocity),
                   linear_speed_m_s=velocity.length, angular_speed_rad_s=angular)
        if (not math.isfinite(angular) or not math.isfinite(velocity.length)
                or any(not math.isfinite(v) for key in ('position_m','quaternion_wxyz','linear_velocity_m_s') for v in row[key])):
            raise ValueError('Nonfinite engine trajectory')
        report['trajectory'].append(row)
        matrices.append(matrix)
        previous = position.copy(), rotation.copy()
    final_vertices = [list(matrices[-1] @ v.co) for v in body.data.vertices]
    report['after'] = mesh_diagnostics(final_vertices, active['triangles'], static_trees, parent)
    from mathutils import Vector
    trace = report['trajectory']
    recent = trace[-args.fps//2:]
    last = Vector(trace[-1]['position_m'])
    displacement = (last-Vector(trace[0]['position_m'])).length
    fixed_translation, fixed_rotation = 0., 0.
    for obj, before in fixed_poses:
        after = obj.evaluated_get(bpy.context.evaluated_depsgraph_get()).matrix_world
        fixed_translation = max(fixed_translation, (after.translation-before.translation).length)
        fixed_rotation = max(fixed_rotation, angular_speed(before.to_quaternion(), after.to_quaternion(), 1))
    report['summary'] = dict(displacement_m=displacement,
        fixed_body_max_translation_drift_m=fixed_translation,
        fixed_body_max_rotation_drift_rad=fixed_rotation,
        final_window_s=len(recent)/args.fps,
        final_window_max_linear_speed_m_s=max(r['linear_speed_m_s'] for r in recent),
        final_window_max_angular_speed_rad_s=max(r['angular_speed_rad_s'] for r in recent),
        final_window_position_drift_m=max((Vector(r['position_m'])-last).length for r in recent))
    facts = report['dynamic_mesh']
    failures = report['failures']
    if facts['nonmanifold_edges'] or facts['inconsistently_oriented_edges'] or abs(facts['signed_volume_m3']) < 1e-12:
        failures.append('dynamic_mesh_not_closed_or_consistently_oriented')
    if facts['connected_components'] != 1:
        failures.append('multipart_dynamic_inertia_or_internal_contacts_unverified')
    if not facts['convex']:
        failures.append('concave_active_triangle_mesh_stability_unverified')
    if any(r['nonmanifold_edges'] or r['inconsistently_oriented_edges'] for r in report['support_meshes']):
        failures.append('support_mesh_volume_fidelity_unverified')
    if report['uncertain_meshes']:
        failures.append('degenerate_saved_collision_triangles')
    report['collider_fidelity_verified'] = not failures
    if fixed_translation > 1e-9 or fixed_rotation > 1e-9:
        failures.append('fixed_saved_environment_moved')
    summary = report['summary']
    if (summary['final_window_max_linear_speed_m_s'] > .02
            or summary['final_window_max_angular_speed_rad_s'] > .05
            or summary['final_window_position_drift_m'] > .005):
        failures.append('not_settled_in_final_window')
    if not report['after']['support_contact_samples']:
        failures.append('no_sampled_final_contact_on_declared_support')
    if report['after']['triangle_surface_intersections']:
        failures.append('final_mesh_surface_intersections')
    report['settling_passed'] = not failures
    report['initial_placement_passed'] = bool(report['settling_passed']
        and displacement <= .01 and report['before']['support_contact_samples']
        and report['before']['triangle_surface_intersections'] == 0)


def run(args):
    import bpy
    report = dict(schema='rhg.gravity-settle.v2', scope='single_supported_prop_fixed_saved_triangle_environment',
        engine=dict(name='Blender/Bullet', version=bpy.app.version_string,
                    build_hash=bpy.app.build_hash.decode(), device='CPU'),
        engine_executed=False, settling_passed=False, initial_placement_passed=False,
        physics_qualified=False, collider_fidelity_verified=False, source_blend_saved=False,
        geometry_qualification='not_assessed_by_this_runner',
        source_unchanged=False, input_sha256={}, parameters={k:str(v) if isinstance(v,Path) else v for k,v in vars(args).items()},
        model=dict(gravity_m_s2=[0,0,-9.81], dynamic_collision='MESH (Bullet active triangle mesh)',
            fixed_collision='exact evaluated saved triangles, including hidden physical meshes',
            mass_and_surface_parameters='explicit assumed mass/friction/restitution, not measured',
            inertia='Bullet triangle shape inertia; homogeneous solid centroid, not measured',
            native_joint_motion='not_run; doors and every other entity are fixed',
            velocity_source='finite differences of consecutive evaluated Bullet poses',
            contact_source='mesh BVH downward rays; no Bullet impulse telemetry'),
        limits=['Not whole-house physics, articulation, appearance or robot task acceptance',
                'Triangle intersections and sampled support rays do not certify volumetric nonpenetration',
                'Any concave/multipart/nonclosed active mesh remains unqualified',
                'Parent must bind current geometry and this exact input/model separately'],
        thresholds=dict(linear_speed_m_s=.02, angular_speed_rad_s=.05, drift_m=.005,
                        initial_motion_m=.01, support_ray_distance_m=.003, collision_margin_m=.0005),
        colliders=[], trajectory=[], uncertain_meshes=[], failures=[])
    try:
        for path in (args.scene, args.manifest, Path(__file__).resolve(), Path(bpy.app.binary_path).resolve()):
            report['input_sha256'][str(path)] = digest(path)
        manifest = json.loads(args.manifest.read_text())
        child, parent = target(manifest, args.entity_id)
        report.update(entity_id=args.entity_id, support_entity_id=parent)
        if not bpy.app.build_options.bullet:
            raise ValueError('Runtime has no Bullet engine')
        active, fixed = extract(args, child, parent, report)
        simulate(args, active, fixed, parent, report)
    except Exception as error:
        report.update(error=str(error), error_type=type(error).__name__, traceback=traceback.format_exc())
    finally:
        report['source_unchanged'] = all(Path(p).is_file() and digest(p)==sha
                                         for p,sha in report['input_sha256'].items())
        if not report['source_unchanged']:
            report['failures'].append('bound_input_changed')
            report['settling_passed'] = report['initial_placement_passed'] = False
        args.output.parent.mkdir(parents=True, exist_ok=True)
        with args.output.open('x') as stream:
            json.dump(report, stream, indent=2, allow_nan=False)
        print(json.dumps({k:report[k] for k in ('engine_executed','settling_passed','initial_placement_passed',
                                               'physics_qualified','source_unchanged','failures')}), flush=True)
    return report


if __name__ == '__main__':
    args = arguments(sys.argv[sys.argv.index('--')+1:])
    report = run(args)
    raise SystemExit(1 if report.get('error') or not report['source_unchanged']
                     else (0 if report['settling_passed'] else 2))