ToolPaint.py 125 KB

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