ToolPaint.py 117 KB

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