ToolPaint.py 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903
  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. from shapely.geometry import base
  12. import gettext
  13. import FlatCAMTranslation as fcTranslate
  14. import builtins
  15. fcTranslate.apply_language('strings')
  16. if '_' not in builtins.__dict__:
  17. _ = gettext.gettext
  18. class ToolPaint(FlatCAMTool, Gerber):
  19. toolName = _("Paint Tool")
  20. def __init__(self, app):
  21. self.app = app
  22. FlatCAMTool.__init__(self, app)
  23. Geometry.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  24. # ## Title
  25. title_label = QtWidgets.QLabel("%s" % self.toolName)
  26. title_label.setStyleSheet("""
  27. QLabel
  28. {
  29. font-size: 16px;
  30. font-weight: bold;
  31. }
  32. """)
  33. self.layout.addWidget(title_label)
  34. self.tools_frame = QtWidgets.QFrame()
  35. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  36. self.layout.addWidget(self.tools_frame)
  37. self.tools_box = QtWidgets.QVBoxLayout()
  38. self.tools_box.setContentsMargins(0, 0, 0, 0)
  39. self.tools_frame.setLayout(self.tools_box)
  40. # ## Form Layout
  41. form_layout = QtWidgets.QFormLayout()
  42. self.tools_box.addLayout(form_layout)
  43. # ################################################
  44. # ##### Type of object to be painted #############
  45. # ################################################
  46. self.type_obj_combo = QtWidgets.QComboBox()
  47. self.type_obj_combo.addItem("Gerber")
  48. self.type_obj_combo.addItem("Excellon")
  49. self.type_obj_combo.addItem("Geometry")
  50. # we get rid of item1 ("Excellon") as it is not suitable
  51. self.type_obj_combo.view().setRowHidden(1, True)
  52. self.type_obj_combo.setItemIcon(0, QtGui.QIcon("share/flatcam_icon16.png"))
  53. self.type_obj_combo.setItemIcon(2, QtGui.QIcon("share/geometry16.png"))
  54. self.type_obj_combo_label = QtWidgets.QLabel('%s:' % _("Obj Type"))
  55. self.type_obj_combo_label.setToolTip(
  56. _("Specify the type of object to be painted.\n"
  57. "It can be of type: Gerber or Geometry.\n"
  58. "What is selected here will dictate the kind\n"
  59. "of objects that will populate the 'Object' combobox.")
  60. )
  61. self.type_obj_combo_label.setMinimumWidth(60)
  62. form_layout.addRow(self.type_obj_combo_label, self.type_obj_combo)
  63. # ################################################
  64. # ##### The object to be painted #################
  65. # ################################################
  66. self.obj_combo = QtWidgets.QComboBox()
  67. self.obj_combo.setModel(self.app.collection)
  68. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  69. self.obj_combo.setCurrentIndex(1)
  70. self.object_label = QtWidgets.QLabel('%s:' % _("Object"))
  71. self.object_label.setToolTip(_("Object to be painted."))
  72. form_layout.addRow(self.object_label, self.obj_combo)
  73. e_lab_0 = QtWidgets.QLabel('')
  74. form_layout.addRow(e_lab_0)
  75. # ### Tools ## ##
  76. self.tools_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Tools Table'))
  77. self.tools_table_label.setToolTip(
  78. _("Tools pool from which the algorithm\n"
  79. "will pick the ones used for painting.")
  80. )
  81. self.tools_box.addWidget(self.tools_table_label)
  82. self.tools_table = FCTable()
  83. self.tools_box.addWidget(self.tools_table)
  84. self.tools_table.setColumnCount(4)
  85. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), ''])
  86. self.tools_table.setColumnHidden(3, True)
  87. # self.tools_table.setSortingEnabled(False)
  88. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  89. self.tools_table.horizontalHeaderItem(0).setToolTip(
  90. _("This is the Tool Number.\n"
  91. "Painting will start with the tool with the biggest diameter,\n"
  92. "continuing until there are no more tools.\n"
  93. "Only tools that create painting geometry will still be present\n"
  94. "in the resulting geometry. This is because with some tools\n"
  95. "this function will not be able to create painting geometry.")
  96. )
  97. self.tools_table.horizontalHeaderItem(1).setToolTip(
  98. _("Tool Diameter. It's value (in current FlatCAM units) \n"
  99. "is the cut width into the material."))
  100. self.tools_table.horizontalHeaderItem(2).setToolTip(
  101. _("The Tool Type (TT) can be:<BR>"
  102. "- <B>Circular</B> with 1 ... 4 teeth -> it is informative only. Being circular, <BR>"
  103. "the cut width in material is exactly the tool diameter.<BR>"
  104. "- <B>Ball</B> -> informative only and make reference to the Ball type endmill.<BR>"
  105. "- <B>V-Shape</B> -> it will disable de Z-Cut parameter in the resulting geometry UI form "
  106. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and "
  107. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such "
  108. "as the cut width into material will be equal with the value in the Tool Diameter "
  109. "column of this table.<BR>"
  110. "Choosing the <B>V-Shape</B> Tool Type automatically will select the Operation Type "
  111. "in the resulting geometry as Isolation."))
  112. self.order_label = QtWidgets.QLabel('<b>%s:</b>' % _('Tool order'))
  113. self.order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  114. "'No' --> means that the used order is the one in the tool table\n"
  115. "'Forward' --> means that the tools will be ordered from small to big\n"
  116. "'Reverse' --> menas that the tools will ordered from big to small\n\n"
  117. "WARNING: using rest machining will automatically set the order\n"
  118. "in reverse and disable this control."))
  119. self.order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  120. {'label': _('Forward'), 'value': 'fwd'},
  121. {'label': _('Reverse'), 'value': 'rev'}])
  122. self.order_radio.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  123. "'No' --> means that the used order is the one in the tool table\n"
  124. "'Forward' --> means that the tools will be ordered from small to big\n"
  125. "'Reverse' --> menas that the tools will ordered from big to small\n\n"
  126. "WARNING: using rest machining will automatically set the order\n"
  127. "in reverse and disable this control."))
  128. form = QtWidgets.QFormLayout()
  129. self.tools_box.addLayout(form)
  130. form.addRow(QtWidgets.QLabel(''), QtWidgets.QLabel(''))
  131. form.addRow(self.order_label, self.order_radio)
  132. # ### Add a new Tool ## ##
  133. hlay = QtWidgets.QHBoxLayout()
  134. self.tools_box.addLayout(hlay)
  135. self.addtool_entry_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Tool Dia'))
  136. self.addtool_entry_lbl.setToolTip(
  137. _("Diameter for the new tool.")
  138. )
  139. self.addtool_entry = FCEntry2()
  140. # hlay.addWidget(self.addtool_label)
  141. # hlay.addStretch()
  142. hlay.addWidget(self.addtool_entry_lbl)
  143. hlay.addWidget(self.addtool_entry)
  144. grid2 = QtWidgets.QGridLayout()
  145. self.tools_box.addLayout(grid2)
  146. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  147. self.addtool_btn.setToolTip(
  148. _("Add a new tool to the Tool Table\n"
  149. "with the diameter specified above.")
  150. )
  151. # self.copytool_btn = QtWidgets.QPushButton('Copy')
  152. # self.copytool_btn.setToolTip(
  153. # "Copy a selection of tools in the Tool Table\n"
  154. # "by first selecting a row in the Tool Table."
  155. # )
  156. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  157. self.deltool_btn.setToolTip(
  158. _("Delete a selection of tools in the Tool Table\n"
  159. "by first selecting a row(s) in the Tool Table.")
  160. )
  161. grid2.addWidget(self.addtool_btn, 0, 0)
  162. # grid2.addWidget(self.copytool_btn, 0, 1)
  163. grid2.addWidget(self.deltool_btn, 0, 2)
  164. self.empty_label_0 = QtWidgets.QLabel('')
  165. self.tools_box.addWidget(self.empty_label_0)
  166. grid3 = QtWidgets.QGridLayout()
  167. self.tools_box.addLayout(grid3)
  168. # Overlap
  169. ovlabel = QtWidgets.QLabel('%s:' % _('Overlap Rate'))
  170. ovlabel.setToolTip(
  171. _("How much (fraction) of the tool width to overlap each tool pass.\n"
  172. "Example:\n"
  173. "A value here of 0.25 means 25% from the tool diameter found above.\n\n"
  174. "Adjust the value starting with lower values\n"
  175. "and increasing it if areas that should be painted are still \n"
  176. "not painted.\n"
  177. "Lower values = faster processing, faster execution on PCB.\n"
  178. "Higher values = slow processing and slow execution on CNC\n"
  179. "due of too many paths.")
  180. )
  181. grid3.addWidget(ovlabel, 1, 0)
  182. self.paintoverlap_entry = FCEntry()
  183. grid3.addWidget(self.paintoverlap_entry, 1, 1)
  184. # Margin
  185. marginlabel = QtWidgets.QLabel('%s:' % _('Margin'))
  186. marginlabel.setToolTip(
  187. _("Distance by which to avoid\n"
  188. "the edges of the polygon to\n"
  189. "be painted.")
  190. )
  191. grid3.addWidget(marginlabel, 2, 0)
  192. self.paintmargin_entry = FCEntry()
  193. grid3.addWidget(self.paintmargin_entry, 2, 1)
  194. # Method
  195. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  196. methodlabel.setToolTip(
  197. _("Algorithm for non-copper clearing:<BR>"
  198. "<B>Standard</B>: Fixed step inwards.<BR>"
  199. "<B>Seed-based</B>: Outwards from seed.<BR>"
  200. "<B>Line-based</B>: Parallel lines.")
  201. )
  202. grid3.addWidget(methodlabel, 3, 0)
  203. self.paintmethod_combo = RadioSet([
  204. {"label": _("Standard"), "value": "standard"},
  205. {"label": _("Seed-based"), "value": "seed"},
  206. {"label": _("Straight lines"), "value": "lines"}
  207. ], orientation='vertical', stretch=False)
  208. grid3.addWidget(self.paintmethod_combo, 3, 1)
  209. # Connect lines
  210. pathconnectlabel = QtWidgets.QLabel('%s:' % _("Connect"))
  211. pathconnectlabel.setToolTip(
  212. _("Draw lines between resulting\n"
  213. "segments to minimize tool lifts.")
  214. )
  215. grid3.addWidget(pathconnectlabel, 4, 0)
  216. self.pathconnect_cb = FCCheckBox()
  217. grid3.addWidget(self.pathconnect_cb, 4, 1)
  218. contourlabel = QtWidgets.QLabel('%s:' % _("Contour"))
  219. contourlabel.setToolTip(
  220. _("Cut around the perimeter of the polygon\n"
  221. "to trim rough edges.")
  222. )
  223. grid3.addWidget(contourlabel, 5, 0)
  224. self.paintcontour_cb = FCCheckBox()
  225. grid3.addWidget(self.paintcontour_cb, 5, 1)
  226. restlabel = QtWidgets.QLabel('%s:' % _("Rest M."))
  227. restlabel.setToolTip(
  228. _("If checked, use 'rest machining'.\n"
  229. "Basically it will clear copper outside PCB features,\n"
  230. "using the biggest tool and continue with the next tools,\n"
  231. "from bigger to smaller, to clear areas of copper that\n"
  232. "could not be cleared by previous tool, until there is\n"
  233. "no more copper to clear or there are no more tools.\n\n"
  234. "If not checked, use the standard algorithm.")
  235. )
  236. grid3.addWidget(restlabel, 6, 0)
  237. self.rest_cb = FCCheckBox()
  238. grid3.addWidget(self.rest_cb, 6, 1)
  239. # Polygon selection
  240. selectlabel = QtWidgets.QLabel('%s:' % _('Selection'))
  241. selectlabel.setToolTip(
  242. _("How to select the polygons to paint.<BR>"
  243. "Options:<BR>"
  244. "- <B>Single Polygons</B>: left mouse click on the polygon to be painted.<BR>"
  245. "- <B>Area Selection</B>: left mouse click to start selection of the area to be painted.<BR>"
  246. "- <B>All Polygons</B>: paint all polygons.<BR>"
  247. "- <B>Reference Object</B>: paint an area described by an external reference object.")
  248. )
  249. grid3.addWidget(selectlabel, 7, 0)
  250. # grid3 = QtWidgets.QGridLayout()
  251. self.selectmethod_combo = RadioSet([
  252. {"label": _("Single Polygon"), "value": "single"},
  253. {"label": _("Area Selection"), "value": "area"},
  254. {"label": _("All Polygons"), "value": "all"},
  255. {"label": _("Reference Object"), "value": "ref"}
  256. ], orientation='vertical', stretch=False)
  257. self.selectmethod_combo.setToolTip(
  258. _("How to select the polygons to paint.<BR>"
  259. "Options:<BR>"
  260. "- <B>Single Polygons</B>: left mouse click on the polygon to be painted.<BR>"
  261. "- <B>Area Selection</B>: left mouse click to start selection of the area to be painted.<BR>"
  262. "- <B>All Polygons</B>: paint all polygons.<BR>"
  263. "- <B>Reference Object</B>: paint an area described by an external reference object.")
  264. )
  265. grid3.addWidget(self.selectmethod_combo, 7, 1)
  266. form1 = QtWidgets.QFormLayout()
  267. self.tools_box.addLayout(form1)
  268. self.box_combo_type_label = QtWidgets.QLabel('%s:' % _("Ref. Type"))
  269. self.box_combo_type_label.setToolTip(
  270. _("The type of FlatCAM object to be used as paint reference.\n"
  271. "It can be Gerber, Excellon or Geometry.")
  272. )
  273. self.box_combo_type = QtWidgets.QComboBox()
  274. self.box_combo_type.addItem(_("Gerber Reference Box Object"))
  275. self.box_combo_type.addItem(_("Excellon Reference Box Object"))
  276. self.box_combo_type.addItem(_("Geometry Reference Box Object"))
  277. form1.addRow(self.box_combo_type_label, self.box_combo_type)
  278. self.box_combo_label = QtWidgets.QLabel('%s:' % _("Ref. Object"))
  279. self.box_combo_label.setToolTip(
  280. _("The FlatCAM object to be used as non copper clearing reference.")
  281. )
  282. self.box_combo = QtWidgets.QComboBox()
  283. self.box_combo.setModel(self.app.collection)
  284. self.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  285. self.box_combo.setCurrentIndex(1)
  286. form1.addRow(self.box_combo_label, self.box_combo)
  287. self.box_combo.hide()
  288. self.box_combo_label.hide()
  289. self.box_combo_type.hide()
  290. self.box_combo_type_label.hide()
  291. # GO Button
  292. self.generate_paint_button = QtWidgets.QPushButton(_('Create Paint Geometry'))
  293. self.generate_paint_button.setToolTip(
  294. _("After clicking here, click inside<BR>"
  295. "the polygon you wish to be painted if <B>Single</B> is selected.<BR>"
  296. "If <B>Area</B> is selected, then the selection of the area to be painted<BR>"
  297. "will be initiated by a first click and finished by the second mouse click.<BR>"
  298. "If <B>All</B> is selected then the Paint will start after click.<BR>"
  299. "If <B>Ref</B> is selected then the Paint will start after click,<BR>"
  300. "and the painted area will be described by a selected object.<BR>"
  301. "A new Geometry object with the tool paths will be created.")
  302. )
  303. self.tools_box.addWidget(self.generate_paint_button)
  304. self.tools_box.addStretch()
  305. self.obj_name = ""
  306. self.paint_obj = None
  307. self.units = ''
  308. self.paint_tools = {}
  309. self.tooluid = 0
  310. self.first_click = False
  311. self.cursor_pos = None
  312. self.mouse_is_dragging = False
  313. self.sel_rect = []
  314. # store here the default data for Geometry Data
  315. self.default_data = {}
  316. self.default_data.update({
  317. "name": '_paint',
  318. "plot": self.app.defaults["geometry_plot"],
  319. "cutz": self.app.defaults["geometry_cutz"],
  320. "vtipdia": 0.1,
  321. "vtipangle": 30,
  322. "travelz": self.app.defaults["geometry_travelz"],
  323. "feedrate": self.app.defaults["geometry_feedrate"],
  324. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  325. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  326. "dwell": self.app.defaults["geometry_dwell"],
  327. "dwelltime": self.app.defaults["geometry_dwelltime"],
  328. "multidepth": self.app.defaults["geometry_multidepth"],
  329. "ppname_g": self.app.defaults["geometry_ppname_g"],
  330. "depthperpass": self.app.defaults["geometry_depthperpass"],
  331. "extracut": self.app.defaults["geometry_extracut"],
  332. "toolchange": self.app.defaults["geometry_toolchange"],
  333. "toolchangez": self.app.defaults["geometry_toolchangez"],
  334. "endz": self.app.defaults["geometry_endz"],
  335. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  336. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  337. "startz": self.app.defaults["geometry_startz"],
  338. "tooldia": self.app.defaults["tools_painttooldia"],
  339. "paintmargin": self.app.defaults["tools_paintmargin"],
  340. "paintmethod": self.app.defaults["tools_paintmethod"],
  341. "selectmethod": self.app.defaults["tools_selectmethod"],
  342. "pathconnect": self.app.defaults["tools_pathconnect"],
  343. "paintcontour": self.app.defaults["tools_paintcontour"],
  344. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  345. })
  346. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  347. # ## Signals
  348. self.addtool_btn.clicked.connect(self.on_tool_add)
  349. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  350. # self.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  351. self.tools_table.itemChanged.connect(self.on_tool_edit)
  352. self.deltool_btn.clicked.connect(self.on_tool_delete)
  353. self.generate_paint_button.clicked.connect(self.on_paint_button_click)
  354. self.selectmethod_combo.activated_custom.connect(self.on_radio_selection)
  355. self.order_radio.activated_custom[str].connect(self.on_order_changed)
  356. self.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  357. self.box_combo_type.currentIndexChanged.connect(self.on_combo_box_type)
  358. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  359. def on_type_obj_index_changed(self, index):
  360. obj_type = self.type_obj_combo.currentIndex()
  361. self.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  362. self.obj_combo.setCurrentIndex(0)
  363. def install(self, icon=None, separator=None, **kwargs):
  364. FlatCAMTool.install(self, icon, separator, shortcut='ALT+P', **kwargs)
  365. def run(self, toggle=True):
  366. self.app.report_usage("ToolPaint()")
  367. if toggle:
  368. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  369. if self.app.ui.splitter.sizes()[0] == 0:
  370. self.app.ui.splitter.setSizes([1, 1])
  371. else:
  372. try:
  373. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  374. self.app.ui.splitter.setSizes([0, 1])
  375. except AttributeError:
  376. pass
  377. else:
  378. if self.app.ui.splitter.sizes()[0] == 0:
  379. self.app.ui.splitter.setSizes([1, 1])
  380. FlatCAMTool.run(self)
  381. self.set_tool_ui()
  382. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  383. def on_radio_selection(self):
  384. if self.selectmethod_combo.get_value() == "ref":
  385. self.box_combo.show()
  386. self.box_combo_label.show()
  387. self.box_combo_type.show()
  388. self.box_combo_type_label.show()
  389. else:
  390. self.box_combo.hide()
  391. self.box_combo_label.hide()
  392. self.box_combo_type.hide()
  393. self.box_combo_type_label.hide()
  394. if self.selectmethod_combo.get_value() == 'single':
  395. # disable rest-machining for single polygon painting
  396. self.rest_cb.set_value(False)
  397. self.rest_cb.setDisabled(True)
  398. # delete all tools except first row / tool for single polygon painting
  399. list_to_del = list(range(1, self.tools_table.rowCount()))
  400. if list_to_del:
  401. self.on_tool_delete(rows_to_delete=list_to_del)
  402. # disable addTool and delTool
  403. self.addtool_entry.setDisabled(True)
  404. self.addtool_btn.setDisabled(True)
  405. self.deltool_btn.setDisabled(True)
  406. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  407. if self.selectmethod_combo.get_value() == 'area':
  408. # disable rest-machining for single polygon painting
  409. self.rest_cb.set_value(False)
  410. self.rest_cb.setDisabled(True)
  411. else:
  412. self.rest_cb.setDisabled(False)
  413. self.addtool_entry.setDisabled(False)
  414. self.addtool_btn.setDisabled(False)
  415. self.deltool_btn.setDisabled(False)
  416. self.tools_table.setContextMenuPolicy(Qt.ActionsContextMenu)
  417. def on_order_changed(self, order):
  418. if order != 'no':
  419. self.build_ui()
  420. def on_rest_machining_check(self, state):
  421. if state:
  422. self.order_radio.set_value('rev')
  423. self.order_label.setDisabled(True)
  424. self.order_radio.setDisabled(True)
  425. else:
  426. self.order_label.setDisabled(False)
  427. self.order_radio.setDisabled(False)
  428. def set_tool_ui(self):
  429. self.tools_frame.show()
  430. self.reset_fields()
  431. # ## Init the GUI interface
  432. self.order_radio.set_value(self.app.defaults["tools_paintorder"])
  433. self.paintmargin_entry.set_value(self.default_data["paintmargin"])
  434. self.paintmethod_combo.set_value(self.default_data["paintmethod"])
  435. self.selectmethod_combo.set_value(self.default_data["selectmethod"])
  436. self.pathconnect_cb.set_value(self.default_data["pathconnect"])
  437. self.paintcontour_cb.set_value(self.default_data["paintcontour"])
  438. self.paintoverlap_entry.set_value(self.default_data["paintoverlap"])
  439. # updated units
  440. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  441. if self.units == "IN":
  442. self.addtool_entry.set_value(0.039)
  443. else:
  444. self.addtool_entry.set_value(1)
  445. self.tools_table.setupContextMenu()
  446. self.tools_table.addContextMenu(
  447. "Add", lambda: self.on_tool_add(dia=None, muted=None), icon=QtGui.QIcon("share/plus16.png"))
  448. self.tools_table.addContextMenu(
  449. "Delete", lambda:
  450. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  451. # set the working variables to a known state
  452. self.paint_tools.clear()
  453. self.tooluid = 0
  454. self.default_data.clear()
  455. self.default_data.update({
  456. "name": '_paint',
  457. "plot": self.app.defaults["geometry_plot"],
  458. "cutz": self.app.defaults["geometry_cutz"],
  459. "vtipdia": 0.1,
  460. "vtipangle": 30,
  461. "travelz": self.app.defaults["geometry_travelz"],
  462. "feedrate": self.app.defaults["geometry_feedrate"],
  463. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  464. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  465. "dwell": self.app.defaults["geometry_dwell"],
  466. "dwelltime": self.app.defaults["geometry_dwelltime"],
  467. "multidepth": self.app.defaults["geometry_multidepth"],
  468. "ppname_g": self.app.defaults["geometry_ppname_g"],
  469. "depthperpass": self.app.defaults["geometry_depthperpass"],
  470. "extracut": self.app.defaults["geometry_extracut"],
  471. "toolchange": self.app.defaults["geometry_toolchange"],
  472. "toolchangez": self.app.defaults["geometry_toolchangez"],
  473. "endz": self.app.defaults["geometry_endz"],
  474. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  475. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  476. "startz": self.app.defaults["geometry_startz"],
  477. "tooldia": self.app.defaults["tools_painttooldia"],
  478. "paintmargin": self.app.defaults["tools_paintmargin"],
  479. "paintmethod": self.app.defaults["tools_paintmethod"],
  480. "selectmethod": self.app.defaults["tools_selectmethod"],
  481. "pathconnect": self.app.defaults["tools_pathconnect"],
  482. "paintcontour": self.app.defaults["tools_paintcontour"],
  483. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  484. })
  485. # call on self.on_tool_add() counts as an call to self.build_ui()
  486. # through this, we add a initial row / tool in the tool_table
  487. self.on_tool_add(self.app.defaults["tools_painttooldia"], muted=True)
  488. # if the Paint Method is "Single" disable the tool table context menu
  489. if self.default_data["selectmethod"] == "single":
  490. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  491. def build_ui(self):
  492. try:
  493. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  494. self.tools_table.itemChanged.disconnect()
  495. except (TypeError, AttributeError):
  496. pass
  497. # updated units
  498. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  499. sorted_tools = []
  500. for k, v in self.paint_tools.items():
  501. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  502. order = self.order_radio.get_value()
  503. if order == 'fwd':
  504. sorted_tools.sort(reverse=False)
  505. elif order == 'rev':
  506. sorted_tools.sort(reverse=True)
  507. else:
  508. pass
  509. n = len(sorted_tools)
  510. self.tools_table.setRowCount(n)
  511. tool_id = 0
  512. for tool_sorted in sorted_tools:
  513. for tooluid_key, tooluid_value in self.paint_tools.items():
  514. if float('%.4f' % tooluid_value['tooldia']) == tool_sorted:
  515. tool_id += 1
  516. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  517. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  518. row_no = tool_id - 1
  519. self.tools_table.setItem(row_no, 0, id) # Tool name/id
  520. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  521. # There are no drill bits in MM with more than 3 decimals diameter
  522. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  523. if self.units == 'MM':
  524. dia = QtWidgets.QTableWidgetItem('%.2f' % tooluid_value['tooldia'])
  525. else:
  526. dia = QtWidgets.QTableWidgetItem('%.4f' % tooluid_value['tooldia'])
  527. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  528. tool_type_item = QtWidgets.QComboBox()
  529. for item in self.tool_type_item_options:
  530. tool_type_item.addItem(item)
  531. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  532. idx = tool_type_item.findText(tooluid_value['tool_type'])
  533. tool_type_item.setCurrentIndex(idx)
  534. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  535. self.tools_table.setItem(row_no, 1, dia) # Diameter
  536. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  537. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  538. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  539. # make the diameter column editable
  540. for row in range(tool_id):
  541. self.tools_table.item(row, 1).setFlags(
  542. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  543. # all the tools are selected by default
  544. self.tools_table.selectColumn(0)
  545. #
  546. self.tools_table.resizeColumnsToContents()
  547. self.tools_table.resizeRowsToContents()
  548. vertical_header = self.tools_table.verticalHeader()
  549. vertical_header.hide()
  550. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  551. horizontal_header = self.tools_table.horizontalHeader()
  552. horizontal_header.setMinimumSectionSize(10)
  553. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  554. horizontal_header.resizeSection(0, 20)
  555. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  556. # self.tools_table.setSortingEnabled(True)
  557. # sort by tool diameter
  558. # self.tools_table.sortItems(1)
  559. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  560. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  561. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  562. self.tools_table.itemChanged.connect(self.on_tool_edit)
  563. def on_combo_box_type(self):
  564. obj_type = self.box_combo_type.currentIndex()
  565. self.box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  566. self.box_combo.setCurrentIndex(0)
  567. def on_tool_add(self, dia=None, muted=None):
  568. try:
  569. self.tools_table.itemChanged.disconnect()
  570. except Exception as e:
  571. log.debug("ToolPaint.on_tool_add() --> %s" % str(e))
  572. if dia:
  573. tool_dia = dia
  574. else:
  575. try:
  576. tool_dia = float(self.addtool_entry.get_value())
  577. except ValueError:
  578. # try to convert comma to decimal point. if it's still not working error message and return
  579. try:
  580. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  581. except ValueError:
  582. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  583. "use a number."))
  584. return
  585. if tool_dia is None:
  586. self.build_ui()
  587. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter to add, in Float format."))
  588. return
  589. # construct a list of all 'tooluid' in the self.tools
  590. tool_uid_list = []
  591. for tooluid_key in self.paint_tools:
  592. tool_uid_item = int(tooluid_key)
  593. tool_uid_list.append(tool_uid_item)
  594. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  595. if not tool_uid_list:
  596. max_uid = 0
  597. else:
  598. max_uid = max(tool_uid_list)
  599. self.tooluid = int(max_uid + 1)
  600. tool_dias = []
  601. for k, v in self.paint_tools.items():
  602. for tool_v in v.keys():
  603. if tool_v == 'tooldia':
  604. tool_dias.append(float('%.4f' % v[tool_v]))
  605. if float('%.4f' % tool_dia) in tool_dias:
  606. if muted is None:
  607. self.app.inform.emit(_("[WARNING_NOTCL] Adding tool cancelled. Tool already in Tool Table."))
  608. self.tools_table.itemChanged.connect(self.on_tool_edit)
  609. return
  610. else:
  611. if muted is None:
  612. self.app.inform.emit(_("[success] New tool added to Tool Table."))
  613. self.paint_tools.update({
  614. int(self.tooluid): {
  615. 'tooldia': float('%.4f' % tool_dia),
  616. 'offset': 'Path',
  617. 'offset_value': 0.0,
  618. 'type': 'Iso',
  619. 'tool_type': 'V',
  620. 'data': dict(self.default_data),
  621. 'solid_geometry': []
  622. }
  623. })
  624. self.build_ui()
  625. def on_tool_edit(self):
  626. old_tool_dia = ''
  627. try:
  628. self.tools_table.itemChanged.disconnect()
  629. except Exception as e:
  630. log.debug("ToolPaint.on_tool_edit() --> %s" % str(e))
  631. tool_dias = []
  632. for k, v in self.paint_tools.items():
  633. for tool_v in v.keys():
  634. if tool_v == 'tooldia':
  635. tool_dias.append(float('%.4f' % v[tool_v]))
  636. for row in range(self.tools_table.rowCount()):
  637. try:
  638. new_tool_dia = float(self.tools_table.item(row, 1).text())
  639. except ValueError:
  640. # try to convert comma to decimal point. if it's still not working error message and return
  641. try:
  642. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  643. except ValueError:
  644. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  645. "use a number."))
  646. return
  647. tooluid = int(self.tools_table.item(row, 3).text())
  648. # identify the tool that was edited and get it's tooluid
  649. if new_tool_dia not in tool_dias:
  650. self.paint_tools[tooluid]['tooldia'] = new_tool_dia
  651. self.app.inform.emit(_("[success] Tool from Tool Table was edited."))
  652. self.build_ui()
  653. return
  654. else:
  655. # identify the old tool_dia and restore the text in tool table
  656. for k, v in self.paint_tools.items():
  657. if k == tooluid:
  658. old_tool_dia = v['tooldia']
  659. break
  660. restore_dia_item = self.tools_table.item(row, 1)
  661. restore_dia_item.setText(str(old_tool_dia))
  662. self.app.inform.emit(_("[WARNING_NOTCL] Edit cancelled. "
  663. "New diameter value is already in the Tool Table."))
  664. self.build_ui()
  665. # def on_tool_copy(self, all=None):
  666. # try:
  667. # self.tools_table.itemChanged.disconnect()
  668. # except:
  669. # pass
  670. #
  671. # # find the tool_uid maximum value in the self.tools
  672. # uid_list = []
  673. # for key in self.paint_tools:
  674. # uid_list.append(int(key))
  675. # try:
  676. # max_uid = max(uid_list, key=int)
  677. # except ValueError:
  678. # max_uid = 0
  679. #
  680. # if all is None:
  681. # if self.tools_table.selectedItems():
  682. # for current_row in self.tools_table.selectedItems():
  683. # # sometime the header get selected and it has row number -1
  684. # # we don't want to do anything with the header :)
  685. # if current_row.row() < 0:
  686. # continue
  687. # try:
  688. # tooluid_copy = int(self.tools_table.item(current_row.row(), 3).text())
  689. # max_uid += 1
  690. # self.paint_tools[int(max_uid)] = dict(self.paint_tools[tooluid_copy])
  691. # for td in self.paint_tools:
  692. # print("COPIED", self.paint_tools[td])
  693. # self.build_ui()
  694. # except AttributeError:
  695. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  696. # self.build_ui()
  697. # return
  698. # except Exception as e:
  699. # log.debug("on_tool_copy() --> " + str(e))
  700. # # deselect the table
  701. # # self.ui.geo_tools_table.clearSelection()
  702. # else:
  703. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  704. # self.build_ui()
  705. # return
  706. # else:
  707. # # we copy all tools in geo_tools_table
  708. # try:
  709. # temp_tools = dict(self.paint_tools)
  710. # max_uid += 1
  711. # for tooluid in temp_tools:
  712. # self.paint_tools[int(max_uid)] = dict(temp_tools[tooluid])
  713. # temp_tools.clear()
  714. # self.build_ui()
  715. # except Exception as e:
  716. # log.debug("on_tool_copy() --> " + str(e))
  717. #
  718. # self.app.inform.emit("[success] Tool was copied in the Tool Table.")
  719. def on_tool_delete(self, rows_to_delete=None, all=None):
  720. try:
  721. self.tools_table.itemChanged.disconnect()
  722. except Exception as e:
  723. log.debug("ToolPaint.on_tool_delete() --> %s" % str(e))
  724. pass
  725. deleted_tools_list = []
  726. if all:
  727. self.paint_tools.clear()
  728. self.build_ui()
  729. return
  730. if rows_to_delete:
  731. try:
  732. for row in rows_to_delete:
  733. tooluid_del = int(self.tools_table.item(row, 3).text())
  734. deleted_tools_list.append(tooluid_del)
  735. except TypeError:
  736. deleted_tools_list.append(rows_to_delete)
  737. for t in deleted_tools_list:
  738. self.paint_tools.pop(t, None)
  739. self.build_ui()
  740. return
  741. try:
  742. if self.tools_table.selectedItems():
  743. for row_sel in self.tools_table.selectedItems():
  744. row = row_sel.row()
  745. if row < 0:
  746. continue
  747. tooluid_del = int(self.tools_table.item(row, 3).text())
  748. deleted_tools_list.append(tooluid_del)
  749. for t in deleted_tools_list:
  750. self.paint_tools.pop(t, None)
  751. except AttributeError:
  752. self.app.inform.emit(_("[WARNING_NOTCL] Delete failed. Select a tool to delete."))
  753. return
  754. except Exception as e:
  755. log.debug(str(e))
  756. self.app.inform.emit(_("[success] Tool(s) deleted from Tool Table."))
  757. self.build_ui()
  758. def on_paint_button_click(self):
  759. self.app.report_usage(_("geometry_on_paint_button"))
  760. # self.app.call_source = 'paint'
  761. try:
  762. overlap = float(self.paintoverlap_entry.get_value())
  763. except ValueError:
  764. # try to convert comma to decimal point. if it's still not working error message and return
  765. try:
  766. overlap = float(self.paintoverlap_entry.get_value().replace(',', '.'))
  767. except ValueError:
  768. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  769. "use a number."))
  770. return
  771. if overlap >= 1 or overlap < 0:
  772. self.app.inform.emit(_("[ERROR_NOTCL] Overlap value must be between "
  773. "0 (inclusive) and 1 (exclusive), "))
  774. return
  775. self.app.inform.emit(_("[WARNING_NOTCL] Click inside the desired polygon."))
  776. connect = self.pathconnect_cb.get_value()
  777. contour = self.paintcontour_cb.get_value()
  778. select_method = self.selectmethod_combo.get_value()
  779. self.obj_name = self.obj_combo.currentText()
  780. # Get source object.
  781. try:
  782. self.paint_obj = self.app.collection.get_by_name(str(self.obj_name))
  783. except Exception as e:
  784. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  785. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  786. return
  787. if self.paint_obj is None:
  788. self.app.inform.emit(_("[ERROR_NOTCL] Object not found: %s") % self.paint_obj)
  789. return
  790. # test if the Geometry Object is multigeo and return Fail if True because
  791. # for now Paint don't work on MultiGeo
  792. if self.paint_obj.multigeo is True:
  793. self.app.inform.emit(_("[ERROR_NOTCL] Can't do Paint on MultiGeo geometries ..."))
  794. return 'Fail'
  795. o_name = '%s_multitool_paint' % self.obj_name
  796. if select_method == "all":
  797. self.paint_poly_all(self.paint_obj,
  798. outname=o_name,
  799. overlap=overlap,
  800. connect=connect,
  801. contour=contour)
  802. elif select_method == "single":
  803. self.app.inform.emit(_("[WARNING_NOTCL] Click inside the desired polygon."))
  804. # use the first tool in the tool table; get the diameter
  805. tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  806. # To be called after clicking on the plot.
  807. def doit(event):
  808. # do paint single only for left mouse clicks
  809. if event.button == 1:
  810. self.app.inform.emit(_("Painting polygon..."))
  811. self.app.plotcanvas.vis_disconnect('mouse_press', doit)
  812. pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  813. if self.app.grid_status() == True:
  814. pos = self.app.geo_editor.snap(pos[0], pos[1])
  815. self.paint_poly(self.paint_obj,
  816. inside_pt=[pos[0], pos[1]],
  817. tooldia=tooldia,
  818. overlap=overlap,
  819. connect=connect,
  820. contour=contour)
  821. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  822. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  823. self.app.plotcanvas.vis_connect('mouse_press', doit)
  824. elif select_method == "area":
  825. self.app.inform.emit(_("[WARNING_NOTCL] Click the start point of the paint area."))
  826. # use the first tool in the tool table; get the diameter
  827. tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  828. # To be called after clicking on the plot.
  829. def on_mouse_release(event):
  830. # do paint single only for left mouse clicks
  831. if event.button == 1:
  832. if not self.first_click:
  833. self.first_click = True
  834. self.app.inform.emit(_("[WARNING_NOTCL] Click the end point of the paint area."))
  835. self.cursor_pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  836. if self.app.grid_status() == True:
  837. self.cursor_pos = self.app.geo_editor.snap(self.cursor_pos[0], self.cursor_pos[1])
  838. else:
  839. self.app.inform.emit(_("Zone added. Right click to finish."))
  840. self.app.delete_selection_shape()
  841. curr_pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  842. if self.app.grid_status() == True:
  843. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  844. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  845. x1, y1 = curr_pos[0], curr_pos[1]
  846. pt1 = (x0, y0)
  847. pt2 = (x1, y0)
  848. pt3 = (x1, y1)
  849. pt4 = (x0, y1)
  850. self.sel_rect.append(Polygon([pt1, pt2, pt3, pt4]))
  851. modifiers = QtWidgets.QApplication.keyboardModifiers()
  852. if modifiers == QtCore.Qt.ShiftModifier:
  853. mod_key = 'Shift'
  854. elif modifiers == QtCore.Qt.ControlModifier:
  855. mod_key = 'Control'
  856. else:
  857. mod_key = None
  858. if mod_key == self.app.defaults["global_mselect_key"]:
  859. self.first_click = False
  860. return
  861. self.sel_rect = cascaded_union(self.sel_rect)
  862. self.paint_poly_area(obj=self.paint_obj,
  863. sel_obj= self.sel_rect,
  864. outname=o_name,
  865. overlap=overlap,
  866. connect=connect,
  867. contour=contour)
  868. self.app.plotcanvas.vis_disconnect('mouse_release', on_mouse_release)
  869. self.app.plotcanvas.vis_disconnect('mouse_move', on_mouse_move)
  870. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  871. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  872. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  873. elif event.button == 2 and self.first_click is False and self.mouse_is_dragging is False:
  874. self.first_click = False
  875. self.app.plotcanvas.vis_disconnect('mouse_release', on_mouse_release)
  876. self.app.plotcanvas.vis_disconnect('mouse_move', on_mouse_move)
  877. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  878. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  879. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  880. self.sel_rect = cascaded_union(self.sel_rect)
  881. self.paint_poly_area(obj=self.paint_obj,
  882. sel_obj=self.sel_rect,
  883. outname=o_name,
  884. overlap=overlap,
  885. connect=connect,
  886. contour=contour)
  887. # called on mouse move
  888. def on_mouse_move(event):
  889. curr_pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  890. self.app.app_cursor.enabled = False
  891. if event.button == 2:
  892. if event.is_dragging is True:
  893. self.mouse_is_dragging = True
  894. else:
  895. self.mouse_is_dragging = False
  896. if self.app.grid_status() == True:
  897. self.app.app_cursor.enabled = True
  898. # Update cursor
  899. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  900. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  901. symbol='++', edge_color='black', size=20)
  902. if self.first_click:
  903. self.app.delete_selection_shape()
  904. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  905. coords=(curr_pos[0], curr_pos[1]),
  906. face_alpha=0.0)
  907. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  908. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  909. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  910. self.app.plotcanvas.vis_connect('mouse_release', on_mouse_release)
  911. self.app.plotcanvas.vis_connect('mouse_move', on_mouse_move)
  912. elif select_method == 'ref':
  913. self.bound_obj_name = self.box_combo.currentText()
  914. # Get source object.
  915. try:
  916. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  917. except Exception as e:
  918. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  919. return "Could not retrieve object: %s" % self.obj_name
  920. geo = self.bound_obj.solid_geometry
  921. try:
  922. if isinstance(geo, MultiPolygon):
  923. env_obj = geo.convex_hull
  924. elif (isinstance(geo, MultiPolygon) and len(geo) == 1) or \
  925. (isinstance(geo, list) and len(geo) == 1) and isinstance(geo[0], Polygon):
  926. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  927. else:
  928. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  929. env_obj = env_obj.convex_hull
  930. sel_rect = env_obj.buffer(distance=0.0000001, join_style=base.JOIN_STYLE.mitre)
  931. except Exception as e:
  932. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  933. self.app.inform.emit(_("[ERROR_NOTCL] No object available."))
  934. return
  935. self.paint_poly_area(obj=self.paint_obj,
  936. sel_obj=sel_rect,
  937. outname=o_name,
  938. overlap=overlap,
  939. connect=connect,
  940. contour=contour)
  941. def paint_poly(self, obj, inside_pt, tooldia, overlap, outname=None, connect=True, contour=True):
  942. """
  943. Paints a polygon selected by clicking on its interior.
  944. Note:
  945. * The margin is taken directly from the form.
  946. :param obj: painted object
  947. :param inside_pt: [x, y]
  948. :param tooldia: Diameter of the painting tool
  949. :param overlap: Overlap of the tool between passes.
  950. :param outname: Name of the resulting Geometry Object.
  951. :param connect: Connect lines to avoid tool lifts.
  952. :param contour: Paint around the edges.
  953. :return: None
  954. """
  955. # Which polygon.
  956. # poly = find_polygon(self.solid_geometry, inside_pt)
  957. poly = self.find_polygon(point=inside_pt, geoset=obj.solid_geometry)
  958. paint_method = self.paintmethod_combo.get_value()
  959. try:
  960. paint_margin = float(self.paintmargin_entry.get_value())
  961. except ValueError:
  962. # try to convert comma to decimal point. if it's still not working error message and return
  963. try:
  964. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  965. except ValueError:
  966. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  967. "use a number."))
  968. return
  969. # No polygon?
  970. if poly is None:
  971. self.app.log.warning('No polygon found.')
  972. self.app.inform.emit(_('[WARNING] No polygon found.'))
  973. return
  974. proc = self.app.proc_container.new(_("Painting polygon."))
  975. name = outname if outname else self.obj_name + "_paint"
  976. # Initializes the new geometry object
  977. def gen_paintarea(geo_obj, app_obj):
  978. assert isinstance(geo_obj, FlatCAMGeometry), \
  979. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  980. # assert isinstance(app_obj, App)
  981. def paint_p(polyg):
  982. if paint_method == "seed":
  983. # Type(cp) == FlatCAMRTreeStorage | None
  984. cpoly = self.clear_polygon2(polyg,
  985. tooldia=tooldia,
  986. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  987. overlap=overlap,
  988. contour=contour,
  989. connect=connect)
  990. elif paint_method == "lines":
  991. # Type(cp) == FlatCAMRTreeStorage | None
  992. cpoly = self.clear_polygon3(polyg,
  993. tooldia=tooldia,
  994. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  995. overlap=overlap,
  996. contour=contour,
  997. connect=connect)
  998. else:
  999. # Type(cp) == FlatCAMRTreeStorage | None
  1000. cpoly = self.clear_polygon(polyg,
  1001. tooldia=tooldia,
  1002. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1003. overlap=overlap,
  1004. contour=contour,
  1005. connect=connect)
  1006. if cpoly is not None:
  1007. geo_obj.solid_geometry += list(cpoly.get_objects())
  1008. return cpoly
  1009. else:
  1010. self.app.inform.emit(_('[ERROR_NOTCL] Geometry could not be painted completely'))
  1011. return None
  1012. geo_obj.solid_geometry = []
  1013. try:
  1014. a, b, c, d = poly.bounds
  1015. geo_obj.options['xmin'] = a
  1016. geo_obj.options['ymin'] = b
  1017. geo_obj.options['xmax'] = c
  1018. geo_obj.options['ymax'] = d
  1019. except Exception as e:
  1020. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1021. return
  1022. try:
  1023. poly_buf = poly.buffer(-paint_margin)
  1024. if isinstance(poly_buf, MultiPolygon):
  1025. cp = []
  1026. for pp in poly_buf:
  1027. cp.append(paint_p(pp))
  1028. else:
  1029. cp = paint_p(poly_buf)
  1030. except Exception as e:
  1031. log.debug("Could not Paint the polygons. %s" % str(e))
  1032. self.app.inform.emit(
  1033. _("[ERROR] Could not do Paint. Try a different combination of parameters. "
  1034. "Or a different strategy of paint\n%s") % str(e))
  1035. return
  1036. if cp is not None:
  1037. if isinstance(cp, list):
  1038. for x in cp:
  1039. geo_obj.solid_geometry += list(x.get_objects())
  1040. else:
  1041. geo_obj.solid_geometry = list(cp.get_objects())
  1042. geo_obj.options["cnctooldia"] = str(tooldia)
  1043. # this turn on the FlatCAMCNCJob plot for multiple tools
  1044. geo_obj.multigeo = False
  1045. geo_obj.multitool = True
  1046. current_uid = int(self.tools_table.item(0, 3).text())
  1047. for k, v in self.paint_tools.items():
  1048. if k == current_uid:
  1049. v['data']['name'] = name
  1050. geo_obj.tools = dict(self.paint_tools)
  1051. # Experimental...
  1052. # print("Indexing...", end=' ')
  1053. # geo_obj.make_index()
  1054. # if errors == 0:
  1055. # print("[success] Paint single polygon Done")
  1056. # self.app.inform.emit("[success] Paint single polygon Done")
  1057. # else:
  1058. # print("[WARNING] Paint single polygon done with errors")
  1059. # self.app.inform.emit("[WARNING] Paint single polygon done with errors. "
  1060. # "%d area(s) could not be painted.\n"
  1061. # "Use different paint parameters or edit the paint geometry and correct"
  1062. # "the issue."
  1063. # % errors)
  1064. def job_thread(app_obj):
  1065. try:
  1066. app_obj.new_object("geometry", name, gen_paintarea)
  1067. except Exception as e:
  1068. proc.done()
  1069. self.app.inform.emit(_('[ERROR_NOTCL] PaintTool.paint_poly() --> %s') % str(e))
  1070. return
  1071. proc.done()
  1072. # focus on Selected Tab
  1073. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1074. self.app.inform.emit(_("Polygon Paint started ..."))
  1075. # Promise object with the new name
  1076. self.app.collection.promise(name)
  1077. # Background
  1078. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1079. def paint_poly_all(self, obj, overlap, outname=None, connect=True, contour=True):
  1080. """
  1081. Paints all polygons in this object.
  1082. :param obj: painted object
  1083. :param overlap:
  1084. :param outname:
  1085. :param connect: Connect lines to avoid tool lifts.
  1086. :param contour: Paint around the edges.
  1087. :return:
  1088. """
  1089. paint_method = self.paintmethod_combo.get_value()
  1090. try:
  1091. paint_margin = float(self.paintmargin_entry.get_value())
  1092. except ValueError:
  1093. # try to convert comma to decimal point. if it's still not working error message and return
  1094. try:
  1095. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  1096. except ValueError:
  1097. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  1098. "use a number."))
  1099. return
  1100. proc = self.app.proc_container.new(_("Painting polygon..."))
  1101. name = outname if outname else self.obj_name + "_paint"
  1102. over = overlap
  1103. conn = connect
  1104. cont = contour
  1105. # This is a recursive generator of individual Polygons.
  1106. # Note: Double check correct implementation. Might exit
  1107. # early if it finds something that is not a Polygon?
  1108. # def recurse(geo):
  1109. # try:
  1110. # for subg in geo:
  1111. # for subsubg in recurse(subg):
  1112. # yield subsubg
  1113. # except TypeError:
  1114. # if isinstance(geo, Polygon):
  1115. # yield geo
  1116. #
  1117. # raise StopIteration
  1118. def recurse(geometry, reset=True):
  1119. """
  1120. Creates a list of non-iterable linear geometry objects.
  1121. Results are placed in self.flat_geometry
  1122. :param geometry: Shapely type or list or list of list of such.
  1123. :param reset: Clears the contents of self.flat_geometry.
  1124. """
  1125. if geometry is None:
  1126. return
  1127. if reset:
  1128. self.flat_geometry = []
  1129. # ## If iterable, expand recursively.
  1130. try:
  1131. for geo in geometry:
  1132. if geo is not None:
  1133. recurse(geometry=geo, reset=False)
  1134. # ## Not iterable, do the actual indexing and add.
  1135. except TypeError:
  1136. if isinstance(geometry, LinearRing):
  1137. g = Polygon(geometry)
  1138. self.flat_geometry.append(g)
  1139. else:
  1140. self.flat_geometry.append(geometry)
  1141. return self.flat_geometry
  1142. # Initializes the new geometry object
  1143. def gen_paintarea(geo_obj, app_obj):
  1144. assert isinstance(geo_obj, FlatCAMGeometry), \
  1145. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1146. tool_dia = None
  1147. sorted_tools = []
  1148. for row in range(self.tools_table.rowCount()):
  1149. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1150. order = self.order_radio.get_value()
  1151. if order == 'fwd':
  1152. sorted_tools.sort(reverse=False)
  1153. elif order == 'rev':
  1154. sorted_tools.sort(reverse=True)
  1155. else:
  1156. pass
  1157. try:
  1158. a, b, c, d = obj.bounds()
  1159. geo_obj.options['xmin'] = a
  1160. geo_obj.options['ymin'] = b
  1161. geo_obj.options['xmax'] = c
  1162. geo_obj.options['ymax'] = d
  1163. except Exception as e:
  1164. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1165. return
  1166. total_geometry = []
  1167. current_uid = int(1)
  1168. geo_obj.solid_geometry = []
  1169. for tool_dia in sorted_tools:
  1170. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1171. for k, v in self.paint_tools.items():
  1172. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1173. current_uid = int(k)
  1174. break
  1175. for geo in recurse(obj.solid_geometry):
  1176. try:
  1177. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  1178. if not isinstance(geo, Polygon):
  1179. continue
  1180. poly_buf = geo.buffer(-paint_margin)
  1181. if paint_method == "seed":
  1182. # Type(cp) == FlatCAMRTreeStorage | None
  1183. cp = self.clear_polygon2(poly_buf,
  1184. tooldia=tool_dia,
  1185. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1186. overlap=over,
  1187. contour=cont,
  1188. connect=conn)
  1189. elif paint_method == "lines":
  1190. # Type(cp) == FlatCAMRTreeStorage | None
  1191. cp = self.clear_polygon3(poly_buf,
  1192. tooldia=tool_dia,
  1193. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1194. overlap=over,
  1195. contour=cont,
  1196. connect=conn)
  1197. else:
  1198. # Type(cp) == FlatCAMRTreeStorage | None
  1199. cp = self.clear_polygon(poly_buf,
  1200. tooldia=tool_dia,
  1201. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1202. overlap=over,
  1203. contour=cont,
  1204. connect=conn)
  1205. if cp is not None:
  1206. total_geometry += list(cp.get_objects())
  1207. except Exception as e:
  1208. log.debug("Could not Paint the polygons. %s" % str(e))
  1209. self.app.inform.emit(
  1210. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1211. "Or a different Method of paint\n%s") % str(e))
  1212. return
  1213. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  1214. # temporary list that stored that solid_geometry
  1215. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1216. self.paint_tools[current_uid]['data']['name'] = name
  1217. total_geometry[:] = []
  1218. geo_obj.options["cnctooldia"] = str(tool_dia)
  1219. # this turn on the FlatCAMCNCJob plot for multiple tools
  1220. geo_obj.multigeo = True
  1221. geo_obj.multitool = True
  1222. geo_obj.tools.clear()
  1223. geo_obj.tools = dict(self.paint_tools)
  1224. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1225. has_solid_geo = 0
  1226. for tooluid in geo_obj.tools:
  1227. if geo_obj.tools[tooluid]['solid_geometry']:
  1228. has_solid_geo += 1
  1229. if has_solid_geo == 0:
  1230. self.app.inform.emit(_("[ERROR] There is no Painting Geometry in the file.\n"
  1231. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1232. "Change the painting parameters and try again."))
  1233. return
  1234. # Experimental...
  1235. # print("Indexing...", end=' ')
  1236. # geo_obj.make_index()
  1237. self.app.inform.emit(_("[success] Paint All Done."))
  1238. # Initializes the new geometry object
  1239. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1240. assert isinstance(geo_obj, FlatCAMGeometry), \
  1241. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1242. tool_dia = None
  1243. sorted_tools = []
  1244. for row in range(self.tools_table.rowCount()):
  1245. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1246. sorted_tools.sort(reverse=True)
  1247. cleared_geo = []
  1248. current_uid = int(1)
  1249. geo_obj.solid_geometry = []
  1250. try:
  1251. a, b, c, d = obj.bounds()
  1252. geo_obj.options['xmin'] = a
  1253. geo_obj.options['ymin'] = b
  1254. geo_obj.options['xmax'] = c
  1255. geo_obj.options['ymax'] = d
  1256. except Exception as e:
  1257. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1258. return
  1259. for tool_dia in sorted_tools:
  1260. for geo in recurse(obj.solid_geometry):
  1261. try:
  1262. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  1263. poly_buf = geo.buffer(-paint_margin)
  1264. cp = None
  1265. if paint_method == "standard":
  1266. # Type(cp) == FlatCAMRTreeStorage | None
  1267. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1268. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1269. overlap=over, contour=cont, connect=conn)
  1270. elif paint_method == "seed":
  1271. # Type(cp) == FlatCAMRTreeStorage | None
  1272. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1273. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1274. overlap=over, contour=cont, connect=conn)
  1275. elif paint_method == "lines":
  1276. # Type(cp) == FlatCAMRTreeStorage | None
  1277. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1278. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1279. overlap=over, contour=cont, connect=conn)
  1280. if cp is not None:
  1281. cleared_geo += list(cp.get_objects())
  1282. except Exception as e:
  1283. log.debug("Could not Paint the polygons. %s" % str(e))
  1284. self.app.inform.emit(
  1285. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1286. "Or a different Method of paint\n%s") % str(e))
  1287. return
  1288. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1289. for k, v in self.paint_tools.items():
  1290. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1291. current_uid = int(k)
  1292. break
  1293. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  1294. # temporary list that stored that solid_geometry
  1295. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1296. self.paint_tools[current_uid]['data']['name'] = name
  1297. cleared_geo[:] = []
  1298. geo_obj.options["cnctooldia"] = str(tool_dia)
  1299. # this turn on the FlatCAMCNCJob plot for multiple tools
  1300. geo_obj.multigeo = True
  1301. geo_obj.multitool = True
  1302. geo_obj.tools.clear()
  1303. geo_obj.tools = dict(self.paint_tools)
  1304. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1305. has_solid_geo = 0
  1306. for tooluid in geo_obj.tools:
  1307. if geo_obj.tools[tooluid]['solid_geometry']:
  1308. has_solid_geo += 1
  1309. if has_solid_geo == 0:
  1310. self.app.inform.emit(_("[ERROR_NOTCL] There is no Painting Geometry in the file.\n"
  1311. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1312. "Change the painting parameters and try again."))
  1313. return
  1314. # Experimental...
  1315. # print("Indexing...", end=' ')
  1316. # geo_obj.make_index()
  1317. self.app.inform.emit(_("[success] Paint All with Rest-Machining done."))
  1318. def job_thread(app_obj):
  1319. try:
  1320. if self.rest_cb.isChecked():
  1321. app_obj.new_object("geometry", name, gen_paintarea_rest_machining)
  1322. else:
  1323. app_obj.new_object("geometry", name, gen_paintarea)
  1324. except Exception as e:
  1325. proc.done()
  1326. traceback.print_stack()
  1327. return
  1328. proc.done()
  1329. # focus on Selected Tab
  1330. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1331. self.app.inform.emit(_("Polygon Paint started ..."))
  1332. # Promise object with the new name
  1333. self.app.collection.promise(name)
  1334. # Background
  1335. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1336. def paint_poly_area(self, obj, sel_obj, overlap, outname=None, connect=True, contour=True):
  1337. """
  1338. Paints all polygons in this object that are within the sel_obj object
  1339. :param obj: painted object
  1340. :param sel_obj: paint only what is inside this object bounds
  1341. :param overlap:
  1342. :param outname:
  1343. :param connect: Connect lines to avoid tool lifts.
  1344. :param contour: Paint around the edges.
  1345. :return:
  1346. """
  1347. paint_method = self.paintmethod_combo.get_value()
  1348. try:
  1349. paint_margin = float(self.paintmargin_entry.get_value())
  1350. except ValueError:
  1351. # try to convert comma to decimal point. if it's still not working error message and return
  1352. try:
  1353. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  1354. except ValueError:
  1355. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  1356. "use a number."))
  1357. return
  1358. proc = self.app.proc_container.new(_("Painting polygon..."))
  1359. name = outname if outname else self.obj_name + "_paint"
  1360. over = overlap
  1361. conn = connect
  1362. cont = contour
  1363. def recurse(geometry, reset=True):
  1364. """
  1365. Creates a list of non-iterable linear geometry objects.
  1366. Results are placed in self.flat_geometry
  1367. :param geometry: Shapely type or list or list of list of such.
  1368. :param reset: Clears the contents of self.flat_geometry.
  1369. """
  1370. if geometry is None:
  1371. return
  1372. if reset:
  1373. self.flat_geometry = []
  1374. # ## If iterable, expand recursively.
  1375. try:
  1376. for geo in geometry:
  1377. if geo is not None:
  1378. recurse(geometry=geo, reset=False)
  1379. # ## Not iterable, do the actual indexing and add.
  1380. except TypeError:
  1381. if isinstance(geometry, LinearRing):
  1382. g = Polygon(geometry)
  1383. self.flat_geometry.append(g)
  1384. else:
  1385. self.flat_geometry.append(geometry)
  1386. return self.flat_geometry
  1387. # Initializes the new geometry object
  1388. def gen_paintarea(geo_obj, app_obj):
  1389. assert isinstance(geo_obj, FlatCAMGeometry), \
  1390. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1391. tool_dia = None
  1392. sorted_tools = []
  1393. for row in range(self.tools_table.rowCount()):
  1394. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1395. order = self.order_radio.get_value()
  1396. if order == 'fwd':
  1397. sorted_tools.sort(reverse=False)
  1398. elif order == 'rev':
  1399. sorted_tools.sort(reverse=True)
  1400. else:
  1401. pass
  1402. geo_to_paint = []
  1403. if not isinstance(obj.solid_geometry, list):
  1404. target_geo = [obj.solid_geometry]
  1405. else:
  1406. target_geo = obj.solid_geometry
  1407. print(target_geo)
  1408. print(sel_obj)
  1409. for poly in target_geo:
  1410. new_pol = poly.intersection(sel_obj)
  1411. geo_to_paint.append(new_pol)
  1412. try:
  1413. a, b, c, d = self.paint_bounds(geo_to_paint)
  1414. geo_obj.options['xmin'] = a
  1415. geo_obj.options['ymin'] = b
  1416. geo_obj.options['xmax'] = c
  1417. geo_obj.options['ymax'] = d
  1418. except Exception as e:
  1419. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1420. return
  1421. total_geometry = []
  1422. current_uid = int(1)
  1423. geo_obj.solid_geometry = []
  1424. for tool_dia in sorted_tools:
  1425. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1426. for k, v in self.paint_tools.items():
  1427. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1428. current_uid = int(k)
  1429. break
  1430. for geo in recurse(geo_to_paint):
  1431. try:
  1432. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  1433. if not isinstance(geo, Polygon):
  1434. continue
  1435. poly_buf = geo.buffer(-paint_margin)
  1436. if paint_method == "seed":
  1437. # Type(cp) == FlatCAMRTreeStorage | None
  1438. cp = self.clear_polygon2(poly_buf,
  1439. tooldia=tool_dia,
  1440. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1441. overlap=over,
  1442. contour=cont,
  1443. connect=conn)
  1444. elif paint_method == "lines":
  1445. # Type(cp) == FlatCAMRTreeStorage | None
  1446. cp = self.clear_polygon3(poly_buf,
  1447. tooldia=tool_dia,
  1448. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1449. overlap=over,
  1450. contour=cont,
  1451. connect=conn)
  1452. else:
  1453. # Type(cp) == FlatCAMRTreeStorage | None
  1454. cp = self.clear_polygon(poly_buf,
  1455. tooldia=tool_dia,
  1456. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1457. overlap=over,
  1458. contour=cont,
  1459. connect=conn)
  1460. if cp is not None:
  1461. total_geometry += list(cp.get_objects())
  1462. except Exception as e:
  1463. log.debug("Could not Paint the polygons. %s" % str(e))
  1464. self.app.inform.emit(
  1465. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1466. "Or a different Method of paint\n%s") % str(e))
  1467. return
  1468. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  1469. # temporary list that stored that solid_geometry
  1470. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1471. self.paint_tools[current_uid]['data']['name'] = name
  1472. total_geometry[:] = []
  1473. geo_obj.options["cnctooldia"] = str(tool_dia)
  1474. # this turn on the FlatCAMCNCJob plot for multiple tools
  1475. geo_obj.multigeo = True
  1476. geo_obj.multitool = True
  1477. geo_obj.tools.clear()
  1478. geo_obj.tools = dict(self.paint_tools)
  1479. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1480. has_solid_geo = 0
  1481. for tooluid in geo_obj.tools:
  1482. if geo_obj.tools[tooluid]['solid_geometry']:
  1483. has_solid_geo += 1
  1484. if has_solid_geo == 0:
  1485. self.app.inform.emit(_("[ERROR] There is no Painting Geometry in the file.\n"
  1486. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1487. "Change the painting parameters and try again."))
  1488. return
  1489. # Experimental...
  1490. # print("Indexing...", end=' ')
  1491. # geo_obj.make_index()
  1492. self.app.inform.emit(_("[success] Paint All Done."))
  1493. # Initializes the new geometry object
  1494. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1495. assert isinstance(geo_obj, FlatCAMGeometry), \
  1496. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1497. tool_dia = None
  1498. sorted_tools = []
  1499. for row in range(self.tools_table.rowCount()):
  1500. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1501. sorted_tools.sort(reverse=True)
  1502. cleared_geo = []
  1503. current_uid = int(1)
  1504. geo_obj.solid_geometry = []
  1505. try:
  1506. a, b, c, d = obj.bounds()
  1507. geo_obj.options['xmin'] = a
  1508. geo_obj.options['ymin'] = b
  1509. geo_obj.options['xmax'] = c
  1510. geo_obj.options['ymax'] = d
  1511. except Exception as e:
  1512. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1513. return
  1514. for tool_dia in sorted_tools:
  1515. for geo in recurse(obj.solid_geometry):
  1516. try:
  1517. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  1518. poly_buf = geo.buffer(-paint_margin)
  1519. cp = None
  1520. if paint_method == "standard":
  1521. # Type(cp) == FlatCAMRTreeStorage | None
  1522. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1523. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1524. overlap=over, contour=cont, connect=conn)
  1525. elif paint_method == "seed":
  1526. # Type(cp) == FlatCAMRTreeStorage | None
  1527. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1528. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1529. overlap=over, contour=cont, connect=conn)
  1530. elif paint_method == "lines":
  1531. # Type(cp) == FlatCAMRTreeStorage | None
  1532. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1533. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1534. overlap=over, contour=cont, connect=conn)
  1535. if cp is not None:
  1536. cleared_geo += list(cp.get_objects())
  1537. except Exception as e:
  1538. log.debug("Could not Paint the polygons. %s" % str(e))
  1539. self.app.inform.emit(
  1540. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1541. "Or a different Method of paint\n%s") % str(e))
  1542. return
  1543. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1544. for k, v in self.paint_tools.items():
  1545. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1546. current_uid = int(k)
  1547. break
  1548. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  1549. # temporary list that stored that solid_geometry
  1550. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1551. self.paint_tools[current_uid]['data']['name'] = name
  1552. cleared_geo[:] = []
  1553. geo_obj.options["cnctooldia"] = str(tool_dia)
  1554. # this turn on the FlatCAMCNCJob plot for multiple tools
  1555. geo_obj.multigeo = True
  1556. geo_obj.multitool = True
  1557. geo_obj.tools.clear()
  1558. geo_obj.tools = dict(self.paint_tools)
  1559. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1560. has_solid_geo = 0
  1561. for tooluid in geo_obj.tools:
  1562. if geo_obj.tools[tooluid]['solid_geometry']:
  1563. has_solid_geo += 1
  1564. if has_solid_geo == 0:
  1565. self.app.inform.emit(_("[ERROR_NOTCL] There is no Painting Geometry in the file.\n"
  1566. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1567. "Change the painting parameters and try again."))
  1568. return
  1569. # Experimental...
  1570. # print("Indexing...", end=' ')
  1571. # geo_obj.make_index()
  1572. self.app.inform.emit(_("[success] Paint All with Rest-Machining done."))
  1573. def job_thread(app_obj):
  1574. try:
  1575. if self.rest_cb.isChecked():
  1576. app_obj.new_object("geometry", name, gen_paintarea_rest_machining)
  1577. else:
  1578. app_obj.new_object("geometry", name, gen_paintarea)
  1579. except Exception as e:
  1580. proc.done()
  1581. traceback.print_stack()
  1582. return
  1583. proc.done()
  1584. # focus on Selected Tab
  1585. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1586. self.app.inform.emit(_("Polygon Paint started ..."))
  1587. # Promise object with the new name
  1588. self.app.collection.promise(name)
  1589. # Background
  1590. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1591. @staticmethod
  1592. def paint_bounds(geometry):
  1593. def bounds_rec(o):
  1594. if type(o) is list:
  1595. minx = Inf
  1596. miny = Inf
  1597. maxx = -Inf
  1598. maxy = -Inf
  1599. for k in o:
  1600. try:
  1601. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1602. except Exception as e:
  1603. log.debug("ToolPaint.bounds() --> %s" % str(e))
  1604. return
  1605. minx = min(minx, minx_)
  1606. miny = min(miny, miny_)
  1607. maxx = max(maxx, maxx_)
  1608. maxy = max(maxy, maxy_)
  1609. return minx, miny, maxx, maxy
  1610. else:
  1611. # it's a Shapely object, return it's bounds
  1612. return o.bounds
  1613. return bounds_rec(geometry)
  1614. def reset_fields(self):
  1615. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))