"""Typed static proof for source-bound thin covers on a common saved floor. No compression, stability or dynamics is inferred. A source receipt alone or an AABB thickness alone never permits overlap. Unknown solids stay unknown. """ import hashlib import json import math if __package__: from .support_contract import verify_surface_evidence else: from support_contract import verify_surface_evidence SCHEMA = 'rhg.permitted_floor_cover_contact.v1' POLICY_REVISION = 'thin-floor-cover-common-floor-v1' REQUIRED_GATE = 'actual_all_triangle_intersections_within_5mm_of_common_floor_contact_plane' BAND_M = (0., .005) PLANE_ARITHMETIC_GUARD_M = 1e-9 FLOOR_COVER_CATEGORIES = frozenset({'rug', 'carpet', 'floor_mat', 'doormat'}) def export_arithmetic_guard(plane): return 8 * (2.**-23) * max(abs(plane), abs(plane+BAND_M[1])) def is_floor_cover(entity): # Only taxonomy routes into the existing exact saved-mesh proof. # A conflicting explicit category must not be overridden by a generic role. category = entity.get('category') or entity.get('role') return category in FLOOR_COVER_CATEGORIES def fingerprint(value): return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':'), allow_nan=False).encode()).hexdigest() def _number(value): return type(value) in (int, float) and math.isfinite(value) def _bottom_contact_region(meshes, bottom): """Project the complete triangle/lowest-plane contact set, without sampling.""" from shapely.geometry import Point, LineString, Polygon from shapely.ops import unary_union regions = [] for mesh in meshes: for triangle in mesh['vertices'][mesh['triangles']]: points = triangle[abs(triangle[:,2]-bottom) <= PLANE_ARITHMETIC_GUARD_M,:2] if len(points) == 1: regions.append(Point(points[0])) elif len(points) == 2: regions.append(LineString(points)) elif len(points) == 3: polygon = Polygon(points) regions.append(polygon if polygon.area else LineString(points)) return unary_union(regions) def _receipt(cover, furniture, inputs): receipts = furniture.get('floor_cover_contact_evidence') if not isinstance(receipts, list): return None matching = [r for r in receipts if isinstance(r, dict) and r.get('floor_cover_entity_id') == cover['entity_id']] unique = {fingerprint(r): r for r in matching} if len(unique) != 1: return None receipt = next(iter(unique.values())) if (receipt.get('floor_cover_asset_id') != cover.get('asset_id') or receipt.get('floor_remains_primary_support') is not True or receipt.get('contact_tolerance_m') != BAND_M[1] or receipt.get('required_gate') != REQUIRED_GATE or receipt.get('physical_compression_model') != 'unknown_not_assumed' or not _number(receipt.get('measured_cover_plane_z_m')) or not _number(receipt.get('furniture_bottom_z_m'))): return None source = verify_surface_evidence(cover, receipt.get('source_evidence_path'), receipt.get('source_evidence_sha256'), inputs=inputs) # The layout solver records a measured upward patch's mean plane, not # necessarily the maximum of a textured cover's complete saved solid. with open(source['evidence_path']) as stream: data = json.load(stream) planes = data['records'][source['pool_candidate_key']].get('upward_planes') if planes is not None: heights = [p.get('height_m') for p in planes if isinstance(p, dict)] if not heights or any(not _number(height) for height in heights): return None source['measured_patch_heights_m'] = heights return receipt, source def measure_contact(left, right, overlap, *, entities, groups, shell, solids, contacts, flat_region, manifest_fingerprint, mesh_fingerprint, scene_sha256, evidence_inputs): """Prove every vertex of the exact polyhedral intersection is in the band. A linear z coordinate reaches its extrema at vertices, so measuring every intersection vertex bounds the entire closed solid, including containment. Full saved bottom-face coverage independently proves the common floor. """ import numpy as np try: rows = [entities[left], entities[right]] if (not isinstance(scene_sha256, str) or len(scene_sha256) != 64 or any(c not in '0123456789abcdef' for c in scene_sha256)): return None covers = [r for r in rows if is_floor_cover(r)] if len(covers) != 1: return None cover = covers[0] furniture = next(r for r in rows if r is not cover) if (not cover.get('room_id') or cover['room_id'] != furniture.get('room_id') or any(r['entity_id'] not in solids for r in rows)): return None for row in rows: if (any(row.get(k) is not None for k in ('supported_by_entity_id', 'support_entity_id', 'parent_entity_id', 'derived_support_relation')) or row.get('selected_support_surface') is not None): return None contact = contacts.get(row['entity_id'], {}) if (contact.get('support_type') != 'floor' or contact.get('support_entity_id') is not None or contact.get('complete') is not True or contact.get('passed') is not True or contact.get('status') != 'measured' or contact.get('pending_fields')): return None proof = _receipt(cover, furniture, evidence_inputs) if proof is None: return None receipt, source = proof # Only actual closed saved floor geometry may establish the plane. floors = [m for m in shell if m['solid'] is not None and (m['name'] == 'floor' or m['name'].startswith('floor__'))] if not floors: return None bottoms = {r['entity_id']: min(float(m['low'][2]) for m in groups[r['entity_id']]) for r in rows} plane = bottoms[cover['entity_id']] if any(abs(z-plane) > PLANE_ARITHMETIC_GUARD_M for z in bottoms.values()): return None # Derive the plane from saved upward faces, never the manifest/receipt. supporting = [m for m in floors if abs(float(m['high'][2])-plane) <= PLANE_ARITHMETIC_GUARD_M] if not supporting: return None plane = float(supporting[0]['high'][2]) supporting = [m for m in supporting if float(m['high'][2]) == plane] floor_region = flat_region(supporting, plane, PLANE_ARITHMETIC_GUARD_M, upward=True) if floor_region.is_empty: return None names = sorted(m['name'] for m in supporting) floor_proofs = [] for row in sorted(rows, key=lambda r: r['entity_id']): identifier = row['entity_id'] bottom = bottoms[identifier] if abs(bottom-plane) > PLANE_ARITHMETIC_GUARD_M: return None base = _bottom_contact_region(groups[identifier], bottom) if base.is_empty or not base.difference(floor_region).is_empty: return None floor_proofs.append(dict(entity_id=identifier, support_type='floor', support_entity_id=None, complete=True, passed=True, actual_bottom_z_m=bottom, common_floor_mesh_names=names, bottom_contact_geometry_proof=dict( method='complete_saved_triangle_minimum_plane_points_edges_faces_covered', complete=True, passed=True, actual_bottom_z_m=bottom, contact_geometry_kind=base.geom_type, uncovered_geometry_empty=True, common_floor_mesh_names=names))) cover_points = np.concatenate([m['vertices'] for m in groups[cover['entity_id']]]) # This additional narrow restriction rejects folds and raised covers; # it never substitutes for the complete solid-intersection proof below. # Eight float32 ulps at the policy boundary account only for saved # export arithmetic (about 4.8 nm at 5 mm), never a physical margin. export_guard = export_arithmetic_guard(plane) if 'measured_patch_heights_m' in source: # Layout may choose any measured upward patch, not the highest one. # Match its recorded mean plane to the same hash-bound source data. patch_planes = [plane+h for h in source['measured_patch_heights_m'] if abs(receipt['measured_cover_plane_z_m']-(plane+h)) <= 1e-6] if not patch_planes: return None patch_plane = min(patch_planes, key=lambda z: abs(receipt['measured_cover_plane_z_m']-z)) else: patch_plane = float(cover_points[:,2].max()) if (float(cover_points[:,2].min()) < plane or float(cover_points[:,2].max()) > plane+BAND_M[1]+export_guard or abs(receipt['measured_cover_plane_z_m']-patch_plane) > 1e-6 or abs(receipt['furniture_bottom_z_m']-bottoms[furniture['entity_id']]) > 1e-6): return None measured_thickness = float(cover_points[:,2].max()) - plane permitted_band = [0., min(BAND_M[1]+export_guard, measured_thickness)] vertices = np.asarray(overlap.to_mesh64().vert_properties)[:,:3] if not len(vertices) or not np.isfinite(vertices).all(): return None zrange = [float(vertices[:,2].min()), float(vertices[:,2].max())] if zrange[0] < plane or zrange[1] > plane+permitted_band[1]: return None certificate = dict(schema=SCHEMA, policy_revision=POLICY_REVISION, kind='thin_floor_cover_common_floor_contact', complete=True, passed=True, physical_qualified=False, entity_ids=sorted((left,right)), floor_cover_entity_id=cover['entity_id'], furniture_entity_id=furniture['entity_id'], room_id=cover['room_id'], overlap_volume_m3=overlap.volume(), scene_sha256=scene_sha256, manifest_fingerprint=manifest_fingerprint, mesh_fingerprint=mesh_fingerprint, source_evidence_path=source['evidence_path'], source_evidence_sha256=source['evidence_sha256'], source_identity=source['source_identity'], common_floor_z_m=plane, common_floor_mesh_names=names, permitted_band_m=permitted_band, intersection_z_range_m=zrange, measured_cover_thickness_m=measured_thickness, policy_ceiling_m=BAND_M[1], float32_export_arithmetic_guard_m=export_guard, measured_source_patch_plane_z_m=patch_plane, floor_support_proofs=floor_proofs, scope='static_saved_closed_solid_common_floor_contact_only; compression_stability_dynamics_unknown') certificate['certificate_id'] = fingerprint(certificate) return certificate except (OSError, ValueError, TypeError, KeyError, IndexError): # An unusable proof does not change the original collision result. return None