ToolPaint.py 141 KB

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