ToolPaint.py 117 KB

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