File size: 21,268 Bytes
1fe7075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7a38a3
 
 
1fe7075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Main pipeline orchestrator: build_segmentation_bundle."""

from __future__ import annotations

import io
import time

import cv2
import numpy as np
from PIL import Image

from config.runtime import (
    ENABLE_FAST_SHADOW_TRANSFER,
    ENABLE_INTRINSIC_SHADING,
    ENABLE_SHADING_TRANSFER,
    ENABLE_WALL_SEGMENTS,
)
from models.depth import estimate_scene_geometry
from models.loader import _load_intrinsic_model
from models.segmentation import active_model_metadata, active_segmentation_model_name, run_segmentation
from services.debug.capture import PipelineDebugCapture
from services.direction.analysis import floor_direction_geometry_inputs
from services.floor.edge_coverage import scaled_odd_kernel_size
from services.floor.mask import build_floor_surface_mask, clean_floor_mask, wall_subtract
from services.floor.detection import estimate_floor_plane
from services.floor.edge_refinement import refine_surface_edges
from services.geometry.multi_plane import geometry_point_maps
from services.geometry.uv_mapping import build_surface_uv_mapping
from services.lighting.intrinsic import build_intrinsic_lighting_maps
from services.lighting.shading import (
    build_fast_shadow_lighting_maps,
    build_luminance_lighting_maps,
    lighting_map_statistics,
)
from services.pipeline.packaging import encode_bundle_image_data_url, foreground_occlusion_mask
from services.pipeline.bundle_assembly import build_fallback_segments, build_floor_segment
from services.pipeline import debug_stages
from services.pipeline.inference_utils import downscale_for_inference
from services.wall.pipeline import WallResult, build_wall_segments
from direction_finder import find_floor_direction
import state
from state import FLOOR_SURFACE_CLASSES, PRIMARY_FLOOR_CLASSES, REPLACEABLE_SOFT_FLOOR_CLASSES, class_ids
from enums import FloorMaskSource, PipelinePhase
from utils import mask_to_indices, seg_class_mask, timed_stage

from enums import TextureMappingMode, TextureMappingReason

_DEFAULT_MAPPING_META = {
    "surfaceUvEnabled": False, "textureMappingMode": TextureMappingMode.REGULARIZED_FLOOR_PLANE,
    "textureMappingReason": TextureMappingReason.SURFACE_UV_UNAVAILABLE, "surfaceUvCoverage": 0.0,
    "surfaceUvFinitePixels": 0, "surfaceUvTotalPixels": 0, "surfaceUvNeighborCount": 0,
    "surfaceUvMedianNeighborDelta": None, "surfaceUvP95NeighborDelta": None,
    "surfaceUvP99NeighborDelta": None, "surfaceUvJumpLimit": None,
    "surfaceUvBadNeighborRatio": None, "surfaceUvPlaneBoundaryRatio": None,
    "surfaceUvAssignedPlaneCount": 0,
}


def build_segmentation_bundle(
    contents: bytes,
    debug: PipelineDebugCapture | None = None,
    progress_callback=None,
    include_pixels: bool = True,
):
    t_start = time.perf_counter()
    d = debug  # shorthand
    stage_times: list[tuple[str, float, str]] = []  # (stage_name, seconds, detail)

    def _log_stage(name: str, t0: float, detail: str = ""):
        elapsed = time.perf_counter() - t0
        stage_times.append((name, elapsed, detail))

    # Time job-progress updates so they show as their own report line instead
    # of hiding inside "Pipeline Overhead". Every call below sits between
    # timed stages, never inside one, so nothing is counted twice.
    progress_elapsed = 0.0
    progress_calls = 0
    report_progress = progress_callback

    def progress_callback(phase, phase_progress):
        nonlocal progress_elapsed, progress_calls
        if report_progress is None:
            return
        started = time.perf_counter()
        try:
            report_progress(phase, phase_progress)
        finally:
            progress_elapsed += time.perf_counter() - started
            progress_calls += 1

    t0 = time.perf_counter()
    img = Image.open(io.BytesIO(contents)).convert("RGB")
    img_np = np.array(img)
    h, w = img_np.shape[:2]
    min_floor_area = max(1200, int(w * h * 0.015))

    # Downscale for faster inference β€” masks/depth are output at full resolution
    inf_img, inf_np, inf_scale = downscale_for_inference(img, img_np)
    inf_h, inf_w = inf_np.shape[:2]
    el = (time.perf_counter() - t0) * 1000
    if inf_scale < 1.0:
        _log_stage("Image Loading", t0, f"{w}x{h} (inference@{inf_w}x{inf_h})")
    else:
        _log_stage("Image Loading", t0, f"{w}x{h}")
    if d:
        debug_stages.record_source_image(d, img_np, w, h, min_floor_area, el)

    # --- Segmentation + Geometry (parallel on CPU, sequential on single GPU) ---
    if progress_callback:
        progress_callback(PipelinePhase.SEGMENTATION, 0)

    use_parallel = state.device.type == "cpu"
    if use_parallel:
        from concurrent.futures import ThreadPoolExecutor
        t0 = time.perf_counter()
        with ThreadPoolExecutor(max_workers=2) as pool:
            seg_future = pool.submit(run_segmentation, inf_img, inf_np, h, w)
            geo_future = pool.submit(estimate_scene_geometry, inf_img, inf_np, w, h)
            seg_map = seg_future.result()
            geometry = geo_future.result()
        t_seg_geo = time.perf_counter() - t0
        _log_stage("Segmentation+Geometry (parallel)", t0)
    else:
        t0 = time.perf_counter()
        seg_map = run_segmentation(inf_img, inf_np, target_h=h, target_w=w)
        _log_stage("Segmentation", t0)
        t0 = time.perf_counter()
        geometry = estimate_scene_geometry(inf_img, inf_np, w, h)
        _log_stage("Geometry", t0, f"provider={geometry.get('provider')}")

    depth = geometry.get("depth")
    el = (time.perf_counter() - t0) * 1000
    if d:
        debug_stages.record_segmentation(d, img_np, seg_map, state.segmentation_backend, w, h, el)
        debug_stages.record_geometry(d, depth, None, geometry, el)
    if progress_callback:
        progress_callback(PipelinePhase.SEGMENTATION, 100)
        progress_callback(PipelinePhase.GEOMETRY, 55)

    # --- Walls: one background thread, overlapping every floor stage below ---
    # All wall work runs at working resolution (see services.wall.pipeline), so
    # it normally finishes before the floor does and "Wall Wait" stays ~0.
    wall_future = None
    wall_pool = None
    if ENABLE_WALL_SEGMENTS:
        from concurrent.futures import ThreadPoolExecutor as _WallPool
        wall_pool = _WallPool(max_workers=1, thread_name_prefix="walls")
        wall_future = wall_pool.submit(
            build_wall_segments, img_np, seg_map, geometry, min_floor_area,
            active_segmentation_model_name(), 1,
        )

    # --- Encode room image in background (overlaps with masking + later stages) ---
    # Skipped for job conversions: the split vizbundle references the uploaded
    # image by URL, so a full-resolution re-encode would be discarded.
    _img_pool = None
    _pixels_b64_future = None
    if include_pixels:
        from concurrent.futures import ThreadPoolExecutor as _TP
        _img_pool = _TP(max_workers=1)
        _pixels_b64_future = _img_pool.submit(encode_bundle_image_data_url, img_np)

    # --- Floor masking (SAM2 removed β€” morphological cleanup only) ---
    if progress_callback:
        progress_callback(PipelinePhase.MASKING, 0)
    t0 = time.perf_counter()
    raw_primary = seg_class_mask(seg_map, class_ids(PRIMARY_FLOOR_CLASSES))
    floor_mask = clean_floor_mask(wall_subtract(raw_primary.copy(), seg_map, dilation=0))
    floor_mask_source = FloorMaskSource.PRIMARY_FLOOR
    if int(floor_mask.sum()) < min_floor_area:
        floor_mask = clean_floor_mask(wall_subtract(
            seg_class_mask(seg_map, class_ids(FLOOR_SURFACE_CLASSES)), seg_map, dilation=0))
        floor_mask_source = FloorMaskSource.FLOOR_SURFACE_FALLBACK
    cleaned = floor_mask.copy()
    sam_metadata = {"samRefinementEnabled": False, "samRefinementApplied": False, "samRefinementReason": "removed"}
    el = (time.perf_counter() - t0) * 1000
    _log_stage("Floor Masking", t0, f"source={floor_mask_source}")
    if d:
        debug_stages.record_floor_mask(d, img_np, raw_primary, cleaned, floor_mask, floor_mask_source, sam_metadata, el)
    if progress_callback:
        progress_callback(PipelinePhase.MASKING, 100)

    t0 = time.perf_counter()
    homography, plane = estimate_floor_plane(floor_mask, img_np, geometry)
    el = (time.perf_counter() - t0) * 1000
    _log_stage("Plane Fitting", t0)
    if d:
        debug_stages.record_plane(d, img_np, plane, homography, el)
    if progress_callback:
        progress_callback(PipelinePhase.GEOMETRY, 100)

    # --- Surface mask ---
    t0 = time.perf_counter()
    geometry_maps_started = time.perf_counter()
    prepared_geometry_maps = geometry_point_maps(floor_mask, geometry)
    geometry_maps_ms = (time.perf_counter() - geometry_maps_started) * 1000
    quad = np.asarray(plane["quad"], dtype=np.float32).reshape(4, 2) if plane and plane.get("quad") else None
    surface_mask, edge_metadata = build_floor_surface_mask(
        floor_mask,
        seg_map,
        quad,
        depth,
        geometry,
        plane,
        geometry_maps=prepared_geometry_maps,
    )
    unrefined_surface_mask = surface_mask
    surface_mask, edge_alpha_map, refinement_metadata = refine_surface_edges(img_np, surface_mask, seg_map)
    edge_metadata = {**edge_metadata, **refinement_metadata}
    replaced_material_mask = (seg_class_mask(seg_map, class_ids(REPLACEABLE_SOFT_FLOOR_CLASSES)).astype(bool) & (surface_mask > 0)).astype(np.uint8)
    surface_indices = mask_to_indices(surface_mask)
    # One alpha byte per mask pixel, in mask order; the renderer blends the tile with it.
    edge_alpha = edge_alpha_map.reshape(-1)[surface_indices]
    occlusion_mask = foreground_occlusion_mask(surface_mask, seg_map)
    occlusion_indices = mask_to_indices(occlusion_mask)
    el = (time.perf_counter() - t0) * 1000
    surface_timing = edge_metadata.get("surfaceMaskingTimingMs") or {}
    filter_ms = sum(float(surface_timing.get(name) or 0.0) for name in (
        "initialGeometryFilter",
        "postEdgeGeometryFilter",
        "postSoftFloorGeometryFilter",
    ))
    _log_stage(
        "Surface Masking",
        t0,
        f"geometry-prep={geometry_maps_ms:.0f}ms filters={filter_ms:.0f}ms "
        f"edges={float((refinement_metadata.get('edgeRefinementTimingMs') or {}).get('total') or 0.0):.0f}ms",
    )
    if d:
        debug_stages.record_surface(d, img_np, floor_mask, surface_mask, occlusion_mask, edge_metadata, el)

    # --- Surface UV mapping ---
    if progress_callback:
        progress_callback(PipelinePhase.SURFACE_MAPPING, 0)
    t0 = time.perf_counter()
    surface_mapping = build_surface_uv_mapping(
        surface_mask,
        surface_indices,
        geometry,
        geometry_maps=prepared_geometry_maps,
        # Depth is blurry where the floor meets a wall, so the edge pixels the
        # refinement added get their UV from the floor plane instead.
        ray_fill_mask=(surface_mask > 0) & (unrefined_surface_mask == 0),
    )
    use_surface_uv = bool(surface_mapping and surface_mapping.get("useSurfaceUv"))
    mapping_metadata = surface_mapping["metadata"] if surface_mapping is not None else {
        **_DEFAULT_MAPPING_META, "surfaceUvTotalPixels": int(len(surface_indices))}
    el = (time.perf_counter() - t0) * 1000
    uv_timing = mapping_metadata.get("surfaceUvTimingMs") or {}
    uv_detail = f"uv={'yes' if use_surface_uv else 'no'}"
    if uv_timing:
        uv_detail += (
            f" fit={float(uv_timing.get('planeFit') or 0.0):.0f}ms"
            f" assign={float(uv_timing.get('planeAssignment') or 0.0):.0f}ms"
            f" quality={float(uv_timing.get('qualityAnalysis') or 0.0):.0f}ms"
        )
    _log_stage("UV Mapping", t0, uv_detail)
    if d:
        debug_stages.record_surface_mapping(d, h, w, surface_indices, surface_mapping, use_surface_uv, mapping_metadata, el)
    if progress_callback:
        progress_callback(PipelinePhase.SURFACE_MAPPING, 100)

    # --- Lighting ---
    if progress_callback:
        progress_callback(PipelinePhase.LIGHTING, 0)
    t0 = time.perf_counter()
    lighting_maps, shade_map, showroom_shade_map, reflection_map = None, None, None, None
    lighting_source, intrinsic_lighting_used = None, False
    if ENABLE_SHADING_TRANSFER and ENABLE_INTRINSIC_SHADING:
        if state.intrinsic_models is None:
            _load_intrinsic_model()
        if state.intrinsic_models is not None:
            lighting_maps = build_intrinsic_lighting_maps(img_np, surface_mask, replaced_material_mask)
            if lighting_maps and lighting_maps.get("shadeMap") is not None:
                from config.models import INTRINSIC_MODEL_VERSION
                lighting_source, intrinsic_lighting_used = f"intrinsic-{INTRINSIC_MODEL_VERSION}", True
    if ENABLE_FAST_SHADOW_TRANSFER and (not lighting_maps or lighting_maps.get("shadeMap") is None):
        lighting_maps = build_fast_shadow_lighting_maps(
            img_np,
            surface_mask,
            replaced_material_mask,
        )
        if lighting_maps and lighting_maps.get("shadeMap") is not None:
            lighting_source = "fast-luminance"
    if ENABLE_SHADING_TRANSFER and (not lighting_maps or lighting_maps.get("shadeMap") is None):
        lighting_maps = build_luminance_lighting_maps(img_np, surface_mask, replaced_material_mask)
        if lighting_maps and lighting_maps.get("shadeMap") is not None:
            lighting_source = "luminance"
    if lighting_maps:
        shade_map, showroom_shade_map, reflection_map = lighting_maps.get("shadeMap"), lighting_maps.get("showroomShadeMap"), lighting_maps.get("reflectionMap")
    shade_statistics = lighting_map_statistics(shade_map, surface_mask)
    el = (time.perf_counter() - t0) * 1000
    lighting_detail = f"source={lighting_source}"
    if shade_map is not None:
        lighting_detail += f" map={shade_map.shape[1]}x{shade_map.shape[0]}"
    _log_stage("Lighting", t0, lighting_detail)
    if d:
        debug_stages.record_lighting(d, shade_map, showroom_shade_map, reflection_map, surface_mask, lighting_source, el)

    # The semantic wall mask remains useful as a structural cue for floor
    # direction, even when wall surfaces are not emitted in the bundle.
    wall_mask = seg_class_mask(seg_map, class_ids({"wall"}))

    if progress_callback:
        progress_callback(PipelinePhase.LIGHTING, 100)

    # --- Floor direction ---
    if progress_callback:
        progress_callback(PipelinePhase.DIRECTION, 0)
    t0 = time.perf_counter()
    dir_xform = plane.get("floorTransform") if plane and plane.get("floorTransform") and float(plane.get("geometryConfidence") or 0.0) >= 0.35 else homography
    dir_inputs = floor_direction_geometry_inputs(
        surface_mask,
        geometry,
        plane,
        surface_mapping,
        use_surface_uv=use_surface_uv,
        geometry_maps=prepared_geometry_maps,
    )
    struct_mask = seg_class_mask(seg_map, class_ids({"wall", "ceiling", "door", "window", "column", "base", "railing"}))
    sk = scaled_odd_kernel_size(h, w, 0.006, minimum=3)
    struct_mask = cv2.dilate(struct_mask, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (sk, sk)), iterations=1)
    floor_direction = find_floor_direction(
        img_np, surface_mask, wall_mask=wall_mask, structure_mask=struct_mask,
        normals_map=dir_inputs["normalsMap"], geometry_valid_mask=dir_inputs["validMask"],
        intrinsics=dir_inputs["intrinsics"], floor_normal=dir_inputs["floorNormal"],
        render_u_axis=dir_inputs["renderUAxis"], render_v_axis=dir_inputs["renderVAxis"],
        render_transform=dir_xform,
        surface_uv=surface_mapping["uv"] if use_surface_uv else None,
        surface_indices=surface_indices if use_surface_uv else None,
        surface_plane_ids=surface_mapping["planeIds"] if use_surface_uv else None,
    )
    el = (time.perf_counter() - t0) * 1000
    _log_stage("Floor Direction", t0, f"method={floor_direction.get('directionMethod')}")
    if d:
        debug_stages.record_direction(d, img_np, floor_direction, el)
    if progress_callback:
        progress_callback(PipelinePhase.DIRECTION, 100)

    walls = _collect_walls(wall_future, wall_pool, _log_stage)

    # --- Package segments ---
    if progress_callback:
        progress_callback(PipelinePhase.PACKAGING, 0)
    t0 = time.perf_counter()
    models = active_model_metadata(geometry, depth, shade_map, intrinsic_lighting_used)
    segments = []
    if len(surface_indices) >= min_floor_area:
        segments.append(build_floor_segment(
            surface_indices=surface_indices, occlusion_indices=occlusion_indices, edge_alpha=edge_alpha,
            homography=homography, plane=plane, surface_mapping=surface_mapping,
            use_surface_uv=use_surface_uv, shade_map=shade_map,
            showroom_shade_map=showroom_shade_map, reflection_map=reflection_map,
            floor_mask=floor_mask, surface_mask=surface_mask,
            replaced_material_mask=replaced_material_mask, occlusion_mask=occlusion_mask,
            floor_direction=floor_direction, sam_metadata=sam_metadata,
            edge_metadata=edge_metadata, mapping_metadata=mapping_metadata,
            shade_statistics=shade_statistics, lighting_source=lighting_source,
            intrinsic_lighting_used=intrinsic_lighting_used, models=models, depth=depth, geometry=geometry))
    segments.extend(walls.segments)
    if not segments:
        segments = build_fallback_segments(seg_map, depth, models)

    _log_stage("Packaging", t0, f"segments={len(segments)}")
    if progress_callback:
        progress_callback(PipelinePhase.PACKAGING, 100)
    pixels_b64 = None
    if _pixels_b64_future is not None:
        t0 = time.perf_counter()
        pixels_b64 = _pixels_b64_future.result()
        _img_pool.shutdown(wait=False)
        _log_stage("Image Encoding Wait", t0)

    if progress_calls:
        stage_times.append(("Progress Updates", progress_elapsed, f"calls={progress_calls}"))

    total_elapsed = time.perf_counter() - t_start
    accounted_elapsed = sum(elapsed for _, elapsed, _ in stage_times)
    overhead_elapsed = max(0.0, total_elapsed - accounted_elapsed)
    if overhead_elapsed >= 0.001:
        stage_times.append((
            "Pipeline Overhead",
            overhead_elapsed,
            "callbacks, metadata and untimed glue",
        ))

    # ── Print clean timing summary ──
    _print_pipeline_summary(stage_times, total_elapsed, w, h)

    if d:
        d.complete(total_elapsed * 1000)
    pipeline_stages = [
        {"name": name, "elapsed_s": round(elapsed, 3), "detail": detail}
        for name, elapsed, detail in stage_times
    ]
    pipeline_stages.append({
        "name": "TOTAL", "elapsed_s": round(total_elapsed, 3), "detail": f"{w}x{h}",
    })

    return {"width": w, "height": h, "pixels": pixels_b64, "segments": segments,
            "modelName": models["segmentation"]["name"], "models": models,
            "pipelineStages": pipeline_stages,
            # Not part of the bundle: the conversion saves it for "Enhance with AI" (services/enhance).
            "enhanceContext": {"segMap": seg_map}}


def _collect_walls(wall_future, wall_pool, log_stage) -> WallResult:
    """Wait for the background wall thread and log its cost.

    "Wall Wait" is the only time walls add to the pipeline (the floor was
    already done); its detail carries the walls' own (overlapped) timings.
    A wall failure never fails the job: the floor ships without walls.
    """
    if wall_future is None:
        return WallResult()
    t0 = time.perf_counter()
    try:
        walls = wall_future.result()
    except Exception as exc:
        print(f"[WALLS] skipped: wall stage failed ({exc})", flush=True)
        walls = WallResult()
    finally:
        wall_pool.shutdown(wait=False)
    # Wall timings go in the detail, not as their own stages, because they
    # overlapped the floor stages and would otherwise be counted twice.
    log_stage("Wall Wait", t0, walls.detail)
    print(f"[WALLS] {walls.detail}", flush=True)
    return walls


def _print_pipeline_summary(
    stage_times: list[tuple[str, float, str]],
    total_elapsed: float,
    w: int,
    h: int,
):
    """Print a formatted pipeline timing summary to stdout."""
    sep = "─" * 60
    lines = [
        "",
        f"β”Œ{sep}┐",
        f"β”‚ {'PIPELINE TIMING REPORT':^58} β”‚",
        f"β”‚ {'Image: ' + f'{w}x{h}':^58} β”‚",
        f"β”œ{'─' * 30}┬{'─' * 14}┬{'─' * 14}─",
        f"β”‚ {'Stage':<28} β”‚ {'Time':>12} β”‚ {'% Total':>12} β”‚",
        f"β”œ{'─' * 30}β”Ό{'─' * 14}β”Ό{'─' * 14}─",
    ]
    for name, elapsed, detail in stage_times:
        pct = (elapsed / total_elapsed * 100) if total_elapsed > 0 else 0
        time_str = f"{elapsed:.2f}s"
        pct_str = f"{pct:.1f}%"
        label = f"{name} ({detail})" if detail else name
        if len(label) > 28:
            label = label[:27] + "\u2026"
        lines.append(f"β”‚ {label:<28} β”‚ {time_str:>12} β”‚ {pct_str:>12} β”‚")
    lines.append(f"β”œ{'─' * 30}β”Ό{'─' * 14}β”Ό{'─' * 14}─")
    total_str = f"{total_elapsed:.2f}s"
    lines.append(f"β”‚ {'TOTAL':.<28} β”‚ {total_str:>12} β”‚ {'100%':>12} β”‚")
    lines.append(f"β””{'─' * 30}β”΄{'─' * 14}β”΄{'─' * 14}β”˜")
    lines.append("")
    print("\n".join(lines), flush=True)