ToolPaint.py 114 KB

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