ToolPaint.py 113 KB

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