File size: 41,638 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
870b85a
 
 
 
3f15e9f
 
 
 
 
870b85a
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
 
 
 
 
 
870b85a
 
3f15e9f
 
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
 
870b85a
 
 
 
3f15e9f
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
 
 
 
 
 
 
 
 
 
870b85a
 
 
 
 
3f15e9f
 
 
 
 
 
 
 
870b85a
3f15e9f
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
 
870b85a
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
870b85a
 
3f15e9f
 
 
 
 
 
 
 
870b85a
 
 
 
3f15e9f
870b85a
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
 
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
 
 
 
 
 
 
 
 
 
 
 
 
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
 
 
 
 
 
870b85a
 
 
3f15e9f
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
"""Bounds-derived cameras and conservative render-evidence acceptance.

Coordinates are metres, Z up. Object-index pixels establish sampled visibility,
not semantic recognizability or complete surface coverage. Projection is never
used as occlusion evidence. Missing evidence remains pending.

visibility_policy on the manifest declares min_target_pixels (default 8) and
target_min_pixels overrides keyed by entity ID. One pixel proves presence;
coverage requires the declared count in one valid bound view, never a sum of
repeated views. Thresholds are sampling requirements, not recognizability or
appearance qualification. Legacy plans with only min_target_pixels still audit.
"""
import math
from pathlib import PurePosixPath


INTERIOR_RENDER_PROFILE = dict(width=1280, height=720, samples=64, denoise=True,
                               time_budget_s=900.)


def valid_sha256(value):
    return isinstance(value, str) and len(value) == 64 and all(c in '0123456789abcdef' for c in value)


def _bounds(value, wall_height=3):
    if len(value) == 4:
        low, high = [value[0], value[1], 0], [value[2], value[3], wall_height]
    elif len(value) == 6:
        low, high = value[:3], value[3:]
    else:
        low, high = value
    low, high = list(map(float, low)), list(map(float, high))
    if (len(low) != 3 or len(high) != 3 or
            not all(math.isfinite(v) for v in low+high) or
            any(a >= b for a, b in zip(low, high))):
        raise ValueError('Invalid nonfinite or reversed bounds')
    return [low, high]


def _union(boxes):
    return [[min(b[0][i] for b in boxes) for i in range(3)],
            [max(b[1][i] for b in boxes) for i in range(3)]]


def _camera(camera_id, box, direction, width, height, rooms, targets, required=True):
    center = [(a+b)/2 for a, b in zip(*box)]
    span = math.dist(*box)
    norm = math.sqrt(math.fsum(v*v for v in direction))
    back = [v/norm for v in direction]
    # Camera right = world up cross backward, except for a vertical camera.
    right = [-back[1], back[0], 0] if abs(back[2]) < .999 else [1, 0, 0]
    norm = math.sqrt(math.fsum(v*v for v in right))
    right = [v/norm for v in right]
    up = [back[1]*right[2]-back[2]*right[1], back[2]*right[0]-back[0]*right[2],
          back[0]*right[1]-back[1]*right[0]]
    extents = [b-a for a, b in zip(*box)]
    horizontal = math.fsum(abs(a)*b for a, b in zip(right, extents))
    vertical = math.fsum(abs(a)*b for a, b in zip(up, extents))
    aspect = width/height
    scale = max(horizontal, vertical*aspect)/min(1., aspect)*1.12
    return dict(camera_id=camera_id, required=required, projection='ORTHO',
                location=[c+d*span*1.5 for c, d in zip(center, back)], target=center,
                ortho_scale=scale, clip_start=max(span*.00001, .00001),
                clip_end=span*5, room_ids=rooms, target_ids=targets)


def _entity_bounds(entity):
    if entity.get('world_bbox_m') is not None:
        return _bounds(entity['world_bbox_m'])
    center, dimensions = entity.get('center_xy_m'), entity.get('dimensions_m')
    base = entity.get('base_z_m')
    if center is None or dimensions is None or base is None:
        return None
    values = [*center, *dimensions, base, entity.get('yaw_deg', 0)]
    if (len(center) != 2 or len(dimensions) != 3
            or any(type(v) not in (int, float) or not math.isfinite(v) for v in values)
            or any(v <= 0 for v in dimensions)):
        raise ValueError('Invalid camera obstacle geometry: '+entity['entity_id'])
    angle = math.radians(entity.get('yaw_deg', 0))
    c, s = abs(math.cos(angle)), abs(math.sin(angle))
    dx = math.fsum((dimensions[0]*c, dimensions[1]*s))/2
    dy = math.fsum((dimensions[0]*s, dimensions[1]*c))/2
    return [[center[0]-dx, center[1]-dy, base],
            [center[0]+dx, center[1]+dy, base+dimensions[2]]]


def _ray_box(origin, direction, box):
    near, far = 0., math.inf
    for axis in range(3):
        if abs(direction[axis]) < 1e-10:
            if not box[0][axis] <= origin[axis] <= box[1][axis]:
                return None
            continue
        a, b = [(side[axis]-origin[axis])/direction[axis] for side in box]
        near, far = max(near, min(a, b)), min(far, max(a, b))
        if near > far:
            return None
    return near


def _composition_score(location, target, room, measured, focus, lens, shift, aspect):
    distance = math.dist(location[:2], target[:2])
    if distance < .1:
        return -math.inf
    forward = [(target[i]-location[i])/distance for i in (0, 1)]
    right = [forward[1], -forward[0]]
    pitched = len(target) == 3
    if pitched:
        rise = target[2]-location[2]
        span = math.hypot(distance, rise)
        cos_pitch, sin_pitch = distance/span, rise/span
    score = 0.
    # Fit the main furniture's complete bounds, including its floor contact.
    # These projections rank cameras; only rendered masks establish visibility.
    for entity, box in focus:
        fits = 0
        for x in (box[0][0], box[1][0]):
            for y in (box[0][1], box[1][1]):
                delta = [x-location[0], y-location[1]]
                depth = math.fsum(a*b for a, b in zip(delta, forward))
                horizontal = math.fsum(a*b for a, b in zip(delta, right))
                for z in (box[0][2], box[1][2]):
                    camera_depth, vertical = depth, z-location[2]
                    if pitched:
                        # Target cameras tilt toward the actual target height.
                        # Rank that rendered frame, including low/high props.
                        camera_depth = depth*cos_pitch+vertical*sin_pitch
                        vertical = vertical*cos_pitch-depth*sin_pitch
                    if camera_depth <= .1:
                        score -= 8
                        continue
                    u = horizontal/camera_depth*lens/18
                    v = (vertical/camera_depth*lens/36-shift)*2/aspect
                    overflow = max(0., abs(u)-.92)+max(0., abs(v)-.92)
                    score -= min(overflow, 3.)*3
                    fits += abs(u) < .92 and abs(v) < .92
        score += fits*2
        center = [(a+b)/2 for a, b in zip(*box)]
        direction = [center[i]-location[i] for i in range(3)]
        if any(other['entity_id'] != entity['entity_id'] and obstacle is not None
               and (hit := _ray_box(location, direction, obstacle)) is not None and hit < .97
               for other, obstacle in measured):
            score -= 12
    score /= max(1, len(focus))
    # Penalize a wall or tall foreground object filling the image near the lens.
    # Floor and ceiling are intentionally excluded from this horizontal screen.
    for u in (-.9, -.6, -.3, 0., .3, .6, .9):
        direction = [forward[i]+right[i]*u*18/lens for i in (0, 1)]
        wall = min((room[1 if direction[i] > 0 else 0][i]-location[i])/direction[i]
                   for i in (0, 1) if abs(direction[i]) > 1e-10)
        nearest = wall
        for _, box in measured:
            if box is not None and box[1][2] > location[2]-.5:
                hit = _ray_box(location, [*direction, 0.], box)
                if hit is not None:
                    nearest = min(nearest, hit)
        score -= max(0., 1.8-nearest)*2
    return round(score+.15*distance, 9)


def _interior_origins(rid, room, entities, *, margin=.3, clearance=.2, min_origins=2):
    lo, hi = room
    eye = lo[2]+1.55
    if eye+.15 >= hi[2]:
        raise ValueError('Room has insufficient standing camera height: '+rid)
    measured = [(e, _entity_bounds(e)) for e in entities if e['room_id'] == rid]
    blockers = [b for _, b in measured if b is not None
                and b[1][2] > lo[2]+.2 and b[0][2] < eye+.15]
    # Screen the standing position as well as the lens against conservative
    # entity bounds. This is planning, not mesh occlusion or physics evidence.
    if min(hi[i]-lo[i] for i in (0, 1)) <= 2*margin:
        raise ValueError('No safe interior camera origin: '+rid)
    candidates = []
    for u in (i/10 for i in range(11)):
        for v in (i/10 for i in range(11)):
            point = [lo[0]+margin+u*(hi[0]-lo[0]-2*margin),
                     lo[1]+margin+v*(hi[1]-lo[1]-2*margin), eye]
            if not any(b[0][0]-clearance <= point[0] <= b[1][0]+clearance
                       and b[0][1]-clearance <= point[1] <= b[1][1]+clearance
                       for b in blockers):
                candidates.append(point)
    if len(candidates) < min_origins:
        if min_origins == 1:
            raise ValueError('No safe interior camera origin: '+rid)
        raise ValueError('No safe interior camera origins for two views: '+rid)
    return measured, candidates


def _room_focus(room, measured):
    lo, hi = room
    # Main room anchors take precedence over storage, desks and small props.
    roles = {e.get('role') for e, b in measured if b is not None}
    functional_roles = next((group for group in (
        {'bed'}, {'sofa', 'coffee_table'}, {'dining_table'},
        ({'cabinet', 'sink', 'oven', 'range_hood'} if 'oven' in roles else
         {'sink', 'shower', 'toilet'}), {'armchair', 'side_table'},
        {'desk', 'cabinet'}) if roles & group), set())
    focus = [(e, b) for e, b in measured if b is not None and e.get('role') in functional_roles]
    if not focus:
        focus = [(e, b) for e, b in measured if b is not None]
    target = ([math.fsum((b[0][i]+b[1][i])/2 for _, b in focus)/len(focus)
               for i in (0, 1)] if focus else [(lo[i]+hi[i])/2 for i in (0, 1)])
    return focus, target


def _interior_cameras(rid, room, entities, ids, width, height, *, margin=.3,
                      clearance=.2, min_origins=2, origin_data=None):
    lo, hi = room
    eye = lo[2]+1.55
    measured, candidates = (origin_data if origin_data is not None else
                            _interior_origins(rid, room, entities, margin=margin,
                                               clearance=clearance, min_origins=min_origins))
    focus, target = _room_focus(room, measured)
    lens = 24.
    rank = lambda item: (_composition_score(item[0], target, room, measured, focus,
                         lens, item[1], height/width)-.1*abs(item[1]+.18))
    settings = [(point, shift) for point in candidates for shift in (-.08, -.14, -.20, -.27)]
    first, first_shift = max(settings, key=rank)
    selected = [('', first, first_shift)]
    if min_origins > 1:
        others = [p for p in candidates if math.dist(p, first) >= .5]
        if not others:
            raise ValueError('No distinct safe interior camera origins: '+rid)
        second, second_shift = max((item for item in settings if item[0] in others),
                                  key=lambda item: rank(item)+.15*math.dist(item[0], first))
        selected.append(('_alternative', second, second_shift))
    result = []
    for suffix, location, shift in selected:
        if math.dist(location[:2], target) < .1:
            raise ValueError('Interior camera direction is degenerate: '+rid)
        result.append(dict(camera_id='room_'+rid+suffix, required=True,
            purpose='interior_human_eye', projection='PERSP',
            location=[round(v, 9) for v in location],
            target=[round(v, 9) for v in [*target, eye]], up=[0, 0, 1],
            lens_mm=lens, sensor_width_mm=36., sensor_fit='HORIZONTAL', shift_y=shift,
            clip_start=.05, clip_end=round(max(20., math.dist(lo, hi)*3), 9),
            room_ids=[rid], target_ids=ids,
            focus_entity_ids=sorted(e['entity_id'] for e, _ in focus)))
    return result


def _target_cameras(rid, room, entities, width, height, *, origin_data=None):
    measured, origins = (origin_data if origin_data is not None else
                         _interior_origins(rid, room, entities))
    result = []
    for entity, box in sorted(measured, key=lambda item: item[0]['entity_id']):
        if box is None:
            continue
        center = [(a+b)/2 for a, b in zip(*box)]
        candidates = [point for point in origins
                      if math.dist(point[:2], center[:2]) >= max(.6, abs(center[2]-point[2]))]
        if not candidates:
            continue
        # Reuse room composition and conservative occlusion ranking. Aim at the
        # actual target height so small tabletop and wall objects are in frame.
        def score(point):
            return _composition_score(point, center, room, measured,
                                      [(entity, box)], 24., 0., height/width)

        first = max(candidates, key=score)
        selected = [first]
        others = [point for point in candidates if math.dist(point, first) >= .5]
        if others:
            def alternate_score(point):
                a = [first[i]-center[i] for i in (0, 1)]
                b = [point[i]-center[i] for i in (0, 1)]
                cosine = math.fsum(x*y for x, y in zip(a, b))/(math.hypot(*a)*math.hypot(*b))
                return score(point)+4*(1-max(-1., min(1., cosine)))
            selected.append(max(others, key=alternate_score))
        for number, point in enumerate(selected, 1):
            result.append(dict(camera_id='target_'+entity['entity_id']+'_'+str(number),
                required=False, purpose='target_coverage', projection='PERSP',
                location=[round(v, 9) for v in point], target=center, up=[0, 0, 1],
                lens_mm=24., sensor_width_mm=36., sensor_fit='HORIZONTAL', shift_y=0.,
                clip_start=.05, clip_end=round(max(20., math.dist(*room)*3), 9),
                room_ids=[rid], target_ids=[entity['entity_id']],
                focus_entity_ids=[entity['entity_id']]))
    return result


def _camera_planning_error(error):
    message = str(error)
    return message.startswith((
        'Room has insufficient standing camera height:',
        'No safe interior camera origin:',
        'No safe interior camera origins for two views:',
        'No distinct safe interior camera origins:',
        'Interior camera direction is degenerate:',
    ))


def _doorway_camera(rid, room, entities, ids, floor, room_boxes):
    """Return one required perspective just outside a declared adjacent-room door."""
    lo, hi = room
    eye = lo[2]+1.55
    if eye+.15 >= hi[2]:
        return None
    doors = floor.get('doors', [])
    if not isinstance(doors, list):
        return None
    measured = [(e, _entity_bounds(e)) for e in entities if e['room_id'] == rid]
    focus, target_xy = _room_focus(room, measured)
    room_center = [(lo[i]+hi[i])/2 for i in (0, 1)]
    for door in sorted((d for d in doors if isinstance(d, dict)),
                       key=lambda d: str(d.get('door_id', ''))):
        room_ids = door.get('room_ids')
        if (not isinstance(room_ids, list) or rid not in room_ids
                or door.get('exterior') is True):
            continue
        adjacent = [other for other in room_ids if other != rid]
        if len(adjacent) != 1 or adjacent[0] not in room_boxes:
            continue
        orientation = str(door.get('wall_orientation', '')).upper()
        interval = door.get('door_interval_m') or door.get('open_interval_m')
        wall = door.get('wall_line_m')
        if (orientation not in ('H', 'V') or not isinstance(interval, list)
                or len(interval) != 2 or any(not isinstance(v, (int, float)) or not math.isfinite(v)
                                             for v in interval)
                or not isinstance(wall, (int, float)) or not math.isfinite(wall)
                or interval[0] >= interval[1]):
            continue
        along = (interval[0]+interval[1])/2
        if orientation == 'H':
            inside = -1 if room_center[1] < wall else 1
            location = [along, wall-inside*.45, eye]
        else:
            inside = -1 if room_center[0] < wall else 1
            location = [wall-inside*.45, along, eye]
        target = [*target_xy, eye]
        if math.dist(location[:2], target[:2]) < .1:
            continue
        return dict(camera_id='room_'+rid+'_doorway', required=True,
                    purpose='interior_human_eye', projection='PERSP',
                    location=[round(v, 9) for v in location],
                    target=[round(v, 9) for v in target], up=[0, 0, 1],
                    lens_mm=24., sensor_width_mm=36., sensor_fit='HORIZONTAL', shift_y=-.14,
                    clip_start=.05, clip_end=round(max(20., math.dist(lo, hi)*3), 9),
                    room_ids=[rid], target_ids=ids,
                    focus_entity_ids=sorted(e['entity_id'] for e, _ in focus),
                    degradation_level='d', degradation_strategy='doorway')
    return None


def _plan_room_cameras(rid, room, entities, ids, width, height, floor, room_boxes):
    attempts = (
        ('a', 'original', .3, .2, 2),
        ('b', 'relaxed', .2, .1, 2),
        ('c', 'single_view', .2, .1, 1),
    )
    failures = []
    for level, strategy, margin, clearance, min_origins in attempts:
        try:
            origin_data = _interior_origins(rid, room, entities, margin=margin,
                                            clearance=clearance, min_origins=min_origins)
            cameras = _interior_cameras(rid, room, entities, ids, width, height,
                                        margin=margin, clearance=clearance,
                                        min_origins=min_origins, origin_data=origin_data)
            record = None if level == 'a' else dict(
                level=level, strategy=strategy,
                reason=failures[-1] if failures else 'original camera plan unavailable')
            return cameras, origin_data, record
        except ValueError as error:
            if not _camera_planning_error(error):
                raise
            failures.append(str(error))
    doorway = _doorway_camera(rid, room, entities, ids, floor, room_boxes)
    if doorway is not None:
        return [doorway], None, dict(level='d', strategy='doorway',
                                     reason=failures[-1] if failures else
                                     'interior camera plan unavailable')
    lo, hi = room
    large_room = min(hi[i]-lo[i] for i in (0, 1)) >= 3.
    reason = ('large_room_camera_planning_failed' if large_room else
              (failures[-1] if failures else 'No usable camera planning strategy'))
    return [], None, dict(level='e', strategy='no_view', reason=reason)


def _thresholds(policy, targets, capacity):
    if not isinstance(policy, dict) or set(policy) - {'min_target_pixels', 'target_min_pixels'}:
        raise ValueError('Unsupported visibility_policy')
    minimum = policy.get('min_target_pixels', 8)
    overrides = policy.get('target_min_pixels', {})
    if not isinstance(overrides, dict) or set(overrides) - set(targets):
        raise ValueError('target_min_pixels requires known target IDs')
    if any(type(n) is not int or not 2 <= n <= capacity for n in [minimum, *overrides.values()]):
        raise ValueError('Coverage pixel thresholds must be integers from 2 to image capacity')
    return minimum, {target: overrides.get(target, minimum) for target in sorted(targets)}


def build_visibility_plan(manifest, width=1280, height=720):
    """Plan all rooms and entities; optional world_bounds_m comes from actual meshes.

    Required: floor_plan.rooms with unique room_id and bounds_m. Optional:
    source_sha256 (saved blend hash), wall_height_m, entities, time_budget_s.
    Every entity is a QA target, including small functional props.
    """
    if any(isinstance(v, bool) or not isinstance(v, int) or v <= 0 for v in (width, height)):
        raise ValueError('Image dimensions must be positive integers')
    floor = manifest.get('floor_plan', {})
    rooms = floor.get('rooms', manifest.get('rooms', []))
    if not rooms:
        raise ValueError('Room bounds required; no reference-house fallback')
    boxes = {}
    for r in rooms:
        rid = r.get('room_id')
        if not isinstance(rid, str) or not rid or rid in boxes:
            raise ValueError('Unique nonempty room_id required')
        boxes[rid] = _bounds(r['bounds_m'], floor.get('wall_height_m', 3))
    entities = manifest.get('entities', [])
    targets = {}
    for e in entities:
        eid = e.get('entity_id')
        if not isinstance(eid, str) or not eid or eid in targets or e.get('room_id') not in boxes:
            raise ValueError('Unique entity_id and known room_id required')
        targets[eid] = e['room_id']
    whole = list(boxes.values())
    for e in entities:
        if e.get('world_bbox_m'):
            whole.append(_bounds(e['world_bbox_m']))
    if manifest.get('world_bounds_m'):
        whole.append(_bounds(manifest['world_bounds_m']))
    box = _union(whole)
    cameras = [_camera('top', box, [0, 0, 1], width, height, [], sorted(targets), False),
               _camera('oblique', box, [1, -1, 1], width, height, [], sorted(targets), False)]
    for camera in cameras:
        camera['purpose'] = 'diagnostic'
    room_visibility_degraded = {}
    for rid, room in sorted(boxes.items()):
        ids = sorted(t for t in targets if targets[t] == rid)
        room_cameras, origin_data, degradation = _plan_room_cameras(
            rid, room, entities, ids, width, height, floor, boxes)
        cameras.extend(room_cameras)
        if degradation is not None:
            room_visibility_degraded[rid] = degradation
        if origin_data is not None:
            cameras.extend(_target_cameras(rid, room, entities, width, height,
                                            origin_data=origin_data))
    budget = float(manifest.get('time_budget_s', INTERIOR_RENDER_PROFILE['time_budget_s']))
    if not math.isfinite(budget) or budget <= 0:
        raise ValueError('Positive finite time_budget_s required')
    minimum, thresholds = _thresholds(manifest.get('visibility_policy', {}), targets, width*height)
    result = dict(schema='rhg.visibility-plan.v1', scene_id=manifest.get('scene_id'),
                source_sha256=manifest.get('source_sha256', manifest.get('blend_sha256')),
                source_manifest_sha256=manifest.get('source_manifest_sha256'),
                bounds_m=box, room_bounds_m=boxes, width=width, height=height,
                room_ids=sorted(boxes), floor_region_room_ids=list(boxes),
                target_ids=sorted(targets), target_rooms=targets,
                cameras=cameras, required_camera_ids=[c['camera_id'] for c in cameras if c['required']],
                time_budget_s=budget, max_views=len(cameras), min_target_pixels=minimum,
                min_presence_pixels=1, target_min_pixels=thresholds,
                camera_safety=dict(method='room_inset_and_conservative_entity_bounds',
                    mesh_clearance_verified=False, unmeasured_entity_ids=sorted(
                        e['entity_id'] for e in entities if _entity_bounds(e) is None)))
    if room_visibility_degraded:
        result['room_visibility_degraded'] = room_visibility_degraded
    return result



def _room_structure_valid(plan, evidence, manifest_sha, errors, unknown):
    structure = evidence.get('room_structure')
    indices = evidence.get('room_index_map')
    if structure is None or indices is None:
        unknown.append('room_structure_evidence_unavailable')
        return False, {}
    before = len(errors)
    expected = {rid: i for i, rid in enumerate(plan['room_ids'], 1)}
    region_order = plan.get('floor_region_room_ids')
    if region_order is None:
        unknown.append('room_region_order_unavailable')
        return False, {}
    if (not isinstance(region_order, list) or len(region_order) != len(expected)
            or any(not isinstance(rid, str) for rid in region_order)
            or set(region_order) != set(expected)):
        errors.append('invalid_floor_region_room_ids')
        return False, {}
    if not isinstance(indices, dict) or indices != expected or any(type(n) is not int for n in indices.values()):
        errors.append('invalid_room_index_map')
        indices = {}
    if not isinstance(structure, dict):
        errors.append('invalid_room_structure')
        return False, indices
    if (structure.get('schema') != 'rhg.room-floor-index.v1' or structure.get('passed') is not True
            or structure.get('geometry_schema') not in (
                'rhg.continuous-room-partitioned-floor.v1', 'rhg.legacy-room-floor.v1')
            or structure.get('room_bounds_m') != plan.get('room_bounds_m')
            or structure.get('region_room_ids') != region_order):
        errors.append('invalid_room_structure_contract')
    for key, value in (('scene_id', plan.get('scene_id')),
                       ('source_sha256', plan.get('source_sha256')),
                       ('source_manifest_sha256', manifest_sha)):
        if structure.get(key) != value:
            errors.append('room_structure:stale_'+key)
    regions = structure.get('regions')
    if not isinstance(regions, dict) or set(regions) != set(expected):
        errors.append('invalid_room_structure_regions')
    else:
        used = set()
        for rid, region in regions.items():
            if not isinstance(region, dict):
                errors.append('invalid_room_region:'+rid)
                continue
            slots = region.get('material_slots')
            area, faces = region.get('top_face_area_m2'), region.get('top_face_count')
            name = region.get('object_name')
            if (region.get('index') != expected[rid] or type(region.get('index')) is not int
                    or not isinstance(name, str) or not name
                    or not isinstance(slots, list) or not slots
                    or any(type(n) is not int or n < 0 for n in slots)
                    or len(slots) != len(set(slots))
                    or type(faces) is not int or faces < 1
                    or type(area) not in (int, float) or not math.isfinite(area) or area <= 0):
                errors.append('invalid_room_region:'+rid)
                continue
            if structure.get('geometry_schema') == 'rhg.continuous-room-partitioned-floor.v1':
                expected_slot = region_order.index(rid)+1
                if name != 'floor__whole_house' or slots != [expected_slot]:
                    errors.append('room_region_mapping_differ:'+rid)
            elif name != 'floor__'+rid:
                errors.append('room_region_mapping_differ:'+rid)
            for slot in slots:
                if (name, slot) in used:
                    errors.append('ambiguous_room_region:'+rid)
                used.add((name, slot))
    return len(errors) == before, indices


def audit_visibility(plan, evidence):
    """Audit a Blender receipt, failing stale/bad data and pending absent data.

    A receipt is trusted measurement input, not a cryptographic attestation.
    The runner decodes files and hashes inputs; this pure API does no file I/O.
    Room coverage requires independently measured floor material-index pixels
    in a room-specific view and a source-bound validated floor-region mapping.
    Structure visibility does not establish furnishing completeness. File hash validation here is structural; the caller
    must independently rehash the files before consuming this trusted receipt.
    """
    errors, unknown = [], []
    if evidence is None:
        evidence = {}
    if not isinstance(evidence, dict):
        errors.append('invalid_evidence_object')
        evidence = {}
    expected = {c['camera_id']: c for c in plan['cameras']}
    capacity = plan['width']*plan['height']
    minimum = plan.get('min_target_pixels', 1)
    thresholds = plan.get('target_min_pixels', {})
    if (type(minimum) is not int or not 1 <= minimum <= capacity
            or not isinstance(thresholds, dict) or set(thresholds) - set(plan['target_ids'])
            or any(type(n) is not int or not 1 <= n <= capacity for n in thresholds.values())):
        errors.append('invalid_target_pixel_thresholds')
        minimum, thresholds = capacity, {}
    thresholds = {target: thresholds.get(target, minimum) for target in plan['target_ids']}
    degraded = plan.get('room_visibility_degraded', {})
    if isinstance(degraded, dict):
        for rid, detail in sorted(degraded.items()):
            if rid not in plan.get('room_ids', []):
                errors.append('room_visibility_degraded_unknown_room:'+str(rid))
                continue
            if isinstance(detail, dict):
                level = detail.get('level', '?')
                reason = detail.get('reason', 'camera planning degraded')
            else:
                level, reason = '?', str(detail)
            unknown.append('room_visibility_degraded:%s:%s:%s' % (rid, level, reason))
    elif degraded is not None:
        errors.append('invalid_room_visibility_degraded')
    sha = plan.get('source_sha256')
    if not valid_sha256(sha):
        unknown.append('expected_source_hash_unavailable')
    if not plan.get('scene_id'):
        unknown.append('expected_scene_id_unavailable')
    if evidence.get('schema') is None:
        unknown.append('missing_evidence_schema')
    elif evidence['schema'] != 'rhg.wholehouse-visibility-evidence.v1':
        errors.append('invalid_evidence_schema')
    if 'passed' in evidence and not isinstance(evidence['passed'], bool):
        errors.append('invalid_passed_flag')
    if evidence.get('passed') is False or evidence.get('error') or evidence.get('error_type'):
        errors.append('render_receipt_failed')
    if 'render_completed' in evidence and evidence['render_completed'] is not True:
        unknown.append('render_incomplete')
    for key, wanted in (('scene_id', plan.get('scene_id')), ('source_sha256', sha)):
        actual = evidence.get(key)
        if actual is None:
            unknown.append('missing_'+key)
        elif wanted is not None and actual != wanted:
            errors.append('stale_'+key)
    manifest_sha = evidence.get('source_manifest_sha256')
    if not valid_sha256(manifest_sha):
        unknown.append('source_manifest_hash_unavailable')
    wanted_manifest_sha = plan.get('source_manifest_sha256')
    if wanted_manifest_sha is not None and (not valid_sha256(wanted_manifest_sha)
                                           or manifest_sha != wanted_manifest_sha):
        errors.append('stale_source_manifest_sha256')
    after_sha = evidence.get('source_sha256_after')
    if after_sha is None:
        unknown.append('source_after_hash_unavailable')
    elif not valid_sha256(after_sha) or after_sha != sha:
        errors.append('source_hash_changed')
    if evidence.get('renderer') != 'BLENDER_CYCLES':
        unknown.append('actual_render_source_unavailable')
    if evidence.get('source_unchanged') is not True:
        (errors if evidence.get('source_unchanged') is False else unknown).append('source_not_verified_unchanged')
    files = evidence.get('files_sha256', {})
    if not isinstance(files, dict):
        errors.append('invalid_files_sha256')
        files = {}
    if not files:
        unknown.append('rendered_file_hashes_unavailable')
    for path, digest in files.items():
        if (not isinstance(path, str) or not path or '\\' in path
                or PurePosixPath(path).is_absolute() or '..' in PurePosixPath(path).parts
                or not valid_sha256(digest)):
            errors.append('invalid_rendered_file_hash')
    indices = evidence.get('object_index_map', {})
    if not isinstance(indices, dict):
        errors.append('invalid_object_index_map')
        indices = {}
    assigned = set()
    for target, index in indices.items():
        if (target not in plan['target_ids'] or isinstance(index, bool)
                or not isinstance(index, int) or not 1 <= index <= 32767 or index in assigned):
            errors.append('ambiguous_object_index:'+str(target))
        else:
            assigned.add(index)

    def artifact(view, cid, key):
        item = view.get(key, {})
        if not isinstance(item, dict):
            errors.append(cid+':invalid_'+key)
            return {}
        if item.get('decoded') is not True:
            unknown.append(cid+':'+key+'_unavailable')
        if item.get('dimensions') != [plan['width'], plan['height']]:
            if not item:
                unknown.append(cid+':'+key+'_dimensions_unavailable')
            else:
                errors.append(cid+':'+key+'_dimensions_differ')
        path, digest = item.get('path'), item.get('sha256')
        if not isinstance(path, str) or not valid_sha256(digest):
            unknown.append(cid+':'+key+'_file_binding_unavailable')
        elif files.get(path) != digest:
            errors.append(cid+':'+key+'_file_hash_differ')
        return item

    structure_valid, room_indices = _room_structure_valid(plan, evidence, manifest_sha, errors, unknown)
    room_valid = {}
    valid, seen = {}, set()
    views = evidence.get('views', [])
    if not isinstance(views, list):
        errors.append('invalid_views')
        views = []
    for view in views:
        if not isinstance(view, dict):
            errors.append('invalid_view')
            continue
        cid = view.get('camera_id')
        if not isinstance(cid, str) or cid in seen or cid not in expected:
            errors.append('duplicate_or_unplanned_camera:'+str(cid))
            continue
        seen.add(cid)
        before = len(errors)+len(unknown)
        for key, wanted in (('source_sha256', sha), ('scene_id', plan.get('scene_id')),
                            ('source_manifest_sha256', manifest_sha)):
            if view.get(key) is None:
                unknown.append(cid+':missing_'+key)
            elif wanted is not None and view[key] != wanted:
                errors.append(cid+':stale_'+key)
        if view.get('camera') != expected[cid]:
            errors.append(cid+':camera_parameters_differ')
        image = artifact(view, cid, 'image')
        if view.get('rendered') is not True or image.get('decoded') is not True:
            unknown.append(cid+':render_unavailable')
        if image.get('nonblank') is False:
            errors.append(cid+':blank_image')
        elif image.get('nonblank') is not True:
            unknown.append(cid+':nonblank_unknown')
        depth = artifact(view, cid, 'depth')
        artifact(view, cid, 'object_index')
        n = depth.get('valid_pixels')
        if n is None:
            unknown.append(cid+':depth_measurement_unavailable')
        elif isinstance(n, bool) or not isinstance(n, int) or not 0 < n <= capacity:
            errors.append(cid+':invalid_depth_pixels')
        else:
            lo, hi = depth.get('min_m'), depth.get('max_m')
            if any(isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v)
                   for v in (lo, hi)) or not 0 < lo <= hi:
                errors.append(cid+':invalid_depth_range')
        counts = view.get('target_pixels', {})
        if not isinstance(counts, dict):
            errors.append(cid+':invalid_target_pixels')
        elif view.get('mask_source') == 'object_index':
            total = 0
            for target, pixels in counts.items():
                if target not in indices:
                    errors.append(cid+':unmapped_target:'+str(target))
                if (isinstance(pixels, bool) or not isinstance(pixels, int)
                        or not 0 <= pixels <= capacity):
                    errors.append(cid+':invalid_mask_pixels:'+str(target))
                else:
                    total += pixels
            if total > capacity or (isinstance(n, int) and total > n):
                errors.append(cid+':oversubscribed_mask_pixels')
        if len(errors)+len(unknown) == before:
            valid[cid] = view
            if structure_valid:
                room_before = len(errors)+len(unknown)
                artifact(view, cid, 'material_index')
                room_counts = view.get('room_pixels')
                if view.get('room_mask_source') != 'material_index' or room_counts is None:
                    unknown.append(cid+':room_measurement_unavailable')
                elif not isinstance(room_counts, dict):
                    errors.append(cid+':invalid_room_pixels')
                else:
                    total = 0
                    for rid, pixels in room_counts.items():
                        if rid not in room_indices:
                            errors.append(cid+':unmapped_room:'+str(rid))
                        if type(pixels) is not int or not 0 <= pixels <= capacity:
                            errors.append(cid+':invalid_room_pixels:'+str(rid))
                        else:
                            total += pixels
                    if total > capacity or (type(n) is int and total > n):
                        errors.append(cid+':oversubscribed_room_pixels')
                if len(errors)+len(unknown) == room_before:
                    room_valid[cid] = view
    missing = sorted(set(plan['required_camera_ids'])-set(valid))
    unknown.extend('missing_required_camera:'+c for c in missing)
    visibility, coverage, observations, covered = {}, {}, {}, set()
    for target in plan['target_ids']:
        counts = []
        observations[target] = []
        for cid, view in valid.items():
            pixels = view.get('target_pixels', {}).get(target)
            if view.get('mask_source') != 'object_index' or pixels is None:
                continue
            if isinstance(pixels, bool) or not isinstance(pixels, int) or not 0 <= pixels <= plan['width']*plan['height']:
                errors.append(cid+':invalid_mask_pixels:'+target)
                continue
            counts.append(pixels)
            observations[target].append(dict(camera_id=cid, pixels=pixels,
                                              present=pixels >= 1,
                                              sufficient_coverage=pixels >= thresholds[target]))
        visibility[target] = ('visible' if any(n >= 1 for n in counts)
                              else 'not_visible' if counts else 'unknown')
        coverage[target] = ('sufficient' if any(n >= thresholds[target] for n in counts)
                            else 'insufficient' if any(n >= 1 for n in counts)
                            else 'not_visible' if counts else 'unknown')
    room_coverage, room_observations = {}, {}
    for rid in plan['room_ids']:
        room_observations[rid] = [dict(camera_id=cid, pixels=view['room_pixels'][rid])
            for cid, view in room_valid.items()
            if rid in expected[cid]['room_ids'] and rid in view['room_pixels']]
        counts = [row['pixels'] for row in room_observations[rid]]
        room_coverage[rid] = ('sufficient' if any(n >= 8 for n in counts)
                              else 'insufficient' if any(n >= 1 for n in counts)
                              else 'not_visible' if counts else 'unknown')
        if room_coverage[rid] == 'sufficient':
            covered.add(rid)
    uncovered = sorted(set(plan['room_ids'])-covered)
    if uncovered:
        unknown.append('room_pixel_coverage_incomplete')
    unseen = [t for t, state in coverage.items() if state != 'sufficient']
    if unseen:
        unknown.append('target_visibility_incomplete')
    needs_more = lambda camera: (set(camera['target_ids']) & set(unseen)
                                 or set(camera['room_ids']) & set(uncovered))
    # A measured but insufficient alternate still needs room-level follow-up.
    # Optional world diagnostics must not replace an interior perspective.
    alternatives = [c['camera_id'] for c in plan['cameras']
                    if c.get('projection') == 'PERSP' and c['room_ids']
                    and c['camera_id'] not in seen
                    and (not c['required'] or c['camera_id'].endswith('_alternative'))
                    # Target views also measure their room's floor. Keep them
                    # eligible while either independent coverage gate is open.
                    and needs_more(c)]
    if not alternatives:
        alternatives = [c['camera_id'] for c in plan['cameras'] if not c['required']
                        and c['camera_id'] not in seen and needs_more(c)]
    status = 'failed' if errors else 'pending' if unknown else 'passed'
    # A planner degradation is a known audit warning. Keep it in unknowns so
    # the 038 exit policy can report it, while leaving the renderer's pending
    # follow-up set compatible with consumers that only accept measurable
    # coverage gaps.
    pending = [item for item in unknown
               if not (isinstance(item, str)
                       and item.startswith('room_visibility_degraded:'))]
    return dict(schema='rhg.visibility-audit.v1', passed=status == 'passed', status=status,
                visibility_passed=status == 'passed', appearance_qualified=False,
                appearance_status='not_assessed',
                errors=errors, pending=pending, missing_camera_ids=missing,
                issues=errors, warnings=[], unknowns=unknown,
                uncovered_room_ids=uncovered, target_visibility=visibility,
                target_coverage=coverage, target_min_pixels=thresholds,
                target_observations=observations, room_coverage=room_coverage,
                room_observations=room_observations, min_room_pixels=8,
                alternative_camera_ids=alternatives,
                evidence_scope='sampled object-index entity and material-index room-floor coverage; furnishing completeness and appearance are not assessed')