ToolNonCopperClear.py 41 KB

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