-
Notifications
You must be signed in to change notification settings - Fork 31
/
FlatCAMObj.py
1595 lines (1270 loc) · 55.1 KB
/
FlatCAMObj.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 cStringIO import StringIO
from PyQt4 import QtCore
from copy import copy
from ObjectUI import *
import FlatCAMApp
import inspect # TODO: For debugging only.
from camlib import *
from FlatCAMCommon import LoudDict
from FlatCAMDraw import FlatCAMDraw
from shapely.geometry.base import JOIN_STYLE
# Interrupts plotting process if FlatCAMObj has been deleted
class ObjectDeleted(Exception):
pass
########################################
## FlatCAMObj ##
########################################
class FlatCAMObj(QtCore.QObject):
"""
Base type of objects handled in FlatCAM. These become interactive
in the GUI, can be plotted, and their options can be modified
by the user in their respective forms.
"""
# Instance of the application to which these are related.
# The app should set this value.
app = None
def __init__(self, name):
"""
:param name: Name of the object given by the user.
:return: FlatCAMObj
"""
QtCore.QObject.__init__(self)
# View
self.ui = None
self.options = LoudDict(name=name)
self.options.set_change_callback(self.on_options_change)
self.form_fields = {}
self.kind = None # Override with proper name
# self.shapes = ShapeCollection(parent=self.app.plotcanvas.vispy_canvas.view.scene)
self.shapes = self.app.plotcanvas.new_shape_group()
self.item = None # Link with project view item
self.muted_ui = False
self.deleted = False
self._drawing_tolerance = 0.01
# assert isinstance(self.ui, ObjectUI)
# self.ui.name_entry.returnPressed.connect(self.on_name_activate)
# self.ui.offset_button.clicked.connect(self.on_offset_button_click)
# self.ui.scale_button.clicked.connect(self.on_scale_button_click)
def __del__(self):
pass
def from_dict(self, d):
"""
This supersedes ``from_dict`` in derived classes. Derived classes
must inherit from FlatCAMObj first, then from derivatives of Geometry.
``self.options`` is only updated, not overwritten. This ensures that
options set by the app do not vanish when reading the objects
from a project file.
"""
for attr in self.ser_attrs:
if attr == 'options':
self.options.update(d[attr])
else:
setattr(self, attr, d[attr])
def on_options_change(self, key):
# Update form on programmatically options change
self.set_form_item(key)
# Set object visibility
if key == 'plot':
self.visible = self.options['plot']
self.emit(QtCore.SIGNAL("optionChanged"), key)
def set_ui(self, ui):
self.ui = ui
self.form_fields = {"name": self.ui.name_entry}
assert isinstance(self.ui, ObjectUI)
self.ui.name_entry.returnPressed.connect(self.on_name_activate)
self.ui.offset_button.clicked.connect(self.on_offset_button_click)
self.ui.scale_button.clicked.connect(self.on_scale_button_click)
def __str__(self):
return "<FlatCAMObj({:12s}): {:20s}>".format(self.kind, self.options["name"])
def on_name_activate(self):
old_name = copy(self.options["name"])
new_name = self.ui.name_entry.get_value()
self.options["name"] = self.ui.name_entry.get_value()
self.app.info("Name changed from %s to %s" % (old_name, new_name))
def on_offset_button_click(self):
self.app.report_usage("obj_on_offset_button")
self.read_form()
vect = self.ui.offsetvector_entry.get_value()
self.offset(vect)
self.plot()
def on_scale_button_click(self):
self.app.report_usage("obj_on_scale_button")
self.read_form()
factor = self.ui.scale_entry.get_value()
self.scale(factor)
self.plot()
def to_form(self):
"""
Copies options to the UI form.
:return: None
"""
FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.to_form()")
for option in self.options:
try:
self.set_form_item(option)
except:
self.app.log.warning("Unexpected error:", sys.exc_info())
def read_form(self):
"""
Reads form into ``self.options``.
:return: None
:rtype: None
"""
FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.read_form()")
for option in self.options:
try:
self.read_form_item(option)
except:
self.app.log.warning("Unexpected error:", sys.exc_info())
def build_ui(self):
"""
Sets up the UI/form for this object. Show the UI
in the App.
:return: None
:rtype: None
"""
self.muted_ui = True
FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.build_ui()")
# Remove anything else in the box
# box_children = self.app.ui.notebook.selected_contents.get_children()
# for child in box_children:
# self.app.ui.notebook.selected_contents.remove(child)
# while self.app.ui.selected_layout.count():
# self.app.ui.selected_layout.takeAt(0)
# Put in the UI
# box_selected.pack_start(sw, True, True, 0)
# self.app.ui.notebook.selected_contents.add(self.ui)
# self.app.ui.selected_layout.addWidget(self.ui)
try:
self.app.ui.selected_scroll_area.takeWidget()
except:
self.app.log.debug("Nothing to remove")
self.app.ui.selected_scroll_area.setWidget(self.ui)
self.muted_ui = False
def set_form_item(self, option):
"""
Copies the specified option to the UI form.
:param option: Name of the option (Key in ``self.options``).
:type option: str
:return: None
"""
try:
self.form_fields[option].set_value(self.options[option])
except KeyError:
self.app.log.warn("Tried to set an option or field that does not exist: %s" % option)
def read_form_item(self, option):
"""
Reads the specified option from the UI form into ``self.options``.
:param option: Name of the option.
:type option: str
:return: None
"""
try:
self.options[option] = self.form_fields[option].get_value()
except KeyError:
self.app.log.warning("Failed to read option from field: %s" % option)
# #try read field only when option have equivalent in form_fields
# if option in self.form_fields:
# option_type=type(self.options[option])
# try:
# value=self.form_fields[option].get_value()
# #catch per option as it was ignored anyway, also when syntax error (probably uninitialized field),don't read either.
# except (KeyError,SyntaxError):
# self.app.log.warning("Failed to read option from field: %s" % option)
# else:
# self.app.log.warning("Form fied does not exists: %s" % option)
def plot(self):
"""
Plot this object (Extend this method to implement the actual plotting).
Call this in descendants before doing the plotting.
:return: Whether to continue plotting or not depending on the "plot" option.
:rtype: bool
"""
FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.plot()")
if self.deleted:
return False
self.clear()
return True
def serialize(self):
"""
Returns a representation of the object as a dictionary so
it can be later exported as JSON. Override this method.
:return: Dictionary representing the object
:rtype: dict
"""
return
def deserialize(self, obj_dict):
"""
Re-builds an object from its serialized version.
:param obj_dict: Dictionary representing a FlatCAMObj
:type obj_dict: dict
:return: None
"""
return
def add_shape(self, **kwargs):
if self.deleted:
raise ObjectDeleted()
else:
self.shapes.add(tolerance=self.drawing_tolerance, **kwargs)
@property
def visible(self):
return self.shapes.visible
@visible.setter
def visible(self, value):
self.shapes.visible = value
# Not all object types has annotations
try:
self.annotation.visible = value
except AttributeError:
pass
@property
def drawing_tolerance(self):
return self._drawing_tolerance if self.units == 'MM' or not self.units else self._drawing_tolerance / 25.4
@drawing_tolerance.setter
def drawing_tolerance(self, value):
self._drawing_tolerance = value if self.units == 'MM' or not self.units else value / 25.4
def clear(self, update=False):
self.shapes.clear(update)
# Not all object types has annotations
try:
self.annotation.clear(update)
except AttributeError:
pass
def delete(self):
# Free resources
del self.ui
del self.options
# Set flag
self.deleted = True
class FlatCAMGerber(FlatCAMObj, Gerber):
"""
Represents Gerber code.
"""
ui_type = GerberObjectUI
def __init__(self, name):
Gerber.__init__(self)
FlatCAMObj.__init__(self, name)
self.kind = "gerber"
# The 'name' is already in self.options from FlatCAMObj
# Automatically updates the UI
self.options.update({
"plot": True,
"multicolored": False,
"solid": False,
"isotooldia": 0.016,
"isopasses": 1,
"isooverlap": 0.15,
"combine_passes": True,
"ncctools": "1.0, 0.5",
"nccoverlap": 0.4,
"nccmargin": 1,
"cutouttooldia": 0.07,
"cutoutmargin": 0.2,
"cutoutgapsize": 0.15,
"gaps": "tb",
"noncoppermargin": 0.0,
"noncopperrounded": False,
"bboxmargin": 0.0,
"bboxrounded": False
})
# Attributes to be included in serialization
# Always append to it because it carries contents
# from predecessors.
self.ser_attrs += ['options', 'kind']
# assert isinstance(self.ui, GerberObjectUI)
# self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
# self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
# self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
# self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
# self.ui.generate_cutout_button.clicked.connect(self.on_generatecutout_button_click)
# self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
# self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
def set_ui(self, ui):
"""
Maps options with GUI inputs.
Connects GUI events to methods.
:param ui: GUI object.
:type ui: GerberObjectUI
:return: None
"""
FlatCAMObj.set_ui(self, ui)
FlatCAMApp.App.log.debug("FlatCAMGerber.set_ui()")
self.form_fields.update({
"plot": self.ui.plot_cb,
"multicolored": self.ui.multicolored_cb,
"solid": self.ui.solid_cb,
"isotooldia": self.ui.iso_tool_dia_entry,
"isopasses": self.ui.iso_width_entry,
"isooverlap": self.ui.iso_overlap_entry,
"combine_passes": self.ui.combine_passes_cb,
"ncctools": self.ui.ncc_tool_dia_entry,
"nccoverlap": self.ui.ncc_overlap_entry,
"nccmargin": self.ui.ncc_margin_entry,
"cutouttooldia": self.ui.cutout_tooldia_entry,
"cutoutmargin": self.ui.cutout_margin_entry,
"cutoutgapsize": self.ui.cutout_gap_entry,
"gaps": self.ui.gaps_radio,
"noncoppermargin": self.ui.noncopper_margin_entry,
"noncopperrounded": self.ui.noncopper_rounded_cb,
"bboxmargin": self.ui.bbmargin_entry,
"bboxrounded": self.ui.bbrounded_cb
})
# Fill form fields only on object create
self.to_form()
assert isinstance(self.ui, GerberObjectUI)
self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
self.ui.generate_ncc_button.clicked.connect(self.on_ncc_button_click)
self.ui.generate_cutout_button.clicked.connect(self.on_generatecutout_button_click)
self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
def on_generatenoncopper_button_click(self, *args):
self.app.report_usage("gerber_on_generatenoncopper_button")
self.read_form()
name = self.options["name"] + "_noncopper"
def geo_init(geo_obj, app_obj):
assert isinstance(geo_obj, FlatCAMGeometry)
bounding_box = self.solid_geometry.envelope.buffer(self.options["noncoppermargin"])
if not self.options["noncopperrounded"]:
bounding_box = bounding_box.envelope
non_copper = bounding_box.difference(self.solid_geometry)
geo_obj.solid_geometry = non_copper
# TODO: Check for None
self.app.new_object("geometry", name, geo_init)
def on_generatebb_button_click(self, *args):
self.app.report_usage("gerber_on_generatebb_button")
self.read_form()
name = self.options["name"] + "_bbox"
def geo_init(geo_obj, app_obj):
assert isinstance(geo_obj, FlatCAMGeometry)
# Bounding box with rounded corners
bounding_box = self.solid_geometry.envelope.buffer(self.options["bboxmargin"])
if not self.options["bboxrounded"]: # Remove rounded corners
bounding_box = bounding_box.envelope
geo_obj.solid_geometry = bounding_box
self.app.new_object("geometry", name, geo_init)
def on_generatecutout_button_click(self, *args):
self.app.report_usage("gerber_on_generatecutout_button")
self.read_form()
name = self.options["name"] + "_cutout"
def geo_init(geo_obj, app_obj):
margin = self.options["cutoutmargin"] + self.options["cutouttooldia"]/2
gap_size = self.options["cutoutgapsize"] + self.options["cutouttooldia"]
minx, miny, maxx, maxy = self.bounds()
minx -= margin
maxx += margin
miny -= margin
maxy += margin
midx = 0.5 * (minx + maxx)
midy = 0.5 * (miny + maxy)
hgap = 0.5 * gap_size
pts = [[midx - hgap, maxy],
[minx, maxy],
[minx, midy + hgap],
[minx, midy - hgap],
[minx, miny],
[midx - hgap, miny],
[midx + hgap, miny],
[maxx, miny],
[maxx, midy - hgap],
[maxx, midy + hgap],
[maxx, maxy],
[midx + hgap, maxy]]
cases = {"tb": [[pts[0], pts[1], pts[4], pts[5]],
[pts[6], pts[7], pts[10], pts[11]]],
"lr": [[pts[9], pts[10], pts[1], pts[2]],
[pts[3], pts[4], pts[7], pts[8]]],
"4": [[pts[0], pts[1], pts[2]],
[pts[3], pts[4], pts[5]],
[pts[6], pts[7], pts[8]],
[pts[9], pts[10], pts[11]]]}
cuts = cases[self.options['gaps']]
geo_obj.solid_geometry = cascaded_union([LineString(segment) for segment in cuts])
# TODO: Check for None
self.app.new_object("geometry", name, geo_init)
def on_iso_button_click(self, *args):
self.app.report_usage("gerber_on_iso_button")
self.read_form()
self.isolate()
def on_ncc_button_click(self, *args):
self.app.report_usage("gerber_on_ncc_button")
# Prepare parameters
try:
tools = [float(eval(dia)) for dia in self.ui.ncc_tool_dia_entry.get_value().split(",")]
except:
FlatCAMApp.App.log.error("At least one tool diameter needed")
return
over = self.ui.ncc_overlap_entry.get_value()
margin = self.ui.ncc_margin_entry.get_value()
if over is None or margin is None:
FlatCAMApp.App.log.error("Overlap and margin values needed")
return
print "non-copper clear button clicked", tools, over, margin
# Sort tools in descending order
tools.sort(reverse=True)
# Prepare non-copper polygons
bounding_box = self.solid_geometry.envelope.buffer(distance=margin, join_style=JOIN_STYLE.mitre)
empty = self.get_empty_area(bounding_box)
if type(empty) is Polygon:
empty = MultiPolygon([empty])
# Main procedure
def clear_non_copper():
# Already cleared area
cleared = MultiPolygon()
# Geometry object creating callback
def geo_init(geo_obj, app_obj):
geo_obj.options["cnctooldia"] = tool
geo_obj.solid_geometry = []
for p in area.geoms:
try:
cp = self.clear_polygon(p, tool, over)
geo_obj.solid_geometry.append(list(cp.get_objects()))
except:
FlatCAMApp.App.log.warning("Polygon is ommited")
# Generate area for each tool
offset = sum(tools)
for tool in tools:
# Get remaining tools offset
offset -= tool
# Area to clear
area = empty.buffer(-offset).difference(cleared)
# Transform area to MultiPolygon
if type(area) is Polygon:
area = MultiPolygon([area])
# Check if area not empty
if len(area.geoms) > 0:
# Overall cleared area
cleared = empty.buffer(-offset * (1 + over)).buffer(-tool / 2).buffer(tool / 2)
# Create geometry object
name = self.options["name"] + "_ncc_" + repr(tool) + "D"
self.app.new_object("geometry", name, geo_init)
else:
return
# Do job in background
proc = self.app.proc_container.new("Clearing non-copper areas.")
def job_thread(app_obj):
try:
clear_non_copper()
except Exception as e:
proc.done()
raise e
proc.done()
self.app.inform.emit("Clear non-copper areas started ...")
self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
def follow(self, outname=None):
"""
Creates a geometry object "following" the gerber paths.
:return: None
"""
default_name = self.options["name"] + "_follow"
follow_name = outname or default_name
def follow_init(follow_obj, app_obj):
# Propagate options
follow_obj.options["cnctooldia"] = self.options["isotooldia"]
follow_obj.solid_geometry = self.solid_geometry
app_obj.info("Follow geometry created: %s" % follow_obj.options["name"])
# TODO: Do something if this is None. Offer changing name?
self.app.new_object("geometry", follow_name, follow_init)
def isolate(self, dia=None, passes=None, overlap=None, outname=None, combine=None):
"""
Creates an isolation routing geometry object in the project.
:param dia: Tool diameter
:param passes: Number of tool widths to cut
:param overlap: Overlap between passes in fraction of tool diameter
:param outname: Base name of the output object
:return: None
"""
if dia is None:
dia = self.options["isotooldia"]
if passes is None:
passes = int(self.options["isopasses"])
if overlap is None:
overlap = self.options["isooverlap"]
if combine is None:
combine = self.options["combine_passes"]
else:
combine = bool(combine)
base_name = self.options["name"] + "_iso"
base_name = outname or base_name
def generate_envelope(offset, invert):
# isolation_geometry produces an envelope that is going on the left of the geometry
# (the copper features). To leave the least amount of burrs on the features
# the tool needs to travel on the right side of the features (this is called conventional milling)
# the first pass is the one cutting all of the features, so it needs to be reversed
# the other passes overlap preceding ones and cut the left over copper. It is better for them
# to cut on the right side of the left over copper i.e on the left side of the features.
geom = self.isolation_geometry(offset)
if invert:
if type(geom) is MultiPolygon:
pl = []
for p in geom:
pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
geom = MultiPolygon(pl)
elif type(geom) is Polygon:
geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
else:
raise "Unexpected Geometry"
return geom
if combine:
iso_name = base_name
# TODO: This is ugly. Create way to pass data into init function.
def iso_init(geo_obj, app_obj):
# Propagate options
geo_obj.options["cnctooldia"] = self.options["isotooldia"]
geo_obj.solid_geometry = []
for i in range(passes):
offset = (2 * i + 1) / 2.0 * dia - i * overlap * dia
geom = generate_envelope (offset, i == 0)
geo_obj.solid_geometry.append(geom)
app_obj.info("Isolation geometry created: %s" % geo_obj.options["name"])
# TODO: Do something if this is None. Offer changing name?
self.app.new_object("geometry", iso_name, iso_init)
else:
for i in range(passes):
offset = (2 * i + 1) / 2.0 * dia - i * overlap * dia
if passes > 1:
iso_name = base_name + str(i + 1)
else:
iso_name = base_name
# TODO: This is ugly. Create way to pass data into init function.
def iso_init(geo_obj, app_obj):
# Propagate options
geo_obj.options["cnctooldia"] = self.options["isotooldia"]
geo_obj.solid_geometry = generate_envelope (offset, i == 0)
app_obj.info("Isolation geometry created: %s" % geo_obj.options["name"])
# TODO: Do something if this is None. Offer changing name?
self.app.new_object("geometry", iso_name, iso_init)
def on_plot_cb_click(self, *args):
if self.muted_ui:
return
self.read_form_item('plot')
def on_solid_cb_click(self, *args):
if self.muted_ui:
return
self.read_form_item('solid')
self.plot()
def on_multicolored_cb_click(self, *args):
if self.muted_ui:
return
self.read_form_item('multicolored')
self.plot()
def convert_units(self, units):
"""
Converts the units of the object by scaling dimensions in all geometry
and options.
:param units: Units to which to convert the object: "IN" or "MM".
:type units: str
:return: None
:rtype: None
"""
factor = Gerber.convert_units(self, units)
self.options['isotooldia'] *= factor
self.options['cutoutmargin'] *= factor
self.options['cutoutgapsize'] *= factor
self.options['noncoppermargin'] *= factor
self.options['bboxmargin'] *= factor
def plot(self):
FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
# Does all the required setup and returns False
# if the 'ptint' option is set to False.
if not FlatCAMObj.plot(self):
return
geometry = self.solid_geometry
# Make sure geometry is iterable.
try:
_ = iter(geometry)
except TypeError:
geometry = [geometry]
def random_color():
color = np.random.rand(4)
color[3] = 1
return color
try:
if self.options["solid"]:
for poly in geometry:
self.add_shape(shape=poly, color='#006E20BF', face_color=random_color()
if self.options['multicolored'] else '#BBF268BF', visible=self.options['plot'])
else:
for poly in geometry:
self.add_shape(shape=poly, color=random_color() if self.options['multicolored'] else 'black',
visible=self.options['plot'])
self.shapes.redraw()
except (ObjectDeleted, AttributeError):
self.shapes.clear(update=True)
def serialize(self):
return {
"options": self.options,
"kind": self.kind
}
class FlatCAMExcellon(FlatCAMObj, Excellon):
"""
Represents Excellon/Drill code.
"""
ui_type = ExcellonObjectUI
def __init__(self, name):
Excellon.__init__(self)
FlatCAMObj.__init__(self, name)
self.kind = "excellon"
self.options.update({
"plot": True,
"solid": False,
"drillz": -0.1,
"travelz": 0.1,
"feedrate": 5.0,
# "toolselection": ""
"tooldia": 0.1,
"toolchange": False,
"toolchangez": 1.0,
"spindlespeed": None
})
# TODO: Document this.
self.tool_cbs = {}
# Attributes to be included in serialization
# Always append to it because it carries contents
# from predecessors.
self.ser_attrs += ['options', 'kind']
@staticmethod
def merge(exc_list, exc_final):
"""
Merge excellons in exc_list into exc_final.
Options are allways copied from source .
Tools are also merged, if name for tool is same and size differs, then as name is used next available number from both lists
if only one object is specified in exc_list then this acts as copy only
:param exc_list: List or one object of FlatCAMExcellon Objects to join.
:param exc_final: Destination FlatCAMExcellon object.
:return: None
"""
if type(exc_list) is not list:
exc_list_real= list()
exc_list_real.append(exc_list)
else:
exc_list_real=exc_list
for exc in exc_list_real:
# Expand lists
if type(exc) is list:
FlatCAMExcellon.merge(exc, exc_final)
# If not list, merge excellons
else:
# TODO: I realize forms does not save values into options , when object is deselected
# leave this here for future use
# this reinitialize options based on forms, all steps may not be necessary
# exc.app.collection.set_active(exc.options['name'])
# exc.to_form()
# exc.read_form()
for option in exc.options:
if option is not 'name':
try:
exc_final.options[option] = exc.options[option]
except:
exc.app.log.warning("Failed to copy option.",option)
#deep copy of all drills,to avoid any references
for drill in exc.drills:
point = Point(drill['point'].x,drill['point'].y)
exc_final.drills.append({"point": point, "tool": drill['tool']})
toolsrework=dict()
max_numeric_tool=0
for toolname in exc.tools.iterkeys():
numeric_tool=int(toolname)
if numeric_tool>max_numeric_tool:
max_numeric_tool=numeric_tool
toolsrework[exc.tools[toolname]['C']]=toolname
#exc_final as last because names from final tools will be used
for toolname in exc_final.tools.iterkeys():
numeric_tool=int(toolname)
if numeric_tool>max_numeric_tool:
max_numeric_tool=numeric_tool
toolsrework[exc_final.tools[toolname]['C']]=toolname
for toolvalues in toolsrework.iterkeys():
if toolsrework[toolvalues] in exc_final.tools:
if exc_final.tools[toolsrework[toolvalues]]!={"C": toolvalues}:
exc_final.tools[str(max_numeric_tool+1)]={"C": toolvalues}
else:
exc_final.tools[toolsrework[toolvalues]]={"C": toolvalues}
#this value was not co
exc_final.zeros=exc.zeros
exc_final.create_geometry()
def build_ui(self):
FlatCAMObj.build_ui(self)
# Populate tool list
n = len(self.tools)
self.ui.tools_table.setColumnCount(2)
self.ui.tools_table.setHorizontalHeaderLabels(['#', 'Diameter'])
self.ui.tools_table.setRowCount(n)
self.ui.tools_table.setSortingEnabled(False)
i = 0
for tool in self.tools:
id = QtGui.QTableWidgetItem(tool)
id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
self.ui.tools_table.setItem(i, 0, id) # Tool name/id
dia = QtGui.QTableWidgetItem(str(self.tools[tool]['C']))
dia.setFlags(QtCore.Qt.ItemIsEnabled)
self.ui.tools_table.setItem(i, 1, dia) # Diameter
i += 1
# sort the tool diameter column
self.ui.tools_table.sortItems(1)
# all the tools are selected by default
self.ui.tools_table.selectColumn(0)
self.ui.tools_table.resizeColumnsToContents()
self.ui.tools_table.resizeRowsToContents()
self.ui.tools_table.horizontalHeader().setStretchLastSection(True)
self.ui.tools_table.verticalHeader().hide()
self.ui.tools_table.setSortingEnabled(True)
def set_ui(self, ui):
"""
Configures the user interface for this object.
Connects options to form fields.
:param ui: User interface object.
:type ui: ExcellonObjectUI
:return: None
"""
FlatCAMObj.set_ui(self, ui)
FlatCAMApp.App.log.debug("FlatCAMExcellon.set_ui()")
self.form_fields.update({
"plot": self.ui.plot_cb,
"solid": self.ui.solid_cb,
"drillz": self.ui.cutz_entry,
"travelz": self.ui.travelz_entry,
"feedrate": self.ui.feedrate_entry,
"tooldia": self.ui.tooldia_entry,
"toolchange": self.ui.toolchange_cb,
"toolchangez": self.ui.toolchangez_entry,
"spindlespeed": self.ui.spindlespeed_entry
})
# Fill form fields
self.to_form()
assert isinstance(self.ui, ExcellonObjectUI), \
"Expected a ExcellonObjectUI, got %s" % type(self.ui)
self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
self.ui.generate_cnc_button.clicked.connect(self.on_create_cncjob_button_click)
self.ui.generate_milling_button.clicked.connect(self.on_generate_milling_button_click)
def get_selected_tools_list(self):
"""
Returns the keys to the self.tools dictionary corresponding
to the selections on the tool list in the GUI.
:return: List of tools.
:rtype: list
"""
return [str(x.text()) for x in self.ui.tools_table.selectedItems()]
def generate_milling(self, tools=None, outname=None, tooldia=None):
"""
Note: This method is a good template for generic operations as
it takes it's options from parameters or otherwise from the
object's options and returns a success, msg tuple as feedback
for shell operations.
:return: Success/failure condition tuple (bool, str).
:rtype: tuple
"""
# Get the tools from the list. These are keys
# to self.tools
if tools is None:
tools = self.get_selected_tools_list()
if outname is None:
outname = self.options["name"] + "_mill"
if tooldia is None:
tooldia = self.options["tooldia"]
if len(tools) == 0:
self.app.inform.emit("Please select one or more tools from the list and try again.")
return False, "Error: No tools."
for tool in tools:
if self.tools[tool]["C"] < tooldia:
self.app.inform.emit("[warning] Milling tool is larger than hole size. Cancelled.")
return False, "Error: Milling tool is larger than hole."
def geo_init(geo_obj, app_obj):
assert isinstance(geo_obj, FlatCAMGeometry), \
"Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
app_obj.progress.emit(20)
geo_obj.solid_geometry = []
for hole in self.drills:
if hole['tool'] in tools:
geo_obj.solid_geometry.append(
Point(hole['point']).buffer(self.tools[hole['tool']]["C"] / 2 -
tooldia / 2).exterior
)
def geo_thread(app_obj):
app_obj.new_object("geometry", outname, geo_init)
app_obj.progress.emit(100)
# Create a promise with the new name
self.app.collection.promise(outname)
# Send to worker
self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
return True, ""
def on_generate_milling_button_click(self, *args):
self.app.report_usage("excellon_on_create_milling_button")
self.read_form()
self.generate_milling()
def on_create_cncjob_button_click(self, *args):
self.app.report_usage("excellon_on_create_cncjob_button")
self.read_form()
# Get the tools from the list
tools = self.get_selected_tools_list()
if len(tools) == 0:
self.app.inform.emit("Please select one or more tools from the list and try again.")
return
job_name = self.options["name"] + "_cnc"
# Object initialization function for app.new_object()
def job_init(job_obj, app_obj):
assert isinstance(job_obj, FlatCAMCNCjob), \