FlatCAMGerber.py 75 KB

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