-
Notifications
You must be signed in to change notification settings - Fork 10
/
model.py
3033 lines (2644 loc) · 103 KB
/
model.py
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
"""
Description
----------
ccad modeller designed to be imported from a python prompt or program.
View README for a full description of ccad.
model.py contains classes and functions for modelling.
Author
------
View AUTHORS.
License
-------
Distributed under the GNU LESSER GENERAL PUBLIC LICENSE Version 3.
View LICENSE for details.
"""
from __future__ import print_function
from os import path as _path
import sys as _sys
import re as _re # Needed for svg
import math as _math
#from OCC.ChFi3d import *
#from OCC.BlockFix import *
from OCC.Bnd import Bnd_Box as _Bnd_Box
#from OCC.BOP import *
from OCC.BRep import (BRep_Builder as _BRep_Builder, BRep_Tool as _BRep_Tool,
BRep_Tool_Surface as _BRep_Tool_Surface)
from OCC import BRepAlgo as _BRepAlgo
from OCC import BRepAlgoAPI as _BRepAlgoAPI
from OCC.BRepBndLib import brepbndlib_Add as _brepbndlib_Add
from OCC import BRepBuilderAPI as _BRepBuilderAPI
from OCC.BRepCheck import BRepCheck_Analyzer as _BRepCheck_Analyzer
from OCC.BRepFeat import BRepFeat_Gluer as _BRepFeat_Gluer
from OCC import BRepFilletAPI as _BRepFilletAPI
from OCC.BRepGProp import (brepgprop_VolumeProperties as _brepgprop_VolumeProperties,
brepgprop_LinearProperties as _brepgprop_LinearProperties,
brepgprop_SurfaceProperties as _brepgprop_SurfaceProperties)
from OCC import BRepOffsetAPI as _BRepOffsetAPI
from OCC import BRepOffset as _BRepOffset
from OCC import BRepPrimAPI as _BRepPrimAPI
from OCC import BRepTools as _BRepTools
from OCC.BRepTools import (breptools_Read as _breptools_Read,
breptools_Write as _breptools_Write)
from OCC.GC import (GC_MakeArcOfCircle as _GC_MakeArcOfCircle,
GC_MakeArcOfEllipse as _GC_MakeArcOfEllipse)
from OCC.GCPnts import (GCPnts_QuasiUniformDeflection as
_GCPnts_QuasiUniformDeflection)
from OCC.Geom import Geom_BezierCurve as _Geom_BezierCurve
from OCC import GeomAbs as _GeomAbs
from OCC.GeomAdaptor import (GeomAdaptor_Curve as _GeomAdaptor_Curve,
GeomAdaptor_Surface as _GeomAdaptor_Surface)
from OCC.GeomAPI import GeomAPI_PointsToBSpline as _GeomAPI_PointsToBSpline
from OCC import gp as _gp
from OCC.GProp import GProp_GProps as _GProp_GProps
from OCC import IFSelect as _IFSelect
from OCC.IGESControl import (IGESControl_Controller as _IGESControl_Controller,
IGESControl_Reader as _IGESControl_Reader,
IGESControl_Writer as _IGESControl_Writer)
from OCC.Interface import (
Interface_Static_SetCVal as _Interface_Static_SetCVal,
Interface_Static_SetIVal as _Interface_Static_SetIVal,
Interface_Static_SetRVal as _Interface_Static_SetRVal)
from OCC.LocOpe import LocOpe_FindEdges as _LocOpe_FindEdges
from OCC.ShapeFix import ShapeFix_Shape as _ShapeFix_Shape
from OCC import STEPControl as _STEPControl
from OCC.StlAPI import StlAPI_Writer as _StlAPI_Writer
from OCC.TColgp import TColgp_Array1OfPnt as _TColgp_Array1OfPnt
from OCC.TColStd import TColStd_Array1OfReal as _TColStd_Array1OfReal
from OCC import TopAbs as _TopAbs
from OCC.TopoDS import (topods_Edge as _TopoDS_edge,
topods_Face as _TopoDS_face,
topods_Solid as _TopoDS_solid,
topods_Shell as _TopoDS_shell,
topods_Compound as _TopoDS_compound,
topods_CompSolid as _TopoDS_compsolid,
topods_Vertex as _TopoDS_vertex,
topods_Wire as _TopoDS_wire,
TopoDS_Shape as _TopoDS_Shape)
from OCC import TopoDS as _TopoDS
from OCC.TopExp import (TopExp_Explorer as _TopExp_Explorer,
topexp_MapShapesAndAncestors as
_TopExp_MapShapesAndAncestors)
from OCC.TopOpeBRep import (TopOpeBRep_FacesIntersector as
_TopOpeBRep_FacesIntersector)
from OCC.TopOpeBRepTool import (TopOpeBRepTool_FuseEdges as
_TopOpeBRepTool_FuseEdges)
from OCC import TopTools as _TopTools
# Shape Functions
def _translate(s1, pdir):
m = _gp.gp_Trsf()
m.SetTranslation(_gp.gp_Vec(pdir[0], pdir[1], pdir[2]))
trf = _BRepBuilderAPI.BRepBuilderAPI_Transform(m)
trf.Perform(s1.shape, True)
return trf.Shape()
def _rotate(s1, pabout, pdir, angle):
m = _gp.gp_Trsf()
m.SetRotation(_gp.gp_Ax1(_gp.gp_Pnt(pabout[0], pabout[1], pabout[2]),
_gp.gp_Dir(pdir[0], pdir[1], pdir[2])), angle)
trf = _BRepBuilderAPI.BRepBuilderAPI_Transform(m)
trf.Perform(s1.shape, True)
return trf.Shape()
def _mirror(s1, pabout, pdir):
m = _gp.gp_Trsf()
m.SetMirror(_gp.gp_Ax2(_gp.gp_Pnt(pabout[0], pabout[1], pabout[2]),
_gp.gp_Dir(pdir[0], pdir[1], pdir[2])))
trf = _BRepBuilderAPI.BRepBuilderAPI_Transform(m)
trf.Perform(s1.shape, True)
return trf.Shape()
def _scale(s1, sx=1.0, sy=1.0, sz=1.0):
m = _gp.gp_GTrsf()
m.SetVectorialPart(_gp.gp_Mat(sx, 0, 0, 0, sy, 0, 0, 0, sz))
trf = _BRepBuilderAPI.BRepBuilderAPI_GTransform(s1.shape, m, False)
return trf.Shape()
def translated(s1, pdir):
"""
Returns a new shape which is s1 translated (moved).
"""
s2 = s1.copy()
s2.translate(pdir)
return s2
def rotated(s1, pabout, pdir, angle):
"""
Returns a new shape which is s1 rotated.
"""
s2 = s1.copy()
s2.rotate(pabout, pdir, angle)
return s2
def rotatedx(s1, angle):
"""
Returns a new shape which is s1 rotated about (0.0, 0.0, 0.0) and
around (1.0, 0.0, 0.0)
"""
s2 = s1.copy()
s2.rotatex(angle)
return s2
def rotatedy(s1, angle):
"""
Returns a new shape which is s1 rotated about (0.0, 0.0, 0.0) and
around (0.0, 1.0, 0.0)
"""
s2 = s1.copy()
s2.rotatey(angle)
return s2
def rotatedz(s1, angle):
"""
Returns a new shape which is s1 rotated about (0.0, 0.0, 0.0) and
around (0.0, 0.0, 1.0)
"""
s2 = s1.copy()
s2.rotatez(angle)
return s2
def mirrored(s1, pabout, pdir):
"""
Returns a new shape which is s1 mirrored.
"""
s2 = s1.copy()
s2.mirror(pabout, pdir)
return s2
def mirroredx(s1):
"""
Returns a new shape which is s1 mirrored about (0.0, 0.0, 0.0) in
the x-direction
"""
s2 = s1.copy()
s2.mirrorx()
return s2
def mirroredy(s1):
"""
Returns a new shape which is s1 mirrored about (0.0, 0.0, 0.0) in
the y-direction
"""
s2 = s1.copy()
s2.mirrory()
return s2
def mirroredz(s1):
"""
Returns a new shape which is s1 mirrored about (0.0, 0.0, 0.0) in
the z-direction
"""
s2 = s1.copy()
s2.mirrorz()
return s2
def scaled(s1, sfx, sfy=None, sfz=None):
"""
Returns a new shape which is s1 scaled by a different scale factor
in all 3 dimensions. If sfy and sfz are left undefined, all 3
dimensions are scaled by sfx.
"""
s2 = s1.copy()
s2.scale(sfx, sfy, sfz)
return s2
def scaledx(s1, sfx):
"""
Returns a new shape which is s1 scaled by sfx in the x-dimension
"""
s2 = s1.copy()
s2.scalex(sfx)
return s2
def scaledy(s1, sfy):
"""
Returns a new shape which is s1 scaled by sfy in the y-dimension
"""
s2 = s1.copy()
s2.scaley(sfy)
return s2
def scaledz(s1, sfz):
"""
Returns a new shape which is s1 scaled by sfz in the z-dimension
"""
s2 = s1.copy()
s2.scalez(sfz)
return s2
def reversed(s1):
"""
Returns a new shape which is s1 reversed in orientation.
"""
s2 = s1.copy()
s2.reverse()
return s2
# Face Functions
def _raw_faces_same_domain(f1, f2, skip_fits=0):
"""
If f1 and f2 are in the same domain, returns 1; otherwise, returns
0. FacesIntersector is painfully slow. I don't think the
intersection calculation is necessary, but I couldn't find a
stand-alone OCC domain checker. ***
"""
# Didn't Work. Always empty.
#fi = TopOpeBRepDS_DataStructure()
#i1 = fi.AddShape(f1)
#print fi.ShapeSameDomain(f2).IsEmpty():
# Pre-screen, since FacesIntersector is slow
t1 = _GeomAdaptor_Surface(_BRep_Tool_Surface(_TopoDS_face(f1))).GetType()
t2 = _GeomAdaptor_Surface(_BRep_Tool_Surface(_TopoDS_face(f2))).GetType()
if t1 != t2:
return 0
else:
if not skip_fits or (skip_fits and t1 <= _GeomAbs.GeomAbs_Torus):
fi = _TopOpeBRep_FacesIntersector()
fi.Perform(f1, f2)
return fi.SameDomain()
else:
return 0
def _raw_faces_merge(f1, f2):
"""
Merges two raw faces in the same domain that share common edge(s)
into a single face.
"""
# Attempt with Fuse didn't work
#new_face = BRepAlgoAPI_Fuse(f1, f2).Shape()
#new_face = BRepAlgo_Fuse(f1, f2).Shape()
#print _raw_type(new_face)
# Attempt with sewing didn't work
#b = BRepBuilderAPI_Sewing()
#b.Add(f1)
#b.Add(f2)
#b.Perform()
#new_face = b.SewedShape()
#print 'new_face type', _raw_type(new_face)
#new_faces[index] = new_face
## This worked, but only sometimes. Error
## reporting wasn't sufficient enough to discover
## cause.
#lfs = TopTools_ListOfShape()
#print f1.Orientation(), f2.Orientation()
# Didn't help
#if f1.Orientation() != f2.Orientation():
# f2.Reverse()
#lfs.Append(f1)
#lfs.Append(f2)
#b = TopOpeBRepBuild_FuseFace(TopTools_ListOfShape(), lfs, 1)
##b.PerformEdge()
#b.PerformFace()
#if not b.IsModified():
# print 'Error: Face fusion failed'
# #return face(f1), face(f2)
#lfs = b.LFuseFace()
#new_face = lfs.First()
#new_faces[index] = new_face
# The orientations were derived by trial and error.
# Expect problems. ***
other_wires = []
ow1 = _BRepTools.breptools_OuterWire(_TopoDS_face(f1))
ow1o = ow1.Orientation()
ex1w = _TopExp_Explorer(f1, _TopAbs.TopAbs_WIRE)
while ex1w.More():
cw = ex1w.Current()
if cw != ow1:
cw.Orientation(_TopAbs.TopAbs_Compose(ow1o, cw.Orientation()))
other_wires.append(cw)
ex1w.Next()
ex1e = _BRepTools.BRepTools_WireExplorer(_TopoDS_wire(ow1))
e1s = []
while ex1e.More():
e1s.append(ex1e.Current())
ex1e.Next()
ow2 = _BRepTools.breptools_OuterWire(_TopoDS_face(f2))
ow2o = ow2.Orientation()
ex2w = _TopExp_Explorer(f2, _TopAbs.TopAbs_WIRE)
while ex2w.More():
cw = ex2w.Current()
if cw != ow2:
cw.Orientation(_TopAbs.TopAbs_Compose(ow2o, cw.Orientation()))
other_wires.append(cw)
ex2w.Next()
ex2e = _BRepTools.BRepTools_WireExplorer(_TopoDS_wire(ow2))
e2s = []
while ex2e.More():
e2s.append(ex2e.Current())
ex2e.Next()
# Find all places where wires are connected
c1s = []
c2s = []
e1_hashes = map(lambda x: x.__hash__(), e1s)
e2_hashes = map(lambda x: x.__hash__(), e2s)
for index1, e1 in enumerate(e1_hashes):
try:
index2 = e2_hashes.index(e1)
except:
index2 = -1
if index2 > -1:
c1s.append(index1)
c2s.append(index2)
# Can only handle one continuous edge merge now.
# Multiple edge merges sometimes imply holes and
# sometimes don't. Truncate c1s, c2s
# accordingly. ***
if len(c1s) == 0:
print('No common edges')
if len(c1s) > 1:
print('c1-', c1s, c2s, len(e1s), len(e2s))
min_index = 0
max_index = 0
while (max_index < len(c1s) - 1 and
c1s[max_index + 1] - c1s[max_index] == 1):
max_index = max_index + 1
if max_index < len(c1s) - 1:
while (min_index > -(len(c1s) - 1) and
c1s[min_index] - c1s[min_index - 1] == 1):
min_index = min_index - 1
if min_index < 0:
c1s = c1s[min_index:] + c1s[:max_index + 1]
c2s = c2s[min_index:] + c2s[:max_index + 1]
else:
c1s = c1s[:max_index + 1]
c2s = c2s[:max_index + 1]
print('c1+', c1s, c2s, len(e1s), len(e2s))
# Create the merged wire
b = _BRepBuilderAPI.BRepBuilderAPI_MakeWire()
ds = []
for count in range(len(e1s)):
if count in c1s:
if len(c2s) < len(e2s): # Make sure they're not all common
index1 = c1s.index(count)
count2 = c2s[index1]
while count2 in c2s:
count2 = (count2 + 1) % len(e2s)
b2 = _BRepBuilderAPI.BRepBuilderAPI_MakeWire()
while count2 not in c2s:
b2.Add(e2s[count2])
count2 = (count2 + 1) % len(e2s)
b.Add(_TopoDS_wire(b2.Wire()))
else:
b.Add(e1s[count])
ds.append(edge(e1s[count]))
w = b.Wire()
b = _ShapeFix_Shape(w)
b.Perform()
w = b.Shape()
# Create the fused face
s = _BRep_Tool_Surface(_TopoDS_face(f1))
bf = _BRepBuilderAPI.BRepBuilderAPI_MakeFace(s, _TopoDS_wire(w))
for other_wire in other_wires:
if ow1o != ow2o:
other_wire.Reverse()
bf.Add(_TopoDS_wire(other_wire))
f = bf.Face()
# Fix wire mess orientation mess ups. It would be
# nicer to avoid this in the first place
# above. ***
# ShapeFix creates new edges, which hinders
# multiple merges. Unfortunately, only an
# orientation fix had problems too. ***
b = _ShapeFix_Shape(f)
b.Perform()
f = b.Shape()
#b = ShapeFix_Face(f)
#bw = b.FixWireTool().GetObject()
#bw.FixReorder()
#b.FixOrientation()
#f = b.Face()
# Since I use f1's surface, I must orient
# the output the same way.
if ow1o == _TopAbs.TopAbs_REVERSED:
f.Reverse()
return f
# Solid Functions
def fuse(s1, s2, refine=0):
"""
Performs a boolean fuse between solids s1 and s2 and returns the
result as a new solid.
"""
#return solid(BRepAlgoAPI_Fuse(s1.shape, s2.shape).Shape())
b1 = _BRepAlgoAPI.BRepAlgoAPI_Fuse(s1.shape, s2.shape)
if refine:
# Fuses edges along the way however doesn't fuse faces
b1.RefineEdges()
return solid(b1.Shape())
def old_fuse(s1, s2):
"""
Performs a boolean fuse between solids s1 and s2 and returns the
result as a new solid. Uses OCC's old Fuse algorithm.
"""
return solid(_BRepAlgo.BRepAlgo_Fuse(s1.shape, s2.shape).Shape())
def cut(s1, s2, refine=0):
"""
Performs a boolean cut between solids s1 and s2 and returns the
result as a new solid.
"""
b1 = _BRepAlgoAPI.BRepAlgoAPI_Cut(s1.shape, s2.shape)
if refine:
b1.RefineEdges()
return solid(b1.Shape())
def old_cut(s1, s2):
"""
Performs a boolean cut between solids s1 and s2 and returns the
result as a new solid. Uses OCC's old Cut algorithm.
"""
return solid(_BRepAlgo.BRepAlgo_Cut(s1.shape, s2.shape).Shape())
def common(s1, s2, refine=0):
"""
Performs a boolean common between solids s1 and s2 and returns the
result as a new solid.
"""
b1 = _BRepAlgoAPI.BRepAlgoAPI_Common(s1.shape, s2.shape)
if refine:
b1.RefineEdges()
return solid(b1.Shape())
def old_common(s1, s2):
"""
Performs a boolean common between solids s1 and s2 and returns the
result as a new solid. Uses OCC's old Common algorithm.
"""
return solid(_BRepAlgo.BRepAlgo_Common(s1.shape, s2.shape).Shape())
def _fillet_boolean(b1, rad):
new_edges = b1.SectionEdges()
b2 = _BRepFilletAPI.BRepFilletAPI_MakeFillet(b1.Shape())
iterator = _TopTools.TopTools_ListIteratorOfListOfShape(new_edges)
while iterator.More():
b2.Add(rad, _TopoDS_edge(iterator.Value()))
iterator.Next()
return solid(b2.Shape())
def fillet_fuse(s1, s2, rad):
"""
Performs a boolean fuse between s1 and s2 and fillets the newly
created edges.
"""
if rad > 0.0:
return _fillet_boolean(
_BRepAlgoAPI.BRepAlgoAPI_Fuse(s1.shape, s2.shape), rad)
else:
return fuse(s1, s2)
def fillet_cut(s1, s2, rad):
"""
Performs a boolean cut between s1 and s2 and fillets the newly
created edges.
"""
if rad > 0.0:
return _fillet_boolean(
_BRepAlgoAPI.BRepAlgoAPI_Cut(s1.shape, s2.shape), rad)
else:
return cut(s1, s2)
def fillet_common(s1, s2, rad):
"""
Performs a boolean common between s1 and s2 and fillets the newly
created edges.
"""
if rad > 0.0:
return _fillet_boolean(
_BRepAlgoAPI.BRepAlgoAPI_Common(s1.shape, s2.shape), rad)
else:
return common(s1, s2)
def _chamfer_boolean(b1, dist):
# Doesn't work. The SectionEdges don't map to faces, it seems. ***
new_edges = b1.SectionEdges()
edge_map = _TopTools.TopTools_IndexedDataMapOfShapeListOfShape()
s = b1.Shape()
_TopExp_MapShapesAndAncestors(s, _TopAbs.TopAbs_EDGE, _TopAbs.TopAbs_FACE,
edge_map)
b2 = _BRepFilletAPI.BRepFilletAPI_MakeChamfer(s)
iterator = _TopTools.TopTools_ListIteratorOfListOfShape(new_edges)
while iterator.More():
e1 = iterator.Value()
f1 = edge_map.FindFromKey(e1).First()
b2.Add(dist, dist, _TopoDS_edge(e1), _TopoDS_face(f1))
iterator.Next()
return solid(b2.Shape())
def chamfer_fuse(s1, s2, dist):
"""
Performs a chamfer fuse between s1 and s2 and chamfers the newly
created edges.
"""
if dist > 0.0:
return _chamfer_boolean(
_BRepAlgoAPI.BRepAlgoAPI_Fuse(s1.shape, s2.shape), dist)
else:
return fuse(s1, s2)
def chamfer_cut(s1, s2, dist):
"""
Performs a chamfer cut between s1 and s2 and chamfers the newly
created edges.
"""
if dist > 0.0:
return _chamfer_boolean(
_BRepAlgoAPI.BRepAlgoAPI_Cut(s1.shape, s2.shape), dist)
else:
return cut(s1, s2)
def chamfer_common(s1, s2, dist):
"""
Performs a chamfer common between s1 and s2 and chamfers the newly
created edges.
"""
if dist > 0.0:
return _chamfer_boolean(
_BRepAlgoAPI.BRepAlgoAPI_Common(s1.shape, s2.shape), dist)
else:
return common(s1, s2)
def glue(s1, s2, face_pairs=[]):
"""
Glues solids s1 and s2 together at the face_pairs. face_pairs is
a list of tuples. Each tuple represents face indices that should
be glued.
"""
s1f = s1._raw('face')
s2f = s2._raw('face')
if len(face_pairs) == 0:
print('Error: Haven\'t implemented locate glued faces')
return
# This was expensive and didn't work. I believe intersections
# occurred at edge coincidences. I may want to try
# BRepTools_UVBounds as a pre-filter. I may also want to try
# Bounds first. ***
for i1, f1 in enumerate(s1f):
for i2, f2 in enumerate(s2f):
b = _TopOpeBRep_FacesIntersector()
b.Perform(f1, f2)
if b.SurfacesSameOriented():
face_pairs.append((i1, i2))
print(face_pairs)
b = _BRepFeat_Gluer(s1.shape, s2.shape)
for face_pair in face_pairs:
f1 = _TopoDS_face(s1f[face_pair[0]])
f2 = _TopoDS_face(s2f[face_pair[1]])
b.Bind(f1, f2)
common_edges = _LocOpe_FindEdges(f1, f2)
common_edges.InitIterator()
while common_edges.More():
b.Bind(common_edges.EdgeFrom(), common_edges.EdgeTo())
common_edges.Next()
return solid(b.Shape())
def simple_glue(s1, s2, face_pairs=[], tolerance=1e-3):
"""
Glues solids s1 and s2 together at the face_pairs. face_pairs is
a list of tuples. Each tuple represents faces that should be
glued. Unlike glue, each face_pair is expected to exactly
overlap. It's more robust than glue, so it was added.
"""
s1f = s1._raw('face')
s2f = s2._raw('face')
f1rs = []
f2rs = []
for face_pair in face_pairs:
f1rs.append(face_pair[0])
f2rs.append(face_pair[1])
f1rs.sort()
f1rs.reverse()
f2rs.sort()
f2rs.reverse()
for f1r in f1rs:
del s1f[f1r]
for f2r in f2rs:
del s2f[f2r]
b = _BRepBuilderAPI.BRepBuilderAPI_Sewing(tolerance)
for f in s1f:
b.Add(f)
for f in s2f:
b.Add(f)
b.Perform()
new_shell = b.SewedShape()
if _raw_type(new_shell) == 'shell':
b2 = _BRepBuilderAPI.BRepBuilderAPI_MakeSolid()
b2.Add(_TopoDS_shell(new_shell))
return solid(b2.Solid())
elif _raw_type(new_shell) == 'compound':
print('Warning: simple_glue() returned compound')
s = solid(new_shell)
css = s._raw('shell')
c = _TopoDS_compound()
b3 = _BRep_Builder()
b3.MakeCompound(c)
for cs in css:
b2 = _BRepBuilderAPI.BRepBuilderAPI_MakeSolid()
b2.Add(_TopoDS_shell(cs))
b3.Add(c, b2.Solid())
return solid(c)
else:
print('Warning: Wrong sewed shape after simple_glue():', end='')
_raw_type(new_shell)
return solid(new_shell)
# Import Functions
def _convert_import(s):
stype = _raw_type(s)
if stype in ['solid', 'compound', 'compsolid']:
return solid(s)
elif stype == 'shape':
print('Error: Unsupported type', stype)
else:
return eval(stype + '(s)')
def from_brep(name):
"""
Imports a brep file and returns the shape.
"""
if _path.exists(name):
s = _TopoDS_Shape()
b = _BRep_Builder()
_breptools_Read(s, name, b)
return _convert_import(s)
else:
print('Error: Can\'t find', name)
def from_iges(name):
"""
Imports an iges file and returns the shape.
"""
if _path.exists(name):
reader = _IGESControl_Reader()
status = reader.ReadFile(name)
okay = reader.TransferRoots()
if not okay:
print('Warning: Could not translate all shapes')
shape = reader.OneShape()
return _convert_import(shape)
else:
print('Error: Can\'t find', name)
def from_step(name):
"""
Imports a step file and returns the shape.
"""
if _path.exists(name):
reader = _STEPControl.STEPControl_Reader()
status = reader.ReadFile(name)
okay = reader.TransferRoots()
shape = reader.OneShape()
return _convert_import(shape)
else:
print('Error: Can\'t find', name)
def from_svg(name):
"""
Imports a 2D svg file, converts each graphics path into a wire,
and returns a list of wires.
Warning: Currently only implements a subset of the svg protocol.
The subset follows. However, it's pretty easy to add more.
transforms with
matrix, translate
paths with
a, A, c, C, l, L, m, M, q, Q, z, Z elements
Warning: Only checked with small inkscape-generated files
"""
def finish_wire():
if len(local_wire) > 0:
retval.append(wire(local_wire))
# Cannot do local_wire = [] because thinks a new variable
del local_wire[:]
def strpt_to_float(strpt):
pt = list(map(lambda x: float(x), strpt.split(',')))
if not absolute:
pt = (pt0[0] + pt[0], pt0[1] + pt[1]) # Make absolute
return (pt[0], pt[1])
def transform_matrix():
retval = _gp.gp_Mat(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0)
for matrix in matrices:
retval.Multiply(matrix[1]) # second element is the matrix
return retval
def transform_pts(transform, pts):
# Matrix transforms and adds a third dimension
retval = []
for pt in pts:
#retval.append((pt[0], pt[1], 0.0)) # No transform (for debug)
xyz = _gp.gp_XYZ(pt[0], pt[1], 1.0)
xyz.Multiply(transform)
# svg y increases downward; height - xpt[1] corrects
retval.append((xyz.X(), height - xyz.Y(), 0.0))
return retval
def vector_angle(u, v):
# Computes the angle between two vectors
if ((u[0] * v[1]) - (u[1] * v[0])) < 0.0:
s = -1
else:
s = 1
dot = (u[0] * v[0]) + (u[1] * v[1])
magu = _math.sqrt((u[0] ** 2) + (u[1] ** 2))
magv = _math.sqrt((v[0] ** 2) + (v[1] ** 2))
return s * _math.acos(min(1.0, max(-1.0, dot / (magu * magv))))
height = 0.0
fp = open(name, 'r')
entities = []
matrices = []
transforms = []
paths = []
for line in fp:
m = _re.match('\s*<([a-zA-Z]+)', line) # Start of an entity
if m:
entities.append(m.group(1))
if len(entities) > 0 and entities[-1] == 'svg':
m = _re.match('\s*height="(.+)"', line)
if m:
height = float(m.group(1))
if (len(entities) > 1 and
entities[-2] == 'g' and
entities[-1] == 'path'):
m = _re.match('\s*d="(.+)"', line) # Should this be multi-line?
if m:
paths.append(m.group(1))
transforms.append(transform_matrix())
if len(entities) > 0 and entities[-1] == 'g':
m = _re.match('\s*transform="matrix\((.+)\)"', line)
if m:
matrix = map(lambda x: float(x), m.group(1).split(','))
matrices.append((len(entities), _gp.gp_Mat(matrix[0],
matrix[2],
matrix[4],
matrix[1],
matrix[3],
matrix[5],
0.0, 0.0, 1.0)))
m = _re.match('\s*transform="translate\((.+)\)"', line)
if m:
matrix = map(lambda x: float(x), m.group(1).split(','))
matrices.append((len(entities), _gp.gp_Mat(1.0,
0.0,
matrix[0],
0.0,
1.0,
matrix[1],
0.0, 0.0, 1.0)))
m = _re.match('.*/>|.*</', line) # End of an entity
if m:
if (entities[-1] == 'g' and
len(matrices) > 0 and
matrices[-1][0] == len(entities)):
matrices.pop()
entities.pop()
fp.close()
retval = []
local_wire = []
cmds = 'aAcChHlLmMqQsStTvVzZ'
for path, transform in zip(paths, transforms):
pt0 = (0.0, 0.0)
absolute = 1
# command, arguments format
#ls = filter(lambda x: x != '', re.split('([' + cmds + '])', path))
ls = path.split()
index = 0
while index < len(ls):
if ls[index].isupper():
absolute = 1
else:
absolute = 0
cmd = ls[index].lower()
if cmd == 'm': # Move
finish_wire()
pt0 = strpt_to_float(ls[index + 1])
index = index + 2
pts = [pt0]
while index < len(ls) and ls[index] not in cmds:
pts.append(strpt_to_float(ls[index]))
pt0 = pts[-1]
index = index + 1
if len(pts) > 1:
local_wire.append(polygon(transform_pts(transform, pts)))
elif cmd == 'q': # Quadratic Bezier
index = index + 1
while index < len(ls) and ls[index] not in cmds:
pts = [pt0,
strpt_to_float(ls[index]),
strpt_to_float(ls[index + 1])]
pt0 = pts[-1]
local_wire.append(bezier(transform_pts(transform, pts)))
index = index + 2
elif cmd == 'c': # Cubic Bezier
index = index + 1
while index < len(ls) and ls[index] not in cmds:
pts = [pt0,
strpt_to_float(ls[index]),
strpt_to_float(ls[index + 1]),
strpt_to_float(ls[index + 2])]
pt0 = pts[-1]
local_wire.append(bezier(transform_pts(transform, pts)))
index = index + 3
elif cmd == 'l': # Line
index = index + 1
pts = [pt0]
while index < len(ls) and ls[index] not in cmds:
pts.append(strpt_to_float(ls[index]))
pt0 = pts[-1]
index = index + 1
local_wire.append(polygon(transform_pts(transform, pts)))
elif cmd == 'a': # Elliptical Arc
index = index + 1
while index < len(ls) and ls[index] not in cmds:
x1, y1 = pt0
rx, ry = map(lambda x: float(x), ls[index].split(','))
phi = _math.radians(float(ls[index + 1]))
fa = int(ls[index + 2])
fs = int(ls[index + 3])
x2, y2 = strpt_to_float(ls[index + 4])
index = index + 5
# Algorithm copied from W3C SVG 1.1 Appendix F
rx = abs(rx)
ry = abs(ry)
if rx == 0.0 or ry == 0.0:
pts = [(x1, y1), (x2, y2)]
local_wire.append(
polygon(transform_pts(transform, pts)))
else:
cosphi = _math.cos(phi)
sinphi = _math.sin(phi)
x = (x1 - x2) / 2
y = (y1 - y2) / 2
x1p = (cosphi * x) + (sinphi * y)
y1p = (-sinphi * x) + (cosphi * y)
# Correct for out-of-range radii
l = _math.sqrt((x1p ** 2) / (rx ** 2) +
(y1p ** 2) / (ry ** 2))
if l > 1.0:
rx = rx * l
ry = ry * l
if fa == fs:
s = -1
else:
s = 1
c = s * _math.sqrt(max(0.0,
(rx ** 2) * (ry ** 2) -
(rx ** 2) * (y1p ** 2) -
(ry ** 2) * (x1p ** 2)) /
((rx ** 2) * (y1p ** 2) +
(ry ** 2) * (x1p ** 2)))
cxp = c * rx * y1p / ry
cyp = c * (-ry) * x1p / rx
cx = (cosphi * cxp) - (sinphi * cyp) + (x1 + x2) / 2
cy = (sinphi * cxp) + (cosphi * cyp) + (y1 + y2) / 2
v1 = (1.0, 0.0)
v2 = ((x1p - cxp) / rx, (y1p - cyp) / ry)
v3 = ((-x1p - cxp) / rx, (-y1p - cyp) / ry)
theta = vector_angle(v1, v2)
dtheta = vector_angle(v2, v3) % (2 * _math.pi)
if fs == 0 and dtheta > 0.0:
dtheta = dtheta - 2 * _math.pi
elif fs == 1 and dtheta < 0.0:
dtheta = dtheta + 2 * _math.pi
if dtheta < 0.0:
theta1 = theta + dtheta
theta2 = theta
else:
theta1 = theta
theta2 = theta + dtheta
a = translate(
rotatez(arc_ellipse(rx, ry, theta1, theta2), phi),
(cx, cy, 0.0))
a.bounds()
# Transform a
m = _gp.gp_Trsf()
# There's probably a better way to convert a
# matrix to a transformation
m.SetValues(transform.Value(1, 1),
transform.Value(1, 2),
0.0,
transform.Value(1, 3),
transform.Value(2, 1),
transform.Value(2, 2),
0.0,
transform.Value(2, 3),
0.0,
0.0,
transform.Value(1, 1),
0.0, 1e-16, 1e-7) # unsure of
# TolAng and
# TolDist
trf = _BRepBuilderAPI.BRepBuilderAPI_Transform(m)
trf.Perform(a.shape, 1)
a.shape = trf.Shape()
# Convert y to height - y