forked from realthunder/fcad_pcb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkicad.py
1451 lines (1203 loc) · 47.8 KB
/
kicad.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
from __future__ import (absolute_import, division,
print_function, unicode_literals)
#from builtins import *
from future.utils import iteritems
from collections import defaultdict
from math import sqrt, atan2, degrees, sin, cos, radians, pi, hypot
import traceback
import FreeCAD
import FreeCADGui
import Part
from FreeCAD import Console,Vector,Placement,Rotation
import DraftGeomUtils,DraftVecUtils
import Path
import sys, os
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from kicad_parser import KicadPCB,SexpList
def updateGui():
try:
FreeCADGui.updateGui()
except Exception:
pass
class FCADLogger:
def __init__(self, tag):
self.tag = tag
self.levels = { 'error':0, 'warning':1, 'info':2,
'log':3, 'trace':4 }
def _isEnabledFor(self,level):
return FreeCAD.getLogLevel(self.tag) >= level
def isEnabledFor(self,level):
return self._isEnabledFor(self.levels[level])
def trace(self,msg):
if self._isEnabledFor(4):
FreeCAD.Console.PrintLog(msg+'\n')
updateGui()
def log(self,msg):
if self._isEnabledFor(3):
FreeCAD.Console.PrintLog(msg+'\n')
updateGui()
def info(self,msg):
if self._isEnabledFor(2):
FreeCAD.Console.PrintMessage(msg+'\n')
updateGui()
def warning(self,msg):
if self._isEnabledFor(1):
FreeCAD.Console.PrintWarning(msg+'\n')
updateGui()
def error(self,msg):
if self._isEnabledFor(0):
FreeCAD.Console.PrintError(msg+'\n')
updateGui()
logger = FCADLogger('fcad_pcb')
def getActiveDoc():
if FreeCAD.ActiveDocument is None:
return FreeCAD.newDocument('kicad_fcad')
return FreeCAD.ActiveDocument
def fitView():
try:
FreeCADGui.ActiveDocument.ActiveView.fitAll()
except Exception:
pass
def isZero(f):
return round(f,DraftGeomUtils.precision())==0
def makeColor(*color):
if len(color)==1:
if isinstance(color[0],basestring):
color = int(color[0],0)
else:
color = color[0]
r = float((color>>24)&0xFF)
g = float((color>>16)&0xFF)
b = float((color>>8)&0xFF)
else:
r,g,b = color
return (r/255.0,g/255.0,b/255.0)
def makeVect(l):
return Vector(l[0],-l[1],0)
def getAt(at):
v = makeVect(at)
return (v,0) if len(at)==2 else (v,at[2])
def product(v1,v2):
return Vector(v1.x*v2.x,v1.y*v2.y,v1.z*v2.z)
def make_rect(size):
return Part.makePolygon([product(size,Vector(*v))
for v in ((-0.5,-0.5),(0.5,-0.5),(0.5,0.5),(-0.5,0.5),(-0.5,-0.5))])
def make_circle(size):
return Part.Wire(Part.makeCircle(size.x*0.5))
def make_oval(size):
if size.x == size.y:
return make_circle(size)
if size.x < size.y:
r = size.x*0.5
size.y -= size.x
s = ((0,0.5),(-0.5,0.5),(-0.5,-0.5),(0,-0.5),(0.5,-0.5),(0.5,0.5))
a = (0,180,180,360)
else:
r = size.y*0.5
size.x -= size.y
s = ((-0.5,0),(-0.5,-0.5),(0.5,-0.5),(0.5,0),(0.5,0.5),(-0.5,0.5))
a = (90,270,-90,-270)
pts = [product(size,Vector(*v)) for v in s]
return Part.Wire([
Part.makeCircle(r,pts[0],Vector(0,0,1),a[0],a[1]),
Part.makeLine(pts[1],pts[2]),
Part.makeCircle(r,pts[3],Vector(0,0,1),a[2],a[3]),
Part.makeLine(pts[4],pts[5])])
def makeThickLine(p1,p2,width):
length = p1.distanceToPoint(p2)
line = make_oval(Vector(length+2*width,2*width))
p = p2.sub(p1)
a = -degrees(DraftVecUtils.angle(p))
line.translate(Vector(length*0.5))
line.rotate(Vector(),Vector(0,0,1),a)
line.translate(p1)
return line
def makeArc(center,start,angle):
p = start.sub(center)
r = p.Length
a = -degrees(DraftVecUtils.angle(p))
# NOTE: KiCAD pcb geometry runs in clockwise, while FreeCAD is CCW. So the
# resulting arc below is the reverse of what's specified in kicad_pcb
arc = Part.makeCircle(r,center,Vector(0,0,1),a-angle,a)
arc.reverse();
return arc
def findWires(edges):
try:
return [Part.Wire(e) for e in Part.sortEdges(edges)]
except AttributeError:
msg = 'Missing Part.sortEdges.'\
'You need newer FreeCAD (0.17 git 799c43d2)'
logger.error(msg)
raise AttributeError(msg)
def getFaceCompound(shape,wire=False):
objs = []
for f in shape.Faces:
selected = True
for v in f.Vertexes:
if not isZero(v.Z):
selected = False
break
if not selected:
continue
################################################################
## TODO: FreeCAD curve.normalAt is not implemented
################################################################
# for e in f.Edges:
# if isinstance(e.Curve,(Part.LineSegment,Part.Line)): continue
# if not isZero(e.normalAt(Vector()).dot(Vector(0,0,1))):
# selected = False
# break
# if not selected: continue
if not wire:
objs.append(f)
continue
for w in f.Wires:
objs.append(w)
if not objs:
raise ValueError('null shape')
return Part.makeCompound(objs)
def unpack(obj):
if not obj:
raise ValueError('null shape')
if isinstance(obj,(list,tuple)) and len(obj)==1:
return obj[0]
return obj
def getKicadPath():
if sys.platform != 'win32':
path='/usr/share/kicad/modules/packages3d'
if not os.path.isdir(path):
path = '/usr/local/share/kicad/modules/packages3d'
return path
import re
confpath = os.path.join(os.path.abspath(os.environ['APPDATA']),'kicad')
kicad_common = os.path.join(confpath,'kicad_common')
if not os.path.isfile(kicad_common):
logger.warning('cannot find kicad_common')
return None
with open(kicad_common,'rb') as f:
content = f.read()
match = re.search(r'^\s*KISYS3DMOD\s*=\s*([^\r\n]+)',content,re.MULTILINE)
if not match:
logger.warning('no KISYS3DMOD found')
return None
return match.group(1).rstrip(' ')
_model_cache = {}
def clearModelCache():
_model_cache = {}
def recomputeObj(obj):
obj.recompute()
obj.purgeTouched()
def loadModel(filename):
mtime = None
try:
mtime = os.path.getmtime(filename)
obj = _model_cache[filename]
if obj[2] == mtime:
logger.info('model cache hit');
return obj
else:
logger.info('model reload due to time stamp change');
except KeyError:
pass
except OSError:
return
import ImportGui
doc = getActiveDoc()
if not os.path.isfile(filename):
return
count = len(doc.Objects)
dobjs = []
try:
ImportGui.insert(filename,doc.Name)
dobjs = doc.Objects[count:]
obj = doc.addObject('Part::Compound','tmp')
obj.Links = dobjs
recomputeObj(obj)
dobjs = [obj]+dobjs
obj = (obj.Shape.copy(),obj.ViewObject.DiffuseColor,mtime)
_model_cache[filename] = obj
return obj
except Exception as ex:
logger.error('failed to load model: {}'.format(ex))
finally:
for o in dobjs:
doc.removeObject(o.Name)
class KicadFcad:
def __init__(self,filename=None,debug=False,**kwds):
self.prefix = ''
self.indent = ' '
self.make_sketch = False
self.sketch_use_draft = False
self.sketch_radius_precision = -1
self.work_plane = Part.makeCircle(1)
self.holes_cache = {}
self.active_doc_uuid = None
self.sketch_constraint = True
self.sketch_align_constraint = False
self.merge_holes = not debug
self.merge_pads = not debug
self.merge_vias = not debug
self.zone_merge_holes = not debug
self.add_feature = True
self.part_path = getKicadPath()
if filename is None:
filename = '/home/thunder/pwr.kicad_pcb'
if not os.path.isfile(filename):
raise ValueError("file not found");
self.filename = filename
self.colors = {
'board':makeColor("0x3A6629"),
'pad':{0:makeColor(204,204,204)},
'zone':{0:makeColor(0,80,0)},
'track':{0:makeColor(0,120,0)},
'copper':{0:makeColor(200,117,51)},
}
self.layer_type = 0
for key,value in iteritems(kwds):
if not hasattr(self,key):
raise ValueError('unknown parameter "{}"'.format(key))
setattr(self,key,value)
self.pcb = KicadPCB.load(self.filename)
# This will be override by setLayer. It's here just to make syntax
# checker happy
self.layer = 'Fu.C'
self.setLayer(self.layer_type)
def setLayer(self,layer):
try:
layer = int(layer)
except:
for layer_type in self.pcb.layers:
if self.pcb.layers[layer_type][0] == layer:
self.layer = layer
self.layer_type = int(layer_type)
return
raise KeyError('layer {} not found'.format(layer))
else:
if str(layer) not in self.pcb.layers:
raise KeyError('layer {} not found'.format(layer))
self.layer_type = layer
self.layer = self.pcb.layers[str(layer)][0]
def _log(self,msg,*arg,**kargs):
level = 'info'
if kargs:
if 'level' in kargs:
level = kargs['level']
if logger.isEnabledFor(level):
getattr(logger,level)('{}{}'.format(self.prefix,msg.format(*arg)))
def _pushLog(self,msg=None,*arg,**kargs):
if msg:
self._log(msg,*arg,**kargs)
if 'prefix' in kargs:
prefix = kargs['prefix']
if prefix is not None:
self.prefix = prefix
self.prefix += self.indent
def _popLog(self,msg=None,*arg,**kargs):
self.prefix = self.prefix[:-len(self.indent)]
if msg:
self._log(msg,*arg,**kargs)
def _makeLabel(self,obj,label):
if self.layer:
obj.Label = '{}#{}'.format(obj.Name,self.layer)
if label is not None:
obj.Label += '#{}'.format(label)
def _makeObject(self,otype,name,
label=None,links=None,shape=None):
doc = getActiveDoc()
obj = doc.addObject(otype,name)
self._makeLabel(obj,label)
if links is not None:
setattr(obj,links,shape)
for s in shape if isinstance(shape,(list,tuple)) else (shape,):
if hasattr(s,'ViewObject'):
s.ViewObject.Visibility = False
if hasattr(obj,'recompute'):
recomputeObj(obj)
return obj
def _makeSketch(self,objs,name,label=None):
if self.sketch_use_draft:
import Draft
getActiveDoc()
nobj = Draft.makeSketch(objs,name=name,autoconstraints=True,
delete=True,radiusPrecision=self.sketch_radius_precision)
self._makeLabel(nobj,label)
return nobj
from Sketcher import Constraint
StartPoint = 1
EndPoint = 2
doc = getActiveDoc()
nobj = doc.addObject("Sketcher::SketchObject", '{}_sketch'.format(name))
self._makeLabel(nobj,label)
nobj.ViewObject.Autoconstraints = False
radiuses = {}
constraints = []
def addRadiusConstraint(edge):
try:
if self.sketch_radius_precision<0:
return
if self.sketch_radius_precision==0:
constraints.append(Constraint('Radius',
nobj.GeometryCount-1, edge.Curve.Radius))
return
r = round(edge.Curve.Radius,self.sketch_radius_precision)
constraints.append(Constraint('Equal',
radiuses[r], nobj.GeometryCount-1))
except KeyError:
radiuses[r] = nobj.GeometryCount-1
constraints.append(Constraint('Radius',nobj.GeometryCount-1,r))
except AttributeError:
pass
for obj in objs if isinstance(objs,(list,tuple)) else (objs,):
if isinstance(obj,Part.Shape):
shape = obj
else:
shape = obj.Shape
norm = DraftGeomUtils.getNormal(shape)
if not self.sketch_constraint:
for wire in shape.Wires:
for edge in wire.OrderedEdges:
nobj.addGeometry(DraftGeomUtils.orientEdge(
edge,norm,make_arc=True))
continue
for wire in shape.Wires:
last_count = nobj.GeometryCount
edges = wire.OrderedEdges
for edge in edges:
nobj.addGeometry(DraftGeomUtils.orientEdge(
edge,norm,make_arc=True))
addRadiusConstraint(edge)
for i,g in enumerate(nobj.Geometry[last_count:]):
if edges[i].Closed:
continue
seg = last_count+i
if self.sketch_align_constraint:
if DraftGeomUtils.isAligned(g,"x"):
constraints.append(Constraint("Vertical",seg))
elif DraftGeomUtils.isAligned(g,"y"):
constraints.append(Constraint("Horizontal",seg))
if seg == nobj.GeometryCount-1:
if not wire.isClosed():
break
g2 = nobj.Geometry[last_count]
seg2 = last_count
else:
seg2 = seg+1
g2 = nobj.Geometry[seg2]
end1 = g.value(g.LastParameter)
start2 = g2.value(g2.FirstParameter)
if DraftVecUtils.equals(end1,start2) :
constraints.append(Constraint(
"Coincident",seg,EndPoint,seg2,StartPoint))
continue
end2 = g2.value(g2.LastParameter)
start1 = g.value(g.FirstParameter)
if DraftVecUtils.equals(end2,start1):
constraints.append(Constraint(
"Coincident",seg,StartPoint,seg2,EndPoint))
elif DraftVecUtils.equals(start1,start2):
constraints.append(Constraint(
"Coincident",seg,StartPoint,seg2,StartPoint))
elif DraftVecUtils.equals(end1,end2):
constraints.append(Constraint(
"Coincident",seg,EndPoint,seg2,EndPoint))
if obj.isDerivedFrom("Part::Feature"):
objs = [obj]
while objs:
obj = objs[0]
objs = objs[1:] + obj.OutList
doc.removeObject(obj.Name)
nobj.addConstraint(constraints)
recomputeObj(nobj)
return nobj
def _makeCompound(self,obj,name,label=None,fit_arcs=False,
fuse=False,add_feature=False,force=False):
obj = unpack(obj)
if not isinstance(obj,(list,tuple)):
if not force and (
not fuse or obj.TypeId=='Path::FeatureArea'):
return obj
obj = [obj]
if fuse:
return self._makeArea(obj,name,label=label,fit_arcs=fit_arcs)
if add_feature or self.add_feature:
return self._makeObject('Part::Compound',
'{}_combo'.format(name),label,'Links',obj)
obj = Part.makeCompound(obj)
recomputeObj(obj)
return obj
def _makeArea(self,obj,name,offset=0,op=0,fill=None,label=None,
force=False,fit_arcs=False,reorient=False):
if fill is None:
fill = 2
elif fill:
fill = 1
else:
fill = 0
if self.add_feature:
if not isinstance(obj,(list,tuple)):
obj = (obj,)
if not force and obj[0].TypeId == 'Path::FeatureArea' and (
obj[0].Operation == op or len(obj[0].Sources)==1) and \
obj[0].Fill == fill:
ret = obj[0]
if len(obj) > 1:
ret.Sources = list(ret.Sources) + list(obj[1:])
else:
ret = self._makeObject('Path::FeatureArea',
'{}_area'.format(name),label)
ret.Sources = obj
ret.Operation = op
ret.Fill = fill
ret.Offset = offset
ret.WorkPlane = self.work_plane
ret.FitArcs = fit_arcs
ret.Reorient = reorient
for o in obj:
o.ViewObject.Visibility = False
recomputeObj(ret)
else:
ret = Path.Area(Fill=fill,FitArcs=fit_arcs)
ret.setPlane(self.work_plane)
ret.add(obj,op=op)
if offset:
ret = ret.makeOffset(offset=offset)
else:
ret = ret.getShape()
return ret
def _makeWires(self,obj,name,offset=0,fill=False,label=None,fit_arcs=False):
if self.add_feature:
if self.make_sketch:
obj = self._makeSketch(obj,name,label)
elif isinstance(obj,Part.Shape):
obj = self._makeObject('Part::Feature', '{}_wire'.format(name),
label,'Shape',obj)
elif isinstance(obj,(list,tuple)):
objs = []
comp = []
for o in obj:
if isinstance(o,Part.Shape):
comp.append(o)
else:
objs.append(o)
if comp:
comp = Part.makeCompound(comp)
objs.append(self._makeObject('Part::Feature',
'{}_wire'.format(name),label,'Shape',comp))
obj = objs
if fill or offset:
return self._makeArea(obj,name,offset=offset,fill=fill,
fit_arcs=fit_arcs,label=label)
else:
return self._makeCompound(obj,name,label=label)
def _makeSolid(self,obj,name,height,label=None,fit_arcs=True):
obj = self._makeCompound(obj,name,label=label,
fuse=True,fit_arcs=fit_arcs)
if not self.add_feature:
return obj.extrude(Vector(0,0,height))
nobj = self._makeObject('Part::Extrusion',
'{}_solid'.format(name),label)
nobj.Base = obj
nobj.Dir = Vector(0,0,height)
obj.ViewObject.Visibility = False
recomputeObj(nobj)
return nobj
def _makeFuse(self,objs,name,label=None,force=False):
obj = unpack(objs)
if not isinstance(obj,(list,tuple)):
if not force:
return obj
obj = [obj]
name = '{}_fuse'.format(name)
if self.add_feature:
self._log('making fuse {}...',name)
obj = self._makeObject('Part::MultiFuse',name,label,'Shapes',obj)
self._log('fuse done')
return obj
solids = []
for o in obj:
solids += o.Solids;
if solids:
self._log('making fuse {}...',name)
obj = solids[0].multiFuse(solids[1:])
self._log('fuse done')
return obj
def _makeCut(self,base,tool,name,label=None):
base = self._makeFuse(base,name,label=label)
tool = self._makeFuse(tool,'drill',label=label)
name = '{}_drilled'.format(name)
self._log('making cut {}...',name)
if self.add_feature:
cut = self._makeObject('Part::Cut',name,label=label)
cut.Base = base
cut.Tool = tool
base.ViewObject.Visibility = False
tool.ViewObject.Visibility = False
recomputeObj(cut)
cut.ViewObject.ShapeColor = base.ViewObject.ShapeColor
else:
cut = base.cut(tool)
self._log('cut done')
return cut
def _place(self,obj,pos,angle=None):
if not self.add_feature:
if angle:
obj.rotate(Vector(),Vector(0,0,1),angle)
obj.translate(pos)
else:
r = Rotation(Vector(0,0,1),angle) if angle else Rotation()
obj.Placement = Placement(pos,r)
obj.purgeTouched()
def makeBoard(self,shape_type='solid',thickness=None,fit_arcs=True,
holes=True, minHoleSize=0,ovalHole=True,prefix=''):
edges = []
self._pushLog('making board...',prefix=prefix)
self._log('making {} lines',len(self.pcb.gr_line))
for l in self.pcb.gr_line:
if l.layer != 'Edge.Cuts':
continue
edges.append(Part.makeLine(makeVect(l.start),makeVect(l.end)))
self._log('making {} arcs',len(self.pcb.gr_arc))
for l in self.pcb.gr_arc:
if l.layer != 'Edge.Cuts':
continue
# for gr_arc, 'start' is actual the center, and 'end' is the start
edges.append(makeArc(makeVect(l.start),makeVect(l.end),l.angle))
if not edges:
self._popLog('no board edges found')
return
wires = findWires(edges)
if not thickness:
thickness = self.pcb.general.thickness
holes = self._cutHoles(None,holes,None,
minSize=minHoleSize,oval=ovalHole)
def _wire(fill=False):
obj = self._makeWires(wires,'board',fill=fill)
if not holes:
return obj
return self._makeArea((obj,holes),'board',
op=1,fill=fill,fit_arcs=fit_arcs)
def _face():
return _wire(True)
def _solid():
return self._makeSolid(_face(),'board',thickness,
fit_arcs = fit_arcs)
try:
func = locals()['_{}'.format(shape_type)]
except KeyError:
raise ValueError('invalid shape type: {}'.format(shape_type))
obj = func()
if self.add_feature:
obj.ViewObject.ShapeColor = self.colors['board']
self._popLog('board done')
fitView();
return obj
def makeHoles(self,shape_type='wire',minSize=0,maxSize=0,
oval=False,prefix='',offset=0.0,npth=0,thickness=None):
self._pushLog('making holes...',prefix=prefix)
holes = defaultdict(list)
ovals = defaultdict(list)
width=0
def _wire(obj,name,fill=False):
return self._makeWires(obj,name,fill=fill,label=width)
def _face(obj,name):
return _wire(obj,name,True)
def _solid(obj,name):
return self._makeWires(obj,name,fill=True,label=width,fit_arcs=True)
try:
func = locals()['_{}'.format(shape_type)]
except KeyError:
raise ValueError('invalid shape type: {}'.format(shape_type))
oval_count = 0
count = 0
skip_count = 0
for m in self.pcb.module:
m_at,m_angle = getAt(m.at)
for p in m.pad:
if 'drill' not in p:
continue
if npth:
if p[1]=='np_thru_hole':
if npth<0:
skip_count += 1
continue
elif npth>0:
skip_count += 1
continue
if p.drill.oval:
if not oval:
continue
size = Vector(p.drill[0],p.drill[1])
w = make_oval(size+Vector(offset,offset))
ovals[min(size.x,size.y)].append(w)
oval_count += 1
elif p.drill[0]>=minSize and \
(not maxSize or p.drill[0]<=maxSize):
w = make_circle(Vector(p.drill[0]+offset))
holes[p.drill[0]].append(w)
count += 1
else:
skip_count += 1
continue
at,angle = getAt(p.at)
angle -= m_angle;
if not isZero(angle):
w.rotate(Vector(),Vector(0,0,1),angle)
w.translate(at)
if m_angle:
w.rotate(Vector(),Vector(0,0,1),m_angle)
w.translate(m_at)
self._log('pad holes: {}, skipped: {}',count+skip_count,skip_count)
if oval:
self._log('oval holes: {}',oval_count)
if npth<=0:
skip_count = 0
for v in self.pcb.via:
if v.drill>=minSize and (not maxSize or v.drill<=maxSize):
w = make_circle(Vector(v.drill+offset))
holes[v.drill].append(w)
w.translate(makeVect(v.at))
else:
skip_count += 1
self._log('via holes: {}, skipped: {}',len(self.pcb.via),skip_count)
self._log('total holes added: {}',
count+oval_count+len(self.pcb.via)-skip_count)
if holes or ovals:
objs = []
if self.merge_holes:
for o in ovals.values():
objs += o
for o in holes.values():
objs += o
objs = func(objs,"holes")
else:
for r in ((ovals,'oval'),(holes,'hole')):
if not r[0]:
continue
for (width,rs) in iteritems(r[0]):
objs.append(func(rs,r[1]))
if not npth:
label=None
elif npth>0:
label='npth'
else:
label='th'
if shape_type == 'solid':
if not thickness:
thickness = self.pcb.general.thickness+0.02
pos = -0.01
else:
pos = 0.0
objs = self._makeSolid(objs,'holes',thickness,label=label)
self._place(objs,FreeCAD.Vector(0,0,pos))
else:
objs = self._makeCompound(objs,'holes',label=label)
self._popLog('holes done')
return objs
def _cutHoles(self,objs,holes,name,label=None,fit_arcs=False,
minSize=0,maxSize=0,oval=True,npth=0,offset=0.0):
if not holes:
return objs
if not isinstance(holes,(Part.Feature,Part.Shape)):
hit = False
if self.holes_cache is not None:
key = '{}.{}.{}.{}.{}'.format(
minSize,maxSize,oval,npth,offset)
doc = getActiveDoc();
if self.active_doc_uuid != doc.Uid:
self.holes_cache.clear()
self.active_doc_uuid = doc.Uid
try:
holes = self.holes_cache[key]
hit = True
self._log("fetch holes from cache")
except KeyError:
pass
if not hit:
self._pushLog()
holes = self.makeHoles(shape_type='wire',prefix=None,npth=npth,
minSize=minSize,maxSize=maxSize,oval=oval,offset=offset)
self._popLog()
if isinstance(self.holes_cache,dict):
self.holes_cache[key] = holes
if not objs:
return holes
objs = (self._makeCompound(objs,name,label=label),holes)
return self._makeArea(objs,name,op=1,label=label,fit_arcs=fit_arcs)
def makePads(self,shape_type='face',thickness=0.05,holes=False,
fit_arcs=True,prefix=''):
self._pushLog('making pads...',prefix=prefix)
def _wire(obj,name,label=None,fill=False):
return self._makeWires(obj,name,fill=fill,label=label)
def _face(obj,name,label=None):
return _wire(obj,name,label,True)
_solid = _face
try:
func = locals()['_{}'.format(shape_type)]
except KeyError:
raise ValueError('invalid shape type: {}'.format(shape_type))
layer_match = '*.{}'.format(self.layer.split('.')[-1])
objs = []
count = 0
skip_count = 0
for i,m in enumerate(self.pcb.module):
ref = ''
for t in m.fp_text:
if t[0] == 'reference':
ref = t[1]
break;
m_at,m_angle = getAt(m.at)
pads = []
count += len(m.pad)
for j,p in enumerate(m.pad):
if self.layer not in p.layers \
and layer_match not in p.layers \
and '*' not in p.layers:
skip_count+=1
continue
shape = p[2]
try:
make_shape = globals()['make_{}'.format(shape)]
except KeyError:
raise NotImplementedError(
'pad shape {} not implemented\n'.format(shape))
w = make_shape(Vector(*p.size))
at,angle = getAt(p.at)
angle -= m_angle;
if not isZero(angle):
w.rotate(Vector(),Vector(0,0,1),angle)
w.translate(at)
if not self.merge_pads:
pads.append(func(w,'pad',
'{}#{}#{}#{}'.format(i,j,p[0],ref)))
else:
pads.append(w)
if not pads:
continue
if not self.merge_pads:
obj = self._makeCompound(pads,'pads','{}#{}'.format(i,ref))
else:
obj = func(pads,'pads','{}#{}'.format(i,ref))
self._place(obj,m_at,m_angle)
objs.append(obj)
via_skip = 0
vias = []
for i,v in enumerate(self.pcb.via):
if self.layer not in v.layers:
via_skip += 1
continue
w = make_circle(Vector(v.size))
w.translate(makeVect(v.at))
if not self.merge_vias:
vias.append(func(w,'via','{}#{}'.format(i,v.size)))
else:
vias.append(w)
if vias:
if self.merge_vias:
objs.append(func(vias,'vias'))
else:
objs.append(self._makeCompound(vias,'vias'))
self._log('modules: {}',len(self.pcb.module))
self._log('pads: {}, skipped: {}',count,skip_count)
self._log('vias: {}, skipped: {}',len(self.pcb.via),via_skip)
self._log('total pads added: {}',
count-skip_count+len(self.pcb.via)-via_skip)
if objs:
objs = self._cutHoles(objs,holes,'pads',fit_arcs=fit_arcs)
if shape_type=='solid':
objs = self._makeSolid(objs,'pads', thickness,
fit_arcs = fit_arcs)
else:
objs = self._makeCompound(objs,'pads',
fuse=True,fit_arcs=fit_arcs)
self.setColor(objs,'pad')
self._popLog('pads done')
fitView();
return objs
def setColor(self,obj,otype):
if not self.add_feature:
return
try:
color = self.colors[otype][self.layer_type]
except KeyError:
color = self.colors[otype][0]
obj.ViewObject.ShapeColor = color
def makeTracks(self,shape_type='face',fit_arcs=True,
thickness=0.05,holes=False,prefix=''):
self._pushLog('making tracks...',prefix=prefix)
width = 0
def _line(edges,offset=0,fill=False):
wires = findWires(edges)
return self._makeWires(wires,'track',
offset=offset,fill=fill,label=width)
def _wire(edges,fill=False):
return _line(edges,width*0.5,fill)
def _face(edges):
return _wire(edges,True)