File size: 27,967 Bytes
3f15e9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75e20e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f15e9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Finite preferences for newly generated shell openings, before mesh creation.

This adapter never modifies an already furnished shell. Door frames, motion
volumes and metric contracts must be compiled AFTER this function returns.
"""
import copy
import math
import os


VERSION = 'rhg.adaptive-shell.v1'


class AuthoredWindowValidationError(ValueError):
    """Invalid supplied geometry with JSON-safe evidence for the build result."""

    def __init__(self, diagnostic):
        self.diagnostic = diagnostic
        conflicts = '; '.join(
            f"{row['opening_id']}: gap {row['gap_m']:.3f} m, "
            f"minimum {row['minimum_gap_m']:.3f} m"
            for row in diagnostic['opening_conflicts'])
        message = (
            f"authored window not in legal exterior interval: {diagnostic['window_id']} "
            f"in room {diagnostic['room_id']}, interval {diagnostic['window_interval_m']}, "
            f"legal intervals {diagnostic['legal_exterior_intervals_m']}"
        )
        if conflicts:
            message += '; ' + conflicts
        super().__init__(message + '. ' + diagnostic['remediation'])


def _invalid_window_diagnostic(plan, room, window, spans):
    from engine.source.scripts.internal.scene_generation.window_rules import MIN_OPENING_GAP_M

    lo, hi = window['window_interval_m']
    conflicts = []
    for kind in ('window', 'door'):
        for other in plan.get(kind + 's', []):
            if other is window or not _same_wall(window, other):
                continue
            interval = other.get(kind + '_interval_m')
            if not interval:
                continue
            gap = max(interval[0] - hi, lo - interval[1])
            if gap < MIN_OPENING_GAP_M - 1e-6:
                conflicts.append(dict(
                    opening_id=other.get(kind + '_id'), opening_kind=kind,
                    interval_m=list(interval), gap_m=round(gap, 6),
                    minimum_gap_m=MIN_OPENING_GAP_M,
                    deficit_m=round(MIN_OPENING_GAP_M - gap, 6)))
    return dict(
        schema='rhg.authored-window-validation.v1',
        code='authored_window_not_in_legal_exterior_interval',
        window_id=window.get('window_id'), room_id=window['room_id'],
        source=window.get('source'), fixed=_fixed(window),
        wall_orientation=window['wall_orientation'], wall_line_m=window['wall_line_m'],
        window_interval_m=list(window['window_interval_m']), room_bounds_m=list(room['bounds_m']),
        legal_exterior_intervals_m=[[round(a, 6), round(b, 6)] for a, b in spans],
        opening_conflicts=conflicts,
        remediation='Correct the supplied window in the source plan to fit a legal exterior '
                    'interval and the required opening gap, then retry. Supplied openings '
                    'have not been moved.')


def _components(plan):
    graph = {r['room_id']: set() for r in plan['rooms']}
    links = [d['room_ids'] for d in plan.get('doors', [])]
    links += [a['room_ids'] for a in plan.get('topology_adjacencies', []) if a.get('open_interval_m')]
    for pair in links:
        if len(pair) == 2 and all(r in graph for r in pair):
            a, b = pair; graph[a].add(b); graph[b].add(a)
    unseen = set(graph); components = []
    while unseen:
        pending = [min(unseen)]; seen = set()
        while pending:
            rid = pending.pop()
            if rid in seen: continue
            seen.add(rid); pending.extend(graph[rid] - seen)
        unseen -= seen; components.append(sorted(seen))
    return sorted(components)


def _fixed(row):
    return any(row.get(k) for k in ('fixed', 'locked', 'authored', 'preserve_opening'))


def _same_wall(a, b):
    return a.get('wall_orientation') == b.get('wall_orientation') and abs(a['wall_line_m'] - b['wall_line_m']) < 1e-5


def _subtract(spans, cut):
    result = []
    for lo, hi in spans:
        a, b = max(lo, cut[0]), min(hi, cut[1])
        if a >= b: result.append((lo, hi)); continue
        if lo < a: result.append((lo, a))
        if b < hi: result.append((b, hi))
    return result


def _shared_record_valid(rec, rooms):
    """The record is evidence only when two actual room boundaries agree."""
    if len(rec.get('room_ids', [])) != 2: return False
    a, b = [rooms[r]['bounds_m'] for r in rec['room_ids']]
    axis = 0 if rec['wall_orientation'] == 'V' else 1
    tangent = 1-axis; line=rec['wall_line_m']
    opposite = ((abs(a[axis+2]-line)<1e-4 and abs(b[axis]-line)<1e-4) or
                (abs(b[axis+2]-line)<1e-4 and abs(a[axis]-line)<1e-4))
    lo, hi = rec['overlap_interval_m']
    return opposite and lo >= max(a[tangent], b[tangent])-1e-4 and hi <= min(a[tangent+2],b[tangent+2])+1e-4


def _relocate_doors(plan, report):
    rooms={r['room_id']: r for r in plan['rooms']}
    for door in list(plan.get('doors', [])):
        if _fixed(door) or door.get('source') != 'circulation_graph_selected_v8': continue
        ids=door.get('room_ids', [])
        if len(ids)!=2: continue
        bedrooms=[r for r in ids if 'bedroom' in rooms[r].get('room_type','')]
        living=[r for r in ids if rooms[r].get('room_type')=='living_room']
        if not bedrooms or not living: continue
        bedroom=bedrooms[0]
        old=next((a for a in plan['topology_adjacencies'] if a.get('door_id')==door['door_id']),None)
        if not old or _fixed(old): continue
        candidates=[a for a in plan['topology_adjacencies'] if bedroom in a['room_ids']
                    and any(rooms[r].get('room_type') in ('hallway','corridor') for r in a['room_ids'])
                    and not a.get('open_connection') and not a.get('door_interval_m') and not _fixed(a)
                    and _shared_record_valid(a,rooms)]
        candidates.sort(key=lambda a: (-a['overlap_len_m'],tuple(a['room_ids'])))
        changed=False
        for target in candidates[:4]:
            lo,hi=target['overlap_interval_m']; width=door['door_width_m']
            margin=max(.30,float(plan.get('wall_thickness_m',.2))+.10)
            if hi-lo < width+2*margin: continue
            # Prefer the end closest to the old entrance, minimizing approach change.
            tangent=0 if target['wall_orientation']=='H' else 1
            old_mid=(sum(door['door_interval_m'])/2 if door['wall_orientation']==target['wall_orientation']
                     else door['wall_line_m'])
            starts=sorted([lo+margin,hi-margin-width], key=lambda s:abs(s+width/2-old_mid))
            for start in starts:
                interval=[round(start,3),round(start+width,3)]
                if any(_same_wall(target,d) and min(interval[1],d['door_interval_m'][1])-
                       max(interval[0],d['door_interval_m'][0])>-.10 for d in plan['doors'] if d is not door): continue
                snapshot=copy.deepcopy(plan)
                before=copy.deepcopy(door)
                door.update(room_ids=list(target['room_ids']),room_types=list(target['room_types']),
                            door_id='door__'+'__'.join(target['room_ids']),
                            wall_orientation=target['wall_orientation'],wall_line_m=target['wall_line_m'],
                            door_interval_m=interval,source='adaptive_generated_hall_access_v1')
                old.pop('door_id',None);old.pop('door_interval_m',None)
                old['connection_kind']='solid_wall_adaptive_living_furniture'
                target.update(door_id=door['door_id'],door_interval_m=interval,
                              connection_kind='selected_single_room_access')
                if _components(plan)!=_components(snapshot):
                    plan.clear();plan.update(snapshot)
                    return  # Defensive rollback; never continue with stale references.
                report.append(dict(before=before,after=copy.deepcopy(door),
                                   reason='generated_bedroom_access_to_adjacent_hall_frees_living_wall'))
                changed=True;break
            if changed:break


DOOR_MIN_JAMB_M = .05   # solid wall kept between a door and the face of the perpendicular wall at its segment end


def ensure_door_jambs(plan, min_jamb_m=DOOR_MIN_JAMB_M):
    """Keep every non-fixed interior door clear of the perpendicular walls at the ends of its shared wall.

    A door whose edge lies within half a wall thickness (plus a jamb) of a room corner leaves a wall stub only a
    centimetre long; the meshed shell then has a notch beside the frame and the saved-opening check fails. The door is
    slid inward along the same wall. Its width is never changed: ordinary openings are contracted to their declared
    width downstream. A shared wall too short for the door plus both jambs is left unchanged and reported.
    Returns a new plan."""
    result = copy.deepcopy(plan)
    rooms = {r['room_id']: r for r in result.get('rooms', [])}
    margin = float(result.get('wall_thickness_m', .2)) / 2 + float(min_jamb_m)
    changes = []
    for door in result.get('doors', []):
        ids = door.get('room_ids') or []
        interval = _finite_interval(door.get('door_interval_m'))
        if (_fixed(door) or len(ids) != 2 or not all(r in rooms for r in ids) or interval is None
                or door.get('exterior') or 'exterior' in (door.get('room_types') or [])
                or door.get('wall_orientation') not in ('H', 'V')):
            continue
        tangent = 1 if door['wall_orientation'] == 'V' else 0
        a, b = (rooms[r]['bounds_m'] for r in ids)
        seg_lo, seg_hi = max(a[tangent], b[tangent]), min(a[tangent + 2], b[tangent + 2])
        lo, hi = interval
        if lo - seg_lo >= margin - 1e-6 and seg_hi - hi >= margin - 1e-6:
            continue
        width = new_width = hi - lo
        record = dict(door_id=door.get('door_id'), before_interval_m=[lo, hi], shared_wall_m=[seg_lo, seg_hi],
                      required_margin_m=round(margin, 4))
        if seg_hi - seg_lo - 2 * margin < width - 1e-6:
            changes.append(dict(record, status='unchanged_shared_wall_too_short'))
            continue
        center = min(max((lo + hi) / 2, seg_lo + margin + new_width / 2), seg_hi - margin - new_width / 2)
        new = [round(center - new_width / 2, 4), round(center + new_width / 2, 4)]
        clash = any(other is not door and _same_wall(door, other) and other.get('door_interval_m')
                    and min(new[1], other['door_interval_m'][1]) - max(new[0], other['door_interval_m'][0]) > -.10
                    for other in result.get('doors', []))
        if clash:
            changes.append(dict(record, status='unchanged_neighbour_door'))
            continue
        door['door_interval_m'] = new
        for adjacency in result.get('topology_adjacencies', []):
            if adjacency.get('door_id') and adjacency.get('door_id') == door.get('door_id'):
                adjacency['door_interval_m'] = list(new)
        changes.append(dict(record, status='adjusted', after_interval_m=new))
    if changes:
        result.setdefault('adaptive_shell_door_jambs', []).extend(changes)
    return result


def _exterior_spans(plan, room, window, corner_margin_m=.2):
    from engine.source.scripts.internal.scene_generation.window_rules import MIN_OPENING_GAP_M

    b=room['bounds_m'];axis=0 if window['wall_orientation']=='V' else 1;tangent=1-axis
    line=window['wall_line_m']
    if min(abs(line-b[axis]),abs(line-b[axis+2]))>1e-5:return []
    side=1 if abs(line-b[axis+2])<1e-5 else -1
    spans=[(b[tangent],b[tangent+2])]
    for other in plan['rooms']:
        if other['room_id']==room['room_id']:continue
        ob=other['bounds_m']
        # Shared/intersecting neighboring room projection is never exterior.
        touches=(ob[axis]-0.1 <= line < ob[axis+2]-1e-5 if side>0
                 else ob[axis]+1e-5 < line <= ob[axis+2]+0.1)
        if touches:spans=_subtract(spans,(ob[tangent],ob[tangent+2]))
    # Native RPLAN topology merges nearby boundaries; those spans remain
    # interior even when the raw rectangles have a small gap between them.
    for adj in plan.get('topology_adjacencies',[]):
        if (room['room_id'] in adj.get('room_ids',[]) and adj.get('wall_orientation')==window['wall_orientation']
                and abs(adj['wall_line_m']-line)<=.29+1e-6):
            spans=_subtract(spans,adj['overlap_interval_m'])
    spans=[(lo+corner_margin_m,hi-corner_margin_m) for lo,hi in spans
           if hi-lo>2*corner_margin_m]
    for other in plan.get('windows',[])+plan.get('doors',[]):
        if other is window or not _same_wall(window,other):continue
        interval=other.get('window_interval_m',other.get('door_interval_m'))
        if interval:spans=_subtract(spans,(interval[0]-MIN_OPENING_GAP_M,interval[1]+MIN_OPENING_GAP_M))
    return spans


def _finite_interval(value):
    try:
        if len(value) != 2 or not all(math.isfinite(float(v)) for v in value):
            return None
    except (TypeError, ValueError):
        return None
    return [float(value[0]), float(value[1])]


def _front_door_snap_limit_m():
    try:
        value = float(os.environ.get('RHG_FRONT_DOOR_MAX_SNAP_M', '1.5'))
    except (TypeError, ValueError):
        return 1.5
    return value if math.isfinite(value) and value >= 0 else 1.5


def _front_door_snap_candidate(interval, spans, width=1.0):
    lo, hi = interval
    center = (lo + hi) / 2.0
    candidates = []
    for start, end in spans:
        if end - start < width - 1e-6:
            continue
        candidate_start = min(max(center - width / 2.0, start), end - width)
        candidate = [round(candidate_start, 6), round(candidate_start + width, 6)]
        candidates.append((abs(candidate_start + width / 2.0 - center), candidate))
    return min(candidates, key=lambda item: item[0]) if candidates else None


def _resize_windows(plan, report):
    from engine.source.scripts.internal.scene_generation import window_rules
    rooms={r['room_id']:r for r in plan['rooms']};thickness=float(plan.get('wall_thickness_m',.2))
    for w in plan.get('windows',[]):
        room=rooms[w['room_id']]
        if 'bedroom' not in room.get('room_type','') or _fixed(w):continue
        if w.get('source')!='v14_4_exterior_daylight_ventilation_glazing':continue
        spans=_exterior_spans(plan,room,w)
        if not spans:
            report.append(dict(window_id=w['window_id'],status='no_legal_exterior_interval'));continue
        b=room['bounds_m'];axis=1 if w['wall_orientation']=='V' else 0
        height=min(1.5,float(plan.get('wall_height_m',3))-.25-.9)
        if height<=0:continue
        area=max(0,b[2]-b[0]-thickness)*max(0,b[3]-b[1]-thickness)
        target=max((b[axis+2]-b[axis]-thickness)*.5,area*.18/height)
        middle=sum(w['window_interval_m'])/2
        spans.sort(key=lambda s:(not (s[0]<=middle<=s[1]),-(s[1]-s[0]),s[0]))
        lo,hi=spans[0];available=hi-lo
        tiers=[v for v in (1.8,2.2,2.4) if v<=available+1e-6]
        choices=[v for v in tiers if v>=target-1e-6]
        width=min(choices) if choices else max(tiers) if tiers else min(w['window_width_m'],available)
        if width<=0:continue
        old=copy.deepcopy(w);center=(lo+hi)/2
        w.update(window_interval_m=[round(center-width/2,3),round(center+width/2,3)],
                 window_width_m=round(width,3),sill_height_m=.9,head_height_m=round(.9+height,3))
        w['glazing']=window_rules.glazing(w,float(plan.get('wall_height_m',3)))
        report.append(dict(window_id=w['window_id'],before_width_m=old['window_width_m'],
                           chosen_width_m=w['window_width_m'],target_width_m=round(target,3),
                           status='standard_size' if choices else 'largest_standard_below_target' if tiers else 'compact_legal_fallback',
                           daylight_qualified=False))


def adapt_generated_shell(plan):
    result=copy.deepcopy(plan)
    if result.get('adaptive_shell',{}).get('schema')==VERSION:return result
    report=dict(schema=VERSION,authority='new_generated_openings_only',door_changes=[],window_changes=[],
                connected_before=_components(result),physical_qualified=False)
    _relocate_doors(result,report['door_changes'])
    _resize_windows(result,report['window_changes'])
    report['connected_after']=_components(result)
    result['adaptive_shell']=report
    return result


def _reconcile_front_windows(plan, door, rooms, authored_windows):
    """Give the real entrance priority over unfixed native glazing on its wall."""
    from engine.source.scripts.internal.scene_generation.window_rules import MIN_OPENING_GAP_M

    lo,hi=door['door_interval_m']
    protected={w.get('window_id') for w in authored_windows}
    generated_sources={'v14_4_exterior_daylight_ventilation_glazing',
                       'window_rules_v1_second_window_for_daylight_ratio'}
    for window in list(plan.get('windows', [])):
        if (window.get('source') not in generated_sources or _fixed(window) or
                window.get('window_id') in protected or not _same_wall(door,window)):
            continue
        a,b=window['window_interval_m']
        if max(a-hi,lo-b)>=MIN_OPENING_GAP_M-1e-6:
            continue
        width=b-a
        spans=_exterior_spans(plan,rooms[window['room_id']],window)
        starts=[min(max(a,s),t-width) for s,t in spans if t-s>=width-1e-6]
        if starts:
            start=min(starts,key=lambda v:abs(v-a))
            window['window_interval_m']=[round(start,6),round(start+width,6)]
        else:
            plan['windows'].remove(window)


def restore_authored_openings(generated, source):
    """Reconcile supplied openings after topology discovery, before meshing.

    Invalid supplied geometry is reported instead of silently moving a fixed
    opening. Partial authored lists replace their corresponding generated pair.
    RPLAN interior doors additionally replace other native access doors of the
    same private/service room. RPLAN front doors replace the native exterior
    entry when possible, snapping a partially out-of-range interval or
    recording a native-entry fallback when it cannot be used. The caller must
    validate the resulting graph and fall back to its native snapshot if those
    replacements disconnect it.
    """
    result=copy.deepcopy(generated)
    rooms={r['room_id']:r for r in result['rooms']}
    rplan_private=set()
    has_rplan_front=any(d.get('source')=='rplan_png_front_door' for d in source.get('doors', []))
    authored_windows=copy.deepcopy(source.get('windows',[]))
    if has_rplan_front:
        # Front-door validation must see final supplied glazing, including a
        # window that replaces a conflicting native window on the same wall.
        result['windows']=[w for w in result.get('windows',[]) if not any(
            w.get('room_id')==s.get('room_id') and _same_wall(w,s) for s in authored_windows)]
        result['windows'].extend(authored_windows)
    native_front_doors=[copy.deepcopy(d) for d in result.get('doors',[])
                        if d.get('source')=='v14_3_public_exterior_entry']
    front_windows_snapshot=copy.deepcopy(result.get('windows',[]))

    def front_door_fallback(door, reason, spans):
        # A failed authored front-door attempt must leave the native entry and
        # the pre-attempt glazing in place for the caller's connectivity check.
        result['windows']=copy.deepcopy(front_windows_snapshot)
        result['doors']=[d for d in result.get('doors',[])
                         if d.get('source')!='v14_3_public_exterior_entry' and
                         not (d.get('exterior') or 'exterior' in (d.get('room_types') or []))]
        result['doors'].extend(copy.deepcopy(native_front_doors))
        result['authored_front_door_fallback']=dict(
            door_id=door.get('door_id'), reason=reason,
            interval=_finite_interval(door.get('door_interval_m')),
            legal_intervals=[[round(a,6),round(b,6)] for a,b in spans])

    def front_legal_spans(door, room_id):
        if room_id not in rooms or door.get('wall_orientation') not in ('H','V'):
            return []
        try:
            if not math.isfinite(float(door['wall_line_m'])):
                return []
        except (KeyError,TypeError,ValueError):
            return []
        return _exterior_spans(result, rooms[room_id], door, corner_margin_m=.1)

    for supplied in source.get('doors',[]):
        door=copy.deepcopy(supplied);ids=door.get('room_ids',[])
        rplan=door.get('source')=='rplan_png_interior_door'
        rplan_front=door.get('source')=='rplan_png_front_door'
        if has_rplan_front and not rplan_front and (door.get('source')=='v14_3_public_exterior_entry' or
                door.get('exterior') or 'exterior' in (door.get('room_types') or [])):
            continue
        if rplan_front:
            room_id=ids[0] if isinstance(ids,(list,tuple)) and len(ids)==1 else None
            exterior=bool(door.get('exterior')) or 'exterior' in (door.get('room_types') or [])
            if room_id not in rooms or not exterior:
                front_door_fallback(door,'invalid_exterior_geometry_or_width',[])
                continue
            try:
                lo,hi=door['door_interval_m']
                wall_line=float(door['wall_line_m']);width=float(door['door_width_m'])
                lo=float(lo);hi=float(hi)
                geometry_valid=(door.get('wall_orientation') in ('H','V') and lo<hi and
                    all(math.isfinite(v) for v in (lo,hi,wall_line,width)) and
                    abs(width-1.0)<=1e-6 and abs(hi-lo-1.0)<=1e-6)
            except (KeyError,TypeError,ValueError):
                geometry_valid=False
            if not geometry_valid:
                front_door_fallback(door,'invalid_exterior_geometry_or_width',
                                    front_legal_spans(door,room_id))
                continue
            # Native topology adds an entry after internal doors are selected.
            # Remove every native entry before validating the authored interval,
            # so a different room or wall can replace it cleanly.
            result['doors']=[d for d in result.get('doors', [])
                             if d.get('source')!='v14_3_public_exterior_entry' and
                             d.get('door_id')!=door.get('door_id') and
                             not (d.get('exterior') or 'exterior' in (d.get('room_types') or []))]
            room=rooms[room_id]
            # The native windows were placed around the old entry. Only
            # generated, unfixed glazing may yield to this authored entrance.
            result['doors'].append(door)
            _reconcile_front_windows(result,door,rooms,source.get('windows',[]))
            result['doors'].remove(door)
            spans=_exterior_spans(result, room, door, corner_margin_m=.1)
            if not any(a-1e-6<=lo and hi<=b+1e-6 for a,b in spans):
                candidate=_front_door_snap_candidate((lo,hi),spans,width=1.0)
                if candidate is None:
                    front_door_fallback(door,'no_legal_exterior_interval',spans)
                    continue
                snap_distance,candidate_interval=candidate
                if snap_distance>_front_door_snap_limit_m()+1e-6:
                    front_door_fallback(door,'snap_distance_exceeds_limit',spans)
                    continue
                door['snapped_from_interval_m']=[round(lo,6),round(hi,6)]
                door['snap_distance_m']=round(snap_distance,6)
                door['snap_reason']='outside_legal_exterior_interval'
                door['door_interval_m']=candidate_interval
                door['door_width_m']=1.0
            result['doors']=[d for d in result.get('doors', [])
                             if d.get('door_id')!=door.get('door_id') and
                             not (d.get('exterior') or 'exterior' in (d.get('room_types') or []))]
            result['doors'].append(door)
            continue
        if not ids or any(r not in rooms for r in ids):raise ValueError('authored door room missing')
        # These source records describe interior swing doors only. Never turn
        # a native entry, public opening or balcony portal into one.
        if rplan and (len(ids)==1 or any(rooms[r].get('room_type')=='balcony' for r in ids)):
            continue
        if len(ids)==2:
            target=next((a for a in result['topology_adjacencies'] if set(a['room_ids'])==set(ids)),None)
            # Mixed libraries may supply a superseded default after the real
            # door. Skip only those defaults; keep all other authored ordering.
            if (door.get('source')=='circulation_graph_selected_v8' and rplan_private.intersection(ids)
                    and not any(rooms[r].get('room_type')=='balcony' for r in ids)
                    and not (target and (target.get('open_connection') or target.get('open_interval_m')))):
                continue
            if rplan and target is not None and (target.get('open_connection') or target.get('open_interval_m')):
                continue
            if target is None or not _same_wall(target,door):raise ValueError('authored door is not on shared wall')
            lo,hi=door['door_interval_m'];a,b=target['overlap_interval_m']
            if not a<=lo<hi<=b:raise ValueError('authored door outside shared wall')
            if rplan:
                private={r for r in ids if 'bedroom' in rooms[r].get('room_type','') or
                         rooms[r].get('room_type') in ('bathroom','kitchen')}
                rplan_private.update(private)
                removed=[]
                for old in result.get('doors',[]):
                    owners=old.get('room_ids',[])
                    if (old.get('source')!='circulation_graph_selected_v8' or len(owners)!=2 or
                            not private.intersection(owners) or
                            any(rooms[r].get('room_type')=='balcony' for r in owners)):
                        continue
                    adj=next((a for a in result['topology_adjacencies'] if set(a['room_ids'])==set(owners)),None)
                    if adj is not None and (adj.get('open_connection') or adj.get('open_interval_m')):
                        continue
                    removed.append(old)
                removed_ids={d['door_id'] for d in removed}
                result['doors']=[d for d in result.get('doors',[]) if d['door_id'] not in removed_ids]
                for adj in result['topology_adjacencies']:
                    if adj is not target and adj.get('door_id') in removed_ids:
                        adj.pop('door_id',None);adj.pop('door_interval_m',None)
                        adj['connection_kind']='solid_wall_replaced_by_authored_door'
            target.update(door_id=door['door_id'],door_interval_m=list(door['door_interval_m']),
                          open_connection=False,connection_kind='authored_fixed_door')
            for key in ('open_interval_m','clear_width_m'):target.pop(key,None)
        elif len(ids)!=1:raise ValueError('authored door must have one or two rooms')
        result['doors']=[d for d in result.get('doors',[]) if d.get('door_id')!=door['door_id'] and set(d['room_ids'])!=set(ids)]+[door]
    if not has_rplan_front:
        result['windows']=[w for w in result.get('windows',[]) if not any(w.get('room_id')==s.get('room_id') and _same_wall(w,s) for s in authored_windows)]
        result['windows'].extend(authored_windows)
    for window in authored_windows:
        if window.get('room_id') not in rooms:raise ValueError('authored window room missing')
        lo,hi=window['window_interval_m']
        spans=_exterior_spans(result,rooms[window['room_id']],window)
        if not any(a-1e-6<=lo<hi<=b+1e-6 for a,b in spans):
            raise AuthoredWindowValidationError(
                _invalid_window_diagnostic(result, rooms[window['room_id']], window, spans))
    return result