ToolPaint.py 124 KB

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