/
importDXF.py
2078 lines (1946 loc) · 80.8 KB
/
importDXF.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
# -*- coding: utf8 -*-
#***************************************************************************
#* *
#* Copyright (c) 2009 Yorik van Havre <yorik@uncreated.net> *
#* *
#* 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 - DXF importer/exporter"
__author__ = "Yorik van Havre <yorik@uncreated.net>"
__url__ = ["http://www.freecadweb.org"]
'''
This script uses a DXF-parsing library created by Stani,
Kitsu and Migius for Blender
imports:
line, polylines, lwpolylines, arcs, circles, texts,
mtexts, layers (as groups), colors
exports:
lines, polylines, lwpolylines, circles, arcs,
texts, colors,layers (from groups)
'''
TEXTSCALING = 1.35 # scaling factor between autocad font sizes and coin font sizes
CURRENTDXFLIB = 1.39 # the minimal version of the dxfLibrary needed to run
import sys, FreeCAD, os, Part, math, re, string, Mesh, Draft, DraftVecUtils, DraftGeomUtils
from Draft import _Dimension, _ViewProviderDimension
from FreeCAD import Vector
gui = FreeCAD.GuiUp
draftui = None
if gui:
import FreeCADGui
try:
draftui = FreeCADGui.draftToolBar
except (AttributeError,NameError):
draftui = None
dxfReader = None
dxfColorMap = None
dxfLibrary = None
if open.__module__ == '__builtin__':
pythonopen = open # to distinguish python built-in open function from the one declared here
def errorDXFLib(gui):
p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Draft")
dxfAllowDownload = p.GetBool("dxfAllowDownload",False)
if dxfAllowDownload:
files = ['dxfColorMap.py','dxfImportObjects.py','dxfLibrary.py','dxfReader.py']
baseurl = 'https://raw.githubusercontent.com/yorikvanhavre/Draft-dxf-importer/'+str(CURRENTDXFLIB)+"/"
import ArchCommands
from FreeCAD import Base
progressbar = Base.ProgressIndicator()
progressbar.start("Downloading files...",4)
for f in files:
progressbar.next()
p = None
p = ArchCommands.download(baseurl+f,force=True)
if not p:
if gui:
from PySide import QtGui, QtCore
from DraftTools import translate
message = translate("Draft","""Download of dxf libraries failed.
Please download and install them manually.
See complete instructions at
http://www.freecadweb.org/wiki/index.php?title=Dxf_Importer_Install""")
QtGui.QMessageBox.information(None,"",message)
else:
FreeCAD.Console.PrintWarning("The DXF import/export libraries needed by FreeCAD to handle the DXF format are not installed.\n")
FreeCAD.Console.PrintWarning("Please check https://github.com/yorikvanhavre/Draft-dxf-importer\n")
break
progressbar.stop()
sys.path.append(FreeCAD.ConfigGet("UserAppData"))
else:
if gui:
from PySide import QtGui, QtCore
from DraftTools import translate
message = translate('draft',"""The DXF import/export libraries needed by FreeCAD to handle
the DXF format were not found on this system.
Please either enable FreeCAD to download these libraries:
1 - Load Draft workbench
2 - Menu Edit > Preferences > Import-Export > DXF > Enable downloads
Or download these libraries manually, as explained on
https://github.com/yorikvanhavre/Draft-dxf-importer
To enabled FreeCAD to download these libraries, answer Yes.""")
reply = QtGui.QMessageBox.question(None,"",message.decode('utf8'),
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
p.SetBool("dxfAllowDownload",True)
errorDXFLib(gui)
if reply == QtGui.QMessageBox.No:
pass
else:
FreeCAD.Console.PrintWarning("The DXF import/export libraries needed by FreeCAD to handle the DXF format are not installed.\n")
FreeCAD.Console.PrintWarning("Please check https://github.com/yorikvanhavre/Draft-dxf-importer\n")
def getDXFlibs():
"loads the DXF python libraries"
try:
if FreeCAD.ConfigGet("UserAppData") not in sys.path:
sys.path.append(FreeCAD.ConfigGet("UserAppData"))
global dxfLibrary,dxfColorMap,dxfReader
import dxfLibrary
import dxfColorMap
import dxfReader
except ImportError:
libsok = False
FreeCAD.Console.PrintWarning("DXF libraries not found. Trying to download...\n")
else:
if "v"+str(CURRENTDXFLIB) in dxfLibrary.__version__:
libsok = True
else:
FreeCAD.Console.PrintWarning("DXF libraries need to be updated. Trying to download...\n")
libsok = False
if not libsok:
errorDXFLib(gui)
try:
import dxfColorMap, dxfLibrary, dxfReader
except ImportError:
dxfReader = None
dxfLibrary = None
FreeCAD.Console.PrintWarning("DXF libraries not available. Aborting.\n")
def prec():
"returns the current Draft precision level"
return Draft.getParam("precision",6)
def decodeName(name):
"decodes encoded strings"
try:
decodedName = (name.decode("utf8"))
except UnicodeDecodeError:
try:
decodedName = (name.decode("latin1"))
except UnicodeDecodeError:
print("dxf: error: couldn't determine character encoding")
decodedName = name
return decodedName
def deformat(text):
"removes weird formats in texts and wipes UTF characters"
# remove ACAD string formatation
#t = re.sub('{([^!}]([^}]|\n)*)}', '', text)
#print("input text: ",text)
t = text.strip("{}")
t = re.sub("\\\.*?;","",t)
# replace UTF codes by utf chars
sts = re.split("\\\\(U\+....)",t)
ns = u""
for ss in sts:
#print(ss, type(ss))
if ss.startswith("U+"):
ucode = "0x"+ss[2:]
ns += unichr(eval(ucode)) #Python3 - unichr doesn't exist anymore
else:
try:
ns += ss.decode("utf8")
except UnicodeError:
try:
ns += ss.decode("latin1")
except UnicodeError:
print("unable to decode text: ",text)
t = ns
# replace degrees, diameters chars
t = re.sub('%%d',u'°',t)
t = re.sub('%%c',u'Ø',t)
t = re.sub('%%D',u'°',t)
t = re.sub('%%C',u'Ø',t)
#print("output text: ",t)
return t
def locateLayer(wantedLayer,color=None):
"returns layer group and creates it if needed"
wantedLayerName = decodeName(wantedLayer)
for l in layers:
if wantedLayerName==l.Label:
return l
if dxfUseDraftVisGroups:
newLayer = Draft.makeVisGroup(name=wantedLayer)
else:
newLayer = doc.addObject("App::DocumentObjectGroup",wantedLayer)
newLayer.Label = wantedLayerName
layers.append(newLayer)
return newLayer
def getdimheight(style):
"returns the dimension text height from the given dimstyle"
for t in drawing.tables.data:
if t.name == 'dimstyle':
for a in t.data:
if hasattr(a,"type"):
if a.type == "dimstyle":
if rawValue(a,2) == style:
return rawValue(a,140)
return 1
def calcBulge(v1,bulge,v2):
'''
calculates intermediary vertex for curved segments.
algorithm from http://www.afralisp.net/lisp/Bulges1.htm
'''
chord = v2.sub(v1)
sagitta = (bulge * chord.Length)/2
perp = chord.cross(Vector(0,0,1))
startpoint = v1.add(chord.multiply(0.5))
if not DraftVecUtils.isNull(perp): perp.normalize()
endpoint = perp.multiply(sagitta)
return startpoint.add(endpoint)
def getGroup(ob):
"checks if the object is part of a group"
for i in FreeCAD.ActiveDocument.Objects:
if i.isDerivedFrom("App::DocumentObjectGroup"):
for j in i.Group:
if (j == ob):
return i.Label
return "0"
def getACI(ob,text=False):
"gets the ACI color closest to the objects color"
if not gui:
return 0
else:
if text:
col=ob.ViewObject.TextColor
else:
col=ob.ViewObject.LineColor
aci=[0,442]
for i in range (255,-1,-1):
ref=dxfColorMap.color_map[i]
dist=((ref[0]-col[0])**2 + (ref[1]-col[1])**2 + (ref[2]-col[2])**2)
if (dist <= aci[1]): aci=[i,dist]
return aci[0]
def rawValue(entity,code):
"returns the value of a DXF code in an entity section"
value = None
for pair in entity.data:
if pair[0] == code:
value = pair[1]
return value
def getMultiplePoints(entity):
"scans the given entity for multiple points (paths, leaders, etc)"
pts = []
for d in entity.data:
if d[0] == 10:
pts.append([d[1]])
elif d[0] in [20,30]:
pts[-1].append(d[1])
pts.reverse()
points = []
for p in pts:
if len(p) == 3:
points.append(Vector(p[0],p[1],p[2]))
else:
points.append(Vector(p[0],p[1],0))
return points
def isBrightBackground():
"checks if the current viewport background is bright"
p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/View")
if p.GetBool("Gradient"):
c1 = p.GetUnsigned("BackgroundColor2")
c2 = p.GetUnsigned("BackgroundColor3")
r1 = float((c1>>24)&0xFF)
g1 = float((c1>>16)&0xFF)
b1 = float((c1>>8)&0xFF)
r2 = float((c2>>24)&0xFF)
g2 = float((c2>>16)&0xFF)
b2 = float((c2>>8)&0xFF)
v1 = FreeCAD.Vector(r1,g1,b1)
v2 = FreeCAD.Vector(r2,g2,b2)
v = v2.sub(v1)
v.multiply(0.5)
cv = v1.add(v)
else:
c1 = p.GetUnsigned("BackgroundColor")
r1 = float((c1>>24)&0xFF)
g1 = float((c1>>16)&0xFF)
b1 = float((c1>>8)&0xFF)
cv = FreeCAD.Vector(r1,g1,b1)
value = cv.x*.3 + cv.y*.59 + cv.z*.11
if value < 128:
return False
else:
return True
def getGroupColor(dxfobj,index=False):
"get color of bylayer stuff"
name = dxfobj.layer
for table in drawing.tables.get_type("table"):
if table.name == "layer":
for l in table.get_type("layer"):
if l.name == name:
if index:
return l.color
else:
if (l.color == 7) and dxfBrightBackground:
return [0.0,0.0,0.0]
else:
if isinstance(l.color,int):
if l.color > 0:
return dxfColorMap.color_map[l.color]
return [0.0,0.0,0.0]
def getColor():
if gui and draftui:
r = float(draftui.color.red()/255.0)
g = float(draftui.color.green()/255.0)
b = float(draftui.color.blue()/255.0)
return (r,g,b,0.0)
else:
p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/View")
c = p.GetUnsigned("DefaultShapeLineColor",0)
r = float(((c>>24)&0xFF)/255)
g = float(((c>>16)&0xFF)/255)
b = float(((c>>8)&0xFF)/255)
return (r,g,b,0.0)
def formatObject(obj,dxfobj=None):
"applies color and linetype to objects"
if dxfGetColors and dxfobj and hasattr(dxfobj,"color_index"):
if hasattr(obj.ViewObject,"TextColor"):
if dxfobj.color_index == 256:
cm = getGroupColor(dxfobj)[:3]
else:
cm = dxfColorMap.color_map[dxfobj.color_index]
obj.ViewObject.TextColor = (cm[0],cm[1],cm[2])
elif hasattr(obj.ViewObject,"LineColor"):
if dxfobj.color_index == 256:
cm = getGroupColor(dxfobj)
elif (dxfobj.color_index == 7) and dxfBrightBackground:
cm = [0.0,0.0,0.0]
else:
cm = dxfColorMap.color_map[dxfobj.color_index]
obj.ViewObject.LineColor = (cm[0],cm[1],cm[2],0.0)
else:
if hasattr(obj.ViewObject,"TextColor"):
obj.ViewObject.TextColor = dxfDefaultColor
elif hasattr(obj.ViewObject,"LineColor"):
obj.ViewObject.LineColor = dxfDefaultColor
def vec(pt):
"returns a rounded and scaled Vector from a dxf point, or rounded and scaled value"
if isinstance(pt,float) or isinstance(pt,int):
v = round(pt,prec())
if dxfScaling != 1:
v = v * dxfScaling
else:
v = FreeCAD.Vector(round(pt[0],prec()),round(pt[1],prec()),round(pt[2],prec()))
if dxfScaling != 1:
v.multiply(dxfScaling)
return v
def drawLine(line,forceShape=False):
"returns a Part shape from a dxf line"
if (len(line.points) > 1):
v1=vec(line.points[0])
v2=vec(line.points[1])
if not DraftVecUtils.equals(v1,v2):
try:
if (dxfCreateDraft or dxfCreateSketch) and (not forceShape):
return Draft.makeWire([v1,v2])
else:
return Part.Line(v1,v2).toShape()
except Part.OCCError:
warn(line)
return None
def drawPolyline(polyline,forceShape=False,num=None):
"returns a Part shape from a dxf polyline"
if (len(polyline.points) > 1):
edges = []
curves = False
verts = []
for p in range(len(polyline.points)-1):
p1 = polyline.points[p]
p2 = polyline.points[p+1]
v1 = vec(p1)
v2 = vec(p2)
verts.append(v1)
if not DraftVecUtils.equals(v1,v2):
if polyline.points[p].bulge:
curves = True
cv = calcBulge(v1,polyline.points[p].bulge,v2)
if DraftVecUtils.isColinear([v1,cv,v2]):
try: edges.append(Part.Line(v1,v2).toShape())
except Part.OCCError: warn(polyline,num)
else:
try: edges.append(Part.Arc(v1,cv,v2).toShape())
except Part.OCCError: warn(polyline,num)
else:
try: edges.append(Part.Line(v1,v2).toShape())
except Part.OCCError: warn(polyline,num)
verts.append(v2)
if polyline.closed:
p1 = polyline.points[len(polyline.points)-1]
p2 = polyline.points[0]
v1 = vec(p1)
v2 = vec(p2)
cv = calcBulge(v1,polyline.points[-1].bulge,v2)
if not DraftVecUtils.equals(v1,v2):
if DraftVecUtils.isColinear([v1,cv,v2]):
try:
edges.append(Part.Line(v1,v2).toShape())
except Part.OCCError:
warn(polyline,num)
else:
try:
edges.append(Part.Arc(v1,cv,v2).toShape())
except Part.OCCError:
warn(polyline,num)
if edges:
try:
width = rawValue(polyline,43)
if width and dxfRenderPolylineWidth:
w = Part.Wire(edges)
w1 = w.makeOffset(width/2)
if polyline.closed:
w2 = w.makeOffset(-width/2)
w1 = Part.Face(w1)
w2 = Part.Face(w2)
if w1.BoundBox.DiagonalLength > w2.BoundBox.DiagonalLength:
return w1.cut(w2)
else:
return w2.cut(w1)
else:
return Part.Face(w1)
elif (dxfCreateDraft or dxfCreateSketch) and (not curves) and (not forceShape):
ob = Draft.makeWire(verts)
ob.Closed = polyline.closed
return ob
else:
if polyline.closed and dxfFillMode:
w = Part.Wire(edges)
return(Part.Face(w))
else:
return Part.Wire(edges)
except Part.OCCError:
warn(polyline,num)
return None
def drawArc(arc,forceShape=False):
"returns a Part shape from a dxf arc"
v=vec(arc.loc)
firstangle=round(arc.start_angle,prec())
lastangle=round(arc.end_angle,prec())
circle=Part.Circle()
circle.Center=v
circle.Radius=vec(arc.radius)
try:
if (dxfCreateDraft or dxfCreateSketch) and (not forceShape):
pl = FreeCAD.Placement()
pl.move(v)
return Draft.makeCircle(arc.radius,pl,False,firstangle,lastangle)
else:
return circle.toShape(math.radians(firstangle),math.radians(lastangle))
except Part.OCCError:
warn(arc)
return None
def drawCircle(circle,forceShape=False):
"returns a Part shape from a dxf circle"
v = vec(circle.loc)
curve = Part.Circle()
curve.Radius = vec(circle.radius)
curve.Center = v
try:
if (dxfCreateDraft or dxfCreateSketch) and (not forceShape):
pl = FreeCAD.Placement()
pl.move(v)
return Draft.makeCircle(circle.radius,pl)
else:
return curve.toShape()
except Part.OCCError:
warn(circle)
return None
def drawEllipse(ellipse,forceShape=False):
"returns a Part shape from a dxf arc"
try:
c = vec(ellipse.loc)
start = round(ellipse.start_angle,prec())
end = round(ellipse.end_angle,prec())
majv = vec(ellipse.major)
majr = majv.Length
minr = majr*ellipse.ratio
el = Part.Ellipse(vec((0,0,0)),majr,minr)
x = majv.normalize()
z = vec(ellipse.extrusion).normalize()
y = z.cross(x)
m = DraftVecUtils.getPlaneRotation(x,y,z)
pl = FreeCAD.Placement(m)
pl.move(c)
if (dxfCreateDraft or dxfCreateSketch) and (not forceShape):
if (start != 0.0) or ((end != 0.0) or (end != round(math.pi/2,prec()))):
shape = el.toShape(start,end)
shape.Placement = pl
return shape
else:
return Draft.makeEllipse(majr,minr,pl)
else:
shape = el.toShape(start,end)
shape.Placement = pl
return shape
except Part.OCCError:
warn(arc)
return None
def drawFace(face):
"returns a Part face from a list of points"
pl = []
for p in face.points:
pl.append(vec(p))
p1 = face.points[0]
pl.append(vec(p1))
try:
pol = Part.makePolygon(pl)
return Part.Face(pol)
except Part.OCCError:
warn(face)
return None
def drawMesh(mesh):
"returns a Mesh from a dxf mesh"
md = []
if mesh.flags == 16:
pts = mesh.points
udim = rawValue(mesh,71)
vdim = rawValue(mesh,72)
for u in range(udim-1):
for v in range(vdim-1):
b = u+v*udim
p1 = pts[b]
p2 = pts[b+1]
p3 = pts[b+udim]
p4 = pts[b+udim+1]
md.append([p1,p2,p4])
md.append([p1,p4,p3])
elif mesh.flags == 64:
pts = []
fcs = []
for p in mesh.points:
if p.flags == 192:
pts.append(p)
elif p.flags == 128:
fcs.append(p)
for f in fcs:
p1 = pts[rawValue(f,71)-1]
p2 = pts[rawValue(f,72)-1]
p3 = pts[rawValue(f,73)-1]
md.append([p1,p2,p3])
if rawValue(f,74) != None:
p4 = pts[rawValue(f,74)-1]
md.append([p1,p3,p4])
try:
return Mesh.Mesh(md)
except FreeCAD.Base.FreeCADError:
warn(mesh)
return None
def drawSolid(solid):
"returns a Part shape from a dxf solid"
p4 = None
p1x = rawValue(solid,10)
p1y = rawValue(solid,20)
p1z = rawValue(solid,30) or 0
p2x = rawValue(solid,11)
p2y = rawValue(solid,21)
p2z = rawValue(solid,31) or p1z
p3x = rawValue(solid,12)
p3y = rawValue(solid,22)
p3z = rawValue(solid,32) or p1z
p4x = rawValue(solid,13)
p4y = rawValue(solid,23)
p4z = rawValue(solid,33) or p1z
p1 = FreeCAD.Vector(p1x,p1y,p1z)
p2 = FreeCAD.Vector(p2x,p2y,p2z)
p3 = FreeCAD.Vector(p3x,p3y,p3z)
if p4x != None: p4 = FreeCAD.Vector(p4x,p4y,p4z)
if p4 and (p4 != p3) and (p4 != p2) and (p4 != p1):
try:
return Part.Face(Part.makePolygon([p1,p2,p4,p3,p1]))
except Part.OCCError:
warn(solid)
else:
try:
return Part.Face(Part.makePolygon([p1,p2,p3,p1]))
except Part.OCCError:
warn(solid)
return None
def drawSplineIterpolation(verts,closed=False,forceShape=False,\
alwaysDiscretize=False):
if (dxfCreateDraft or dxfCreateSketch) and (not forceShape):
if dxfDiscretizeCurves or alwaysDiscretize:
ob = Draft.makeWire(verts)
else:
ob = Draft.makeBSpline(verts)
ob.Closed = closed
return ob
else:
if dxfDiscretizeCurves or alwaysDiscretize:
sh = Part.makePolygon(verts+[verts[0]])
else:
sp = Part.BSplineCurve()
# print(knots)
sp.interpolate(verts)
sh = Part.Wire(sp.toShape())
if closed and dxfFillMode:
return Part.Face(sh)
else:
return sh
def drawSplineOld(spline,forceShape=False):
"returns a Part Shape from a dxf spline"
flag = rawValue(spline,70)
if flag == 1:
closed = True
else:
closed = False
verts = []
knots = []
for dline in spline.data:
if dline[0] == 10:
cp = [dline[1]]
elif dline[0] == 20:
cp.append(dline[1])
elif dline[0] == 30:
cp.append(dline[1])
pt = vec(cp)
if verts:
if pt != verts[-1]:
verts.append(pt)
else:
verts.append(pt)
elif dline[0] == 40:
knots.append(dline[1])
try:
return drawSplineIterpolation(verts,closed,forceShape)
except Part.OCCError:
warn(spline)
return None
def drawSpline(spline,forceShape=False):
"""returns a Part Shape from a dxf spline
as there is currently no Draft premitive to handle splines the result is a
non-parametric curve"""
flags = rawValue(spline,70)
closed = (flags & 1) != 0
periodic = (flags & 2) != 0 and False # workaround
rational = (flags & 4) != 0
planar = (flags & 8) != 0
linear = (flags & 16) != 0
degree = rawValue(spline,71)
nbknots = rawValue(spline,72) or 0
nbcontrolp = rawValue(spline,73) or 0
nbfitp = rawValue(spline,74) or 0
knots = []
weights = []
controlpoints = []
fitpoints = []
# parse the knots and points
dataremain = spline.data[:]
while len(dataremain) >0:
groupnumber = dataremain[0][0]
if groupnumber == 40: #knot
knots.append(dataremain[0][1])
dataremain = dataremain[1:]
elif groupnumber == 41: #weight
weights.append(dataremain[0][1])
dataremain = dataremain[1:]
elif groupnumber in (10,11): # control or fit point
x = dataremain[0][1]
if dataremain[1][0] in (20,21):
y=dataremain[1][1]
if dataremain[2][0] in (30,31):
z=dataremain[2][1]
dataremain = dataremain[3:]
else:
z=0.0
dataremain = dataremain[2:]
else:
y=0.0
dataremain = dataremain[1:]
v = vec([x,y,z])
if groupnumber == 10:
controlpoints.append(v)
elif groupnumber == 11:
fitpoints.append(v)
else:
dataremain = dataremain[1:]
#print groupnumber #debug
if nbknots != len(knots):
raise ValueError('Wrong number of knots')
if nbcontrolp != len(controlpoints):
raise ValueError('Wrong number of control points')
if nbfitp != len(fitpoints):
raise ValueError('Wrong number of fit points')
if rational == all((w == 1.0 or w is None) for w in weights):
raise ValueError('inconsistant rational flag')
if len(weights) == 0:
weights = None
elif len(weights) != len(controlpoints):
raise ValueError('Wrong number of weights')
# build knotvector and multvector
# this means to remove duplicate knots
multvector=[]
knotvector=[]
mult=0
previousknot=None
for knotvalue in knots:
if knotvalue == previousknot:
mult += 1
else:
if mult > 0:
multvector.append(mult)
mult = 1
previousknot = knotvalue
knotvector.append(knotvalue)
multvector.append(mult)
# check if the multiplicities are valid
innermults = multvector[:] if periodic else multvector[1:-1]
if any(m>degree for m in innermults): #invalid
if all(m == degree+1 for m in multvector):
if not forceShape and weights is None:
points=controlpoints[:]
del points[degree+1::degree+1]
return Draft.makeBezCurve(points,Degree=degree)
else:
poles=controlpoints[:]
edges=[]
while len(poles) >= degree+1:
#bezier segments
bzseg=Part.BezierCurve()
bzseg.increase(degree)
bzseg.setPoles(poles[0:degree+1])
poles=poles[degree+1:]
if weights is not None:
bzseg.setWeights(weights[0:degree+1])
weights=weights[degree+1:]
edges.append(bzseg.toShape())
return Part.Wire(edges)
else:
warn('polygon fallback on %s' %spline)
return drawSplineIterpolation(controlpoints,closed=closed,\
forceShape=forceShape,alwaysDiscretize=True)
try:
bspline=Part.BSplineCurve()
bspline.buildFromPolesMultsKnots(poles=controlpoints,mults=multvector,\
knots=knotvector,degree=degree,periodic=periodic,\
weights=weights)
return bspline.toShape()
except Part.OCCError:
warn(spline)
return None
def drawBlock(blockref,num=None,createObject=False):
"returns a shape from a dxf block reference"
if not dxfStarBlocks:
if blockref.name[0] == '*':
return None
if len(blockref.entities.data) == 0:
print("skipping empty block ",blockref.name)
return None
#print("creating block ", blockref.name, " containing ", len(blockref.entities.data), " entities")
shapes = []
for line in blockref.entities.get_type('line'):
s = drawLine(line,forceShape=True)
if s: shapes.append(s)
for polyline in blockref.entities.get_type('polyline'):
s = drawPolyline(polyline,forceShape=True)
if s: shapes.append(s)
for polyline in blockref.entities.get_type('lwpolyline'):
s = drawPolyline(polyline,forceShape=True)
if s: shapes.append(s)
for arc in blockref.entities.get_type('arc'):
s = drawArc(arc,forceShape=True)
if s: shapes.append(s)
for circle in blockref.entities.get_type('circle'):
s = drawCircle(circle,forceShape=True)
if s: shapes.append(s)
for insert in blockref.entities.get_type('insert'):
#print("insert ",insert," in block ",insert.block[0])
if dxfStarBlocks or insert.block[0] != '*':
s = drawInsert(insert)
if s: shapes.append(s)
for solid in blockref.entities.get_type('solid'):
s = drawSolid(solid)
if s: shapes.append(s)
for spline in blockref.entities.get_type('spline'):
s = drawSpline(spline,forceShape=True)
if s: shapes.append(s)
for text in blockref.entities.get_type('text'):
if dxfImportTexts:
if dxfImportLayouts or (not rawValue(text,67)):
addText(text)
for text in blockref.entities.get_type('mtext'):
if dxfImportTexts:
if dxfImportLayouts or (not rawValue(text,67)):
print("adding block text",text.value, " from ",blockref)
addText(text)
try: shape = Part.makeCompound(shapes)
except Part.OCCError: warn(blockref)
if shape:
blockshapes[blockref.name]=shape
if createObject:
newob=doc.addObject("Part::Feature",blockref.name)
newob.Shape = shape
blockobjects[blockref.name] = newob
return newob
return shape
return None
def drawInsert(insert,num=None,clone=False):
if dxfImportTexts:
attrs = attribs(insert)
for a in attrs:
addText(a,attrib=True)
if clone:
if insert.block in blockobjects:
newob = Draft.clone(blockobjects[insert.block])
tsf = FreeCAD.Matrix()
rot = math.radians(insert.rotation)
pos = vec(insert.loc)
tsf.move(pos)
tsf.rotateZ(rot)
sc = insert.scale
sc = vec([sc[0],sc[1],0])
newob.Placement = FreeCAD.Placement(tsf)
newob.Scale = sc
return newob
else:
shape = None
else:
if insert in blockshapes:
shape = blockshapes[insert.block].copy()
else:
shape = None
for b in drawing.blocks.data:
if b.name == insert.block:
shape = drawBlock(b,num)
if shape:
pos = vec(insert.loc)
rot = math.radians(insert.rotation)
scale = insert.scale
tsf = FreeCAD.Matrix()
tsf.scale(scale[0],scale[1],0) # for some reason z must be 0 to work
tsf.rotateZ(rot)
shape = shape.transformGeometry(tsf)
shape.translate(pos)
return shape
return None
def drawLayerBlock(objlist):
"draws a Draft block with the given shapes or objects"
obj = None
if (dxfCreateDraft or dxfCreateSketch):
try:
obj = Draft.makeBlock(objlist)
except Part.OCCError:
pass
else:
try:
obj = Part.makeCompound(objlist)
except Part.OCCError:
pass
return obj
def attribs(insert):
"checks if an insert has attributes, and returns the values if yes"
atts = []
if rawValue(insert,66) != 1: return []
index = None
for i in range(len(drawing.entities.data)):
if drawing.entities.data[i] == insert:
index = i
break
if index == None: return []
j = index+1
while True:
ent = drawing.entities.data[j]
if str(ent) == 'seqend':
return atts
elif str(ent) == 'attrib':
atts.append(ent)
j += 1
def addObject(shape,name="Shape",layer=None):
"adds a new object to the document with passed arguments"
if isinstance(shape,Part.Shape):
newob=doc.addObject("Part::Feature",name)
newob.Shape = shape
else:
newob = shape
if layer:
lay=locateLayer(layer)
lay.addObject(newob)
formatObject(newob)
return newob
def addText(text,attrib=False):
"adds a new text to the document"
if attrib:
lay = locateLayer(rawValue(text,8))
val = rawValue(text,1)
pos = vec([rawValue(text,10),rawValue(text,20),rawValue(text,30)])
hgt = vec(rawValue(text,40))
else:
lay = locateLayer(text.layer)
val = text.value
pos = vec(text.loc)
hgt = vec(text.height)
if val:
if attrib:
newob = doc.addObject("App::Annotation","Attribute")
else:
newob = doc.addObject("App::Annotation","Text")
lay.addObject(newob)
val = deformat(val)
# the following stores text as Latin1 in annotations, which
# displays ok in coin texts, but causes errors later on.
# better store as utf8 always.
#try:
# val = val.decode("utf8").encode("Latin1")
#except:
# try:
# val = val.encode("latin1")
# except:
# pass
rx = rawValue(text,11)
ry = rawValue(text,21)
rz = rawValue(text,31)
xv = Vector(1,0,0)
ax = Vector(0,0,1)
if rx or ry or rz:
xv = vec([rx,ry,rz])
if not DraftVecUtils.isNull(xv):
ax = (xv.cross(Vector(1,0,0))).negative()
if DraftVecUtils.isNull(ax):
ax = Vector(0,0,1)
ang = -math.degrees(DraftVecUtils.angle(xv,Vector(1,0,0),ax))
Draft.rotate(newob,ang,axis=ax)
if ax == Vector(0,0,-1): ax = Vector(0,0,1)
elif hasattr(text,"rotation"):
if text.rotation:
Draft.rotate(newob,text.rotation)
if attrib:
attrot = rawValue(text,50)
if attrot:
Draft.rotate(newob,attrot)
newob.LabelText = val.split("\n")
if gui and draftui and dxfUseStandardSize:
fsize = draftui.fontsize
else:
fsize = float(hgt)*TEXTSCALING
if hasattr(text,"alignment"):
yv = ax.cross(xv)
if text.alignment in [1,2,3]:
sup = DraftVecUtils.scaleTo(yv,fsize/TEXTSCALING).negative()
#print(ax,sup)
pos = pos.add(sup)
elif text.alignment in [4,5,6]:
sup = DraftVecUtils.scaleTo(yv,fsize/(2*TEXTSCALING)).negative()
pos = pos.add(sup)
newob.Position = pos
if gui:
newob.ViewObject.FontSize = fsize
if hasattr(text,"alignment"):
if text.alignment in [2,5,8]:
newob.ViewObject.Justification = "Center"
elif text.alignment in [3,6,9]:
newob.ViewObject.Justification = "Right"
newob.ViewObject.DisplayMode = "World"
formatObject(newob,text)