ToolPaint.py 117 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Modified: Marius Adrian Stanciu (c) #
  4. # Date: 3/10/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtGui, QtCore
  8. from PyQt5.QtCore import Qt
  9. from FlatCAMTool import FlatCAMTool
  10. from copy import deepcopy
  11. # from ObjectCollection import *
  12. from flatcamParsers.ParseGerber import Gerber
  13. from FlatCAMObj import FlatCAMGerber, FlatCAMGeometry
  14. from camlib import Geometry
  15. from flatcamGUI.GUIElements import FCTable, FCDoubleSpinner, FCCheckBox, FCInputDialog, RadioSet
  16. import FlatCAMApp
  17. from shapely.geometry import base, Polygon, MultiPolygon, LinearRing
  18. from shapely.ops import cascaded_union
  19. import numpy as np
  20. from numpy import Inf
  21. import traceback
  22. import logging
  23. import gettext
  24. import FlatCAMTranslation as fcTranslate
  25. import builtins
  26. fcTranslate.apply_language('strings')
  27. if '_' not in builtins.__dict__:
  28. _ = gettext.gettext
  29. log = logging.getLogger('base')
  30. class ToolPaint(FlatCAMTool, Gerber):
  31. toolName = _("Paint Tool")
  32. def __init__(self, app):
  33. self.app = app
  34. self.decimals = 4
  35. FlatCAMTool.__init__(self, app)
  36. Geometry.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  37. # ## Title
  38. title_label = QtWidgets.QLabel("%s" % self.toolName)
  39. title_label.setStyleSheet("""
  40. QLabel
  41. {
  42. font-size: 16px;
  43. font-weight: bold;
  44. }
  45. """)
  46. self.layout.addWidget(title_label)
  47. self.tools_frame = QtWidgets.QFrame()
  48. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  49. self.layout.addWidget(self.tools_frame)
  50. self.tools_box = QtWidgets.QVBoxLayout()
  51. self.tools_box.setContentsMargins(0, 0, 0, 0)
  52. self.tools_frame.setLayout(self.tools_box)
  53. # ## Form Layout
  54. form_layout = QtWidgets.QFormLayout()
  55. self.tools_box.addLayout(form_layout)
  56. # ################################################
  57. # ##### Type of object to be painted #############
  58. # ################################################
  59. self.type_obj_combo = QtWidgets.QComboBox()
  60. self.type_obj_combo.addItem("Gerber")
  61. self.type_obj_combo.addItem("Excellon")
  62. self.type_obj_combo.addItem("Geometry")
  63. # we get rid of item1 ("Excellon") as it is not suitable
  64. self.type_obj_combo.view().setRowHidden(1, True)
  65. self.type_obj_combo.setItemIcon(0, QtGui.QIcon("share/flatcam_icon16.png"))
  66. self.type_obj_combo.setItemIcon(2, QtGui.QIcon("share/geometry16.png"))
  67. self.type_obj_combo_label = QtWidgets.QLabel('%s:' % _("Obj Type"))
  68. self.type_obj_combo_label.setToolTip(
  69. _("Specify the type of object to be painted.\n"
  70. "It can be of type: Gerber or Geometry.\n"
  71. "What is selected here will dictate the kind\n"
  72. "of objects that will populate the 'Object' combobox.")
  73. )
  74. self.type_obj_combo_label.setMinimumWidth(60)
  75. form_layout.addRow(self.type_obj_combo_label, self.type_obj_combo)
  76. # ################################################
  77. # ##### The object to be painted #################
  78. # ################################################
  79. self.obj_combo = QtWidgets.QComboBox()
  80. self.obj_combo.setModel(self.app.collection)
  81. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  82. self.obj_combo.setCurrentIndex(1)
  83. self.object_label = QtWidgets.QLabel('%s:' % _("Object"))
  84. self.object_label.setToolTip(_("Object to be painted."))
  85. form_layout.addRow(self.object_label, self.obj_combo)
  86. e_lab_0 = QtWidgets.QLabel('')
  87. form_layout.addRow(e_lab_0)
  88. # ### Tools ## ##
  89. self.tools_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Tools Table'))
  90. self.tools_table_label.setToolTip(
  91. _("Tools pool from which the algorithm\n"
  92. "will pick the ones used for painting.")
  93. )
  94. self.tools_box.addWidget(self.tools_table_label)
  95. self.tools_table = FCTable()
  96. self.tools_box.addWidget(self.tools_table)
  97. self.tools_table.setColumnCount(4)
  98. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), ''])
  99. self.tools_table.setColumnHidden(3, True)
  100. # self.tools_table.setSortingEnabled(False)
  101. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  102. self.tools_table.horizontalHeaderItem(0).setToolTip(
  103. _("This is the Tool Number.\n"
  104. "Painting will start with the tool with the biggest diameter,\n"
  105. "continuing until there are no more tools.\n"
  106. "Only tools that create painting geometry will still be present\n"
  107. "in the resulting geometry. This is because with some tools\n"
  108. "this function will not be able to create painting geometry.")
  109. )
  110. self.tools_table.horizontalHeaderItem(1).setToolTip(
  111. _("Tool Diameter. It's value (in current FlatCAM units) \n"
  112. "is the cut width into the material."))
  113. self.tools_table.horizontalHeaderItem(2).setToolTip(
  114. _("The Tool Type (TT) can be:<BR>"
  115. "- <B>Circular</B> with 1 ... 4 teeth -> it is informative only. Being circular, <BR>"
  116. "the cut width in material is exactly the tool diameter.<BR>"
  117. "- <B>Ball</B> -> informative only and make reference to the Ball type endmill.<BR>"
  118. "- <B>V-Shape</B> -> it will disable de Z-Cut parameter in the resulting geometry UI form "
  119. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and "
  120. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such "
  121. "as the cut width into material will be equal with the value in the Tool Diameter "
  122. "column of this table.<BR>"
  123. "Choosing the <B>V-Shape</B> Tool Type automatically will select the Operation Type "
  124. "in the resulting geometry as Isolation."))
  125. self.order_label = QtWidgets.QLabel('<b>%s:</b>' % _('Tool order'))
  126. self.order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  127. "'No' --> means that the used order is the one in the tool table\n"
  128. "'Forward' --> means that the tools will be ordered from small to big\n"
  129. "'Reverse' --> menas that the tools will ordered from big to small\n\n"
  130. "WARNING: using rest machining will automatically set the order\n"
  131. "in reverse and disable this control."))
  132. self.order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  133. {'label': _('Forward'), 'value': 'fwd'},
  134. {'label': _('Reverse'), 'value': 'rev'}])
  135. self.order_radio.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  136. "'No' --> means that the used order is the one in the tool table\n"
  137. "'Forward' --> means that the tools will be ordered from small to big\n"
  138. "'Reverse' --> menas that the tools will ordered from big to small\n\n"
  139. "WARNING: using rest machining will automatically set the order\n"
  140. "in reverse and disable this control."))
  141. form = QtWidgets.QFormLayout()
  142. self.tools_box.addLayout(form)
  143. form.addRow(QtWidgets.QLabel(''), QtWidgets.QLabel(''))
  144. form.addRow(self.order_label, self.order_radio)
  145. # ### Add a new Tool ## ##
  146. self.addtool_entry_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Tool Dia'))
  147. self.addtool_entry_lbl.setToolTip(
  148. _("Diameter for the new tool.")
  149. )
  150. self.addtool_entry = FCDoubleSpinner()
  151. self.addtool_entry.set_precision(self.decimals)
  152. form.addRow(self.addtool_entry_lbl, self.addtool_entry)
  153. grid2 = QtWidgets.QGridLayout()
  154. self.tools_box.addLayout(grid2)
  155. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  156. self.addtool_btn.setToolTip(
  157. _("Add a new tool to the Tool Table\n"
  158. "with the diameter specified above.")
  159. )
  160. # self.copytool_btn = QtWidgets.QPushButton('Copy')
  161. # self.copytool_btn.setToolTip(
  162. # "Copy a selection of tools in the Tool Table\n"
  163. # "by first selecting a row in the Tool Table."
  164. # )
  165. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  166. self.deltool_btn.setToolTip(
  167. _("Delete a selection of tools in the Tool Table\n"
  168. "by first selecting a row(s) in the Tool Table.")
  169. )
  170. grid2.addWidget(self.addtool_btn, 0, 0)
  171. # grid2.addWidget(self.copytool_btn, 0, 1)
  172. grid2.addWidget(self.deltool_btn, 0, 2)
  173. self.empty_label_0 = QtWidgets.QLabel('')
  174. self.tools_box.addWidget(self.empty_label_0)
  175. grid3 = QtWidgets.QGridLayout()
  176. self.tools_box.addLayout(grid3)
  177. grid3.setColumnStretch(0, 0)
  178. grid3.setColumnStretch(1, 1)
  179. # Overlap
  180. ovlabel = QtWidgets.QLabel('%s:' % _('Overlap Rate'))
  181. ovlabel.setToolTip(
  182. _("How much (fraction) of the tool width to overlap each tool pass.\n"
  183. "Adjust the value starting with lower values\n"
  184. "and increasing it if areas that should be painted are still \n"
  185. "not painted.\n"
  186. "Lower values = faster processing, faster execution on CNC.\n"
  187. "Higher values = slow processing and slow execution on CNC\n"
  188. "due of too many paths.")
  189. )
  190. self.paintoverlap_entry = FCDoubleSpinner(suffix='%')
  191. self.paintoverlap_entry.set_precision(3)
  192. self.paintoverlap_entry.setWrapping(True)
  193. self.paintoverlap_entry.setRange(0.0000, 99.9999)
  194. self.paintoverlap_entry.setSingleStep(0.1)
  195. grid3.addWidget(ovlabel, 1, 0)
  196. grid3.addWidget(self.paintoverlap_entry, 1, 1)
  197. # Margin
  198. marginlabel = QtWidgets.QLabel('%s:' % _('Margin'))
  199. marginlabel.setToolTip(
  200. _("Distance by which to avoid\n"
  201. "the edges of the polygon to\n"
  202. "be painted.")
  203. )
  204. grid3.addWidget(marginlabel, 2, 0)
  205. self.paintmargin_entry = FCDoubleSpinner()
  206. self.paintmargin_entry.set_precision(self.decimals)
  207. grid3.addWidget(self.paintmargin_entry, 2, 1)
  208. # Method
  209. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  210. methodlabel.setToolTip(
  211. _("Algorithm for painting:\n"
  212. "- Standard: Fixed step inwards.\n"
  213. "- Seed-based: Outwards from seed.\n"
  214. "- Line-based: Parallel lines.")
  215. )
  216. grid3.addWidget(methodlabel, 3, 0)
  217. self.paintmethod_combo = RadioSet([
  218. {"label": _("Standard"), "value": "standard"},
  219. {"label": _("Seed-based"), "value": "seed"},
  220. {"label": _("Straight lines"), "value": "lines"}
  221. ], orientation='vertical', stretch=False)
  222. grid3.addWidget(self.paintmethod_combo, 3, 1)
  223. # Connect lines
  224. pathconnectlabel = QtWidgets.QLabel('%s:' % _("Connect"))
  225. pathconnectlabel.setToolTip(
  226. _("Draw lines between resulting\n"
  227. "segments to minimize tool lifts.")
  228. )
  229. grid3.addWidget(pathconnectlabel, 4, 0)
  230. self.pathconnect_cb = FCCheckBox()
  231. grid3.addWidget(self.pathconnect_cb, 4, 1)
  232. contourlabel = QtWidgets.QLabel('%s:' % _("Contour"))
  233. contourlabel.setToolTip(
  234. _("Cut around the perimeter of the polygon\n"
  235. "to trim rough edges.")
  236. )
  237. grid3.addWidget(contourlabel, 5, 0)
  238. self.paintcontour_cb = FCCheckBox()
  239. grid3.addWidget(self.paintcontour_cb, 5, 1)
  240. restlabel = QtWidgets.QLabel('%s:' % _("Rest M."))
  241. restlabel.setToolTip(
  242. _("If checked, use 'rest machining'.\n"
  243. "Basically it will clear copper outside PCB features,\n"
  244. "using the biggest tool and continue with the next tools,\n"
  245. "from bigger to smaller, to clear areas of copper that\n"
  246. "could not be cleared by previous tool, until there is\n"
  247. "no more copper to clear or there are no more tools.\n\n"
  248. "If not checked, use the standard algorithm.")
  249. )
  250. grid3.addWidget(restlabel, 6, 0)
  251. self.rest_cb = FCCheckBox()
  252. grid3.addWidget(self.rest_cb, 6, 1)
  253. # Polygon selection
  254. selectlabel = QtWidgets.QLabel('%s:' % _('Selection'))
  255. selectlabel.setToolTip(
  256. _("How to select Polygons to be painted.\n"
  257. "- 'Polygon Selection' - left mouse click to add/remove polygons to be painted.\n"
  258. "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  259. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  260. "- 'All Polygons' - the Paint will start after click.\n"
  261. "- 'Reference Object' - will do non copper clearing within the area\n"
  262. "specified by another object.")
  263. )
  264. grid3.addWidget(selectlabel, 7, 0)
  265. # grid3 = QtWidgets.QGridLayout()
  266. self.selectmethod_combo = RadioSet([
  267. {"label": _("Polygon Selection"), "value": "single"},
  268. {"label": _("Area Selection"), "value": "area"},
  269. {"label": _("All Polygons"), "value": "all"},
  270. {"label": _("Reference Object"), "value": "ref"}
  271. ], orientation='vertical', stretch=False)
  272. self.selectmethod_combo.setToolTip(
  273. _("How to select Polygons to be painted.\n"
  274. "- 'Polygon Selection' - left mouse click to add/remove polygons to be painted.\n"
  275. "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  276. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  277. "- 'All Polygons' - the Paint will start after click.\n"
  278. "- 'Reference Object' - will do non copper clearing within the area\n"
  279. "specified by another object.")
  280. )
  281. grid3.addWidget(self.selectmethod_combo, 7, 1)
  282. form1 = QtWidgets.QFormLayout()
  283. self.tools_box.addLayout(form1)
  284. self.box_combo_type_label = QtWidgets.QLabel('%s:' % _("Ref. Type"))
  285. self.box_combo_type_label.setToolTip(
  286. _("The type of FlatCAM object to be used as paint reference.\n"
  287. "It can be Gerber, Excellon or Geometry.")
  288. )
  289. self.box_combo_type = QtWidgets.QComboBox()
  290. self.box_combo_type.addItem(_("Reference Gerber"))
  291. self.box_combo_type.addItem(_("Reference Excellon"))
  292. self.box_combo_type.addItem(_("Reference Geometry"))
  293. form1.addRow(self.box_combo_type_label, self.box_combo_type)
  294. self.box_combo_label = QtWidgets.QLabel('%s:' % _("Ref. Object"))
  295. self.box_combo_label.setToolTip(
  296. _("The FlatCAM object to be used as non copper clearing reference.")
  297. )
  298. self.box_combo = QtWidgets.QComboBox()
  299. self.box_combo.setModel(self.app.collection)
  300. self.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  301. self.box_combo.setCurrentIndex(1)
  302. form1.addRow(self.box_combo_label, self.box_combo)
  303. self.box_combo.hide()
  304. self.box_combo_label.hide()
  305. self.box_combo_type.hide()
  306. self.box_combo_type_label.hide()
  307. # GO Button
  308. self.generate_paint_button = QtWidgets.QPushButton(_('Create Paint Geometry'))
  309. self.generate_paint_button.setToolTip(
  310. _("- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  311. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  312. "- 'All Polygons' - the Paint will start after click.\n"
  313. "- 'Reference Object' - will do non copper clearing within the area\n"
  314. "specified by another object.")
  315. )
  316. self.generate_paint_button.setStyleSheet("""
  317. QPushButton
  318. {
  319. font-weight: bold;
  320. }
  321. """)
  322. self.tools_box.addWidget(self.generate_paint_button)
  323. self.tools_box.addStretch()
  324. # ## Reset Tool
  325. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  326. self.reset_button.setToolTip(
  327. _("Will reset the tool parameters.")
  328. )
  329. self.reset_button.setStyleSheet("""
  330. QPushButton
  331. {
  332. font-weight: bold;
  333. }
  334. """)
  335. self.tools_box.addWidget(self.reset_button)
  336. # #################################### FINSIHED GUI #####################################
  337. # #######################################################################################
  338. self.obj_name = ""
  339. self.paint_obj = None
  340. self.bound_obj_name = ""
  341. self.bound_obj = None
  342. self.tooldia_list = []
  343. self.sel_rect = None
  344. self.o_name = None
  345. self.overlap = None
  346. self.connect = None
  347. self.contour = None
  348. self.select_method = None
  349. self.units = ''
  350. self.paint_tools = {}
  351. self.tooluid = 0
  352. self.first_click = False
  353. self.cursor_pos = None
  354. self.mouse_is_dragging = False
  355. self.mm = None
  356. self.mp = None
  357. self.mr = None
  358. self.sel_rect = []
  359. # store here if the grid snapping is active
  360. self.grid_status_memory = False
  361. # dict to store the polygons selected for painting; key is the shape added to be plotted and value is the poly
  362. self.poly_dict = dict()
  363. # store here the default data for Geometry Data
  364. self.default_data = {}
  365. self.default_data.update({
  366. "name": '_paint',
  367. "plot": self.app.defaults["geometry_plot"],
  368. "cutz": self.app.defaults["geometry_cutz"],
  369. "vtipdia": 0.1,
  370. "vtipangle": 30,
  371. "travelz": self.app.defaults["geometry_travelz"],
  372. "feedrate": self.app.defaults["geometry_feedrate"],
  373. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  374. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  375. "dwell": self.app.defaults["geometry_dwell"],
  376. "dwelltime": self.app.defaults["geometry_dwelltime"],
  377. "multidepth": self.app.defaults["geometry_multidepth"],
  378. "ppname_g": self.app.defaults["geometry_ppname_g"],
  379. "depthperpass": self.app.defaults["geometry_depthperpass"],
  380. "extracut": self.app.defaults["geometry_extracut"],
  381. "toolchange": self.app.defaults["geometry_toolchange"],
  382. "toolchangez": self.app.defaults["geometry_toolchangez"],
  383. "endz": self.app.defaults["geometry_endz"],
  384. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  385. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  386. "startz": self.app.defaults["geometry_startz"],
  387. "tooldia": self.app.defaults["tools_painttooldia"],
  388. "paintmargin": self.app.defaults["tools_paintmargin"],
  389. "paintmethod": self.app.defaults["tools_paintmethod"],
  390. "selectmethod": self.app.defaults["tools_selectmethod"],
  391. "pathconnect": self.app.defaults["tools_pathconnect"],
  392. "paintcontour": self.app.defaults["tools_paintcontour"],
  393. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  394. })
  395. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  396. # #############################################################################
  397. # ################################# Signals ###################################
  398. # #############################################################################
  399. self.addtool_btn.clicked.connect(self.on_tool_add)
  400. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  401. # self.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  402. self.tools_table.itemChanged.connect(self.on_tool_edit)
  403. self.deltool_btn.clicked.connect(self.on_tool_delete)
  404. self.generate_paint_button.clicked.connect(self.on_paint_button_click)
  405. self.selectmethod_combo.activated_custom.connect(self.on_radio_selection)
  406. self.order_radio.activated_custom[str].connect(self.on_order_changed)
  407. self.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  408. self.box_combo_type.currentIndexChanged.connect(self.on_combo_box_type)
  409. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  410. self.reset_button.clicked.connect(self.set_tool_ui)
  411. # #############################################################################
  412. # ###################### Setup CONTEXT MENU ###################################
  413. # #############################################################################
  414. self.tools_table.setupContextMenu()
  415. self.tools_table.addContextMenu(
  416. "Add", self.on_add_tool_by_key, icon=QtGui.QIcon("share/plus16.png"))
  417. self.tools_table.addContextMenu(
  418. "Delete", lambda:
  419. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  420. def on_type_obj_index_changed(self, index):
  421. obj_type = self.type_obj_combo.currentIndex()
  422. self.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  423. self.obj_combo.setCurrentIndex(0)
  424. def install(self, icon=None, separator=None, **kwargs):
  425. FlatCAMTool.install(self, icon, separator, shortcut='ALT+P', **kwargs)
  426. def on_add_tool_by_key(self):
  427. tool_add_popup = FCInputDialog(title='%s...' % _("New Tool"),
  428. text='%s:' % _('Enter a Tool Diameter'),
  429. min=0.0000, max=99.9999, decimals=4)
  430. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  431. val, ok = tool_add_popup.get_value()
  432. if ok:
  433. if float(val) == 0:
  434. self.app.inform.emit('[WARNING_NOTCL] %s' %
  435. _("Please enter a tool diameter with non-zero value, in Float format."))
  436. return
  437. self.on_tool_add(dia=float(val))
  438. else:
  439. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  440. def run(self, toggle=True):
  441. self.app.report_usage("ToolPaint()")
  442. if toggle:
  443. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  444. if self.app.ui.splitter.sizes()[0] == 0:
  445. self.app.ui.splitter.setSizes([1, 1])
  446. else:
  447. try:
  448. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  449. # if tab is populated with the tool but it does not have the focus, focus on it
  450. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  451. # focus on Tool Tab
  452. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  453. else:
  454. self.app.ui.splitter.setSizes([0, 1])
  455. except AttributeError:
  456. pass
  457. else:
  458. if self.app.ui.splitter.sizes()[0] == 0:
  459. self.app.ui.splitter.setSizes([1, 1])
  460. FlatCAMTool.run(self)
  461. self.set_tool_ui()
  462. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  463. def reset_usage(self):
  464. self.obj_name = ""
  465. self.paint_obj = None
  466. self.bound_obj = None
  467. self.first_click = False
  468. self.cursor_pos = None
  469. self.mouse_is_dragging = False
  470. self.sel_rect = []
  471. def on_radio_selection(self):
  472. if self.selectmethod_combo.get_value() == "ref":
  473. self.box_combo.show()
  474. self.box_combo_label.show()
  475. self.box_combo_type.show()
  476. self.box_combo_type_label.show()
  477. else:
  478. self.box_combo.hide()
  479. self.box_combo_label.hide()
  480. self.box_combo_type.hide()
  481. self.box_combo_type_label.hide()
  482. if self.selectmethod_combo.get_value() == 'single':
  483. # disable rest-machining for single polygon painting
  484. self.rest_cb.set_value(False)
  485. self.rest_cb.setDisabled(True)
  486. if self.selectmethod_combo.get_value() == 'area':
  487. # disable rest-machining for single polygon painting
  488. self.rest_cb.set_value(False)
  489. self.rest_cb.setDisabled(True)
  490. else:
  491. self.rest_cb.setDisabled(False)
  492. self.addtool_entry.setDisabled(False)
  493. self.addtool_btn.setDisabled(False)
  494. self.deltool_btn.setDisabled(False)
  495. self.tools_table.setContextMenuPolicy(Qt.ActionsContextMenu)
  496. def on_order_changed(self, order):
  497. if order != 'no':
  498. self.build_ui()
  499. def on_rest_machining_check(self, state):
  500. if state:
  501. self.order_radio.set_value('rev')
  502. self.order_label.setDisabled(True)
  503. self.order_radio.setDisabled(True)
  504. else:
  505. self.order_label.setDisabled(False)
  506. self.order_radio.setDisabled(False)
  507. def set_tool_ui(self):
  508. self.tools_frame.show()
  509. self.reset_fields()
  510. # ## Init the GUI interface
  511. self.order_radio.set_value(self.app.defaults["tools_paintorder"])
  512. self.paintmargin_entry.set_value(self.default_data["paintmargin"])
  513. self.paintmethod_combo.set_value(self.default_data["paintmethod"])
  514. self.selectmethod_combo.set_value(self.default_data["selectmethod"])
  515. self.pathconnect_cb.set_value(self.default_data["pathconnect"])
  516. self.paintcontour_cb.set_value(self.default_data["paintcontour"])
  517. self.paintoverlap_entry.set_value(self.default_data["paintoverlap"])
  518. # make the default object type, "Geometry"
  519. self.type_obj_combo.setCurrentIndex(2)
  520. # updated units
  521. self.units = self.app.defaults['units'].upper()
  522. if self.units == "IN":
  523. self.decimals = 4
  524. self.addtool_entry.set_value(0.039)
  525. else:
  526. self.decimals = 2
  527. self.addtool_entry.set_value(1)
  528. # set the working variables to a known state
  529. self.paint_tools.clear()
  530. self.tooluid = 0
  531. self.default_data.clear()
  532. self.default_data.update({
  533. "name": '_paint',
  534. "plot": self.app.defaults["geometry_plot"],
  535. "cutz": float(self.app.defaults["geometry_cutz"]),
  536. "vtipdia": 0.1,
  537. "vtipangle": 30,
  538. "travelz": float(self.app.defaults["geometry_travelz"]),
  539. "feedrate": float(self.app.defaults["geometry_feedrate"]),
  540. "feedrate_z": float(self.app.defaults["geometry_feedrate_z"]),
  541. "feedrate_rapid": float(self.app.defaults["geometry_feedrate_rapid"]),
  542. "dwell": self.app.defaults["geometry_dwell"],
  543. "dwelltime": float(self.app.defaults["geometry_dwelltime"]),
  544. "multidepth": self.app.defaults["geometry_multidepth"],
  545. "ppname_g": self.app.defaults["geometry_ppname_g"],
  546. "depthperpass": float(self.app.defaults["geometry_depthperpass"]),
  547. "extracut": self.app.defaults["geometry_extracut"],
  548. "toolchange": self.app.defaults["geometry_toolchange"],
  549. "toolchangez": float(self.app.defaults["geometry_toolchangez"]),
  550. "endz": float(self.app.defaults["geometry_endz"]),
  551. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  552. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  553. "startz": self.app.defaults["geometry_startz"],
  554. "tooldia": float(self.app.defaults["tools_painttooldia"]),
  555. "paintmargin": float(self.app.defaults["tools_paintmargin"]),
  556. "paintmethod": self.app.defaults["tools_paintmethod"],
  557. "selectmethod": self.app.defaults["tools_selectmethod"],
  558. "pathconnect": self.app.defaults["tools_pathconnect"],
  559. "paintcontour": self.app.defaults["tools_paintcontour"],
  560. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  561. })
  562. # call on self.on_tool_add() counts as an call to self.build_ui()
  563. # through this, we add a initial row / tool in the tool_table
  564. self.on_tool_add(float(self.app.defaults["tools_painttooldia"]), muted=True)
  565. # if the Paint Method is "Single" disable the tool table context menu
  566. if self.default_data["selectmethod"] == "single":
  567. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  568. def build_ui(self):
  569. try:
  570. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  571. self.tools_table.itemChanged.disconnect()
  572. except (TypeError, AttributeError):
  573. pass
  574. # updated units
  575. self.units = self.app.defaults['units'].upper()
  576. sorted_tools = []
  577. for k, v in self.paint_tools.items():
  578. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  579. order = self.order_radio.get_value()
  580. if order == 'fwd':
  581. sorted_tools.sort(reverse=False)
  582. elif order == 'rev':
  583. sorted_tools.sort(reverse=True)
  584. else:
  585. pass
  586. n = len(sorted_tools)
  587. self.tools_table.setRowCount(n)
  588. tool_id = 0
  589. for tool_sorted in sorted_tools:
  590. for tooluid_key, tooluid_value in self.paint_tools.items():
  591. if float('%.*f' % (self.decimals, tooluid_value['tooldia'])) == tool_sorted:
  592. tool_id += 1
  593. id_item = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  594. id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  595. row_no = tool_id - 1
  596. self.tools_table.setItem(row_no, 0, id_item) # Tool name/id
  597. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  598. # There are no drill bits in MM with more than 2 decimals diameter
  599. # For INCH the decimals should be no more than 4. There are no drills under 10mils
  600. dia = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, tooluid_value['tooldia']))
  601. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  602. tool_type_item = QtWidgets.QComboBox()
  603. for item in self.tool_type_item_options:
  604. tool_type_item.addItem(item)
  605. # tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  606. idx = tool_type_item.findText(tooluid_value['tool_type'])
  607. tool_type_item.setCurrentIndex(idx)
  608. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  609. self.tools_table.setItem(row_no, 1, dia) # Diameter
  610. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  611. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  612. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  613. # make the diameter column editable
  614. for row in range(tool_id):
  615. self.tools_table.item(row, 1).setFlags(
  616. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  617. # all the tools are selected by default
  618. self.tools_table.selectColumn(0)
  619. #
  620. self.tools_table.resizeColumnsToContents()
  621. self.tools_table.resizeRowsToContents()
  622. vertical_header = self.tools_table.verticalHeader()
  623. vertical_header.hide()
  624. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  625. horizontal_header = self.tools_table.horizontalHeader()
  626. horizontal_header.setMinimumSectionSize(10)
  627. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  628. horizontal_header.resizeSection(0, 20)
  629. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  630. # self.tools_table.setSortingEnabled(True)
  631. # sort by tool diameter
  632. # self.tools_table.sortItems(1)
  633. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  634. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  635. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  636. self.tools_table.itemChanged.connect(self.on_tool_edit)
  637. def on_combo_box_type(self):
  638. obj_type = self.box_combo_type.currentIndex()
  639. self.box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  640. self.box_combo.setCurrentIndex(0)
  641. def on_tool_add(self, dia=None, muted=None):
  642. try:
  643. self.tools_table.itemChanged.disconnect()
  644. except TypeError:
  645. pass
  646. if dia:
  647. tool_dia = dia
  648. else:
  649. tool_dia = float(self.addtool_entry.get_value())
  650. if tool_dia is None:
  651. self.build_ui()
  652. self.app.inform.emit('[WARNING_NOTCL] %s' %
  653. _("Please enter a tool diameter to add, in Float format."))
  654. return
  655. # construct a list of all 'tooluid' in the self.tools
  656. tool_uid_list = []
  657. for tooluid_key in self.paint_tools:
  658. tool_uid_item = int(tooluid_key)
  659. tool_uid_list.append(tool_uid_item)
  660. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  661. if not tool_uid_list:
  662. max_uid = 0
  663. else:
  664. max_uid = max(tool_uid_list)
  665. self.tooluid = int(max_uid + 1)
  666. tool_dias = []
  667. for k, v in self.paint_tools.items():
  668. for tool_v in v.keys():
  669. if tool_v == 'tooldia':
  670. tool_dias.append(float('%.*f' % (self.decimals, v[tool_v])))
  671. if float('%.*f' % (self.decimals, tool_dia)) in tool_dias:
  672. if muted is None:
  673. self.app.inform.emit('[WARNING_NOTCL] %s' %
  674. _("Adding tool cancelled. Tool already in Tool Table."))
  675. self.tools_table.itemChanged.connect(self.on_tool_edit)
  676. return
  677. else:
  678. if muted is None:
  679. self.app.inform.emit('[success] %s' %
  680. _("New tool added to Tool Table."))
  681. self.paint_tools.update({
  682. int(self.tooluid): {
  683. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  684. 'offset': 'Path',
  685. 'offset_value': 0.0,
  686. 'type': 'Iso',
  687. 'tool_type': 'V',
  688. 'data': dict(self.default_data),
  689. 'solid_geometry': []
  690. }
  691. })
  692. self.build_ui()
  693. def on_tool_edit(self):
  694. old_tool_dia = ''
  695. try:
  696. self.tools_table.itemChanged.disconnect()
  697. except TypeError:
  698. pass
  699. tool_dias = []
  700. for k, v in self.paint_tools.items():
  701. for tool_v in v.keys():
  702. if tool_v == 'tooldia':
  703. tool_dias.append(float('%.*f' % (self.decimals, v[tool_v])))
  704. for row in range(self.tools_table.rowCount()):
  705. try:
  706. new_tool_dia = float(self.tools_table.item(row, 1).text())
  707. except ValueError:
  708. # try to convert comma to decimal point. if it's still not working error message and return
  709. try:
  710. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  711. except ValueError:
  712. self.app.inform.emit('[ERROR_NOTCL] %s' %
  713. _("Wrong value format entered, use a number."))
  714. return
  715. tooluid = int(self.tools_table.item(row, 3).text())
  716. # identify the tool that was edited and get it's tooluid
  717. if new_tool_dia not in tool_dias:
  718. self.paint_tools[tooluid]['tooldia'] = new_tool_dia
  719. self.app.inform.emit('[success] %s' %
  720. _("Tool from Tool Table was edited."))
  721. self.build_ui()
  722. return
  723. else:
  724. # identify the old tool_dia and restore the text in tool table
  725. for k, v in self.paint_tools.items():
  726. if k == tooluid:
  727. old_tool_dia = v['tooldia']
  728. break
  729. restore_dia_item = self.tools_table.item(row, 1)
  730. restore_dia_item.setText(str(old_tool_dia))
  731. self.app.inform.emit('[WARNING_NOTCL] %s' %
  732. _("Edit cancelled. New diameter value is already in the Tool Table."))
  733. self.build_ui()
  734. # def on_tool_copy(self, all=None):
  735. # try:
  736. # self.tools_table.itemChanged.disconnect()
  737. # except:
  738. # pass
  739. #
  740. # # find the tool_uid maximum value in the self.tools
  741. # uid_list = []
  742. # for key in self.paint_tools:
  743. # uid_list.append(int(key))
  744. # try:
  745. # max_uid = max(uid_list, key=int)
  746. # except ValueError:
  747. # max_uid = 0
  748. #
  749. # if all is None:
  750. # if self.tools_table.selectedItems():
  751. # for current_row in self.tools_table.selectedItems():
  752. # # sometime the header get selected and it has row number -1
  753. # # we don't want to do anything with the header :)
  754. # if current_row.row() < 0:
  755. # continue
  756. # try:
  757. # tooluid_copy = int(self.tools_table.item(current_row.row(), 3).text())
  758. # max_uid += 1
  759. # self.paint_tools[int(max_uid)] = dict(self.paint_tools[tooluid_copy])
  760. # for td in self.paint_tools:
  761. # print("COPIED", self.paint_tools[td])
  762. # self.build_ui()
  763. # except AttributeError:
  764. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  765. # self.build_ui()
  766. # return
  767. # except Exception as e:
  768. # log.debug("on_tool_copy() --> " + str(e))
  769. # # deselect the table
  770. # # self.ui.geo_tools_table.clearSelection()
  771. # else:
  772. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  773. # self.build_ui()
  774. # return
  775. # else:
  776. # # we copy all tools in geo_tools_table
  777. # try:
  778. # temp_tools = dict(self.paint_tools)
  779. # max_uid += 1
  780. # for tooluid in temp_tools:
  781. # self.paint_tools[int(max_uid)] = dict(temp_tools[tooluid])
  782. # temp_tools.clear()
  783. # self.build_ui()
  784. # except Exception as e:
  785. # log.debug("on_tool_copy() --> " + str(e))
  786. #
  787. # self.app.inform.emit("[success] Tool was copied in the Tool Table.")
  788. def on_tool_delete(self, rows_to_delete=None, all=None):
  789. try:
  790. self.tools_table.itemChanged.disconnect()
  791. except TypeError:
  792. pass
  793. deleted_tools_list = []
  794. if all:
  795. self.paint_tools.clear()
  796. self.build_ui()
  797. return
  798. if rows_to_delete:
  799. try:
  800. for row in rows_to_delete:
  801. tooluid_del = int(self.tools_table.item(row, 3).text())
  802. deleted_tools_list.append(tooluid_del)
  803. except TypeError:
  804. deleted_tools_list.append(rows_to_delete)
  805. for t in deleted_tools_list:
  806. self.paint_tools.pop(t, None)
  807. self.build_ui()
  808. return
  809. try:
  810. if self.tools_table.selectedItems():
  811. for row_sel in self.tools_table.selectedItems():
  812. row = row_sel.row()
  813. if row < 0:
  814. continue
  815. tooluid_del = int(self.tools_table.item(row, 3).text())
  816. deleted_tools_list.append(tooluid_del)
  817. for t in deleted_tools_list:
  818. self.paint_tools.pop(t, None)
  819. except AttributeError:
  820. self.app.inform.emit('[WARNING_NOTCL] %s' %
  821. _("Delete failed. Select a tool to delete."))
  822. return
  823. except Exception as e:
  824. log.debug(str(e))
  825. self.app.inform.emit('[success] %s' %
  826. _("Tool(s) deleted from Tool Table."))
  827. self.build_ui()
  828. def on_paint_button_click(self):
  829. # init values for the next usage
  830. self.reset_usage()
  831. self.app.report_usage("on_paint_button_click")
  832. # self.app.call_source = 'paint'
  833. # #####################################################
  834. # ######### Reading Parameters ########################
  835. # #####################################################
  836. self.app.inform.emit(_("Paint Tool. Reading parameters."))
  837. self.overlap = float(self.paintoverlap_entry.get_value()) / 100.0
  838. self.connect = self.pathconnect_cb.get_value()
  839. self.contour = self.paintcontour_cb.get_value()
  840. self.select_method = self.selectmethod_combo.get_value()
  841. self.obj_name = self.obj_combo.currentText()
  842. # Get source object.
  843. try:
  844. self.paint_obj = self.app.collection.get_by_name(str(self.obj_name))
  845. except Exception as e:
  846. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  847. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  848. (_("Could not retrieve object: %s"),
  849. self.obj_name))
  850. return
  851. if self.paint_obj is None:
  852. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  853. (_("Object not found"),
  854. self.paint_obj))
  855. return
  856. # test if the Geometry Object is multigeo and return Fail if True because
  857. # for now Paint don't work on MultiGeo
  858. if self.paint_obj.multigeo is True:
  859. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  860. _("Can't do Paint on MultiGeo geometries"))
  861. return 'Fail'
  862. o_name = '%s_multitool_paint' % self.obj_name
  863. # use the selected tools in the tool table; get diameters
  864. self.tooldia_list = list()
  865. if self.tools_table.selectedItems():
  866. for x in self.tools_table.selectedItems():
  867. try:
  868. self.tooldia = float(self.tools_table.item(x.row(), 1).text())
  869. except ValueError:
  870. # try to convert comma to decimal point. if it's still not working error message and return
  871. try:
  872. self.tooldia = float(self.tools_table.item(x.row(), 1).text().replace(',', '.'))
  873. except ValueError:
  874. self.app.inform.emit('[ERROR_NOTCL] %s' %
  875. _("Wrong value format entered, use a number."))
  876. continue
  877. self.tooldia_list.append(self.tooldia)
  878. else:
  879. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No selected tools in Tool Table."))
  880. return
  881. if self.select_method == "all":
  882. self.paint_poly_all(self.paint_obj,
  883. tooldia=self.tooldia_list,
  884. outname=self.o_name,
  885. overlap=self.overlap,
  886. connect=self.connect,
  887. contour=self.contour)
  888. elif self.select_method == "single":
  889. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click on a polygon to paint it."))
  890. # disengage the grid snapping since it may be hard to click on polygons with grid snapping on
  891. if self.app.ui.grid_snap_btn.isChecked():
  892. self.grid_status_memory = True
  893. self.app.ui.grid_snap_btn.trigger()
  894. else:
  895. self.grid_status_memory = False
  896. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_single_poly_mouse_release)
  897. if self.app.is_legacy is False:
  898. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  899. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  900. else:
  901. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  902. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  903. elif self.select_method == "area":
  904. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the paint area."))
  905. if self.app.is_legacy is False:
  906. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  907. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  908. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  909. else:
  910. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  911. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  912. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  913. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  914. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  915. elif self.select_method == 'ref':
  916. self.bound_obj_name = self.box_combo.currentText()
  917. # Get source object.
  918. try:
  919. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  920. except Exception as e:
  921. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  922. (_("Could not retrieve object"),
  923. self.obj_name))
  924. return "Could not retrieve object: %s" % self.obj_name
  925. self.paint_poly_ref(obj=self.paint_obj,
  926. sel_obj=self.bound_obj,
  927. tooldia=self.tooldia_list,
  928. overlap=self.overlap,
  929. outname=self.o_name,
  930. connect=self.connect,
  931. contour=self.contour)
  932. # To be called after clicking on the plot.
  933. def on_single_poly_mouse_release(self, event):
  934. if self.app.is_legacy is False:
  935. event_pos = event.pos
  936. right_button = 2
  937. event_is_dragging = self.app.event_is_dragging
  938. else:
  939. event_pos = (event.xdata, event.ydata)
  940. right_button = 3
  941. event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  942. try:
  943. x = float(event_pos[0])
  944. y = float(event_pos[1])
  945. except TypeError:
  946. return
  947. event_pos = (x, y)
  948. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  949. # do paint single only for left mouse clicks
  950. if event.button == 1:
  951. clicked_poly = self.find_polygon(point=(curr_pos[0], curr_pos[1]), geoset=self.paint_obj.solid_geometry)
  952. if clicked_poly:
  953. if clicked_poly not in self.poly_dict.values():
  954. shape_id = self.app.tool_shapes.add(tolerance=self.paint_obj.drawing_tolerance,
  955. layer=0,
  956. shape=clicked_poly,
  957. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  958. face_color=self.app.defaults['global_sel_draw_color'] + 'AF',
  959. visible=True)
  960. self.poly_dict[shape_id] = clicked_poly
  961. self.app.inform.emit(
  962. '%s: %d. %s' % (_("Added polygon"),
  963. int(len(self.poly_dict)),
  964. _("Click to add next polygon or right click to start painting."))
  965. )
  966. else:
  967. try:
  968. for k, v in list(self.poly_dict.items()):
  969. if v == clicked_poly:
  970. self.app.tool_shapes.remove(k)
  971. self.poly_dict.pop(k)
  972. break
  973. except TypeError:
  974. return
  975. self.app.inform.emit(
  976. '%s. %s' % (_("Removed polygon"),
  977. _("Click to add/remove next polygon or right click to start painting."))
  978. )
  979. self.app.tool_shapes.redraw()
  980. else:
  981. self.app.inform.emit(_("No polygon detected under click position."))
  982. elif event.button == right_button and event_is_dragging is False:
  983. # restore the Grid snapping if it was active before
  984. if self.grid_status_memory is True:
  985. self.app.ui.grid_snap_btn.trigger()
  986. if self.app.is_legacy is False:
  987. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_single_poly_mouse_release)
  988. else:
  989. self.app.plotcanvas.graph_event_disconnect(self.mr)
  990. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  991. self.app.on_mouse_click_over_plot)
  992. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  993. self.app.on_mouse_click_release_over_plot)
  994. self.app.tool_shapes.clear(update=True)
  995. if self.poly_dict:
  996. poly_list = deepcopy(list(self.poly_dict.values()))
  997. self.paint_poly(self.paint_obj,
  998. poly_list=poly_list,
  999. tooldia=self.tooldia_list,
  1000. overlap=self.overlap,
  1001. connect=self.connect,
  1002. contour=self.contour)
  1003. self.poly_dict.clear()
  1004. else:
  1005. self.app.inform.emit('[ERROR_NOTCL] %s' % _("List of single polygons is empty. Aborting."))
  1006. # To be called after clicking on the plot.
  1007. def on_mouse_release(self, event):
  1008. if self.app.is_legacy is False:
  1009. event_pos = event.pos
  1010. event_is_dragging = event.is_dragging
  1011. right_button = 2
  1012. else:
  1013. event_pos = (event.xdata, event.ydata)
  1014. event_is_dragging = self.app.plotcanvas.is_dragging
  1015. right_button = 3
  1016. try:
  1017. x = float(event_pos[0])
  1018. y = float(event_pos[1])
  1019. except TypeError:
  1020. return
  1021. event_pos = (x, y)
  1022. # do paint single only for left mouse clicks
  1023. if event.button == 1:
  1024. if not self.first_click:
  1025. self.first_click = True
  1026. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1027. _("Click the end point of the paint area."))
  1028. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  1029. if self.app.grid_status() == True:
  1030. self.cursor_pos = self.app.geo_editor.snap(self.cursor_pos[0], self.cursor_pos[1])
  1031. else:
  1032. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  1033. self.app.delete_selection_shape()
  1034. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  1035. if self.app.grid_status() == True:
  1036. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1037. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  1038. x1, y1 = curr_pos[0], curr_pos[1]
  1039. pt1 = (x0, y0)
  1040. pt2 = (x1, y0)
  1041. pt3 = (x1, y1)
  1042. pt4 = (x0, y1)
  1043. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  1044. self.sel_rect.append(new_rectangle)
  1045. # add a temporary shape on canvas
  1046. self.draw_tool_selection_shape(old_coords=(x0, y0), coords=(x1, y1))
  1047. self.first_click = False
  1048. return
  1049. elif event.button == right_button and self.mouse_is_dragging is False:
  1050. self.first_click = False
  1051. self.delete_tool_selection_shape()
  1052. if self.app.is_legacy is False:
  1053. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1054. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1055. else:
  1056. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1057. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1058. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1059. self.app.on_mouse_click_over_plot)
  1060. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1061. self.app.on_mouse_move_over_plot)
  1062. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1063. self.app.on_mouse_click_release_over_plot)
  1064. if len(self.sel_rect) == 0:
  1065. return
  1066. self.sel_rect = cascaded_union(self.sel_rect)
  1067. self.paint_poly_area(obj=self.paint_obj,
  1068. tooldia=self.tooldia_list,
  1069. sel_obj=self.sel_rect,
  1070. outname=self.o_name,
  1071. overlap=self.overlap,
  1072. connect=self.connect,
  1073. contour=self.contour)
  1074. # called on mouse move
  1075. def on_mouse_move(self, event):
  1076. if self.app.is_legacy is False:
  1077. event_pos = event.pos
  1078. event_is_dragging = event.is_dragging
  1079. right_button = 2
  1080. else:
  1081. event_pos = (event.xdata, event.ydata)
  1082. event_is_dragging = self.app.plotcanvas.is_dragging
  1083. right_button = 3
  1084. try:
  1085. x = float(event_pos[0])
  1086. y = float(event_pos[1])
  1087. except TypeError:
  1088. return
  1089. curr_pos = self.app.plotcanvas.translate_coords((x, y))
  1090. # detect mouse dragging motion
  1091. if event_is_dragging == 1:
  1092. self.mouse_is_dragging = True
  1093. else:
  1094. self.mouse_is_dragging = False
  1095. # update the cursor position
  1096. if self.app.grid_status() == True:
  1097. # Update cursor
  1098. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1099. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1100. symbol='++', edge_color=self.app.cursor_color_3D,
  1101. size=self.app.defaults["global_cursor_size"])
  1102. # update the positions on status bar
  1103. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  1104. "<b>Y</b>: %.4f" % (curr_pos[0], curr_pos[1]))
  1105. if self.cursor_pos is None:
  1106. self.cursor_pos = (0, 0)
  1107. dx = curr_pos[0] - float(self.cursor_pos[0])
  1108. dy = curr_pos[1] - float(self.cursor_pos[1])
  1109. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1110. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  1111. # draw the utility geometry
  1112. if self.first_click:
  1113. self.app.delete_selection_shape()
  1114. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  1115. coords=(curr_pos[0], curr_pos[1]))
  1116. def paint_poly(self, obj,
  1117. inside_pt=None,
  1118. poly_list=None,
  1119. tooldia=None,
  1120. overlap=None,
  1121. order=None,
  1122. margin=None,
  1123. method=None,
  1124. outname=None,
  1125. connect=None,
  1126. contour=None,
  1127. tools_storage=None,
  1128. plot=True,
  1129. run_threaded=True):
  1130. """
  1131. Paints a polygon selected by clicking on its interior or by having a point coordinates given
  1132. Note:
  1133. * The margin is taken directly from the form.
  1134. :param obj: painted object
  1135. :param inside_pt: [x, y]
  1136. :param tooldia: Diameter of the painting tool
  1137. :param overlap: Overlap of the tool between passes.
  1138. :param order: if the tools are ordered and how
  1139. :param margin: a border around painting area
  1140. :param outname: Name of the resulting Geometry Object.
  1141. :param connect: Connect lines to avoid tool lifts.
  1142. :param contour: Paint around the edges.
  1143. :param method: choice out of 'seed', 'normal', 'lines'
  1144. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1145. Usage of the different one is related to when this function is called from a TcL command.
  1146. :return: None
  1147. """
  1148. if isinstance(obj, FlatCAMGerber):
  1149. if self.app.defaults["gerber_buffering"] == 'no':
  1150. self.app.inform.emit('%s %s %s' %
  1151. (_("Paint Tool."), _("Normal painting polygon task started."),
  1152. _("Buffering geometry...")))
  1153. else:
  1154. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Normal painting polygon task started.")))
  1155. else:
  1156. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Normal painting polygon task started.")))
  1157. if isinstance(obj, FlatCAMGerber):
  1158. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1159. if isinstance(obj.solid_geometry, list):
  1160. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1161. else:
  1162. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1163. polygon_list = None
  1164. if inside_pt and poly_list is None:
  1165. polygon_list = [self.find_polygon(point=inside_pt, geoset=obj.solid_geometry)]
  1166. elif inside_pt is None and poly_list:
  1167. polygon_list = poly_list
  1168. # No polygon?
  1169. if polygon_list is None:
  1170. self.app.log.warning('No polygon found.')
  1171. self.app.inform.emit('[WARNING] %s' % _('No polygon found.'))
  1172. return
  1173. paint_method = method if method is not None else self.paintmethod_combo.get_value()
  1174. paint_margin = float(self.paintmargin_entry.get_value()) if margin is None else margin
  1175. # determine if to use the progressive plotting
  1176. prog_plot = True if self.app.defaults["tools_paint_plotting"] == 'progressive' else False
  1177. name = outname if outname is not None else self.obj_name + "_paint"
  1178. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"])
  1179. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1180. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1181. order = order if order is not None else self.order_radio.get_value()
  1182. tools_storage = self.paint_tools if tools_storage is None else tools_storage
  1183. sorted_tools = []
  1184. if tooldia is not None:
  1185. try:
  1186. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1187. except AttributeError:
  1188. if not isinstance(tooldia, list):
  1189. sorted_tools = [float(tooldia)]
  1190. else:
  1191. sorted_tools = tooldia
  1192. else:
  1193. for row in range(self.tools_table.rowCount()):
  1194. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1195. # sort the tools if we have an order selected in the UI
  1196. if order == 'fwd':
  1197. sorted_tools.sort(reverse=False)
  1198. elif order == 'rev':
  1199. sorted_tools.sort(reverse=True)
  1200. proc = self.app.proc_container.new(_("Painting polygon..."))
  1201. # Initializes the new geometry object
  1202. def gen_paintarea(geo_obj, app_obj):
  1203. geo_obj.solid_geometry = list()
  1204. def paint_p(polyg, tooldiameter):
  1205. cpoly = None
  1206. try:
  1207. if paint_method == "seed":
  1208. # Type(cp) == FlatCAMRTreeStorage | None
  1209. cpoly = self.clear_polygon2(polyg,
  1210. tooldia=tooldiameter,
  1211. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1212. overlap=over,
  1213. contour=cont,
  1214. connect=conn,
  1215. prog_plot=prog_plot)
  1216. elif paint_method == "lines":
  1217. # Type(cp) == FlatCAMRTreeStorage | None
  1218. cpoly = self.clear_polygon3(polyg,
  1219. tooldia=tooldiameter,
  1220. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1221. overlap=over,
  1222. contour=cont,
  1223. connect=conn,
  1224. prog_plot=prog_plot)
  1225. else:
  1226. # Type(cp) == FlatCAMRTreeStorage | None
  1227. cpoly = self.clear_polygon(polyg,
  1228. tooldia=tooldiameter,
  1229. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1230. overlap=over,
  1231. contour=cont,
  1232. connect=conn,
  1233. prog_plot=prog_plot)
  1234. except FlatCAMApp.GracefulException:
  1235. return "fail"
  1236. except Exception as e:
  1237. log.debug("ToolPaint.paint_poly().gen_paintarea().paint_p() --> %s" % str(e))
  1238. if cpoly is not None:
  1239. geo_obj.solid_geometry += list(cpoly.get_objects())
  1240. return cpoly
  1241. else:
  1242. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1243. _('Geometry could not be painted completely'))
  1244. return None
  1245. current_uid = int(1)
  1246. tool_dia = None
  1247. for tool_dia in sorted_tools:
  1248. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1249. for k, v in tools_storage.items():
  1250. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1251. current_uid = int(k)
  1252. break
  1253. try:
  1254. poly_buf = [pol.buffer(-paint_margin) for pol in polygon_list]
  1255. cp = list()
  1256. try:
  1257. for pp in poly_buf:
  1258. cp.append(paint_p(pp, tooldiameter=tool_dia))
  1259. except TypeError:
  1260. cp = paint_p(poly_buf, tooldiameter=tool_dia)
  1261. total_geometry = list()
  1262. if cp:
  1263. try:
  1264. for x in cp:
  1265. total_geometry += list(x.get_objects())
  1266. except TypeError:
  1267. total_geometry = list(cp.get_objects())
  1268. except FlatCAMApp.GracefulException:
  1269. return "fail"
  1270. except Exception as e:
  1271. log.debug("Could not Paint the polygons. %s" % str(e))
  1272. app_obj.inform.emit('[ERROR] %s\n%s' %
  1273. (_("Could not do Paint. Try a different combination of parameters. "
  1274. "Or a different strategy of paint"),
  1275. str(e)
  1276. )
  1277. )
  1278. return "fail"
  1279. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1280. # dictionary and then reset the temporary list that stored that solid_geometry
  1281. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1282. tools_storage[current_uid]['data']['name'] = name
  1283. # clean the progressive plotted shapes if it was used
  1284. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1285. self.temp_shapes.clear(update=True)
  1286. # delete tools with empty geometry
  1287. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1288. for uid in list(tools_storage.keys()):
  1289. # if the solid_geometry (type=list) is empty
  1290. if not tools_storage[uid]['solid_geometry']:
  1291. tools_storage.pop(uid, None)
  1292. geo_obj.options["cnctooldia"] = str(tool_dia)
  1293. # this will turn on the FlatCAMCNCJob plot for multiple tools
  1294. geo_obj.multigeo = True
  1295. geo_obj.multitool = True
  1296. geo_obj.tools.clear()
  1297. geo_obj.tools = dict(tools_storage)
  1298. geo_obj.solid_geometry = cascaded_union(tools_storage[current_uid]['solid_geometry'])
  1299. try:
  1300. a, b, c, d = geo_obj.solid_geometry.bounds
  1301. geo_obj.options['xmin'] = a
  1302. geo_obj.options['ymin'] = b
  1303. geo_obj.options['xmax'] = c
  1304. geo_obj.options['ymax'] = d
  1305. except Exception as e:
  1306. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1307. return
  1308. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1309. has_solid_geo = 0
  1310. for tooluid in geo_obj.tools:
  1311. if geo_obj.tools[tooluid]['solid_geometry']:
  1312. has_solid_geo += 1
  1313. if has_solid_geo == 0:
  1314. self.app.inform.emit('[ERROR] %s' %
  1315. _("There is no Painting Geometry in the file.\n"
  1316. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1317. "Change the painting parameters and try again."))
  1318. return
  1319. total_geometry[:] = []
  1320. self.app.inform.emit('[success] %s' % _("Paint Single Done."))
  1321. # Experimental...
  1322. # print("Indexing...", end=' ')
  1323. # geo_obj.make_index()
  1324. # if errors == 0:
  1325. # print("[success] Paint single polygon Done")
  1326. # self.app.inform.emit("[success] Paint single polygon Done")
  1327. # else:
  1328. # print("[WARNING] Paint single polygon done with errors")
  1329. # self.app.inform.emit("[WARNING] Paint single polygon done with errors. "
  1330. # "%d area(s) could not be painted.\n"
  1331. # "Use different paint parameters or edit the paint geometry and correct"
  1332. # "the issue."
  1333. # % errors)
  1334. def job_thread(app_obj):
  1335. try:
  1336. app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  1337. except FlatCAMApp.GracefulException:
  1338. proc.done()
  1339. return
  1340. except Exception as e:
  1341. proc.done()
  1342. self.app.inform.emit('[ERROR_NOTCL] %s --> %s' %
  1343. ('PaintTool.paint_poly()',
  1344. str(e)))
  1345. return
  1346. proc.done()
  1347. # focus on Selected Tab
  1348. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1349. self.app.inform.emit(_("Polygon Paint started ..."))
  1350. # Promise object with the new name
  1351. self.app.collection.promise(name)
  1352. if run_threaded:
  1353. # Background
  1354. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1355. else:
  1356. job_thread(app_obj=self.app)
  1357. def paint_poly_all(self, obj,
  1358. tooldia=None,
  1359. overlap=None,
  1360. order=None,
  1361. margin=None,
  1362. method=None,
  1363. outname=None,
  1364. connect=None,
  1365. contour=None,
  1366. tools_storage=None,
  1367. plot=True,
  1368. run_threaded=True):
  1369. """
  1370. Paints all polygons in this object.
  1371. :param obj: painted object
  1372. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1373. :param overlap: value by which the paths will overlap
  1374. :param order: if the tools are ordered and how
  1375. :param margin: a border around painting area
  1376. :param outname: name of the resulting object
  1377. :param connect: Connect lines to avoid tool lifts.
  1378. :param contour: Paint around the edges.
  1379. :param method: choice out of 'seed', 'normal', 'lines'
  1380. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1381. Usage of the different one is related to when this function is called from a TcL command.
  1382. :return:
  1383. """
  1384. paint_method = method if method is not None else self.paintmethod_combo.get_value()
  1385. if margin is not None:
  1386. paint_margin = margin
  1387. else:
  1388. paint_margin = float(self.paintmargin_entry.get_value())
  1389. # determine if to use the progressive plotting
  1390. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1391. prog_plot = True
  1392. else:
  1393. prog_plot = False
  1394. proc = self.app.proc_container.new(_("Painting polygons..."))
  1395. name = outname if outname is not None else self.obj_name + "_paint"
  1396. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"])
  1397. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1398. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1399. order = order if order is not None else self.order_radio.get_value()
  1400. sorted_tools = []
  1401. if tooldia is not None:
  1402. try:
  1403. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1404. except AttributeError:
  1405. if not isinstance(tooldia, list):
  1406. sorted_tools = [float(tooldia)]
  1407. else:
  1408. sorted_tools = tooldia
  1409. else:
  1410. for row in range(self.tools_table.rowCount()):
  1411. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1412. if tools_storage is not None:
  1413. tools_storage = tools_storage
  1414. else:
  1415. tools_storage = self.paint_tools
  1416. # This is a recursive generator of individual Polygons.
  1417. # Note: Double check correct implementation. Might exit
  1418. # early if it finds something that is not a Polygon?
  1419. # def recurse(geo):
  1420. # try:
  1421. # for subg in geo:
  1422. # for subsubg in recurse(subg):
  1423. # yield subsubg
  1424. # except TypeError:
  1425. # if isinstance(geo, Polygon):
  1426. # yield geo
  1427. #
  1428. # raise StopIteration
  1429. def recurse(geometry, reset=True):
  1430. """
  1431. Creates a list of non-iterable linear geometry objects.
  1432. Results are placed in self.flat_geometry
  1433. :param geometry: Shapely type or list or list of list of such.
  1434. :param reset: Clears the contents of self.flat_geometry.
  1435. """
  1436. if self.app.abort_flag:
  1437. # graceful abort requested by the user
  1438. raise FlatCAMApp.GracefulException
  1439. if geometry is None:
  1440. return
  1441. if reset:
  1442. self.flat_geometry = []
  1443. # ## If iterable, expand recursively.
  1444. try:
  1445. for geo in geometry:
  1446. if geo is not None:
  1447. recurse(geometry=geo, reset=False)
  1448. # ## Not iterable, do the actual indexing and add.
  1449. except TypeError:
  1450. if isinstance(geometry, LinearRing):
  1451. g = Polygon(geometry)
  1452. self.flat_geometry.append(g)
  1453. else:
  1454. self.flat_geometry.append(geometry)
  1455. return self.flat_geometry
  1456. # Initializes the new geometry object
  1457. def gen_paintarea(geo_obj, app_obj):
  1458. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1459. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1460. log.debug("Paint Tool. Normal painting all task started.")
  1461. if isinstance(obj, FlatCAMGerber):
  1462. if app_obj.defaults["gerber_buffering"] == 'no':
  1463. app_obj.inform.emit('%s %s' %
  1464. (_("Paint Tool. Normal painting all task started."),
  1465. _("Buffering geometry...")))
  1466. else:
  1467. app_obj.inform.emit(_("Paint Tool. Normal painting all task started."))
  1468. else:
  1469. app_obj.inform.emit(_("Paint Tool. Normal painting all task started."))
  1470. tool_dia = None
  1471. if order == 'fwd':
  1472. sorted_tools.sort(reverse=False)
  1473. elif order == 'rev':
  1474. sorted_tools.sort(reverse=True)
  1475. else:
  1476. pass
  1477. if isinstance(obj, FlatCAMGerber):
  1478. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1479. if isinstance(obj.solid_geometry, list):
  1480. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1481. else:
  1482. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1483. try:
  1484. a, b, c, d = obj.bounds()
  1485. geo_obj.options['xmin'] = a
  1486. geo_obj.options['ymin'] = b
  1487. geo_obj.options['xmax'] = c
  1488. geo_obj.options['ymax'] = d
  1489. except Exception as e:
  1490. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1491. return
  1492. total_geometry = []
  1493. current_uid = int(1)
  1494. geo_obj.solid_geometry = []
  1495. for tool_dia in sorted_tools:
  1496. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1497. app_obj.inform.emit(
  1498. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1499. str(tool_dia),
  1500. self.units.lower(),
  1501. _('started'))
  1502. )
  1503. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1504. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1505. for k, v in tools_storage.items():
  1506. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1507. current_uid = int(k)
  1508. break
  1509. painted_area = recurse(obj.solid_geometry)
  1510. # variables to display the percentage of work done
  1511. geo_len = len(painted_area)
  1512. old_disp_number = 0
  1513. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1514. pol_nr = 0
  1515. for geo in painted_area:
  1516. try:
  1517. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  1518. if not isinstance(geo, Polygon):
  1519. continue
  1520. poly_buf = geo.buffer(-paint_margin)
  1521. if paint_method == "seed":
  1522. # Type(cp) == FlatCAMRTreeStorage | None
  1523. cp = self.clear_polygon2(poly_buf,
  1524. tooldia=tool_dia,
  1525. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1526. overlap=over,
  1527. contour=cont,
  1528. connect=conn,
  1529. prog_plot=prog_plot)
  1530. elif paint_method == "lines":
  1531. # Type(cp) == FlatCAMRTreeStorage | None
  1532. cp = self.clear_polygon3(poly_buf,
  1533. tooldia=tool_dia,
  1534. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1535. overlap=over,
  1536. contour=cont,
  1537. connect=conn,
  1538. prog_plot=prog_plot)
  1539. else:
  1540. # Type(cp) == FlatCAMRTreeStorage | None
  1541. cp = self.clear_polygon(poly_buf,
  1542. tooldia=tool_dia,
  1543. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1544. overlap=over,
  1545. contour=cont,
  1546. connect=conn,
  1547. prog_plot=prog_plot)
  1548. if cp is not None:
  1549. total_geometry += list(cp.get_objects())
  1550. except FlatCAMApp.GracefulException:
  1551. return "fail"
  1552. except Exception as e:
  1553. log.debug("Could not Paint the polygons. %s" % str(e))
  1554. self.app.inform.emit('[ERROR] %s\n%s' %
  1555. (_("Could not do Paint All. Try a different combination of parameters. "
  1556. "Or a different Method of paint"),
  1557. str(e)))
  1558. return "fail"
  1559. pol_nr += 1
  1560. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1561. # log.debug("Polygons cleared: %d" % pol_nr)
  1562. if old_disp_number < disp_number <= 100:
  1563. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  1564. old_disp_number = disp_number
  1565. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1566. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1567. # dictionary and then reset the temporary list that stored that solid_geometry
  1568. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1569. tools_storage[current_uid]['data']['name'] = name
  1570. total_geometry[:] = []
  1571. # clean the progressive plotted shapes if it was used
  1572. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1573. self.temp_shapes.clear(update=True)
  1574. # delete tools with empty geometry
  1575. keys_to_delete = []
  1576. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1577. for uid in tools_storage:
  1578. # if the solid_geometry (type=list) is empty
  1579. if not tools_storage[uid]['solid_geometry']:
  1580. keys_to_delete.append(uid)
  1581. # actual delete of keys from the tools_storage dict
  1582. for k in keys_to_delete:
  1583. tools_storage.pop(k, None)
  1584. geo_obj.options["cnctooldia"] = str(tool_dia)
  1585. # this turn on the FlatCAMCNCJob plot for multiple tools
  1586. geo_obj.multigeo = True
  1587. geo_obj.multitool = True
  1588. geo_obj.tools.clear()
  1589. geo_obj.tools = dict(tools_storage)
  1590. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1591. has_solid_geo = 0
  1592. for tooluid in geo_obj.tools:
  1593. if geo_obj.tools[tooluid]['solid_geometry']:
  1594. has_solid_geo += 1
  1595. if has_solid_geo == 0:
  1596. self.app.inform.emit('[ERROR] %s' %
  1597. _("There is no Painting Geometry in the file.\n"
  1598. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1599. "Change the painting parameters and try again."))
  1600. return
  1601. # Experimental...
  1602. # print("Indexing...", end=' ')
  1603. # geo_obj.make_index()
  1604. self.app.inform.emit('[success] %s' % _("Paint All Done."))
  1605. # Initializes the new geometry object
  1606. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1607. assert isinstance(geo_obj, FlatCAMGeometry), \
  1608. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1609. log.debug("Paint Tool. Rest machining painting all task started.")
  1610. if isinstance(obj, FlatCAMGerber):
  1611. if app_obj.defaults["gerber_buffering"] == 'no':
  1612. app_obj.inform.emit('%s %s %s' %
  1613. (_("Paint Tool."), _("Rest machining painting all task started."),
  1614. _("Buffering geometry...")))
  1615. else:
  1616. app_obj.inform.emit('%s %s' %
  1617. (_("Paint Tool."), _("Rest machining painting all task started.")))
  1618. else:
  1619. app_obj.inform.emit('%s %s' %
  1620. (_("Paint Tool."), _("Rest machining painting all task started.")))
  1621. tool_dia = None
  1622. sorted_tools.sort(reverse=True)
  1623. cleared_geo = []
  1624. current_uid = int(1)
  1625. geo_obj.solid_geometry = []
  1626. if isinstance(obj, FlatCAMGerber):
  1627. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1628. if isinstance(obj.solid_geometry, list):
  1629. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1630. else:
  1631. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1632. try:
  1633. a, b, c, d = obj.bounds()
  1634. geo_obj.options['xmin'] = a
  1635. geo_obj.options['ymin'] = b
  1636. geo_obj.options['xmax'] = c
  1637. geo_obj.options['ymax'] = d
  1638. except Exception as e:
  1639. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1640. return
  1641. for tool_dia in sorted_tools:
  1642. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1643. app_obj.inform.emit(
  1644. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1645. str(tool_dia),
  1646. self.units.lower(),
  1647. _('started'))
  1648. )
  1649. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1650. painted_area = recurse(obj.solid_geometry)
  1651. # variables to display the percentage of work done
  1652. geo_len = int(len(painted_area) / 100)
  1653. old_disp_number = 0
  1654. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1655. pol_nr = 0
  1656. for geo in painted_area:
  1657. try:
  1658. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  1659. poly_buf = geo.buffer(-paint_margin)
  1660. cp = None
  1661. if paint_method == "standard":
  1662. # Type(cp) == FlatCAMRTreeStorage | None
  1663. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1664. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1665. overlap=over, contour=cont, connect=conn,
  1666. prog_plot=prog_plot)
  1667. elif paint_method == "seed":
  1668. # Type(cp) == FlatCAMRTreeStorage | None
  1669. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1670. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1671. overlap=over, contour=cont, connect=conn,
  1672. prog_plot=prog_plot)
  1673. elif paint_method == "lines":
  1674. # Type(cp) == FlatCAMRTreeStorage | None
  1675. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1676. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1677. overlap=over, contour=cont, connect=conn,
  1678. prog_plot=prog_plot)
  1679. if cp is not None:
  1680. cleared_geo += list(cp.get_objects())
  1681. except FlatCAMApp.GracefulException:
  1682. return "fail"
  1683. except Exception as e:
  1684. log.debug("Could not Paint the polygons. %s" % str(e))
  1685. self.app.inform.emit('[ERROR] %s\n%s' %
  1686. (_("Could not do Paint All. Try a different combination of parameters. "
  1687. "Or a different Method of paint"),
  1688. str(e)))
  1689. return "fail"
  1690. pol_nr += 1
  1691. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1692. # log.debug("Polygons cleared: %d" % pol_nr)
  1693. if old_disp_number < disp_number <= 100:
  1694. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  1695. old_disp_number = disp_number
  1696. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1697. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1698. for k, v in tools_storage.items():
  1699. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1700. current_uid = int(k)
  1701. break
  1702. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  1703. # then reset the temporary list that stored that solid_geometry
  1704. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1705. tools_storage[current_uid]['data']['name'] = name
  1706. cleared_geo[:] = []
  1707. geo_obj.options["cnctooldia"] = str(tool_dia)
  1708. # this turn on the FlatCAMCNCJob plot for multiple tools
  1709. geo_obj.multigeo = True
  1710. geo_obj.multitool = True
  1711. geo_obj.tools.clear()
  1712. geo_obj.tools = dict(tools_storage)
  1713. # clean the progressive plotted shapes if it was used
  1714. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1715. self.temp_shapes.clear(update=True)
  1716. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1717. has_solid_geo = 0
  1718. for tooluid in geo_obj.tools:
  1719. if geo_obj.tools[tooluid]['solid_geometry']:
  1720. has_solid_geo += 1
  1721. if has_solid_geo == 0:
  1722. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1723. _("There is no Painting Geometry in the file.\n"
  1724. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1725. "Change the painting parameters and try again."))
  1726. return
  1727. # Experimental...
  1728. # print("Indexing...", end=' ')
  1729. # geo_obj.make_index()
  1730. self.app.inform.emit('[success] %s' % _("Paint All with Rest-Machining done."))
  1731. def job_thread(app_obj):
  1732. try:
  1733. if self.rest_cb.isChecked():
  1734. app_obj.new_object("geometry", name, gen_paintarea_rest_machining, plot=plot)
  1735. else:
  1736. app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  1737. except FlatCAMApp.GracefulException:
  1738. proc.done()
  1739. return
  1740. except Exception:
  1741. proc.done()
  1742. traceback.print_stack()
  1743. return
  1744. proc.done()
  1745. # focus on Selected Tab
  1746. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1747. self.app.inform.emit(_("Polygon Paint started ..."))
  1748. # Promise object with the new name
  1749. self.app.collection.promise(name)
  1750. if run_threaded:
  1751. # Background
  1752. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1753. else:
  1754. job_thread(app_obj=self.app)
  1755. def paint_poly_area(self, obj, sel_obj,
  1756. tooldia=None,
  1757. overlap=None,
  1758. order=None,
  1759. margin=None,
  1760. method=None,
  1761. outname=None,
  1762. connect=None,
  1763. contour=None,
  1764. tools_storage=None,
  1765. plot=True,
  1766. run_threaded=True):
  1767. """
  1768. Paints all polygons in this object that are within the sel_obj object
  1769. :param obj: painted object
  1770. :param sel_obj: paint only what is inside this object bounds
  1771. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1772. :param overlap: value by which the paths will overlap
  1773. :param order: if the tools are ordered and how
  1774. :param margin: a border around painting area
  1775. :param outname: name of the resulting object
  1776. :param connect: Connect lines to avoid tool lifts.
  1777. :param contour: Paint around the edges.
  1778. :param method: choice out of 'seed', 'normal', 'lines'
  1779. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1780. Usage of the different one is related to when this function is called from a TcL command.
  1781. :return:
  1782. """
  1783. paint_method = method if method is not None else self.paintmethod_combo.get_value()
  1784. if margin is not None:
  1785. paint_margin = margin
  1786. else:
  1787. try:
  1788. paint_margin = float(self.paintmargin_entry.get_value())
  1789. except ValueError:
  1790. # try to convert comma to decimal point. if it's still not working error message and return
  1791. try:
  1792. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  1793. except ValueError:
  1794. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1795. _("Wrong value format entered, use a number."))
  1796. return
  1797. # determine if to use the progressive plotting
  1798. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1799. prog_plot = True
  1800. else:
  1801. prog_plot = False
  1802. proc = self.app.proc_container.new(_("Painting polygons..."))
  1803. name = outname if outname is not None else self.obj_name + "_paint"
  1804. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"])
  1805. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1806. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1807. order = order if order is not None else self.order_radio.get_value()
  1808. sorted_tools = []
  1809. if tooldia is not None:
  1810. try:
  1811. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1812. except AttributeError:
  1813. if not isinstance(tooldia, list):
  1814. sorted_tools = [float(tooldia)]
  1815. else:
  1816. sorted_tools = tooldia
  1817. else:
  1818. for row in range(self.tools_table.rowCount()):
  1819. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1820. if tools_storage is not None:
  1821. tools_storage = tools_storage
  1822. else:
  1823. tools_storage = self.paint_tools
  1824. def recurse(geometry, reset=True):
  1825. """
  1826. Creates a list of non-iterable linear geometry objects.
  1827. Results are placed in self.flat_geometry
  1828. :param geometry: Shapely type or list or list of list of such.
  1829. :param reset: Clears the contents of self.flat_geometry.
  1830. """
  1831. if self.app.abort_flag:
  1832. # graceful abort requested by the user
  1833. raise FlatCAMApp.GracefulException
  1834. if geometry is None:
  1835. return
  1836. if reset:
  1837. self.flat_geometry = []
  1838. # ## If iterable, expand recursively.
  1839. try:
  1840. for geo in geometry:
  1841. if geo is not None:
  1842. recurse(geometry=geo, reset=False)
  1843. # ## Not iterable, do the actual indexing and add.
  1844. except TypeError:
  1845. if isinstance(geometry, LinearRing):
  1846. g = Polygon(geometry)
  1847. self.flat_geometry.append(g)
  1848. else:
  1849. self.flat_geometry.append(geometry)
  1850. return self.flat_geometry
  1851. # Initializes the new geometry object
  1852. def gen_paintarea(geo_obj, app_obj):
  1853. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1854. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1855. log.debug("Paint Tool. Normal painting area task started.")
  1856. if isinstance(obj, FlatCAMGerber):
  1857. if app_obj.defaults["gerber_buffering"] == 'no':
  1858. app_obj.inform.emit('%s %s %s' %
  1859. (_("Paint Tool."),
  1860. _("Normal painting area task started."),
  1861. _("Buffering geometry...")))
  1862. else:
  1863. app_obj.inform.emit('%s %s' %
  1864. (_("Paint Tool."), _("Normal painting area task started.")))
  1865. else:
  1866. app_obj.inform.emit('%s %s' %
  1867. (_("Paint Tool."), _("Normal painting area task started.")))
  1868. tool_dia = None
  1869. if order == 'fwd':
  1870. sorted_tools.sort(reverse=False)
  1871. elif order == 'rev':
  1872. sorted_tools.sort(reverse=True)
  1873. else:
  1874. pass
  1875. # this is were heavy lifting is done and creating the geometry to be painted
  1876. target_geo = MultiPolygon(obj.solid_geometry)
  1877. if isinstance(obj, FlatCAMGerber):
  1878. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1879. if isinstance(target_geo, list):
  1880. target_geo = MultiPolygon(target_geo).buffer(0)
  1881. else:
  1882. target_geo = target_geo.buffer(0)
  1883. geo_to_paint = target_geo.intersection(sel_obj)
  1884. painted_area = recurse(geo_to_paint)
  1885. try:
  1886. a, b, c, d = self.paint_bounds(geo_to_paint)
  1887. geo_obj.options['xmin'] = a
  1888. geo_obj.options['ymin'] = b
  1889. geo_obj.options['xmax'] = c
  1890. geo_obj.options['ymax'] = d
  1891. except Exception as e:
  1892. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1893. return
  1894. total_geometry = []
  1895. current_uid = int(1)
  1896. geo_obj.solid_geometry = []
  1897. for tool_dia in sorted_tools:
  1898. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1899. app_obj.inform.emit(
  1900. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1901. str(tool_dia),
  1902. self.units.lower(),
  1903. _('started'))
  1904. )
  1905. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1906. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1907. for k, v in tools_storage.items():
  1908. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1909. current_uid = int(k)
  1910. break
  1911. # variables to display the percentage of work done
  1912. geo_len = len(painted_area)
  1913. old_disp_number = 0
  1914. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1915. pol_nr = 0
  1916. for geo in painted_area:
  1917. try:
  1918. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  1919. if not isinstance(geo, Polygon):
  1920. continue
  1921. poly_buf = geo.buffer(-paint_margin)
  1922. if paint_method == "seed":
  1923. # Type(cp) == FlatCAMRTreeStorage | None
  1924. cp = self.clear_polygon2(poly_buf,
  1925. tooldia=tool_dia,
  1926. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1927. overlap=over,
  1928. contour=cont,
  1929. connect=conn,
  1930. prog_plot=prog_plot)
  1931. elif paint_method == "lines":
  1932. # Type(cp) == FlatCAMRTreeStorage | None
  1933. cp = self.clear_polygon3(poly_buf,
  1934. tooldia=tool_dia,
  1935. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1936. overlap=over,
  1937. contour=cont,
  1938. connect=conn,
  1939. prog_plot=prog_plot)
  1940. else:
  1941. # Type(cp) == FlatCAMRTreeStorage | None
  1942. cp = self.clear_polygon(poly_buf,
  1943. tooldia=tool_dia,
  1944. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1945. overlap=over,
  1946. contour=cont,
  1947. connect=conn,
  1948. prog_plot=prog_plot)
  1949. if cp is not None:
  1950. total_geometry += list(cp.get_objects())
  1951. except FlatCAMApp.GracefulException:
  1952. return "fail"
  1953. except Exception as e:
  1954. log.debug("Could not Paint the polygons. %s" % str(e))
  1955. self.app.inform.emit('[ERROR] %s\n%s' %
  1956. (_("Could not do Paint All. Try a different combination of parameters. "
  1957. "Or a different Method of paint"), str(e)))
  1958. return
  1959. pol_nr += 1
  1960. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1961. # log.debug("Polygons cleared: %d" % pol_nr)
  1962. if old_disp_number < disp_number <= 100:
  1963. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  1964. old_disp_number = disp_number
  1965. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1966. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1967. # dictionary and then reset the temporary list that stored that solid_geometry
  1968. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1969. tools_storage[current_uid]['data']['name'] = name
  1970. total_geometry[:] = []
  1971. # clean the progressive plotted shapes if it was used
  1972. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1973. self.temp_shapes.clear(update=True)
  1974. # delete tools with empty geometry
  1975. keys_to_delete = []
  1976. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1977. for uid in tools_storage:
  1978. # if the solid_geometry (type=list) is empty
  1979. if not tools_storage[uid]['solid_geometry']:
  1980. keys_to_delete.append(uid)
  1981. # actual delete of keys from the tools_storage dict
  1982. for k in keys_to_delete:
  1983. tools_storage.pop(k, None)
  1984. geo_obj.options["cnctooldia"] = str(tool_dia)
  1985. # this turn on the FlatCAMCNCJob plot for multiple tools
  1986. geo_obj.multigeo = True
  1987. geo_obj.multitool = True
  1988. geo_obj.tools.clear()
  1989. geo_obj.tools = dict(tools_storage)
  1990. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1991. has_solid_geo = 0
  1992. for tooluid in geo_obj.tools:
  1993. if geo_obj.tools[tooluid]['solid_geometry']:
  1994. has_solid_geo += 1
  1995. if has_solid_geo == 0:
  1996. self.app.inform.emit('[ERROR] %s' %
  1997. _("There is no Painting Geometry in the file.\n"
  1998. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1999. "Change the painting parameters and try again."))
  2000. return
  2001. # Experimental...
  2002. # print("Indexing...", end=' ')
  2003. # geo_obj.make_index()
  2004. self.app.inform.emit('[success] %s' % _("Paint Area Done."))
  2005. # Initializes the new geometry object
  2006. def gen_paintarea_rest_machining(geo_obj, app_obj):
  2007. assert isinstance(geo_obj, FlatCAMGeometry), \
  2008. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2009. log.debug("Paint Tool. Rest machining painting area task started.")
  2010. if isinstance(obj, FlatCAMGerber):
  2011. if app_obj.defaults["gerber_buffering"] == 'no':
  2012. app_obj.inform.emit('%s %s %s' %
  2013. (_("Paint Tool."),
  2014. _("Rest machining painting area task started."),
  2015. _("Buffering geometry...")))
  2016. else:
  2017. app_obj.inform.emit(_("Paint Tool. Rest machining painting area task started."))
  2018. else:
  2019. app_obj.inform.emit('%s %s' %
  2020. (_("Paint Tool."), _("Rest machining painting area task started.")))
  2021. tool_dia = None
  2022. sorted_tools.sort(reverse=True)
  2023. cleared_geo = []
  2024. current_uid = int(1)
  2025. geo_obj.solid_geometry = []
  2026. # this is were heavy lifting is done and creating the geometry to be painted
  2027. target_geo = obj.solid_geometry
  2028. if isinstance(obj, FlatCAMGerber):
  2029. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2030. if isinstance(target_geo, list):
  2031. target_geo = MultiPolygon(target_geo).buffer(0)
  2032. else:
  2033. target_geo = target_geo.buffer(0)
  2034. geo_to_paint = target_geo.intersection(sel_obj)
  2035. painted_area = recurse(geo_to_paint)
  2036. try:
  2037. a, b, c, d = obj.bounds()
  2038. geo_obj.options['xmin'] = a
  2039. geo_obj.options['ymin'] = b
  2040. geo_obj.options['xmax'] = c
  2041. geo_obj.options['ymax'] = d
  2042. except Exception as e:
  2043. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  2044. return
  2045. for tool_dia in sorted_tools:
  2046. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  2047. app_obj.inform.emit(
  2048. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  2049. str(tool_dia),
  2050. self.units.lower(),
  2051. _('started'))
  2052. )
  2053. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2054. # variables to display the percentage of work done
  2055. geo_len = len(painted_area)
  2056. old_disp_number = 0
  2057. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2058. pol_nr = 0
  2059. for geo in painted_area:
  2060. try:
  2061. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  2062. poly_buf = geo.buffer(-paint_margin)
  2063. cp = None
  2064. if paint_method == "standard":
  2065. # Type(cp) == FlatCAMRTreeStorage | None
  2066. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  2067. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2068. overlap=over, contour=cont, connect=conn,
  2069. prog_plot=prog_plot)
  2070. elif paint_method == "seed":
  2071. # Type(cp) == FlatCAMRTreeStorage | None
  2072. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  2073. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2074. overlap=over, contour=cont, connect=conn,
  2075. prog_plot=prog_plot)
  2076. elif paint_method == "lines":
  2077. # Type(cp) == FlatCAMRTreeStorage | None
  2078. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  2079. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2080. overlap=over, contour=cont, connect=conn,
  2081. prog_plot=prog_plot)
  2082. if cp is not None:
  2083. cleared_geo += list(cp.get_objects())
  2084. except FlatCAMApp.GracefulException:
  2085. return "fail"
  2086. except Exception as e:
  2087. log.debug("Could not Paint the polygons. %s" % str(e))
  2088. self.app.inform.emit('[ERROR] %s\n%s' %
  2089. (_("Could not do Paint All. Try a different combination of parameters. "
  2090. "Or a different Method of paint"), str(e)))
  2091. return
  2092. pol_nr += 1
  2093. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2094. # log.debug("Polygons cleared: %d" % pol_nr)
  2095. if old_disp_number < disp_number <= 100:
  2096. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  2097. old_disp_number = disp_number
  2098. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2099. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  2100. for k, v in tools_storage.items():
  2101. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  2102. current_uid = int(k)
  2103. break
  2104. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  2105. # then reset the temporary list that stored that solid_geometry
  2106. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  2107. tools_storage[current_uid]['data']['name'] = name
  2108. cleared_geo[:] = []
  2109. geo_obj.options["cnctooldia"] = str(tool_dia)
  2110. # this turn on the FlatCAMCNCJob plot for multiple tools
  2111. geo_obj.multigeo = True
  2112. geo_obj.multitool = True
  2113. geo_obj.tools.clear()
  2114. geo_obj.tools = dict(self.paint_tools)
  2115. # clean the progressive plotted shapes if it was used
  2116. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2117. self.temp_shapes.clear(update=True)
  2118. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2119. has_solid_geo = 0
  2120. for tooluid in geo_obj.tools:
  2121. if geo_obj.tools[tooluid]['solid_geometry']:
  2122. has_solid_geo += 1
  2123. if has_solid_geo == 0:
  2124. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2125. _("There is no Painting Geometry in the file.\n"
  2126. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2127. "Change the painting parameters and try again."))
  2128. return
  2129. # Experimental...
  2130. # print("Indexing...", end=' ')
  2131. # geo_obj.make_index()
  2132. self.app.inform.emit('[success] %s' % _("Paint All with Rest-Machining done."))
  2133. def job_thread(app_obj):
  2134. try:
  2135. if self.rest_cb.isChecked():
  2136. app_obj.new_object("geometry", name, gen_paintarea_rest_machining, plot=plot)
  2137. else:
  2138. app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  2139. except FlatCAMApp.GracefulException:
  2140. proc.done()
  2141. return
  2142. except Exception:
  2143. proc.done()
  2144. traceback.print_stack()
  2145. return
  2146. proc.done()
  2147. # focus on Selected Tab
  2148. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2149. self.app.inform.emit(_("Polygon Paint started ..."))
  2150. # Promise object with the new name
  2151. self.app.collection.promise(name)
  2152. if run_threaded:
  2153. # Background
  2154. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2155. else:
  2156. job_thread(app_obj=self.app)
  2157. def paint_poly_ref(self, obj, sel_obj,
  2158. tooldia=None,
  2159. overlap=None,
  2160. order=None,
  2161. margin=None,
  2162. method=None,
  2163. outname=None,
  2164. connect=None,
  2165. contour=None,
  2166. tools_storage=None,
  2167. plot=True,
  2168. run_threaded=True):
  2169. """
  2170. Paints all polygons in this object that are within the sel_obj object
  2171. :param obj: painted object
  2172. :param sel_obj: paint only what is inside this object bounds
  2173. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  2174. :param overlap: value by which the paths will overlap
  2175. :param order: if the tools are ordered and how
  2176. :param margin: a border around painting area
  2177. :param outname: name of the resulting object
  2178. :param connect: Connect lines to avoid tool lifts.
  2179. :param contour: Paint around the edges.
  2180. :param method: choice out of 'seed', 'normal', 'lines'
  2181. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  2182. Usage of the different one is related to when this function is called from a TcL command.
  2183. :return:
  2184. """
  2185. geo = sel_obj.solid_geometry
  2186. try:
  2187. if isinstance(geo, MultiPolygon):
  2188. env_obj = geo.convex_hull
  2189. elif (isinstance(geo, MultiPolygon) and len(geo) == 1) or \
  2190. (isinstance(geo, list) and len(geo) == 1) and isinstance(geo[0], Polygon):
  2191. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  2192. else:
  2193. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  2194. env_obj = env_obj.convex_hull
  2195. sel_rect = env_obj.buffer(distance=0.0000001, join_style=base.JOIN_STYLE.mitre)
  2196. except Exception as e:
  2197. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  2198. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  2199. return
  2200. self.paint_poly_area(obj=obj,
  2201. sel_obj=sel_rect,
  2202. tooldia=tooldia,
  2203. overlap=overlap,
  2204. order=order,
  2205. margin=margin,
  2206. method=method,
  2207. outname=outname,
  2208. connect=connect,
  2209. contour=contour,
  2210. tools_storage=tools_storage,
  2211. plot=plot,
  2212. run_threaded=run_threaded)
  2213. @staticmethod
  2214. def paint_bounds(geometry):
  2215. def bounds_rec(o):
  2216. if type(o) is list:
  2217. minx = Inf
  2218. miny = Inf
  2219. maxx = -Inf
  2220. maxy = -Inf
  2221. for k in o:
  2222. try:
  2223. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  2224. except Exception as e:
  2225. log.debug("ToolPaint.bounds() --> %s" % str(e))
  2226. return
  2227. minx = min(minx, minx_)
  2228. miny = min(miny, miny_)
  2229. maxx = max(maxx, maxx_)
  2230. maxy = max(maxy, maxy_)
  2231. return minx, miny, maxx, maxy
  2232. else:
  2233. # it's a Shapely object, return it's bounds
  2234. return o.bounds
  2235. return bounds_rec(geometry)
  2236. def reset_fields(self):
  2237. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))