-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1273 lines (1120 loc) · 48.5 KB
/
Copy pathmain.py
File metadata and controls
1273 lines (1120 loc) · 48.5 KB
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import csv
import json
import os
import sys
from dataclasses import dataclass, asdict
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
# ---------- Dependencies ----------
try:
import ifcopenshell
import ifcopenshell.geom
from ifcopenshell.util import unit as ifc_unit
try:
# pset helper is optional but common
from ifcopenshell.util.element import get_psets as ifc_get_psets
except Exception:
ifc_get_psets = None
except Exception:
print("This script needs ifcopenshell with geometry enabled. Try: pip install ifcopenshell", file=sys.stderr)
raise
# Kept as a fallback for rare cases; primary ops use Open3D now
try:
import trimesh
TRIMESH_OK = True
except Exception:
TRIMESH_OK = False
try:
import open3d as o3d
OPEN3D_OK = True
except Exception:
OPEN3D_OK = False
print("This script needs open3d. Try: pip install open3d", file=sys.stderr)
raise
VERBOSE = True
def log_step(message: str) -> None:
if VERBOSE:
print(f"[step] {message}", flush=True)
_LOG_STATE = {
"boolean_intersection_fallback": False,
"boolean_union_fallback": False,
"voxel_union_fallback": False,
}
# ---------- Data structures ----------
@dataclass
class Meta:
GlobalId: str
IfcType: str
Name: str
ObjectType: Optional[str]
PredefinedType: Optional[str]
Tag: Optional[str]
ExpressID: Optional[int]
Psets: Optional[Dict[str, Any]] # nested dict of {Pset: {Prop: value}}
@dataclass
class Comp:
idx: int # index in our arrays
guid: str
etype: str
meta: Meta
mesh: o3d.geometry.TriangleMesh # Open3D mesh (primary)
volume: float
aabb_min: np.ndarray
aabb_max: np.ndarray
# ---------- Open3D helpers ----------
def _o3d_mesh_copy(mesh: o3d.geometry.TriangleMesh) -> o3d.geometry.TriangleMesh:
# deep copy helper (o3d meshes are mutable)
return o3d.geometry.TriangleMesh(mesh)
def _o3d_concat_meshes(meshes: List[o3d.geometry.TriangleMesh]) -> o3d.geometry.TriangleMesh:
"""Concatenate triangle meshes into a single mesh (index-safe)."""
if not meshes:
return o3d.geometry.TriangleMesh()
all_verts = []
all_tris = []
v_offset = 0
for m in meshes:
if len(m.vertices) == 0 or len(m.triangles) == 0:
continue
V = np.asarray(m.vertices)
F = np.asarray(m.triangles)
all_verts.append(V)
all_tris.append(F + v_offset)
v_offset += V.shape[0]
if not all_verts:
return o3d.geometry.TriangleMesh()
V = np.vstack(all_verts)
F = np.vstack(all_tris)
out = o3d.geometry.TriangleMesh(
vertices=o3d.utility.Vector3dVector(V),
triangles=o3d.utility.Vector3iVector(F)
)
return out
def _o3d_clean_mesh(mesh: o3d.geometry.TriangleMesh) -> None:
"""Best-effort cleanup akin to trimesh processing."""
try:
mesh.remove_duplicated_vertices()
mesh.remove_degenerate_triangles()
mesh.remove_duplicated_triangles()
mesh.remove_non_manifold_edges()
mesh.compute_vertex_normals()
except Exception:
pass # keep going with best effort
def _o3d_bounds(mesh: o3d.geometry.TriangleMesh) -> Tuple[np.ndarray, np.ndarray]:
aabb = mesh.get_axis_aligned_bounding_box()
return np.asarray(aabb.min_bound), np.asarray(aabb.max_bound)
def _o3d_is_watertight(mesh: o3d.geometry.TriangleMesh) -> bool:
try:
return mesh.is_watertight()
except Exception:
# conservative default
return False
def _o3d_signed_volume(mesh: o3d.geometry.TriangleMesh) -> float:
"""Compute signed volume of a (possibly watertight) triangle mesh via divergence theorem."""
if len(mesh.vertices) == 0 or len(mesh.triangles) == 0:
return 0.0
V = np.asarray(mesh.vertices, dtype=np.float64)
F = np.asarray(mesh.triangles, dtype=np.int64)
v0 = V[F[:, 0]]
v1 = V[F[:, 1]]
v2 = V[F[:, 2]]
# sum over tetrahedra w.r.t. origin: 1/6 * dot(v0, cross(v1, v2))
cross = np.cross(v1, v2)
vol = np.einsum('ij,ij->i', v0, cross).sum() / 6.0
return float(vol)
def _get_volume(mesh: o3d.geometry.TriangleMesh) -> float:
"""
Robust volume helper: try Open3D's get_volume() first (fast),
but catch exceptions (non-watertight meshes) and fall back to:
1) a signed-volume triangle-based computation (_o3d_signed_volume),
2) convex-hull -> signed-volume,
3) finally return 0.0 on failure.
Returns a positive float (absolute volume).
"""
# Try to ensure consistent triangle orientation first (best-effort)
try:
if mesh.is_orientable():
mesh.orient_triangles()
except Exception:
# ignore orientation failures; continue to robust volume paths
pass
# Primary fast attempt: Open3D's get_volume() (may throw for non-watertight meshes)
try:
vol = mesh.get_volume()
return float(abs(vol))
except Exception:
# Fall back to a pure-Python signed-volume computation over triangles
try:
vol = _o3d_signed_volume(mesh)
return float(abs(vol))
except Exception:
# As a last resort, try convex hull and compute signed volume on the hull
try:
hull, _ = mesh.compute_convex_hull()
try:
if hull.is_orientable():
hull.orient_triangles()
except Exception:
pass
# compute signed volume on the hull (avoids relying on get_volume)
hvol = _o3d_signed_volume(hull)
return float(abs(hvol))
except Exception:
# give up and return zero
return 0.0
def _o3d_mesh_volume_or_hull(mesh: o3d.geometry.TriangleMesh) -> float:
"""Positive volume using mesh if watertight, else convex hull volume."""
if _o3d_is_watertight(mesh):
return abs(_o3d_signed_volume(mesh))
try:
hull, _ = mesh.compute_convex_hull()
return abs(_o3d_signed_volume(hull))
except Exception:
# last resort: zero
return 0.0
def _o3d_transform_inplace(meshes: List[Comp], T: np.ndarray) -> None:
T = np.asarray(T, dtype=np.float64)
if T.shape != (4, 4):
raise ValueError("Transformation matrix T must be 4x4.")
for c in meshes:
c.mesh.transform(T)
c.aabb_min, c.aabb_max = _o3d_bounds(c.mesh)
def _o3d_sample_points(meshes: List[o3d.geometry.TriangleMesh], target_pts: int = 80000) -> o3d.geometry.PointCloud:
total_area = sum(m.get_surface_area() for m in meshes if len(m.triangles) > 0)
points = []
if total_area <= 0:
if not meshes:
return o3d.geometry.PointCloud()
V = np.vstack([np.asarray(m.vertices) for m in meshes if len(m.vertices) > 0]) if meshes else np.zeros((0, 3))
return o3d.geometry.PointCloud(o3d.utility.Vector3dVector(V))
for m in meshes:
if len(m.triangles) == 0:
continue
n = max(200, int(target_pts * (m.get_surface_area() / total_area)))
pts = m.sample_points_uniformly(number_of_points=n)
points.append(np.asarray(pts.points))
P = np.vstack(points) if points else np.zeros((0, 3))
return o3d.geometry.PointCloud(o3d.utility.Vector3dVector(P))
def legacy_to_tensor_minimal(legacy_mesh: o3d.geometry.TriangleMesh) -> o3d.t.geometry.TriangleMesh:
vp = o3d.core.Tensor(np.asarray(legacy_mesh.vertices), o3d.core.Dtype.Float32)
ti = o3d.core.Tensor(np.asarray(legacy_mesh.triangles), o3d.core.Dtype.Int64)
return o3d.t.geometry.TriangleMesh(vp, ti)
def drop_all_but_positions_indices(tm):
"""
Remove all vertex attributes except 'positions' and all triangle attributes
except 'indices'. Works across Open3D legacy and tensor-backed TriangleMesh APIs.
This function is defensive: it tries several common attribute-listing and
removal APIs (get_attribute_names, attribute_names, remove_attribute, pop,
del) and ignores failures. This avoids calling `tm.vertex.keys()` on a
TensorMap (which can raise the 'Key keys not found in TensorMap' error).
"""
def _list_attr_map(attr_map):
# Try several ways to list attributes in preferred order.
try:
if hasattr(attr_map, "get_attribute_names") and callable(attr_map.get_attribute_names):
return list(attr_map.get_attribute_names())
# attribute_names may be a list/tuple property on some versions
if hasattr(attr_map, "attribute_names"):
try:
return list(attr_map.attribute_names)
except Exception:
pass
# Some older APIs expose a mapping-like object (dict-like)
if isinstance(attr_map, dict):
return list(attr_map.keys())
# Avoid blindly calling attr_map.keys() on TensorMap (can be handled as a key),
# but if it's callable and behaves like a mapping, attempt it guarded.
keys_attr = getattr(attr_map, "keys", None)
if callable(keys_attr):
try:
return list(keys_attr())
except Exception:
pass
# Last resort: try to read available attributes via dir (no private names)
return [n for n in dir(attr_map) if not n.startswith("_")]
except Exception:
return []
def _try_remove_vertex_attr(attr_map, name):
# Try removal with several candidate APIs; ignore failures.
try:
if hasattr(attr_map, "remove_attribute") and callable(attr_map.remove_attribute):
attr_map.remove_attribute(name)
return True
except Exception:
pass
try:
if hasattr(attr_map, "pop") and callable(attr_map.pop):
# mapping-like pop
attr_map.pop(name, None)
return True
except Exception:
pass
try:
# mapping delete
delattr(attr_map, name)
return True
except Exception:
pass
try:
# mapping-like __delitem__
del attr_map[name]
return True
except Exception:
pass
# no supported removal method found / all failed
return False
# Vertex attributes: keep only 'positions'
try:
vmap = tm.vertex
vkeys = _list_attr_map(vmap)
for k in vkeys:
if k == "positions":
continue
_ = _try_remove_vertex_attr(vmap, k)
except Exception:
# Best-effort: ignore failures
pass
# Triangle attributes: keep only 'indices'
try:
tmap = tm.triangle
tkeys = _list_attr_map(tmap)
for k in tkeys:
if k == "indices":
continue
_ = _try_remove_vertex_attr(tmap, k)
except Exception:
pass
def _o3d_boolean_intersection(a: o3d.geometry.TriangleMesh, b: o3d.geometry.TriangleMesh) -> Optional[o3d.geometry.TriangleMesh]:
"""
Try a.boolean_intersection(b) but first make a cleaned copy of both meshes
(remove duplicated/degenerate triangles, non-manifold edges, compute normals).
Return None on failure or empty result (caller will fallback to voxels).
"""
# try:
a2 = _o3d_mesh_copy(a)
b2 = _o3d_mesh_copy(b)
# best-effort cleanup before boolean ops
for m in (a2, b2):
try:
m.remove_duplicated_vertices()
m.remove_degenerate_triangles()
m.remove_duplicated_triangles()
m.remove_non_manifold_edges()
m.compute_vertex_normals()
except Exception:
# keep going even if some cleanup calls fail
pass
a2t = legacy_to_tensor_minimal(a2)
b2t = legacy_to_tensor_minimal(b2)
inter_t = a2t.boolean_intersection(b2t)
drop_all_but_positions_indices(inter_t)
inter = inter_t.to_legacy()
# Some Open3D boolean implementations return empty meshes instead of raising.
if inter is None or len(inter.vertices) == 0 or len(inter.triangles) == 0:
return None
return inter
# except Exception:
# if not _LOG_STATE["boolean_intersection_fallback"]:
# log_step(" Open3D boolean_intersection failed; will fall back to voxel IoU where needed")
# _LOG_STATE["boolean_intersection_fallback"] = True
# return None
def _o3d_boolean_union(meshes: List[o3d.geometry.TriangleMesh]) -> Optional[o3d.geometry.TriangleMesh]:
if not meshes:
return None
try:
acc = legacy_to_tensor_minimal(_o3d_mesh_copy(meshes[0]))
for m in meshes[1:]:
mt = legacy_to_tensor_minimal(_o3d_mesh_copy(m))
acc = acc.boolean_union(mt)
drop_all_but_positions_indices(acc)
out = acc.to_legacy()
return out if out is not None and len(out.triangles) > 0 else None
except Exception:
if not _LOG_STATE["boolean_union_fallback"]:
log_step(" Open3D boolean_union failed; will fall back to voxel-based union approximation")
_LOG_STATE["boolean_union_fallback"] = True
return None
def _o3d_voxelize_indices(mesh: o3d.geometry.TriangleMesh, pitch: float, origin: np.ndarray, dims: np.ndarray) -> np.ndarray:
"""Voxelize mesh into a fixed grid defined by (origin, pitch, dims)."""
# shift mesh so that origin maps to (0,0,0) in voxel grid space
m = _o3d_mesh_copy(mesh)
m.translate(-origin, relative=True)
vg = o3d.geometry.VoxelGrid.create_from_triangle_mesh(m, voxel_size=pitch)
occ = np.zeros((dims[0], dims[1], dims[2]), dtype=bool)
if vg is None or len(vg.get_voxels()) == 0:
return occ
for v in vg.get_voxels():
idx = v.grid_index # IntVector3d
i, j, k = int(idx[0]), int(idx[1]), int(idx[2])
if 0 <= i < dims[0] and 0 <= j < dims[1] and 0 <= k < dims[2]:
occ[i, j, k] = True
return occ
def _o3d_boxes_from_indices(indices: np.ndarray, pitch: float, origin: np.ndarray) -> o3d.geometry.TriangleMesh:
"""Create a mesh by instancing boxes at occupied voxel indices (fallback for union)."""
boxes = []
half = pitch / 2.0
for (i, j, k) in np.argwhere(indices):
center = origin + np.array([i + 0.5, j + 0.5, k + 0.5]) * pitch
box = o3d.geometry.TriangleMesh.create_box(width=pitch, height=pitch, depth=pitch)
box.translate(center - np.array([half, half, half]), relative=False)
boxes.append(box)
return _o3d_concat_meshes(boxes) if boxes else o3d.geometry.TriangleMesh()
# ---------- IFC -> mesh & metadata ----------
def _ifc_length_scale_m(ifc) -> float:
try:
return float(ifc_unit.calculate_unit_scale(ifc))
except Exception:
return 1.0
def _flatten_psets(psets: Dict[str, Any]) -> Dict[str, Any]:
flat = {}
for pset, props in (psets or {}).items():
if isinstance(props, dict):
for k, v in props.items():
flat[f"{pset}:{k}"] = v
else:
flat[pset] = props
return flat
def _product_meta(p) -> Meta:
guid = getattr(p, "GlobalId", None)
name = getattr(p, "Name", None)
etype = p.is_a()
objtype = getattr(p, "ObjectType", None)
tag = getattr(p, "Tag", None)
predefined = None
try:
predefined = getattr(p, "PredefinedType", None)
if isinstance(predefined, ifcopenshell.entity_instance):
predefined = str(predefined)
except Exception:
pass
expid = None
try:
expid = int(p.id())
except Exception:
pass
psets = None
if ifc_get_psets is not None:
try:
psets = ifc_get_psets(p, include_inherited=True, recursive=True)
except Exception:
psets = None
return Meta(
GlobalId=guid or "",
IfcType=etype,
Name=name or "",
ObjectType=objtype if objtype not in (None, "") else None,
PredefinedType=predefined if predefined not in (None, "") else None,
Tag=tag if tag not in (None, "") else None,
ExpressID=expid,
Psets=psets
)
def _shape_to_o3d_mesh(shape, scale_to_m: float) -> Optional[o3d.geometry.TriangleMesh]:
g = shape.geometry
verts = getattr(g, "verts", None)
if verts is None:
verts = getattr(g, "vertices", None)
faces = getattr(g, "faces", None)
if faces is None:
faces = getattr(g, "indices", None)
if verts is None or faces is None:
return None
V = np.asarray(verts, dtype=np.float64).reshape(-1, 3)
F = np.asarray(faces, dtype=np.int64).reshape(-1, 3)
# 4x4 transform (column-major to standard)
M = np.array(shape.transformation.matrix, dtype=np.float64).reshape(4, 4).T
Vh = np.c_[V, np.ones((V.shape[0], 1))]
Vw = (Vh @ M.T)[:, :3] * scale_to_m
mesh = o3d.geometry.TriangleMesh(
vertices=o3d.utility.Vector3dVector(Vw),
triangles=o3d.utility.Vector3iVector(F)
)
_o3d_clean_mesh(mesh)
return mesh
def _build_geom_settings(use_python_occ: bool) -> Optional["ifcopenshell.geom.settings"]:
"""Create geometry settings, optionally enabling pythonOCC output."""
log_step(f"Configuring geometry settings (pythonOCC={'on' if use_python_occ else 'off'})")
settings = ifcopenshell.geom.settings()
if use_python_occ:
try:
settings.set("USE_PYTHON_OPENCASCADE", True)
log_step(" pythonOCC enabled for geometry extraction")
except Exception:
log_step(" pythonOCC enable failed; will fall back")
return None
settings.set("DISABLE_OPENING_SUBTRACTIONS", False)
settings.set("WELD_VERTICES", True)
settings.set("APPLY_DEFAULT_MATERIALS", False)
log_step(" Geometry settings ready")
return settings
def _type_matches(etype: str, include_types: Optional[List[str]]) -> bool:
"""Return True if etype matches any entry in include_types.
Matching is case-insensitive and permits entries without the 'Ifc' prefix,
e.g. 'Wall' will match 'IfcWall'.
"""
if not include_types:
return True
etl = (etype or "").strip().lower()
for t in include_types:
if t is None:
continue
tl = t.strip().lower()
if not tl:
continue
if tl == etl:
return True
# allow user to provide 'Wall' to match 'IfcWall'
if tl == etl.replace("ifc", ""):
return True
return False
def load_ifc_components(path: str, include_types: Optional[List[str]] = None) -> Tuple[List[Comp], float]:
"""Load IfcProduct elements from path and return list of Comp.
If include_types is provided (e.g. ['IfcWall', 'IfcDoor'] or ['Wall','Door']),
only products whose type matches the provided list will be processed.
"""
if not os.path.isfile(path):
raise FileNotFoundError(path)
log_step(f"Loading IFC components from {path}")
ifc = ifcopenshell.open(path)
schema_attr = getattr(ifc, "schema", None)
if callable(schema_attr):
try:
schema_name = schema_attr()
except Exception:
schema_name = "unknown"
else:
schema_name = schema_attr if isinstance(schema_attr, str) else "unknown"
log_step(f" IFC schema: {schema_name}")
scale = _ifc_length_scale_m(ifc)
log_step(f" Unit scale: {scale:.6f} meters per IFC unit")
# temporarily disable scale
scale = 1
settings = _build_geom_settings(use_python_occ=True)
using_occ = settings is not None
if not using_occ:
log_step(" pythonOCC geometry unavailable; using default triangulation settings")
settings = _build_geom_settings(use_python_occ=False)
fallback_settings = None
comps: List[Comp] = []
total_products = 0
geometry_errors = 0
suppressed_geometry_error_notice = False
empty_volume_count = 0
progress_step = 50
for p in ifc.by_type("IfcProduct"):
# Filter by representation present
if not getattr(p, "Representation", None):
continue
# Filter by requested IFC classes if provided
etype = p.is_a()
if not _type_matches(etype, include_types):
continue
total_products += 1
guid = getattr(p, "GlobalId", "") or "<no guid>"
try:
shape = ifcopenshell.geom.create_shape(settings, p)
except Exception as exc:
geometry_errors += 1
if geometry_errors <= 5:
log_step(f" Geometry creation failed for {guid} ({etype}): {exc}")
elif geometry_errors == 6 and not suppressed_geometry_error_notice:
log_step(" Additional geometry creation failures encountered; suppressing further details")
suppressed_geometry_error_notice = True
continue
mesh = _shape_to_o3d_mesh(shape, scale_to_m=scale)
if (mesh is None or len(mesh.triangles) == 0) and using_occ:
if fallback_settings is None:
log_step(" Initializing fallback geometry settings (pythonOCC off)")
fallback_settings = _build_geom_settings(use_python_occ=False)
if fallback_settings is None:
log_step(f" Fallback geometry settings unavailable; skipping {guid} ({etype})")
continue
log_step(f" Empty mesh from pythonOCC for {guid} ({etype}); retrying with fallback settings")
try:
shape = ifcopenshell.geom.create_shape(fallback_settings, p)
except Exception as exc:
log_step(f" Fallback geometry also failed for {guid} ({etype}): {exc}")
continue
mesh = _shape_to_o3d_mesh(shape, scale_to_m=scale)
if mesh is None or len(mesh.triangles) == 0:
log_step(f" No mesh produced for {guid} ({etype}) even after fallback; skipping")
continue
settings = fallback_settings
using_occ = False
log_step(" Switching to fallback geometry settings for remaining elements")
if mesh is None or len(mesh.triangles) == 0:
log_step(f" Empty mesh for {guid} ({etype}); skipping")
continue
vol = _o3d_mesh_volume_or_hull(mesh)
if vol <= 0.0:
empty_volume_count += 1
if empty_volume_count <= 5:
log_step(f" Non-positive volume for {guid} ({etype}); skipping")
elif empty_volume_count == 6:
log_step(" Additional non-positive volume elements suppressed")
continue
aabb_min, aabb_max = _o3d_bounds(mesh)
meta = _product_meta(p)
comps.append(Comp(
idx=len(comps),
guid=meta.GlobalId,
etype=meta.IfcType,
meta=meta,
mesh=mesh,
volume=vol,
aabb_min=aabb_min,
aabb_max=aabb_max
))
if len(comps) % progress_step == 0:
log_step(f" Meshed {len(comps)} components so far")
if not comps:
raise RuntimeError(f"No meshable IfcProducts with positive volume found in {os.path.basename(path)}")
log_step(f"Finished meshing {len(comps)} components (processed {total_products} candidates)")
return comps, scale
# ---------- Alignment (PRED -> GT) ----------
def _centroid_align(pred_meshes: List[o3d.geometry.TriangleMesh], gt_meshes: List[o3d.geometry.TriangleMesh]) -> np.ndarray:
pred_all = _o3d_concat_meshes(pred_meshes)
gt_all = _o3d_concat_meshes(gt_meshes)
T = np.eye(4)
T[:3, 3] = (_o3d_bounds(gt_all)[0] + _o3d_bounds(gt_all)[1]) / 2.0 - ((_o3d_bounds(pred_all)[0] + _o3d_bounds(pred_all)[1]) / 2.0)
return T
def _o3d_pcd_from_meshes(meshes: List[o3d.geometry.TriangleMesh], target_pts: int = 80000):
return _o3d_sample_points(meshes, target_pts=target_pts)
def rigid_icp_align(pred_meshes: List[o3d.geometry.TriangleMesh], gt_meshes: List[o3d.geometry.TriangleMesh]) -> np.ndarray:
T0 = _centroid_align(pred_meshes, gt_meshes)
src = _o3d_pcd_from_meshes(pred_meshes)
tgt = _o3d_pcd_from_meshes(gt_meshes)
src.transform(T0)
gt_all = _o3d_concat_meshes(gt_meshes)
gmin, gmax = _o3d_bounds(gt_all)
diag = float(np.linalg.norm(gmax - gmin))
max_corr = max(0.02 * diag, 0.05)
reg = o3d.pipelines.registration.registration_icp(
src, tgt, max_corr, np.eye(4),
o3d.pipelines.registration.TransformationEstimationPointToPoint()
)
return reg.transformation @ T0
def rigid_icp_align_xy_only(pred_meshes: List[o3d.geometry.TriangleMesh], gt_meshes: List[o3d.geometry.TriangleMesh]) -> np.ndarray:
"""
Align PRED -> GT using only an X/Y translation. No rotation is applied.
Strategy:
- Sample point clouds from pred and gt meshes.
- Compute mean (centroid) of each point set.
- Compute translation vector = (tgt_centroid - src_centroid) but only on X and Y.
- Return 4x4 transform with identity rotation and translation [dx, dy, 0].
If sampling fails (empty clouds), fall back to the bbox-centroid alignment but zero the Z translation.
"""
# Sample point clouds
src = _o3d_pcd_from_meshes(pred_meshes)
tgt = _o3d_pcd_from_meshes(gt_meshes)
# If either cloud is empty, fallback to centroid align but enforce no Z translation
try:
src_pts = np.asarray(src.points)
tgt_pts = np.asarray(tgt.points)
except Exception:
src_pts = np.zeros((0, 3))
tgt_pts = np.zeros((0, 3))
if src_pts.size == 0 or tgt_pts.size == 0:
T_cent = _centroid_align(pred_meshes, gt_meshes)
T_cent[2, 3] = 0.0 # enforce no Z translation
print("Alignment (fallback centroid, Z zeroed):")
print(T_cent)
return T_cent
# Compute centroids
src_c = src_pts.mean(axis=0)
tgt_c = tgt_pts.mean(axis=0)
# Build translation only in X and Y; keep Z unchanged
dx = float(tgt_c[0] - src_c[0])
dy = float(tgt_c[1] - src_c[1])
T = np.eye(4, dtype=float)
T[0, 3] = dx
T[1, 3] = dy
T[2, 3] = 0.0
print("Alignment (XY-translation only):")
print(T)
return T
# ---------- IoU + Compactness ----------
def _aabb_overlap(a_min, a_max, b_min, b_max) -> bool:
return np.all(a_min <= b_max) and np.all(b_min <= a_max) and np.all(a_max >= b_min) and np.all(b_max >= a_min)
def _boolean_intersection_volume(a: o3d.geometry.TriangleMesh, b: o3d.geometry.TriangleMesh) -> float:
inter = _o3d_boolean_intersection(a, b)
if inter is None or len(inter.vertices) == 0 or len(inter.triangles) == 0:
return 0.0
_o3d_clean_mesh(inter)
return _o3d_mesh_volume_or_hull(inter)
def _voxelize_to_grid(mesh: o3d.geometry.TriangleMesh, pitch: float, origin: np.ndarray, dims: np.ndarray) -> np.ndarray:
return _o3d_voxelize_indices(mesh, pitch, origin, dims)
def visualize_voxel_occupancy(occ_a: np.ndarray, occ_b: np.ndarray, origin: np.ndarray, pitch: float, pts_mode: bool = True) -> None:
"""
Visualize two boolean occupancy grids (occ_a, occ_b) in the same coordinate frame.
occ_* : 3D boolean numpy arrays with shape (Nx, Ny, Nz)
origin : 3-element array (min corner) for voxel index (0,0,0)
pitch : voxel size (float)
pts_mode : True => draw voxel centers as colored points (fast). False => builds boxes (heavy).
"""
if occ_a.shape != occ_b.shape:
raise ValueError("occ_a and occ_b must have same shape")
# voxel indices where occupied
ia = np.argwhere(occ_a)
ib = np.argwhere(occ_b)
if ia.size == 0 and ib.size == 0:
log_step("visualize_voxel_occupancy: no occupied voxels")
return
# compute centers
centers_a = origin + (ia + 0.5) * pitch if ia.size else np.zeros((0, 3))
centers_b = origin + (ib + 0.5) * pitch if ib.size else np.zeros((0, 3))
# If a voxel is occupied in both, mark as overlap (blue)
# Build a merged list with colors: A-only red, B-only green, overlap blue
# Use sets of tuple indices for quick overlap test
set_a = {tuple(x) for x in ia.tolist()}
set_b = {tuple(x) for x in ib.tolist()}
overlap_idx = np.array(sorted([x for x in set_a & set_b]))
only_a_idx = np.array(sorted([x for x in set_a - set_b]))
only_b_idx = np.array(sorted([x for x in set_b - set_a]))
pts = []
cols = []
def append_from_indices(arr, color):
if arr.size == 0:
return
arr = np.asarray(arr, dtype=float)
centers = origin + (arr + 0.5) * pitch
pts.append(centers)
cols.append(np.tile(color, (centers.shape[0], 1)))
append_from_indices(only_a_idx, [1.0, 0.0, 0.0]) # red
append_from_indices(only_b_idx, [0.0, 1.0, 0.0]) # green
append_from_indices(overlap_idx, [0.0, 0.0, 1.0]) # blue
if not pts:
log_step("visualize_voxel_occupancy: nothing to draw after classification")
return
P = np.vstack(pts)
C = np.vstack(cols)
if pts_mode:
pc = o3d.geometry.PointCloud()
pc.points = o3d.utility.Vector3dVector(P)
pc.colors = o3d.utility.Vector3dVector(C)
try:
o3d.visualization.draw_geometries([pc], window_name="Voxel occupancy (A:red B:green overlap:blue)")
except Exception:
log_step("Open3D visualization failed (headless?)")
else:
# boxes mode: heavy - create box meshes per set (colored)
def boxes_from_list(idx_arr, color):
if idx_arr is None or idx_arr.size == 0:
return o3d.geometry.TriangleMesh()
boxes = []
half = pitch / 2.0
for (i, j, k) in np.asarray(idx_arr, dtype=int):
center = origin + np.array([i + 0.5, j + 0.5, k + 0.5]) * pitch
box = o3d.geometry.TriangleMesh.create_box(width=pitch, height=pitch, depth=pitch)
box.translate(center - np.array([half, half, half]), relative=False)
boxes.append(box)
m = _o3d_concat_meshes(boxes) if boxes else o3d.geometry.TriangleMesh()
if len(m.triangles) > 0:
m.paint_uniform_color(color)
return m
mesh_a = boxes_from_list(only_a_idx, [1, 0, 0])
mesh_b = boxes_from_list(only_b_idx, [0, 1, 0])
mesh_o = boxes_from_list(overlap_idx, [0, 0, 1])
try:
o3d.visualization.draw_geometries([mesh_a, mesh_b, mesh_o], window_name="Voxel boxes")
except Exception:
log_step("Open3D visualization failed (headless?)")
def _iou_voxel(a: o3d.geometry.TriangleMesh, b: o3d.geometry.TriangleMesh, pitch: float) -> float:
a_min, a_max = _o3d_bounds(a)
b_min, b_max = _o3d_bounds(b)
if not _aabb_overlap(a_min, a_max, b_min, b_max):
return 0.0
mn = np.minimum(a_min, b_min)
mx = np.maximum(a_max, b_max)
dims = np.ceil((mx - mn) / pitch).astype(int) + 1
if np.prod(dims) > 400_000_000:
raise MemoryError(f"Voxel grid too large: dims={tuple(int(d) for d in dims)}")
occ_a = _voxelize_to_grid(a, pitch, mn, dims)
occ_b = _voxelize_to_grid(b, pitch, mn, dims)
# visualize_voxel_occupancy(occ_a, occ_b, mn, pitch, pts_mode=True)
inter = np.count_nonzero(occ_a & occ_b)
union = np.count_nonzero(occ_a | occ_b)
return float(inter / union) if union > 0 else 0.0
def visualize_meshes_with_volumes(a: o3d.geometry.TriangleMesh, b: o3d.geometry.TriangleMesh, va: float, vb: float, show_hulls: bool = False) -> None:
"""
Visualize two meshes together with simple coloring and print their computed volumes.
- a : mesh A (will be painted red)
- b : mesh B (will be painted green)
- va, vb : their computed volumes (floats) — printed and shown in the window title
- show_hulls : if True, also compute and show convex hulls (wireframe)
This is a best-effort helper; visualization failures are caught and logged.
"""
try:
ma = _o3d_mesh_copy(a)
mb = _o3d_mesh_copy(b)
ma.paint_uniform_color([1.0, 0.0, 0.0]) # red
mb.paint_uniform_color([0.0, 1.0, 0.0]) # green
geoms = [ma, mb]
if show_hulls:
try:
ha, _ = ma.compute_convex_hull()
hb, _ = mb.compute_convex_hull()
# paint hulls lightly and show wireframe
ha.paint_uniform_color([1.0, 0.6, 0.6])
hb.paint_uniform_color([0.6, 1.0, 0.6])
geoms.extend([ha, hb])
except Exception:
log_step(" Convex hull computation for visualization failed; continuing without hulls")
title = f"Mesh A (red) va={va:.6f} | Mesh B (green) vb={vb:.6f}"
print(title)
try:
o3d.visualization.draw_geometries(geoms, window_name=title, mesh_show_wireframe=True)
except Exception:
log_step("Open3D visualization failed (headless or other issue)")
except Exception as exc:
log_step(f"Visualization helper failed: {exc}")
def _iou_exact(a: o3d.geometry.TriangleMesh, b: o3d.geometry.TriangleMesh) -> float:
a_min, a_max = _o3d_bounds(a)
b_min, b_max = _o3d_bounds(b)
if not _aabb_overlap(a_min, a_max, b_min, b_max):
return 0.0
va = _o3d_mesh_volume_or_hull(a)
vb = _o3d_mesh_volume_or_hull(b)
if va <= 0.0 or vb <= 0.0:
return 0.0
inter = _boolean_intersection_volume(a, b)
union = va + vb - inter
# print(f" Volumes: va={va:.6f} vb={vb:.6f} intersection={inter:.6f}")
# print(f" IoU = {inter:.6f} / {union:.6f} = {float(inter / union) if union > 0 else 0.0:.6f}")
# visualize_meshes_with_volumes(a, b, va, vb, show_hulls=True)
return float(inter / union) if union > 0 else 0.0
def _iou(a: o3d.geometry.TriangleMesh, b: o3d.geometry.TriangleMesh, backend: str, pitch: float) -> float:
if backend == "exact":
return _iou_exact(a, b)
if backend == "voxel":
return _iou_voxel(a, b, pitch)
# auto: try exact; on failure, use voxel
try:
return _iou_exact(a, b)
except Exception:
return _iou_voxel(a, b, pitch)
def _pairwise_iou(gt: List[Comp], pr: List[Comp], backend: str, pitch: float, eps: float) -> np.ndarray:
m, n = len(gt), len(pr)
log_step(f"Computing pairwise IoU matrix ({m}x{n}) using backend='{backend}' (pitch={pitch}, epsilon={eps})")
M = np.zeros((m, n), dtype=float)
progress_stride = max(1, min(50, (m // 10) or 5))
for i, g in enumerate(gt):
for j, p in enumerate(pr):
if not _aabb_overlap(g.aabb_min, g.aabb_max, p.aabb_min, p.aabb_max):
continue
v = _iou(g.mesh, p.mesh, backend, pitch)
M[i, j] = v if v >= eps else 0.0
if VERBOSE and (m > 0) and (((i + 1) % progress_stride == 0) or (i == m - 1)):
log_step(f" IoU progress: processed {i + 1}/{m} GT elements")
log_step("Pairwise IoU matrix ready")
return M
def _union_many(
meshes: List[o3d.geometry.TriangleMesh],
backend: str,
pitch: float,
ref: Optional[o3d.geometry.TriangleMesh] = None
) -> Optional[o3d.geometry.TriangleMesh]:
if not meshes:
return o3d.geometry.TriangleMesh()
if len(meshes) == 1:
return _o3d_mesh_copy(meshes[0])
pitch = float(pitch)
if pitch <= 0:
raise ValueError("voxel pitch must be > 0")
# Try exact first
if backend in ("exact", "auto"):
u = _o3d_boolean_union(meshes)
if u is not None and len(u.triangles) > 0:
return u
if backend == "exact":
# respect user's explicit request
log_step(" Exact union returned empty; falling back to voxel approximation")
# (we deliberately do NOT raise here to keep the pipeline alive)
# ---- voxel fallback ----
bounds = [_o3d_bounds(m) for m in meshes]
if ref is not None:
bounds.append(_o3d_bounds(ref))
mins = np.min(np.stack([b[0] for b in bounds], axis=0), axis=0)
maxs = np.max(np.stack([b[1] for b in bounds], axis=0), axis=0)
ext = np.maximum(maxs - mins, 1e-9)
dims = np.maximum(np.ceil(ext / pitch).astype(int) + 1, 1)
if np.prod(dims) > 200_000_000: # adapt to your RAM budget
log_step(f" Voxel grid too large ({tuple(int(d) for d in dims)}); using triangle concatenation")
return _o3d_concat_meshes(meshes)
if not _LOG_STATE["voxel_union_fallback"]:
log_step(" Falling back to voxel-based union approximation (Open3D)")
_LOG_STATE["voxel_union_fallback"] = True
occ = np.zeros((dims[0], dims[1], dims[2]), dtype=bool)
any_filled = False
for m in meshes:
occ_m = _o3d_voxelize_indices(m, pitch, mins, dims)
any_filled |= occ_m.any()
occ |= occ_m
if not any_filled:
# try a finer pitch once
finer = pitch * 0.5
log_step(" Voxelization empty; retrying with finer pitch")
occ = np.zeros((dims[0]*2, dims[1]*2, dims[2]*2), dtype=bool)
mins2 = mins
dims2 = np.maximum(np.ceil(ext / finer).astype(int) + 1, 1)
if np.prod(dims2) <= 200_000_000:
for m in meshes:
occ |= _o3d_voxelize_indices(m, finer, mins2, dims2)
if occ.any():
u_mesh = _o3d_boxes_from_indices(occ, finer, mins2)
_o3d_clean_mesh(u_mesh)
return u_mesh
log_step(" Still empty after finer pitch; using triangle concatenation")
return _o3d_concat_meshes(meshes)
u_mesh = _o3d_boxes_from_indices(occ, pitch, mins)
if u_mesh is None or len(u_mesh.triangles) == 0:
log_step(" Box instancing produced empty mesh; using triangle concatenation")
return _o3d_concat_meshes(meshes)
_o3d_clean_mesh(u_mesh)
return u_mesh
def _silence_vtk_output(log_to: str | None = None) -> None:
"""Prevent VTK from opening its GUI error window (Windows)."""
try:
import os
# Try VTK 9 logger first (reduces stderr noise)
try:
from vtkmodules.vtkCommonCore import vtkLogger
vtkLogger.SetStderrVerbosity(vtkLogger.VERBOSITY_OFF)
except Exception: