ToolPaint.py 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280
  1. # ########################################################## ##
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # File Modified: 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 gettext
  12. import FlatCAMTranslation as fcTranslate
  13. import builtins
  14. fcTranslate.apply_language('strings')
  15. if '_' not in builtins.__dict__:
  16. _ = gettext.gettext
  17. class ToolPaint(FlatCAMTool, Gerber):
  18. toolName = _("Paint Area")
  19. def __init__(self, app):
  20. self.app = app
  21. FlatCAMTool.__init__(self, app)
  22. Geometry.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  23. # ## Title
  24. title_label = QtWidgets.QLabel("%s" % self.toolName)
  25. title_label.setStyleSheet("""
  26. QLabel
  27. {
  28. font-size: 16px;
  29. font-weight: bold;
  30. }
  31. """)
  32. self.layout.addWidget(title_label)
  33. self.tools_frame = QtWidgets.QFrame()
  34. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  35. self.layout.addWidget(self.tools_frame)
  36. self.tools_box = QtWidgets.QVBoxLayout()
  37. self.tools_box.setContentsMargins(0, 0, 0, 0)
  38. self.tools_frame.setLayout(self.tools_box)
  39. # ## Form Layout
  40. form_layout = QtWidgets.QFormLayout()
  41. self.tools_box.addLayout(form_layout)
  42. # ## Object
  43. self.object_combo = QtWidgets.QComboBox()
  44. self.object_combo.setModel(self.app.collection)
  45. self.object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  46. self.object_combo.setCurrentIndex(1)
  47. self.object_label = QtWidgets.QLabel(_("Geometry:"))
  48. self.object_label.setToolTip(
  49. _("Geometry object to be painted. ")
  50. )
  51. e_lab_0 = QtWidgets.QLabel('')
  52. form_layout.addRow(self.object_label, self.object_combo)
  53. form_layout.addRow(e_lab_0)
  54. # ### Tools ## ##
  55. self.tools_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Tools Table'))
  56. self.tools_table_label.setToolTip(
  57. _("Tools pool from which the algorithm\n"
  58. "will pick the ones used for painting.")
  59. )
  60. self.tools_box.addWidget(self.tools_table_label)
  61. self.tools_table = FCTable()
  62. self.tools_box.addWidget(self.tools_table)
  63. self.tools_table.setColumnCount(4)
  64. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), 'TT', ''])
  65. self.tools_table.setColumnHidden(3, True)
  66. # self.tools_table.setSortingEnabled(False)
  67. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  68. self.tools_table.horizontalHeaderItem(0).setToolTip(
  69. _("This is the Tool Number.\n"
  70. "Painting will start with the tool with the biggest diameter,\n"
  71. "continuing until there are no more tools.\n"
  72. "Only tools that create painting geometry will still be present\n"
  73. "in the resulting geometry. This is because with some tools\n"
  74. "this function will not be able to create painting geometry.")
  75. )
  76. self.tools_table.horizontalHeaderItem(1).setToolTip(
  77. _("Tool Diameter. It's value (in current FlatCAM units) \n"
  78. "is the cut width into the material."))
  79. self.tools_table.horizontalHeaderItem(2).setToolTip(
  80. _("The Tool Type (TT) can be:<BR>"
  81. "- <B>Circular</B> with 1 ... 4 teeth -> it is informative only. Being circular, <BR>"
  82. "the cut width in material is exactly the tool diameter.<BR>"
  83. "- <B>Ball</B> -> informative only and make reference to the Ball type endmill.<BR>"
  84. "- <B>V-Shape</B> -> it will disable de Z-Cut parameter in the resulting geometry UI form "
  85. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and "
  86. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such "
  87. "as the cut width into material will be equal with the value in the Tool Diameter "
  88. "column of this table.<BR>"
  89. "Choosing the <B>V-Shape</B> Tool Type automatically will select the Operation Type "
  90. "in the resulting geometry as Isolation."))
  91. self.empty_label = QtWidgets.QLabel('')
  92. self.tools_box.addWidget(self.empty_label)
  93. # ### Add a new Tool ## ##
  94. hlay = QtWidgets.QHBoxLayout()
  95. self.tools_box.addLayout(hlay)
  96. self.addtool_entry_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Tool Dia'))
  97. self.addtool_entry_lbl.setToolTip(
  98. _("Diameter for the new tool.")
  99. )
  100. self.addtool_entry = FCEntry2()
  101. # hlay.addWidget(self.addtool_label)
  102. # hlay.addStretch()
  103. hlay.addWidget(self.addtool_entry_lbl)
  104. hlay.addWidget(self.addtool_entry)
  105. grid2 = QtWidgets.QGridLayout()
  106. self.tools_box.addLayout(grid2)
  107. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  108. self.addtool_btn.setToolTip(
  109. _("Add a new tool to the Tool Table\n"
  110. "with the diameter specified above.")
  111. )
  112. # self.copytool_btn = QtWidgets.QPushButton('Copy')
  113. # self.copytool_btn.setToolTip(
  114. # "Copy a selection of tools in the Tool Table\n"
  115. # "by first selecting a row in the Tool Table."
  116. # )
  117. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  118. self.deltool_btn.setToolTip(
  119. _("Delete a selection of tools in the Tool Table\n"
  120. "by first selecting a row(s) in the Tool Table.")
  121. )
  122. grid2.addWidget(self.addtool_btn, 0, 0)
  123. # grid2.addWidget(self.copytool_btn, 0, 1)
  124. grid2.addWidget(self.deltool_btn, 0, 2)
  125. self.empty_label_0 = QtWidgets.QLabel('')
  126. self.tools_box.addWidget(self.empty_label_0)
  127. grid3 = QtWidgets.QGridLayout()
  128. self.tools_box.addLayout(grid3)
  129. # Overlap
  130. ovlabel = QtWidgets.QLabel(_('Overlap Rate:'))
  131. ovlabel.setToolTip(
  132. _("How much (fraction) of the tool width to overlap each tool pass.\n"
  133. "Example:\n"
  134. "A value here of 0.25 means 25% from the tool diameter found above.\n\n"
  135. "Adjust the value starting with lower values\n"
  136. "and increasing it if areas that should be painted are still \n"
  137. "not painted.\n"
  138. "Lower values = faster processing, faster execution on PCB.\n"
  139. "Higher values = slow processing and slow execution on CNC\n"
  140. "due of too many paths.")
  141. )
  142. grid3.addWidget(ovlabel, 1, 0)
  143. self.paintoverlap_entry = FCEntry()
  144. grid3.addWidget(self.paintoverlap_entry, 1, 1)
  145. # Margin
  146. marginlabel = QtWidgets.QLabel(_('Margin:'))
  147. marginlabel.setToolTip(
  148. _("Distance by which to avoid\n"
  149. "the edges of the polygon to\n"
  150. "be painted.")
  151. )
  152. grid3.addWidget(marginlabel, 2, 0)
  153. self.paintmargin_entry = FCEntry()
  154. grid3.addWidget(self.paintmargin_entry, 2, 1)
  155. # Method
  156. methodlabel = QtWidgets.QLabel(_('Method:'))
  157. methodlabel.setToolTip(
  158. _("Algorithm for non-copper clearing:<BR>"
  159. "<B>Standard</B>: Fixed step inwards.<BR>"
  160. "<B>Seed-based</B>: Outwards from seed.<BR>"
  161. "<B>Line-based</B>: Parallel lines.")
  162. )
  163. grid3.addWidget(methodlabel, 3, 0)
  164. self.paintmethod_combo = RadioSet([
  165. {"label": _("Standard"), "value": "standard"},
  166. {"label": _("Seed-based"), "value": "seed"},
  167. {"label": _("Straight lines"), "value": "lines"}
  168. ], orientation='vertical', stretch=False)
  169. grid3.addWidget(self.paintmethod_combo, 3, 1)
  170. # Connect lines
  171. pathconnectlabel = QtWidgets.QLabel(_("Connect:"))
  172. pathconnectlabel.setToolTip(
  173. _("Draw lines between resulting\n"
  174. "segments to minimize tool lifts.")
  175. )
  176. grid3.addWidget(pathconnectlabel, 4, 0)
  177. self.pathconnect_cb = FCCheckBox()
  178. grid3.addWidget(self.pathconnect_cb, 4, 1)
  179. contourlabel = QtWidgets.QLabel(_("Contour:"))
  180. contourlabel.setToolTip(
  181. _("Cut around the perimeter of the polygon\n"
  182. "to trim rough edges.")
  183. )
  184. grid3.addWidget(contourlabel, 5, 0)
  185. self.paintcontour_cb = FCCheckBox()
  186. grid3.addWidget(self.paintcontour_cb, 5, 1)
  187. restlabel = QtWidgets.QLabel(_("Rest M.:"))
  188. restlabel.setToolTip(
  189. _("If checked, use 'rest machining'.\n"
  190. "Basically it will clear copper outside PCB features,\n"
  191. "using the biggest tool and continue with the next tools,\n"
  192. "from bigger to smaller, to clear areas of copper that\n"
  193. "could not be cleared by previous tool, until there is\n"
  194. "no more copper to clear or there are no more tools.\n\n"
  195. "If not checked, use the standard algorithm.")
  196. )
  197. grid3.addWidget(restlabel, 6, 0)
  198. self.rest_cb = FCCheckBox()
  199. grid3.addWidget(self.rest_cb, 6, 1)
  200. # Polygon selection
  201. selectlabel = QtWidgets.QLabel(_('Selection:'))
  202. selectlabel.setToolTip(
  203. _("How to select the polygons to paint.<BR>"
  204. "Options:<BR>"
  205. "- <B>Single</B>: left mouse click on the polygon to be painted.<BR>"
  206. "- <B>All</B>: paint all polygons.")
  207. )
  208. grid3.addWidget(selectlabel, 7, 0)
  209. # grid3 = QtWidgets.QGridLayout()
  210. self.selectmethod_combo = RadioSet([
  211. {"label": _("Single"), "value": "single"},
  212. {"label": _("All"), "value": "all"},
  213. # {"label": "Rectangle", "value": "rectangle"}
  214. ])
  215. grid3.addWidget(self.selectmethod_combo, 7, 1)
  216. # GO Button
  217. self.generate_paint_button = QtWidgets.QPushButton(_('Create Paint Geometry'))
  218. self.generate_paint_button.setToolTip(
  219. _("After clicking here, click inside<BR>"
  220. "the polygon you wish to be painted if <B>Single</B> is selected.<BR>"
  221. "If <B>All</B> is selected then the Paint will start after click.<BR>"
  222. "A new Geometry object with the tool<BR>"
  223. "paths will be created.")
  224. )
  225. self.tools_box.addWidget(self.generate_paint_button)
  226. self.tools_box.addStretch()
  227. self.obj_name = ""
  228. self.paint_obj = None
  229. self.units = ''
  230. self.paint_tools = {}
  231. self.tooluid = 0
  232. # store here the default data for Geometry Data
  233. self.default_data = {}
  234. self.default_data.update({
  235. "name": '_paint',
  236. "plot": self.app.defaults["geometry_plot"],
  237. "cutz": self.app.defaults["geometry_cutz"],
  238. "vtipdia": 0.1,
  239. "vtipangle": 30,
  240. "travelz": self.app.defaults["geometry_travelz"],
  241. "feedrate": self.app.defaults["geometry_feedrate"],
  242. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  243. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  244. "dwell": self.app.defaults["geometry_dwell"],
  245. "dwelltime": self.app.defaults["geometry_dwelltime"],
  246. "multidepth": self.app.defaults["geometry_multidepth"],
  247. "ppname_g": self.app.defaults["geometry_ppname_g"],
  248. "depthperpass": self.app.defaults["geometry_depthperpass"],
  249. "extracut": self.app.defaults["geometry_extracut"],
  250. "toolchange": self.app.defaults["geometry_toolchange"],
  251. "toolchangez": self.app.defaults["geometry_toolchangez"],
  252. "endz": self.app.defaults["geometry_endz"],
  253. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  254. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  255. "startz": self.app.defaults["geometry_startz"],
  256. "tooldia": self.app.defaults["tools_painttooldia"],
  257. "paintmargin": self.app.defaults["tools_paintmargin"],
  258. "paintmethod": self.app.defaults["tools_paintmethod"],
  259. "selectmethod": self.app.defaults["tools_selectmethod"],
  260. "pathconnect": self.app.defaults["tools_pathconnect"],
  261. "paintcontour": self.app.defaults["tools_paintcontour"],
  262. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  263. })
  264. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  265. # ## Signals
  266. self.addtool_btn.clicked.connect(self.on_tool_add)
  267. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  268. # self.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  269. self.tools_table.itemChanged.connect(self.on_tool_edit)
  270. self.deltool_btn.clicked.connect(self.on_tool_delete)
  271. self.generate_paint_button.clicked.connect(self.on_paint_button_click)
  272. self.selectmethod_combo.activated_custom.connect(self.on_radio_selection)
  273. def install(self, icon=None, separator=None, **kwargs):
  274. FlatCAMTool.install(self, icon, separator, shortcut='ALT+P', **kwargs)
  275. def run(self, toggle=True):
  276. self.app.report_usage("ToolPaint()")
  277. if toggle:
  278. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  279. if self.app.ui.splitter.sizes()[0] == 0:
  280. self.app.ui.splitter.setSizes([1, 1])
  281. else:
  282. try:
  283. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  284. self.app.ui.splitter.setSizes([0, 1])
  285. except AttributeError:
  286. pass
  287. else:
  288. if self.app.ui.splitter.sizes()[0] == 0:
  289. self.app.ui.splitter.setSizes([1, 1])
  290. FlatCAMTool.run(self)
  291. self.set_tool_ui()
  292. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  293. def on_radio_selection(self):
  294. if self.selectmethod_combo.get_value() == 'single':
  295. # disable rest-machining for single polygon painting
  296. self.rest_cb.set_value(False)
  297. self.rest_cb.setDisabled(True)
  298. # delete all tools except first row / tool for single polygon painting
  299. list_to_del = list(range(1, self.tools_table.rowCount()))
  300. if list_to_del:
  301. self.on_tool_delete(rows_to_delete=list_to_del)
  302. # disable addTool and delTool
  303. self.addtool_entry.setDisabled(True)
  304. self.addtool_btn.setDisabled(True)
  305. self.deltool_btn.setDisabled(True)
  306. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  307. else:
  308. self.rest_cb.setDisabled(False)
  309. self.addtool_entry.setDisabled(False)
  310. self.addtool_btn.setDisabled(False)
  311. self.deltool_btn.setDisabled(False)
  312. self.tools_table.setContextMenuPolicy(Qt.ActionsContextMenu)
  313. def set_tool_ui(self):
  314. self.tools_frame.show()
  315. self.reset_fields()
  316. # ## Init the GUI interface
  317. self.paintmargin_entry.set_value(self.default_data["paintmargin"])
  318. self.paintmethod_combo.set_value(self.default_data["paintmethod"])
  319. self.selectmethod_combo.set_value(self.default_data["selectmethod"])
  320. self.pathconnect_cb.set_value(self.default_data["pathconnect"])
  321. self.paintcontour_cb.set_value(self.default_data["paintcontour"])
  322. self.paintoverlap_entry.set_value(self.default_data["paintoverlap"])
  323. # updated units
  324. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  325. if self.units == "IN":
  326. self.addtool_entry.set_value(0.039)
  327. else:
  328. self.addtool_entry.set_value(1)
  329. self.tools_table.setupContextMenu()
  330. self.tools_table.addContextMenu(
  331. "Add", lambda: self.on_tool_add(dia=None, muted=None), icon=QtGui.QIcon("share/plus16.png"))
  332. self.tools_table.addContextMenu(
  333. "Delete", lambda:
  334. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  335. # set the working variables to a known state
  336. self.paint_tools.clear()
  337. self.tooluid = 0
  338. self.default_data.clear()
  339. self.default_data.update({
  340. "name": '_paint',
  341. "plot": self.app.defaults["geometry_plot"],
  342. "cutz": self.app.defaults["geometry_cutz"],
  343. "vtipdia": 0.1,
  344. "vtipangle": 30,
  345. "travelz": self.app.defaults["geometry_travelz"],
  346. "feedrate": self.app.defaults["geometry_feedrate"],
  347. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  348. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  349. "dwell": self.app.defaults["geometry_dwell"],
  350. "dwelltime": self.app.defaults["geometry_dwelltime"],
  351. "multidepth": self.app.defaults["geometry_multidepth"],
  352. "ppname_g": self.app.defaults["geometry_ppname_g"],
  353. "depthperpass": self.app.defaults["geometry_depthperpass"],
  354. "extracut": self.app.defaults["geometry_extracut"],
  355. "toolchange": self.app.defaults["geometry_toolchange"],
  356. "toolchangez": self.app.defaults["geometry_toolchangez"],
  357. "endz": self.app.defaults["geometry_endz"],
  358. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  359. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  360. "startz": self.app.defaults["geometry_startz"],
  361. "tooldia": self.app.defaults["tools_painttooldia"],
  362. "paintmargin": self.app.defaults["tools_paintmargin"],
  363. "paintmethod": self.app.defaults["tools_paintmethod"],
  364. "selectmethod": self.app.defaults["tools_selectmethod"],
  365. "pathconnect": self.app.defaults["tools_pathconnect"],
  366. "paintcontour": self.app.defaults["tools_paintcontour"],
  367. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  368. })
  369. # call on self.on_tool_add() counts as an call to self.build_ui()
  370. # through this, we add a initial row / tool in the tool_table
  371. self.on_tool_add(self.app.defaults["tools_painttooldia"], muted=True)
  372. # if the Paint Method is "Single" disable the tool table context menu
  373. if self.default_data["selectmethod"] == "single":
  374. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  375. def build_ui(self):
  376. try:
  377. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  378. self.tools_table.itemChanged.disconnect()
  379. except:
  380. pass
  381. # updated units
  382. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  383. sorted_tools = []
  384. for k, v in self.paint_tools.items():
  385. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  386. sorted_tools.sort()
  387. n = len(sorted_tools)
  388. self.tools_table.setRowCount(n)
  389. tool_id = 0
  390. for tool_sorted in sorted_tools:
  391. for tooluid_key, tooluid_value in self.paint_tools.items():
  392. if float('%.4f' % tooluid_value['tooldia']) == tool_sorted:
  393. tool_id += 1
  394. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  395. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  396. row_no = tool_id - 1
  397. self.tools_table.setItem(row_no, 0, id) # Tool name/id
  398. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  399. # There are no drill bits in MM with more than 3 decimals diameter
  400. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  401. if self.units == 'MM':
  402. dia = QtWidgets.QTableWidgetItem('%.2f' % tooluid_value['tooldia'])
  403. else:
  404. dia = QtWidgets.QTableWidgetItem('%.4f' % tooluid_value['tooldia'])
  405. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  406. tool_type_item = QtWidgets.QComboBox()
  407. for item in self.tool_type_item_options:
  408. tool_type_item.addItem(item)
  409. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  410. idx = tool_type_item.findText(tooluid_value['tool_type'])
  411. tool_type_item.setCurrentIndex(idx)
  412. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  413. self.tools_table.setItem(row_no, 1, dia) # Diameter
  414. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  415. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  416. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  417. # make the diameter column editable
  418. for row in range(tool_id):
  419. self.tools_table.item(row, 1).setFlags(
  420. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  421. # all the tools are selected by default
  422. self.tools_table.selectColumn(0)
  423. #
  424. self.tools_table.resizeColumnsToContents()
  425. self.tools_table.resizeRowsToContents()
  426. vertical_header = self.tools_table.verticalHeader()
  427. vertical_header.hide()
  428. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  429. horizontal_header = self.tools_table.horizontalHeader()
  430. horizontal_header.setMinimumSectionSize(10)
  431. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  432. horizontal_header.resizeSection(0, 20)
  433. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  434. # self.tools_table.setSortingEnabled(True)
  435. # sort by tool diameter
  436. # self.tools_table.sortItems(1)
  437. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  438. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  439. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  440. self.tools_table.itemChanged.connect(self.on_tool_edit)
  441. def on_tool_add(self, dia=None, muted=None):
  442. try:
  443. self.tools_table.itemChanged.disconnect()
  444. except Exception as e:
  445. log.debug("ToolPaint.on_tool_add() --> %s" % str(e))
  446. if dia:
  447. tool_dia = dia
  448. else:
  449. try:
  450. tool_dia = float(self.addtool_entry.get_value())
  451. except ValueError:
  452. # try to convert comma to decimal point. if it's still not working error message and return
  453. try:
  454. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  455. except ValueError:
  456. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  457. "use a number."))
  458. return
  459. if tool_dia is None:
  460. self.build_ui()
  461. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter to add, in Float format."))
  462. return
  463. # construct a list of all 'tooluid' in the self.tools
  464. tool_uid_list = []
  465. for tooluid_key in self.paint_tools:
  466. tool_uid_item = int(tooluid_key)
  467. tool_uid_list.append(tool_uid_item)
  468. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  469. if not tool_uid_list:
  470. max_uid = 0
  471. else:
  472. max_uid = max(tool_uid_list)
  473. self.tooluid = int(max_uid + 1)
  474. tool_dias = []
  475. for k, v in self.paint_tools.items():
  476. for tool_v in v.keys():
  477. if tool_v == 'tooldia':
  478. tool_dias.append(float('%.4f' % v[tool_v]))
  479. if float('%.4f' % tool_dia) in tool_dias:
  480. if muted is None:
  481. self.app.inform.emit(_("[WARNING_NOTCL] Adding tool cancelled. Tool already in Tool Table."))
  482. self.tools_table.itemChanged.connect(self.on_tool_edit)
  483. return
  484. else:
  485. if muted is None:
  486. self.app.inform.emit(_("[success] New tool added to Tool Table."))
  487. self.paint_tools.update({
  488. int(self.tooluid): {
  489. 'tooldia': float('%.4f' % tool_dia),
  490. 'offset': 'Path',
  491. 'offset_value': 0.0,
  492. 'type': 'Iso',
  493. 'tool_type': 'V',
  494. 'data': dict(self.default_data),
  495. 'solid_geometry': []
  496. }
  497. })
  498. self.build_ui()
  499. def on_tool_edit(self):
  500. old_tool_dia = ''
  501. try:
  502. self.tools_table.itemChanged.disconnect()
  503. except Exception as e:
  504. log.debug("ToolPaint.on_tool_edit() --> %s" % str(e))
  505. tool_dias = []
  506. for k, v in self.paint_tools.items():
  507. for tool_v in v.keys():
  508. if tool_v == 'tooldia':
  509. tool_dias.append(float('%.4f' % v[tool_v]))
  510. for row in range(self.tools_table.rowCount()):
  511. try:
  512. new_tool_dia = float(self.tools_table.item(row, 1).text())
  513. except ValueError:
  514. # try to convert comma to decimal point. if it's still not working error message and return
  515. try:
  516. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  517. except ValueError:
  518. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  519. "use a number."))
  520. return
  521. tooluid = int(self.tools_table.item(row, 3).text())
  522. # identify the tool that was edited and get it's tooluid
  523. if new_tool_dia not in tool_dias:
  524. self.paint_tools[tooluid]['tooldia'] = new_tool_dia
  525. self.app.inform.emit(_("[success] Tool from Tool Table was edited."))
  526. self.build_ui()
  527. return
  528. else:
  529. # identify the old tool_dia and restore the text in tool table
  530. for k, v in self.paint_tools.items():
  531. if k == tooluid:
  532. old_tool_dia = v['tooldia']
  533. break
  534. restore_dia_item = self.tools_table.item(row, 1)
  535. restore_dia_item.setText(str(old_tool_dia))
  536. self.app.inform.emit(_("[WARNING_NOTCL] Edit cancelled. "
  537. "New diameter value is already in the Tool Table."))
  538. self.build_ui()
  539. # def on_tool_copy(self, all=None):
  540. # try:
  541. # self.tools_table.itemChanged.disconnect()
  542. # except:
  543. # pass
  544. #
  545. # # find the tool_uid maximum value in the self.tools
  546. # uid_list = []
  547. # for key in self.paint_tools:
  548. # uid_list.append(int(key))
  549. # try:
  550. # max_uid = max(uid_list, key=int)
  551. # except ValueError:
  552. # max_uid = 0
  553. #
  554. # if all is None:
  555. # if self.tools_table.selectedItems():
  556. # for current_row in self.tools_table.selectedItems():
  557. # # sometime the header get selected and it has row number -1
  558. # # we don't want to do anything with the header :)
  559. # if current_row.row() < 0:
  560. # continue
  561. # try:
  562. # tooluid_copy = int(self.tools_table.item(current_row.row(), 3).text())
  563. # max_uid += 1
  564. # self.paint_tools[int(max_uid)] = dict(self.paint_tools[tooluid_copy])
  565. # for td in self.paint_tools:
  566. # print("COPIED", self.paint_tools[td])
  567. # self.build_ui()
  568. # except AttributeError:
  569. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  570. # self.build_ui()
  571. # return
  572. # except Exception as e:
  573. # log.debug("on_tool_copy() --> " + str(e))
  574. # # deselect the table
  575. # # self.ui.geo_tools_table.clearSelection()
  576. # else:
  577. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  578. # self.build_ui()
  579. # return
  580. # else:
  581. # # we copy all tools in geo_tools_table
  582. # try:
  583. # temp_tools = dict(self.paint_tools)
  584. # max_uid += 1
  585. # for tooluid in temp_tools:
  586. # self.paint_tools[int(max_uid)] = dict(temp_tools[tooluid])
  587. # temp_tools.clear()
  588. # self.build_ui()
  589. # except Exception as e:
  590. # log.debug("on_tool_copy() --> " + str(e))
  591. #
  592. # self.app.inform.emit("[success] Tool was copied in the Tool Table.")
  593. def on_tool_delete(self, rows_to_delete=None, all=None):
  594. try:
  595. self.tools_table.itemChanged.disconnect()
  596. except Exception as e:
  597. log.debug("ToolPaint.on_tool_delete() --> %s" % str(e))
  598. pass
  599. deleted_tools_list = []
  600. if all:
  601. self.paint_tools.clear()
  602. self.build_ui()
  603. return
  604. if rows_to_delete:
  605. try:
  606. for row in rows_to_delete:
  607. tooluid_del = int(self.tools_table.item(row, 3).text())
  608. deleted_tools_list.append(tooluid_del)
  609. except TypeError:
  610. deleted_tools_list.append(rows_to_delete)
  611. for t in deleted_tools_list:
  612. self.paint_tools.pop(t, None)
  613. self.build_ui()
  614. return
  615. try:
  616. if self.tools_table.selectedItems():
  617. for row_sel in self.tools_table.selectedItems():
  618. row = row_sel.row()
  619. if row < 0:
  620. continue
  621. tooluid_del = int(self.tools_table.item(row, 3).text())
  622. deleted_tools_list.append(tooluid_del)
  623. for t in deleted_tools_list:
  624. self.paint_tools.pop(t, None)
  625. except AttributeError:
  626. self.app.inform.emit(_("[WARNING_NOTCL] Delete failed. Select a tool to delete."))
  627. return
  628. except Exception as e:
  629. log.debug(str(e))
  630. self.app.inform.emit(_("[success] Tool(s) deleted from Tool Table."))
  631. self.build_ui()
  632. def on_paint_button_click(self):
  633. self.app.report_usage(_("geometry_on_paint_button"))
  634. # self.app.call_source = 'paint'
  635. try:
  636. overlap = float(self.paintoverlap_entry.get_value())
  637. except ValueError:
  638. # try to convert comma to decimal point. if it's still not working error message and return
  639. try:
  640. overlap = float(self.paintoverlap_entry.get_value().replace(',', '.'))
  641. except ValueError:
  642. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  643. "use a number."))
  644. return
  645. if overlap >= 1 or overlap < 0:
  646. self.app.inform.emit(_("[ERROR_NOTCL] Overlap value must be between "
  647. "0 (inclusive) and 1 (exclusive), "))
  648. return
  649. self.app.inform.emit(_("[WARNING_NOTCL] Click inside the desired polygon."))
  650. connect = self.pathconnect_cb.get_value()
  651. contour = self.paintcontour_cb.get_value()
  652. select_method = self.selectmethod_combo.get_value()
  653. self.obj_name = self.object_combo.currentText()
  654. # Get source object.
  655. try:
  656. self.paint_obj = self.app.collection.get_by_name(str(self.obj_name))
  657. except Exception as e:
  658. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  659. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  660. return
  661. if self.paint_obj is None:
  662. self.app.inform.emit(_("[ERROR_NOTCL] Object not found: %s") % self.paint_obj)
  663. return
  664. # test if the Geometry Object is multigeo and return Fail if True because
  665. # for now Paint don't work on MultiGeo
  666. if self.paint_obj.multigeo is True:
  667. self.app.inform.emit(_("[ERROR_NOTCL] Can't do Paint on MultiGeo geometries ..."))
  668. return 'Fail'
  669. o_name = '%s_multitool_paint' % self.obj_name
  670. if select_method == "all":
  671. self.paint_poly_all(self.paint_obj,
  672. outname=o_name,
  673. overlap=overlap,
  674. connect=connect,
  675. contour=contour)
  676. if select_method == "single":
  677. self.app.inform.emit(_("[WARNING_NOTCL] Click inside the desired polygon."))
  678. # use the first tool in the tool table; get the diameter
  679. tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  680. # To be called after clicking on the plot.
  681. def doit(event):
  682. # do paint single only for left mouse clicks
  683. if event.button == 1:
  684. self.app.inform.emit(_("Painting polygon..."))
  685. self.app.plotcanvas.vis_disconnect('mouse_press', doit)
  686. pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  687. if self.app.grid_status():
  688. pos = self.app.geo_editor.snap(pos[0], pos[1])
  689. self.paint_poly(self.paint_obj,
  690. inside_pt=[pos[0], pos[1]],
  691. tooldia=tooldia,
  692. overlap=overlap,
  693. connect=connect,
  694. contour=contour)
  695. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  696. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  697. self.app.plotcanvas.vis_connect('mouse_press', doit)
  698. def paint_poly(self, obj, inside_pt, tooldia, overlap, outname=None, connect=True, contour=True):
  699. """
  700. Paints a polygon selected by clicking on its interior.
  701. Note:
  702. * The margin is taken directly from the form.
  703. :param obj: painted object
  704. :param inside_pt: [x, y]
  705. :param tooldia: Diameter of the painting tool
  706. :param overlap: Overlap of the tool between passes.
  707. :param outname: Name of the resulting Geometry Object.
  708. :param connect: Connect lines to avoid tool lifts.
  709. :param contour: Paint around the edges.
  710. :return: None
  711. """
  712. # Which polygon.
  713. # poly = find_polygon(self.solid_geometry, inside_pt)
  714. poly = self.find_polygon(point=inside_pt, geoset=obj.solid_geometry)
  715. paint_method = self.paintmethod_combo.get_value()
  716. try:
  717. paint_margin = float(self.paintmargin_entry.get_value())
  718. except ValueError:
  719. # try to convert comma to decimal point. if it's still not working error message and return
  720. try:
  721. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  722. except ValueError:
  723. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  724. "use a number."))
  725. return
  726. # No polygon?
  727. if poly is None:
  728. self.app.log.warning('No polygon found.')
  729. self.app.inform.emit(_('[WARNING] No polygon found.'))
  730. return
  731. proc = self.app.proc_container.new(_("Painting polygon."))
  732. name = outname if outname else self.obj_name + "_paint"
  733. # Initializes the new geometry object
  734. def gen_paintarea(geo_obj, app_obj):
  735. assert isinstance(geo_obj, FlatCAMGeometry), \
  736. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  737. # assert isinstance(app_obj, App)
  738. def paint_p(polyg):
  739. if paint_method == "seed":
  740. # Type(cp) == FlatCAMRTreeStorage | None
  741. cpoly = self.clear_polygon2(polyg,
  742. tooldia=tooldia,
  743. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  744. overlap=overlap,
  745. contour=contour,
  746. connect=connect)
  747. elif paint_method == "lines":
  748. # Type(cp) == FlatCAMRTreeStorage | None
  749. cpoly = self.clear_polygon3(polyg,
  750. tooldia=tooldia,
  751. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  752. overlap=overlap,
  753. contour=contour,
  754. connect=connect)
  755. else:
  756. # Type(cp) == FlatCAMRTreeStorage | None
  757. cpoly = self.clear_polygon(polyg,
  758. tooldia=tooldia,
  759. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  760. overlap=overlap,
  761. contour=contour,
  762. connect=connect)
  763. if cpoly is not None:
  764. geo_obj.solid_geometry += list(cpoly.get_objects())
  765. return cpoly
  766. else:
  767. self.app.inform.emit(_('[ERROR_NOTCL] Geometry could not be painted completely'))
  768. return None
  769. geo_obj.solid_geometry = []
  770. try:
  771. a, b, c, d = poly.bounds
  772. geo_obj.options['xmin'] = a
  773. geo_obj.options['ymin'] = b
  774. geo_obj.options['xmax'] = c
  775. geo_obj.options['ymax'] = d
  776. except Exception as e:
  777. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  778. return
  779. try:
  780. poly_buf = poly.buffer(-paint_margin)
  781. if isinstance(poly_buf, MultiPolygon):
  782. cp = []
  783. for pp in poly_buf:
  784. cp.append(paint_p(pp))
  785. else:
  786. cp = paint_p(poly_buf)
  787. except Exception as e:
  788. log.debug("Could not Paint the polygons. %s" % str(e))
  789. self.app.inform.emit(
  790. _("[ERROR] Could not do Paint. Try a different combination of parameters. "
  791. "Or a different strategy of paint\n%s") % str(e))
  792. return
  793. if cp is not None:
  794. if isinstance(cp, list):
  795. for x in cp:
  796. geo_obj.solid_geometry += list(x.get_objects())
  797. else:
  798. geo_obj.solid_geometry = list(cp.get_objects())
  799. geo_obj.options["cnctooldia"] = str(tooldia)
  800. # this turn on the FlatCAMCNCJob plot for multiple tools
  801. geo_obj.multigeo = False
  802. geo_obj.multitool = True
  803. current_uid = int(self.tools_table.item(0, 3).text())
  804. for k, v in self.paint_tools.items():
  805. if k == current_uid:
  806. v['data']['name'] = name
  807. geo_obj.tools = dict(self.paint_tools)
  808. # Experimental...
  809. # print("Indexing...", end=' ')
  810. # geo_obj.make_index()
  811. # if errors == 0:
  812. # print("[success] Paint single polygon Done")
  813. # self.app.inform.emit("[success] Paint single polygon Done")
  814. # else:
  815. # print("[WARNING] Paint single polygon done with errors")
  816. # self.app.inform.emit("[WARNING] Paint single polygon done with errors. "
  817. # "%d area(s) could not be painted.\n"
  818. # "Use different paint parameters or edit the paint geometry and correct"
  819. # "the issue."
  820. # % errors)
  821. def job_thread(app_obj):
  822. try:
  823. app_obj.new_object("geometry", name, gen_paintarea)
  824. except Exception as e:
  825. proc.done()
  826. self.app.inform.emit(_('[ERROR_NOTCL] PaintTool.paint_poly() --> %s') % str(e))
  827. return
  828. proc.done()
  829. # focus on Selected Tab
  830. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  831. self.app.inform.emit(_("Polygon Paint started ..."))
  832. # Promise object with the new name
  833. self.app.collection.promise(name)
  834. # Background
  835. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  836. def paint_poly_all(self, obj, overlap, outname=None, connect=True, contour=True):
  837. """
  838. Paints all polygons in this object.
  839. :param obj: painted object
  840. :param overlap:
  841. :param outname:
  842. :param connect: Connect lines to avoid tool lifts.
  843. :param contour: Paint around the edges.
  844. :return:
  845. """
  846. paint_method = self.paintmethod_combo.get_value()
  847. try:
  848. paint_margin = float(self.paintmargin_entry.get_value())
  849. except ValueError:
  850. # try to convert comma to decimal point. if it's still not working error message and return
  851. try:
  852. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  853. except ValueError:
  854. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  855. "use a number."))
  856. return
  857. proc = self.app.proc_container.new(_("Painting polygon..."))
  858. name = outname if outname else self.obj_name + "_paint"
  859. over = overlap
  860. conn = connect
  861. cont = contour
  862. # This is a recursive generator of individual Polygons.
  863. # Note: Double check correct implementation. Might exit
  864. # early if it finds something that is not a Polygon?
  865. # def recurse(geo):
  866. # try:
  867. # for subg in geo:
  868. # for subsubg in recurse(subg):
  869. # yield subsubg
  870. # except TypeError:
  871. # if isinstance(geo, Polygon):
  872. # yield geo
  873. #
  874. # raise StopIteration
  875. def recurse(geometry, reset=True):
  876. """
  877. Creates a list of non-iterable linear geometry objects.
  878. Results are placed in self.flat_geometry
  879. :param geometry: Shapely type or list or list of list of such.
  880. :param reset: Clears the contents of self.flat_geometry.
  881. """
  882. if geometry is None:
  883. return
  884. if reset:
  885. self.flat_geometry = []
  886. # ## If iterable, expand recursively.
  887. try:
  888. for geo in geometry:
  889. if geo is not None:
  890. recurse(geometry=geo, reset=False)
  891. # ## Not iterable, do the actual indexing and add.
  892. except TypeError:
  893. if isinstance(geometry, LinearRing):
  894. g = Polygon(geometry)
  895. self.flat_geometry.append(g)
  896. else:
  897. self.flat_geometry.append(geometry)
  898. return self.flat_geometry
  899. # Initializes the new geometry object
  900. def gen_paintarea(geo_obj, app_obj):
  901. assert isinstance(geo_obj, FlatCAMGeometry), \
  902. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  903. tool_dia = None
  904. sorted_tools = []
  905. for row in range(self.tools_table.rowCount()):
  906. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  907. sorted_tools.sort(reverse=True)
  908. try:
  909. a, b, c, d = obj.bounds()
  910. geo_obj.options['xmin'] = a
  911. geo_obj.options['ymin'] = b
  912. geo_obj.options['xmax'] = c
  913. geo_obj.options['ymax'] = d
  914. except Exception as e:
  915. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  916. return
  917. total_geometry = []
  918. current_uid = int(1)
  919. geo_obj.solid_geometry = []
  920. for tool_dia in sorted_tools:
  921. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  922. for k, v in self.paint_tools.items():
  923. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  924. current_uid = int(k)
  925. break
  926. for geo in recurse(obj.solid_geometry):
  927. try:
  928. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  929. if not isinstance(geo, Polygon):
  930. continue
  931. poly_buf = geo.buffer(-paint_margin)
  932. if paint_method == "seed":
  933. # Type(cp) == FlatCAMRTreeStorage | None
  934. cp = self.clear_polygon2(poly_buf,
  935. tooldia=tool_dia,
  936. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  937. overlap=over,
  938. contour=cont,
  939. connect=conn)
  940. elif paint_method == "lines":
  941. # Type(cp) == FlatCAMRTreeStorage | None
  942. cp = self.clear_polygon3(poly_buf,
  943. tooldia=tool_dia,
  944. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  945. overlap=over,
  946. contour=cont,
  947. connect=conn)
  948. else:
  949. # Type(cp) == FlatCAMRTreeStorage | None
  950. cp = self.clear_polygon(poly_buf,
  951. tooldia=tool_dia,
  952. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  953. overlap=over,
  954. contour=cont,
  955. connect=conn)
  956. if cp is not None:
  957. total_geometry += list(cp.get_objects())
  958. except Exception as e:
  959. log.debug("Could not Paint the polygons. %s" % str(e))
  960. self.app.inform.emit(
  961. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  962. "Or a different Method of paint\n%s") % str(e))
  963. return
  964. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  965. # temporary list that stored that solid_geometry
  966. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  967. self.paint_tools[current_uid]['data']['name'] = name
  968. total_geometry[:] = []
  969. geo_obj.options["cnctooldia"] = str(tool_dia)
  970. # this turn on the FlatCAMCNCJob plot for multiple tools
  971. geo_obj.multigeo = True
  972. geo_obj.multitool = True
  973. geo_obj.tools.clear()
  974. geo_obj.tools = dict(self.paint_tools)
  975. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  976. has_solid_geo = 0
  977. for tooluid in geo_obj.tools:
  978. if geo_obj.tools[tooluid]['solid_geometry']:
  979. has_solid_geo += 1
  980. if has_solid_geo == 0:
  981. self.app.inform.emit(_("[ERROR] There is no Painting Geometry in the file.\n"
  982. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  983. "Change the painting parameters and try again."))
  984. return
  985. # Experimental...
  986. # print("Indexing...", end=' ')
  987. # geo_obj.make_index()
  988. self.app.inform.emit(_("[success] Paint All Done."))
  989. # Initializes the new geometry object
  990. def gen_paintarea_rest_machining(geo_obj, app_obj):
  991. assert isinstance(geo_obj, FlatCAMGeometry), \
  992. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  993. tool_dia = None
  994. sorted_tools = []
  995. for row in range(self.tools_table.rowCount()):
  996. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  997. sorted_tools.sort(reverse=True)
  998. cleared_geo = []
  999. current_uid = int(1)
  1000. geo_obj.solid_geometry = []
  1001. try:
  1002. a, b, c, d = obj.bounds()
  1003. geo_obj.options['xmin'] = a
  1004. geo_obj.options['ymin'] = b
  1005. geo_obj.options['xmax'] = c
  1006. geo_obj.options['ymax'] = d
  1007. except Exception as e:
  1008. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1009. return
  1010. for tool_dia in sorted_tools:
  1011. for geo in recurse(obj.solid_geometry):
  1012. try:
  1013. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  1014. poly_buf = geo.buffer(-paint_margin)
  1015. cp = None
  1016. if paint_method == "standard":
  1017. # Type(cp) == FlatCAMRTreeStorage | None
  1018. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1019. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1020. overlap=over, contour=cont, connect=conn)
  1021. elif paint_method == "seed":
  1022. # Type(cp) == FlatCAMRTreeStorage | None
  1023. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1024. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1025. overlap=over, contour=cont, connect=conn)
  1026. elif paint_method == "lines":
  1027. # Type(cp) == FlatCAMRTreeStorage | None
  1028. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1029. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1030. overlap=over, contour=cont, connect=conn)
  1031. if cp is not None:
  1032. cleared_geo += list(cp.get_objects())
  1033. except Exception as e:
  1034. log.debug("Could not Paint the polygons. %s" % str(e))
  1035. self.app.inform.emit(
  1036. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1037. "Or a different Method of paint\n%s") % str(e))
  1038. return
  1039. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1040. for k, v in self.paint_tools.items():
  1041. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1042. current_uid = int(k)
  1043. break
  1044. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  1045. # temporary list that stored that solid_geometry
  1046. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1047. self.paint_tools[current_uid]['data']['name'] = name
  1048. cleared_geo[:] = []
  1049. geo_obj.options["cnctooldia"] = str(tool_dia)
  1050. # this turn on the FlatCAMCNCJob plot for multiple tools
  1051. geo_obj.multigeo = True
  1052. geo_obj.multitool = True
  1053. geo_obj.tools.clear()
  1054. geo_obj.tools = dict(self.paint_tools)
  1055. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1056. has_solid_geo = 0
  1057. for tooluid in geo_obj.tools:
  1058. if geo_obj.tools[tooluid]['solid_geometry']:
  1059. has_solid_geo += 1
  1060. if has_solid_geo == 0:
  1061. self.app.inform.emit(_("[ERROR_NOTCL] There is no Painting Geometry in the file.\n"
  1062. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1063. "Change the painting parameters and try again."))
  1064. return
  1065. # Experimental...
  1066. # print("Indexing...", end=' ')
  1067. # geo_obj.make_index()
  1068. self.app.inform.emit(_("[success] Paint All with Rest-Machining done."))
  1069. def job_thread(app_obj):
  1070. try:
  1071. if self.rest_cb.isChecked():
  1072. app_obj.new_object("geometry", name, gen_paintarea_rest_machining)
  1073. else:
  1074. app_obj.new_object("geometry", name, gen_paintarea)
  1075. except Exception as e:
  1076. proc.done()
  1077. traceback.print_stack()
  1078. return
  1079. proc.done()
  1080. # focus on Selected Tab
  1081. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1082. self.app.inform.emit(_("Polygon Paint started ..."))
  1083. # Promise object with the new name
  1084. self.app.collection.promise(name)
  1085. # Background
  1086. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1087. def reset_fields(self):
  1088. self.object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))