ToolPaint.py 140 KB

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