ToolNonCopperClear.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  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. 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. FlatCAMTool.run(self)
  221. self.set_tool_ui()
  222. self.build_ui()
  223. self.app.ui.notebook.setTabText(2, _("NCC Tool"))
  224. def set_tool_ui(self):
  225. self.tools_frame.show()
  226. self.ncc_overlap_entry.set_value(self.app.defaults["tools_nccoverlap"])
  227. self.ncc_margin_entry.set_value(self.app.defaults["tools_nccmargin"])
  228. self.ncc_method_radio.set_value(self.app.defaults["tools_nccmethod"])
  229. self.ncc_connect_cb.set_value(self.app.defaults["tools_nccconnect"])
  230. self.ncc_contour_cb.set_value(self.app.defaults["tools_ncccontour"])
  231. self.ncc_rest_cb.set_value(self.app.defaults["tools_nccrest"])
  232. self.tools_table.setupContextMenu()
  233. self.tools_table.addContextMenu(
  234. "Add", lambda: self.on_tool_add(dia=None, muted=None), icon=QtGui.QIcon("share/plus16.png"))
  235. self.tools_table.addContextMenu(
  236. "Delete", lambda:
  237. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  238. # init the working variables
  239. self.default_data.clear()
  240. self.default_data.update({
  241. "name": '_ncc',
  242. "plot": self.app.defaults["geometry_plot"],
  243. "cutz": self.app.defaults["geometry_cutz"],
  244. "vtipdia": 0.1,
  245. "vtipangle": 30,
  246. "travelz": self.app.defaults["geometry_travelz"],
  247. "feedrate": self.app.defaults["geometry_feedrate"],
  248. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  249. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  250. "dwell": self.app.defaults["geometry_dwell"],
  251. "dwelltime": self.app.defaults["geometry_dwelltime"],
  252. "multidepth": self.app.defaults["geometry_multidepth"],
  253. "ppname_g": self.app.defaults["geometry_ppname_g"],
  254. "depthperpass": self.app.defaults["geometry_depthperpass"],
  255. "extracut": self.app.defaults["geometry_extracut"],
  256. "toolchange": self.app.defaults["geometry_toolchange"],
  257. "toolchangez": self.app.defaults["geometry_toolchangez"],
  258. "endz": self.app.defaults["geometry_endz"],
  259. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  260. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  261. "startz": self.app.defaults["geometry_startz"],
  262. "tooldia": self.app.defaults["tools_painttooldia"],
  263. "paintmargin": self.app.defaults["tools_paintmargin"],
  264. "paintmethod": self.app.defaults["tools_paintmethod"],
  265. "selectmethod": self.app.defaults["tools_selectmethod"],
  266. "pathconnect": self.app.defaults["tools_pathconnect"],
  267. "paintcontour": self.app.defaults["tools_paintcontour"],
  268. "paintoverlap": self.app.defaults["tools_paintoverlap"],
  269. "nccoverlap": self.app.defaults["tools_nccoverlap"],
  270. "nccmargin": self.app.defaults["tools_nccmargin"],
  271. "nccmethod": self.app.defaults["tools_nccmethod"],
  272. "nccconnect": self.app.defaults["tools_nccconnect"],
  273. "ncccontour": self.app.defaults["tools_ncccontour"],
  274. "nccrest": self.app.defaults["tools_nccrest"]
  275. })
  276. try:
  277. dias = [float(eval(dia)) for dia in self.app.defaults["tools_ncctools"].split(",")]
  278. except:
  279. log.error("At least one tool diameter needed. Verify in Edit -> Preferences -> TOOLS -> NCC Tools.")
  280. return
  281. self.tooluid = 0
  282. self.ncc_tools.clear()
  283. for tool_dia in dias:
  284. self.tooluid += 1
  285. self.ncc_tools.update({
  286. int(self.tooluid): {
  287. 'tooldia': float('%.4f' % tool_dia),
  288. 'offset': 'Path',
  289. 'offset_value': 0.0,
  290. 'type': 'Iso',
  291. 'tool_type': 'V',
  292. 'data': dict(self.default_data),
  293. 'solid_geometry': []
  294. }
  295. })
  296. self.obj_name = ""
  297. self.ncc_obj = None
  298. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  299. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  300. def build_ui(self):
  301. self.ui_disconnect()
  302. # updated units
  303. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  304. if self.units == "IN":
  305. self.addtool_entry.set_value(0.039)
  306. else:
  307. self.addtool_entry.set_value(1)
  308. sorted_tools = []
  309. for k, v in self.ncc_tools.items():
  310. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  311. sorted_tools.sort()
  312. n = len(sorted_tools)
  313. self.tools_table.setRowCount(n)
  314. tool_id = 0
  315. for tool_sorted in sorted_tools:
  316. for tooluid_key, tooluid_value in self.ncc_tools.items():
  317. if float('%.4f' % tooluid_value['tooldia']) == tool_sorted:
  318. tool_id += 1
  319. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  320. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  321. row_no = tool_id - 1
  322. self.tools_table.setItem(row_no, 0, id) # Tool name/id
  323. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  324. # There are no drill bits in MM with more than 3 decimals diameter
  325. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  326. if self.units == 'MM':
  327. dia = QtWidgets.QTableWidgetItem('%.2f' % tooluid_value['tooldia'])
  328. else:
  329. dia = QtWidgets.QTableWidgetItem('%.3f' % tooluid_value['tooldia'])
  330. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  331. tool_type_item = QtWidgets.QComboBox()
  332. for item in self.tool_type_item_options:
  333. tool_type_item.addItem(item)
  334. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  335. idx = tool_type_item.findText(tooluid_value['tool_type'])
  336. tool_type_item.setCurrentIndex(idx)
  337. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  338. self.tools_table.setItem(row_no, 1, dia) # Diameter
  339. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  340. ### REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  341. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  342. # make the diameter column editable
  343. for row in range(tool_id):
  344. self.tools_table.item(row, 1).setFlags(
  345. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  346. # all the tools are selected by default
  347. self.tools_table.selectColumn(0)
  348. #
  349. self.tools_table.resizeColumnsToContents()
  350. self.tools_table.resizeRowsToContents()
  351. vertical_header = self.tools_table.verticalHeader()
  352. vertical_header.hide()
  353. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  354. horizontal_header = self.tools_table.horizontalHeader()
  355. horizontal_header.setMinimumSectionSize(10)
  356. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  357. horizontal_header.resizeSection(0, 20)
  358. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  359. # self.tools_table.setSortingEnabled(True)
  360. # sort by tool diameter
  361. # self.tools_table.sortItems(1)
  362. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  363. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  364. self.ui_connect()
  365. def ui_connect(self):
  366. self.tools_table.itemChanged.connect(self.on_tool_edit)
  367. def ui_disconnect(self):
  368. try:
  369. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  370. self.tools_table.itemChanged.disconnect(self.on_tool_edit)
  371. except:
  372. pass
  373. def on_tool_add(self, dia=None, muted=None):
  374. self.ui_disconnect()
  375. if dia:
  376. tool_dia = dia
  377. else:
  378. try:
  379. tool_dia = float(self.addtool_entry.get_value())
  380. except ValueError:
  381. # try to convert comma to decimal point. if it's still not working error message and return
  382. try:
  383. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  384. except ValueError:
  385. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  386. "use a number."))
  387. return
  388. if tool_dia is None:
  389. self.build_ui()
  390. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter to add, in Float format."))
  391. return
  392. if tool_dia == 0:
  393. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  394. return
  395. # construct a list of all 'tooluid' in the self.tools
  396. tool_uid_list = []
  397. for tooluid_key in self.ncc_tools:
  398. tool_uid_item = int(tooluid_key)
  399. tool_uid_list.append(tool_uid_item)
  400. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  401. if not tool_uid_list:
  402. max_uid = 0
  403. else:
  404. max_uid = max(tool_uid_list)
  405. self.tooluid = int(max_uid + 1)
  406. tool_dias = []
  407. for k, v in self.ncc_tools.items():
  408. for tool_v in v.keys():
  409. if tool_v == 'tooldia':
  410. tool_dias.append(float('%.4f' % v[tool_v]))
  411. if float('%.4f' % tool_dia) in tool_dias:
  412. if muted is None:
  413. self.app.inform.emit(_("[WARNING_NOTCL]Adding tool cancelled. Tool already in Tool Table."))
  414. self.tools_table.itemChanged.connect(self.on_tool_edit)
  415. return
  416. else:
  417. if muted is None:
  418. self.app.inform.emit(_("[success] New tool added to Tool Table."))
  419. self.ncc_tools.update({
  420. int(self.tooluid): {
  421. 'tooldia': float('%.4f' % tool_dia),
  422. 'offset': 'Path',
  423. 'offset_value': 0.0,
  424. 'type': 'Iso',
  425. 'tool_type': 'V',
  426. 'data': dict(self.default_data),
  427. 'solid_geometry': []
  428. }
  429. })
  430. self.build_ui()
  431. def on_tool_edit(self):
  432. self.ui_disconnect()
  433. tool_dias = []
  434. for k, v in self.ncc_tools.items():
  435. for tool_v in v.keys():
  436. if tool_v == 'tooldia':
  437. tool_dias.append(float('%.4f' % v[tool_v]))
  438. for row in range(self.tools_table.rowCount()):
  439. try:
  440. new_tool_dia = float(self.tools_table.item(row, 1).text())
  441. except ValueError:
  442. # try to convert comma to decimal point. if it's still not working error message and return
  443. try:
  444. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  445. except ValueError:
  446. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  447. "use a number."))
  448. return
  449. tooluid = int(self.tools_table.item(row, 3).text())
  450. # identify the tool that was edited and get it's tooluid
  451. if new_tool_dia not in tool_dias:
  452. self.ncc_tools[tooluid]['tooldia'] = new_tool_dia
  453. self.app.inform.emit(_("[success] Tool from Tool Table was edited."))
  454. self.build_ui()
  455. return
  456. else:
  457. # identify the old tool_dia and restore the text in tool table
  458. for k, v in self.ncc_tools.items():
  459. if k == tooluid:
  460. old_tool_dia = v['tooldia']
  461. break
  462. restore_dia_item = self.tools_table.item(row, 1)
  463. restore_dia_item.setText(str(old_tool_dia))
  464. self.app.inform.emit(_("[WARNING_NOTCL] Edit cancelled. New diameter value is already in the Tool Table."))
  465. self.build_ui()
  466. def on_tool_delete(self, rows_to_delete=None, all=None):
  467. self.ui_disconnect()
  468. deleted_tools_list = []
  469. if all:
  470. self.paint_tools.clear()
  471. self.build_ui()
  472. return
  473. if rows_to_delete:
  474. try:
  475. for row in rows_to_delete:
  476. tooluid_del = int(self.tools_table.item(row, 3).text())
  477. deleted_tools_list.append(tooluid_del)
  478. except TypeError:
  479. deleted_tools_list.append(rows_to_delete)
  480. for t in deleted_tools_list:
  481. self.ncc_tools.pop(t, None)
  482. self.build_ui()
  483. return
  484. try:
  485. if self.tools_table.selectedItems():
  486. for row_sel in self.tools_table.selectedItems():
  487. row = row_sel.row()
  488. if row < 0:
  489. continue
  490. tooluid_del = int(self.tools_table.item(row, 3).text())
  491. deleted_tools_list.append(tooluid_del)
  492. for t in deleted_tools_list:
  493. self.ncc_tools.pop(t, None)
  494. except AttributeError:
  495. self.app.inform.emit(_("[WARNING_NOTCL]Delete failed. Select a tool to delete."))
  496. return
  497. except Exception as e:
  498. log.debug(str(e))
  499. self.app.inform.emit(_("[success] Tool(s) deleted from Tool Table."))
  500. self.build_ui()
  501. def on_ncc(self):
  502. try:
  503. over = float(self.ncc_overlap_entry.get_value())
  504. except ValueError:
  505. # try to convert comma to decimal point. if it's still not working error message and return
  506. try:
  507. over = float(self.ncc_overlap_entry.get_value().replace(',', '.'))
  508. except ValueError:
  509. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  510. "use a number."))
  511. return
  512. over = over if over else self.app.defaults["tools_nccoverlap"]
  513. try:
  514. margin = float(self.ncc_margin_entry.get_value())
  515. except ValueError:
  516. # try to convert comma to decimal point. if it's still not working error message and return
  517. try:
  518. margin = float(self.ncc_margin_entry.get_value().replace(',', '.'))
  519. except ValueError:
  520. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  521. "use a number."))
  522. return
  523. margin = margin if margin else self.app.defaults["tools_nccmargin"]
  524. connect = self.ncc_connect_cb.get_value()
  525. connect = connect if connect else self.app.defaults["tools_nccconnect"]
  526. contour = self.ncc_contour_cb.get_value()
  527. contour = contour if contour else self.app.defaults["tools_ncccontour"]
  528. clearing_method = self.ncc_rest_cb.get_value()
  529. clearing_method = clearing_method if clearing_method else self.app.defaults["tools_nccrest"]
  530. pol_method = self.ncc_method_radio.get_value()
  531. pol_method = pol_method if pol_method else self.app.defaults["tools_nccmethod"]
  532. self.obj_name = self.object_combo.currentText()
  533. # Get source object.
  534. try:
  535. self.ncc_obj = self.app.collection.get_by_name(self.obj_name)
  536. except:
  537. self.app.inform.emit(_("[ERROR_NOTCL]Could not retrieve object: %s") % self.obj_name)
  538. return "Could not retrieve object: %s" % self.obj_name
  539. # Prepare non-copper polygons
  540. try:
  541. bounding_box = self.ncc_obj.solid_geometry.envelope.buffer(distance=margin, join_style=JOIN_STYLE.mitre)
  542. except AttributeError:
  543. self.app.inform.emit(_("[ERROR_NOTCL]No Gerber file available."))
  544. return
  545. # calculate the empty area by subtracting the solid_geometry from the object bounding box geometry
  546. empty = self.ncc_obj.get_empty_area(bounding_box)
  547. if type(empty) is Polygon:
  548. empty = MultiPolygon([empty])
  549. # clear non copper using standard algorithm
  550. if clearing_method == False:
  551. self.clear_non_copper(
  552. empty=empty,
  553. over=over,
  554. pol_method=pol_method,
  555. connect=connect,
  556. contour=contour
  557. )
  558. # clear non copper using rest machining algorithm
  559. else:
  560. self.clear_non_copper_rest(
  561. empty=empty,
  562. over=over,
  563. pol_method=pol_method,
  564. connect=connect,
  565. contour=contour
  566. )
  567. def clear_non_copper(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  568. name = outname if outname else self.obj_name + "_ncc"
  569. # Sort tools in descending order
  570. sorted_tools = []
  571. for k, v in self.ncc_tools.items():
  572. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  573. sorted_tools.sort(reverse=True)
  574. # Do job in background
  575. proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  576. def initialize(geo_obj, app_obj):
  577. assert isinstance(geo_obj, FlatCAMGeometry), \
  578. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  579. cleared_geo = []
  580. # Already cleared area
  581. cleared = MultiPolygon()
  582. # flag for polygons not cleared
  583. app_obj.poly_not_cleared = False
  584. # Generate area for each tool
  585. offset = sum(sorted_tools)
  586. current_uid = int(1)
  587. for tool in sorted_tools:
  588. self.app.inform.emit(_('[success] Non-Copper Clearing with ToolDia = %s started.') % str(tool))
  589. cleared_geo[:] = []
  590. # Get remaining tools offset
  591. offset -= (tool - 1e-12)
  592. # Area to clear
  593. area = empty.buffer(-offset)
  594. try:
  595. area = area.difference(cleared)
  596. except:
  597. continue
  598. # Transform area to MultiPolygon
  599. if type(area) is Polygon:
  600. area = MultiPolygon([area])
  601. if area.geoms:
  602. if len(area.geoms) > 0:
  603. for p in area.geoms:
  604. try:
  605. if pol_method == 'standard':
  606. cp = self.clear_polygon(p, tool, self.app.defaults["gerber_circle_steps"],
  607. overlap=over, contour=contour, connect=connect)
  608. elif pol_method == 'seed':
  609. cp = self.clear_polygon2(p, tool, self.app.defaults["gerber_circle_steps"],
  610. overlap=over, contour=contour, connect=connect)
  611. else:
  612. cp = self.clear_polygon3(p, tool, self.app.defaults["gerber_circle_steps"],
  613. overlap=over, contour=contour, connect=connect)
  614. if cp:
  615. cleared_geo += list(cp.get_objects())
  616. except:
  617. log.warning("Polygon can not be cleared.")
  618. app_obj.poly_not_cleared = True
  619. continue
  620. # check if there is a geometry at all in the cleared geometry
  621. if cleared_geo:
  622. # Overall cleared area
  623. cleared = empty.buffer(-offset * (1 + over)).buffer(-tool / 1.999999).buffer(
  624. tool / 1.999999)
  625. # clean-up cleared geo
  626. cleared = cleared.buffer(0)
  627. # find the tooluid associated with the current tool_dia so we know where to add the tool
  628. # solid_geometry
  629. for k, v in self.ncc_tools.items():
  630. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  631. current_uid = int(k)
  632. # add the solid_geometry to the current too in self.paint_tools dictionary
  633. # and then reset the temporary list that stored that solid_geometry
  634. v['solid_geometry'] = deepcopy(cleared_geo)
  635. v['data']['name'] = name
  636. break
  637. geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  638. else:
  639. log.debug("There are no geometries in the cleared polygon.")
  640. geo_obj.options["cnctooldia"] = tool
  641. geo_obj.multigeo = True
  642. def job_thread(app_obj):
  643. try:
  644. app_obj.new_object("geometry", name, initialize)
  645. except Exception as e:
  646. proc.done()
  647. self.app.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper() --> %s') % str(e))
  648. return
  649. proc.done()
  650. if app_obj.poly_not_cleared is False:
  651. self.app.inform.emit(_('[success] NCC Tool finished.'))
  652. else:
  653. self.app.inform.emit(_('[WARNING_NOTCL] NCC Tool finished but some PCB features could not be cleared. '
  654. 'Check the result.'))
  655. # reset the variable for next use
  656. app_obj.poly_not_cleared = False
  657. # focus on Selected Tab
  658. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  659. self.tools_frame.hide()
  660. self.app.ui.notebook.setTabText(2, _("Tools"))
  661. # Promise object with the new name
  662. self.app.collection.promise(name)
  663. # Background
  664. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  665. # clear copper with 'rest-machining' algorithm
  666. def clear_non_copper_rest(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  667. name = outname if outname is not None else self.obj_name + "_ncc_rm"
  668. # Sort tools in descending order
  669. sorted_tools = []
  670. for k, v in self.ncc_tools.items():
  671. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  672. sorted_tools.sort(reverse=True)
  673. # Do job in background
  674. proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  675. def initialize_rm(geo_obj, app_obj):
  676. assert isinstance(geo_obj, FlatCAMGeometry), \
  677. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  678. cleared_geo = []
  679. cleared_by_last_tool = []
  680. rest_geo = []
  681. current_uid = 1
  682. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  683. app_obj.poly_not_cleared = True
  684. area = empty.buffer(0)
  685. # Generate area for each tool
  686. while sorted_tools:
  687. tool = sorted_tools.pop(0)
  688. self.app.inform.emit(_('[success] Non-Copper Rest Clearing with ToolDia = %s started.') % str(tool))
  689. tool_used = tool - 1e-12
  690. cleared_geo[:] = []
  691. # Area to clear
  692. for poly in cleared_by_last_tool:
  693. try:
  694. area = area.difference(poly)
  695. except:
  696. pass
  697. cleared_by_last_tool[:] = []
  698. # Transform area to MultiPolygon
  699. if type(area) is Polygon:
  700. area = MultiPolygon([area])
  701. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  702. # and rest_geo it's a list
  703. allparts = [p.buffer(0) for p in area.geoms]
  704. allparts += deepcopy(rest_geo)
  705. rest_geo[:] = []
  706. area = MultiPolygon(deepcopy(allparts))
  707. allparts[:] = []
  708. if area.geoms:
  709. if len(area.geoms) > 0:
  710. for p in area.geoms:
  711. try:
  712. if pol_method == 'standard':
  713. cp = self.clear_polygon(p, tool_used, self.app.defaults["gerber_circle_steps"],
  714. overlap=over, contour=contour, connect=connect)
  715. elif pol_method == 'seed':
  716. cp = self.clear_polygon2(p, tool_used,
  717. self.app.defaults["gerber_circle_steps"],
  718. overlap=over, contour=contour, connect=connect)
  719. else:
  720. cp = self.clear_polygon3(p, tool_used,
  721. self.app.defaults["gerber_circle_steps"],
  722. overlap=over, contour=contour, connect=connect)
  723. cleared_geo.append(list(cp.get_objects()))
  724. except:
  725. log.warning("Polygon can't be cleared.")
  726. # this polygon should be added to a list and then try clear it with a smaller tool
  727. rest_geo.append(p)
  728. # check if there is a geometry at all in the cleared geometry
  729. if cleared_geo:
  730. # Overall cleared area
  731. cleared_area = list(self.flatten_list(cleared_geo))
  732. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  733. # for p in cleared_area])
  734. # here we store the poly's already processed in the original geometry by the current tool
  735. # into cleared_by_last_tool list
  736. # this will be sustracted from the original geometry_to_be_cleared and make data for
  737. # the next tool
  738. buffer_value = tool_used / 2
  739. for p in cleared_area:
  740. poly = p.buffer(buffer_value)
  741. cleared_by_last_tool.append(poly)
  742. # find the tooluid associated with the current tool_dia so we know
  743. # where to add the tool solid_geometry
  744. for k, v in self.ncc_tools.items():
  745. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  746. current_uid = int(k)
  747. # add the solid_geometry to the current too in self.paint_tools dictionary
  748. # and then reset the temporary list that stored that solid_geometry
  749. v['solid_geometry'] = deepcopy(cleared_area)
  750. v['data']['name'] = name
  751. cleared_area[:] = []
  752. break
  753. geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  754. else:
  755. log.debug("There are no geometries in the cleared polygon.")
  756. geo_obj.multigeo = True
  757. geo_obj.options["cnctooldia"] = tool
  758. # check to see if geo_obj.tools is empty
  759. # it will be updated only if there is a solid_geometry for tools
  760. if geo_obj.tools:
  761. return
  762. else:
  763. # I will use this variable for this purpose although it was meant for something else
  764. # signal that we have no geo in the object therefore don't create it
  765. app_obj.poly_not_cleared = False
  766. return "fail"
  767. def job_thread(app_obj):
  768. try:
  769. app_obj.new_object("geometry", name, initialize_rm)
  770. except Exception as e:
  771. proc.done()
  772. self.app.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper_rest() --> %s') % str(e))
  773. return
  774. if app_obj.poly_not_cleared is True:
  775. self.app.inform.emit('[success] NCC Tool finished.')
  776. # focus on Selected Tab
  777. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  778. else:
  779. self.app.inform.emit(_('[ERROR_NOTCL] NCC Tool finished but could not clear the object '
  780. 'with current settings.'))
  781. # focus on Project Tab
  782. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  783. proc.done()
  784. # reset the variable for next use
  785. app_obj.poly_not_cleared = False
  786. self.tools_frame.hide()
  787. self.app.ui.notebook.setTabText(2, "Tools")
  788. # Promise object with the new name
  789. self.app.collection.promise(name)
  790. # Background
  791. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  792. def reset_fields(self):
  793. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))