ToolEtchCompensation.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 2/14/2020 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtCore
  8. from AppTool import AppTool
  9. from AppGUI.GUIElements import FCButton, FCDoubleSpinner, RadioSet, FCComboBox, NumericalEvalEntry, FCEntry
  10. from shapely.ops import unary_union
  11. from copy import deepcopy
  12. import math
  13. import logging
  14. import gettext
  15. import AppTranslation as fcTranslate
  16. import builtins
  17. fcTranslate.apply_language('strings')
  18. if '_' not in builtins.__dict__:
  19. _ = gettext.gettext
  20. log = logging.getLogger('base')
  21. class ToolEtchCompensation(AppTool):
  22. toolName = _("Etch Compensation Tool")
  23. def __init__(self, app):
  24. self.app = app
  25. self.decimals = self.app.decimals
  26. AppTool.__init__(self, app)
  27. self.tools_frame = QtWidgets.QFrame()
  28. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  29. self.layout.addWidget(self.tools_frame)
  30. self.tools_box = QtWidgets.QVBoxLayout()
  31. self.tools_box.setContentsMargins(0, 0, 0, 0)
  32. self.tools_frame.setLayout(self.tools_box)
  33. # Title
  34. title_label = QtWidgets.QLabel("%s" % self.toolName)
  35. title_label.setStyleSheet("""
  36. QLabel
  37. {
  38. font-size: 16px;
  39. font-weight: bold;
  40. }
  41. """)
  42. self.tools_box.addWidget(title_label)
  43. # Grid Layout
  44. grid0 = QtWidgets.QGridLayout()
  45. grid0.setColumnStretch(0, 0)
  46. grid0.setColumnStretch(1, 1)
  47. self.tools_box.addLayout(grid0)
  48. grid0.addWidget(QtWidgets.QLabel(''), 0, 0, 1, 2)
  49. # Target Gerber Object
  50. self.gerber_combo = FCComboBox()
  51. self.gerber_combo.setModel(self.app.collection)
  52. self.gerber_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  53. self.gerber_combo.is_last = True
  54. self.gerber_combo.obj_type = "Gerber"
  55. self.gerber_label = QtWidgets.QLabel('<b>%s:</b>' % _("GERBER"))
  56. self.gerber_label.setToolTip(
  57. _("Gerber object that will be inverted.")
  58. )
  59. grid0.addWidget(self.gerber_label, 1, 0, 1, 2)
  60. grid0.addWidget(self.gerber_combo, 2, 0, 1, 2)
  61. grid0.addWidget(QtWidgets.QLabel(""), 3, 0, 1, 2)
  62. self.util_label = QtWidgets.QLabel("<b>%s:</b>" % _("Utilities"))
  63. self.util_label.setToolTip('%s.' % _("Conversion utilities"))
  64. grid0.addWidget(self.util_label, 4, 0, 1, 2)
  65. # Oz to um conversion
  66. self.oz_um_label = QtWidgets.QLabel('%s:' % _('Oz to Microns'))
  67. self.oz_um_label.setToolTip(
  68. _("Will convert from oz thickness to microns [um].\n"
  69. "Can use formulas with operators: /, *, +, -, %, .\n"
  70. "The real numbers use the dot decimals separator.")
  71. )
  72. grid0.addWidget(self.oz_um_label, 5, 0, 1, 2)
  73. hlay_1 = QtWidgets.QHBoxLayout()
  74. self.oz_entry = NumericalEvalEntry(border_color='#0069A9')
  75. self.oz_entry.setPlaceholderText(_("Oz value"))
  76. self.oz_to_um_entry = FCEntry()
  77. self.oz_to_um_entry.setPlaceholderText(_("Microns value"))
  78. self.oz_to_um_entry.setReadOnly(True)
  79. hlay_1.addWidget(self.oz_entry)
  80. hlay_1.addWidget(self.oz_to_um_entry)
  81. grid0.addLayout(hlay_1, 6, 0, 1, 2)
  82. # Mils to um conversion
  83. self.mils_um_label = QtWidgets.QLabel('%s:' % _('Mils to Microns'))
  84. self.mils_um_label.setToolTip(
  85. _("Will convert from mils to microns [um].\n"
  86. "Can use formulas with operators: /, *, +, -, %, .\n"
  87. "The real numbers use the dot decimals separator.")
  88. )
  89. grid0.addWidget(self.mils_um_label, 7, 0, 1, 2)
  90. hlay_2 = QtWidgets.QHBoxLayout()
  91. self.mils_entry = NumericalEvalEntry(border_color='#0069A9')
  92. self.mils_entry.setPlaceholderText(_("Mils value"))
  93. self.mils_to_um_entry = FCEntry()
  94. self.mils_to_um_entry.setPlaceholderText(_("Microns value"))
  95. self.mils_to_um_entry.setReadOnly(True)
  96. hlay_2.addWidget(self.mils_entry)
  97. hlay_2.addWidget(self.mils_to_um_entry)
  98. grid0.addLayout(hlay_2, 8, 0, 1, 2)
  99. grid0.addWidget(QtWidgets.QLabel(""), 9, 0, 1, 2)
  100. self.param_label = QtWidgets.QLabel("<b>%s:</b>" % _("Parameters"))
  101. self.param_label.setToolTip('%s.' % _("Parameters for this tool"))
  102. grid0.addWidget(self.param_label, 10, 0, 1, 2)
  103. # Thickness
  104. self.thick_label = QtWidgets.QLabel('%s:' % _('Copper Thickness'))
  105. self.thick_label.setToolTip(
  106. _("The thickness of the copper foil.\n"
  107. "In microns [um].")
  108. )
  109. self.thick_entry = FCDoubleSpinner(callback=self.confirmation_message)
  110. self.thick_entry.set_precision(self.decimals)
  111. self.thick_entry.set_range(0.0000, 9999.9999)
  112. self.thick_entry.setObjectName(_("Thickness"))
  113. grid0.addWidget(self.thick_label, 12, 0)
  114. grid0.addWidget(self.thick_entry, 12, 1)
  115. self.ratio_label = QtWidgets.QLabel('%s:' % _("Ratio"))
  116. self.ratio_label.setToolTip(
  117. _("The ratio of lateral etch versus depth etch.\n"
  118. "Can be:\n"
  119. "- custom -> the user will enter a custom value\n"
  120. "- preselection -> value which depends on a selection of etchants")
  121. )
  122. self.ratio_radio = RadioSet([
  123. {'label': _('Etch Factor'), 'value': 'factor'},
  124. {'label': _('Etchants list'), 'value': 'etch_list'},
  125. {'label': _('Manual offset'), 'value': 'manual'}
  126. ], orientation='vertical', stretch=False)
  127. grid0.addWidget(self.ratio_label, 14, 0, 1, 2)
  128. grid0.addWidget(self.ratio_radio, 16, 0, 1, 2)
  129. # Etchants
  130. self.etchants_label = QtWidgets.QLabel('%s:' % _('Etchants'))
  131. self.etchants_label.setToolTip(
  132. _("A list of etchants.")
  133. )
  134. self.etchants_combo = FCComboBox(callback=self.confirmation_message)
  135. self.etchants_combo.setObjectName(_("Etchants"))
  136. self.etchants_combo.addItems(["CuCl2", "Fe3Cl"])
  137. grid0.addWidget(self.etchants_label, 18, 0)
  138. grid0.addWidget(self.etchants_combo, 18, 1)
  139. # Etch Factor
  140. self.factor_label = QtWidgets.QLabel('%s:' % _('Etch factor'))
  141. self.factor_label.setToolTip(
  142. _("The ratio between depth etch and lateral etch .\n"
  143. "Accepts real numbers and formulas using the operators: /,*,+,-,%")
  144. )
  145. self.factor_entry = NumericalEvalEntry(border_color='#0069A9')
  146. self.factor_entry.setPlaceholderText(_("Real number or formula"))
  147. self.factor_entry.setObjectName(_("Etch_factor"))
  148. grid0.addWidget(self.factor_label, 19, 0)
  149. grid0.addWidget(self.factor_entry, 19, 1)
  150. # Manual Offset
  151. self.offset_label = QtWidgets.QLabel('%s:' % _('Offset'))
  152. self.offset_label.setToolTip(
  153. _("Value with which to increase or decrease (buffer)\n"
  154. "the copper features. In microns [um].")
  155. )
  156. self.offset_entry = FCDoubleSpinner(callback=self.confirmation_message)
  157. self.offset_entry.set_precision(self.decimals)
  158. self.offset_entry.set_range(-9999.9999, 9999.9999)
  159. self.offset_entry.setObjectName(_("Offset"))
  160. grid0.addWidget(self.offset_label, 20, 0)
  161. grid0.addWidget(self.offset_entry, 20, 1)
  162. # Hide the Etchants and Etch factor
  163. self.etchants_label.hide()
  164. self.etchants_combo.hide()
  165. self.factor_label.hide()
  166. self.factor_entry.hide()
  167. self.offset_label.hide()
  168. self.offset_entry.hide()
  169. separator_line = QtWidgets.QFrame()
  170. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  171. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  172. grid0.addWidget(separator_line, 22, 0, 1, 2)
  173. self.compensate_btn = FCButton(_('Compensate'))
  174. self.compensate_btn.setToolTip(
  175. _("Will increase the copper features thickness to compensate the lateral etch.")
  176. )
  177. self.compensate_btn.setStyleSheet("""
  178. QPushButton
  179. {
  180. font-weight: bold;
  181. }
  182. """)
  183. grid0.addWidget(self.compensate_btn, 24, 0, 1, 2)
  184. self.tools_box.addStretch()
  185. # ## Reset Tool
  186. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  187. self.reset_button.setToolTip(
  188. _("Will reset the tool parameters.")
  189. )
  190. self.reset_button.setStyleSheet("""
  191. QPushButton
  192. {
  193. font-weight: bold;
  194. }
  195. """)
  196. self.tools_box.addWidget(self.reset_button)
  197. self.compensate_btn.clicked.connect(self.on_compensate)
  198. self.reset_button.clicked.connect(self.set_tool_ui)
  199. self.ratio_radio.activated_custom.connect(self.on_ratio_change)
  200. self.oz_entry.textChanged.connect(self.on_oz_conversion)
  201. self.mils_entry.textChanged.connect(self.on_mils_conversion)
  202. def install(self, icon=None, separator=None, **kwargs):
  203. AppTool.install(self, icon, separator, shortcut='', **kwargs)
  204. def run(self, toggle=True):
  205. self.app.defaults.report_usage("ToolEtchCompensation()")
  206. log.debug("ToolEtchCompensation() is running ...")
  207. if toggle:
  208. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  209. if self.app.ui.splitter.sizes()[0] == 0:
  210. self.app.ui.splitter.setSizes([1, 1])
  211. else:
  212. try:
  213. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  214. # if tab is populated with the tool but it does not have the focus, focus on it
  215. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  216. # focus on Tool Tab
  217. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  218. else:
  219. self.app.ui.splitter.setSizes([0, 1])
  220. except AttributeError:
  221. pass
  222. else:
  223. if self.app.ui.splitter.sizes()[0] == 0:
  224. self.app.ui.splitter.setSizes([1, 1])
  225. AppTool.run(self)
  226. self.set_tool_ui()
  227. self.app.ui.notebook.setTabText(2, _("Etch Compensation Tool"))
  228. def set_tool_ui(self):
  229. self.thick_entry.set_value(18.0)
  230. self.ratio_radio.set_value('factor')
  231. def on_ratio_change(self, val):
  232. """
  233. Called on activated_custom signal of the RadioSet GUI element self.radio_ratio
  234. :param val: 'c' or 'p': 'c' means custom factor and 'p' means preselected etchants
  235. :type val: str
  236. :return: None
  237. :rtype:
  238. """
  239. if val == 'factor':
  240. self.etchants_label.hide()
  241. self.etchants_combo.hide()
  242. self.factor_label.show()
  243. self.factor_entry.show()
  244. self.offset_label.hide()
  245. self.offset_entry.hide()
  246. elif val == 'etch_list':
  247. self.etchants_label.show()
  248. self.etchants_combo.show()
  249. self.factor_label.hide()
  250. self.factor_entry.hide()
  251. self.offset_label.hide()
  252. self.offset_entry.hide()
  253. else:
  254. self.etchants_label.hide()
  255. self.etchants_combo.hide()
  256. self.factor_label.hide()
  257. self.factor_entry.hide()
  258. self.offset_label.show()
  259. self.offset_entry.show()
  260. def on_oz_conversion(self, txt):
  261. try:
  262. val = eval(txt)
  263. # oz thickness to mils by multiplying with 1.37
  264. # mils to microns by multiplying with 25.4
  265. val *= 34.798
  266. except Exception:
  267. self.oz_to_um_entry.set_value('')
  268. return
  269. self.oz_to_um_entry.set_value(val, self.decimals)
  270. def on_mils_conversion(self, txt):
  271. try:
  272. val = eval(txt)
  273. val *= 25.4
  274. except Exception:
  275. self.mils_to_um_entry.set_value('')
  276. return
  277. self.mils_to_um_entry.set_value(val, self.decimals)
  278. def on_compensate(self):
  279. log.debug("ToolEtchCompensation.on_compensate()")
  280. ratio_type = self.ratio_radio.get_value()
  281. thickness = self.thick_entry.get_value() / 1000 # in microns
  282. grb_circle_steps = int(self.app.defaults["gerber_circle_steps"])
  283. obj_name = self.gerber_combo.currentText()
  284. outname = obj_name + "_comp"
  285. # Get source object.
  286. try:
  287. grb_obj = self.app.collection.get_by_name(obj_name)
  288. except Exception as e:
  289. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(obj_name)))
  290. return "Could not retrieve object: %s with error: %s" % (obj_name, str(e))
  291. if grb_obj is None:
  292. if obj_name == '':
  293. obj_name = 'None'
  294. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(obj_name)))
  295. return
  296. if ratio_type == 'factor':
  297. etch_factor = 1 / self.factor_entry.get_value()
  298. offset = thickness / etch_factor
  299. elif ratio_type == 'etch_list':
  300. etchant = self.etchants_combo.get_value()
  301. if etchant == "CuCl2":
  302. etch_factor = 0.33
  303. else:
  304. etch_factor = 0.25
  305. offset = thickness / etch_factor
  306. else:
  307. offset = self.offset_entry.get_value() / 1000 # in microns
  308. try:
  309. __ = iter(grb_obj.solid_geometry)
  310. except TypeError:
  311. grb_obj.solid_geometry = list(grb_obj.solid_geometry)
  312. new_solid_geometry = []
  313. for poly in grb_obj.solid_geometry:
  314. new_solid_geometry.append(poly.buffer(offset, int(grb_circle_steps)))
  315. new_solid_geometry = unary_union(new_solid_geometry)
  316. new_options = {}
  317. for opt in grb_obj.options:
  318. new_options[opt] = deepcopy(grb_obj.options[opt])
  319. new_apertures = deepcopy(grb_obj.apertures)
  320. # update the apertures attributes (keys in the apertures dict)
  321. for ap in new_apertures:
  322. type = new_apertures[ap]['type']
  323. for k in new_apertures[ap]:
  324. if type == 'R' or type == 'O':
  325. if k == 'width' or k == 'height':
  326. new_apertures[ap][k] += offset
  327. else:
  328. if k == 'size' or k == 'width' or k == 'height':
  329. new_apertures[ap][k] += offset
  330. if k == 'geometry':
  331. for geo_el in new_apertures[ap][k]:
  332. if 'solid' in geo_el:
  333. geo_el['solid'] = geo_el['solid'].buffer(offset, int(grb_circle_steps))
  334. # in case of 'R' or 'O' aperture type we need to update the aperture 'size' after
  335. # the 'width' and 'height' keys were updated
  336. for ap in new_apertures:
  337. type = new_apertures[ap]['type']
  338. for k in new_apertures[ap]:
  339. if type == 'R' or type == 'O':
  340. if k == 'size':
  341. new_apertures[ap][k] = math.sqrt(
  342. new_apertures[ap]['width'] ** 2 + new_apertures[ap]['height'] ** 2)
  343. def init_func(new_obj, app_obj):
  344. """
  345. Init a new object in FlatCAM Object collection
  346. :param new_obj: New object
  347. :type new_obj: ObjectCollection
  348. :param app_obj: App
  349. :type app_obj: App_Main.App
  350. :return: None
  351. :rtype:
  352. """
  353. new_obj.options.update(new_options)
  354. new_obj.options['name'] = outname
  355. new_obj.fill_color = deepcopy(grb_obj.fill_color)
  356. new_obj.outline_color = deepcopy(grb_obj.outline_color)
  357. new_obj.apertures = deepcopy(new_apertures)
  358. new_obj.solid_geometry = deepcopy(new_solid_geometry)
  359. new_obj.source_file = self.app.export_gerber(obj_name=outname, filename=None,
  360. local_use=new_obj, use_thread=False)
  361. self.app.app_obj.new_object('gerber', outname, init_func)
  362. def reset_fields(self):
  363. self.gerber_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  364. @staticmethod
  365. def poly2rings(poly):
  366. return [poly.exterior] + [interior for interior in poly.interiors]
  367. # end of file