ToolPaint.py 114 KB

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