-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscene_composition_pytorch3d.py
More file actions
1861 lines (1522 loc) ยท 84.1 KB
/
scene_composition_pytorch3d.py
File metadata and controls
1861 lines (1522 loc) ยท 84.1 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
# scene_composition_pytorch3d.py - Scene composition using PyTorch3D and Open3D
import os
import sys
import numpy as np
import re
import json
import math
import trimesh
from typing import Dict, List, Optional, Tuple
import open3d as o3d
class SceneComfaposer:
def __init__(self, root_path=None, clip_results_path="/source/sumin/stylin/FlairGPT/retrieval/clip_rerank_results"):
"""
Initialize the scene composer with standardized folder structure
Args:
root_path: Root directory path. If None, uses script directory.
clip_results_path: Path to CLIP rerank results folder
"""
# Determine root path
if root_path is None:
self.root_path = os.path.dirname(os.path.abspath(__file__))
else:
self.root_path = os.path.abspath(root_path)
print(f"Using root path: {self.root_path}")
# Set up standardized paths
self.clip_results_path = clip_results_path
self.layout_file_path = os.path.join(self.root_path, "layout.txt")
self.background_color_path = os.path.join(self.root_path, "background_color.txt")
self.output_path = os.path.join(self.root_path, "output")
# 3D-FUTURE dataset paths
self.dataset_paths = [
"../../dataset/3D-FUTURE-model-part1",
"../../dataset/3D-FUTURE-model-part2",
"../../dataset/3D-FUTURE-model-part3",
"../../dataset/3D-FUTURE-model-part4"
]
# Create output directory if it doesn't exist
os.makedirs(self.output_path, exist_ok=True)
# Validate required files
self.validate_structure()
# Parse configuration files
self.layout_data = self.parse_layout_file()
self.background_colors = self.parse_background_colors()
# Store all scene meshes
self.scene_meshes = []
def validate_structure(self):
"""Validate that required files exist"""
required_paths = [
(self.layout_file_path, "layout.txt"),
]
missing = []
for path, name in required_paths:
if not os.path.exists(path):
missing.append(name)
if missing:
print(f"โ Missing required files: {', '.join(missing)}")
print(f"Expected structure in: {self.root_path}")
print("Required:")
print(" - layout.txt")
sys.exit(1)
else:
print("โ
File structure validated")
# parse_layout_file ํจ์ ์์ (์์ ๋ก๋ฉ ๊ฐ์ )
def parse_layout_file(self):
"""Parse the layout text file and extract room and object information - FIXED VERSION"""
layout_data = {
'room_width': None,
'room_length': None,
'objects': {},
'style': None,
'prompt': None
}
print(f"๐ Reading layout file: {self.layout_file_path}")
with open(self.layout_file_path, 'r') as f:
content = f.read()
# Debug: Show first part of content
print(f"๐ Layout file preview:")
lines = content.split('\n')[:10] # First 10 lines
for i, line in enumerate(lines):
print(f" {i+1:2d}: {line}")
total_lines = len(content.split('\n'))
if total_lines > 10:
print(f" ... (total {total_lines} lines)")
# Extract room dimensions
room_width_match = re.search(r'room_width:\s*(\d+(?:\.\d+)?)', content)
room_length_match = re.search(r'room_length:\s*(\d+(?:\.\d+)?)', content)
if room_width_match:
layout_data['room_width'] = float(room_width_match.group(1))
print(f"๐ Found room width: {layout_data['room_width']}")
if room_length_match:
layout_data['room_length'] = float(room_length_match.group(1))
print(f"๐ Found room length: {layout_data['room_length']}")
# Extract prompt
prompt_match = re.search(r'prompt:\s*(.+)', content)
if prompt_match:
layout_data['prompt'] = prompt_match.group(1)
print(f"๐ Found prompt: {layout_data['prompt'][:50]}...")
# FIXED: Extract ALL objects from position format (including doors and windows)
print(f"\n๐ Searching for ALL objects with position data...")
# Updated pattern to catch all object names (including with numbers)
object_pattern = r'(\w+\d*):\s*\{\'position\':\s*\(([\d\w\.\(\), -]+)\),\s*\'width\':\s*([\d\.]+),\s*\'length\':\s*([\d\.]+)\}'
all_objects_found = 0
doors_windows_found = 0
furniture_found = 0
for match in re.finditer(object_pattern, content):
obj_name = match.group(1)
all_objects_found += 1
# Parse position tuple
position_str = match.group(2)
pos_numbers = re.findall(r'np\.float64\(([\d\.-]+)\)|(\d+(?:\.\d+)?)', position_str)
position = []
for num_match in pos_numbers:
if num_match[0]: # np.float64 format
position.append(float(num_match[0]))
elif num_match[1]: # regular float format
position.append(float(num_match[1]))
if len(position) >= 3:
obj_data = {
'position': (position[0], position[1], position[2]),
'width': float(match.group(3)),
'length': float(match.group(4))
}
# Check if it's a door or window
is_door_window = any(keyword in obj_name.lower() for keyword in ['door', 'window'])
if is_door_window:
doors_windows_found += 1
print(f" ๐ช/๐ช Found door/window: '{obj_name}' at {obj_data['position']}, size {obj_data['width']}x{obj_data['length']}")
else:
furniture_found += 1
print(f" ๐ช Found furniture: '{obj_name}' at {obj_data['position']}, size {obj_data['width']}x{obj_data['length']}")
layout_data['objects'][obj_name] = obj_data
else:
print(f" โ Invalid position data for {obj_name}: {position_str}")
print(f"\n๐ Parsing summary:")
print(f" ๐ฆ Total objects found: {all_objects_found}")
print(f" ๐ช Doors/Windows: {doors_windows_found}")
print(f" ๐ช Furniture: {furniture_found}")
# Extract numbered object names (for reference only, already parsed above)
pattern = re.compile(
r'^\s*(\d+)[\.\)\-:\s]+\*\*([^*]+)\*\*[\s\S]*?(?=^\s*\d+[\.\)\-:\s]+\*\*|$\Z)',
re.MULTILINE
)
numbered_objects = []
for match in pattern.finditer(content):
object_name = match.group(2).strip()
numbered_objects.append(object_name)
if numbered_objects:
print(f"๐ Found {len(numbered_objects)} numbered objects (for reference): {numbered_objects}")
# Extract style description
style_match = re.search(r'style:\s*(.+)', content, re.DOTALL)
if style_match:
layout_data['style'] = style_match.group(1).strip()
print(f"๐จ Found style: {layout_data['style'][:100]}...")
print(f"\nโ
Final object list:")
for name, data in layout_data['objects'].items():
obj_type = "๐ช/๐ช" if any(keyword in name.lower() for keyword in ['door', 'window']) else "๐ช"
print(f" {obj_type} {name}: pos={data['position']}, size={data['width']}x{data['length']}")
return layout_data
# parse_background_colors ํจ์ ์์ (layout.txt ์์ ์ฐ์ ์ฌ์ฉ)
def parse_background_colors(self):
"""Parse layout.txt and extract floor and wall colors from both formats"""
# ๊ธฐ๋ณธ ์์๊ฐ ์ค์
colors = {
'floor_color': (0.8, 0.6, 0.4), # ๊ธฐ๋ณธ ๋ฐ๋ฅ ์์
'wall_color': (0.6, 0.7, 0.6) # ๊ธฐ๋ณธ ๋ฒฝ ์์
}
# layout.txt์์ ์์ ์ ๋ณด ํ์ฑ
if hasattr(self, 'layout_file_path') and os.path.exists(self.layout_file_path):
print(f"๐ Parsing colors from layout.txt: {self.layout_file_path}")
try:
with open(self.layout_file_path, 'r', encoding='utf-8') as f:
content = f.read()
# ๋ ๊ฐ์ง ํ์ ๋ชจ๋ ์๋
colors = self.parse_colors_from_content(content, colors)
except Exception as e:
print(f"โ Error reading layout.txt: {e}")
print("Using default colors")
else:
print(f"๐ Layout file not found, using default colors")
print(f"๐จ Final colors - Floor: {colors['floor_color']}, Wall: {colors['wall_color']}")
return colors
def parse_colors_from_content(self, content, default_colors):
"""Parse colors from content with multiple format support"""
colors = default_colors.copy()
# ์ฐ์ ์์ 1: ๊ฐ๋จํ ํ์ (wall_color: (0.95, 0.95, 0.95, 1.0))
print("๐ Trying simple format first...")
# wall_color ๊ฐ๋จํ ํ์
wall_simple_match = re.search(r"wall_color\s*:\s*\(([^)]+)\)", content)
if wall_simple_match:
try:
rgba_str = wall_simple_match.group(1)
rgba_values = [float(x.strip()) for x in rgba_str.split(',')]
if len(rgba_values) >= 3:
colors['wall_color'] = tuple(rgba_values[:3]) # RGB๋ง ์ฌ์ฉ
print(f"๐จ Parsed wall color (simple format): {colors['wall_color']}")
except Exception as e:
print(f"โ Error parsing wall color (simple): {e}")
# floor_color ๊ฐ๋จํ ํ์
floor_simple_match = re.search(r"floor_color\s*:\s*\(([^)]+)\)", content)
if floor_simple_match:
try:
rgba_str = floor_simple_match.group(1)
rgba_values = [float(x.strip()) for x in rgba_str.split(',')]
if len(rgba_values) >= 3:
colors['floor_color'] = tuple(rgba_values[:3]) # RGB๋ง ์ฌ์ฉ
print(f"๐จ Parsed floor color (simple format): {colors['floor_color']}")
except Exception as e:
print(f"โ Error parsing floor color (simple): {e}")
# ์ฐ์ ์์ 2: ๋์
๋๋ฆฌ ํ์ (๊ฐ๋จํ ํ์์์ ์ฐพ์ง ๋ชปํ ๊ฒฝ์ฐ๋ง)
if colors['wall_color'] == default_colors['wall_color'] or colors['floor_color'] == default_colors['floor_color']:
print("๐ Trying dictionary format...")
# wall_color ๋์
๋๋ฆฌ ํ์ (๊ฐ๋จํ ํ์์์ ๋ชป ์ฐพ์ ๊ฒฝ์ฐ๋ง)
if colors['wall_color'] == default_colors['wall_color']:
wall_dict_match = re.search(r"'wall_color'\s*:\s*\{[^}]*'rgba'\s*:\s*\(([^)]+)\)", content)
if wall_dict_match:
try:
rgba_str = wall_dict_match.group(1)
rgba_values = [float(x.strip()) for x in rgba_str.split(',')]
if len(rgba_values) >= 3:
colors['wall_color'] = tuple(rgba_values[:3]) # RGB๋ง ์ฌ์ฉ
print(f"๐จ Parsed wall color (dict format): {colors['wall_color']}")
except Exception as e:
print(f"โ Error parsing wall color (dict): {e}")
# floor_color ๋์
๋๋ฆฌ ํ์ (๊ฐ๋จํ ํ์์์ ๋ชป ์ฐพ์ ๊ฒฝ์ฐ๋ง)
if colors['floor_color'] == default_colors['floor_color']:
floor_dict_match = re.search(r"'floor_color'\s*:\s*\{[^}]*'rgba'\s*:\s*\(([^)]+)\)", content)
if floor_dict_match:
try:
rgba_str = floor_dict_match.group(1)
rgba_values = [float(x.strip()) for x in rgba_str.split(',')]
if len(rgba_values) >= 3:
colors['floor_color'] = tuple(rgba_values[:3]) # RGB๋ง ์ฌ์ฉ
print(f"๐จ Parsed floor color (dict format): {colors['floor_color']}")
except Exception as e:
print(f"โ Error parsing floor color (dict): {e}")
return colors
def create_room_mesh(self):
"""Create room mesh with floor and walls - ENHANCED VERSION"""
width = self.layout_data['room_width']
length = self.layout_data['room_length']
height = 3.0 # Standard room height
wall_thickness = 0.1
print(f"๐ Creating room: {width}m x {length}m x {height}m")
# Create floor
floor_mesh = self.create_floor_mesh(width, length)
self.scene_meshes.append({
'mesh': floor_mesh,
'name': 'floor',
'color': self.background_colors['floor_color']
})
# Create walls with openings - ENHANCED
wall_meshes = self.create_wall_meshes_enhanced(width, length, height, wall_thickness)
for wall_mesh, wall_name in wall_meshes:
self.scene_meshes.append({
'mesh': wall_mesh,
'name': wall_name,
'color': self.background_colors['wall_color']
})
def create_floor_mesh(self, width, length):
"""Create floor mesh"""
# Create floor as a box mesh
floor_mesh = trimesh.creation.box(
extents=[width, length, 0.01],
transform=trimesh.transformations.translation_matrix([width/2, length/2, -0.005])
)
return floor_mesh
def prepare_mesh_for_boolean(self, mesh):
"""Check if mesh is ready for boolean operations"""
try:
# Check if mesh is watertight
if hasattr(mesh, 'is_watertight'):
return mesh.is_watertight
# Fallback check
return len(mesh.vertices) > 0 and len(mesh.faces) > 0
except:
return False
def fix_mesh_for_boolean(self, mesh):
"""Attempt to fix mesh for boolean operations"""
try:
print(f" ๐ง Fixing mesh for boolean operations...")
# Remove duplicate vertices and faces
if hasattr(mesh, 'remove_duplicate_faces'):
mesh.remove_duplicate_faces()
if hasattr(mesh, 'remove_degenerate_faces'):
mesh.remove_degenerate_faces()
# Fix normals
if hasattr(mesh, 'fix_normals'):
mesh.fix_normals()
# Fill holes if possible
if hasattr(mesh, 'fill_holes'):
mesh.fill_holes()
# Process mesh to clean it up
if hasattr(mesh, 'process'):
mesh.process()
print(f" โ
Mesh fixed")
return mesh
except Exception as e:
print(f" โ ๏ธ Mesh fixing failed: {e}")
return mesh
def manual_mesh_subtraction(self, wall_mesh, cutter_mesh, opening, wall_name):
"""Manual mesh subtraction as fallback method"""
print(f" ๐ง Performing manual mesh subtraction...")
# Get wall and cutter bounds
wall_bounds = wall_mesh.bounds
cutter_bounds = cutter_mesh.bounds
# Create a new wall mesh by removing vertices/faces that overlap with cutter
vertices = wall_mesh.vertices.copy()
faces = wall_mesh.faces.copy()
# Find vertices inside the cutter bounds (simplified approach)
inside_mask = np.ones(len(vertices), dtype=bool)
for i, vertex in enumerate(vertices):
# Check if vertex is inside cutter bounds
if (cutter_bounds[0][0] <= vertex[0] <= cutter_bounds[1][0] and
cutter_bounds[0][1] <= vertex[1] <= cutter_bounds[1][1] and
cutter_bounds[0][2] <= vertex[2] <= cutter_bounds[1][2]):
inside_mask[i] = False
# Keep only vertices outside the cutter
outside_vertices = vertices[inside_mask]
# Map old vertex indices to new indices
vertex_map = {}
new_idx = 0
for old_idx, keep in enumerate(inside_mask):
if keep:
vertex_map[old_idx] = new_idx
new_idx += 1
# Filter faces that reference removed vertices
new_faces = []
for face in faces:
if all(idx in vertex_map for idx in face):
new_face = [vertex_map[idx] for idx in face]
new_faces.append(new_face)
if len(outside_vertices) > 0 and len(new_faces) > 0:
# Create new mesh
new_mesh = trimesh.Trimesh(vertices=outside_vertices, faces=new_faces)
return new_mesh
else:
print(f" โ ๏ธ Manual subtraction resulted in empty mesh")
return wall_mesh
def debug_wall_cutting(self, wall_mesh, cutter_mesh, opening, wall_name):
"""Debug function to understand why cutting isn't working"""
print(f"๐ DEBUGGING WALL CUTTING for {wall_name}")
# 1. Check mesh properties
print(f" ๐ Wall mesh info:")
print(f" - Vertices: {len(wall_mesh.vertices)}")
print(f" - Faces: {len(wall_mesh.faces)}")
print(f" - Is watertight: {getattr(wall_mesh, 'is_watertight', 'unknown')}")
print(f" - Bounds: {wall_mesh.bounds}")
print(f" ๐ Cutter mesh info:")
print(f" - Vertices: {len(cutter_mesh.vertices)}")
print(f" - Faces: {len(cutter_mesh.faces)}")
print(f" - Is watertight: {getattr(cutter_mesh, 'is_watertight', 'unknown')}")
print(f" - Bounds: {cutter_mesh.bounds}")
# 2. Check intersection
try:
# Check if meshes actually intersect
intersection = wall_mesh.intersection(cutter_mesh)
if intersection is not None and len(intersection.vertices) > 0:
print(f" โ
Meshes DO intersect - intersection volume: {getattr(intersection, 'volume', 'unknown')}")
else:
print(f" โ Meshes DO NOT intersect properly")
return False
except Exception as e:
print(f" โ ๏ธ Could not check intersection: {e}")
# 3. Check if cutter is inside wall bounds
wall_bounds = wall_mesh.bounds
cutter_bounds = cutter_mesh.bounds
print(f" ๐ Bounds comparison:")
print(f" Wall: X({wall_bounds[0][0]:.3f}, {wall_bounds[1][0]:.3f}) Y({wall_bounds[0][1]:.3f}, {wall_bounds[1][1]:.3f}) Z({wall_bounds[0][2]:.3f}, {wall_bounds[1][2]:.3f})")
print(f" Cutter: X({cutter_bounds[0][0]:.3f}, {cutter_bounds[1][0]:.3f}) Y({cutter_bounds[0][1]:.3f}, {cutter_bounds[1][1]:.3f}) Z({cutter_bounds[0][2]:.3f}, {cutter_bounds[1][2]:.3f})")
# Check overlap
overlap_x = not (cutter_bounds[1][0] < wall_bounds[0][0] or cutter_bounds[0][0] > wall_bounds[1][0])
overlap_y = not (cutter_bounds[1][1] < wall_bounds[0][1] or cutter_bounds[0][1] > wall_bounds[1][1])
overlap_z = not (cutter_bounds[1][2] < wall_bounds[0][2] or cutter_bounds[0][2] > wall_bounds[1][2])
print(f" Overlap: X={overlap_x}, Y={overlap_y}, Z={overlap_z}")
if not (overlap_x and overlap_y and overlap_z):
print(f" โ NO OVERLAP - This is why cutting fails!")
return False
return True
def cut_wall_openings_enhanced(self, wall_mesh, wall_name, openings, room_width, room_length, room_height):
"""Enhanced wall cutting with better debugging"""
if not openings:
return wall_mesh
print(f"๐ช Cutting {len(openings)} openings in {wall_name}...")
current_wall = wall_mesh.copy()
for i, opening in enumerate(openings):
try:
print(f" ๐ง Processing opening {i+1}/{len(openings)}: {opening['type']} '{opening['name']}'")
# Create cutter mesh
cutter_mesh = self.create_opening_cutter_enhanced(opening, wall_name, room_width, room_length)
if cutter_mesh is None:
print(f" โ Failed to create cutter for {opening['name']}")
continue
# Debug intersection
print(f" ๐ Wall bounds: {current_wall.bounds}")
print(f" ๐ Cutter bounds: {cutter_mesh.bounds}")
# Try boolean operation
success = False
# Method 1: Try manifold
try:
print(f" ๐ฏ Trying manifold engine...")
result = current_wall.difference(cutter_mesh, engine='manifold')
if result is not None and len(result.vertices) > 0:
# Check if it actually changed
if len(result.vertices) != len(current_wall.vertices):
current_wall = result
success = True
print(f" โ
Manifold successful: {len(current_wall.vertices)} vertices")
else:
print(f" โ ๏ธ Manifold returned same mesh")
else:
print(f" โ Manifold returned empty result")
except Exception as e:
print(f" โ Manifold failed: {e}")
# Method 2: Try blender if manifold failed
if not success:
try:
print(f" ๐ฏ Trying blender engine...")
result = current_wall.difference(cutter_mesh, engine='blender')
if result is not None and len(result.vertices) > 0:
if len(result.vertices) != len(current_wall.vertices):
current_wall = result
success = True
print(f" โ
Blender successful: {len(current_wall.vertices)} vertices")
else:
print(f" โ ๏ธ Blender returned same mesh")
else:
print(f" โ Blender returned empty result")
except Exception as e:
print(f" โ Blender failed: {e}")
if success:
print(f" โ
Successfully cut {opening['type']} opening")
else:
print(f" โ Failed to cut {opening['type']} opening")
except Exception as e:
print(f" โ Error processing opening {i+1}: {e}")
import traceback
traceback.print_exc()
return current_wall
def create_multiple_cutters(self, opening, wall_name, room_width, room_length, room_height):
"""Create multiple cutter strategies with different sizes and positions"""
wall_thickness = 0.1
pos_x, pos_y = opening['position']
opening_width = opening['width']
opening_height = opening['height']
opening_bottom = opening['bottom_height']
wall_direction = wall_name.replace('_wall', '')
cutters = []
# Strategy 1: Exact size cutter
cutter1 = self.create_exact_cutter(pos_x, pos_y, opening_width, opening_height, opening_bottom,
wall_direction, room_width, room_length, wall_thickness)
cutters.append((cutter1, "Exact size"))
# Strategy 2: Oversized cutter
cutter2 = self.create_oversized_cutter(pos_x, pos_y, opening_width, opening_height, opening_bottom,
wall_direction, room_width, room_length, wall_thickness)
cutters.append((cutter2, "Oversized"))
# Strategy 3: Extended through cutter
cutter3 = self.create_extended_cutter(pos_x, pos_y, opening_width, opening_height, opening_bottom,
wall_direction, room_width, room_length, wall_thickness, room_height)
cutters.append((cutter3, "Extended through"))
return cutters
def create_exact_cutter(self, pos_x, pos_y, width, height, bottom, wall_direction, room_width, room_length, wall_thickness):
"""Create exact size cutter"""
try:
if wall_direction == 'front':
pos = [pos_x, -wall_thickness/2, bottom + height/2]
extents = [width, wall_thickness + 0.02, height]
elif wall_direction == 'back':
pos = [pos_x, room_length + wall_thickness/2, bottom + height/2]
extents = [width, wall_thickness + 0.02, height]
elif wall_direction == 'left':
pos = [-wall_thickness/2, pos_y, bottom + height/2]
extents = [wall_thickness + 0.02, width, height]
elif wall_direction == 'right':
pos = [room_width + wall_thickness/2, pos_y, bottom + height/2]
extents = [wall_thickness + 0.02, width, height]
else:
return None
return trimesh.creation.box(extents=extents, transform=trimesh.transformations.translation_matrix(pos))
except:
return None
def create_oversized_cutter(self, pos_x, pos_y, width, height, bottom, wall_direction, room_width, room_length, wall_thickness):
"""Create oversized cutter with margins"""
try:
margin = 0.1 # 10cm margin
if wall_direction == 'front':
pos = [pos_x, -wall_thickness/2, bottom + height/2]
extents = [width + margin, wall_thickness + 0.1, height + margin]
elif wall_direction == 'back':
pos = [pos_x, room_length + wall_thickness/2, bottom + height/2]
extents = [width + margin, wall_thickness + 0.1, height + margin]
elif wall_direction == 'left':
pos = [-wall_thickness/2, pos_y, bottom + height/2]
extents = [wall_thickness + 0.1, width + margin, height + margin]
elif wall_direction == 'right':
pos = [room_width + wall_thickness/2, pos_y, bottom + height/2]
extents = [wall_thickness + 0.1, width + margin, height + margin]
else:
return None
return trimesh.creation.box(extents=extents, transform=trimesh.transformations.translation_matrix(pos))
except:
return None
def create_extended_cutter(self, pos_x, pos_y, width, height, bottom, wall_direction, room_width, room_length, wall_thickness, room_height):
"""Create cutter that extends through entire room"""
try:
if wall_direction == 'front':
pos = [pos_x, room_length/2, bottom + height/2]
extents = [width, room_length + wall_thickness * 2, height]
elif wall_direction == 'back':
pos = [pos_x, room_length/2, bottom + height/2]
extents = [width, room_length + wall_thickness * 2, height]
elif wall_direction == 'left':
pos = [room_width/2, pos_y, bottom + height/2]
extents = [room_width + wall_thickness * 2, width, height]
elif wall_direction == 'right':
pos = [room_width/2, pos_y, bottom + height/2]
extents = [room_width + wall_thickness * 2, width, height]
else:
return None
return trimesh.creation.box(extents=extents, transform=trimesh.transformations.translation_matrix(pos))
except:
return None
def try_boolean_methods(self, wall_mesh, cutter_mesh, strategy_name):
"""Try different boolean methods in order"""
methods = [
('manifold', lambda w, c: w.difference(c, engine='manifold')),
('blender', lambda w, c: w.difference(c, engine='blender')),
('auto', lambda w, c: w.difference(c)),
('trimesh_boolean', self.trimesh_boolean_difference),
]
for method_name, method_func in methods:
try:
print(f" ๐ Trying {method_name} method...")
result = method_func(wall_mesh, cutter_mesh)
if result is not None and len(result.vertices) > 0:
print(f" โ
{method_name} method successful")
return result
else:
print(f" โ {method_name} method returned empty result")
except Exception as e:
print(f" โ {method_name} method failed: {e}")
return None
def trimesh_boolean_difference(self, wall_mesh, cutter_mesh):
"""Use trimesh.boolean module directly"""
import trimesh.boolean
try:
return trimesh.boolean.difference([wall_mesh, cutter_mesh], engine='auto')
except:
return trimesh.boolean.difference([wall_mesh, cutter_mesh])
def mesh_actually_changed(self, original_mesh, new_mesh):
"""Check if the mesh actually changed after boolean operation"""
try:
# Compare vertex counts
if len(original_mesh.vertices) == len(new_mesh.vertices):
# If same number of vertices, check if positions are different
if np.allclose(original_mesh.vertices, new_mesh.vertices, atol=1e-6):
return False
# Compare volumes if available
try:
original_volume = getattr(original_mesh, 'volume', None)
new_volume = getattr(new_mesh, 'volume', None)
if original_volume is not None and new_volume is not None:
volume_diff = abs(original_volume - new_volume)
if volume_diff < 1e-6: # Very small difference
return False
print(f" ๐ Volume changed: {original_volume:.6f} โ {new_volume:.6f} (diff: {volume_diff:.6f})")
except:
pass
return True
except Exception as e:
print(f" โ ๏ธ Could not compare meshes: {e}")
return True # Assume it changed if we can't tell
def manual_vertex_removal(self, wall_mesh, opening, wall_name, room_width, room_length):
"""Last resort: manually remove vertices in the opening area"""
print(f" ๐ง Attempting manual vertex removal...")
try:
wall_direction = wall_name.replace('_wall', '')
pos_x, pos_y = opening['position']
width = opening['width']
height = opening['height']
bottom = opening['bottom_height']
vertices = wall_mesh.vertices.copy()
faces = wall_mesh.faces.copy()
# Define removal bounds based on wall direction
if wall_direction in ['front', 'back']:
# Remove vertices in X-Z plane
x_min, x_max = pos_x - width/2, pos_x + width/2
z_min, z_max = bottom, bottom + height
remove_mask = (
(vertices[:, 0] >= x_min) & (vertices[:, 0] <= x_max) &
(vertices[:, 2] >= z_min) & (vertices[:, 2] <= z_max)
)
else: # left, right
# Remove vertices in Y-Z plane
y_min, y_max = pos_y - width/2, pos_y + width/2
z_min, z_max = bottom, bottom + height
remove_mask = (
(vertices[:, 1] >= y_min) & (vertices[:, 1] <= y_max) &
(vertices[:, 2] >= z_min) & (vertices[:, 2] <= z_max)
)
# Keep vertices outside the opening area
keep_mask = ~remove_mask
removed_count = np.sum(remove_mask)
if removed_count > 0:
print(f" ๐ Removing {removed_count} vertices")
# Keep only vertices outside opening
new_vertices = vertices[keep_mask]
# Create vertex mapping
vertex_map = {}
new_idx = 0
for old_idx, keep in enumerate(keep_mask):
if keep:
vertex_map[old_idx] = new_idx
new_idx += 1
# Filter faces
new_faces = []
for face in faces:
if all(idx in vertex_map for idx in face):
new_face = [vertex_map[idx] for idx in face]
new_faces.append(new_face)
if len(new_vertices) > 0 and len(new_faces) > 0:
result_mesh = trimesh.Trimesh(vertices=new_vertices, faces=new_faces)
print(f" โ
Manual removal successful: {len(new_vertices)} vertices, {len(new_faces)} faces")
return result_mesh
print(f" โ ๏ธ Manual removal had no effect")
return wall_mesh
except Exception as e:
print(f" โ Manual removal failed: {e}")
return wall_mesh
def create_wall_meshes_enhanced(self, width, length, height, wall_thickness):
"""Create wall meshes with door and window openings - ENHANCED VERSION"""
walls = []
# Wall positions and dimensions
wall_configs = [
('back_wall', [width/2, length + wall_thickness/2, height/2], [width + 2*wall_thickness, wall_thickness, height]),
('front_wall', [width/2, -wall_thickness/2, height/2], [width + 2*wall_thickness, wall_thickness, height]),
('left_wall', [-wall_thickness/2, length/2, height/2], [wall_thickness, length, height]),
('right_wall', [width + wall_thickness/2, length/2, height/2], [wall_thickness, length, height])
]
for wall_name, position, dimensions in wall_configs:
try:
print(f"๐๏ธ Creating {wall_name}...")
# Create basic wall
wall_mesh = trimesh.creation.box(
extents=dimensions,
transform=trimesh.transformations.translation_matrix(position)
)
# Check for openings on this wall
openings = self.get_openings_for_wall(wall_name, width, length)
if openings:
print(f" ๐ช Found {len(openings)} openings for {wall_name}")
# Cut openings
wall_mesh = self.cut_wall_openings_enhanced(wall_mesh, wall_name, openings, width, length, height)
else:
print(f" โน๏ธ No openings for {wall_name}")
walls.append((wall_mesh, wall_name))
print(f" โ
{wall_name} created successfully")
except Exception as e:
print(f" โ Error creating {wall_name}: {e}")
import traceback
traceback.print_exc()
# Create simple wall as fallback
simple_wall = trimesh.creation.box(
extents=dimensions,
transform=trimesh.transformations.translation_matrix(position)
)
walls.append((simple_wall, wall_name))
return walls
def determine_wall_for_opening(self, pos_x, pos_y, room_width, room_length):
"""Determine which wall an opening belongs to based on its position - IMPROVED"""
tolerance = 0.3 # Increased tolerance
print(f" ๐งฎ Determining wall for position ({pos_x:.2f}, {pos_y:.2f})")
print(f" ๐ Room dimensions: {room_width}m x {room_length}m")
# Calculate distances to each wall
distances = {
'front': abs(pos_y - 0), # Distance to front wall (y=0)
'back': abs(pos_y - room_length), # Distance to back wall (y=room_length)
'left': abs(pos_x - 0), # Distance to left wall (x=0)
'right': abs(pos_x - room_width) # Distance to right wall (x=room_width)
}
print(f" ๐ Distances to walls:")
for wall, dist in distances.items():
print(f" {wall}: {dist:.3f}m")
# Find the closest wall
closest_wall = min(distances, key=distances.get)
closest_distance = distances[closest_wall]
print(f" ๐ฏ Closest wall: {closest_wall} (distance: {closest_distance:.3f}m)")
# Check if it's within tolerance
if closest_distance <= tolerance:
print(f" โ
Within tolerance ({tolerance}m), assigning to {closest_wall} wall")
return closest_wall
else:
print(f" โ ๏ธ Distance {closest_distance:.3f}m > tolerance {tolerance}m, but assigning to {closest_wall} anyway")
return closest_wall
def get_openings_for_wall(self, wall_name, room_width, room_length):
"""Get door and window openings for a specific wall - IMPROVED VERSION"""
openings = []
wall_direction = wall_name.replace('_wall', '')
print(f"๐ Checking for openings on {wall_name} (direction: {wall_direction})")
doors_windows_found = 0
for obj_name, obj_data in self.layout_data['objects'].items():
# Check if this is a door or window
if any(keyword in obj_name.lower() for keyword in ['door', 'window']):
doors_windows_found += 1
opening_type = 'door' if 'door' in obj_name.lower() else 'window'
pos_x, pos_y, rotation = obj_data['position']
width = obj_data['width']
print(f" ๐ Checking {opening_type} '{obj_name}' at ({pos_x:.2f}, {pos_y:.2f}) for {wall_direction} wall")
wall_for_opening = self.determine_wall_for_opening(pos_x, pos_y, room_width, room_length)
print(f" ๐ Determined wall: {wall_for_opening}")
if wall_for_opening == wall_direction:
opening_data = {
'type': opening_type,
'position': (pos_x, pos_y),
'width': width,
'height': 2.1 if opening_type == 'door' else 1.2,
'bottom_height': 0 if opening_type == 'door' else 1.0,
'name': obj_name
}
openings.append(opening_data)
print(f" โ
Added {opening_type} '{obj_name}' to {wall_direction} wall")
else:
print(f" โญ๏ธ {opening_type} '{obj_name}' belongs to {wall_for_opening} wall, not {wall_direction}")
print(f" ๐ Found {doors_windows_found} total doors/windows, {len(openings)} for {wall_name}")
return openings
def determine_wall_for_opening(self, pos_x, pos_y, room_width, room_length):
"""Determine which wall an opening belongs to"""
tolerance = 0.2
if abs(pos_y) < tolerance:
return 'front'
elif abs(pos_y - room_length) < tolerance:
return 'back'
elif abs(pos_x) < tolerance:
return 'left'
elif abs(pos_x - room_width) < tolerance:
return 'right'
else:
distances = {
'front': pos_y,
'back': room_length - pos_y,
'left': pos_x,
'right': room_width - pos_x
}
return min(distances, key=distances.get)
def cut_wall_openings_enhanced(self, wall_mesh, wall_name, openings, room_width, room_length, room_height):
"""Enhanced wall cutting with better debugging"""
if not openings:
return wall_mesh
print(f"๐ช Cutting {len(openings)} openings in {wall_name}...")
current_wall = wall_mesh.copy()
for i, opening in enumerate(openings):
try:
print(f" ๐ง Processing opening {i+1}/{len(openings)}: {opening['type']} '{opening['name']}'")
# Create cutter mesh
cutter_mesh = self.create_opening_cutter_enhanced(opening, wall_name, room_width, room_length)
if cutter_mesh is None:
print(f" โ Failed to create cutter for {opening['name']}")
continue
# Debug intersection
print(f" ๐ Wall bounds: {current_wall.bounds}")
print(f" ๐ Cutter bounds: {cutter_mesh.bounds}")
# Try boolean operation
success = False
# Method 1: Try manifold
try:
print(f" ๐ฏ Trying manifold engine...")
result = current_wall.difference(cutter_mesh, engine='manifold')
if result is not None and len(result.vertices) > 0:
# Check if it actually changed
if len(result.vertices) != len(current_wall.vertices):
current_wall = result
success = True
print(f" โ
Manifold successful: {len(current_wall.vertices)} vertices")
else:
print(f" โ ๏ธ Manifold returned same mesh")
else:
print(f" โ Manifold returned empty result")
except Exception as e:
print(f" โ Manifold failed: {e}")
# Method 2: Try blender if manifold failed
if not success:
try:
print(f" ๐ฏ Trying blender engine...")
result = current_wall.difference(cutter_mesh, engine='blender')
if result is not None and len(result.vertices) > 0:
if len(result.vertices) != len(current_wall.vertices):
current_wall = result
success = True
print(f" โ
Blender successful: {len(current_wall.vertices)} vertices")
else:
print(f" โ ๏ธ Blender returned same mesh")
else:
print(f" โ Blender returned empty result")
except Exception as e:
print(f" โ Blender failed: {e}")
if success:
print(f" โ
Successfully cut {opening['type']} opening")
else:
print(f" โ Failed to cut {opening['type']} opening")
except Exception as e:
print(f" โ Error processing opening {i+1}: {e}")
import traceback
traceback.print_exc()
return current_wall
def create_opening_cutter_enhanced(self, opening, wall_name, room_width, room_length):
"""Enhanced opening cutter creation"""
wall_thickness = 0.1
pos_x, pos_y = opening['position']
opening_width = opening['width']
opening_height = opening['height']
opening_bottom = opening['bottom_height']
wall_direction = wall_name.replace('_wall', '')
# Add extra margin for reliable cutting
margin = 0.05
extended_thickness = wall_thickness + 2 * margin
print(f" ๐ฆ Creating cutter for {opening['type']} on {wall_direction} wall")
print(f" ๐ Position: ({pos_x:.2f}, {pos_y:.2f})")
print(f" ๐ Size: {opening_width}m x {opening_height}m")
# Determine cutter position based on wall direction