ToolPaint.py 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272
  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. fcTranslate.apply_language('strings')
  14. import builtins
  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('%.3f' % 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:
  445. pass
  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. try:
  501. self.tools_table.itemChanged.disconnect()
  502. except:
  503. pass
  504. tool_dias = []
  505. for k, v in self.paint_tools.items():
  506. for tool_v in v.keys():
  507. if tool_v == 'tooldia':
  508. tool_dias.append(float('%.4f' % v[tool_v]))
  509. for row in range(self.tools_table.rowCount()):
  510. try:
  511. new_tool_dia = float(self.tools_table.item(row, 1).text())
  512. except ValueError:
  513. # try to convert comma to decimal point. if it's still not working error message and return
  514. try:
  515. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  516. except ValueError:
  517. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  518. "use a number."))
  519. return
  520. tooluid = int(self.tools_table.item(row, 3).text())
  521. # identify the tool that was edited and get it's tooluid
  522. if new_tool_dia not in tool_dias:
  523. self.paint_tools[tooluid]['tooldia'] = new_tool_dia
  524. self.app.inform.emit(_("[success] Tool from Tool Table was edited."))
  525. self.build_ui()
  526. return
  527. else:
  528. # identify the old tool_dia and restore the text in tool table
  529. for k, v in self.paint_tools.items():
  530. if k == tooluid:
  531. old_tool_dia = v['tooldia']
  532. break
  533. restore_dia_item = self.tools_table.item(row, 1)
  534. restore_dia_item.setText(str(old_tool_dia))
  535. self.app.inform.emit(_("[WARNING_NOTCL] Edit cancelled. New diameter value is already in the Tool Table."))
  536. self.build_ui()
  537. # def on_tool_copy(self, all=None):
  538. # try:
  539. # self.tools_table.itemChanged.disconnect()
  540. # except:
  541. # pass
  542. #
  543. # # find the tool_uid maximum value in the self.tools
  544. # uid_list = []
  545. # for key in self.paint_tools:
  546. # uid_list.append(int(key))
  547. # try:
  548. # max_uid = max(uid_list, key=int)
  549. # except ValueError:
  550. # max_uid = 0
  551. #
  552. # if all is None:
  553. # if self.tools_table.selectedItems():
  554. # for current_row in self.tools_table.selectedItems():
  555. # # sometime the header get selected and it has row number -1
  556. # # we don't want to do anything with the header :)
  557. # if current_row.row() < 0:
  558. # continue
  559. # try:
  560. # tooluid_copy = int(self.tools_table.item(current_row.row(), 3).text())
  561. # max_uid += 1
  562. # self.paint_tools[int(max_uid)] = dict(self.paint_tools[tooluid_copy])
  563. # for td in self.paint_tools:
  564. # print("COPIED", self.paint_tools[td])
  565. # self.build_ui()
  566. # except AttributeError:
  567. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  568. # self.build_ui()
  569. # return
  570. # except Exception as e:
  571. # log.debug("on_tool_copy() --> " + str(e))
  572. # # deselect the table
  573. # # self.ui.geo_tools_table.clearSelection()
  574. # else:
  575. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  576. # self.build_ui()
  577. # return
  578. # else:
  579. # # we copy all tools in geo_tools_table
  580. # try:
  581. # temp_tools = dict(self.paint_tools)
  582. # max_uid += 1
  583. # for tooluid in temp_tools:
  584. # self.paint_tools[int(max_uid)] = dict(temp_tools[tooluid])
  585. # temp_tools.clear()
  586. # self.build_ui()
  587. # except Exception as e:
  588. # log.debug("on_tool_copy() --> " + str(e))
  589. #
  590. # self.app.inform.emit("[success] Tool was copied in the Tool Table.")
  591. def on_tool_delete(self, rows_to_delete=None, all=None):
  592. try:
  593. self.tools_table.itemChanged.disconnect()
  594. except:
  595. pass
  596. deleted_tools_list = []
  597. if all:
  598. self.paint_tools.clear()
  599. self.build_ui()
  600. return
  601. if rows_to_delete:
  602. try:
  603. for row in rows_to_delete:
  604. tooluid_del = int(self.tools_table.item(row, 3).text())
  605. deleted_tools_list.append(tooluid_del)
  606. except TypeError:
  607. deleted_tools_list.append(rows_to_delete)
  608. for t in deleted_tools_list:
  609. self.paint_tools.pop(t, None)
  610. self.build_ui()
  611. return
  612. try:
  613. if self.tools_table.selectedItems():
  614. for row_sel in self.tools_table.selectedItems():
  615. row = row_sel.row()
  616. if row < 0:
  617. continue
  618. tooluid_del = int(self.tools_table.item(row, 3).text())
  619. deleted_tools_list.append(tooluid_del)
  620. for t in deleted_tools_list:
  621. self.paint_tools.pop(t, None)
  622. except AttributeError:
  623. self.app.inform.emit(_("[WARNING_NOTCL] Delete failed. Select a tool to delete."))
  624. return
  625. except Exception as e:
  626. log.debug(str(e))
  627. self.app.inform.emit(_("[success] Tool(s) deleted from Tool Table."))
  628. self.build_ui()
  629. def on_paint_button_click(self):
  630. self.app.report_usage(_("geometry_on_paint_button"))
  631. # self.app.call_source = 'paint'
  632. try:
  633. overlap = float(self.paintoverlap_entry.get_value())
  634. except ValueError:
  635. # try to convert comma to decimal point. if it's still not working error message and return
  636. try:
  637. overlap = float(self.paintoverlap_entry.get_value().replace(',', '.'))
  638. except ValueError:
  639. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  640. "use a number."))
  641. return
  642. if overlap >= 1 or overlap < 0:
  643. self.app.inform.emit(_("[ERROR_NOTCL] Overlap value must be between "
  644. "0 (inclusive) and 1 (exclusive), "))
  645. return
  646. self.app.inform.emit(_("[WARNING_NOTCL] Click inside the desired polygon."))
  647. connect = self.pathconnect_cb.get_value()
  648. contour = self.paintcontour_cb.get_value()
  649. select_method = self.selectmethod_combo.get_value()
  650. self.obj_name = self.object_combo.currentText()
  651. # Get source object.
  652. try:
  653. self.paint_obj = self.app.collection.get_by_name(str(self.obj_name))
  654. except:
  655. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  656. return
  657. if self.paint_obj is None:
  658. self.app.inform.emit(_("[ERROR_NOTCL] Object not found: %s") % self.paint_obj)
  659. return
  660. # test if the Geometry Object is multigeo and return Fail if True because
  661. # for now Paint don't work on MultiGeo
  662. if self.paint_obj.multigeo is True:
  663. self.app.inform.emit(_("[ERROR_NOTCL] Can't do Paint on MultiGeo geometries ..."))
  664. return 'Fail'
  665. o_name = '%s_multitool_paint' % (self.obj_name)
  666. if select_method == "all":
  667. self.paint_poly_all(self.paint_obj,
  668. outname=o_name,
  669. overlap=overlap,
  670. connect=connect,
  671. contour=contour)
  672. if select_method == "single":
  673. self.app.inform.emit(_("[WARNING_NOTCL] Click inside the desired polygon."))
  674. # use the first tool in the tool table; get the diameter
  675. tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  676. # To be called after clicking on the plot.
  677. def doit(event):
  678. # do paint single only for left mouse clicks
  679. if event.button == 1:
  680. self.app.inform.emit(_("Painting polygon..."))
  681. self.app.plotcanvas.vis_disconnect('mouse_press', doit)
  682. pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  683. if self.app.grid_status():
  684. pos = self.app.geo_editor.snap(pos[0], pos[1])
  685. self.paint_poly(self.paint_obj,
  686. inside_pt=[pos[0], pos[1]],
  687. tooldia=tooldia,
  688. overlap=overlap,
  689. connect=connect,
  690. contour=contour)
  691. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  692. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  693. self.app.plotcanvas.vis_connect('mouse_press', doit)
  694. def paint_poly(self, obj, inside_pt, tooldia, overlap,
  695. outname=None, connect=True,
  696. contour=True):
  697. """
  698. Paints a polygon selected by clicking on its interior.
  699. Note:
  700. * The margin is taken directly from the form.
  701. :param inside_pt: [x, y]
  702. :param tooldia: Diameter of the painting tool
  703. :param overlap: Overlap of the tool between passes.
  704. :param outname: Name of the resulting Geometry Object.
  705. :param connect: Connect lines to avoid tool lifts.
  706. :param contour: Paint around the edges.
  707. :return: None
  708. """
  709. # Which polygon.
  710. # poly = find_polygon(self.solid_geometry, inside_pt)
  711. poly = self.find_polygon(point=inside_pt, geoset=obj.solid_geometry)
  712. paint_method = self.paintmethod_combo.get_value()
  713. try:
  714. paint_margin = float(self.paintmargin_entry.get_value())
  715. except ValueError:
  716. # try to convert comma to decimal point. if it's still not working error message and return
  717. try:
  718. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  719. except ValueError:
  720. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  721. "use a number."))
  722. return
  723. # No polygon?
  724. if poly is None:
  725. self.app.log.warning('No polygon found.')
  726. self.app.inform.emit(_('[WARNING] No polygon found.'))
  727. return
  728. proc = self.app.proc_container.new(_("Painting polygon."))
  729. name = outname if outname else self.obj_name + "_paint"
  730. # Initializes the new geometry object
  731. def gen_paintarea(geo_obj, app_obj):
  732. assert isinstance(geo_obj, FlatCAMGeometry), \
  733. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  734. # assert isinstance(app_obj, App)
  735. def paint_p(polyg):
  736. if paint_method == "seed":
  737. # Type(cp) == FlatCAMRTreeStorage | None
  738. cp = self.clear_polygon2(polyg,
  739. tooldia=tooldia,
  740. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  741. overlap=overlap,
  742. contour=contour,
  743. connect=connect)
  744. elif paint_method == "lines":
  745. # Type(cp) == FlatCAMRTreeStorage | None
  746. cp = self.clear_polygon3(polyg,
  747. tooldia=tooldia,
  748. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  749. overlap=overlap,
  750. contour=contour,
  751. connect=connect)
  752. else:
  753. # Type(cp) == FlatCAMRTreeStorage | None
  754. cp = self.clear_polygon(polyg,
  755. tooldia=tooldia,
  756. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  757. overlap=overlap,
  758. contour=contour,
  759. connect=connect)
  760. if cp is not None:
  761. geo_obj.solid_geometry += list(cp.get_objects())
  762. return cp
  763. else:
  764. self.app.inform.emit(_('[ERROR_NOTCL] Geometry could not be painted completely'))
  765. return None
  766. geo_obj.solid_geometry = []
  767. try:
  768. a, b, c, d = poly.bounds
  769. geo_obj.options['xmin'] = a
  770. geo_obj.options['ymin'] = b
  771. geo_obj.options['xmax'] = c
  772. geo_obj.options['ymax'] = d
  773. except Exception as e:
  774. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  775. return
  776. try:
  777. poly_buf = poly.buffer(-paint_margin)
  778. if isinstance(poly_buf, MultiPolygon):
  779. cp = []
  780. for pp in poly_buf:
  781. cp.append(paint_p(pp))
  782. else:
  783. cp = paint_p(poly_buf)
  784. except Exception as e:
  785. log.debug("Could not Paint the polygons. %s" % str(e))
  786. self.app.inform.emit(
  787. _("[ERROR] Could not do Paint. Try a different combination of parameters. "
  788. "Or a different strategy of paint\n%s") % str(e))
  789. return
  790. if cp is not None:
  791. if isinstance(cp, list):
  792. for x in cp:
  793. geo_obj.solid_geometry += list(x.get_objects())
  794. else:
  795. geo_obj.solid_geometry = list(cp.get_objects())
  796. geo_obj.options["cnctooldia"] = tooldia
  797. # this turn on the FlatCAMCNCJob plot for multiple tools
  798. geo_obj.multigeo = False
  799. geo_obj.multitool = True
  800. current_uid = int(self.tools_table.item(0, 3).text())
  801. for k, v in self.paint_tools.items():
  802. if k == current_uid:
  803. v['data']['name'] = name
  804. geo_obj.tools = dict(self.paint_tools)
  805. # Experimental...
  806. # print("Indexing...", end=' ')
  807. # geo_obj.make_index()
  808. # if errors == 0:
  809. # print("[success] Paint single polygon Done")
  810. # self.app.inform.emit("[success] Paint single polygon Done")
  811. # else:
  812. # print("[WARNING] Paint single polygon done with errors")
  813. # self.app.inform.emit("[WARNING] Paint single polygon done with errors. "
  814. # "%d area(s) could not be painted.\n"
  815. # "Use different paint parameters or edit the paint geometry and correct"
  816. # "the issue."
  817. # % errors)
  818. def job_thread(app_obj):
  819. try:
  820. app_obj.new_object("geometry", name, gen_paintarea)
  821. except Exception as e:
  822. proc.done()
  823. self.app.inform.emit(_('[ERROR_NOTCL] PaintTool.paint_poly() --> %s') % str(e))
  824. return
  825. proc.done()
  826. # focus on Selected Tab
  827. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  828. self.app.inform.emit(_("Polygon Paint started ..."))
  829. # Promise object with the new name
  830. self.app.collection.promise(name)
  831. # Background
  832. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  833. def paint_poly_all(self, obj, overlap, outname=None,
  834. connect=True, contour=True):
  835. """
  836. Paints all polygons in this object.
  837. :param tooldia:
  838. :param overlap:
  839. :param outname:
  840. :param connect: Connect lines to avoid tool lifts.
  841. :param contour: Paint around the edges.
  842. :return:
  843. """
  844. paint_method = self.paintmethod_combo.get_value()
  845. try:
  846. paint_margin = float(self.paintmargin_entry.get_value())
  847. except ValueError:
  848. # try to convert comma to decimal point. if it's still not working error message and return
  849. try:
  850. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  851. except ValueError:
  852. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  853. "use a number."))
  854. return
  855. proc = self.app.proc_container.new(_("Painting polygon..."))
  856. name = outname if outname else self.obj_name + "_paint"
  857. over = overlap
  858. conn = connect
  859. cont = contour
  860. # This is a recursive generator of individual Polygons.
  861. # Note: Double check correct implementation. Might exit
  862. # early if it finds something that is not a Polygon?
  863. # def recurse(geo):
  864. # try:
  865. # for subg in geo:
  866. # for subsubg in recurse(subg):
  867. # yield subsubg
  868. # except TypeError:
  869. # if isinstance(geo, Polygon):
  870. # yield geo
  871. #
  872. # raise StopIteration
  873. def recurse(geometry, reset=True):
  874. """
  875. Creates a list of non-iterable linear geometry objects.
  876. Results are placed in self.flat_geometry
  877. :param geometry: Shapely type or list or list of list of such.
  878. :param reset: Clears the contents of self.flat_geometry.
  879. """
  880. if geometry is None:
  881. return
  882. if reset:
  883. self.flat_geometry = []
  884. # ## If iterable, expand recursively.
  885. try:
  886. for geo in geometry:
  887. if geo is not None:
  888. recurse(geometry=geo, reset=False)
  889. # ## Not iterable, do the actual indexing and add.
  890. except TypeError:
  891. self.flat_geometry.append(geometry)
  892. return self.flat_geometry
  893. # Initializes the new geometry object
  894. def gen_paintarea(geo_obj, app_obj):
  895. assert isinstance(geo_obj, FlatCAMGeometry), \
  896. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  897. sorted_tools = []
  898. for row in range(self.tools_table.rowCount()):
  899. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  900. sorted_tools.sort(reverse=True)
  901. try:
  902. a, b, c, d = obj.bounds()
  903. geo_obj.options['xmin'] = a
  904. geo_obj.options['ymin'] = b
  905. geo_obj.options['xmax'] = c
  906. geo_obj.options['ymax'] = d
  907. except Exception as e:
  908. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  909. return
  910. total_geometry = []
  911. current_uid = int(1)
  912. geo_obj.solid_geometry = []
  913. for tool_dia in sorted_tools:
  914. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  915. for k, v in self.paint_tools.items():
  916. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  917. current_uid = int(k)
  918. break
  919. for geo in recurse(obj.solid_geometry):
  920. try:
  921. #Polygons are the only really paintable geometries, lines in theory have no area to be painted
  922. if not isinstance(geo, Polygon):
  923. continue
  924. poly_buf = geo.buffer(-paint_margin)
  925. if paint_method == "seed":
  926. # Type(cp) == FlatCAMRTreeStorage | None
  927. cp = self.clear_polygon2(poly_buf,
  928. tooldia=tool_dia,
  929. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  930. overlap=over,
  931. contour=cont,
  932. connect=conn)
  933. elif paint_method == "lines":
  934. # Type(cp) == FlatCAMRTreeStorage | None
  935. cp = self.clear_polygon3(poly_buf,
  936. tooldia=tool_dia,
  937. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  938. overlap=over,
  939. contour=cont,
  940. connect=conn)
  941. else:
  942. # Type(cp) == FlatCAMRTreeStorage | None
  943. cp = self.clear_polygon(poly_buf,
  944. tooldia=tool_dia,
  945. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  946. overlap=over,
  947. contour=cont,
  948. connect=conn)
  949. if cp is not None:
  950. total_geometry += list(cp.get_objects())
  951. except Exception as e:
  952. log.debug("Could not Paint the polygons. %s" % str(e))
  953. self.app.inform.emit(
  954. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  955. "Or a different Method of paint\n%s") % str(e))
  956. return
  957. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  958. # temporary list that stored that solid_geometry
  959. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  960. self.paint_tools[current_uid]['data']['name'] = name
  961. total_geometry[:] = []
  962. geo_obj.options["cnctooldia"] = tool_dia
  963. # this turn on the FlatCAMCNCJob plot for multiple tools
  964. geo_obj.multigeo = True
  965. geo_obj.multitool = True
  966. geo_obj.tools.clear()
  967. geo_obj.tools = dict(self.paint_tools)
  968. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  969. has_solid_geo = 0
  970. for tooluid in geo_obj.tools:
  971. if geo_obj.tools[tooluid]['solid_geometry']:
  972. has_solid_geo += 1
  973. if has_solid_geo == 0:
  974. self.app.inform.emit(_("[ERROR] There is no Painting Geometry in the file.\n"
  975. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  976. "Change the painting parameters and try again."))
  977. return
  978. # Experimental...
  979. # print("Indexing...", end=' ')
  980. # geo_obj.make_index()
  981. self.app.inform.emit(_("[success] Paint All Done."))
  982. # Initializes the new geometry object
  983. def gen_paintarea_rest_machining(geo_obj, app_obj):
  984. assert isinstance(geo_obj, FlatCAMGeometry), \
  985. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  986. sorted_tools = []
  987. for row in range(self.tools_table.rowCount()):
  988. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  989. sorted_tools.sort(reverse=True)
  990. cleared_geo = []
  991. current_uid = int(1)
  992. geo_obj.solid_geometry = []
  993. try:
  994. a, b, c, d = obj.bounds()
  995. geo_obj.options['xmin'] = a
  996. geo_obj.options['ymin'] = b
  997. geo_obj.options['xmax'] = c
  998. geo_obj.options['ymax'] = d
  999. except Exception as e:
  1000. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1001. return
  1002. for tool_dia in sorted_tools:
  1003. for geo in recurse(obj.solid_geometry):
  1004. try:
  1005. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  1006. poly_buf = geo.buffer(-paint_margin)
  1007. if paint_method == "standard":
  1008. # Type(cp) == FlatCAMRTreeStorage | None
  1009. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1010. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1011. overlap=over, contour=cont, connect=conn)
  1012. elif paint_method == "seed":
  1013. # Type(cp) == FlatCAMRTreeStorage | None
  1014. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1015. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1016. overlap=over, contour=cont, connect=conn)
  1017. elif paint_method == "lines":
  1018. # Type(cp) == FlatCAMRTreeStorage | None
  1019. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1020. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1021. overlap=over, contour=cont, connect=conn)
  1022. if cp is not None:
  1023. cleared_geo += list(cp.get_objects())
  1024. except Exception as e:
  1025. log.debug("Could not Paint the polygons. %s" % str(e))
  1026. self.app.inform.emit(
  1027. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1028. "Or a different Method of paint\n%s") % str(e))
  1029. return
  1030. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1031. for k, v in self.paint_tools.items():
  1032. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1033. current_uid = int(k)
  1034. break
  1035. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  1036. # temporary list that stored that solid_geometry
  1037. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1038. self.paint_tools[current_uid]['data']['name'] = name
  1039. cleared_geo[:] = []
  1040. geo_obj.options["cnctooldia"] = tool_dia
  1041. # this turn on the FlatCAMCNCJob plot for multiple tools
  1042. geo_obj.multigeo = True
  1043. geo_obj.multitool = True
  1044. geo_obj.tools.clear()
  1045. geo_obj.tools = dict(self.paint_tools)
  1046. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1047. has_solid_geo = 0
  1048. for tooluid in geo_obj.tools:
  1049. if geo_obj.tools[tooluid]['solid_geometry']:
  1050. has_solid_geo += 1
  1051. if has_solid_geo == 0:
  1052. self.app.inform.emit(_("[ERROR_NOTCL] There is no Painting Geometry in the file.\n"
  1053. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1054. "Change the painting parameters and try again."))
  1055. return
  1056. # Experimental...
  1057. # print("Indexing...", end=' ')
  1058. # geo_obj.make_index()
  1059. self.app.inform.emit(_("[success] Paint All with Rest-Machining done."))
  1060. def job_thread(app_obj):
  1061. try:
  1062. if self.rest_cb.isChecked():
  1063. app_obj.new_object("geometry", name, gen_paintarea_rest_machining)
  1064. else:
  1065. app_obj.new_object("geometry", name, gen_paintarea)
  1066. except Exception as e:
  1067. proc.done()
  1068. traceback.print_stack()
  1069. return
  1070. proc.done()
  1071. # focus on Selected Tab
  1072. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1073. self.app.inform.emit(_("Polygon Paint started ..."))
  1074. # Promise object with the new name
  1075. self.app.collection.promise(name)
  1076. # Background
  1077. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1078. def reset_fields(self):
  1079. self.object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))