ToolNonCopperClear.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # File Modified by: Marius Adrian Stanciu (c) #
  5. # Date: 3/10/2019 #
  6. # MIT Licence #
  7. ############################################################
  8. from FlatCAMTool import FlatCAMTool
  9. from copy import copy,deepcopy
  10. from ObjectCollection import *
  11. import time
  12. import gettext
  13. import FlatCAMTranslation as fcTranslate
  14. fcTranslate.apply_language('strings')
  15. import builtins
  16. if '_' not in builtins.__dict__:
  17. _ = gettext.gettext
  18. class NonCopperClear(FlatCAMTool, Gerber):
  19. toolName = _("Non-Copper Clearing")
  20. def __init__(self, app):
  21. self.app = app
  22. FlatCAMTool.__init__(self, app)
  23. Gerber.__init__(self, steps_per_circle=self.app.defaults["gerber_circle_steps"])
  24. self.tools_frame = QtWidgets.QFrame()
  25. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  26. self.layout.addWidget(self.tools_frame)
  27. self.tools_box = QtWidgets.QVBoxLayout()
  28. self.tools_box.setContentsMargins(0, 0, 0, 0)
  29. self.tools_frame.setLayout(self.tools_box)
  30. ## Title
  31. title_label = QtWidgets.QLabel("%s" % self.toolName)
  32. title_label.setStyleSheet("""
  33. QLabel
  34. {
  35. font-size: 16px;
  36. font-weight: bold;
  37. }
  38. """)
  39. self.tools_box.addWidget(title_label)
  40. ## Form Layout
  41. form_layout = QtWidgets.QFormLayout()
  42. self.tools_box.addLayout(form_layout)
  43. ## Object
  44. self.object_combo = QtWidgets.QComboBox()
  45. self.object_combo.setModel(self.app.collection)
  46. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  47. self.object_combo.setCurrentIndex(1)
  48. self.object_label = QtWidgets.QLabel("Gerber:")
  49. self.object_label.setToolTip(
  50. _("Gerber object to be cleared of excess copper. ")
  51. )
  52. e_lab_0 = QtWidgets.QLabel('')
  53. form_layout.addRow(self.object_label, self.object_combo)
  54. form_layout.addRow(e_lab_0)
  55. #### Tools ####
  56. self.tools_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Tools Table'))
  57. self.tools_table_label.setToolTip(
  58. _("Tools pool from which the algorithm\n"
  59. "will pick the ones used for copper clearing.")
  60. )
  61. self.tools_box.addWidget(self.tools_table_label)
  62. self.tools_table = FCTable()
  63. self.tools_box.addWidget(self.tools_table)
  64. self.tools_table.setColumnCount(4)
  65. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), 'TT', ''])
  66. self.tools_table.setColumnHidden(3, True)
  67. self.tools_table.setSortingEnabled(False)
  68. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  69. self.tools_table.horizontalHeaderItem(0).setToolTip(
  70. _("This is the Tool Number.\n"
  71. "Non copper clearing will start with the tool with the biggest \n"
  72. "diameter, continuing until there are no more tools.\n"
  73. "Only tools that create NCC clearing geometry will still be present\n"
  74. "in the resulting geometry. This is because with some tools\n"
  75. "this function will not be able to create painting geometry.")
  76. )
  77. self.tools_table.horizontalHeaderItem(1).setToolTip(
  78. _("Tool Diameter. It's value (in current FlatCAM units) \n"
  79. "is the cut width into the material."))
  80. self.tools_table.horizontalHeaderItem(2).setToolTip(
  81. _("The Tool Type (TT) can be:<BR>"
  82. "- <B>Circular</B> with 1 ... 4 teeth -> it is informative only. Being circular, <BR>"
  83. "the cut width in material is exactly the tool diameter.<BR>"
  84. "- <B>Ball</B> -> informative only and make reference to the Ball type endmill.<BR>"
  85. "- <B>V-Shape</B> -> it will disable de Z-Cut parameter in the resulting geometry UI form "
  86. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and "
  87. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such "
  88. "as the cut width into material will be equal with the value in the Tool Diameter "
  89. "column of this table.<BR>"
  90. "Choosing the <B>V-Shape</B> Tool Type automatically will select the Operation Type "
  91. "in the resulting geometry as Isolation."))
  92. self.empty_label = QtWidgets.QLabel('')
  93. self.tools_box.addWidget(self.empty_label)
  94. #### Add a new Tool ####
  95. hlay = QtWidgets.QHBoxLayout()
  96. self.tools_box.addLayout(hlay)
  97. self.addtool_entry_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Tool Dia'))
  98. self.addtool_entry_lbl.setToolTip(
  99. _("Diameter for the new tool to add in the Tool Table")
  100. )
  101. self.addtool_entry = FCEntry()
  102. # hlay.addWidget(self.addtool_label)
  103. # hlay.addStretch()
  104. hlay.addWidget(self.addtool_entry_lbl)
  105. hlay.addWidget(self.addtool_entry)
  106. grid2 = QtWidgets.QGridLayout()
  107. self.tools_box.addLayout(grid2)
  108. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  109. self.addtool_btn.setToolTip(
  110. _("Add a new tool to the Tool Table\n"
  111. "with the diameter specified above.")
  112. )
  113. # self.copytool_btn = QtWidgets.QPushButton('Copy')
  114. # self.copytool_btn.setToolTip(
  115. # "Copy a selection of tools in the Tool Table\n"
  116. # "by first selecting a row in the Tool Table."
  117. # )
  118. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  119. self.deltool_btn.setToolTip(
  120. _("Delete a selection of tools in the Tool Table\n"
  121. "by first selecting a row(s) in the Tool Table.")
  122. )
  123. grid2.addWidget(self.addtool_btn, 0, 0)
  124. # grid2.addWidget(self.copytool_btn, 0, 1)
  125. grid2.addWidget(self.deltool_btn, 0,2)
  126. self.empty_label_0 = QtWidgets.QLabel('')
  127. self.tools_box.addWidget(self.empty_label_0)
  128. grid3 = QtWidgets.QGridLayout()
  129. self.tools_box.addLayout(grid3)
  130. e_lab_1 = QtWidgets.QLabel('')
  131. grid3.addWidget(e_lab_1, 0, 0)
  132. nccoverlabel = QtWidgets.QLabel(_('Overlap:'))
  133. nccoverlabel.setToolTip(
  134. _("How much (fraction) of the tool width to overlap each tool pass.\n"
  135. "Example:\n"
  136. "A value here of 0.25 means 25% from the tool diameter found above.\n\n"
  137. "Adjust the value starting with lower values\n"
  138. "and increasing it if areas that should be cleared are still \n"
  139. "not cleared.\n"
  140. "Lower values = faster processing, faster execution on PCB.\n"
  141. "Higher values = slow processing and slow execution on CNC\n"
  142. "due of too many paths.")
  143. )
  144. grid3.addWidget(nccoverlabel, 1, 0)
  145. self.ncc_overlap_entry = FCEntry()
  146. grid3.addWidget(self.ncc_overlap_entry, 1, 1)
  147. nccmarginlabel = QtWidgets.QLabel(_('Margin:'))
  148. nccmarginlabel.setToolTip(
  149. _("Bounding box margin.")
  150. )
  151. grid3.addWidget(nccmarginlabel, 2, 0)
  152. self.ncc_margin_entry = FCEntry()
  153. grid3.addWidget(self.ncc_margin_entry, 2, 1)
  154. # Method
  155. methodlabel = QtWidgets.QLabel(_('Method:'))
  156. methodlabel.setToolTip(
  157. _("Algorithm for non-copper clearing:<BR>"
  158. "<B>Standard</B>: Fixed step inwards.<BR>"
  159. "<B>Seed-based</B>: Outwards from seed.<BR>"
  160. "<B>Line-based</B>: Parallel lines.")
  161. )
  162. grid3.addWidget(methodlabel, 3, 0)
  163. self.ncc_method_radio = RadioSet([
  164. {"label": "Standard", "value": "standard"},
  165. {"label": "Seed-based", "value": "seed"},
  166. {"label": "Straight lines", "value": "lines"}
  167. ], orientation='vertical', stretch=False)
  168. grid3.addWidget(self.ncc_method_radio, 3, 1)
  169. # Connect lines
  170. pathconnectlabel = QtWidgets.QLabel(_("Connect:"))
  171. pathconnectlabel.setToolTip(
  172. _("Draw lines between resulting\n"
  173. "segments to minimize tool lifts.")
  174. )
  175. grid3.addWidget(pathconnectlabel, 4, 0)
  176. self.ncc_connect_cb = FCCheckBox()
  177. grid3.addWidget(self.ncc_connect_cb, 4, 1)
  178. contourlabel = QtWidgets.QLabel(_("Contour:"))
  179. contourlabel.setToolTip(
  180. _("Cut around the perimeter of the polygon\n"
  181. "to trim rough edges.")
  182. )
  183. grid3.addWidget(contourlabel, 5, 0)
  184. self.ncc_contour_cb = FCCheckBox()
  185. grid3.addWidget(self.ncc_contour_cb, 5, 1)
  186. restlabel = QtWidgets.QLabel(_("Rest M.:"))
  187. restlabel.setToolTip(
  188. _("If checked, use 'rest machining'.\n"
  189. "Basically it will clear copper outside PCB features,\n"
  190. "using the biggest tool and continue with the next tools,\n"
  191. "from bigger to smaller, to clear areas of copper that\n"
  192. "could not be cleared by previous tool, until there is\n"
  193. "no more copper to clear or there are no more tools.\n"
  194. "If not checked, use the standard algorithm.")
  195. )
  196. grid3.addWidget(restlabel, 6, 0)
  197. self.ncc_rest_cb = FCCheckBox()
  198. grid3.addWidget(self.ncc_rest_cb, 6, 1)
  199. self.generate_ncc_button = QtWidgets.QPushButton(_('Generate Geometry'))
  200. self.generate_ncc_button.setToolTip(
  201. _("Create the Geometry Object\n"
  202. "for non-copper routing.")
  203. )
  204. self.tools_box.addWidget(self.generate_ncc_button)
  205. self.units = ''
  206. self.ncc_tools = {}
  207. self.tooluid = 0
  208. # store here the default data for Geometry Data
  209. self.default_data = {}
  210. self.obj_name = ""
  211. self.ncc_obj = None
  212. self.tools_box.addStretch()
  213. self.addtool_btn.clicked.connect(self.on_tool_add)
  214. self.deltool_btn.clicked.connect(self.on_tool_delete)
  215. self.generate_ncc_button.clicked.connect(self.on_ncc)
  216. def install(self, icon=None, separator=None, **kwargs):
  217. FlatCAMTool.install(self, icon, separator, shortcut='ALT+N', **kwargs)
  218. def run(self, toggle=True):
  219. self.app.report_usage("ToolNonCopperClear()")
  220. if toggle:
  221. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  222. if self.app.ui.splitter.sizes()[0] == 0:
  223. self.app.ui.splitter.setSizes([1, 1])
  224. else:
  225. try:
  226. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  227. self.app.ui.splitter.setSizes([0, 1])
  228. except AttributeError:
  229. pass
  230. else:
  231. if self.app.ui.splitter.sizes()[0] == 0:
  232. self.app.ui.splitter.setSizes([1, 1])
  233. FlatCAMTool.run(self)
  234. self.set_tool_ui()
  235. self.build_ui()
  236. self.app.ui.notebook.setTabText(2, _("NCC Tool"))
  237. def set_tool_ui(self):
  238. self.tools_frame.show()
  239. self.ncc_overlap_entry.set_value(self.app.defaults["tools_nccoverlap"])
  240. self.ncc_margin_entry.set_value(self.app.defaults["tools_nccmargin"])
  241. self.ncc_method_radio.set_value(self.app.defaults["tools_nccmethod"])
  242. self.ncc_connect_cb.set_value(self.app.defaults["tools_nccconnect"])
  243. self.ncc_contour_cb.set_value(self.app.defaults["tools_ncccontour"])
  244. self.ncc_rest_cb.set_value(self.app.defaults["tools_nccrest"])
  245. self.tools_table.setupContextMenu()
  246. self.tools_table.addContextMenu(
  247. "Add", lambda: self.on_tool_add(dia=None, muted=None), icon=QtGui.QIcon("share/plus16.png"))
  248. self.tools_table.addContextMenu(
  249. "Delete", lambda:
  250. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  251. # init the working variables
  252. self.default_data.clear()
  253. self.default_data.update({
  254. "name": '_ncc',
  255. "plot": self.app.defaults["geometry_plot"],
  256. "cutz": self.app.defaults["geometry_cutz"],
  257. "vtipdia": 0.1,
  258. "vtipangle": 30,
  259. "travelz": self.app.defaults["geometry_travelz"],
  260. "feedrate": self.app.defaults["geometry_feedrate"],
  261. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  262. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  263. "dwell": self.app.defaults["geometry_dwell"],
  264. "dwelltime": self.app.defaults["geometry_dwelltime"],
  265. "multidepth": self.app.defaults["geometry_multidepth"],
  266. "ppname_g": self.app.defaults["geometry_ppname_g"],
  267. "depthperpass": self.app.defaults["geometry_depthperpass"],
  268. "extracut": self.app.defaults["geometry_extracut"],
  269. "toolchange": self.app.defaults["geometry_toolchange"],
  270. "toolchangez": self.app.defaults["geometry_toolchangez"],
  271. "endz": self.app.defaults["geometry_endz"],
  272. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  273. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  274. "startz": self.app.defaults["geometry_startz"],
  275. "tooldia": self.app.defaults["tools_painttooldia"],
  276. "paintmargin": self.app.defaults["tools_paintmargin"],
  277. "paintmethod": self.app.defaults["tools_paintmethod"],
  278. "selectmethod": self.app.defaults["tools_selectmethod"],
  279. "pathconnect": self.app.defaults["tools_pathconnect"],
  280. "paintcontour": self.app.defaults["tools_paintcontour"],
  281. "paintoverlap": self.app.defaults["tools_paintoverlap"],
  282. "nccoverlap": self.app.defaults["tools_nccoverlap"],
  283. "nccmargin": self.app.defaults["tools_nccmargin"],
  284. "nccmethod": self.app.defaults["tools_nccmethod"],
  285. "nccconnect": self.app.defaults["tools_nccconnect"],
  286. "ncccontour": self.app.defaults["tools_ncccontour"],
  287. "nccrest": self.app.defaults["tools_nccrest"]
  288. })
  289. try:
  290. dias = [float(eval(dia)) for dia in self.app.defaults["tools_ncctools"].split(",")]
  291. except:
  292. log.error("At least one tool diameter needed. Verify in Edit -> Preferences -> TOOLS -> NCC Tools.")
  293. return
  294. self.tooluid = 0
  295. self.ncc_tools.clear()
  296. for tool_dia in dias:
  297. self.tooluid += 1
  298. self.ncc_tools.update({
  299. int(self.tooluid): {
  300. 'tooldia': float('%.4f' % tool_dia),
  301. 'offset': 'Path',
  302. 'offset_value': 0.0,
  303. 'type': 'Iso',
  304. 'tool_type': 'V',
  305. 'data': dict(self.default_data),
  306. 'solid_geometry': []
  307. }
  308. })
  309. self.obj_name = ""
  310. self.ncc_obj = None
  311. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  312. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  313. def build_ui(self):
  314. self.ui_disconnect()
  315. # updated units
  316. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  317. if self.units == "IN":
  318. self.addtool_entry.set_value(0.039)
  319. else:
  320. self.addtool_entry.set_value(1)
  321. sorted_tools = []
  322. for k, v in self.ncc_tools.items():
  323. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  324. sorted_tools.sort()
  325. n = len(sorted_tools)
  326. self.tools_table.setRowCount(n)
  327. tool_id = 0
  328. for tool_sorted in sorted_tools:
  329. for tooluid_key, tooluid_value in self.ncc_tools.items():
  330. if float('%.4f' % tooluid_value['tooldia']) == tool_sorted:
  331. tool_id += 1
  332. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  333. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  334. row_no = tool_id - 1
  335. self.tools_table.setItem(row_no, 0, id) # Tool name/id
  336. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  337. # There are no drill bits in MM with more than 3 decimals diameter
  338. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  339. if self.units == 'MM':
  340. dia = QtWidgets.QTableWidgetItem('%.2f' % tooluid_value['tooldia'])
  341. else:
  342. dia = QtWidgets.QTableWidgetItem('%.3f' % tooluid_value['tooldia'])
  343. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  344. tool_type_item = QtWidgets.QComboBox()
  345. for item in self.tool_type_item_options:
  346. tool_type_item.addItem(item)
  347. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  348. idx = tool_type_item.findText(tooluid_value['tool_type'])
  349. tool_type_item.setCurrentIndex(idx)
  350. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  351. self.tools_table.setItem(row_no, 1, dia) # Diameter
  352. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  353. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  354. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  355. # make the diameter column editable
  356. for row in range(tool_id):
  357. self.tools_table.item(row, 1).setFlags(
  358. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  359. # all the tools are selected by default
  360. self.tools_table.selectColumn(0)
  361. #
  362. self.tools_table.resizeColumnsToContents()
  363. self.tools_table.resizeRowsToContents()
  364. vertical_header = self.tools_table.verticalHeader()
  365. vertical_header.hide()
  366. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  367. horizontal_header = self.tools_table.horizontalHeader()
  368. horizontal_header.setMinimumSectionSize(10)
  369. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  370. horizontal_header.resizeSection(0, 20)
  371. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  372. # self.tools_table.setSortingEnabled(True)
  373. # sort by tool diameter
  374. # self.tools_table.sortItems(1)
  375. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  376. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  377. self.ui_connect()
  378. def ui_connect(self):
  379. self.tools_table.itemChanged.connect(self.on_tool_edit)
  380. def ui_disconnect(self):
  381. try:
  382. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  383. self.tools_table.itemChanged.disconnect(self.on_tool_edit)
  384. except:
  385. pass
  386. def on_tool_add(self, dia=None, muted=None):
  387. self.ui_disconnect()
  388. if dia:
  389. tool_dia = dia
  390. else:
  391. try:
  392. tool_dia = float(self.addtool_entry.get_value())
  393. except ValueError:
  394. # try to convert comma to decimal point. if it's still not working error message and return
  395. try:
  396. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  397. except ValueError:
  398. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  399. "use a number."))
  400. return
  401. if tool_dia is None:
  402. self.build_ui()
  403. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter to add, in Float format."))
  404. return
  405. if tool_dia == 0:
  406. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  407. return
  408. # construct a list of all 'tooluid' in the self.tools
  409. tool_uid_list = []
  410. for tooluid_key in self.ncc_tools:
  411. tool_uid_item = int(tooluid_key)
  412. tool_uid_list.append(tool_uid_item)
  413. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  414. if not tool_uid_list:
  415. max_uid = 0
  416. else:
  417. max_uid = max(tool_uid_list)
  418. self.tooluid = int(max_uid + 1)
  419. tool_dias = []
  420. for k, v in self.ncc_tools.items():
  421. for tool_v in v.keys():
  422. if tool_v == 'tooldia':
  423. tool_dias.append(float('%.4f' % v[tool_v]))
  424. if float('%.4f' % tool_dia) in tool_dias:
  425. if muted is None:
  426. self.app.inform.emit(_("[WARNING_NOTCL]Adding tool cancelled. Tool already in Tool Table."))
  427. self.tools_table.itemChanged.connect(self.on_tool_edit)
  428. return
  429. else:
  430. if muted is None:
  431. self.app.inform.emit(_("[success] New tool added to Tool Table."))
  432. self.ncc_tools.update({
  433. int(self.tooluid): {
  434. 'tooldia': float('%.4f' % tool_dia),
  435. 'offset': 'Path',
  436. 'offset_value': 0.0,
  437. 'type': 'Iso',
  438. 'tool_type': 'V',
  439. 'data': dict(self.default_data),
  440. 'solid_geometry': []
  441. }
  442. })
  443. self.build_ui()
  444. def on_tool_edit(self):
  445. self.ui_disconnect()
  446. tool_dias = []
  447. for k, v in self.ncc_tools.items():
  448. for tool_v in v.keys():
  449. if tool_v == 'tooldia':
  450. tool_dias.append(float('%.4f' % v[tool_v]))
  451. for row in range(self.tools_table.rowCount()):
  452. try:
  453. new_tool_dia = float(self.tools_table.item(row, 1).text())
  454. except ValueError:
  455. # try to convert comma to decimal point. if it's still not working error message and return
  456. try:
  457. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  458. except ValueError:
  459. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  460. "use a number."))
  461. return
  462. tooluid = int(self.tools_table.item(row, 3).text())
  463. # identify the tool that was edited and get it's tooluid
  464. if new_tool_dia not in tool_dias:
  465. self.ncc_tools[tooluid]['tooldia'] = new_tool_dia
  466. self.app.inform.emit(_("[success] Tool from Tool Table was edited."))
  467. self.build_ui()
  468. return
  469. else:
  470. # identify the old tool_dia and restore the text in tool table
  471. for k, v in self.ncc_tools.items():
  472. if k == tooluid:
  473. old_tool_dia = v['tooldia']
  474. break
  475. restore_dia_item = self.tools_table.item(row, 1)
  476. restore_dia_item.setText(str(old_tool_dia))
  477. self.app.inform.emit(_("[WARNING_NOTCL] Edit cancelled. New diameter value is already in the Tool Table."))
  478. self.build_ui()
  479. def on_tool_delete(self, rows_to_delete=None, all=None):
  480. self.ui_disconnect()
  481. deleted_tools_list = []
  482. if all:
  483. self.paint_tools.clear()
  484. self.build_ui()
  485. return
  486. if rows_to_delete:
  487. try:
  488. for row in rows_to_delete:
  489. tooluid_del = int(self.tools_table.item(row, 3).text())
  490. deleted_tools_list.append(tooluid_del)
  491. except TypeError:
  492. deleted_tools_list.append(rows_to_delete)
  493. for t in deleted_tools_list:
  494. self.ncc_tools.pop(t, None)
  495. self.build_ui()
  496. return
  497. try:
  498. if self.tools_table.selectedItems():
  499. for row_sel in self.tools_table.selectedItems():
  500. row = row_sel.row()
  501. if row < 0:
  502. continue
  503. tooluid_del = int(self.tools_table.item(row, 3).text())
  504. deleted_tools_list.append(tooluid_del)
  505. for t in deleted_tools_list:
  506. self.ncc_tools.pop(t, None)
  507. except AttributeError:
  508. self.app.inform.emit(_("[WARNING_NOTCL]Delete failed. Select a tool to delete."))
  509. return
  510. except Exception as e:
  511. log.debug(str(e))
  512. self.app.inform.emit(_("[success] Tool(s) deleted from Tool Table."))
  513. self.build_ui()
  514. def on_ncc(self):
  515. try:
  516. over = float(self.ncc_overlap_entry.get_value())
  517. except ValueError:
  518. # try to convert comma to decimal point. if it's still not working error message and return
  519. try:
  520. over = float(self.ncc_overlap_entry.get_value().replace(',', '.'))
  521. except ValueError:
  522. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  523. "use a number."))
  524. return
  525. over = over if over else self.app.defaults["tools_nccoverlap"]
  526. try:
  527. margin = float(self.ncc_margin_entry.get_value())
  528. except ValueError:
  529. # try to convert comma to decimal point. if it's still not working error message and return
  530. try:
  531. margin = float(self.ncc_margin_entry.get_value().replace(',', '.'))
  532. except ValueError:
  533. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  534. "use a number."))
  535. return
  536. margin = margin if margin else self.app.defaults["tools_nccmargin"]
  537. connect = self.ncc_connect_cb.get_value()
  538. connect = connect if connect else self.app.defaults["tools_nccconnect"]
  539. contour = self.ncc_contour_cb.get_value()
  540. contour = contour if contour else self.app.defaults["tools_ncccontour"]
  541. clearing_method = self.ncc_rest_cb.get_value()
  542. clearing_method = clearing_method if clearing_method else self.app.defaults["tools_nccrest"]
  543. pol_method = self.ncc_method_radio.get_value()
  544. pol_method = pol_method if pol_method else self.app.defaults["tools_nccmethod"]
  545. self.obj_name = self.object_combo.currentText()
  546. # Get source object.
  547. try:
  548. self.ncc_obj = self.app.collection.get_by_name(self.obj_name)
  549. except:
  550. self.app.inform.emit(_("[ERROR_NOTCL]Could not retrieve object: %s") % self.obj_name)
  551. return "Could not retrieve object: %s" % self.obj_name
  552. # Prepare non-copper polygons
  553. try:
  554. bounding_box = self.ncc_obj.solid_geometry.envelope.buffer(distance=margin, join_style=JOIN_STYLE.mitre)
  555. except AttributeError:
  556. self.app.inform.emit(_("[ERROR_NOTCL]No Gerber file available."))
  557. return
  558. # calculate the empty area by subtracting the solid_geometry from the object bounding box geometry
  559. empty = self.ncc_obj.get_empty_area(bounding_box)
  560. if type(empty) is Polygon:
  561. empty = MultiPolygon([empty])
  562. # clear non copper using standard algorithm
  563. if clearing_method == False:
  564. self.clear_non_copper(
  565. empty=empty,
  566. over=over,
  567. pol_method=pol_method,
  568. connect=connect,
  569. contour=contour
  570. )
  571. # clear non copper using rest machining algorithm
  572. else:
  573. self.clear_non_copper_rest(
  574. empty=empty,
  575. over=over,
  576. pol_method=pol_method,
  577. connect=connect,
  578. contour=contour
  579. )
  580. def clear_non_copper(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  581. name = outname if outname else self.obj_name + "_ncc"
  582. # Sort tools in descending order
  583. sorted_tools = []
  584. for k, v in self.ncc_tools.items():
  585. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  586. sorted_tools.sort(reverse=True)
  587. # Do job in background
  588. proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  589. def initialize(geo_obj, app_obj):
  590. assert isinstance(geo_obj, FlatCAMGeometry), \
  591. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  592. cleared_geo = []
  593. # Already cleared area
  594. cleared = MultiPolygon()
  595. # flag for polygons not cleared
  596. app_obj.poly_not_cleared = False
  597. # Generate area for each tool
  598. offset = sum(sorted_tools)
  599. current_uid = int(1)
  600. for tool in sorted_tools:
  601. self.app.inform.emit(_('[success] Non-Copper Clearing with ToolDia = %s started.') % str(tool))
  602. cleared_geo[:] = []
  603. # Get remaining tools offset
  604. offset -= (tool - 1e-12)
  605. # Area to clear
  606. area = empty.buffer(-offset)
  607. try:
  608. area = area.difference(cleared)
  609. except:
  610. continue
  611. # Transform area to MultiPolygon
  612. if type(area) is Polygon:
  613. area = MultiPolygon([area])
  614. if area.geoms:
  615. if len(area.geoms) > 0:
  616. for p in area.geoms:
  617. try:
  618. if pol_method == 'standard':
  619. cp = self.clear_polygon(p, tool, self.app.defaults["gerber_circle_steps"],
  620. overlap=over, contour=contour, connect=connect)
  621. elif pol_method == 'seed':
  622. cp = self.clear_polygon2(p, tool, self.app.defaults["gerber_circle_steps"],
  623. overlap=over, contour=contour, connect=connect)
  624. else:
  625. cp = self.clear_polygon3(p, tool, self.app.defaults["gerber_circle_steps"],
  626. overlap=over, contour=contour, connect=connect)
  627. if cp:
  628. cleared_geo += list(cp.get_objects())
  629. except:
  630. log.warning("Polygon can not be cleared.")
  631. app_obj.poly_not_cleared = True
  632. continue
  633. # check if there is a geometry at all in the cleared geometry
  634. if cleared_geo:
  635. # Overall cleared area
  636. cleared = empty.buffer(-offset * (1 + over)).buffer(-tool / 1.999999).buffer(
  637. tool / 1.999999)
  638. # clean-up cleared geo
  639. cleared = cleared.buffer(0)
  640. # find the tooluid associated with the current tool_dia so we know where to add the tool
  641. # solid_geometry
  642. for k, v in self.ncc_tools.items():
  643. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  644. current_uid = int(k)
  645. # add the solid_geometry to the current too in self.paint_tools dictionary
  646. # and then reset the temporary list that stored that solid_geometry
  647. v['solid_geometry'] = deepcopy(cleared_geo)
  648. v['data']['name'] = name
  649. break
  650. geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  651. else:
  652. log.debug("There are no geometries in the cleared polygon.")
  653. geo_obj.options["cnctooldia"] = tool
  654. geo_obj.multigeo = True
  655. def job_thread(app_obj):
  656. try:
  657. app_obj.new_object("geometry", name, initialize)
  658. except Exception as e:
  659. proc.done()
  660. self.app.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper() --> %s') % str(e))
  661. return
  662. proc.done()
  663. if app_obj.poly_not_cleared is False:
  664. self.app.inform.emit(_('[success] NCC Tool finished.'))
  665. else:
  666. self.app.inform.emit(_('[WARNING_NOTCL] NCC Tool finished but some PCB features could not be cleared. '
  667. 'Check the result.'))
  668. # reset the variable for next use
  669. app_obj.poly_not_cleared = False
  670. # focus on Selected Tab
  671. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  672. self.tools_frame.hide()
  673. self.app.ui.notebook.setTabText(2, _("Tools"))
  674. # Promise object with the new name
  675. self.app.collection.promise(name)
  676. # Background
  677. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  678. # clear copper with 'rest-machining' algorithm
  679. def clear_non_copper_rest(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  680. name = outname if outname is not None else self.obj_name + "_ncc_rm"
  681. # Sort tools in descending order
  682. sorted_tools = []
  683. for k, v in self.ncc_tools.items():
  684. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  685. sorted_tools.sort(reverse=True)
  686. # Do job in background
  687. proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  688. def initialize_rm(geo_obj, app_obj):
  689. assert isinstance(geo_obj, FlatCAMGeometry), \
  690. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  691. cleared_geo = []
  692. cleared_by_last_tool = []
  693. rest_geo = []
  694. current_uid = 1
  695. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  696. app_obj.poly_not_cleared = True
  697. area = empty.buffer(0)
  698. # Generate area for each tool
  699. while sorted_tools:
  700. tool = sorted_tools.pop(0)
  701. self.app.inform.emit(_('[success] Non-Copper Rest Clearing with ToolDia = %s started.') % str(tool))
  702. tool_used = tool - 1e-12
  703. cleared_geo[:] = []
  704. # Area to clear
  705. for poly in cleared_by_last_tool:
  706. try:
  707. area = area.difference(poly)
  708. except:
  709. pass
  710. cleared_by_last_tool[:] = []
  711. # Transform area to MultiPolygon
  712. if type(area) is Polygon:
  713. area = MultiPolygon([area])
  714. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  715. # and rest_geo it's a list
  716. allparts = [p.buffer(0) for p in area.geoms]
  717. allparts += deepcopy(rest_geo)
  718. rest_geo[:] = []
  719. area = MultiPolygon(deepcopy(allparts))
  720. allparts[:] = []
  721. if area.geoms:
  722. if len(area.geoms) > 0:
  723. for p in area.geoms:
  724. try:
  725. if pol_method == 'standard':
  726. cp = self.clear_polygon(p, tool_used, self.app.defaults["gerber_circle_steps"],
  727. overlap=over, contour=contour, connect=connect)
  728. elif pol_method == 'seed':
  729. cp = self.clear_polygon2(p, tool_used,
  730. self.app.defaults["gerber_circle_steps"],
  731. overlap=over, contour=contour, connect=connect)
  732. else:
  733. cp = self.clear_polygon3(p, tool_used,
  734. self.app.defaults["gerber_circle_steps"],
  735. overlap=over, contour=contour, connect=connect)
  736. cleared_geo.append(list(cp.get_objects()))
  737. except:
  738. log.warning("Polygon can't be cleared.")
  739. # this polygon should be added to a list and then try clear it with a smaller tool
  740. rest_geo.append(p)
  741. # check if there is a geometry at all in the cleared geometry
  742. if cleared_geo:
  743. # Overall cleared area
  744. cleared_area = list(self.flatten_list(cleared_geo))
  745. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  746. # for p in cleared_area])
  747. # here we store the poly's already processed in the original geometry by the current tool
  748. # into cleared_by_last_tool list
  749. # this will be sustracted from the original geometry_to_be_cleared and make data for
  750. # the next tool
  751. buffer_value = tool_used / 2
  752. for p in cleared_area:
  753. poly = p.buffer(buffer_value)
  754. cleared_by_last_tool.append(poly)
  755. # find the tooluid associated with the current tool_dia so we know
  756. # where to add the tool solid_geometry
  757. for k, v in self.ncc_tools.items():
  758. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  759. current_uid = int(k)
  760. # add the solid_geometry to the current too in self.paint_tools dictionary
  761. # and then reset the temporary list that stored that solid_geometry
  762. v['solid_geometry'] = deepcopy(cleared_area)
  763. v['data']['name'] = name
  764. cleared_area[:] = []
  765. break
  766. geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  767. else:
  768. log.debug("There are no geometries in the cleared polygon.")
  769. geo_obj.multigeo = True
  770. geo_obj.options["cnctooldia"] = tool
  771. # check to see if geo_obj.tools is empty
  772. # it will be updated only if there is a solid_geometry for tools
  773. if geo_obj.tools:
  774. return
  775. else:
  776. # I will use this variable for this purpose although it was meant for something else
  777. # signal that we have no geo in the object therefore don't create it
  778. app_obj.poly_not_cleared = False
  779. return "fail"
  780. def job_thread(app_obj):
  781. try:
  782. app_obj.new_object("geometry", name, initialize_rm)
  783. except Exception as e:
  784. proc.done()
  785. self.app.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper_rest() --> %s') % str(e))
  786. return
  787. if app_obj.poly_not_cleared is True:
  788. self.app.inform.emit('[success] NCC Tool finished.')
  789. # focus on Selected Tab
  790. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  791. else:
  792. self.app.inform.emit(_('[ERROR_NOTCL] NCC Tool finished but could not clear the object '
  793. 'with current settings.'))
  794. # focus on Project Tab
  795. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  796. proc.done()
  797. # reset the variable for next use
  798. app_obj.poly_not_cleared = False
  799. self.tools_frame.hide()
  800. self.app.ui.notebook.setTabText(2, "Tools")
  801. # Promise object with the new name
  802. self.app.collection.promise(name)
  803. # Background
  804. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  805. def reset_fields(self):
  806. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))