-
Notifications
You must be signed in to change notification settings - Fork 58
/
SheetMetalUnfolder.py
3261 lines (2880 loc) · 140 KB
/
SheetMetalUnfolder.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# sheet_ufo.py
#
# Copyright 2014, 2018 Ulrich Brammer <ulrich@Pauline>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# 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 General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#
# CHANGELOG
# sheet_ufo.py git-version
# July 2023
# Significant refactor to remove GUI dependencies.
# UI no folly defined in a .ui file and handle through a separate module.
# main entry function processUnfold() simpler and more readable.
# July 2018
# - added sortEdgesTolerant: more robust generation of Wires for unbend Faces
# - generate fold lines, to be used in drawings of the unfolded part.
# - fixed calculation of Bend Angle, not working in some cases
#
# sheet_ufo20.py
# - removal of dead code
# sheet_ufo19.py
# changes from June 2018
# - found solution for the new unbendFace function.
# - supports now non orthogonals cut in the bends
# - seams do not get a face, just do not call makeSeamFace
# this avoids internal faces in the unfold under certain cases.
# sheet_ufo18.py
# - Changes done in 2016 and June 2018
# - allow more complex bends: not only straight cut side edges
# - tested some code, not published
# sheet_ufo17.py
# - Refactored version December 2015
# - Clear division of tasks between analysis and folding
# sheet_ufo16.py
# - Die Weiterreichung eines schon geschnittenen Seitenfaces macht Probleme.
# - Die Seitenfaces passen hinterher nicht mehr mit den Hauptflächen zusammen.
# Geänderter Ansatz: lasse die Seitenflächen in der Suchliste und
# schneide jeweils nur den benötigten Teil raus.
# Ich brauche jetzt eine Suchliste und eine Unfoldliste für die
# Face-Indices.
# TODO:
# - handle a selected seam
# - handle not-circle-curves in bends, done
# - detect features like welded screws
# - make a view-provider for bends
# - make the k-factor selectable
# - upfold or unfold single bends
# - change code to handle face indexes in the node instead of faces
# ideas:
# During analysis make a mesh-like structure for the bend-node
# list of edges in the bend-node
# for each face store a list with edge-indices.
# the reason is, each edge has to be recalculated at unfolding
# so the number of calculations could be half, as if for each
# face all edges are calculated.
# Edges perpendicular to the sheet may only be moved to the new location?
# Need to think about it! No only at the end of the bend node.
# Edges in the middle of the bend node will be sheared, because the
# neutral line is not in the middle of the sheet-thickness.
# OK this is more complex, than I thought at the beginning.
# in a bend node all faces and edges are recreated
# all vertices are translated except those from the parent node.
# the code looked already at each of them.
# a good storage structure is needed!
"""
def main():
return 0
if __name__ == '__main__':
main()
"""
import Part, FreeCAD, FreeCADGui, os, sys
from FreeCAD import Base
import DraftVecUtils, math, time
import Draft
# import traceback
# traceback.print_exc()
try:
from TechDraw import projectEx
except ImportError:
from Drawing import projectEx
from lookup import get_val_from_range
import tempfile
from math import sqrt
from SheetMetalLogger import SMLogger, UnfoldException, BendException, TreeException
KFACTORSTANDARD = None
# TODO: Error Codes
# - Put error numbers into the text
# - Put user help into more texts
unfold_error = {
# error codes for the tree-object
1: ("starting: volume unusable, needs a real 3D-sheet-metal with thickness"),
2: ("Starting: invalid point for thickness measurement"),
3: ("Starting: invalid thickness"),
4: ("Starting: invalid shape"),
5: (
"Starting: Shape has unneeded edges. Please use function refine shape from the Part Workbench before unfolding!"
),
# error codes for the bend-analysis
10: ("Analysis: zero wires in sheet edge analysis"),
11: ("Analysis: double bends not implemented"),
12: ("Analysis: more than one bend-child actually not supported"),
13: ("Analysis: Sheet thickness invalid for this face!"),
14: ("Analysis: the code can not handle edges without neighbor faces"),
15: ("Analysis: the code needs a face at all sheet edges"),
16: (
"Analysis: did not find startangle of bend, please post failing sample for analysis"
),
17: (
"Analysis: Type of surface not supported for sheet metal parts"
), # <SurfaceOfExtrusion object> FIXME?
# error codes for the unfolding
20: ("Unfold: section wire with less than 4 edges"),
21: ("Unfold: Unfold: section wire not closed"),
22: ("Unfold: section failed"),
23: ("Unfold: CutToolWire not closed"),
24: ("Unfold: bend-face without child not implemented"),
25: ("Unfold: "),
26: ("Unfold: not handled curve type in unbendFace"),
-1: ("Unknown error"),
}
def equal_vector(vec1, vec2, p=5):
# compares two vectors
return (
round(vec1.x - vec2.x, p) == 0
and round(vec1.y - vec2.y, p) == 0
and round(vec1.z - vec2.z, p) == 0
)
def equal_vertex(vert1, vert2, p=5):
# compares two vertices
return (
round(vert1.X - vert2.X, p) == 0
and round(vert1.Y - vert2.Y, p) == 0
and round(vert1.Z - vert2.Z, p) == 0
)
def sk_distance(p0, p1):
return sqrt((p0[0] - p1[0]) ** 2 + (p0[1] - p1[1]) ** 2)
def sanitizeSkBsp(s_name, knot_tolerance):
# s_name = 'Sketch001'
s = FreeCAD.ActiveDocument.getObject(s_name)
FreeCAD.Console.PrintWarning("check to sanitize\n")
if "Sketcher" in s.TypeId:
FreeCAD.ActiveDocument.openTransaction("Sanitizing")
idx_to_del = []
geo_to_del = []
# check for duplicates in splines
if len(s.Geometry) > 2: # cleaning algo approx valid for more than 2 splines
for i, g in enumerate(s.Geometry):
if "BSplineCurve object" in str(g):
j = i + 1
for bg in s.Geometry[(i + 1) :]:
if "BSplineCurve object" in str(bg):
if j not in idx_to_del:
if len(g.KnotSequence) == len(bg.KnotSequence):
# print('equal knot nbrs')
eqp = True
if (
sk_distance(g.StartPoint, bg.StartPoint)
> knot_tolerance
):
if (
sk_distance(g.StartPoint, bg.EndPoint)
> knot_tolerance
):
eqp = False
if (
sk_distance(g.EndPoint, bg.EndPoint)
> knot_tolerance
):
if (
sk_distance(g.EndPoint, bg.StartPoint)
> knot_tolerance
):
eqp = False
# print(simu_dist(g.StartPoint,bg.StartPoint))
# print(simu_dist(g.StartPoint,bg.EndPoint))
# print(simu_dist(g.EndPoint,bg.StartPoint))
# #if simu_dist(g.StartPoint,bg.StartPoint) > knot_tolerance:
# # eqp = False
# print(simu_dist(g.EndPoint,bg.EndPoint))
# if simu_dist(g.EndPoint,bg.EndPoint) > knot_tolerance:
# eqp = False
# for k,kn in enumerate (bg.KnotSequence):
# if abs(kn-g.KnotSequence[k]) > knot_tolerance:
# print (kn,g.KnotSequence[k])
# if abs(kn-g.KnotSequence[k]) > knot_tolerance:
# if (kn == g.KnotSequence[k]):
# eqp = False
if eqp:
print("identical splines found") # ,g,bg)
if j not in idx_to_del:
idx_to_del.append(j)
j += 1
j = 0
# print(idx_to_del)
if len(idx_to_del) > 0:
FreeCAD.Console.PrintMessage("sanitizing " + s.Label)
FreeCAD.Console.PrintMessage("\n")
idx_to_del.sort()
# print(idx_to_del)
idx_to_del.reverse()
# print(idx_to_del)
# stop
for i, e in enumerate(idx_to_del):
# print('to delete ',s.Geometry[(e)],e)
print("deleting identical geo")
# print(s.Geometry)
s.delGeometry(e)
# print(s.Geometry)
FreeCAD.ActiveDocument.commitTransaction()
return s.Geometry
else:
return None
##
def radial_vector(point, axis_pnt, axis):
chord = axis_pnt.sub(point)
norm = axis.cross(chord)
perp = axis.cross(norm)
# FreeCAD.Console.PrintLog( str(chord) + ' ' + str(norm) + ' ' + str(perp)+'\n')
# test_line = Part.makeLine(axis_pnt.add(dist_rv),axis_pnt)
# test_line = Part.makeLine(axis_pnt.add(perp),axis_pnt)
# test_line = Part.makeLine(point, axis_pnt)
# Part.show(test_line)
return perp.normalize()
def equal_angle(ang1, ang2, p=5):
# compares two angles
result = False
if round(ang1 - ang2, p) == 0:
result = True
if round((ang1 - 2.0 * math.pi) - ang2, p) == 0:
result = True
if round(ang1 - (ang2 - 2.0 * math.pi), p) == 0:
result = True
return result
def equal_edge(edg1, edg2, p=5):
result = True
if len(edg1.Vertexes) > 1:
if not (
equal_vertex(edg1.Vertexes[0], edg2.Vertexes[0])
or equal_vertex(edg1.Vertexes[0], edg2.Vertexes[1])
):
result = False
if not (
equal_vertex(edg1.Vertexes[1], edg2.Vertexes[0])
or equal_vertex(edg1.Vertexes[1], edg2.Vertexes[1])
):
result = False
else:
if not (equal_vertex(edg1.Vertexes[0], edg2.Vertexes[0])):
result = False
if len(edg2.Vertexes) > 1:
result = False
return result
class Simple_node(object):
"""This class defines the nodes of a tree, that is the result of
the analysis of a sheet-metal-part.
Each flat or bend part of the metal-sheet gets a node in the tree.
The indexes are the number of the face in the original part.
Faces of the edge of the metal-sheet need in cases to be split.
These new faces are added to the index list.
"""
global KFACTORSTANDARD
def __init__(
self,
f_idx=None,
Parent_node=None,
Parent_edge=None,
k_factor_lookup=None,
):
self.idx = f_idx # Index of the "top-face"
self.c_face_idx = (
None # Face index to the opposite face of the sheet (counter-face)
)
self.node_type = None # 'Flat' or 'Bend'
self.p_node = Parent_node # Parent node
self.p_edge = Parent_edge # The connecting edge to the parent node
self.child_list = [] # List of child-nodes = link to tree structure
self.child_idx_lists = [] # List of lists with child_idx and child_edge
# need a list of indices of child faces
self.sheet_edges = [] # List of edges without child-face
self.axis = None # Direction of the axis of the detected cylindrical face
self.facePosi = None
self.bendCenter = None # Vector of the center of the detected cylindrical face
self.distCenter = (
None # Value used to detect faces at opposite side of the bend
)
self.innerRadius = None # nominal radius of the bend
# self.axis for 'Flat'-face: vector pointing from the surface into the metal
self.bend_dir = None # Bend direction values: "up" or "down"
self.bend_angle = None # Angle in radians
self.tan_vec = None # Direction of translation for Bend nodes
self.oppositePoint = None # Point of a vertex on the opposite site, used to align points to the sheet plane
self.vertexDict = {} # Vertexes of a bend, original and unbend coordinates, flags p, c, t, o
self.edgeDict = {} # Unbend edges dictionary, key is a combination of indexes to vertexDict.
self._trans_length = None # Length of translation for Bend nodes
self.analysis_ok = (
True # Indicator if something went wrong with the analysis of the face
)
self.error_code = None # Index to unfold_error dictionary
self.k_factor_lookup = (
k_factor_lookup # K-factor lookup dictionary, according to ANSI standard
)
# new node features:
self.nfIndexes = [] # List of all face-indexes of a node (flat and bend: folded state)
self.seam_edges = [] # List with edges to seams
# bend faces are needed for movement simulation at single other bends.
# otherwise unfolded faces are recreated from self.b_edges
self.node_flattened_faces = [] # Faces of a flattened bend node
self.unfoldTopList = None # Source of identical side edges
self.unfoldCounterList = None # Source of identical side edges
self.actual_angle = None # State of angle in refolded sheet metal part
self.p_wire = None # Wire common with parent node, used for bend node
self.c_wire = None # Wire common with child node, used for bend node
self.b_edges = [] # List of edges in a bend node, that needs to be recalculated, at unfolding
def dump(self):
print("Node: %s" % (str(self.idx)))
print(" Type: %s" % (str(self.node_type)))
print(" Parent: %s" % (str(self.p_node)))
print(" Parent edge: %s" % (str(self.p_edge)))
print(" Children: %s" % (str(self.child_list)))
print(" Child idx lists: %s" % (str(self.child_idx_lists)))
print(" Sheet edges: %s" % (str(self.sheet_edges)))
print(" Axis: %s" % (str(self.axis)))
print(" Face position: %s" % (str(self.facePosi)))
print(" Bend center: %s" % (str(self.bendCenter)))
print(" Distance to center: %s" % (str(self.distCenter)))
print(" Inner radius: %s" % (str(self.innerRadius)))
print(" Bend direction: %s" % (str(self.bend_dir)))
print(" Bend angle: %s" % (str(self.bend_angle)))
print(" Tangent vector: %s" % (str(self.tan_vec)))
print(" Opposite point: %s" % (str(self.oppositePoint)))
print(" Vertex dictionary: %s" % (str(self.vertexDict)))
print(" Edge dictionary: %s" % (str(self.edgeDict)))
print(" translation length %s" % (str(self._trans_length)))
print(" Analysis ok: %s" % (str(self.analysis_ok)))
print(" Error code: %s" % (str(self.error_code)))
print(" K-factor lookup: %s" % (str(self.k_factor_lookup)))
print(" nfIndexes: %s" % (str(self.nfIndexes)))
print(" seam edges: %s" % (str(self.seam_edges)))
print(" node flattened faces: %s" % (str(self.node_flattened_faces)))
print(" unfoldTopList: %s" % (str(self.unfoldTopList)))
print(" unfoldCounterList: %s" % (str(self.unfoldCounterList)))
print(" actual angle: %s" % (str(self.actual_angle)))
print(" p_wire: %s" % (str(self.p_wire)))
print(" c_wire: %s" % (str(self.c_wire)))
print(" b_edges: %s" % (str(self.b_edges)))
def get_Face_idx(self):
# get the face index from the tree-element
return self.idx
@property
def k_Factor(self):
k = get_val_from_range(self.k_factor_lookup, self.innerRadius / self.thickness)
return k if KFACTORSTANDARD == "ansi" else k / 2
@k_Factor.setter
def k_Factor(self, val):
SMLogger.error(
FreeCAD.Qt.translate(
"Logger", "k_Factor is a readonly property! Won't set to:"
),
val,
)
def get_surface(face):
# 'searchSubShape' is used to distinguish upstream FreeCAD with LinkStage3
# branch, which has a different implementation of findPlane()
if hasattr(face, "searchSubShape"):
try:
surface = face.findPlane()
if surface:
return surface
except Exception:
pass
surface = face.Surface
if face.Orientation == "Reversed" and isinstance(surface, Part.Plane):
return Part.Plane(surface.Position, -surface.Axis)
return surface
class SheetTree(object):
# Class representing a wire to replace in the unfolded shape. During tree creation, some features are detected
# (e.g. countersink and counterbore holes) and are replaced later when the unfolded shape is created.
class WireReplacement:
def __init__(self, face_idx, wire_idx, new_wire):
self.face_idx = face_idx
self.wire_idx = wire_idx
self.new_wire = new_wire
def dump(self):
FreeCAD.Console.PrintLog("Dumping tree:" + "\n")
print("Root node:")
print(self.root)
print("f_list:")
print(self.f_list)
print("index_list:")
print(self.index_list)
print("index Unfold list:")
print(self.index_unfold_list)
def __init__(self, TheShape, f_idx, k_factor_lookup):
self.cFaceTol = 0.002 # tolerance to detect counter-face vertices
# this high tolerance was needed for more real parts
self.root = None # make_new_face_node adds the root node if parent_node == None
self.__Shape = TheShape.copy()
self.error_code = None
self.failed_face_idx = None
self.k_factor_lookup = k_factor_lookup
self.wire_replacements = [] # list of wires to be replaced during unfold shape creation
if not self.__Shape.isValid():
FreeCAD.Console.PrintLog("The shape is not valid!" + "\n")
self.error_code = 4 # Starting: invalid shape
self.failed_face_idx = f_idx
# Part.show(self.__Shape)
# List of indices to the shape.Faces. The list is used a lot for face searches.
# Some faces will be cut and the new ones added to the list.
# So a list of faces independent of the shape is needed.
self.f_list = [] # self.__Shape.Faces.copy() does not work
self.index_list = []
self.index_unfold_list = [] # indexes needed for unfolding
for i in range(len(self.__Shape.Faces)):
# for i in range(len (self.f_list)):
# if i<>(f_idx):
self.index_list.append(i)
self.index_unfold_list.append(i)
self.f_list.append(self.__Shape.Faces[i])
# print self.index_list
self.max_f_idx = len(
self.f_list
) # need this value to make correct indices to new faces
self.unfoldFaces = len(
self.f_list
) # need the original number of faces for error detection
# withoutSplitter = self.__Shape.removeSplitter()
# if self.unfoldFaces > len(withoutSplitter.Faces): # This is not a good idea! Most sheet metal parts have unneeded edges.
# print 'got case which needs a refine shape from the Part workbench!'
# self.error_code = 5
# self.failed_face_idx = f_idx
theVol = self.__Shape.Volume
if theVol < 0.0001:
FreeCAD.Console.PrintLog(
"Shape is not a real 3D-object or to small for a metal-sheet!" + "\n"
)
self.error_code = 1
self.failed_face_idx = f_idx
return
# Make a first estimate of the thickness
estimated_thickness = theVol / (self.__Shape.Area / 2.0)
FreeCAD.Console.PrintLog(
"approximate Thickness: " + str(estimated_thickness) + "\n"
)
# Measure the real thickness of the initial face:
# Use Orientation and Axis to make a measurement vector
if not hasattr(self.__Shape.Faces[f_idx], "Surface"):
return
# Part.show(self.__Shape.Faces[f_idx])
# print 'the object is a face! vertices: ', len(self.__Shape.Faces[f_idx].Vertexes)
F_type = self.__Shape.Faces[f_idx].Surface
# FIXME: through an error, if not Plane Object
FreeCAD.Console.PrintLog("It is a: " + str(F_type) + "\n")
FreeCAD.Console.PrintLog(
"Orientation: " + str(self.__Shape.Faces[f_idx].Orientation) + "\n"
)
# Need a point on the surface to measure the thickness.
# Sheet edges could be sloping, so there is a danger to measure
# right at the edge.
# Try with Arithmetic mean of plane vertices
m_vec = Base.Vector(0.0, 0.0, 0.0) # calculating a mean vector
for Vvec in self.__Shape.Faces[f_idx].Vertexes:
# m_vec = m_vec.add(Base.Vector(Vvec.X, Vvec.Y, Vvec.Z))
m_vec = m_vec.add(Vvec.Point)
mvec = m_vec.multiply(1.0 / len(self.__Shape.Faces[f_idx].Vertexes))
FreeCAD.Console.PrintLog("mvec: " + str(mvec) + "\n")
# if hasattr(self.__Shape.Faces[f_idx].Surface,'Position'):
# s_Posi = self.__Shape.Faces[f_idx].Surface.Position
# k = 0
# while k < len(self.__Shape.Faces[f_idx].Vertexes):
# FIXME: what if measurepoint is outside?
if self.__Shape.isInside(mvec, 0.00001, True):
measure_pos = mvec
gotValidMeasurePosition = True
else:
gotValidMeasurePosition = False
for pvert in self.__Shape.Faces[f_idx].OuterWire.Vertexes:
# pvert = self.__Shape.Faces[f_idx].Vertexes[k]
pvec = Base.Vector(pvert.X, pvert.Y, pvert.Z)
shiftvec = mvec.sub(pvec)
shiftvec = shiftvec.normalize() * 2.0 * estimated_thickness
measure_pos = pvec.add(shiftvec)
if self.__Shape.isInside(measure_pos, 0.00001, True):
gotValidMeasurePosition = True
break
# Description: Checks if a point is inside a solid with a certain tolerance.
# If the 3rd parameter is True a point on a face is considered as inside
# if not self.__Shape.isInside(measure_pos, 0.00001, True):
if not gotValidMeasurePosition:
FreeCAD.Console.PrintLog(
"Starting measure_pos for thickness measurement is outside!\n"
)
self.error_code = 2
self.failed_face_idx = f_idx
surface = get_surface(self.__Shape.Faces[f_idx])
s_Axis = surface.Axis
s_Posi = surface.Position
# print 'We have a position: ', s_Posi
s_Axismp = Base.Vector(s_Axis.x, s_Axis.y, s_Axis.z).multiply(
2.0 * estimated_thickness
)
# Part.show(Meassure_axis)
Meassure_axis = Part.makeLine(measure_pos, measure_pos.sub(s_Axismp))
ext_Vec = Base.Vector(-s_Axis.x, -s_Axis.y, -s_Axis.z)
lostShape = self.__Shape.copy()
lLine = Meassure_axis.common(lostShape)
lLine = Meassure_axis.common(self.__Shape)
FreeCAD.Console.PrintLog("lLine number edges: " + str(len(lLine.Edges)) + "\n")
measVert = Part.Vertex(measure_pos)
for mEdge in lLine.Edges:
if equal_vertex(mEdge.Vertexes[0], measVert) or equal_vertex(
mEdge.Vertexes[1], measVert
):
self.__thickness = mEdge.Length
# self.__thickness = lLine.Length
if (self.__thickness < estimated_thickness) or (
self.__thickness > 1.9 * estimated_thickness
):
self.error_code = 3
self.failed_face_idx = f_idx
FreeCAD.Console.PrintLog(
"estimated thickness: "
+ str(estimated_thickness)
+ " measured thickness: "
+ str(self.__thickness)
+ "\n"
)
Part.show(lLine, "Measurement_Thickness_trial")
def get_node_faces(self, theNode, wires_e_lists):
"""This function searches for all faces making up the node, except
of the top and bottom face, which are already there.
wires_e_list is the list of wires lists of the top face without the parent-edge
theNode: the actual node to be filled with data.
"""
# Where to start?
# Searching for all faces that have two vertices in common with
# an edge from the list should give the sheet edge.
# But, we also need to look at the sheet edge, in order to not claim
# faces from the next node!
# Then we have to treat those faces that belong to more than one node.
# Those faces needs to be cut and the face list needs to be updated.
# Look also at the number of wires of the top face. More wires will
# indicate a hole or a feature.
found_indices = []
# A search strategy for faces based on the wires_e_lists is needed.
for theWire in wires_e_lists:
for theEdge in theWire:
analyVert = theEdge.Vertexes[0]
for i in self.index_list:
for lookVert in self.f_list[i].Vertexes:
if equal_vertex(lookVert, analyVert):
if len(theEdge.Vertexes) == 1: # Edge is a circle
if not self.is_sheet_edge_face(theEdge, theNode):
found_indices.append(i) # found a node face
theNode.child_idx_lists.append([i, theEdge])
# self.index_list.remove(i) # remove this face from the index_list
# Part.show(self.f_list[i])
else:
nextVert = theEdge.Vertexes[1]
for looknextVert in self.f_list[i].Vertexes:
if equal_vertex(looknextVert, nextVert):
# Special case to handle : sometimes, holes are defined as two semicircles, thus there are 2 edges and 2 interior faces for the hole.
# Since both edges have the exact same vertices, this algorithm would bind each interior face with each edge, so we'd get something
# like that : [[face1, edge1], [face2, edge2], [face1, edge2], [face2, edge1]]. Here the last two pairs are not valid, thus we remove
# them by checking that the edge is part of the face before adding the pair to the list.
edge_faces = self.__Shape.ancestorsOfType(
theEdge, Part.Face
)
found = False
for edge_face in edge_faces:
if edge_face.isSame(self.f_list[i]):
found = True
break
if found:
if not self.is_sheet_edge_face(
theEdge, theNode
):
found_indices.append(
i
) # found a node face
theNode.child_idx_lists.append(
[i, theEdge]
)
# self.index_list.remove(i) # remove this face from the index_list
# Part.show(self.f_list[i])
FreeCAD.Console.PrintLog("found_indices: " + str(found_indices) + "\n")
def is_sheet_edge_face(self, ise_edge, tree_node): # ise_edge: IsSheetEdge_edge
# Idea: look at properties of neighbor face
# Look at edges with distance of sheet-thickness.
# if found and surface == cylinder, check if it could be a bend-node.
# Look at number of edges:
# A face with 3 edges is at the sheet edge Cylinder-face or triangle (oh no!)
# need to look also at surface!
# A sheet edge face with more as 4 edges, is common to more than 1 node.
# get the face which has a common edge with ise_edge
the_index = None
has_sheet_distance_vertex = False
for i in self.index_list:
for sf_edge in self.f_list[i].Edges:
if self.same_edges(sf_edge, ise_edge):
the_index = i
# print 'got edge face: Face', str(i+1)
break
if the_index is not None:
break
# Simple strategy applied: look if the connecting face has vertexes
# with sheet-thickness distance to the top face.
# FIXME: this will fail with sharpened sheet edges with two faces
# between top and bottom.
if the_index is not None:
# now we need to search for vertexes with sheet_thickness_distance
for F_vert in self.f_list[i].Vertexes:
# vDist = self.getDistanceToFace(F_vert, tree_node)
# if vDist > maxDist: maxDist = vDist
# if vDist < minDist: minDist = vDist
# maxDist = maxDist- self.__thickness
# if (minDist > -self.cFaceTol) and (maxDist < self.cFaceTol) and (maxDist > -self.cFaceTol):
if self.isVertOpposite(F_vert, tree_node):
has_sheet_distance_vertex = True
if len(self.f_list[i].Edges) < 5:
tree_node.nfIndexes.append(i)
self.index_list.remove(i)
# Part.show(self.f_list[i])
else:
# need to cut the face at the ends of ise_edge
self.divideEdgeFace(i, ise_edge, F_vert, tree_node)
break
else:
tree_node.analysis_ok = False
tree_node.error_code = (
15 # Analysis: the code needs a face at all sheet edges
)
self.error_code = 15
self.failed_face_idx = tree_node.idx
Part.show(self.f_list[tree_node.idx])
return has_sheet_distance_vertex
# Method to check if two edges are the same, i.e. they have the same vertices.
# This is needed because sometimes an edge may be defined twice but with vertices in a different order, thus edge1.isSame(edge2) may fail even though it is the same edge
# Right now this works only if the edge has two vertices, to be improved later if needed.
def same_edges(self, edge1, edge2):
return edge1.isSame(edge2) or (
len(edge1.Vertexes) == 2
and len(edge2.Vertexes) == 2
and edge1.firstVertex().isSame(edge2.lastVertex())
and edge2.firstVertex().isSame(edge1.lastVertex())
)
def isVertOpposite(self, theVert, theNode):
F_type = str(get_surface(self.f_list[theNode.idx]))
vF_vert = Base.Vector(theVert.X, theVert.Y, theVert.Z)
if F_type == "<Plane object>":
distFailure = (
vF_vert.distanceToPlane(theNode.facePosi, theNode.axis)
- self.__thickness
)
elif F_type == "<Cylinder object>":
distFailure = (
vF_vert.distanceToLine(theNode.bendCenter, theNode.axis)
- theNode.distCenter
)
else:
distFailure = 100.0
theNode.error_code = (
17 # Analysis: the code needs a face at all sheet edges
)
self.error_code = 17
self.failed_face_idx = theNode.idx
# Part.show(self.f_list[theNode.idx], 'SurfaceType_not_supported')
# print "counter face distance: ", dist_v + self.__thickness
if (distFailure < self.cFaceTol) and (distFailure > -self.cFaceTol):
return True
else:
return False
def getDistanceToFace(self, theVert, theNode):
F_type = str(get_surface(self.f_list[theNode.idx]))
vF_vert = Base.Vector(theVert.X, theVert.Y, theVert.Z)
# a positive distance should go through the sheet metal
if F_type == "<Plane object>":
dist = vF_vert.distanceToPlane(theNode.facePosi, theNode.axis)
if F_type == "<Cylinder object>":
dist = (
vF_vert.distanceToLine(theNode.bendCenter, theNode.axis)
- self.f_list[theNode.idx].Surface.Radius
)
if theNode.bend_dir == "down":
dist = -dist
return dist
def divideEdgeFace(self, fIdx, ise_edge, F_vert, tree_node):
FreeCAD.Console.PrintLog("Sheet edge face has more than 4 edges!\n")
# first find out where the Sheet edge face has no edge to the opposite side of the sheet
# There is a need to cut the face.
# make a cut-tool perpendicular to the ise_edge
# cut the face and select the good one to add to the node
# make another cut, in order to add the residual face(s) to the face list.
# Search edges in the face with a vertex common with ise_edge
F_type = str(get_surface(self.f_list[tree_node.idx]))
needCut0 = True
firstCutFaceIdx = None
for sEdge in self.f_list[fIdx].Edges:
if equal_vertex(
ise_edge.Vertexes[0], sEdge.Vertexes[0]
) and self.isVertOpposite(sEdge.Vertexes[1], tree_node):
needCut0 = False
theEdge = sEdge
if equal_vertex(
ise_edge.Vertexes[0], sEdge.Vertexes[1]
) and self.isVertOpposite(sEdge.Vertexes[0], tree_node):
needCut0 = False
theEdge = sEdge
if needCut0:
# print "need Cut at 0 with fIdx: ", fIdx
nFace = self.cutEdgeFace(0, fIdx, ise_edge, tree_node)
tree_node.nfIndexes.append(self.max_f_idx)
self.f_list.append(nFace)
firstCutFaceIdx = self.max_f_idx
self.max_f_idx += 1
# self.f_list.append(rFace)
# self.index_list.append(self.max_f_idx)
# self.max_f_idx += 1
# self.index_list.remove(fIdx)
# Part.show(nFace)
# else:
# Part.show(theEdge)
needCut1 = True
for sEdge in self.f_list[fIdx].Edges:
if equal_vertex(ise_edge.Vertexes[1], sEdge.Vertexes[0]):
if self.isVertOpposite(sEdge.Vertexes[1], tree_node):
needCut1 = False
theEdge = sEdge
if equal_vertex(ise_edge.Vertexes[1], sEdge.Vertexes[1]):
if self.isVertOpposite(sEdge.Vertexes[0], tree_node):
needCut1 = False
theEdge = sEdge
if needCut1:
if needCut0:
fIdx = firstCutFaceIdx
tree_node.nfIndexes.remove(fIdx)
# print "need Cut at 1 with fIdx: ", fIdx
nFace = self.cutEdgeFace(1, fIdx, ise_edge, tree_node)
tree_node.nfIndexes.append(self.max_f_idx)
self.f_list.append(nFace)
firstCutFaceIdx = self.max_f_idx
self.max_f_idx += 1
# self.f_list.append(rFace)
# self.index_list.append(self.max_f_idx)
# self.max_f_idx += 1
# if not needCut0:
# self.index_list.remove(fIdx)
# Part.show(nFace)
# else:
# Part.show(theEdge)
def cutEdgeFace(self, eIdx, fIdx, theEdge, theNode):
"""This function cuts a face in two pieces.
one piece is connected to the node.
The residual piece is discarded.
The function returns the piece that has a common edge with the top face of theNode.
"""
# print "now the face cutter: ", fIdx, ' ', eIdx, ' ', theNode.idx
# Part.show(theEdge, 'EdgeToCut'+ str(theNode.idx+1)+'_')
# Part.show(self.f_list[fIdx], 'FaceToCut'+ str(theNode.idx+1)+'_')
if eIdx == 0:
otherIdx = 1
else:
otherIdx = 0
origin = theEdge.Vertexes[eIdx].Point
F_type = str(get_surface(self.f_list[theNode.idx]))
if F_type == "<Plane object>":
tan_vec = theEdge.Vertexes[eIdx].Point - theEdge.Vertexes[otherIdx].Point
# o_thick = Base.Vector(o_vec.x, o_vec.y, o_vec.z)
tan_vec.normalize()
# New approach: search for the nearest vertex at the opposite site.
# The cut is done between the Vertex indicated by eIdx and the nearest
# opposite vertex. This approach should avoid the generation of
# additional short edges in the side faces.
searchAxis = theNode.axis
# else:
# searchAxis = radVector
maxDistance = 1000
oppoPoint = None
# print('need to check Face', str(fIdx+1), ' with ', len(self.f_list[fIdx].Vertexes))
for theVert in self.f_list[fIdx].Vertexes:
# need to check if theVert has
if self.isVertOpposite(theVert, theNode):
vertDist = theVert.Point.distanceToLine(origin, searchAxis)
if vertDist < maxDistance:
maxDistance = vertDist
oppoPoint = theVert.Point
if oppoPoint is None:
print(" error need always an opposite point in a side face!")
# FIXME: need a proper error condition.
# vec1 = Base.Vector(theNode.axis.x, theNode.axis.y, theNode.axis.z) # make a copy
vec1 = (oppoPoint - origin).normalize()
crossVec = tan_vec.cross(vec1)
crossVec.multiply(3.0 * self.__thickness)
vec1.multiply(self.__thickness)
# defining the points of the cutting plane:
Spnt1 = origin - vec1 - crossVec
Spnt2 = origin - vec1 + crossVec
Spnt3 = origin + vec1 + vec1 + crossVec
Spnt4 = origin + vec1 + vec1 - crossVec
if F_type == "<Cylinder object>":
ePar = theEdge.parameterAt(theEdge.Vertexes[eIdx])
FreeCAD.Console.PrintLog("Idx: " + str(eIdx) + " ePar: " + str(ePar) + "\n")
otherPar = theEdge.parameterAt(theEdge.Vertexes[otherIdx])
tan_vec = theEdge.tangentAt(ePar)
if ePar < otherPar:
tan_vec.multiply(-1.0)
# tan_line = Part.makeLine(theEdge.Vertexes[eIdx].Point.add(tan_vec), theEdge.Vertexes[eIdx].Point)
# Part.show(tan_line, 'tan_line'+ str(theNode.idx+1)+'_')
edge_vec = theEdge.Vertexes[eIdx].copy().Point
radVector = radial_vector(edge_vec, theNode.bendCenter, theNode.axis)
if theNode.bend_dir == "down":
radVector.multiply(-1.0)
# rad_line = Part.makeLine(theEdge.Vertexes[eIdx].Point.add(radVector), theEdge.Vertexes[eIdx].Point)
# Part.show(rad_line, 'rad_line'+ str(theNode.idx+1)+'_')
searchAxis = radVector
maxDistance = 1000
oppoPoint = None
# print('need to check Face', str(fIdx+1), ' with ', len(self.f_list[fIdx].Vertexes))
for theVert in self.f_list[fIdx].Vertexes:
# need to check if theVert has
if self.isVertOpposite(theVert, theNode):
vertDist = theVert.Point.distanceToLine(origin, searchAxis)
if vertDist < maxDistance:
maxDistance = vertDist
oppoPoint = theVert.Point
if oppoPoint is None:
print(" error need always an opposite point in a side face!")
# FIXME: need a proper error condition.
# vec1 = Base.Vector(radVector.x, radVector.y, radVector.z) # make a copy
vec1 = (oppoPoint - origin).normalize()
crossVec = tan_vec.cross(vec1)
crossVec.multiply(3.0 * self.__thickness)
vec1.multiply(self.__thickness)
# defining the points of the cutting plane:
Spnt1 = origin - vec1 - crossVec
Spnt2 = origin - vec1 + crossVec
Spnt3 = origin + vec1 + vec1 + crossVec
Spnt4 = origin + vec1 + vec1 - crossVec
Sedge1 = Part.makeLine(Spnt1, Spnt2)
Sedge2 = Part.makeLine(Spnt2, Spnt3)
Sedge3 = Part.makeLine(Spnt3, Spnt4)
Sedge4 = Part.makeLine(Spnt4, Spnt1)
Sw1 = Part.Wire([Sedge1, Sedge2, Sedge3, Sedge4])
# Part.show(Sw1, 'cutWire'+ str(theNode.idx+1)+'_')
Sf1 = Part.Face(Sw1) #
# Part.show(Sf1, 'cutFace'+ str(theNode.idx+1)+'_')
# cut_solid = Sf1.extrude(tan_vec.multiply(5.0))
cut_solid = Sf1.extrude(tan_vec.multiply(self.__thickness))
# Part.show(cut_solid, 'cut_solid'+ str(theNode.idx+1)+'_')
# cut_opposite = Sf1.extrude(tan_vec.multiply(-5.0))
cutFaces_node = self.f_list[fIdx].cut(cut_solid)
for cFace in cutFaces_node.Faces:
for myVert in cFace.Vertexes:
if equal_vertex(theEdge.Vertexes[eIdx], myVert):
nodeFace = cFace
# print "The nodeFace Idx: ", fIdx, ' eIdx: ', eIdx
# Part.show(nodeFace)
break
return nodeFace # , residueFace
def getBendAngle(self, newNode, wires_e_lists):
"""Get the bend angle for a node connected to a bend face,
Get the k-Factor
Get the translation Length
"""
# newNode = Simple_node(face_idx, P_node, P_edge)
P_node = newNode.p_node
P_edge = newNode.p_edge
face_idx = newNode.idx
theFace = self.__Shape.Faces[face_idx]