FlatCAMGerber.py 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ##########################################################
  8. # ##########################################################
  9. # File modified by: Marius Stanciu #
  10. # ##########################################################
  11. from shapely.geometry import Point, Polygon, MultiPolygon, MultiLineString, LineString, LinearRing
  12. from shapely.ops import cascaded_union
  13. from appParsers.ParseGerber import Gerber
  14. from appObjects.FlatCAMObj import *
  15. import math
  16. import numpy as np
  17. from copy import deepcopy
  18. import gettext
  19. import appTranslation as fcTranslate
  20. import builtins
  21. fcTranslate.apply_language('strings')
  22. if '_' not in builtins.__dict__:
  23. _ = gettext.gettext
  24. class GerberObject(FlatCAMObj, Gerber):
  25. """
  26. Represents Gerber code.
  27. """
  28. optionChanged = QtCore.pyqtSignal(str)
  29. replotApertures = QtCore.pyqtSignal()
  30. do_buffer_signal = QtCore.pyqtSignal()
  31. ui_type = GerberObjectUI
  32. @staticmethod
  33. def merge(grb_list, grb_final):
  34. """
  35. Merges the geometry of objects in geo_list into
  36. the geometry of geo_final.
  37. :param grb_list: List of GerberObject Objects to join.
  38. :param grb_final: Destination GeometryObject object.
  39. :return: None
  40. """
  41. if grb_final.solid_geometry is None:
  42. grb_final.solid_geometry = []
  43. grb_final.follow_geometry = []
  44. if not grb_final.apertures:
  45. grb_final.apertures = {}
  46. if type(grb_final.solid_geometry) is not list:
  47. grb_final.solid_geometry = [grb_final.solid_geometry]
  48. grb_final.follow_geometry = [grb_final.follow_geometry]
  49. for grb in grb_list:
  50. # Expand lists
  51. if type(grb) is list:
  52. GerberObject.merge(grb_list=grb, grb_final=grb_final)
  53. else: # If not list, just append
  54. for option in grb.options:
  55. if option != 'name':
  56. try:
  57. grb_final.options[option] = grb.options[option]
  58. except KeyError:
  59. log.warning("Failed to copy option.", option)
  60. try:
  61. for geos in grb.solid_geometry:
  62. grb_final.solid_geometry.append(geos)
  63. grb_final.follow_geometry.append(geos)
  64. except TypeError:
  65. grb_final.solid_geometry.append(grb.solid_geometry)
  66. grb_final.follow_geometry.append(grb.solid_geometry)
  67. for ap in grb.apertures:
  68. if ap not in grb_final.apertures:
  69. grb_final.apertures[ap] = grb.apertures[ap]
  70. else:
  71. # create a list of integers out of the grb.apertures keys and find the max of that value
  72. # then, the aperture duplicate is assigned an id value incremented with 1,
  73. # and finally made string because the apertures dict keys are strings
  74. max_ap = str(max([int(k) for k in grb_final.apertures.keys()]) + 1)
  75. grb_final.apertures[max_ap] = {}
  76. grb_final.apertures[max_ap]['geometry'] = []
  77. for k, v in grb.apertures[ap].items():
  78. grb_final.apertures[max_ap][k] = deepcopy(v)
  79. grb_final.solid_geometry = MultiPolygon(grb_final.solid_geometry)
  80. grb_final.follow_geometry = MultiPolygon(grb_final.follow_geometry)
  81. def __init__(self, name):
  82. self.decimals = self.app.decimals
  83. self.circle_steps = int(self.app.defaults["gerber_circle_steps"])
  84. Gerber.__init__(self, steps_per_circle=self.circle_steps)
  85. FlatCAMObj.__init__(self, name)
  86. self.kind = "gerber"
  87. # The 'name' is already in self.options from FlatCAMObj
  88. # Automatically updates the UI
  89. self.options.update({
  90. "plot": True,
  91. "multicolored": False,
  92. "solid": False,
  93. "noncoppermargin": 0.0,
  94. "noncopperrounded": False,
  95. "bboxmargin": 0.0,
  96. "bboxrounded": False,
  97. "aperture_display": False,
  98. "follow": False,
  99. "milling_type": 'cl',
  100. })
  101. # type of isolation: 0 = exteriors, 1 = interiors, 2 = complete isolation (both interiors and exteriors)
  102. self.iso_type = 2
  103. self.multigeo = False
  104. self.follow = False
  105. self.apertures_row = 0
  106. # store the source file here
  107. self.source_file = ""
  108. # list of rows with apertures plotted
  109. self.marked_rows = []
  110. # Mouse events
  111. self.mr = None
  112. self.mm = None
  113. self.mp = None
  114. # dict to store the polygons selected for isolation; key is the shape added to be plotted and value is the poly
  115. self.poly_dict = {}
  116. # store the status of grid snapping
  117. self.grid_status_memory = None
  118. self.units_found = self.app.defaults['units']
  119. self.fill_color = self.app.defaults['gerber_plot_fill']
  120. self.outline_color = self.app.defaults['gerber_plot_line']
  121. self.alpha_level = 'bf'
  122. # keep track if the UI is built so we don't have to build it every time
  123. self.ui_build = False
  124. # build only once the aperture storage (takes time)
  125. self.build_aperture_storage = False
  126. # Attributes to be included in serialization
  127. # Always append to it because it carries contents
  128. # from predecessors.
  129. self.ser_attrs += ['options', 'kind', 'fill_color', 'outline_color', 'alpha_level']
  130. def set_ui(self, ui):
  131. """
  132. Maps options with GUI inputs.
  133. Connects GUI events to methods.
  134. :param ui: GUI object.
  135. :type ui: GerberObjectUI
  136. :return: None
  137. """
  138. FlatCAMObj.set_ui(self, ui)
  139. log.debug("GerberObject.set_ui()")
  140. self.units = self.app.defaults['units'].upper()
  141. self.replotApertures.connect(self.on_mark_cb_click_table)
  142. self.form_fields.update({
  143. "plot": self.ui.plot_cb,
  144. "multicolored": self.ui.multicolored_cb,
  145. "solid": self.ui.solid_cb,
  146. "noncoppermargin": self.ui.noncopper_margin_entry,
  147. "noncopperrounded": self.ui.noncopper_rounded_cb,
  148. "bboxmargin": self.ui.bbmargin_entry,
  149. "bboxrounded": self.ui.bbrounded_cb,
  150. "aperture_display": self.ui.aperture_table_visibility_cb,
  151. "follow": self.ui.follow_cb
  152. })
  153. # Fill form fields only on object create
  154. self.to_form()
  155. assert isinstance(self.ui, GerberObjectUI), \
  156. "Expected a GerberObjectUI, got %s" % type(self.ui)
  157. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  158. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  159. self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  160. # Editor
  161. self.ui.editor_button.clicked.connect(lambda: self.app.object2editor())
  162. # Tools
  163. self.ui.iso_button.clicked.connect(self.app.isolation_tool.run)
  164. self.ui.generate_ncc_button.clicked.connect(self.app.ncclear_tool.run)
  165. self.ui.generate_cutout_button.clicked.connect(self.app.cutout_tool.run)
  166. self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  167. self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  168. self.ui.aperture_table_visibility_cb.stateChanged.connect(self.on_aperture_table_visibility_change)
  169. self.ui.follow_cb.stateChanged.connect(self.on_follow_cb_click)
  170. self.do_buffer_signal.connect(self.on_generate_buffer)
  171. # Show/Hide Advanced Options
  172. if self.app.defaults["global_app_level"] == 'b':
  173. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  174. self.ui.apertures_table_label.hide()
  175. self.ui.aperture_table_visibility_cb.hide()
  176. self.ui.follow_cb.hide()
  177. else:
  178. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  179. if self.app.defaults["gerber_buffering"] == 'no':
  180. self.ui.create_buffer_button.show()
  181. try:
  182. self.ui.create_buffer_button.clicked.disconnect(self.on_generate_buffer)
  183. except TypeError:
  184. pass
  185. self.ui.create_buffer_button.clicked.connect(self.on_generate_buffer)
  186. else:
  187. self.ui.create_buffer_button.hide()
  188. # set initial state of the aperture table and associated widgets
  189. self.on_aperture_table_visibility_change()
  190. self.build_ui()
  191. self.units_found = self.app.defaults['units']
  192. def build_ui(self):
  193. FlatCAMObj.build_ui(self)
  194. if self.ui.aperture_table_visibility_cb.get_value() and self.ui_build is False:
  195. self.ui_build = True
  196. try:
  197. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  198. self.ui.apertures_table.itemChanged.disconnect()
  199. except (TypeError, AttributeError):
  200. pass
  201. self.apertures_row = 0
  202. aper_no = self.apertures_row + 1
  203. sort = []
  204. for k, v in list(self.apertures.items()):
  205. sort.append(int(k))
  206. sorted_apertures = sorted(sort)
  207. n = len(sorted_apertures)
  208. self.ui.apertures_table.setRowCount(n)
  209. for ap_code in sorted_apertures:
  210. ap_code = str(ap_code)
  211. ap_id_item = QtWidgets.QTableWidgetItem('%d' % int(self.apertures_row + 1))
  212. ap_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  213. self.ui.apertures_table.setItem(self.apertures_row, 0, ap_id_item) # Tool name/id
  214. ap_code_item = QtWidgets.QTableWidgetItem(ap_code)
  215. ap_code_item.setFlags(QtCore.Qt.ItemIsEnabled)
  216. ap_type_item = QtWidgets.QTableWidgetItem(str(self.apertures[ap_code]['type']))
  217. ap_type_item.setFlags(QtCore.Qt.ItemIsEnabled)
  218. if str(self.apertures[ap_code]['type']) == 'R' or str(self.apertures[ap_code]['type']) == 'O':
  219. ap_dim_item = QtWidgets.QTableWidgetItem(
  220. '%.*f, %.*f' % (self.decimals, self.apertures[ap_code]['width'],
  221. self.decimals, self.apertures[ap_code]['height']
  222. )
  223. )
  224. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  225. elif str(self.apertures[ap_code]['type']) == 'P':
  226. ap_dim_item = QtWidgets.QTableWidgetItem(
  227. '%.*f, %.*f' % (self.decimals, self.apertures[ap_code]['diam'],
  228. self.decimals, self.apertures[ap_code]['nVertices'])
  229. )
  230. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  231. else:
  232. ap_dim_item = QtWidgets.QTableWidgetItem('')
  233. ap_dim_item.setFlags(QtCore.Qt.ItemIsEnabled)
  234. try:
  235. if self.apertures[ap_code]['size'] is not None:
  236. ap_size_item = QtWidgets.QTableWidgetItem(
  237. '%.*f' % (self.decimals, float(self.apertures[ap_code]['size'])))
  238. else:
  239. ap_size_item = QtWidgets.QTableWidgetItem('')
  240. except KeyError:
  241. ap_size_item = QtWidgets.QTableWidgetItem('')
  242. ap_size_item.setFlags(QtCore.Qt.ItemIsEnabled)
  243. mark_item = FCCheckBox()
  244. mark_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  245. # if self.ui.aperture_table_visibility_cb.isChecked():
  246. # mark_item.setChecked(True)
  247. self.ui.apertures_table.setItem(self.apertures_row, 1, ap_code_item) # Aperture Code
  248. self.ui.apertures_table.setItem(self.apertures_row, 2, ap_type_item) # Aperture Type
  249. self.ui.apertures_table.setItem(self.apertures_row, 3, ap_size_item) # Aperture Dimensions
  250. self.ui.apertures_table.setItem(self.apertures_row, 4, ap_dim_item) # Aperture Dimensions
  251. empty_plot_item = QtWidgets.QTableWidgetItem('')
  252. empty_plot_item.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  253. self.ui.apertures_table.setItem(self.apertures_row, 5, empty_plot_item)
  254. self.ui.apertures_table.setCellWidget(self.apertures_row, 5, mark_item)
  255. self.apertures_row += 1
  256. self.ui.apertures_table.selectColumn(0)
  257. self.ui.apertures_table.resizeColumnsToContents()
  258. self.ui.apertures_table.resizeRowsToContents()
  259. vertical_header = self.ui.apertures_table.verticalHeader()
  260. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  261. vertical_header.hide()
  262. self.ui.apertures_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  263. horizontal_header = self.ui.apertures_table.horizontalHeader()
  264. horizontal_header.setMinimumSectionSize(10)
  265. horizontal_header.setDefaultSectionSize(70)
  266. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  267. horizontal_header.resizeSection(0, 27)
  268. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
  269. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  270. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  271. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Stretch)
  272. horizontal_header.setSectionResizeMode(5, QtWidgets.QHeaderView.Fixed)
  273. horizontal_header.resizeSection(5, 17)
  274. self.ui.apertures_table.setColumnWidth(5, 17)
  275. self.ui.apertures_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  276. self.ui.apertures_table.setSortingEnabled(False)
  277. self.ui.apertures_table.setMinimumHeight(self.ui.apertures_table.getHeight())
  278. self.ui.apertures_table.setMaximumHeight(self.ui.apertures_table.getHeight())
  279. # update the 'mark' checkboxes state according with what is stored in the self.marked_rows list
  280. if self.marked_rows:
  281. for row in range(self.ui.apertures_table.rowCount()):
  282. try:
  283. self.ui.apertures_table.cellWidget(row, 5).set_value(self.marked_rows[row])
  284. except IndexError:
  285. pass
  286. self.ui_connect()
  287. def ui_connect(self):
  288. for row in range(self.ui.apertures_table.rowCount()):
  289. try:
  290. self.ui.apertures_table.cellWidget(row, 5).clicked.disconnect(self.on_mark_cb_click_table)
  291. except (TypeError, AttributeError):
  292. pass
  293. self.ui.apertures_table.cellWidget(row, 5).clicked.connect(self.on_mark_cb_click_table)
  294. try:
  295. self.ui.mark_all_cb.clicked.disconnect(self.on_mark_all_click)
  296. except (TypeError, AttributeError):
  297. pass
  298. self.ui.mark_all_cb.clicked.connect(self.on_mark_all_click)
  299. def ui_disconnect(self):
  300. for row in range(self.ui.apertures_table.rowCount()):
  301. try:
  302. self.ui.apertures_table.cellWidget(row, 5).clicked.disconnect()
  303. except (TypeError, AttributeError):
  304. pass
  305. try:
  306. self.ui.mark_all_cb.clicked.disconnect(self.on_mark_all_click)
  307. except (TypeError, AttributeError):
  308. pass
  309. @staticmethod
  310. def buffer_handler(geo):
  311. new_geo = geo
  312. if isinstance(new_geo, list):
  313. new_geo = MultiPolygon(new_geo)
  314. new_geo = new_geo.buffer(0.0000001)
  315. new_geo = new_geo.buffer(-0.0000001)
  316. return new_geo
  317. def on_generate_buffer(self):
  318. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Buffering solid geometry"))
  319. def buffer_task():
  320. with self.app.proc_container.new('%s...' % _("Buffering")):
  321. output = self.app.pool.apply_async(self.buffer_handler, args=([self.solid_geometry]))
  322. self.solid_geometry = output.get()
  323. self.app.inform.emit('[success] %s.' % _("Done"))
  324. self.plot_single_object.emit()
  325. self.app.worker_task.emit({'fcn': buffer_task, 'params': []})
  326. def on_generatenoncopper_button_click(self, *args):
  327. self.app.defaults.report_usage("gerber_on_generatenoncopper_button")
  328. self.read_form()
  329. name = self.options["name"] + "_noncopper"
  330. def geo_init(geo_obj, app_obj):
  331. assert geo_obj.kind == 'geometry', "Expected a Geometry object got %s" % type(geo_obj)
  332. if isinstance(self.solid_geometry, list):
  333. try:
  334. self.solid_geometry = MultiPolygon(self.solid_geometry)
  335. except Exception:
  336. self.solid_geometry = cascaded_union(self.solid_geometry)
  337. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["noncoppermargin"]))
  338. if not self.options["noncopperrounded"]:
  339. bounding_box = bounding_box.envelope
  340. non_copper = bounding_box.difference(self.solid_geometry)
  341. if non_copper is None or non_copper.is_empty:
  342. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Operation could not be done."))
  343. return "fail"
  344. geo_obj.solid_geometry = non_copper
  345. self.app.app_obj.new_object("geometry", name, geo_init)
  346. def on_generatebb_button_click(self, *args):
  347. self.app.defaults.report_usage("gerber_on_generatebb_button")
  348. self.read_form()
  349. name = self.options["name"] + "_bbox"
  350. def geo_init(geo_obj, app_obj):
  351. assert geo_obj.kind == 'geometry', "Expected a Geometry object got %s" % type(geo_obj)
  352. if isinstance(self.solid_geometry, list):
  353. try:
  354. self.solid_geometry = MultiPolygon(self.solid_geometry)
  355. except Exception:
  356. self.solid_geometry = cascaded_union(self.solid_geometry)
  357. # Bounding box with rounded corners
  358. bounding_box = self.solid_geometry.envelope.buffer(float(self.options["bboxmargin"]))
  359. if not self.options["bboxrounded"]: # Remove rounded corners
  360. bounding_box = bounding_box.envelope
  361. if bounding_box is None or bounding_box.is_empty:
  362. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Operation could not be done."))
  363. return "fail"
  364. geo_obj.solid_geometry = bounding_box
  365. self.app.app_obj.new_object("geometry", name, geo_init)
  366. def isolate(self, iso_type=None, geometry=None, dia=None, passes=None, overlap=None, outname=None, combine=None,
  367. milling_type=None, follow=None, plot=True):
  368. """
  369. Creates an isolation routing geometry object in the project.
  370. :param iso_type: type of isolation to be done: 0 = exteriors, 1 = interiors and 2 = both
  371. :param geometry: specific geometry to isolate
  372. :param dia: Tool diameter
  373. :param passes: Number of tool widths to cut
  374. :param overlap: Overlap between passes in fraction of tool diameter
  375. :param outname: Base name of the output object
  376. :param combine: Boolean: if to combine passes in one resulting object in case of multiple passes
  377. :param milling_type: type of milling: conventional or climbing
  378. :param follow: Boolean: if to generate a 'follow' geometry
  379. :param plot: Boolean: if to plot the resulting geometry object
  380. :return: None
  381. """
  382. if geometry is None:
  383. work_geo = self.follow_geometry if follow is True else self.solid_geometry
  384. else:
  385. work_geo = geometry
  386. if dia is None:
  387. dia = float(self.app.defaults["tools_iso_tooldia"])
  388. if passes is None:
  389. passes = int(self.app.defaults["tools_iso_passes"])
  390. if overlap is None:
  391. overlap = float(self.app.defaults["tools_iso_overlap"])
  392. overlap /= 100.0
  393. combine = self.app.defaults["tools_iso_combine_passes"] if combine is None else bool(combine)
  394. if milling_type is None:
  395. milling_type = self.app.defaults["tools_iso_milling_type"]
  396. if iso_type is None:
  397. iso_t = 2
  398. else:
  399. iso_t = iso_type
  400. base_name = self.options["name"]
  401. if combine:
  402. if outname is None:
  403. if self.iso_type == 0:
  404. iso_name = base_name + "_ext_iso"
  405. elif self.iso_type == 1:
  406. iso_name = base_name + "_int_iso"
  407. else:
  408. iso_name = base_name + "_iso"
  409. else:
  410. iso_name = outname
  411. def iso_init(geo_obj, app_obj):
  412. # Propagate options
  413. geo_obj.options["cnctooldia"] = str(dia)
  414. geo_obj.tool_type = self.app.defaults["tools_iso_tool_type"]
  415. geo_obj.solid_geometry = []
  416. # transfer the Cut Z and Vtip and VAngle values in case that we use the V-Shape tool in Gerber UI
  417. if geo_obj.tool_type.lower() == 'v':
  418. new_cutz = self.app.defaults["tools_iso_tool_cutz"]
  419. new_vtipdia = self.app.defaults["tools_iso_tool_vtipdia"]
  420. new_vtipangle = self.app.defaults["tools_iso_tool_vtipangle"]
  421. tool_type = 'V'
  422. else:
  423. new_cutz = self.app.defaults['geometry_cutz']
  424. new_vtipdia = self.app.defaults['geometry_vtipdia']
  425. new_vtipangle = self.app.defaults['geometry_vtipangle']
  426. tool_type = 'C1'
  427. # store here the default data for Geometry Data
  428. default_data = {}
  429. default_data.update({
  430. "name": iso_name,
  431. "plot": self.app.defaults['geometry_plot'],
  432. "cutz": new_cutz,
  433. "vtipdia": new_vtipdia,
  434. "vtipangle": new_vtipangle,
  435. "travelz": self.app.defaults['geometry_travelz'],
  436. "feedrate": self.app.defaults['geometry_feedrate'],
  437. "feedrate_z": self.app.defaults['geometry_feedrate_z'],
  438. "feedrate_rapid": self.app.defaults['geometry_feedrate_rapid'],
  439. "dwell": self.app.defaults['geometry_dwell'],
  440. "dwelltime": self.app.defaults['geometry_dwelltime'],
  441. "multidepth": self.app.defaults['geometry_multidepth'],
  442. "ppname_g": self.app.defaults['geometry_ppname_g'],
  443. "depthperpass": self.app.defaults['geometry_depthperpass'],
  444. "extracut": self.app.defaults['geometry_extracut'],
  445. "extracut_length": self.app.defaults['geometry_extracut_length'],
  446. "toolchange": self.app.defaults['geometry_toolchange'],
  447. "toolchangez": self.app.defaults['geometry_toolchangez'],
  448. "endz": self.app.defaults['geometry_endz'],
  449. "spindlespeed": self.app.defaults['geometry_spindlespeed'],
  450. "toolchangexy": self.app.defaults['geometry_toolchangexy'],
  451. "startz": self.app.defaults['geometry_startz']
  452. })
  453. geo_obj.tools = {}
  454. geo_obj.tools['1'] = {}
  455. geo_obj.tools.update({
  456. '1': {
  457. 'tooldia': dia,
  458. 'offset': 'Path',
  459. 'offset_value': 0.0,
  460. 'type': _('Rough'),
  461. 'tool_type': tool_type,
  462. 'data': default_data,
  463. 'solid_geometry': geo_obj.solid_geometry
  464. }
  465. })
  466. for nr_pass in range(passes):
  467. iso_offset = dia * ((2 * nr_pass + 1) / 2.0) - (nr_pass * overlap * dia)
  468. # if milling type is climb then the move is counter-clockwise around features
  469. mill_dir = 1 if milling_type == 'cl' else 0
  470. geom = self.generate_envelope(iso_offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  471. follow=follow, nr_passes=nr_pass)
  472. if geom == 'fail':
  473. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  474. return 'fail'
  475. geo_obj.solid_geometry.append(geom)
  476. # update the geometry in the tools
  477. geo_obj.tools['1']['solid_geometry'] = geo_obj.solid_geometry
  478. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  479. # or just looking in the lists (they are one level depth) and if any is not empty
  480. # proceed with object creation, if there are empty and the number of them is the length
  481. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  482. empty_cnt = 0
  483. if not isinstance(geo_obj.solid_geometry, list) and \
  484. not isinstance(geo_obj.solid_geometry, MultiPolygon):
  485. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  486. for g in geo_obj.solid_geometry:
  487. if g:
  488. break
  489. else:
  490. empty_cnt += 1
  491. if empty_cnt == len(geo_obj.solid_geometry):
  492. raise ValidationError("Empty Geometry", None)
  493. else:
  494. app_obj.inform.emit('[success] %s" %s' % (_("Isolation geometry created"), geo_obj.options["name"]))
  495. # even if combine is checked, one pass is still single-geo
  496. geo_obj.multigeo = True if passes > 1 else False
  497. # ############################################################
  498. # ########## AREA SUBTRACTION ################################
  499. # ############################################################
  500. # if self.app.defaults["tools_iso_except"]:
  501. # self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  502. # geo_obj.solid_geometry = self.area_subtraction(geo_obj.solid_geometry)
  503. self.app.app_obj.new_object("geometry", iso_name, iso_init, plot=plot)
  504. else:
  505. for i in range(passes):
  506. offset = dia * ((2 * i + 1) / 2.0) - (i * overlap * dia)
  507. if passes > 1:
  508. if outname is None:
  509. if self.iso_type == 0:
  510. iso_name = base_name + "_ext_iso" + str(i + 1)
  511. elif self.iso_type == 1:
  512. iso_name = base_name + "_int_iso" + str(i + 1)
  513. else:
  514. iso_name = base_name + "_iso" + str(i + 1)
  515. else:
  516. iso_name = outname
  517. else:
  518. if outname is None:
  519. if self.iso_type == 0:
  520. iso_name = base_name + "_ext_iso"
  521. elif self.iso_type == 1:
  522. iso_name = base_name + "_int_iso"
  523. else:
  524. iso_name = base_name + "_iso"
  525. else:
  526. iso_name = outname
  527. def iso_init(geo_obj, app_obj):
  528. # Propagate options
  529. geo_obj.options["cnctooldia"] = str(dia)
  530. geo_obj.tool_type = self.app.defaults["tools_iso_tool_type"]
  531. # if milling type is climb then the move is counter-clockwise around features
  532. mill_dir = 1 if milling_type == 'cl' else 0
  533. geom = self.generate_envelope(offset, mill_dir, geometry=work_geo, env_iso_type=iso_t,
  534. follow=follow, nr_passes=i)
  535. if geom == 'fail':
  536. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  537. return 'fail'
  538. geo_obj.solid_geometry = geom
  539. # transfer the Cut Z and Vtip and VAngle values in case that we use the V-Shape tool in Gerber UI
  540. # even if the resulting geometry is not multigeo we add the tools dict which will hold the data
  541. # required to be transfered to the Geometry object
  542. if self.app.defaults["tools_iso_tool_type"].lower() == 'v':
  543. new_cutz = self.app.defaults["tools_iso_tool_cutz"]
  544. new_vtipdia = self.app.defaults["tools_iso_tool_vtipdia"]
  545. new_vtipangle = self.app.defaults["tools_iso_tool_vtipangle"]
  546. tool_type = 'V'
  547. else:
  548. new_cutz = self.app.defaults['geometry_cutz']
  549. new_vtipdia = self.app.defaults['geometry_vtipdia']
  550. new_vtipangle = self.app.defaults['geometry_vtipangle']
  551. tool_type = 'C1'
  552. # store here the default data for Geometry Data
  553. default_data = {}
  554. default_data.update({
  555. "name": iso_name,
  556. "plot": self.app.defaults['geometry_plot'],
  557. "cutz": new_cutz,
  558. "vtipdia": new_vtipdia,
  559. "vtipangle": new_vtipangle,
  560. "travelz": self.app.defaults['geometry_travelz'],
  561. "feedrate": self.app.defaults['geometry_feedrate'],
  562. "feedrate_z": self.app.defaults['geometry_feedrate_z'],
  563. "feedrate_rapid": self.app.defaults['geometry_feedrate_rapid'],
  564. "dwell": self.app.defaults['geometry_dwell'],
  565. "dwelltime": self.app.defaults['geometry_dwelltime'],
  566. "multidepth": self.app.defaults['geometry_multidepth'],
  567. "ppname_g": self.app.defaults['geometry_ppname_g'],
  568. "depthperpass": self.app.defaults['geometry_depthperpass'],
  569. "extracut": self.app.defaults['geometry_extracut'],
  570. "extracut_length": self.app.defaults['geometry_extracut_length'],
  571. "toolchange": self.app.defaults['geometry_toolchange'],
  572. "toolchangez": self.app.defaults['geometry_toolchangez'],
  573. "endz": self.app.defaults['geometry_endz'],
  574. "spindlespeed": self.app.defaults['geometry_spindlespeed'],
  575. "toolchangexy": self.app.defaults['geometry_toolchangexy'],
  576. "startz": self.app.defaults['geometry_startz']
  577. })
  578. geo_obj.tools = {}
  579. geo_obj.tools['1'] = {}
  580. geo_obj.tools.update({
  581. '1': {
  582. 'tooldia': dia,
  583. 'offset': 'Path',
  584. 'offset_value': 0.0,
  585. 'type': _('Rough'),
  586. 'tool_type': tool_type,
  587. 'data': default_data,
  588. 'solid_geometry': geo_obj.solid_geometry
  589. }
  590. })
  591. # detect if solid_geometry is empty and this require list flattening which is "heavy"
  592. # or just looking in the lists (they are one level depth) and if any is not empty
  593. # proceed with object creation, if there are empty and the number of them is the length
  594. # of the list then we have an empty solid_geometry which should raise a Custom Exception
  595. empty_cnt = 0
  596. if not isinstance(geo_obj.solid_geometry, list):
  597. geo_obj.solid_geometry = [geo_obj.solid_geometry]
  598. for g in geo_obj.solid_geometry:
  599. if g:
  600. break
  601. else:
  602. empty_cnt += 1
  603. if empty_cnt == len(geo_obj.solid_geometry):
  604. raise ValidationError("Empty Geometry", None)
  605. else:
  606. app_obj.inform.emit('[success] %s: %s' %
  607. (_("Isolation geometry created"), geo_obj.options["name"]))
  608. geo_obj.multigeo = False
  609. # ############################################################
  610. # ########## AREA SUBTRACTION ################################
  611. # ############################################################
  612. # if self.app.defaults["tools_iso_except"]:
  613. # self.app.proc_container.update_view_text(' %s' % _("Subtracting Geo"))
  614. # geo_obj.solid_geometry = self.area_subtraction(geo_obj.solid_geometry)
  615. self.app.app_obj.new_object("geometry", iso_name, iso_init, plot=plot)
  616. def generate_envelope(self, offset, invert, geometry=None, env_iso_type=2, follow=None, nr_passes=0):
  617. # isolation_geometry produces an envelope that is going on the left of the geometry
  618. # (the copper features). To leave the least amount of burrs on the features
  619. # the tool needs to travel on the right side of the features (this is called conventional milling)
  620. # the first pass is the one cutting all of the features, so it needs to be reversed
  621. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  622. # to cut on the right side of the left over copper i.e on the left side of the features.
  623. if follow:
  624. geom = self.isolation_geometry(offset, geometry=geometry, follow=follow)
  625. else:
  626. try:
  627. geom = self.isolation_geometry(offset, geometry=geometry, iso_type=env_iso_type, passes=nr_passes)
  628. except Exception as e:
  629. log.debug('GerberObject.isolate().generate_envelope() --> %s' % str(e))
  630. return 'fail'
  631. if invert:
  632. try:
  633. pl = []
  634. for p in geom:
  635. if p is not None:
  636. if isinstance(p, Polygon):
  637. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  638. elif isinstance(p, LinearRing):
  639. pl.append(Polygon(p.coords[::-1]))
  640. geom = MultiPolygon(pl)
  641. except TypeError:
  642. if isinstance(geom, Polygon) and geom is not None:
  643. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  644. elif isinstance(geom, LinearRing) and geom is not None:
  645. geom = Polygon(geom.coords[::-1])
  646. else:
  647. log.debug("GerberObject.isolate().generate_envelope() Error --> Unexpected Geometry %s" %
  648. type(geom))
  649. except Exception as e:
  650. log.debug("GerberObject.isolate().generate_envelope() Error --> %s" % str(e))
  651. return 'fail'
  652. return geom
  653. def follow_geo(self, outname=None):
  654. """
  655. Creates a geometry object "following" the gerber paths.
  656. :return: None
  657. """
  658. if outname is None:
  659. follow_name = self.options["name"] + "_follow"
  660. else:
  661. follow_name = outname
  662. def follow_init(follow_obj, app):
  663. # Propagate options
  664. follow_obj.options["cnctooldia"] = str(self.app.defaults["tools_iso_tooldia"])
  665. follow_obj.solid_geometry = self.follow_geometry
  666. # TODO: Do something if this is None. Offer changing name?
  667. try:
  668. self.app.app_obj.new_object("geometry", follow_name, follow_init)
  669. except Exception as e:
  670. return "Operation failed: %s" % str(e)
  671. def on_plot_cb_click(self, *args):
  672. if self.muted_ui:
  673. return
  674. self.read_form_item('plot')
  675. self.plot()
  676. def on_solid_cb_click(self, *args):
  677. if self.muted_ui:
  678. return
  679. self.read_form_item('solid')
  680. self.plot()
  681. def on_multicolored_cb_click(self, *args):
  682. if self.muted_ui:
  683. return
  684. self.read_form_item('multicolored')
  685. self.plot()
  686. def on_follow_cb_click(self):
  687. if self.muted_ui:
  688. return
  689. self.plot()
  690. def on_aperture_table_visibility_change(self):
  691. if self.ui.aperture_table_visibility_cb.isChecked():
  692. # add the shapes storage for marking apertures
  693. if self.build_aperture_storage is False:
  694. self.build_aperture_storage = True
  695. if self.app.is_legacy is False:
  696. for ap_code in self.apertures:
  697. self.mark_shapes[ap_code] = self.app.plotcanvas.new_shape_collection(layers=1)
  698. else:
  699. for ap_code in self.apertures:
  700. self.mark_shapes[ap_code] = ShapeCollectionLegacy(obj=self, app=self.app,
  701. name=self.options['name'] + str(ap_code))
  702. self.ui.apertures_table.setVisible(True)
  703. for ap in self.mark_shapes:
  704. self.mark_shapes[ap].enabled = True
  705. self.ui.mark_all_cb.setVisible(True)
  706. self.ui.mark_all_cb.setChecked(False)
  707. self.build_ui()
  708. else:
  709. self.ui.apertures_table.setVisible(False)
  710. self.ui.mark_all_cb.setVisible(False)
  711. # on hide disable all mark plots
  712. try:
  713. for row in range(self.ui.apertures_table.rowCount()):
  714. self.ui.apertures_table.cellWidget(row, 5).set_value(False)
  715. self.clear_plot_apertures()
  716. # for ap in list(self.mark_shapes.keys()):
  717. # # self.mark_shapes[ap].enabled = False
  718. # del self.mark_shapes[ap]
  719. except Exception as e:
  720. log.debug(" GerberObject.on_aperture_visibility_changed() --> %s" % str(e))
  721. def convert_units(self, units):
  722. """
  723. Converts the units of the object by scaling dimensions in all geometry
  724. and options.
  725. :param units: Units to which to convert the object: "IN" or "MM".
  726. :type units: str
  727. :return: None
  728. :rtype: None
  729. """
  730. # units conversion to get a conversion should be done only once even if we found multiple
  731. # units declaration inside a Gerber file (it can happen to find also the obsolete declaration)
  732. if self.conversion_done is True:
  733. log.debug("Gerber units conversion cancelled. Already done.")
  734. return
  735. log.debug("FlatCAMObj.GerberObject.convert_units()")
  736. factor = Gerber.convert_units(self, units)
  737. # self.options['isotooldia'] = float(self.options['isotooldia']) * factor
  738. # self.options['bboxmargin'] = float(self.options['bboxmargin']) * factor
  739. def plot(self, kind=None, **kwargs):
  740. """
  741. :param kind: Not used, for compatibility with the plot method for other objects
  742. :param kwargs: Color and face_color, visible
  743. :return:
  744. """
  745. log.debug(str(inspect.stack()[1][3]) + " --> GerberObject.plot()")
  746. # Does all the required setup and returns False
  747. # if the 'ptint' option is set to False.
  748. if not FlatCAMObj.plot(self):
  749. return
  750. if 'color' in kwargs:
  751. color = kwargs['color']
  752. else:
  753. color = self.outline_color
  754. if 'face_color' in kwargs:
  755. face_color = kwargs['face_color']
  756. else:
  757. face_color = self.fill_color
  758. if 'visible' not in kwargs:
  759. visible = self.options['plot']
  760. else:
  761. visible = kwargs['visible']
  762. # if the Follow Geometry checkbox is checked then plot only the follow geometry
  763. if self.ui.follow_cb.get_value():
  764. geometry = self.follow_geometry
  765. else:
  766. geometry = self.solid_geometry
  767. # Make sure geometry is iterable.
  768. try:
  769. __ = iter(geometry)
  770. except TypeError:
  771. geometry = [geometry]
  772. if self.app.is_legacy is False:
  773. def random_color():
  774. r_color = np.random.rand(4)
  775. r_color[3] = 1
  776. return r_color
  777. else:
  778. def random_color():
  779. while True:
  780. r_color = np.random.rand(4)
  781. r_color[3] = 1
  782. new_color = '#'
  783. for idx in range(len(r_color)):
  784. new_color += '%x' % int(r_color[idx] * 255)
  785. # do it until a valid color is generated
  786. # a valid color has the # symbol, another 6 chars for the color and the last 2 chars for alpha
  787. # for a total of 9 chars
  788. if len(new_color) == 9:
  789. break
  790. return new_color
  791. try:
  792. if self.options["solid"]:
  793. for g in geometry:
  794. if type(g) == Polygon or type(g) == LineString:
  795. self.add_shape(shape=g, color=color,
  796. face_color=random_color() if self.options['multicolored']
  797. else face_color, visible=visible)
  798. elif type(g) == Point:
  799. pass
  800. else:
  801. try:
  802. for el in g:
  803. self.add_shape(shape=el, color=color,
  804. face_color=random_color() if self.options['multicolored']
  805. else face_color, visible=visible)
  806. except TypeError:
  807. self.add_shape(shape=g, color=color,
  808. face_color=random_color() if self.options['multicolored']
  809. else face_color, visible=visible)
  810. else:
  811. for g in geometry:
  812. if type(g) == Polygon or type(g) == LineString:
  813. self.add_shape(shape=g, color=random_color() if self.options['multicolored'] else 'black',
  814. visible=visible)
  815. elif type(g) == Point:
  816. pass
  817. else:
  818. for el in g:
  819. self.add_shape(shape=el, color=random_color() if self.options['multicolored'] else 'black',
  820. visible=visible)
  821. self.shapes.redraw(
  822. # update_colors=(self.fill_color, self.outline_color),
  823. # indexes=self.app.plotcanvas.shape_collection.data.keys()
  824. )
  825. except (ObjectDeleted, AttributeError):
  826. self.shapes.clear(update=True)
  827. except Exception as e:
  828. log.debug("GerberObject.plot() --> %s" % str(e))
  829. # experimental plot() when the solid_geometry is stored in the self.apertures
  830. def plot_aperture(self, run_thread=True, **kwargs):
  831. """
  832. :param run_thread: if True run the aperture plot as a thread in a worker
  833. :param kwargs: color and face_color
  834. :return:
  835. """
  836. log.debug(str(inspect.stack()[1][3]) + " --> GerberObject.plot_aperture()")
  837. # Does all the required setup and returns False
  838. # if the 'ptint' option is set to False.
  839. # if not FlatCAMObj.plot(self):
  840. # return
  841. # for marking apertures, line color and fill color are the same
  842. if 'color' in kwargs:
  843. color = kwargs['color']
  844. else:
  845. color = self.app.defaults['gerber_plot_fill']
  846. if 'marked_aperture' not in kwargs:
  847. return
  848. else:
  849. aperture_to_plot_mark = kwargs['marked_aperture']
  850. if aperture_to_plot_mark is None:
  851. return
  852. if 'visible' not in kwargs:
  853. visibility = True
  854. else:
  855. visibility = kwargs['visible']
  856. with self.app.proc_container.new(_("Plotting Apertures")):
  857. def job_thread(app_obj):
  858. try:
  859. if aperture_to_plot_mark in self.apertures:
  860. for elem in self.apertures[aperture_to_plot_mark]['geometry']:
  861. if 'solid' in elem:
  862. geo = elem['solid']
  863. if type(geo) == Polygon or type(geo) == LineString:
  864. self.add_mark_shape(apid=aperture_to_plot_mark, shape=geo, color=color,
  865. face_color=color, visible=visibility)
  866. else:
  867. for el in geo:
  868. self.add_mark_shape(apid=aperture_to_plot_mark, shape=el, color=color,
  869. face_color=color, visible=visibility)
  870. self.mark_shapes[aperture_to_plot_mark].redraw()
  871. except (ObjectDeleted, AttributeError):
  872. self.clear_plot_apertures()
  873. except Exception as e:
  874. log.debug("GerberObject.plot_aperture() --> %s" % str(e))
  875. if run_thread:
  876. self.app.worker_task.emit({'fcn': job_thread, 'params': [self]})
  877. else:
  878. job_thread(self)
  879. def clear_plot_apertures(self, aperture='all'):
  880. """
  881. :param aperture: string; aperture for which to clear the mark shapes
  882. :return:
  883. """
  884. if self.mark_shapes:
  885. if aperture == 'all':
  886. for apid in list(self.apertures.keys()):
  887. try:
  888. if self.app.is_legacy is True:
  889. self.mark_shapes[apid].clear(update=False)
  890. else:
  891. self.mark_shapes[apid].clear(update=True)
  892. except Exception as e:
  893. log.debug("GerberObject.clear_plot_apertures() 'all' --> %s" % str(e))
  894. else:
  895. try:
  896. if self.app.is_legacy is True:
  897. self.mark_shapes[aperture].clear(update=False)
  898. else:
  899. self.mark_shapes[aperture].clear(update=True)
  900. except Exception as e:
  901. log.debug("GerberObject.clear_plot_apertures() 'aperture' --> %s" % str(e))
  902. def clear_mark_all(self):
  903. self.ui.mark_all_cb.set_value(False)
  904. self.marked_rows[:] = []
  905. def on_mark_cb_click_table(self):
  906. """
  907. Will mark aperture geometries on canvas or delete the markings depending on the checkbox state
  908. :return:
  909. """
  910. self.ui_disconnect()
  911. try:
  912. cw = self.sender()
  913. cw_index = self.ui.apertures_table.indexAt(cw.pos())
  914. cw_row = cw_index.row()
  915. except AttributeError:
  916. cw_row = 0
  917. except TypeError:
  918. return
  919. self.marked_rows[:] = []
  920. try:
  921. aperture = self.ui.apertures_table.item(cw_row, 1).text()
  922. except AttributeError:
  923. return
  924. if self.ui.apertures_table.cellWidget(cw_row, 5).isChecked():
  925. self.marked_rows.append(True)
  926. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  927. self.plot_aperture(color=self.app.defaults['global_sel_draw_color'] + 'AF',
  928. marked_aperture=aperture, visible=True, run_thread=True)
  929. # self.mark_shapes[aperture].redraw()
  930. else:
  931. self.marked_rows.append(False)
  932. self.clear_plot_apertures(aperture=aperture)
  933. # make sure that the Mark All is disabled if one of the row mark's are disabled and
  934. # if all the row mark's are enabled also enable the Mark All checkbox
  935. cb_cnt = 0
  936. total_row = self.ui.apertures_table.rowCount()
  937. for row in range(total_row):
  938. if self.ui.apertures_table.cellWidget(row, 5).isChecked():
  939. cb_cnt += 1
  940. else:
  941. cb_cnt -= 1
  942. if cb_cnt < total_row:
  943. self.ui.mark_all_cb.setChecked(False)
  944. else:
  945. self.ui.mark_all_cb.setChecked(True)
  946. self.ui_connect()
  947. def on_mark_all_click(self):
  948. self.ui_disconnect()
  949. mark_all = self.ui.mark_all_cb.isChecked()
  950. for row in range(self.ui.apertures_table.rowCount()):
  951. # update the mark_rows list
  952. if mark_all:
  953. self.marked_rows.append(True)
  954. else:
  955. self.marked_rows[:] = []
  956. mark_cb = self.ui.apertures_table.cellWidget(row, 5)
  957. mark_cb.setChecked(mark_all)
  958. if mark_all:
  959. for aperture in self.apertures:
  960. # self.plot_aperture(color='#2d4606bf', marked_aperture=aperture, visible=True)
  961. self.plot_aperture(color=self.app.defaults['global_sel_draw_color'] + 'AF',
  962. marked_aperture=aperture, visible=True)
  963. # HACK: enable/disable the grid for a better look
  964. self.app.ui.grid_snap_btn.trigger()
  965. self.app.ui.grid_snap_btn.trigger()
  966. else:
  967. self.clear_plot_apertures()
  968. self.marked_rows[:] = []
  969. self.ui_connect()
  970. def export_gerber(self, whole, fract, g_zeros='L', factor=1):
  971. """
  972. Creates a Gerber file content to be exported to a file.
  973. :param whole: how many digits in the whole part of coordinates
  974. :param fract: how many decimals in coordinates
  975. :param g_zeros: type of the zero suppression used: LZ or TZ; string
  976. :param factor: factor to be applied onto the Gerber coordinates
  977. :return: Gerber_code
  978. """
  979. log.debug("GerberObject.export_gerber() --> Generating the Gerber code from the selected Gerber file")
  980. def tz_format(x, y, fac):
  981. x_c = x * fac
  982. y_c = y * fac
  983. x_form = "{:.{dec}f}".format(x_c, dec=fract)
  984. y_form = "{:.{dec}f}".format(y_c, dec=fract)
  985. # extract whole part and decimal part
  986. x_form = x_form.partition('.')
  987. y_form = y_form.partition('.')
  988. # left padd the 'whole' part with zeros
  989. x_whole = x_form[0].rjust(whole, '0')
  990. y_whole = y_form[0].rjust(whole, '0')
  991. # restore the coordinate padded in the left with 0 and added the decimal part
  992. # without the decinal dot
  993. x_form = x_whole + x_form[2]
  994. y_form = y_whole + y_form[2]
  995. return x_form, y_form
  996. def lz_format(x, y, fac):
  997. x_c = x * fac
  998. y_c = y * fac
  999. x_form = "{:.{dec}f}".format(x_c, dec=fract).replace('.', '')
  1000. y_form = "{:.{dec}f}".format(y_c, dec=fract).replace('.', '')
  1001. # pad with rear zeros
  1002. x_form.ljust(length, '0')
  1003. y_form.ljust(length, '0')
  1004. return x_form, y_form
  1005. # Gerber code is stored here
  1006. gerber_code = ''
  1007. # apertures processing
  1008. try:
  1009. length = whole + fract
  1010. if '0' in self.apertures:
  1011. if 'geometry' in self.apertures['0']:
  1012. for geo_elem in self.apertures['0']['geometry']:
  1013. if 'solid' in geo_elem:
  1014. geo = geo_elem['solid']
  1015. if not geo.is_empty and not isinstance(geo, LineString) and \
  1016. not isinstance(geo, MultiLineString) and not isinstance(geo, Point):
  1017. gerber_code += 'G36*\n'
  1018. geo_coords = list(geo.exterior.coords)
  1019. # first command is a move with pen-up D02 at the beginning of the geo
  1020. if g_zeros == 'T':
  1021. x_formatted, y_formatted = tz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1022. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1023. yform=y_formatted)
  1024. else:
  1025. x_formatted, y_formatted = lz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1026. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1027. yform=y_formatted)
  1028. for coord in geo_coords[1:]:
  1029. if g_zeros == 'T':
  1030. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1031. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1032. yform=y_formatted)
  1033. else:
  1034. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1035. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1036. yform=y_formatted)
  1037. gerber_code += 'D02*\n'
  1038. gerber_code += 'G37*\n'
  1039. clear_list = list(geo.interiors)
  1040. if clear_list:
  1041. gerber_code += '%LPC*%\n'
  1042. for clear_geo in clear_list:
  1043. gerber_code += 'G36*\n'
  1044. geo_coords = list(clear_geo.coords)
  1045. # first command is a move with pen-up D02 at the beginning of the geo
  1046. if g_zeros == 'T':
  1047. x_formatted, y_formatted = tz_format(
  1048. geo_coords[0][0], geo_coords[0][1], factor)
  1049. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1050. yform=y_formatted)
  1051. else:
  1052. x_formatted, y_formatted = lz_format(
  1053. geo_coords[0][0], geo_coords[0][1], factor)
  1054. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1055. yform=y_formatted)
  1056. prev_coord = geo_coords[0]
  1057. for coord in geo_coords[1:]:
  1058. if coord != prev_coord:
  1059. if g_zeros == 'T':
  1060. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1061. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1062. yform=y_formatted)
  1063. else:
  1064. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1065. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1066. yform=y_formatted)
  1067. prev_coord = coord
  1068. gerber_code += 'D02*\n'
  1069. gerber_code += 'G37*\n'
  1070. gerber_code += '%LPD*%\n'
  1071. elif isinstance(geo, LineString) or isinstance(geo, MultiLineString) or \
  1072. isinstance(geo, Point):
  1073. try:
  1074. if not geo.is_empty:
  1075. if isinstance(geo, Point):
  1076. if g_zeros == 'T':
  1077. x_formatted, y_formatted = tz_format(geo.x, geo.y, factor)
  1078. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1079. yform=y_formatted)
  1080. else:
  1081. x_formatted, y_formatted = lz_format(geo.x, geo.y, factor)
  1082. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1083. yform=y_formatted)
  1084. else:
  1085. geo_coords = list(geo.coords)
  1086. # first command is a move with pen-up D02 at the beginning of the geo
  1087. if g_zeros == 'T':
  1088. x_formatted, y_formatted = tz_format(
  1089. geo_coords[0][0], geo_coords[0][1], factor)
  1090. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1091. yform=y_formatted)
  1092. else:
  1093. x_formatted, y_formatted = lz_format(
  1094. geo_coords[0][0], geo_coords[0][1], factor)
  1095. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1096. yform=y_formatted)
  1097. prev_coord = geo_coords[0]
  1098. for coord in geo_coords[1:]:
  1099. if coord != prev_coord:
  1100. if g_zeros == 'T':
  1101. x_formatted, y_formatted = tz_format(coord[0], coord[1],
  1102. factor)
  1103. gerber_code += "X{xform}Y{yform}D01*\n".format(
  1104. xform=x_formatted,
  1105. yform=y_formatted)
  1106. else:
  1107. x_formatted, y_formatted = lz_format(coord[0], coord[1],
  1108. factor)
  1109. gerber_code += "X{xform}Y{yform}D01*\n".format(
  1110. xform=x_formatted,
  1111. yform=y_formatted)
  1112. prev_coord = coord
  1113. # gerber_code += "D02*\n"
  1114. except Exception as e:
  1115. log.debug("FlatCAMObj.GerberObject.export_gerber() 'follow' --> %s" % str(e))
  1116. if 'clear' in geo_elem:
  1117. geo = geo_elem['clear']
  1118. if not geo.is_empty:
  1119. gerber_code += '%LPC*%\n'
  1120. gerber_code += 'G36*\n'
  1121. geo_coords = list(geo.exterior.coords)
  1122. # first command is a move with pen-up D02 at the beginning of the geo
  1123. if g_zeros == 'T':
  1124. x_formatted, y_formatted = tz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1125. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1126. yform=y_formatted)
  1127. else:
  1128. x_formatted, y_formatted = lz_format(geo_coords[0][0], geo_coords[0][1], factor)
  1129. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1130. yform=y_formatted)
  1131. prev_coord = geo_coords[0]
  1132. for coord in geo_coords[1:]:
  1133. if coord != prev_coord:
  1134. if g_zeros == 'T':
  1135. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1136. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1137. yform=y_formatted)
  1138. else:
  1139. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1140. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1141. yform=y_formatted)
  1142. prev_coord = coord
  1143. gerber_code += 'D02*\n'
  1144. gerber_code += 'G37*\n'
  1145. gerber_code += '%LPD*%\n'
  1146. except Exception as e:
  1147. log.debug("FlatCAMObj.GerberObject.export_gerber() '0' aperture --> %s" % str(e))
  1148. for apid in self.apertures:
  1149. if apid == '0':
  1150. continue
  1151. else:
  1152. gerber_code += 'D%s*\n' % str(apid)
  1153. if 'geometry' in self.apertures[apid]:
  1154. for geo_elem in self.apertures[apid]['geometry']:
  1155. try:
  1156. if 'follow' in geo_elem:
  1157. geo = geo_elem['follow']
  1158. if not geo.is_empty:
  1159. if isinstance(geo, Point):
  1160. if g_zeros == 'T':
  1161. x_formatted, y_formatted = tz_format(geo.x, geo.y, factor)
  1162. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1163. yform=y_formatted)
  1164. else:
  1165. x_formatted, y_formatted = lz_format(geo.x, geo.y, factor)
  1166. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1167. yform=y_formatted)
  1168. else:
  1169. geo_coords = list(geo.coords)
  1170. # first command is a move with pen-up D02 at the beginning of the geo
  1171. if g_zeros == 'T':
  1172. x_formatted, y_formatted = tz_format(
  1173. geo_coords[0][0], geo_coords[0][1], factor)
  1174. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1175. yform=y_formatted)
  1176. else:
  1177. x_formatted, y_formatted = lz_format(
  1178. geo_coords[0][0], geo_coords[0][1], factor)
  1179. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1180. yform=y_formatted)
  1181. prev_coord = geo_coords[0]
  1182. for coord in geo_coords[1:]:
  1183. if coord != prev_coord:
  1184. if g_zeros == 'T':
  1185. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1186. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1187. yform=y_formatted)
  1188. else:
  1189. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1190. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1191. yform=y_formatted)
  1192. prev_coord = coord
  1193. # gerber_code += "D02*\n"
  1194. except Exception as e:
  1195. log.debug("FlatCAMObj.GerberObject.export_gerber() 'follow' --> %s" % str(e))
  1196. try:
  1197. if 'clear' in geo_elem:
  1198. gerber_code += '%LPC*%\n'
  1199. geo = geo_elem['clear']
  1200. if not geo.is_empty:
  1201. if isinstance(geo, Point):
  1202. if g_zeros == 'T':
  1203. x_formatted, y_formatted = tz_format(geo.x, geo.y, factor)
  1204. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1205. yform=y_formatted)
  1206. else:
  1207. x_formatted, y_formatted = lz_format(geo.x, geo.y, factor)
  1208. gerber_code += "X{xform}Y{yform}D03*\n".format(xform=x_formatted,
  1209. yform=y_formatted)
  1210. elif isinstance(geo, Polygon):
  1211. geo_coords = list(geo.exterior.coords)
  1212. # first command is a move with pen-up D02 at the beginning of the geo
  1213. if g_zeros == 'T':
  1214. x_formatted, y_formatted = tz_format(
  1215. geo_coords[0][0], geo_coords[0][1], factor)
  1216. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1217. yform=y_formatted)
  1218. else:
  1219. x_formatted, y_formatted = lz_format(
  1220. geo_coords[0][0], geo_coords[0][1], factor)
  1221. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1222. yform=y_formatted)
  1223. prev_coord = geo_coords[0]
  1224. for coord in geo_coords[1:]:
  1225. if coord != prev_coord:
  1226. if g_zeros == 'T':
  1227. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1228. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1229. yform=y_formatted)
  1230. else:
  1231. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1232. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1233. yform=y_formatted)
  1234. prev_coord = coord
  1235. for geo_int in geo.interiors:
  1236. geo_coords = list(geo_int.coords)
  1237. # first command is a move with pen-up D02 at the beginning of the geo
  1238. if g_zeros == 'T':
  1239. x_formatted, y_formatted = tz_format(
  1240. geo_coords[0][0], geo_coords[0][1], factor)
  1241. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1242. yform=y_formatted)
  1243. else:
  1244. x_formatted, y_formatted = lz_format(
  1245. geo_coords[0][0], geo_coords[0][1], factor)
  1246. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1247. yform=y_formatted)
  1248. prev_coord = geo_coords[0]
  1249. for coord in geo_coords[1:]:
  1250. if coord != prev_coord:
  1251. if g_zeros == 'T':
  1252. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1253. gerber_code += "X{xform}Y{yform}D01*\n".format(
  1254. xform=x_formatted,
  1255. yform=y_formatted)
  1256. else:
  1257. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1258. gerber_code += "X{xform}Y{yform}D01*\n".format(
  1259. xform=x_formatted,
  1260. yform=y_formatted)
  1261. prev_coord = coord
  1262. else:
  1263. geo_coords = list(geo.coords)
  1264. # first command is a move with pen-up D02 at the beginning of the geo
  1265. if g_zeros == 'T':
  1266. x_formatted, y_formatted = tz_format(
  1267. geo_coords[0][0], geo_coords[0][1], factor)
  1268. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1269. yform=y_formatted)
  1270. else:
  1271. x_formatted, y_formatted = lz_format(
  1272. geo_coords[0][0], geo_coords[0][1], factor)
  1273. gerber_code += "X{xform}Y{yform}D02*\n".format(xform=x_formatted,
  1274. yform=y_formatted)
  1275. prev_coord = geo_coords[0]
  1276. for coord in geo_coords[1:]:
  1277. if coord != prev_coord:
  1278. if g_zeros == 'T':
  1279. x_formatted, y_formatted = tz_format(coord[0], coord[1], factor)
  1280. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1281. yform=y_formatted)
  1282. else:
  1283. x_formatted, y_formatted = lz_format(coord[0], coord[1], factor)
  1284. gerber_code += "X{xform}Y{yform}D01*\n".format(xform=x_formatted,
  1285. yform=y_formatted)
  1286. prev_coord = coord
  1287. # gerber_code += "D02*\n"
  1288. gerber_code += '%LPD*%\n'
  1289. except Exception as e:
  1290. log.debug("FlatCAMObj.GerberObject.export_gerber() 'clear' --> %s" % str(e))
  1291. if not self.apertures:
  1292. log.debug("FlatCAMObj.GerberObject.export_gerber() --> Gerber Object is empty: no apertures.")
  1293. return 'fail'
  1294. return gerber_code
  1295. def mirror(self, axis, point):
  1296. Gerber.mirror(self, axis=axis, point=point)
  1297. self.replotApertures.emit()
  1298. def offset(self, vect):
  1299. Gerber.offset(self, vect=vect)
  1300. self.replotApertures.emit()
  1301. def rotate(self, angle, point):
  1302. Gerber.rotate(self, angle=angle, point=point)
  1303. self.replotApertures.emit()
  1304. def scale(self, xfactor, yfactor=None, point=None):
  1305. Gerber.scale(self, xfactor=xfactor, yfactor=yfactor, point=point)
  1306. self.replotApertures.emit()
  1307. def skew(self, angle_x, angle_y, point):
  1308. Gerber.skew(self, angle_x=angle_x, angle_y=angle_y, point=point)
  1309. self.replotApertures.emit()
  1310. def buffer(self, distance, join=2, factor=None):
  1311. Gerber.buffer(self, distance=distance, join=join, factor=factor)
  1312. self.replotApertures.emit()
  1313. def serialize(self):
  1314. return {
  1315. "options": self.options,
  1316. "kind": self.kind
  1317. }