File size: 17,120 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
"""Sample contact on saved triangles, independently of closed-solid collision.

Default targets must be declared support surfaces. Floor callers with an
unclassified shell can explicitly select the nearest contact plane per ray.
Normals retain saved winding. No welding, closing, convexification or volume
test occurs. Callers still own footprint coverage, provenance and collisions.
"""
from collections import OrderedDict
import hashlib
import math

import numpy as np


_TARGET_CACHE = OrderedDict()
_CACHE_SIZE = 8
_BATCH_SIZE = 256
_SAMPLE_BAND_M = 1e-7
_WALL_PLANE_BINDING_M = 1e-5


def _meshes(values):
    result = []
    for mesh in values:
        vertices = np.asarray(mesh['vertices'], dtype=np.float64)
        faces = np.asarray(mesh['triangles'])
        if (vertices.ndim != 2 or vertices.shape[1] != 3 or not len(vertices)
                or not np.isfinite(vertices).all() or faces.ndim != 2
                or faces.shape[1] != 3 or not len(faces) or faces.dtype.kind not in 'iu'
                or faces.min() < 0 or faces.max() >= len(vertices)):
            raise ValueError('Contact requires finite saved vertices and triangle indices')
        result.append((vertices, np.asarray(faces, dtype=np.int64)))
    return result


def _target(targets):
    """Content-keyed cache invalidates even if callers mutate existing arrays."""
    digest = hashlib.sha256()
    for vertices, faces in targets:
        for array in (vertices, faces):
            digest.update(str(array.shape).encode('ascii'))
            digest.update(array.tobytes(order='C'))
    key = digest.digest()
    if key in _TARGET_CACHE:
        _TARGET_CACHE.move_to_end(key)
        return _TARGET_CACHE[key]
    import trimesh
    from trimesh.ray.ray_triangle import RayMeshIntersector
    vertices, faces, offset = [], [], 0
    for points, indices in targets:
        vertices.append(points)
        faces.append(indices + offset)
        offset += len(points)
    mesh = trimesh.Trimesh(vertices=np.concatenate(vertices), faces=np.concatenate(faces),
                           process=False, validate=False)
    intersector = RayMeshIntersector(mesh)
    cached = (mesh, intersector)
    _TARGET_CACHE[key] = cached
    while len(_TARGET_CACHE) > _CACHE_SIZE:
        _TARGET_CACHE.popitem(last=False)
    return cached


def _finite_number(value):
    return type(value) in (int, float) and math.isfinite(value)


def _room_wall_regions(row, plan):
    """Resolve authored wall faces without consulting entity-to-wall distance."""
    rooms = plan.get('rooms')
    if (not isinstance(rooms, list) or any(not isinstance(r, dict) for r in rooms)
            or len({r.get('room_id') for r in rooms}) != len(rooms)):
        raise ValueError('Missing or ambiguous room inventory')
    rooms = {r.get('room_id'): r for r in rooms}
    room = rooms.get(row.get('room_id'))
    def bounds(record):
        values = record.get('bounds_m') if isinstance(record, dict) else None
        if (not isinstance(values, (list, tuple)) or len(values) != 4
                or not all(_finite_number(v) for v in values)
                or values[0] >= values[2] or values[1] >= values[3]):
            raise ValueError('Wall targeting requires finite authored room bounds')
        return values
    b = bounds(room)
    thickness = plan.get('wall_thickness_m')
    if not _finite_number(thickness) or thickness <= 0:
        raise ValueError('Missing authored wall thickness')
    anchor = row.get('wall_anchor')
    if anchor not in ('E', 'W', 'N', 'S'):
        raise ValueError('Missing wall anchor')
    axis = 0 if anchor in ('E', 'W') else 1
    along = 1-axis
    sign = 1 if anchor in ('E', 'N') else -1
    edge = b[axis+2 if sign > 0 else axis]
    regions = []
    adjacencies = plan.get('topology_adjacencies', [])
    if not isinstance(adjacencies, list):
        raise ValueError('Malformed authored topology')
    for adjacency in adjacencies:
        ids = adjacency.get('room_ids', []) if isinstance(adjacency, dict) else []
        if row['room_id'] not in ids or adjacency.get('wall_orientation') != ('V' if axis == 0 else 'H'):
            continue
        if len(ids) != 2 or len(set(ids)) != 2:
            raise ValueError('Ambiguous wall adjacency')
        other = bounds(rooms.get(next(r for r in ids if r != row['room_id'])))
        if sign*((other[axis]+other[axis+2])-(b[axis]+b[axis+2])) <= 0:
            continue
        line, interval = adjacency.get('wall_line_m'), adjacency.get('overlap_interval_m')
        opposite = other[axis if sign > 0 else axis+2]
        if (not _finite_number(line) or not isinstance(interval, (list, tuple))
                or len(interval) != 2 or not all(_finite_number(v) for v in interval)
                or interval[0] >= interval[1]
                or not min(edge, opposite)-_WALL_PLANE_BINDING_M <= line <= max(edge, opposite)+_WALL_PLANE_BINDING_M):
            raise ValueError('Wall line does not bind the declared room side')
        start, end = max(b[along], interval[0]), min(b[along+2], interval[1])
        if start < end:
            regions.append(dict(axis=axis, plane_m=line-sign*thickness/2,
                                interval_m=[start, end], origin='topology_adjacency'))
    # The complement of authored adjacencies is this room's exterior boundary.
    cursor = b[along]
    for start, end in sorted(region['interval_m'] for region in regions):
        if start > cursor:
            regions.append(dict(axis=axis, plane_m=edge-sign*thickness/2,
                interval_m=[cursor, start], origin='room_boundary'))
        cursor = max(cursor, end)
    if cursor < b[along+2]:
        regions.append(dict(axis=axis, plane_m=edge-sign*thickness/2,
            interval_m=[cursor, b[along+2]], origin='room_boundary'))
    return regions


def wall_face_targets(row, manifest, shell, *, target_mesh_names=None):
    """Select saved structural wall triangles bound to this room/anchor.

    Faces and their holes remain exactly as saved. The coordinate guard binds
    float-exported triangles to an authored plane; it never expands gap policy.
    Explicit source-bound target names remain a contract for legacy manifests
    without floor-plan metadata. They cannot substitute for an invalid room.
    """
    names = set(target_mesh_names) if target_mesh_names is not None else None
    if names is not None and any(sum(m['name'] == n for m in shell) != 1 for n in names):
        raise ValueError('Installation wall target is missing or ambiguous')
    candidates = [m for m in shell if (m['name'] == 'wall' or m['name'].startswith('wall__'))
                  and (names is None or m['name'] in names)]
    if 'floor_plan' not in manifest and names:
        if len(candidates) != len(names):
            raise ValueError('Pinned installation target is not a structural wall')
        return candidates, dict(policy='source_bound_wall_mesh_names_v1',
            room_id=row.get('room_id'), wall_anchor=row['wall_anchor'],
            target_mesh_names=sorted(names), regions=[])
    plan = manifest.get('floor_plan')
    if not isinstance(plan, dict):
        raise ValueError('Missing room installation-wall contract')
    regions = _room_wall_regions(row, plan)
    direction = np.asarray({'E': (1., 0., 0.), 'W': (-1., 0., 0.),
                            'N': (0., 1., 0.), 'S': (0., -1., 0.)}[row['wall_anchor']])
    selected, records = [], []
    for mesh in candidates:
        vertices, faces = _meshes([mesh])[0]
        triangles = vertices[faces]
        normal = np.cross(triangles[:, 1]-triangles[:, 0], triangles[:, 2]-triangles[:, 0])
        length = np.linalg.norm(normal, axis=1)
        facing = normal @ direction < -.5*length
        keep = np.zeros(len(faces), dtype=bool)
        for region in regions:
            axis, plane = region['axis'], region['plane_m']
            start, end = region['interval_m']
            keep |= (facing & (np.max(np.abs(triangles[:, :, axis]-plane), axis=1) <= _WALL_PLANE_BINDING_M)
                & (triangles[:, :, 1-axis].max(axis=1) >= start)
                & (triangles[:, :, 1-axis].min(axis=1) <= end))
        if keep.any():
            selected.append(dict(mesh, vertices=vertices, triangles=faces[keep]))
            records.append(dict(mesh_name=mesh['name'], triangle_indices=np.flatnonzero(keep).tolist(),
                saved_faces_sha256=hashlib.sha256(vertices.tobytes()+faces[keep].tobytes()).hexdigest()))
    evidence = dict(policy='authored_room_wall_faces_v1', room_id=row['room_id'],
        wall_anchor=row['wall_anchor'], regions=regions,
        plane_binding_tolerance_m=_WALL_PLANE_BINDING_M, selected_faces=records)
    return selected, evidence


def ray_contact(meshes, targets, direction, tolerance, expected_gap=0., gap_range=None,
                *, target_selection='first_facing', target_regions=None, ray_origin='target_bounds'):
    """Return measured signed gaps for extreme vertices and planar centroids.

    Positive gap follows ``direction`` from the entity to its support; negative
    gap means its declared contact plane crosses a facing target surface. All
    negative gaps fail, including those smaller than tolerance. ``gap_range``
    supplies explicit inclusive policy bounds without expanding them by tolerance.
    A measured miss fails contact but says nothing about solid collision.

    ``nearest_contact_plane`` selects the facing hit with smallest absolute
    signed gap, breaking exact ties toward negative gaps. It measures local
    contact among unclassified shell surfaces; crossed surfaces elsewhere must
    remain in the caller's collision checks. Default ``first_facing`` retains
    the first facing surface of a declared target, including deep negative gaps.
    """
    # Local origins exclude unrelated overhead shelves. Hits within the small
    # backward probe band retain negative penetration; deeper misses fail.
    # Independent full-mesh collisions must still check the complete parent.
    if ray_origin not in ('target_bounds', 'contact_plane'):
        raise ValueError('Unknown contact ray origin')
    if target_selection not in ('first_facing', 'nearest_contact_plane'):
        raise ValueError('Unknown contact target selection')
    if (not _finite_number(tolerance) or not 0 < tolerance <= 1e-4
            or not _finite_number(expected_gap) or expected_gap < 0):
        raise ValueError('Contact requires bounded positive tolerance and nonnegative nominal gap')
    raw_direction = np.asarray(direction)
    if (raw_direction.shape != (3,) or raw_direction.dtype.kind not in 'ifu'
            or any(isinstance(v, (bool, np.bool_)) for v in direction)):
        raise ValueError('Contact direction must have three finite numeric components')
    vector = np.asarray(direction, dtype=np.float64)
    if not np.isfinite(vector).all() or not np.any(vector):
        raise ValueError('Contact direction must be finite and nonzero')
    norm = np.linalg.norm(vector)
    if not np.isfinite(norm) or norm == 0:
        raise ValueError('Invalid contact direction magnitude')
    vector = vector / norm
    if target_regions is not None:
        if not isinstance(target_regions, list) or not target_regions:
            raise ValueError('Contact target regions must be nonempty')
        for region in target_regions:
            interval = region.get('interval_m') if isinstance(region, dict) else None
            axis = region.get('axis') if isinstance(region, dict) else None
            if (type(axis) is not int or axis not in (0, 1) or abs(vector[axis]) != 1.
                    or not _finite_number(region.get('plane_m'))
                    or not isinstance(interval, (list, tuple)) or len(interval) != 2
                    or not all(_finite_number(v) for v in interval) or interval[0] >= interval[1]):
                raise ValueError('Invalid authored contact target region')
    if gap_range is not None:
        if (not isinstance(gap_range, (list, tuple)) or len(gap_range) != 2
                or not all(_finite_number(v) for v in gap_range)
                or not 0 <= gap_range[0] <= gap_range[1]):
            raise ValueError('Contact gap range requires ordered finite nonnegative bounds')
        accepted_range = list(gap_range)
    else:
        accepted_range = [max(0., expected_gap-tolerance), expected_gap+tolerance]
    source, target = _meshes(meshes), _meshes(targets)
    if not source:
        raise ValueError('Contact requires saved entity triangles')
    points = np.concatenate([v for v, _ in source])
    projection = points @ vector
    plane = float(projection.max())
    samples = [points[np.abs(projection-plane) <= _SAMPLE_BAND_M]]
    for vertices, faces in source:
        triangles = vertices[faces]
        selected = np.max(np.abs(triangles @ vector-plane), axis=1) <= _SAMPLE_BAND_M
        samples.append(triangles[selected].mean(axis=1))
    samples = np.unique(np.concatenate(samples), axis=0)
    gaps = np.full(len(samples), np.inf)
    if target:
        mesh, intersector = _target(target)
        projected = np.asarray(mesh.vertices) @ vector
        # Start outside the whole target so even deep negative gaps are observed.
        start_plane = (plane - 2*tolerance if ray_origin == 'contact_plane' else
                       min(float(projected.min()), plane) - max(1., float(np.ptp(projected))))
        origins = samples + (start_plane-samples @ vector)[:, None]*vector
        for start in range(0, len(samples), _BATCH_SIZE):
            stop = min(start+_BATCH_SIZE, len(samples))
            indices, ray_ids, locations = intersector.intersects_id(
                origins[start:stop], np.tile(vector, (stop-start, 1)),
                return_locations=True, multiple_hits=True)
            facing = np.asarray(mesh.face_normals)[indices] @ vector < -.5
            if target_regions is not None:
                bound = np.zeros(len(locations), dtype=bool)
                for region in target_regions:
                    axis, plane = region['axis'], region['plane_m']
                    lower, upper = region['interval_m']
                    bound |= ((np.abs(locations[:, axis]-plane) <= _WALL_PLANE_BINDING_M)
                        & (locations[:, 1-axis] >= lower-_WALL_PLANE_BINDING_M)
                        & (locations[:, 1-axis] <= upper+_WALL_PLANE_BINDING_M))
                facing &= bound
            indices, ray_ids, locations = indices[facing], ray_ids[facing]+start, locations[facing]
            if len(ray_ids):
                signed = np.einsum('ij,j->i', locations-samples[ray_ids], vector)
                if ray_origin == 'contact_plane' and np.count_nonzero(vector) == 1:
                    # Refine signed gaps from exact saved axis-flat triangles;
                    # no zero clamp, welding, or tolerance expansion.
                    contact_axis = int(np.flatnonzero(vector)[0])
                    coordinates = np.asarray(mesh.triangles)[indices, :, contact_axis]
                    flat = np.ptp(coordinates, axis=1) == 0
                    signed[flat] = ((coordinates[flat, 0]-samples[ray_ids[flat], contact_axis])
                                    * vector[contact_axis])
                if target_regions is not None:
                    # Ray intersection arithmetic can shift a coplanar point by
                    # one ulp. Read exact axis planes from the hit saved triangle;
                    # subtract actual coordinates, without clamping negative gaps.
                    axis = target_regions[0]['axis']
                    coordinates = np.asarray(mesh.triangles)[indices, :, axis]
                    flat = np.ptp(coordinates, axis=1) == 0
                    signed[flat] = ((coordinates[flat, 0]-samples[ray_ids[flat], axis])
                                    * vector[axis])
                if target_selection == 'nearest_contact_plane':
                    order = np.lexsort((signed, np.abs(signed), ray_ids))
                    ordered_ids = ray_ids[order]
                    first = np.r_[True, ordered_ids[1:] != ordered_ids[:-1]]
                    selected = order[first]
                    gaps[ray_ids[selected]] = signed[selected]
                else:
                    # Preserve crossed surfaces when the caller declares targets.
                    np.minimum.at(gaps, ray_ids, signed)
    measured = [float(g) if np.isfinite(g) else None for g in gaps]
    passed = bool(measured) and all(g is not None and g >= 0
        and accepted_range[0] <= g <= accepted_range[1] for g in measured)
    return dict(passed=passed, complete=True, status='measured', gaps_m=measured,
        sample_count=len(measured), expected_gap_m=expected_gap,
        accepted_gap_range_m=accepted_range, direction=vector.tolist(),
        target_selection=target_selection, ray_origin=ray_origin,
        method='saved_triangle_extreme_vertices_and_face_centroids_rays',
        measurement_backend='trimesh.ray_triangle+rtree',
        evidence_scope='sampled_surface_contact_only',
        physical_qualified=False, whole_task_acceptance=False)