ToolPaint.py 143 KB

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