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