File size: 6,667 Bytes
18196ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Wall stage of the conversion pipeline: one bundle segment per physical wall.

Functions
---------
build_wall_segments - discover walls and build their bundle segments

Designed to run in a background thread alongside the floor stages: all
analysis is at working resolution, and full-resolution work is limited to
each wall's own pixels (mask upscale, index encoding). Each wall's texture
mapping is an exact 3x3 plane transform, so no per-pixel UV is shipped.
"""

from __future__ import annotations

import time
from dataclasses import dataclass, field

import cv2
import numpy as np

from config.runtime import ENABLE_FAST_SHADOW_TRANSFER, ENABLE_SHADING_TRANSFER
from config.surface import WALL_UV_MIN_COVERAGE
from services.geometry.camera import pixel_intrinsics_from_model
from services.geometry.plane_uv import plane_to_image_transform, ray_plane_uv, upright_plane_basis
from services.lighting.shading import build_fast_shadow_lighting_maps, build_luminance_lighting_maps
from services.pipeline.bundle_assembly import build_wall_segment
from services.wall.components import WallComponent, WallDiscovery, discover_wall_components
from services.wall.plane import estimate_wall_plane

# Pixels sampled per wall to measure plane coverage and size.
MAPPING_SAMPLE_PIXELS = 20000


@dataclass
class WallResult:
    segments: list[dict] = field(default_factory=list)
    timings_ms: dict[str, float] = field(default_factory=dict)

    @property
    def detail(self) -> str:
        parts = [f"walls={len(self.segments)}"]
        parts += [f"{name}={ms:.0f}ms" for name, ms in self.timings_ms.items()]
        return " ".join(parts)


def build_wall_segments(
    img_np: np.ndarray,
    seg_map: np.ndarray,
    geometry: dict | None,
    min_area: int,
    segmentation_model: str,
    first_segment_id: int = 1,
) -> WallResult:
    """Discover walls and return their bundle segments (ids start at first_segment_id)."""
    result = WallResult()
    started = time.perf_counter()
    discovery = discover_wall_components(seg_map, geometry, min_area)
    result.timings_ms["discovery"] = (time.perf_counter() - started) * 1000
    if not discovery.components:
        return result

    started = time.perf_counter()
    full_h, full_w = seg_map.shape[:2]
    intrinsics = (
        pixel_intrinsics_from_model(geometry.get("intrinsics"), full_w, full_h)
        if geometry is not None else None
    )
    work_h, work_w = discovery.components[0].work_mask.shape[:2]
    work_image = cv2.resize(img_np, (work_w, work_h), interpolation=cv2.INTER_AREA)

    for index, component in enumerate(discovery.components):
        segment = _build_segment(
            component,
            discovery,
            index=index,
            segment_id=first_segment_id + index,
            intrinsics=intrinsics,
            geometry=geometry,
            img_np=img_np,
            work_image=work_image,
            segmentation_model=segmentation_model,
        )
        if segment is not None:
            result.segments.append(segment)
    for segment in result.segments:
        segment["metadata"]["wallComponentCount"] = len(result.segments)
    result.timings_ms["segments"] = (time.perf_counter() - started) * 1000
    return result


def _build_segment(
    component: WallComponent,
    discovery: WallDiscovery,
    *,
    index: int,
    segment_id: int,
    intrinsics: np.ndarray | None,
    geometry: dict | None,
    img_np: np.ndarray,
    work_image: np.ndarray,
    segmentation_model: str,
) -> dict | None:
    wall_indices = np.flatnonzero(component.mask.ravel()).astype(np.uint32)
    mapping = _wall_plane_mapping(component, discovery.vertical, wall_indices, intrinsics)

    # With an exact plane mapping, skip estimate_wall_plane's second RANSAC fit
    # and keep only its cheap contour quad as a fallback homography.
    homography, plane = estimate_wall_plane(component.mask, None if mapping else geometry)
    if homography is None or plane is None:
        return None
    if mapping:
        plane.update(mapping)
        plane["geometryProvider"] = (geometry or {}).get("provider")

    return build_wall_segment(
        wall_id=segment_id,
        wall_index=index,
        wall_indices=wall_indices,
        homography=homography,
        plane=plane,
        lighting_maps=_wall_lighting(component, img_np, work_image),
        segmentation_model=segmentation_model,
    )


def _wall_plane_mapping(
    component: WallComponent,
    vertical: np.ndarray,
    wall_indices: np.ndarray,
    intrinsics: np.ndarray | None,
) -> dict | None:
    """Exact metric plane mapping for the wall, or None to use the contour homography.

    Coverage and the wall's size in metres are measured on a pixel sample; the
    renderer gets the 3x3 surfaceTransform, which is exact for every pixel.
    """
    if component.plane is None or intrinsics is None or not len(wall_indices):
        return None
    u_axis, v_axis = upright_plane_basis(component.plane.normal, vertical)
    sample = wall_indices[:: max(1, len(wall_indices) // MAPPING_SAMPLE_PIXELS)]
    uv, hit = ray_plane_uv(
        sample, component.mask.shape[1], intrinsics,
        component.plane.origin, component.plane.normal, u_axis, v_axis,
    )
    coverage = float(hit.mean())
    if coverage < WALL_UV_MIN_COVERAGE:
        return None

    uv_min = np.nanmin(uv, axis=0)
    uv_max = np.nanmax(uv, axis=0)
    transform = plane_to_image_transform(
        intrinsics, component.plane.origin, component.plane.normal, u_axis, v_axis,
    ).flatten().tolist()
    return {
        "floorTransform": transform,
        "surfaceTransform": transform,
        "surfaceUAxis": u_axis.astype(float).tolist(),
        "surfaceVAxis": v_axis.astype(float).tolist(),
        "planeNormal": component.plane.normal.astype(float).tolist(),
        "planeOrigin": component.plane.origin.astype(float).tolist(),
        "surfaceWidthMeters": float(max(uv_max[0] - uv_min[0], 0.05)),
        "surfaceHeightMeters": float(max(uv_max[1] - uv_min[1], 0.05)),
        # The renderer treats the transform as metric at >= 0.35 confidence.
        "geometryConfidence": coverage,
    }


def _wall_lighting(component: WallComponent, img_np: np.ndarray, work_image: np.ndarray) -> dict | None:
    """Same lighting switches as the floor; the fast path runs at working resolution."""
    if ENABLE_FAST_SHADOW_TRANSFER:
        maps = build_fast_shadow_lighting_maps(work_image, component.work_mask)
        if maps and maps.get("shadeMap") is not None:
            return maps
    if ENABLE_SHADING_TRANSFER:
        return build_luminance_lighting_maps(img_np, component.mask)
    return None