-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstep_ops.py
More file actions
1052 lines (896 loc) · 40.2 KB
/
Copy pathstep_ops.py
File metadata and controls
1052 lines (896 loc) · 40.2 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
"""
step_ops.py
STEP file parsing, triangulation, and face unfolding CLI module for Pathstitch.
"""
import sys
import json
import argparse
import os
import math
from typing import Dict, List, Any, Tuple, Optional
import ezdxf
from OCC.Core.STEPControl import STEPControl_Reader
from OCC.Core.IFSelect import IFSelect_RetDone
from OCC.Core.TopExp import TopExp_Explorer
from OCC.Core.TopAbs import TopAbs_SOLID, TopAbs_SHELL, TopAbs_FACE, TopAbs_EDGE
from OCC.Core.BRepMesh import BRepMesh_IncrementalMesh
from OCC.Core.BRep import BRep_Tool
from OCC.Core.TopLoc import TopLoc_Location
from OCC.Core.GProp import GProp_GProps
from OCC.Core.BRepGProp import brepgprop
from pathstitch_core.surface_unfold import get_surface_type, unfold_face_geometry, save_polylines_to_dxf, triangulate_face, parameterize_mesh
def load_step_shape(file_path: str):
"""Loads a STEP, STL, or OBJ file and returns its consolidated shape."""
if not os.path.exists(file_path):
raise FileNotFoundError(f"3D file not found: {file_path}")
ext = os.path.splitext(file_path)[1].lower()
if ext == ".stl":
from OCC.Core.StlAPI import StlAPI_Reader
from OCC.Core.TopoDS import TopoDS_Shape
reader = StlAPI_Reader()
shape = TopoDS_Shape()
success = reader.Read(shape, file_path)
if not success or shape.IsNull():
raise ValueError(f"Failed to read STL file: {file_path}")
return shape
elif ext == ".obj":
from OCC.Core.gp import gp_Pnt
from OCC.Core.BRepBuilderAPI import BRepBuilderAPI_MakePolygon, BRepBuilderAPI_MakeFace
from OCC.Core.TopoDS import TopoDS_Compound
from OCC.Core.BRep import BRep_Builder
vertices = []
builder = BRep_Builder()
compound = TopoDS_Compound()
builder.MakeCompound(compound)
has_faces = False
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
parts = line.split()
if not parts:
continue
cmd = parts[0].lower()
if cmd == "v":
if len(parts) >= 4:
try:
x = float(parts[1])
y = float(parts[2])
z = float(parts[3])
vertices.append(gp_Pnt(x, y, z))
except ValueError:
pass
elif cmd == "f":
face_vertices = []
for p in parts[1:]:
v_idx_str = p.split("/")[0]
try:
v_idx = int(v_idx_str)
if v_idx > 0:
v_idx = v_idx - 1
elif v_idx < 0:
v_idx = len(vertices) + v_idx
if 0 <= v_idx < len(vertices):
face_vertices.append(vertices[v_idx])
except ValueError:
pass
if len(face_vertices) >= 3:
try:
poly = BRepBuilderAPI_MakePolygon()
for v in face_vertices:
poly.Add(v)
poly.Close()
face_maker = BRepBuilderAPI_MakeFace(poly.Wire())
if not face_maker.IsDone():
continue
face = face_maker.Face()
if not face.IsNull():
builder.Add(compound, face)
has_faces = True
except Exception:
pass
if not has_faces:
raise ValueError(f"No valid faces could be parsed from OBJ file: {file_path}")
return compound
else:
# Default to STEP
reader = STEPControl_Reader()
status = reader.ReadFile(file_path)
if status != IFSelect_RetDone:
raise ValueError(f"STEP control reader failed to read. Status code: {status}")
reader.TransferRoots()
return reader.OneShape()
def get_solid_bodies(shape) -> List[Any]:
"""Isolates and returns all solid bodies (or shells as fallback)."""
bodies = []
# 1. Search for Solids
exp = TopExp_Explorer(shape, TopAbs_SOLID)
while exp.More():
bodies.append(exp.Current())
exp.Next()
# 2. Search for Shells if no Solids found
if not bodies:
exp = TopExp_Explorer(shape, TopAbs_SHELL)
while exp.More():
bodies.append(exp.Current())
exp.Next()
# 3. Fallback: treat the entire shape as a single body if it contains any faces
if not bodies:
exp = TopExp_Explorer(shape, TopAbs_FACE)
if exp.More():
bodies.append(shape)
return bodies
def op_list_bodies(args: Dict[str, Any]) -> Dict[str, Any]:
"""
Triangulates the STEP file bodies and returns their faces, types,
and 3D coordinates for rendering in Three.js.
"""
input_path = args.get("input")
if not input_path:
return {"status": "error", "message": "Input path must be specified."}
try:
shape = load_step_shape(input_path)
bodies = get_solid_bodies(shape)
bodies_data = []
global_min = [float("inf"), float("inf"), float("inf")]
global_max = [float("-inf"), float("-inf"), float("-inf")]
for b_idx, body in enumerate(bodies):
# Run mesh triangulation (0.3mm linear deflection deflection tolerance is a good speed/detail trade-off)
BRepMesh_IncrementalMesh(body, 0.05)
# Map all edges of this body
from OCC.Core.TopTools import TopTools_IndexedMapOfShape
from OCC.Core.TopoDS import topods
emap = TopTools_IndexedMapOfShape()
edge_exp = TopExp_Explorer(body, TopAbs_EDGE)
while edge_exp.More():
emap.Add(topods.Edge(edge_exp.Current()))
edge_exp.Next()
# Build edge to faces adjacency map
edge_to_faces = {}
faces_list = []
face_exp = TopExp_Explorer(body, TopAbs_FACE)
f_idx = 0
while face_exp.More():
face = face_exp.Current()
face_exp.Next()
# Traverse edges of this face to record adjacency
e_exp = TopExp_Explorer(face, TopAbs_EDGE)
while e_exp.More():
edge = topods.Edge(e_exp.Current())
eid = emap.Add(edge)
edge_to_faces.setdefault(eid, []).append(f_idx)
e_exp.Next()
stype = get_surface_type(face)
# Area calculation
gprops = GProp_GProps()
brepgprop.SurfaceProperties(face, gprops)
area = gprops.Mass()
# Retrieve triangulation
loc = TopLoc_Location()
tri = BRep_Tool.Triangulation(face, loc)
vertices = []
indices = []
if tri:
trans = loc.Transformation()
for i in range(1, tri.NbNodes() + 1):
pnt = tri.Node(i).Transformed(trans)
px, py, pz = float(pnt.X()), float(pnt.Y()), float(pnt.Z())
vertices.extend([px, py, pz])
# Update bounding box
global_min[0] = min(global_min[0], px)
global_min[1] = min(global_min[1], py)
global_min[2] = min(global_min[2], pz)
global_max[0] = max(global_max[0], px)
global_max[1] = max(global_max[1], py)
global_max[2] = max(global_max[2], pz)
for i in range(1, tri.NbTriangles() + 1):
t = tri.Triangle(i)
idx1, idx2, idx3 = t.Get()
indices.extend([idx1 - 1, idx2 - 1, idx3 - 1])
faces_list.append({
"face_index": f_idx,
"type": stype,
"area": float(area),
"vertices": vertices,
"indices": indices
})
f_idx += 1
# Now build the edges list for this body
edges_list = []
from OCC.Core.BRepAdaptor import BRepAdaptor_Curve
for e_idx in range(1, emap.Size() + 1):
edge = topods.Edge(emap.FindKey(e_idx))
try:
adaptor = BRepAdaptor_Curve(edge)
u_start = adaptor.FirstParameter()
u_end = adaptor.LastParameter()
try:
from OCC.Core.GeomAbs import GeomAbs_Line
is_line = (adaptor.GetType() == GeomAbs_Line)
except Exception:
is_line = False
samples = 1 if is_line else 24
pts = []
for i in range(samples + 1):
t = u_start + (u_end - u_start) * (i / samples)
p = adaptor.Value(t)
pts.extend([float(p.X()), float(p.Y()), float(p.Z())])
except Exception:
pts = []
edges_list.append({
"edge_index": e_idx,
"vertices": pts,
"faces": edge_to_faces.get(e_idx, [])
})
bodies_data.append({
"body_index": b_idx,
"name": f"Body {b_idx + 1}",
"faces": faces_list,
"edges": edges_list
})
# If no vertices were found, reset bounding box
if global_min[0] == float("inf"):
global_min = [0.0, 0.0, 0.0]
global_max = [0.0, 0.0, 0.0]
bbox = {
"min": global_min,
"max": global_max,
"center": [
(global_min[0] + global_max[0]) / 2.0,
(global_min[1] + global_max[1]) / 2.0,
(global_min[2] + global_max[2]) / 2.0
]
}
return {
"status": "ok",
"data": {
"bodies": bodies_data,
"bbox": bbox
}
}
except Exception as e:
import traceback
return {"status": "error", "message": f"Failed to list solid bodies: {str(e)}\n{traceback.format_exc()}"}
def get_dxf_bounds(msp) -> Optional[Tuple[float, float, float, float]]:
"""Calculates the 2D bounding box of all renderable geometries in the modelspace."""
from ezdxf.path import make_path
min_x, min_y = float('inf'), float('inf')
max_x, max_y = float('-inf'), float('-inf')
found = False
for ent in msp:
if ent.dxftype() == "LINE":
min_x = min(min_x, ent.dxf.start.x, ent.dxf.end.x)
max_x = max(max_x, ent.dxf.start.x, ent.dxf.end.x)
min_y = min(min_y, ent.dxf.start.y, ent.dxf.end.y)
max_y = max(max_y, ent.dxf.start.y, ent.dxf.end.y)
found = True
elif ent.dxftype() in ("CIRCLE", "ARC"):
cx, cy = ent.dxf.center.x, ent.dxf.center.y
r = ent.dxf.radius
min_x = min(min_x, cx - r)
max_x = max(max_x, cx + r)
min_y = min(min_y, cy - r)
max_y = max(max_y, cy + r)
found = True
elif ent.dxftype() in ("LWPOLYLINE", "POLYLINE"):
for p in ent.get_points() if hasattr(ent, 'get_points') else ent.points:
min_x = min(min_x, p[0])
max_x = max(max_x, p[0])
min_y = min(min_y, p[1])
max_y = max(max_y, p[1])
found = True
elif ent.dxftype() in ("SPLINE", "ELLIPSE"):
try:
path = make_path(ent)
for p in path.flattening(distance=0.1):
min_x = min(min_x, p.x)
max_x = max(max_x, p.x)
min_y = min(min_y, p.y)
max_y = max(max_y, p.y)
found = True
except Exception:
pass
if not found:
return None
return min_x, min_y, max_x, max_y
def op_unfold_face(args: Dict[str, Any]) -> Dict[str, Any]:
"""
Unfolds a specific face of a specific body to a DXF flat pattern.
Appends and arranges to the right of any existing DXF geometry if existing_dxf is provided.
"""
input_path = args.get("input")
output_path = args.get("output")
body_idx = args.get("body_index")
face_idx = args.get("face_index")
existing_dxf = args.get("existing_dxf")
if not input_path or not output_path or body_idx is None or face_idx is None:
return {"status": "error", "message": "Missing required arguments: input, output, body_index, face_index."}
try:
shape = load_step_shape(input_path)
bodies = get_solid_bodies(shape)
if body_idx < 0 or body_idx >= len(bodies):
return {"status": "error", "message": f"Body index {body_idx} out of range. Total bodies: {len(bodies)}."}
body = bodies[body_idx]
# Traverse faces to find the target face index
face_exp = TopExp_Explorer(body, TopAbs_FACE)
f_idx = 0
target_face = None
while face_exp.More():
face = face_exp.Current()
face_exp.Next()
if f_idx == face_idx:
target_face = face
break
f_idx += 1
if target_face is None:
return {"status": "error", "message": f"Face index {face_idx} out of range for body {body_idx}."}
# Call unfolding engine with distortion mode
distortion_mode = args.get("distortion_mode", "conformal")
polylines = unfold_face_geometry(target_face, mode=distortion_mode)
if not polylines:
return {"status": "error", "message": "No geometry returned from unfolding."}
# Calculate 2D bounds of unfolded shape
min_x = min(pt[0] for poly in polylines for pt in poly)
max_x = max(pt[0] for poly in polylines for pt in poly)
min_y = min(pt[1] for poly in polylines for pt in poly)
# Load or create DXF
if existing_dxf and os.path.exists(existing_dxf):
doc = ezdxf.readfile(existing_dxf)
msp = doc.modelspace()
bounds = get_dxf_bounds(msp)
if bounds:
start_x = bounds[2] + 10.0 # 10mm gap
start_y = bounds[1] # Align bottom Y
else:
start_x = 0.0
start_y = 0.0
else:
doc = ezdxf.new(dxfversion="R2010")
msp = doc.modelspace()
start_x = 0.0
start_y = 0.0
if "UNFOLDED_3D" not in doc.layers:
doc.layers.new("UNFOLDED_3D", dxfattribs={"color": 6})
# Translate to correct position and add to layout
for poly in polylines:
translated = []
for pt in poly:
tx = pt[0] - min_x + start_x
ty = pt[1] - min_y + start_y
translated.append((tx, ty))
if len(translated) >= 2:
msp.add_lwpolyline(translated, dxfattribs={"layer": "UNFOLDED_3D"})
doc.saveas(output_path)
return {
"status": "ok",
"data": {
"body_index": body_idx,
"face_index": face_idx,
"output": output_path,
"polylines_count": len(polylines)
}
}
except Exception as e:
return {"status": "error", "message": f"Failed to unfold face: {str(e)}"}
def op_unfold_faces(args: Dict[str, Any]) -> Dict[str, Any]:
"""
Unfolds multiple faces side-by-side and saves to a combined DXF.
Appends and arranges to the right of any existing DXF geometry if existing_dxf is provided.
"""
input_path = args.get("input")
output_path = args.get("output")
faces_to_unfold = args.get("faces")
existing_dxf = args.get("existing_dxf")
if not input_path or not output_path or not faces_to_unfold:
return {"status": "error", "message": "Missing required arguments: input, output, faces."}
try:
shape = load_step_shape(input_path)
bodies = get_solid_bodies(shape)
# Load or create DXF
if existing_dxf and os.path.exists(existing_dxf):
doc = ezdxf.readfile(existing_dxf)
msp = doc.modelspace()
bounds = get_dxf_bounds(msp)
if bounds:
current_x_offset = bounds[2] + 10.0 # 10mm gap
current_y_offset = bounds[1]
else:
current_x_offset = 0.0
current_y_offset = 0.0
else:
doc = ezdxf.new(dxfversion="R2010")
msp = doc.modelspace()
current_x_offset = 0.0
current_y_offset = 0.0
if "UNFOLDED_3D" not in doc.layers:
doc.layers.new("UNFOLDED_3D", dxfattribs={"color": 6})
gap = 10.0 # 10mm gap between unfolded layouts
unfolded_count = 0
for item in faces_to_unfold:
body_idx = item.get("body_index")
face_idx = item.get("face_index")
if body_idx is None or face_idx is None:
continue
if body_idx < 0 or body_idx >= len(bodies):
continue
body = bodies[body_idx]
# Find face
face_exp = TopExp_Explorer(body, TopAbs_FACE)
f_idx = 0
target_face = None
while face_exp.More():
face = face_exp.Current()
face_exp.Next()
if f_idx == face_idx:
target_face = face
break
f_idx += 1
if target_face is None:
continue
# Unfold face geometry with distortion mode
distortion_mode = args.get("distortion_mode", "conformal")
polylines = unfold_face_geometry(target_face, mode=distortion_mode)
if not polylines:
continue
# Compute 2D bounding box
min_x = min(pt[0] for poly in polylines for pt in poly)
max_x = max(pt[0] for poly in polylines for pt in poly)
min_y = min(pt[1] for poly in polylines for pt in poly)
# Translate to current horizontal offset and align base Y
translated_polylines = []
for poly in polylines:
translated_poly = []
for pt in poly:
tx = pt[0] - min_x + current_x_offset
ty = pt[1] - min_y + current_y_offset
translated_poly.append((tx, ty))
translated_polylines.append(translated_poly)
for pts in translated_polylines:
if len(pts) >= 2:
msp.add_lwpolyline(pts, dxfattribs={"layer": "UNFOLDED_3D"})
width = max_x - min_x
current_x_offset += width + gap
unfolded_count += 1
doc.saveas(output_path)
return {
"status": "ok",
"data": {
"output": output_path,
"unfolded_count": unfolded_count
}
}
except Exception as e:
return {"status": "error", "message": f"Failed to unfold multiple faces: {str(e)}"}
def discretize_edge(edge, num_points: int = 30) -> List[Tuple[float, float, float]]:
from OCC.Core.BRepAdaptor import BRepAdaptor_Curve
from OCC.Core.BRep import BRep_Tool
adaptor = BRepAdaptor_Curve(edge)
first = adaptor.FirstParameter()
last = adaptor.LastParameter()
if math.isinf(first) or math.isinf(last):
from OCC.Core.TopExp import TopExp
v1 = TopExp.FirstVertex(edge)
v2 = TopExp.LastVertex(edge)
p1 = BRep_Tool.Pnt(v1)
p2 = BRep_Tool.Pnt(v2)
return [(p1.X(), p1.Y(), p1.Z()), (p2.X(), p2.Y(), p2.Z())]
pts = []
for i in range(num_points):
t = first + (last - first) * i / (num_points - 1)
p = adaptor.Value(t)
pts.append((p.X(), p.Y(), p.Z()))
return pts
def get_face_plane_basis(face):
from OCC.Core.BRepAdaptor import BRepAdaptor_Surface
from OCC.Core.gp import gp_Pnt, gp_Vec
surf = BRepAdaptor_Surface(face)
u_mid = (surf.FirstUParameter() + surf.LastUParameter()) / 2.0
v_mid = (surf.FirstVParameter() + surf.LastVParameter()) / 2.0
pnt = gp_Pnt()
u_vec = gp_Vec()
v_vec = gp_Vec()
surf.D1(u_mid, v_mid, pnt, u_vec, v_vec)
normal_vec = u_vec.Crossed(v_vec)
if normal_vec.Magnitude() < 1e-6:
normal_vec = gp_Vec(0, 0, 1)
else:
normal_vec.Normalize()
u_vec.Normalize()
v_axis = normal_vec.Crossed(u_vec)
v_axis.Normalize()
origin = (pnt.X(), pnt.Y(), pnt.Z())
normal = (normal_vec.X(), normal_vec.Y(), normal_vec.Z())
u_axis = (u_vec.X(), u_vec.Y(), u_vec.Z())
v_axis_coords = (v_axis.X(), v_axis.Y(), v_axis.Z())
return origin, normal, u_axis, v_axis_coords
def _translate_shape(shape, dx: float, dy: float, dz: float):
"""Returns a rigidly translated copy of `shape`. Identity (returns the input)
when the offset is zero, to avoid needless OCC transform churn."""
if dx == 0.0 and dy == 0.0 and dz == 0.0:
return shape
from OCC.Core.gp import gp_Trsf, gp_Vec
from OCC.Core.BRepBuilderAPI import BRepBuilderAPI_Transform
trsf = gp_Trsf()
trsf.SetTranslation(gp_Vec(dx, dy, dz))
return BRepBuilderAPI_Transform(shape, trsf, True).Shape()
def op_project_edges(args: Dict[str, Any]) -> Dict[str, Any]:
input_path = args.get("input")
output_path = args.get("output")
body_idx = args.get("body_index", 0)
plane_type = args.get("plane_type", "XY") # "XY", "XZ", "YZ", or "face"
face_idx = args.get("face_index")
face_body_idx = args.get("face_body_index", body_idx)
existing_dxf = args.get("existing_dxf")
offset = float(args.get("offset", 0.0))
visible_bodies_indices = args.get("visible_bodies")
# Per-body manual move offsets from the 3D gizmo (MAS-140), keyed by body
# index: {"0": [x, y, z], ...}. Applied so the projection matches exactly how
# the model is arranged in the 3D view — moved bodies project where they sit.
body_offsets = args.get("body_offsets") or {}
def _offset_for(idx: int):
o = body_offsets.get(str(idx))
if o is None:
o = body_offsets.get(idx)
if not o:
return (0.0, 0.0, 0.0)
return (float(o[0]), float(o[1]), float(o[2]))
if not input_path or not output_path:
return {"status": "error", "message": "Missing input or output path."}
try:
shape = load_step_shape(input_path)
bodies = get_solid_bodies(shape)
# Apply each body's manual move so all downstream geometry (the face plane
# basis, the section, and the silhouette fallback) reflects the moved pose.
bodies = [_translate_shape(b, *_offset_for(i)) for i, b in enumerate(bodies)]
target_bodies = []
if visible_bodies_indices is not None:
for idx in visible_bodies_indices:
if 0 <= idx < len(bodies):
target_bodies.append(bodies[idx])
else:
if 0 <= body_idx < len(bodies):
target_bodies.append(bodies[body_idx])
else:
target_bodies = bodies
if not target_bodies:
return {"status": "error", "message": "No solid bodies found to project."}
origin = (0.0, 0.0, 0.0)
normal = (0.0, 0.0, 1.0)
u_axis = (1.0, 0.0, 0.0)
v_axis = (0.0, 1.0, 0.0)
if plane_type == "XY":
pass
elif plane_type == "XZ":
normal = (0.0, 1.0, 0.0)
v_axis = (0.0, 0.0, 1.0)
elif plane_type == "YZ":
normal = (1.0, 0.0, 0.0)
u_axis = (0.0, 1.0, 0.0)
v_axis = (0.0, 0.0, 1.0)
elif plane_type == "face" and face_idx is not None:
if 0 <= face_body_idx < len(bodies):
body = bodies[face_body_idx]
face_exp = TopExp_Explorer(body, TopAbs_FACE)
f_idx = 0
target_face = None
while face_exp.More():
face = face_exp.Current()
face_exp.Next()
if f_idx == face_idx:
target_face = face
break
f_idx += 1
if target_face is None:
return {"status": "error", "message": f"Face index {face_idx} not found on body {face_body_idx}."}
basis = get_face_plane_basis(target_face)
if basis:
origin, normal, u_axis, v_axis = basis
else:
return {"status": "error", "message": f"Body index {face_body_idx} out of range for face selection."}
# Shift origin along normal by offset
origin = (
origin[0] + normal[0] * offset,
origin[1] + normal[1] * offset,
origin[2] + normal[2] * offset
)
from OCC.Core.gp import gp_Ax2, gp_Pnt, gp_Dir, gp_Pln
from OCC.Core.BRepAlgoAPI import BRepAlgoAPI_Section
proj_origin = gp_Pnt(origin[0], origin[1], origin[2])
proj_normal = gp_Dir(normal[0], normal[1], normal[2])
proj_u = gp_Dir(u_axis[0], u_axis[1], u_axis[2])
# Build projection plane Pln for intersection section
proj_pln = gp_Pln(proj_origin, proj_normal)
section_edges = []
for body in target_bodies:
try:
sec = BRepAlgoAPI_Section(body, proj_pln)
sec.Build()
if sec.IsDone():
sec_shape = sec.Shape()
edge_exp = TopExp_Explorer(sec_shape, TopAbs_EDGE)
while edge_exp.More():
edge = edge_exp.Current()
section_edges.append(edge)
edge_exp.Next()
except Exception:
pass
polylines = []
seen_projections = set()
if section_edges:
# Intersection Mode: project 3D section curves onto local u, v axes
for edge in section_edges:
try:
pts3d = discretize_edge(edge)
pts2d = []
for pt in pts3d:
dx = pt[0] - origin[0]
dy = pt[1] - origin[1]
dz = pt[2] - origin[2]
u = dx * u_axis[0] + dy * u_axis[1] + dz * u_axis[2]
v = dx * v_axis[0] + dy * v_axis[1] + dz * v_axis[2]
pts2d.append((u, v))
if len(pts2d) < 2:
continue
xs = [p[0] for p in pts2d]
ys = [p[1] for p in pts2d]
if (max(xs) - min(xs)) < 1e-6 and (max(ys) - min(ys)) < 1e-6:
continue
key_fwd = tuple((round(p[0], 4), round(p[1], 4)) for p in pts2d)
key = min(key_fwd, key_fwd[::-1])
if key in seen_projections:
continue
seen_projections.add(key)
polylines.append(pts2d)
except Exception:
pass
# MAS-126: the plane imports ONLY the geometry it actually intersects. The
# full-silhouette projection of all visible bodies is a fallback used
# exclusively when the plane intersects nothing at all — never when a
# section was found (even if those section curves degenerated away).
any_intersection = len(section_edges) > 0
if not polylines and not any_intersection:
# Silhouette/HLR Mode: Project visible outlines/boundaries
from OCC.Core.HLRAlgo import HLRAlgo_Projector
from OCC.Core.HLRBRep import HLRBRep_Algo, HLRBRep_HLRToShape
proj_axes = gp_Ax2(proj_origin, proj_normal, proj_u)
projector = HLRAlgo_Projector(proj_axes)
hlr = HLRBRep_Algo()
for body in target_bodies:
hlr.Add(body)
hlr.Projector(projector)
hlr.Update()
hlr.Hide()
hlr_to_shape = HLRBRep_HLRToShape(hlr)
compounds = []
v_comp = hlr_to_shape.VCompound()
out_comp = hlr_to_shape.OutLineVCompound()
if v_comp is not None:
compounds.append(v_comp)
if out_comp is not None:
compounds.append(out_comp)
for comp in compounds:
edge_exp = TopExp_Explorer(comp, TopAbs_EDGE)
while edge_exp.More():
edge = edge_exp.Current()
edge_exp.Next()
try:
pts3d = discretize_edge(edge)
pts2d = []
for pt in pts3d:
pts2d.append((pt[0], pt[1]))
if len(pts2d) < 2:
continue
xs = [p[0] for p in pts2d]
ys = [p[1] for p in pts2d]
if (max(xs) - min(xs)) < 1e-6 and (max(ys) - min(ys)) < 1e-6:
continue
key_fwd = tuple((round(p[0], 4), round(p[1], 4)) for p in pts2d)
key = min(key_fwd, key_fwd[::-1])
if key in seen_projections:
continue
seen_projections.add(key)
polylines.append(pts2d)
except Exception:
pass
if not polylines:
return {"status": "error", "message": "No projectable edges found."}
min_x = min(pt[0] for poly in polylines for pt in poly)
min_y = min(pt[1] for poly in polylines for pt in poly)
if existing_dxf and os.path.exists(existing_dxf):
doc = ezdxf.readfile(existing_dxf)
msp = doc.modelspace()
bounds = get_dxf_bounds(msp)
if bounds:
start_x = bounds[2] + 10.0
start_y = bounds[1]
else:
start_x = 0.0
start_y = 0.0
else:
doc = ezdxf.new(dxfversion="R2010")
msp = doc.modelspace()
start_x = 0.0
start_y = 0.0
if "PROJECTED_SKETCH" not in doc.layers:
doc.layers.new("PROJECTED_SKETCH", dxfattribs={"color": 5})
for poly in polylines:
translated = []
for pt in poly:
tx = pt[0] - min_x + start_x
ty = pt[1] - min_y + start_y
translated.append((tx, ty))
msp.add_lwpolyline(translated, dxfattribs={"layer": "PROJECTED_SKETCH"})
doc.saveas(output_path)
return {
"status": "ok",
"data": {
"output": output_path,
"polylines_count": len(polylines)
}
}
except Exception as e:
import traceback
return {"status": "error", "message": f"Projection failed: {str(e)}\n{traceback.format_exc()}"}
def op_combine_steps(args: Dict[str, Any]) -> Dict[str, Any]:
"""Merges two STEP files into one (MAS-125): every solid/shell from `input`
and `incoming` is packed into a single compound and written to `output`, so a
model dragged into an already-loaded 3D workspace is appended rather than
replacing it. The viewport's loader handles the side-by-side distribution."""
input_path = args.get("input")
incoming_path = args.get("incoming")
output_path = args.get("output")
if not input_path or not incoming_path or not output_path:
return {"status": "error", "message": "Missing input, incoming, or output path."}
if not os.path.exists(input_path):
return {"status": "error", "message": f"Existing STEP not found: {input_path}"}
if not os.path.exists(incoming_path):
return {"status": "error", "message": f"Incoming STEP not found: {incoming_path}"}
try:
from OCC.Core.TopoDS import TopoDS_Compound
from OCC.Core.BRep import BRep_Builder
from OCC.Core.STEPControl import STEPControl_Writer, STEPControl_AsIs
from OCC.Core.Bnd import Bnd_Box
from OCC.Core.BRepBndLib import brepbndlib
def _bbox(shape):
box = Bnd_Box()
brepbndlib.Add(shape, box)
if box.IsVoid():
return None
return box.Get() # (xmin, ymin, zmin, xmax, ymax, zmax)
existing_bodies = get_solid_bodies(load_step_shape(input_path))
incoming_bodies = get_solid_bodies(load_step_shape(incoming_path))
# Place the incoming model beside the existing geometry, every time, so
# repeated imports lay out as a tidy, non-overlapping row instead of
# stacking at the same origin (the "spacing gets disturbed" report).
# The shift is a single rigid translation of the whole incoming group, so
# a multi-body file keeps its internal arrangement; the EXISTING bodies are
# never moved, so already-placed models stay exactly where they are.
GAP = 20.0
ex_boxes = [b for b in (_bbox(s) for s in existing_bodies) if b]
in_boxes = [b for b in (_bbox(s) for s in incoming_bodies) if b]
if ex_boxes and in_boxes:
ex_xmax = max(b[3] for b in ex_boxes)
in_xmin = min(b[0] for b in in_boxes)
dx = (ex_xmax + GAP) - in_xmin
incoming_bodies = [_translate_shape(b, dx, 0.0, 0.0) for b in incoming_bodies]
builder = BRep_Builder()
compound = TopoDS_Compound()
builder.MakeCompound(compound)
total = 0
for body in existing_bodies:
builder.Add(compound, body)
total += 1
for body in incoming_bodies:
builder.Add(compound, body)
total += 1
writer = STEPControl_Writer()
writer.Transfer(compound, STEPControl_AsIs)
writer.Write(output_path)
return {"status": "ok", "data": {"output": output_path, "body_count": total}}
except Exception as e:
import traceback
return {"status": "error", "message": f"Failed to combine STEP files: {str(e)}\n{traceback.format_exc()}"}
def op_face_distortion(args: Dict[str, Any]) -> Dict[str, Any]:
"""Computes the 2D parameterization of a face under a given distortion mode,
and returns the per-vertex distortion values (area ratios) to color the 3D mesh."""
import numpy as np
input_path = args.get("input")
body_idx = args.get("body_index")
face_idx = args.get("face_index")
mode = args.get("distortion_mode", "conformal")
if not input_path or body_idx is None or face_idx is None:
return {"status": "error", "message": "Missing required arguments: input, body_index, face_index."}
try:
shape = load_step_shape(input_path)
bodies = get_solid_bodies(shape)
if body_idx < 0 or body_idx >= len(bodies):
return {"status": "error", "message": f"Body index {body_idx} out of range."}
body = bodies[body_idx]
# Traverse faces to find the target face index
face_exp = TopExp_Explorer(body, TopAbs_FACE)
f_idx = 0
target_face = None
while face_exp.More():
face = face_exp.Current()
face_exp.Next()
if f_idx == face_idx:
target_face = face
break
f_idx += 1
if target_face is None:
return {"status": "error", "message": f"Face index {face_idx} out of range."}
BRepMesh_IncrementalMesh(target_face, 0.05)
verts3d, tris = triangulate_face(target_face)
if not tris:
return {"status": "ok", "distortion": []}
n = len(verts3d)
stype = get_surface_type(target_face)
if stype in ("Plane", "Cylinder", "Cone") and mode == "conformal":
return {"status": "ok", "distortion": [0.0] * n}
uv = parameterize_mesh(verts3d, tris, mode)
from collections import defaultdict
vert_distortion = defaultdict(list)
V = np.array(verts3d)
for t_idx, (a, b, c) in enumerate(tris):
p0, p1, p2 = V[a], V[b], V[c]
a3d = 0.5 * np.linalg.norm(np.cross(p1 - p0, p2 - p0))
a3d = max(a3d, 1e-12)
u0, u1, u2 = uv[a], uv[b], uv[c]
cross = (u1[0] - u0[0]) * (u2[1] - u0[1]) - (u2[0] - u0[0]) * (u1[1] - u0[1])
a2d = 0.5 * abs(cross)
# Symmetric area distortion: max(a2d/a3d, a3d/a2d) - 1.0
dist = max(a2d / a3d, a3d / a2d) - 1.0
vert_distortion[a].append(dist)
vert_distortion[b].append(dist)
vert_distortion[c].append(dist)
distortion = []
for i in range(n):
d_list = vert_distortion.get(i, [0.0])
distortion.append(float(np.mean(d_list)))
return {"status": "ok", "distortion": distortion}
except Exception as e:
import traceback
return {"status": "error", "message": f"Failed to compute distortion: {str(e)}\n{traceback.format_exc()}"}