/
DraftGeomUtils.py
executable file
·2784 lines (2507 loc) · 105 KB
/
DraftGeomUtils.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
#***************************************************************************
#* *
#* Copyright (c) 2009, 2010 *
#* Yorik van Havre <yorik@uncreated.net>, Ken Cline <cline@frii.com> *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
#* as published by the Free Software Foundation; either version 2 of *
#* the License, or (at your option) any later version. *
#* for detail see the LICENCE text file. *
#* *
#* This program is distributed in the hope that it will be useful, *
#* but WITHOUT ANY WARRANTY; without even the implied warranty of *
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
#* GNU Library General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* License along with this program; if not, write to the Free Software *
#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
#* USA *
#* *
#***************************************************************************
__title__="FreeCAD Draft Workbench - Geometry library"
__author__ = "Yorik van Havre, Jacques-Antoine Gaudin, Ken Cline"
__url__ = ["http://www.freecadweb.org"]
"this file contains generic geometry functions for manipulating Part shapes"
import FreeCAD, Part, DraftVecUtils, math, cmath
from FreeCAD import Vector
NORM = Vector(0,0,1) # provisory normal direction for all geometry ops.
params = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Draft")
# Generic functions *********************************************************
def precision():
"precision(): returns the Draft precision setting"
return params.GetInt("precision")
def vec(edge):
"vec(edge) or vec(line): returns a vector from an edge or a Part.line"
# if edge is not straight, you'll get strange results!
if isinstance(edge,Part.Shape):
return edge.Vertexes[-1].Point.sub(edge.Vertexes[0].Point)
elif isinstance(edge,Part.Line):
return edge.EndPoint.sub(edge.StartPoint)
else:
return None
def edg(p1,p2):
"edg(Vector,Vector): returns an edge from 2 vectors"
if isinstance(p1,FreeCAD.Vector) and isinstance(p2,FreeCAD.Vector):
if DraftVecUtils.equals(p1,p2): return None
else: return Part.Line(p1,p2).toShape()
def getVerts(shape):
"getVerts(shape): returns a list containing vectors of each vertex of the shape"
if not hasattr(shape,"Vertexes"):
return []
p = []
for v in shape.Vertexes:
p.append(v.Point)
return p
def v1(edge):
"v1(edge): returns the first point of an edge"
return edge.Vertexes[0].Point
def isNull(something):
'''isNull(object): returns true if the given shape is null or the given placement is null or
if the given vector is (0,0,0)'''
if isinstance(something,Part.Shape):
return something.isNull()
elif isinstance(something,FreeCAD.Vector):
if something == Vector(0,0,0):
return True
else:
return False
elif isinstance(something,FreeCAD.Placement):
if (something.Base == Vector(0,0,0)) and (something.Rotation.Q == (0,0,0,1)):
return True
else:
return False
def isPtOnEdge(pt,edge) :
'''isPtOnEdge(Vector,edge): Tests if a point is on an edge'''
v = Part.Vertex(pt)
d = v.distToShape(edge)
if d:
if round(d[0],precision()) == 0:
return True
return False
def hasCurves(shape):
"hasCurve(shape): checks if the given shape has curves"
for e in shape.Edges:
if not isinstance(e.Curve,Part.Line):
return True
return False
def isAligned(edge,axis="x"):
"isAligned(edge,axis): checks if the given edge or line is aligned to the given axis (x, y or z)"
if axis == "x":
if isinstance(edge,Part.Edge):
if len(edge.Vertexes) == 2:
if edge.Vertexes[0].X == edge.Vertexes[-1].X:
return True
elif isinstance(edge,Part.Line):
if edge.StartPoint.x == edge.EndPoint.x:
return True
elif axis == "y":
if isinstance(edge,Part.Edge):
if len(edge.Vertexes) == 2:
if edge.Vertexes[0].Y == edge.Vertexes[-1].Y:
return True
elif isinstance(edge,Part.Line):
if edge.StartPoint.y == edge.EndPoint.y:
return True
elif axis == "z":
if isinstance(edge,Part.Edge):
if len(edge.Vertexes) == 2:
if edge.Vertexes[0].Z == edge.Vertexes[-1].Z:
return True
elif isinstance(edge,Part.Line):
if edge.StartPoint.z == edge.EndPoint.z:
return True
return False
def getQuad(face):
"""getQuad(face): returns a list of 3 vectors (basepoint, Xdir, Ydir) if the face
is a quad, or None if not."""
if len(face.Edges) != 4:
return None
v1 = vec(face.Edges[0])
v2 = vec(face.Edges[1])
v3 = vec(face.Edges[2])
v4 = vec(face.Edges[3])
angles90 = [round(math.pi*0.5,precision()),round(math.pi*1.5,precision())]
angles180 = [0,round(math.pi,precision()),round(math.pi*2,precision())]
for ov in [v2,v3,v4]:
if not (round(v1.getAngle(ov),precision()) in angles90+angles180):
return None
for ov in [v2,v3,v4]:
if round(v1.getAngle(ov),precision()) in angles90:
v1.normalize()
ov.normalize()
return [face.Edges[0].Vertexes[0].Point,v1,ov]
def areColinear(e1,e2):
"""areColinear(e1,e2): returns True if both edges are colinear"""
if not isinstance(e1.Curve,Part.Line):
return False
if not isinstance(e2.Curve,Part.Line):
return False
v1 = vec(e1)
v2 = vec(e2)
a = round(v1.getAngle(v2),precision())
if (a == 0) or (a == round(math.pi,precision())):
v3 = e2.Vertexes[0].Point.sub(e1.Vertexes[0].Point)
if DraftVecUtils.isNull(v3):
return True
else:
a2 = round(v1.getAngle(v3),precision())
if (a2 == 0) or (a2 == round(math.pi,precision())):
return True
return False
def hasOnlyWires(shape):
"hasOnlyWires(shape): returns True if all the edges are inside a wire"
ne = 0
for w in shape.Wires:
ne += len(w.Edges)
if ne == len(shape.Edges):
return True
return False
def geomType(edge):
"returns the type of geom this edge is based on"
try:
if isinstance(edge.Curve,Part.Line):
return "Line"
elif isinstance(edge.Curve,Part.Circle):
return "Circle"
elif isinstance(edge.Curve,Part.BSplineCurve):
return "BSplineCurve"
elif isinstance(edge.Curve,Part.BezierCurve):
return "BezierCurve"
elif isinstance(edge.Curve,Part.Ellipse):
return "Ellipse"
else:
return "Unknown"
except:
return "Unknown"
def isValidPath(shape):
"isValidPath(shape): returns True if the shape can be used as an extrusion path"
if shape.isNull():
return False
if shape.Faces:
return False
if len(shape.Wires) > 1:
return False
if shape.Wires:
if shape.Wires[0].isClosed():
return False
if shape.isClosed():
return False
return True
# edge functions *****************************************************************
def findEdge(anEdge,aList):
'''findEdge(anEdge,aList): returns True if anEdge is found in aList of edges'''
for e in range(len(aList)):
if str(anEdge.Curve) == str(aList[e].Curve):
if DraftVecUtils.equals(anEdge.Vertexes[0].Point,aList[e].Vertexes[0].Point):
if DraftVecUtils.equals(anEdge.Vertexes[-1].Point,aList[e].Vertexes[-1].Point):
return(e)
return None
def findIntersection(edge1,edge2,infinite1=False,infinite2=False,ex1=False,ex2=False,dts=True) :
'''findIntersection(edge1,edge2,infinite1=False,infinite2=False,dts=True):
returns a list containing the intersection point(s) of 2 edges.
You can also feed 4 points instead of edge1 and edge2. If dts is used,
Shape.distToShape() is used, which can be buggy'''
def getLineIntersections(pt1,pt2,pt3,pt4,infinite1,infinite2):
if pt1:
# first check if we don't already have coincident endpoints
if (pt1 in [pt3,pt4]):
return [pt1]
elif (pt2 in [pt3,pt4]):
return [pt2]
norm1 = pt2.sub(pt1).cross(pt3.sub(pt1))
norm2 = pt2.sub(pt4).cross(pt3.sub(pt4))
if not DraftVecUtils.isNull(norm1):
try:
norm1.normalize()
except:
return []
if not DraftVecUtils.isNull(norm2):
try:
norm2.normalize()
except:
return []
if DraftVecUtils.isNull(norm1.cross(norm2)):
vec1 = pt2.sub(pt1)
vec2 = pt4.sub(pt3)
if DraftVecUtils.isNull(vec1) or DraftVecUtils.isNull(vec2):
return [] # One of the line has zero-length
try:
vec1.normalize()
vec2.normalize()
except:
return []
norm3 = vec1.cross(vec2)
if not DraftVecUtils.isNull(norm3) :
k = ((pt3.z-pt1.z)*(vec2.x-vec2.y)+(pt3.y-pt1.y)*(vec2.z-vec2.x)+ \
(pt3.x-pt1.x)*(vec2.y-vec2.z))/(norm3.x+norm3.y+norm3.z)
vec1.scale(k,k,k)
intp = pt1.add(vec1)
if infinite1 == False and not isPtOnEdge(intp,edge1) :
return []
if infinite2 == False and not isPtOnEdge(intp,edge2) :
return []
return [intp]
else :
return [] # Lines have same direction
else :
return [] # Lines aren't on same plane
# First, try to use distToShape if possible
if dts and isinstance(edge1,Part.Edge) and isinstance(edge2,Part.Edge) \
and (not infinite1) and (not infinite2) and \
edge1.BoundBox.isIntersection(edge2.BoundBox):
dist, pts, geom = edge1.distToShape(edge2)
sol = []
for p in pts:
sol.append(p[0])
return sol
pt1 = None
if isinstance(edge1,FreeCAD.Vector) and isinstance(edge2,FreeCAD.Vector):
# we got points directly
pt1 = edge1
pt2 = edge2
pt3 = infinite1
pt4 = infinite2
infinite1 = ex1
infinite2 = ex2
return getLineIntersections(pt1,pt2,pt3,pt4,infinite1,infinite2)
elif (geomType(edge1) == "Line") and (geomType(edge2) == "Line") :
# we have 2 straight lines
pt1, pt2, pt3, pt4 = [edge1.Vertexes[0].Point,
edge1.Vertexes[1].Point,
edge2.Vertexes[0].Point,
edge2.Vertexes[1].Point]
return getLineIntersections(pt1,pt2,pt3,pt4,infinite1,infinite2)
elif (geomType(edge1) == "Circle") and (geomType(edge2) == "Line") \
or (geomType(edge1) == "Line") and (geomType(edge2) == "Circle") :
# deals with an arc or circle and a line
edges = [edge1,edge2]
for edge in edges :
if geomType(edge) == "Line":
line = edge
else :
arc = edge
dirVec = vec(line) ; dirVec.normalize()
pt1 = line.Vertexes[0].Point
pt2 = line.Vertexes[1].Point
pt3 = arc.Vertexes[0].Point
pt4 = arc.Vertexes[-1].Point
center = arc.Curve.Center
# first check for coincident endpoints
if (pt1 in [pt3,pt4]):
return [pt1]
elif (pt2 in [pt3,pt4]):
return [pt2]
if DraftVecUtils.isNull(pt1.sub(center).cross(pt2.sub(center)).cross(arc.Curve.Axis)) :
# Line and Arc are on same plane
dOnLine = center.sub(pt1).dot(dirVec)
onLine = Vector(dirVec)
onLine.scale(dOnLine,dOnLine,dOnLine)
toLine = pt1.sub(center).add(onLine)
if toLine.Length < arc.Curve.Radius :
dOnLine = (arc.Curve.Radius**2 - toLine.Length**2)**(0.5)
onLine = Vector(dirVec)
onLine.scale(dOnLine,dOnLine,dOnLine)
int = [center.add(toLine).add(onLine)]
onLine = Vector(dirVec)
onLine.scale(-dOnLine,-dOnLine,-dOnLine)
int += [center.add(toLine).add(onLine)]
elif round(toLine.Length-arc.Curve.Radius,precision()) == 0 :
int = [center.add(toLine)]
else :
return []
else :
# Line isn't on Arc's plane
if dirVec.dot(arc.Curve.Axis) != 0 :
toPlane = Vector(arc.Curve.Axis) ; toPlane.normalize()
d = pt1.dot(toPlane)
if not d:
return []
dToPlane = center.sub(pt1).dot(toPlane)
toPlane = Vector(pt1)
toPlane.scale(dToPlane/d,dToPlane/d,dToPlane/d)
ptOnPlane = toPlane.add(pt1)
if round(ptOnPlane.sub(center).Length - arc.Curve.Radius,precision()) == 0 :
int = [ptOnPlane]
else :
return []
else :
return []
if infinite1 == False :
for i in range(len(int)-1,-1,-1) :
if not isPtOnEdge(int[i],edge1) :
del int[i]
if infinite2 == False :
for i in range(len(int)-1,-1,-1) :
if not isPtOnEdge(int[i],edge2) :
del int[i]
return int
elif (geomType(edge1) == "Circle") and (geomType(edge2) == "Circle") :
# deals with 2 arcs or circles
cent1, cent2 = edge1.Curve.Center, edge2.Curve.Center
rad1 , rad2 = edge1.Curve.Radius, edge2.Curve.Radius
axis1, axis2 = edge1.Curve.Axis , edge2.Curve.Axis
c2c = cent2.sub(cent1)
if DraftVecUtils.isNull(axis1.cross(axis2)) :
if round(c2c.dot(axis1),precision()) == 0 :
# circles are on same plane
dc2c = c2c.Length ;
if not DraftVecUtils.isNull(c2c): c2c.normalize()
if round(rad1+rad2-dc2c,precision()) < 0 \
or round(rad1-dc2c-rad2,precision()) > 0 or round(rad2-dc2c-rad1,precision()) > 0 :
return []
else :
norm = c2c.cross(axis1)
if not DraftVecUtils.isNull(norm): norm.normalize()
if DraftVecUtils.isNull(norm): x = 0
else: x = (dc2c**2 + rad1**2 - rad2**2)/(2*dc2c)
y = abs(rad1**2 - x**2)**(0.5)
c2c.scale(x,x,x)
if round(y,precision()) != 0 :
norm.scale(y,y,y)
int = [cent1.add(c2c).add(norm)]
int += [cent1.add(c2c).sub(norm)]
else :
int = [cent1.add(c2c)]
else :
return [] # circles are on parallel planes
else :
# circles aren't on same plane
axis1.normalize() ; axis2.normalize()
U = axis1.cross(axis2)
V = axis1.cross(U)
dToPlane = c2c.dot(axis2)
d = V.add(cent1).dot(axis2)
V.scale(dToPlane/d,dToPlane/d,dToPlane/d)
PtOn2Planes = V.add(cent1)
planeIntersectionVector = U.add(PtOn2Planes)
intTemp = findIntersection(planeIntersectionVector,edge1,True,True)
int = []
for pt in intTemp :
if round(pt.sub(cent2).Length-rad2,precision()) == 0 :
int += [pt]
if infinite1 == False :
for i in range(len(int)-1,-1,-1) :
if not isPtOnEdge(int[i],edge1) :
del int[i]
if infinite2 == False :
for i in range(len(int)-1,-1,-1) :
if not isPtOnEdge(int[i],edge2) :
del int[i]
return int
else :
print("DraftGeomUtils: Unsupported curve type: (" + str(edge1.Curve) + ", " + str(edge2.Curve) + ")")
def wiresIntersect(wire1,wire2):
"wiresIntersect(wire1,wire2): returns True if some of the edges of the wires are intersecting otherwise False"
for e1 in wire1.Edges:
for e2 in wire2.Edges:
if findIntersection(e1,e2,dts=False):
return True
return False
def pocket2d(shape,offset):
"""pocket2d(shape,offset): return a list of wires obtained from offsetting the wires from the given shape
by the given offset, and intersection if needed."""
# find the outer wire
l = 0
outerWire = None
innerWires = []
for w in shape.Wires:
if w.BoundBox.DiagonalLength > l:
outerWire = w
l = w.BoundBox.DiagonalLength
if not outerWire:
return []
for w in shape.Wires:
if w.hashCode() != outerWire.hashCode():
innerWires.append(w)
o = outerWire.makeOffset(-offset)
if not o.Wires:
return []
offsetWires = o.Wires
print("base offset wires:",offsetWires)
if not innerWires:
return offsetWires
for innerWire in innerWires:
i = innerWire.makeOffset(offset)
if i.Wires:
print("offsetting island ",innerWire," : ",i.Wires)
for w in i.Wires:
added = False
print("checking wire ",w)
k = list(range(len(offsetWires)))
for j in k:
print("checking against existing wire ",j)
ow = offsetWires[j]
if ow:
if wiresIntersect(w,ow):
print("intersect")
f1 = Part.Face(ow)
f2 = Part.Face(w)
f3 = f1.cut(f2)
print("made new wires: ",f3.Wires)
offsetWires[j] = f3.Wires[0]
if len(f3.Wires) > 1:
print("adding more")
offsetWires.extend(f3.Wires[1:])
added = True
else:
a = w.BoundBox
b = ow.BoundBox
if (a.XMin <= b.XMin) and (a.YMin <= b.YMin) and (a.ZMin <= b.ZMin) and (a.XMax >= b.XMax) and (a.YMax >= b.YMax) and (a.ZMax >= b.ZMax):
print("this wire is bigger than the outer wire")
offsetWires[j] = None
added = True
else:
print("doesn't intersect")
if not added:
print("doesn't intersect with any other")
offsetWires.append(w)
offsetWires = [o for o in offsetWires if o != None]
return offsetWires
def geom(edge,plac=FreeCAD.Placement()):
"returns a Line, ArcOfCircle or Circle geom from the given edge, according to the given placement"
if geomType(edge) == "Line":
return edge.Curve
elif geomType(edge) == "Circle":
if len(edge.Vertexes) == 1:
return Part.Circle(edge.Curve.Center,edge.Curve.Axis,edge.Curve.Radius)
else:
# reorienting the arc along the correct normal
normal = plac.Rotation.multVec(FreeCAD.Vector(0,0,1))
v1 = edge.Vertexes[0].Point
v2 = edge.Vertexes[-1].Point
c = edge.Curve.Center
cu = Part.Circle(edge.Curve.Center,normal,edge.Curve.Radius)
ref = plac.Rotation.multVec(Vector(1,0,0))
a1 = DraftVecUtils.angle(v1.sub(c),ref,normal.negative())
a2 = DraftVecUtils.angle(v2.sub(c),ref,normal.negative())
# direction check
if edge.Curve.Axis.getAngle(normal) > 1:
a1,a2 = a2,a1
#print("creating sketch arc from ",cu, ", p1=",v1, " (",math.degrees(a1), "d) p2=",v2," (", math.degrees(a2),"d)")
p= Part.ArcOfCircle(cu,a1,a2)
return p
elif geomType(edge) == "Ellipse":
if len(edge.Vertexes) == 1:
return edge.Curve
else:
return Part.ArcOfEllipse(edge.Curve,edge.FirstParameter,edge.LastParameter)
else:
return edge.Curve
def mirror (point, edge):
"finds mirror point relative to an edge"
normPoint = point.add(findDistance(point, edge, False))
if normPoint:
normPoint_point = Vector.sub(point, normPoint)
normPoint_refl = normPoint_point.negative()
refl = Vector.add(normPoint, normPoint_refl)
return refl
else:
return None
def isClockwise(edge,ref=None):
"""Returns True if a circle-based edge has a clockwise direction"""
if not geomType(edge) == "Circle":
return True
v1 = edge.Curve.tangent(edge.ParameterRange[0])[0]
if DraftVecUtils.isNull(v1):
return True
# we take an arbitrary other point on the edge that has little chances to be aligned with the first one...
v2 = edge.Curve.tangent(edge.ParameterRange[0]+0.01)[0]
n = edge.Curve.Axis
# if that axis points "the wrong way" from the reference, we invert it
if not ref:
ref = Vector(0,0,1)
if n.getAngle(ref) > math.pi/2:
n = n.negative()
if DraftVecUtils.angle(v1,v2,n) < 0:
return False
if n.z < 0:
return False
return True
def isSameLine(e1,e2):
"""isSameLine(e1,e2): return True if the 2 edges are lines and have the same
points"""
if not isinstance(e1.Curve,Part.Line):
return False
if not isinstance(e2.Curve,Part.Line):
return False
if (DraftVecUtils.equals(e1.Vertexes[0].Point,e2.Vertexes[0].Point)) and \
(DraftVecUtils.equals(e1.Vertexes[-1].Point,e2.Vertexes[-1].Point)):
return True
elif (DraftVecUtils.equals(e1.Vertexes[-1].Point,e2.Vertexes[0].Point)) and \
(DraftVecUtils.equals(e1.Vertexes[0].Point,e2.Vertexes[-1].Point)):
return True
return False
def isWideAngle(edge):
"""returns True if the given edge is an arc with angle > 180 degrees"""
if geomType(edge) != "Circle":
return False
r = edge.Curve.Radius
total = 2*r*math.pi
if edge.Length > total/2:
return True
return False
def findClosest(basepoint,pointslist):
'''
findClosest(vector,list)
in a list of 3d points, finds the closest point to the base point.
an index from the list is returned.
'''
if not pointslist: return None
smallest = 100000
for n in range(len(pointslist)):
new = basepoint.sub(pointslist[n]).Length
if new < smallest:
smallest = new
npoint = n
return npoint
def concatenate(shape):
"concatenate(shape) -- turns several faces into one"
edges = getBoundary(shape)
edges = sortEdges(edges)
try:
wire=Part.Wire(edges)
face=Part.Face(wire)
except:
print("DraftGeomUtils: Couldn't join faces into one")
return(shape)
else:
if not wire.isClosed(): return(wire)
else: return(face)
def getBoundary(shape):
"getBoundary(shape) -- this function returns the boundary edges of a group of faces"
# make a lookup-table where we get the number of occurrences
# to each edge in the fused face
if isinstance(shape,list):
shape = Part.makeCompound(shape)
lut={}
for f in shape.Faces:
for e in f.Edges:
hc= e.hashCode()
if hc in lut: lut[hc]=lut[hc]+1
else: lut[hc]=1
# filter out the edges shared by more than one sub-face
bound=[]
for e in shape.Edges:
if lut[e.hashCode()] == 1: bound.append(e)
return bound
def isLine(bsp):
"returns True if the given BSpline curve is a straight line"
step = bsp.LastParameter/10
b = bsp.tangent(0)
for i in range(10):
if bsp.tangent(i*step) != b:
return False
return True
def sortEdges(edges):
"""Sort edges in path order, i.e., such that the end point of edge N
equals the start point of edge N+1.
"""
# Build a dictionary of edges according to their end points.
# Each entry is a set of edges that starts, or ends, at the
# given vertex hash.
if len(edges) < 2:
return edges
sdict = dict()
edict = dict()
nedges = []
for e in edges:
if hasattr(e,"Length"):
if e.Length != 0:
sdict.setdefault( e.Vertexes[0].hashCode(), [] ).append(e)
edict.setdefault( e.Vertexes[-1].hashCode(),[] ).append(e)
nedges.append(e)
if not nedges:
print "DraftGeomUtils.sortEdges: zero-length edges"
return edges
# Find the start of the path. The start is the vertex that appears
# in the sdict dictionary but not in the edict dictionary, and has
# only one edge ending there.
startedge = None
for v, se in sdict.items():
if v not in edict and len(se) == 1:
startedge = se
break
# The above may not find a start vertex; if the start edge is reversed,
# the start vertex will appear in edict (and not sdict).
if not startedge:
for v, se in edict.items():
if v not in sdict and len(se) == 1:
startedge = se
break
# If we still have no start vertex, it was a closed path. If so, start
# with the first edge in the supplied list
if not startedge:
startedge = nedges[0]
v = startedge.Vertexes[0].hashCode()
# Now build the return list by walking the edges starting at the start
# vertex we found. We're done when we've visited each edge, so the
# end check is simply the count of input elements (that works for closed
# as well as open paths).
ret = list()
# store the hash code of the last edge, to avoid picking the same edge back
eh = None
for i in range(len(nedges)):
try:
eset = sdict[v]
e = eset.pop()
if not eset:
del sdict[v]
if e.hashCode() == eh:
raise KeyError
v = e.Vertexes[-1].hashCode()
eh = e.hashCode()
except KeyError:
try:
eset = edict[v]
e = eset.pop()
if not eset:
del edict[v]
if e.hashCode() == eh:
raise KeyError
v = e.Vertexes[0].hashCode()
eh = e.hashCode()
e = invert(e)
except KeyError:
print("DraftGeomUtils.sortEdges failed - running old version")
return sortEdgesOld(edges)
ret.append(e)
# All done.
return ret
def sortEdgesOld(lEdges, aVertex=None):
"an alternative, more accurate version of Part.__sortEdges__ (old version)"
#There is no reason to limit this to lines only because every non-closed edge always
#has exactly two vertices (wmayer)
#for e in lEdges:
# if not isinstance(e.Curve,Part.Line):
# print("Warning: sortedges cannot treat wired containing curves yet.")
# return lEdges
def lookfor(aVertex, inEdges):
''' Look for (aVertex, inEdges) returns count, the position of the instance
the position in the instance and the instance of the Edge'''
count = 0
linstances = [] #lists the instances of aVertex
for i in range(len(inEdges)) :
for j in range(2) :
if aVertex.Point == inEdges[i].Vertexes[j-1].Point:
instance = inEdges[i]
count += 1
linstances += [i,j-1,instance]
return [count]+linstances
if (len(lEdges) < 2):
if aVertex == None:
return lEdges
else:
result = lookfor(aVertex,lEdges)
if result[0] != 0:
if aVertex.Point == result[3].Vertexes[0].Point:
return lEdges
else:
if geomType(result[3]) == "Line":
return [Part.Line(aVertex.Point,result[3].Vertexes[0].Point).toShape()]
elif geomType(result[3]) == "Circle":
mp = findMidpoint(result[3])
return [Part.Arc(aVertex.Point,mp,result[3].Vertexes[0].Point).toShape()]
elif geomType(result[3]) == "BSplineCurve" or\
geomType(result[3]) == "BezierCurve":
if isLine(result[3].Curve):
return [Part.Line(aVertex.Point,result[3].Vertexes[0].Point).toShape()]
else:
return lEdges
else:
return lEdges
olEdges = [] # ol stands for ordered list
if aVertex == None:
for i in range(len(lEdges)*2) :
if len(lEdges[i/2].Vertexes) > 1:
result = lookfor(lEdges[i/2].Vertexes[i%2],lEdges)
if result[0] == 1 : # Have we found an end ?
olEdges = sortEdgesOld(lEdges, result[3].Vertexes[result[2]])
return olEdges
# if the wire is closed there is no end so choose 1st Vertex
# print("closed wire, starting from ",lEdges[0].Vertexes[0].Point)
return sortEdgesOld(lEdges, lEdges[0].Vertexes[0])
else :
#print("looking ",aVertex.Point)
result = lookfor(aVertex,lEdges)
if result[0] != 0 :
del lEdges[result[1]]
next = sortEdgesOld(lEdges, result[3].Vertexes[-((-result[2])^1)])
#print("result ",result[3].Vertexes[0].Point," ",result[3].Vertexes[1].Point, " compared to ",aVertex.Point)
if aVertex.Point == result[3].Vertexes[0].Point:
#print("keeping")
olEdges += [result[3]] + next
else:
#print("inverting", result[3].Curve)
if geomType(result[3]) == "Line":
newedge = Part.Line(aVertex.Point,result[3].Vertexes[0].Point).toShape()
olEdges += [newedge] + next
elif geomType(result[3]) == "Circle":
mp = findMidpoint(result[3])
newedge = Part.Arc(aVertex.Point,mp,result[3].Vertexes[0].Point).toShape()
olEdges += [newedge] + next
elif geomType(result[3]) == "BSplineCurve" or \
geomType(result[3]) == "BezierCurve":
if isLine(result[3].Curve):
newedge = Part.Line(aVertex.Point,result[3].Vertexes[0].Point).toShape()
olEdges += [newedge] + next
else:
olEdges += [result[3]] + next
else:
olEdges += [result[3]] + next
return olEdges
else :
return []
def invert(edge):
'''invert(edge): returns an inverted copy of this edge'''
if len(edge.Vertexes) == 1:
return edge
if geomType(edge) == "Line":
return Part.Line(edge.Vertexes[-1].Point,edge.Vertexes[0].Point).toShape()
elif geomType(edge) == "Circle":
mp = findMidpoint(edge)
return Part.Arc(edge.Vertexes[-1].Point,mp,edge.Vertexes[0].Point).toShape()
elif geomType(edge) in ["BSplineCurve","BezierCurve"]:
if isLine(edge.Curve):
return Part.Line(edge.Vertexes[-1].Point,edge.Vertexes[0].Point).toShape()
print "DraftGeomUtils.invert: unable to invert ",edge.Curve
return edge
def flattenWire(wire):
'''flattenWire(wire): forces a wire to get completely flat
along its normal.'''
import WorkingPlane
n = getNormal(wire)
if not n:
return
o = wire.Vertexes[0].Point
plane = WorkingPlane.plane()
plane.alignToPointAndAxis(o,n,0)
verts = [o]
for v in wire.Vertexes[1:]:
verts.append(plane.projectPoint(v.Point))
verts.append(o)
w = Part.makePolygon(verts)
return w
def findWires(edgeslist):
'''finds connected wires in the given list of edges'''
def touches(e1,e2):
if len(e1.Vertexes) < 2:
return False
if len(e2.Vertexes) < 2:
return False
if DraftVecUtils.equals(e1.Vertexes[0].Point,e2.Vertexes[0].Point):
return True
if DraftVecUtils.equals(e1.Vertexes[0].Point,e2.Vertexes[-1].Point):
return True
if DraftVecUtils.equals(e1.Vertexes[-1].Point,e2.Vertexes[0].Point):
return True
if DraftVecUtils.equals(e1.Vertexes[-1].Point,e2.Vertexes[-1].Point):
return True
return False
edges = edgeslist[:]
wires = []
lost = []
while edges:
e = edges[0]
if not wires:
# create first group
edges.remove(e)
wires.append([e])
else:
found = False
for w in wires:
if not found:
for we in w:
if touches(e,we):
edges.remove(e)
w.append(e)
found = True
break
if not found:
if e in lost:
# we already tried this edge, and still nothing
edges.remove(e)
wires.append([e])
lost = []
else:
# put to the end of the list
edges.remove(e)
edges.append(e)
lost.append(e)
nwires = []
for w in wires:
try:
wi = Part.Wire(w)
except:
print("couldn't join some edges")
else:
nwires.append(wi)
return nwires
def superWire(edgeslist,closed=False):
'''superWire(edges,[closed]): forces a wire between edges that don't necessarily
have coincident endpoints. If closed=True, wire will always be closed'''
def median(v1,v2):
vd = v2.sub(v1)
vd.scale(.5,.5,.5)
return v1.add(vd)
edges = sortEdges(edgeslist)
print(edges)
newedges = []
for i in range(len(edges)):
curr = edges[i]
if i == 0:
if closed:
prev = edges[-1]
else:
prev = None
else:
prev = edges[i-1]
if i == (len(edges)-1):
if closed:
next = edges[0]
else:
next = None
else:
next = edges[i+1]
print(i,prev,curr,next)
if prev:
if curr.Vertexes[0].Point == prev.Vertexes[-1].Point:
p1 = curr.Vertexes[0].Point
else:
p1 = median(curr.Vertexes[0].Point,prev.Vertexes[-1].Point)
else:
p1 = curr.Vertexes[0].Point
if next:
if curr.Vertexes[-1].Point == next.Vertexes[0].Point:
p2 = next.Vertexes[0].Point
else:
p2 = median(curr.Vertexes[-1].Point,next.Vertexes[0].Point)
else:
p2 = curr.Vertexes[-1].Point
if geomType(curr) == "Line":
print("line",p1,p2)
newedges.append(Part.Line(p1,p2).toShape())
elif geomType(curr) == "Circle":
p3 = findMidpoint(curr)
print("arc",p1,p3,p2)
newedges.append(Part.Arc(p1,p3,p2).toShape())
else:
print("Cannot superWire edges that are not lines or arcs")
return None
print(newedges)
return Part.Wire(newedges)
def findMidpoint(edge):
"calculates the midpoint of an edge"
first = edge.Vertexes[0].Point
last = edge.Vertexes[-1].Point
if geomType(edge) == "Circle":
center = edge.Curve.Center
radius = edge.Curve.Radius
if len(edge.Vertexes) == 1:
# Circle
dv = first.sub(center)
dv = dv.negative()
return center.add(dv)
axis = edge.Curve.Axis
chord = last.sub(first)
perp = chord.cross(axis)
perp.normalize()
ray = first.sub(center)
apothem = ray.dot(perp)
sagitta = radius - apothem
startpoint = Vector.add(first, chord.multiply(0.5))
endpoint = DraftVecUtils.scaleTo(perp,sagitta)
return Vector.add(startpoint,endpoint)
elif geomType(edge) == "Line":
halfedge = (last.sub(first)).multiply(.5)
return Vector.add(first,halfedge)
else:
return None