ToolPaint.py 211 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163
  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, FlatCAMRTreeStorage
  15. from flatcamGUI.GUIElements import FCTable, FCDoubleSpinner, FCCheckBox, FCInputDialog, RadioSet, FCButton, FCComboBox
  16. import FlatCAMApp
  17. from shapely.geometry import base, Polygon, MultiPolygon, LinearRing, Point, MultiLineString
  18. from shapely.ops import cascaded_union, unary_union, linemerge
  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_label = QtWidgets.QLabel('%s:' % _("Obj Type"))
  63. self.type_obj_combo_label.setToolTip(
  64. _("Specify the type of object to be painted.\n"
  65. "It can be of type: Gerber or Geometry.\n"
  66. "What is selected here will dictate the kind\n"
  67. "of objects that will populate the 'Object' combobox.")
  68. )
  69. self.type_obj_combo_label.setMinimumWidth(60)
  70. self.type_obj_combo = RadioSet([{'label': "Geometry", 'value': 'geometry'},
  71. {'label': "Gerber", 'value': 'gerber'}])
  72. grid0.addWidget(self.type_obj_combo_label, 1, 0)
  73. grid0.addWidget(self.type_obj_combo, 1, 1)
  74. # ################################################
  75. # ##### The object to be painted #################
  76. # ################################################
  77. self.obj_combo = QtWidgets.QComboBox()
  78. self.obj_combo.setModel(self.app.collection)
  79. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  80. self.obj_combo.setCurrentIndex(1)
  81. self.object_label = QtWidgets.QLabel('%s:' % _("Object"))
  82. self.object_label.setToolTip(_("Object to be painted."))
  83. grid0.addWidget(self.object_label, 2, 0)
  84. grid0.addWidget(self.obj_combo, 2, 1)
  85. separator_line = QtWidgets.QFrame()
  86. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  87. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  88. grid0.addWidget(separator_line, 5, 0, 1, 2)
  89. # ### Tools ## ##
  90. self.tools_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Tools Table'))
  91. self.tools_table_label.setToolTip(
  92. _("Tools pool from which the algorithm\n"
  93. "will pick the ones used for painting.")
  94. )
  95. self.tools_table = FCTable()
  96. grid0.addWidget(self.tools_table_label, 6, 0, 1, 2)
  97. grid0.addWidget(self.tools_table, 7, 0, 1, 2)
  98. self.tools_table.setColumnCount(4)
  99. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), ''])
  100. self.tools_table.setColumnHidden(3, True)
  101. # self.tools_table.setSortingEnabled(False)
  102. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  103. self.tools_table.horizontalHeaderItem(0).setToolTip(
  104. _("This is the Tool Number.\n"
  105. "Painting will start with the tool with the biggest diameter,\n"
  106. "continuing until there are no more tools.\n"
  107. "Only tools that create painting geometry will still be present\n"
  108. "in the resulting geometry. This is because with some tools\n"
  109. "this function will not be able to create painting geometry.")
  110. )
  111. self.tools_table.horizontalHeaderItem(1).setToolTip(
  112. _("Tool Diameter. It's value (in current FlatCAM units) \n"
  113. "is the cut width into the material."))
  114. self.tools_table.horizontalHeaderItem(2).setToolTip(
  115. _("The Tool Type (TT) can be:<BR>"
  116. "- <B>Circular</B> with 1 ... 4 teeth -> it is informative only. Being circular, <BR>"
  117. "the cut width in material is exactly the tool diameter.<BR>"
  118. "- <B>Ball</B> -> informative only and make reference to the Ball type endmill.<BR>"
  119. "- <B>V-Shape</B> -> it will disable de Z-Cut parameter in the resulting geometry UI form "
  120. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and "
  121. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such "
  122. "as the cut width into material will be equal with the value in the Tool Diameter "
  123. "column of this table.<BR>"
  124. "Choosing the <B>V-Shape</B> Tool Type automatically will select the Operation Type "
  125. "in the resulting geometry as Isolation."))
  126. self.order_label = QtWidgets.QLabel('<b>%s:</b>' % _('Tool order'))
  127. self.order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  128. "'No' --> means that the used order is the one in the tool table\n"
  129. "'Forward' --> means that the tools will be ordered from small to big\n"
  130. "'Reverse' --> menas that the tools will ordered from big to small\n\n"
  131. "WARNING: using rest machining will automatically set the order\n"
  132. "in reverse and disable this control."))
  133. self.order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  134. {'label': _('Forward'), 'value': 'fwd'},
  135. {'label': _('Reverse'), 'value': 'rev'}])
  136. self.order_radio.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  137. "'No' --> means that the used order is the one in the tool table\n"
  138. "'Forward' --> means that the tools will be ordered from small to big\n"
  139. "'Reverse' --> menas that the tools will ordered from big to small\n\n"
  140. "WARNING: using rest machining will automatically set the order\n"
  141. "in reverse and disable this control."))
  142. grid0.addWidget(self.order_label, 9, 0)
  143. grid0.addWidget(self.order_radio, 9, 1)
  144. separator_line = QtWidgets.QFrame()
  145. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  146. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  147. grid0.addWidget(separator_line, 10, 0, 1, 2)
  148. self.grid3 = QtWidgets.QGridLayout()
  149. self.tools_box.addLayout(self.grid3)
  150. self.grid3.setColumnStretch(0, 0)
  151. self.grid3.setColumnStretch(1, 1)
  152. # ##############################################################################
  153. # ###################### ADD A NEW TOOL ########################################
  154. # ##############################################################################
  155. self.tool_sel_label = QtWidgets.QLabel('<b>%s</b>' % _("New Tool"))
  156. self.grid3.addWidget(self.tool_sel_label, 1, 0, 1, 2)
  157. # Tool Type Radio Button
  158. self.tool_type_label = QtWidgets.QLabel('%s:' % _('Tool Type'))
  159. self.tool_type_label.setToolTip(
  160. _("Default tool type:\n"
  161. "- 'V-shape'\n"
  162. "- Circular")
  163. )
  164. self.tool_type_radio = RadioSet([{'label': _('V-shape'), 'value': 'V'},
  165. {'label': _('Circular'), 'value': 'C1'}])
  166. self.tool_type_radio.setToolTip(
  167. _("Default tool type:\n"
  168. "- 'V-shape'\n"
  169. "- Circular")
  170. )
  171. self.tool_type_radio.setObjectName('p_tool_type')
  172. self.grid3.addWidget(self.tool_type_label, 2, 0)
  173. self.grid3.addWidget(self.tool_type_radio, 2, 1)
  174. # Tip Dia
  175. self.tipdialabel = QtWidgets.QLabel('%s:' % _('V-Tip Dia'))
  176. self.tipdialabel.setToolTip(
  177. _("The tip diameter for V-Shape Tool"))
  178. self.tipdia_entry = FCDoubleSpinner(callback=self.confirmation_message)
  179. self.tipdia_entry.set_precision(self.decimals)
  180. self.tipdia_entry.set_range(0.0000, 9999.9999)
  181. self.tipdia_entry.setSingleStep(0.1)
  182. self.tipdia_entry.setObjectName('p_vtip_dia')
  183. self.grid3.addWidget(self.tipdialabel, 3, 0)
  184. self.grid3.addWidget(self.tipdia_entry, 3, 1)
  185. # Tip Angle
  186. self.tipanglelabel = QtWidgets.QLabel('%s:' % _('V-Tip Angle'))
  187. self.tipanglelabel.setToolTip(
  188. _("The tip angle for V-Shape Tool.\n"
  189. "In degree."))
  190. self.tipangle_entry = FCDoubleSpinner(callback=self.confirmation_message)
  191. self.tipangle_entry.set_precision(self.decimals)
  192. self.tipangle_entry.set_range(0.0000, 180.0000)
  193. self.tipangle_entry.setSingleStep(5)
  194. self.tipangle_entry.setObjectName('p_vtip_angle')
  195. self.grid3.addWidget(self.tipanglelabel, 4, 0)
  196. self.grid3.addWidget(self.tipangle_entry, 4, 1)
  197. # Cut Z entry
  198. cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  199. cutzlabel.setToolTip(
  200. _("Depth of cut into material. Negative value.\n"
  201. "In FlatCAM units.")
  202. )
  203. self.cutz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  204. self.cutz_entry.set_precision(self.decimals)
  205. self.cutz_entry.set_range(-99999.9999, 0.0000)
  206. self.cutz_entry.setObjectName('p_cutz')
  207. self.cutz_entry.setToolTip(
  208. _("Depth of cut into material. Negative value.\n"
  209. "In FlatCAM units.")
  210. )
  211. self.grid3.addWidget(cutzlabel, 5, 0)
  212. self.grid3.addWidget(self.cutz_entry, 5, 1)
  213. # ### Tool Diameter ####
  214. self.addtool_entry_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Tool Dia'))
  215. self.addtool_entry_lbl.setToolTip(
  216. _("Diameter for the new tool to add in the Tool Table.\n"
  217. "If the tool is V-shape type then this value is automatically\n"
  218. "calculated from the other parameters.")
  219. )
  220. self.addtool_entry = FCDoubleSpinner(callback=self.confirmation_message)
  221. self.addtool_entry.set_precision(self.decimals)
  222. self.addtool_entry.set_range(0.000, 9999.9999)
  223. self.addtool_entry.setObjectName('p_tool_dia')
  224. self.grid3.addWidget(self.addtool_entry_lbl, 6, 0)
  225. self.grid3.addWidget(self.addtool_entry, 6, 1)
  226. hlay = QtWidgets.QHBoxLayout()
  227. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  228. self.addtool_btn.setToolTip(
  229. _("Add a new tool to the Tool Table\n"
  230. "with the diameter specified above.")
  231. )
  232. self.addtool_from_db_btn = QtWidgets.QPushButton(_('Add from DB'))
  233. self.addtool_from_db_btn.setToolTip(
  234. _("Add a new tool to the Tool Table\n"
  235. "from the Tool DataBase.")
  236. )
  237. hlay.addWidget(self.addtool_btn)
  238. hlay.addWidget(self.addtool_from_db_btn)
  239. self.grid3.addLayout(hlay, 7, 0, 1, 2)
  240. separator_line = QtWidgets.QFrame()
  241. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  242. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  243. self.grid3.addWidget(separator_line, 8, 0, 1, 2)
  244. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  245. self.deltool_btn.setToolTip(
  246. _("Delete a selection of tools in the Tool Table\n"
  247. "by first selecting a row(s) in the Tool Table.")
  248. )
  249. self.grid3.addWidget(self.deltool_btn, 9, 0, 1, 2)
  250. self.grid3.addWidget(QtWidgets.QLabel(''), 10, 0, 1, 2)
  251. separator_line = QtWidgets.QFrame()
  252. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  253. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  254. self.grid3.addWidget(separator_line, 11, 0, 1, 2)
  255. self.tool_data_label = QtWidgets.QLabel(
  256. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), int(1)))
  257. self.tool_data_label.setToolTip(
  258. _(
  259. "The data used for creating GCode.\n"
  260. "Each tool store it's own set of such data."
  261. )
  262. )
  263. self.grid3.addWidget(self.tool_data_label, 12, 0, 1, 2)
  264. grid4 = QtWidgets.QGridLayout()
  265. grid4.setColumnStretch(0, 0)
  266. grid4.setColumnStretch(1, 1)
  267. self.tools_box.addLayout(grid4)
  268. # Overlap
  269. ovlabel = QtWidgets.QLabel('%s:' % _('Overlap'))
  270. ovlabel.setToolTip(
  271. _("How much (percentage) of the tool width to overlap each tool pass.\n"
  272. "Adjust the value starting with lower values\n"
  273. "and increasing it if areas that should be painted are still \n"
  274. "not painted.\n"
  275. "Lower values = faster processing, faster execution on CNC.\n"
  276. "Higher values = slow processing and slow execution on CNC\n"
  277. "due of too many paths.")
  278. )
  279. self.paintoverlap_entry = FCDoubleSpinner(callback=self.confirmation_message, suffix='%')
  280. self.paintoverlap_entry.set_precision(3)
  281. self.paintoverlap_entry.setWrapping(True)
  282. self.paintoverlap_entry.setRange(0.0000, 99.9999)
  283. self.paintoverlap_entry.setSingleStep(0.1)
  284. self.paintoverlap_entry.setObjectName('p_overlap')
  285. grid4.addWidget(ovlabel, 1, 0)
  286. grid4.addWidget(self.paintoverlap_entry, 1, 1)
  287. # Margin
  288. marginlabel = QtWidgets.QLabel('%s:' % _('Margin'))
  289. marginlabel.setToolTip(
  290. _("Distance by which to avoid\n"
  291. "the edges of the polygon to\n"
  292. "be painted.")
  293. )
  294. self.paintmargin_entry = FCDoubleSpinner(callback=self.confirmation_message)
  295. self.paintmargin_entry.set_precision(self.decimals)
  296. self.paintmargin_entry.set_range(-9999.9999, 9999.9999)
  297. self.paintmargin_entry.setObjectName('p_margin')
  298. grid4.addWidget(marginlabel, 2, 0)
  299. grid4.addWidget(self.paintmargin_entry, 2, 1)
  300. # Method
  301. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  302. methodlabel.setToolTip(
  303. _("Algorithm for painting:\n"
  304. "- Standard: Fixed step inwards.\n"
  305. "- Seed-based: Outwards from seed.\n"
  306. "- Line-based: Parallel lines.\n"
  307. "- Laser-lines: Active only for Gerber objects.\n"
  308. "Will create lines that follow the traces.\n"
  309. "- Combo: In case of failure a new method will be picked from the above\n"
  310. "in the order specified.")
  311. )
  312. # self.paintmethod_combo = RadioSet([
  313. # {"label": _("Standard"), "value": "standard"},
  314. # {"label": _("Seed-based"), "value": _("Seed")},
  315. # {"label": _("Straight lines"), "value": _("Lines")},
  316. # {"label": _("Laser lines"), "value": _("Laser_lines")},
  317. # {"label": _("Combo"), "value": _("Combo")}
  318. # ], orientation='vertical', stretch=False)
  319. # for choice in self.paintmethod_combo.choices:
  320. # if choice['value'] == _("Laser_lines"):
  321. # choice["radio"].setEnabled(False)
  322. self.paintmethod_combo = FCComboBox()
  323. self.paintmethod_combo.addItems(
  324. [_("Standard"), _("Seed"), _("Lines"), _("Laser_lines"), _("Combo")]
  325. )
  326. idx = self.paintmethod_combo.findText(_("Laser_lines"))
  327. self.paintmethod_combo.model().item(idx).setEnabled(False)
  328. self.paintmethod_combo.setObjectName('p_method')
  329. grid4.addWidget(methodlabel, 7, 0)
  330. grid4.addWidget(self.paintmethod_combo, 7, 1)
  331. # Connect lines
  332. self.pathconnect_cb = FCCheckBox('%s' % _("Connect"))
  333. self.pathconnect_cb.setObjectName('p_connect')
  334. self.pathconnect_cb.setToolTip(
  335. _("Draw lines between resulting\n"
  336. "segments to minimize tool lifts.")
  337. )
  338. self.paintcontour_cb = FCCheckBox('%s' % _("Contour"))
  339. self.paintcontour_cb.setObjectName('p_contour')
  340. self.paintcontour_cb.setToolTip(
  341. _("Cut around the perimeter of the polygon\n"
  342. "to trim rough edges.")
  343. )
  344. grid4.addWidget(self.pathconnect_cb, 10, 0)
  345. grid4.addWidget(self.paintcontour_cb, 10, 1)
  346. separator_line = QtWidgets.QFrame()
  347. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  348. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  349. grid4.addWidget(separator_line, 11, 0, 1, 2)
  350. self.apply_param_to_all = FCButton(_("Apply parameters to all tools"))
  351. self.apply_param_to_all.setToolTip(
  352. _("The parameters in the current form will be applied\n"
  353. "on all the tools from the Tool Table.")
  354. )
  355. grid4.addWidget(self.apply_param_to_all, 12, 0, 1, 2)
  356. separator_line = QtWidgets.QFrame()
  357. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  358. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  359. grid4.addWidget(separator_line, 13, 0, 1, 2)
  360. # General Parameters
  361. self.gen_param_label = QtWidgets.QLabel('<b>%s</b>' % _("Common Parameters"))
  362. self.gen_param_label.setToolTip(
  363. _("Parameters that are common for all tools.")
  364. )
  365. grid4.addWidget(self.gen_param_label, 15, 0, 1, 2)
  366. self.rest_cb = FCCheckBox('%s' % _("Rest Machining"))
  367. self.rest_cb.setObjectName('p_rest_machining')
  368. self.rest_cb.setToolTip(
  369. _("If checked, use 'rest machining'.\n"
  370. "Basically it will clear copper outside PCB features,\n"
  371. "using the biggest tool and continue with the next tools,\n"
  372. "from bigger to smaller, to clear areas of copper that\n"
  373. "could not be cleared by previous tool, until there is\n"
  374. "no more copper to clear or there are no more tools.\n\n"
  375. "If not checked, use the standard algorithm.")
  376. )
  377. grid4.addWidget(self.rest_cb, 16, 0, 1, 2)
  378. # Polygon selection
  379. selectlabel = QtWidgets.QLabel('%s:' % _('Selection'))
  380. selectlabel.setToolTip(
  381. _("How to select Polygons to be painted.\n"
  382. "- 'Polygon Selection' - left mouse click to add/remove polygons to be painted.\n"
  383. "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  384. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  385. "- 'All Polygons' - the Paint will start after click.\n"
  386. "- 'Reference Object' - will do non copper clearing within the area\n"
  387. "specified by another object.")
  388. )
  389. # grid3 = QtWidgets.QGridLayout()
  390. # self.selectmethod_combo = RadioSet([
  391. # {"label": _("Polygon Selection"), "value": "single"},
  392. # {"label": _("Area Selection"), "value": "area"},
  393. # {"label": _("All Polygons"), "value": "all"},
  394. # {"label": _("Reference Object"), "value": "ref"}
  395. # ], orientation='vertical', stretch=False)
  396. # self.selectmethod_combo.setObjectName('p_selection')
  397. # self.selectmethod_combo.setToolTip(
  398. # _("How to select Polygons to be painted.\n"
  399. # "- 'Polygon Selection' - left mouse click to add/remove polygons to be painted.\n"
  400. # "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  401. # "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  402. # "- 'All Polygons' - the Paint will start after click.\n"
  403. # "- 'Reference Object' - will do non copper clearing within the area\n"
  404. # "specified by another object.")
  405. # )
  406. self.selectmethod_combo = FCComboBox()
  407. self.selectmethod_combo.addItems(
  408. [_("Polygon Selection"), _("Area Selection"), _("All Polygons"), _("Reference Object")]
  409. )
  410. self.selectmethod_combo.setObjectName('p_selection')
  411. grid4.addWidget(selectlabel, 18, 0)
  412. grid4.addWidget(self.selectmethod_combo, 18, 1)
  413. form1 = QtWidgets.QFormLayout()
  414. grid4.addLayout(form1, 20, 0, 1, 2)
  415. self.box_combo_type_label = QtWidgets.QLabel('%s:' % _("Ref. Type"))
  416. self.box_combo_type_label.setToolTip(
  417. _("The type of FlatCAM object to be used as paint reference.\n"
  418. "It can be Gerber, Excellon or Geometry.")
  419. )
  420. self.box_combo_type = QtWidgets.QComboBox()
  421. self.box_combo_type.addItem(_("Reference Gerber"))
  422. self.box_combo_type.addItem(_("Reference Excellon"))
  423. self.box_combo_type.addItem(_("Reference Geometry"))
  424. form1.addRow(self.box_combo_type_label, self.box_combo_type)
  425. self.box_combo_label = QtWidgets.QLabel('%s:' % _("Ref. Object"))
  426. self.box_combo_label.setToolTip(
  427. _("The FlatCAM object to be used as non copper clearing reference.")
  428. )
  429. self.box_combo = QtWidgets.QComboBox()
  430. self.box_combo.setModel(self.app.collection)
  431. self.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  432. self.box_combo.setCurrentIndex(1)
  433. form1.addRow(self.box_combo_label, self.box_combo)
  434. self.box_combo.hide()
  435. self.box_combo_label.hide()
  436. self.box_combo_type.hide()
  437. self.box_combo_type_label.hide()
  438. # GO Button
  439. self.generate_paint_button = QtWidgets.QPushButton(_('Generate Geometry'))
  440. self.generate_paint_button.setToolTip(
  441. _("- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  442. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  443. "- 'All Polygons' - the Paint will start after click.\n"
  444. "- 'Reference Object' - will do non copper clearing within the area\n"
  445. "specified by another object.")
  446. )
  447. self.generate_paint_button.setStyleSheet("""
  448. QPushButton
  449. {
  450. font-weight: bold;
  451. }
  452. """)
  453. self.tools_box.addWidget(self.generate_paint_button)
  454. self.tools_box.addStretch()
  455. # ## Reset Tool
  456. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  457. self.reset_button.setToolTip(
  458. _("Will reset the tool parameters.")
  459. )
  460. self.reset_button.setStyleSheet("""
  461. QPushButton
  462. {
  463. font-weight: bold;
  464. }
  465. """)
  466. self.tools_box.addWidget(self.reset_button)
  467. # #################################### FINSIHED GUI ###########################
  468. # #############################################################################
  469. # #############################################################################
  470. # ########################## VARIABLES ########################################
  471. # #############################################################################
  472. self.obj_name = ""
  473. self.paint_obj = None
  474. self.bound_obj_name = ""
  475. self.bound_obj = None
  476. self.tooldia_list = list()
  477. self.tooldia = None
  478. self.sel_rect = None
  479. self.o_name = None
  480. self.overlap = None
  481. self.connect = None
  482. self.contour = None
  483. self.select_method = None
  484. self.units = ''
  485. self.paint_tools = dict()
  486. self.tooluid = 0
  487. self.first_click = False
  488. self.cursor_pos = None
  489. self.mouse_is_dragging = False
  490. self.mm = None
  491. self.mp = None
  492. self.mr = None
  493. self.sel_rect = list()
  494. # store here if the grid snapping is active
  495. self.grid_status_memory = False
  496. # dict to store the polygons selected for painting; key is the shape added to be plotted and value is the poly
  497. self.poly_dict = dict()
  498. # store here the default data for Geometry Data
  499. self.default_data = dict()
  500. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  501. self.form_fields = {
  502. "paintoverlap": self.paintoverlap_entry,
  503. "paintmargin": self.paintmargin_entry,
  504. "paintmethod": self.paintmethod_combo,
  505. "pathconnect": self.pathconnect_cb,
  506. "paintcontour": self.paintcontour_cb,
  507. }
  508. self.name2option = {
  509. 'p_overlap': "paintoverlap",
  510. 'p_margin': "paintmargin",
  511. 'p_method': "paintmethod",
  512. 'p_connect': "pathconnect",
  513. 'p_contour': "paintcontour",
  514. }
  515. self.old_tool_dia = None
  516. # #############################################################################
  517. # ################################# Signals ###################################
  518. # #############################################################################
  519. self.addtool_btn.clicked.connect(self.on_tool_add)
  520. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  521. self.deltool_btn.clicked.connect(self.on_tool_delete)
  522. self.tipdia_entry.returnPressed.connect(self.on_calculate_tooldia)
  523. self.tipangle_entry.returnPressed.connect(self.on_calculate_tooldia)
  524. self.cutz_entry.returnPressed.connect(self.on_calculate_tooldia)
  525. # self.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  526. # self.tools_table.itemChanged.connect(self.on_tool_edit)
  527. self.tools_table.clicked.connect(self.on_row_selection_change)
  528. self.generate_paint_button.clicked.connect(self.on_paint_button_click)
  529. self.selectmethod_combo.currentIndexChanged.connect(self.on_selection)
  530. self.order_radio.activated_custom[str].connect(self.on_order_changed)
  531. self.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  532. self.box_combo_type.currentIndexChanged.connect(self.on_combo_box_type)
  533. self.type_obj_combo.activated_custom.connect(self.on_type_obj_changed)
  534. self.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  535. self.reset_button.clicked.connect(self.set_tool_ui)
  536. # #############################################################################
  537. # ###################### Setup CONTEXT MENU ###################################
  538. # #############################################################################
  539. self.tools_table.setupContextMenu()
  540. self.tools_table.addContextMenu(
  541. _("Add"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  542. )
  543. self.tools_table.addContextMenu(
  544. _("Add from DB"), self.on_add_tool_by_key, icon=QtGui.QIcon(self.app.resource_location + "/plus16.png")
  545. )
  546. self.tools_table.addContextMenu(
  547. _("Delete"), lambda:
  548. self.on_tool_delete(rows_to_delete=None, all_tools=None),
  549. icon=QtGui.QIcon(self.app.resource_location + "/delete32.png")
  550. )
  551. def on_type_obj_changed(self, val):
  552. obj_type = 0 if val == 'gerber' else 2
  553. self.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  554. self.obj_combo.setCurrentIndex(0)
  555. idx = self.paintmethod_combo.findText(_("Laser_lines"))
  556. if self.type_obj_combo.get_value().lower() == 'gerber':
  557. self.paintmethod_combo.model().item(idx).setEnabled(True)
  558. else:
  559. self.paintmethod_combo.model().item(idx).setEnabled(False)
  560. if self.paintmethod_combo.get_value() == _("Laser_lines"):
  561. self.paintmethod_combo.set_value(_("Lines"))
  562. def install(self, icon=None, separator=None, **kwargs):
  563. FlatCAMTool.install(self, icon, separator, shortcut='ALT+P', **kwargs)
  564. def run(self, toggle=True):
  565. self.app.report_usage("ToolPaint()")
  566. log.debug("ToolPaint().run() was launched ...")
  567. if toggle:
  568. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  569. if self.app.ui.splitter.sizes()[0] == 0:
  570. self.app.ui.splitter.setSizes([1, 1])
  571. else:
  572. try:
  573. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  574. # if tab is populated with the tool but it does not have the focus, focus on it
  575. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  576. # focus on Tool Tab
  577. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  578. else:
  579. self.app.ui.splitter.setSizes([0, 1])
  580. except AttributeError:
  581. pass
  582. else:
  583. if self.app.ui.splitter.sizes()[0] == 0:
  584. self.app.ui.splitter.setSizes([1, 1])
  585. FlatCAMTool.run(self)
  586. self.set_tool_ui()
  587. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  588. def on_row_selection_change(self):
  589. self.blockSignals(True)
  590. sel_rows = [it.row() for it in self.tools_table.selectedItems()]
  591. # sel_rows = sorted(set(index.row() for index in self.tools_table.selectedIndexes()))
  592. if not sel_rows:
  593. sel_rows = [0]
  594. for current_row in sel_rows:
  595. # populate the form with the data from the tool associated with the row parameter
  596. try:
  597. item = self.tools_table.item(current_row, 3)
  598. if item is None:
  599. return 'fail'
  600. tooluid = int(item.text())
  601. except Exception as e:
  602. log.debug("Tool missing. Add a tool in the Tool Table. %s" % str(e))
  603. return
  604. # update the QLabel that shows for which Tool we have the parameters in the UI form
  605. if len(sel_rows) == 1:
  606. cr = self.tools_table.item(current_row, 0).text()
  607. self.tool_data_label.setText(
  608. "<b>%s: <font color='#0000FF'>%s %s</font></b>" % (_('Parameters for'), _("Tool"), cr)
  609. )
  610. try:
  611. # set the form with data from the newly selected tool
  612. for tooluid_key, tooluid_value in list(self.paint_tools.items()):
  613. if int(tooluid_key) == tooluid:
  614. for key, value in tooluid_value.items():
  615. if key == 'data':
  616. form_value_storage = tooluid_value[key]
  617. self.storage_to_form(form_value_storage)
  618. except Exception as e:
  619. log.debug("ToolPaint ---> update_ui() " + str(e))
  620. else:
  621. self.tool_data_label.setText(
  622. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  623. )
  624. self.blockSignals(False)
  625. def storage_to_form(self, dict_storage):
  626. for form_key in self.form_fields:
  627. for storage_key in dict_storage:
  628. if form_key == storage_key:
  629. try:
  630. self.form_fields[form_key].set_value(dict_storage[form_key])
  631. except Exception:
  632. pass
  633. def form_to_storage(self):
  634. if self.tools_table.rowCount() == 0:
  635. # there is no tool in tool table so we can't save the GUI elements values to storage
  636. return
  637. self.blockSignals(True)
  638. widget_changed = self.sender()
  639. wdg_objname = widget_changed.objectName()
  640. option_changed = self.name2option[wdg_objname]
  641. # row = self.tools_table.currentRow()
  642. rows = sorted(set(index.row() for index in self.tools_table.selectedIndexes()))
  643. for row in rows:
  644. if row < 0:
  645. row = 0
  646. tooluid_item = int(self.tools_table.item(row, 3).text())
  647. for tooluid_key, tooluid_val in self.paint_tools.items():
  648. if int(tooluid_key) == tooluid_item:
  649. new_option_value = self.form_fields[option_changed].get_value()
  650. if option_changed in tooluid_val:
  651. tooluid_val[option_changed] = new_option_value
  652. if option_changed in tooluid_val['data']:
  653. tooluid_val['data'][option_changed] = new_option_value
  654. self.blockSignals(False)
  655. def on_apply_param_to_all_clicked(self):
  656. if self.tools_table.rowCount() == 0:
  657. # there is no tool in tool table so we can't save the GUI elements values to storage
  658. log.debug("NonCopperClear.on_apply_param_to_all_clicked() --> no tool in Tools Table, aborting.")
  659. return
  660. self.blockSignals(True)
  661. row = self.tools_table.currentRow()
  662. if row < 0:
  663. row = 0
  664. tooluid_item = int(self.tools_table.item(row, 3).text())
  665. temp_tool_data = dict()
  666. for tooluid_key, tooluid_val in self.paint_tools.items():
  667. if int(tooluid_key) == tooluid_item:
  668. # this will hold the 'data' key of the self.tools[tool] dictionary that corresponds to
  669. # the current row in the tool table
  670. temp_tool_data = tooluid_val['data']
  671. break
  672. for tooluid_key, tooluid_val in self.paint_tools.items():
  673. tooluid_val['data'] = deepcopy(temp_tool_data)
  674. self.app.inform.emit('[success] %s' % _("Current Tool parameters were applied to all tools."))
  675. self.blockSignals(False)
  676. def on_add_tool_by_key(self):
  677. tool_add_popup = FCInputDialog(title='%s...' % _("New Tool"),
  678. text='%s:' % _('Enter a Tool Diameter'),
  679. min=0.0000, max=99.9999, decimals=4)
  680. tool_add_popup.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/letter_t_32.png'))
  681. val, ok = tool_add_popup.get_value()
  682. if ok:
  683. if float(val) == 0:
  684. self.app.inform.emit('[WARNING_NOTCL] %s' %
  685. _("Please enter a tool diameter with non-zero value, in Float format."))
  686. return
  687. self.on_tool_add(dia=float(val))
  688. else:
  689. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  690. def on_tooltable_cellwidget_change(self):
  691. cw = self.sender()
  692. cw_index = self.tools_table.indexAt(cw.pos())
  693. cw_row = cw_index.row()
  694. cw_col = cw_index.column()
  695. current_uid = int(self.tools_table.item(cw_row, 3).text())
  696. # if the sender is in the column with index 2 then we update the tool_type key
  697. if cw_col == 2:
  698. tt = cw.currentText()
  699. typ = 'Iso' if tt == 'V' else "Rough"
  700. self.paint_tools[current_uid].update({
  701. 'type': typ,
  702. 'tool_type': tt,
  703. })
  704. def on_tool_type(self, val):
  705. if val == 'V':
  706. self.addtool_entry_lbl.setDisabled(True)
  707. self.addtool_entry.setDisabled(True)
  708. self.tipdialabel.show()
  709. self.tipdia_entry.show()
  710. self.tipanglelabel.show()
  711. self.tipangle_entry.show()
  712. self.on_calculate_tooldia()
  713. else:
  714. self.addtool_entry_lbl.setDisabled(False)
  715. self.addtool_entry.setDisabled(False)
  716. self.tipdialabel.hide()
  717. self.tipdia_entry.hide()
  718. self.tipanglelabel.hide()
  719. self.tipangle_entry.hide()
  720. self.addtool_entry.set_value(self.old_tool_dia)
  721. def on_calculate_tooldia(self):
  722. if self.tool_type_radio.get_value() == 'V':
  723. tip_dia = float(self.tipdia_entry.get_value())
  724. tip_angle = float(self.tipangle_entry.get_value()) / 2.0
  725. cut_z = float(self.cutz_entry.get_value())
  726. cut_z = -cut_z if cut_z < 0 else cut_z
  727. # calculated tool diameter so the cut_z parameter is obeyed
  728. tool_dia = tip_dia + (2 * cut_z * math.tan(math.radians(tip_angle)))
  729. # update the default_data so it is used in the ncc_tools dict
  730. self.default_data.update({
  731. "vtipdia": tip_dia,
  732. "vtipangle": (tip_angle * 2),
  733. })
  734. self.addtool_entry.set_value(tool_dia)
  735. return tool_dia
  736. else:
  737. return float(self.addtool_entry.get_value())
  738. def on_selection(self):
  739. if self.selectmethod_combo.get_value() == _("Reference Object"):
  740. self.box_combo.show()
  741. self.box_combo_label.show()
  742. self.box_combo_type.show()
  743. self.box_combo_type_label.show()
  744. else:
  745. self.box_combo.hide()
  746. self.box_combo_label.hide()
  747. self.box_combo_type.hide()
  748. self.box_combo_type_label.hide()
  749. if self.selectmethod_combo.get_value() == _("Polygon Selection"):
  750. # disable rest-machining for single polygon painting
  751. self.rest_cb.set_value(False)
  752. self.rest_cb.setDisabled(True)
  753. if self.selectmethod_combo.get_value() == _("Area Selection"):
  754. # disable rest-machining for single polygon painting
  755. self.rest_cb.set_value(False)
  756. self.rest_cb.setDisabled(True)
  757. else:
  758. self.rest_cb.setDisabled(False)
  759. self.addtool_entry.setDisabled(False)
  760. self.addtool_btn.setDisabled(False)
  761. self.deltool_btn.setDisabled(False)
  762. self.tools_table.setContextMenuPolicy(Qt.ActionsContextMenu)
  763. def on_order_changed(self, order):
  764. if order != 'no':
  765. self.build_ui()
  766. def on_rest_machining_check(self, state):
  767. if state:
  768. self.order_radio.set_value('rev')
  769. self.order_label.setDisabled(True)
  770. self.order_radio.setDisabled(True)
  771. else:
  772. self.order_label.setDisabled(False)
  773. self.order_radio.setDisabled(False)
  774. def set_tool_ui(self):
  775. self.tools_frame.show()
  776. self.reset_fields()
  777. self.old_tool_dia = self.app.defaults["tools_paintnewdia"]
  778. # updated units
  779. self.units = self.app.defaults['units'].upper()
  780. # set the working variables to a known state
  781. self.paint_tools.clear()
  782. self.tooluid = 0
  783. self.default_data.clear()
  784. self.default_data.update({
  785. "name": '_paint',
  786. "plot": self.app.defaults["geometry_plot"],
  787. "cutz": float(self.cutz_entry.get_value()),
  788. "vtipdia": float(self.tipdia_entry.get_value()),
  789. "vtipangle": float(self.tipangle_entry.get_value()),
  790. "travelz": float(self.app.defaults["geometry_travelz"]),
  791. "feedrate": float(self.app.defaults["geometry_feedrate"]),
  792. "feedrate_z": float(self.app.defaults["geometry_feedrate_z"]),
  793. "feedrate_rapid": float(self.app.defaults["geometry_feedrate_rapid"]),
  794. "dwell": self.app.defaults["geometry_dwell"],
  795. "dwelltime": float(self.app.defaults["geometry_dwelltime"]),
  796. "multidepth": self.app.defaults["geometry_multidepth"],
  797. "ppname_g": self.app.defaults["geometry_ppname_g"],
  798. "depthperpass": float(self.app.defaults["geometry_depthperpass"]),
  799. "extracut": self.app.defaults["geometry_extracut"],
  800. "extracut_length": self.app.defaults["geometry_extracut_length"],
  801. "toolchange": self.app.defaults["geometry_toolchange"],
  802. "toolchangez": float(self.app.defaults["geometry_toolchangez"]),
  803. "endz": float(self.app.defaults["geometry_endz"]),
  804. "endxy": self.app.defaults["geometry_endxy"],
  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. # ## Init the GUI interface
  818. self.order_radio.set_value(self.app.defaults["tools_paintorder"])
  819. self.paintmargin_entry.set_value(self.app.defaults["tools_paintmargin"])
  820. self.paintmethod_combo.set_value(self.app.defaults["tools_paintmethod"])
  821. self.selectmethod_combo.set_value(self.app.defaults["tools_selectmethod"])
  822. self.pathconnect_cb.set_value(self.app.defaults["tools_pathconnect"])
  823. self.paintcontour_cb.set_value(self.app.defaults["tools_paintcontour"])
  824. self.paintoverlap_entry.set_value(self.app.defaults["tools_paintoverlap"])
  825. self.cutz_entry.set_value(self.app.defaults["tools_paintcutz"])
  826. self.tool_type_radio.set_value(self.app.defaults["tools_painttool_type"])
  827. self.tipdia_entry.set_value(self.app.defaults["tools_painttipdia"])
  828. self.tipangle_entry.set_value(self.app.defaults["tools_painttipangle"])
  829. self.addtool_entry.set_value(self.app.defaults["tools_paintnewdia"])
  830. self.rest_cb.set_value(self.app.defaults["tools_paintrest"])
  831. self.on_tool_type(val=self.tool_type_radio.get_value())
  832. # make the default object type, "Geometry"
  833. self.type_obj_combo.set_value("geometry")
  834. try:
  835. diameters = [float(self.app.defaults["tools_painttooldia"])]
  836. except (ValueError, TypeError):
  837. diameters = [eval(x) for x in self.app.defaults["tools_painttooldia"].split(",") if x != '']
  838. if not diameters:
  839. log.error("At least one tool diameter needed. Verify in Edit -> Preferences -> TOOLS -> NCC Tools.")
  840. self.build_ui()
  841. # if the Paint Method is "Single" disable the tool table context menu
  842. if self.default_data["selectmethod"] == "single":
  843. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  844. return
  845. # call on self.on_tool_add() counts as an call to self.build_ui()
  846. # through this, we add a initial row / tool in the tool_table
  847. for dia in diameters:
  848. self.on_tool_add(dia, muted=True)
  849. # if the Paint Method is "Single" disable the tool table context menu
  850. if self.default_data["selectmethod"] == "single":
  851. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  852. def build_ui(self):
  853. self.ui_disconnect()
  854. # updated units
  855. self.units = self.app.defaults['units'].upper()
  856. sorted_tools = []
  857. for k, v in self.paint_tools.items():
  858. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  859. order = self.order_radio.get_value()
  860. if order == 'fwd':
  861. sorted_tools.sort(reverse=False)
  862. elif order == 'rev':
  863. sorted_tools.sort(reverse=True)
  864. else:
  865. pass
  866. n = len(sorted_tools)
  867. self.tools_table.setRowCount(n)
  868. tool_id = 0
  869. for tool_sorted in sorted_tools:
  870. for tooluid_key, tooluid_value in self.paint_tools.items():
  871. if float('%.*f' % (self.decimals, tooluid_value['tooldia'])) == tool_sorted:
  872. tool_id += 1
  873. id_item = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  874. id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  875. row_no = tool_id - 1
  876. self.tools_table.setItem(row_no, 0, id_item) # Tool name/id
  877. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  878. # There are no drill bits in MM with more than 2 decimals diameter
  879. # For INCH the decimals should be no more than 4. There are no drills under 10mils
  880. dia = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, tooluid_value['tooldia']))
  881. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  882. tool_type_item = QtWidgets.QComboBox()
  883. for item in self.tool_type_item_options:
  884. tool_type_item.addItem(item)
  885. # tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  886. idx = tool_type_item.findText(tooluid_value['tool_type'])
  887. tool_type_item.setCurrentIndex(idx)
  888. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  889. self.tools_table.setItem(row_no, 1, dia) # Diameter
  890. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  891. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  892. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  893. # make the diameter column editable
  894. for row in range(tool_id):
  895. self.tools_table.item(row, 1).setFlags(
  896. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  897. # all the tools are selected by default
  898. self.tools_table.selectColumn(0)
  899. #
  900. self.tools_table.resizeColumnsToContents()
  901. self.tools_table.resizeRowsToContents()
  902. vertical_header = self.tools_table.verticalHeader()
  903. vertical_header.hide()
  904. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  905. horizontal_header = self.tools_table.horizontalHeader()
  906. horizontal_header.setMinimumSectionSize(10)
  907. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  908. horizontal_header.resizeSection(0, 20)
  909. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  910. # self.tools_table.setSortingEnabled(True)
  911. # sort by tool diameter
  912. # self.tools_table.sortItems(1)
  913. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  914. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  915. self.ui_connect()
  916. def on_combo_box_type(self):
  917. obj_type = self.box_combo_type.currentIndex()
  918. self.box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  919. self.box_combo.setCurrentIndex(0)
  920. def on_tool_add(self, dia=None, muted=None):
  921. self.blockSignals(True)
  922. if dia:
  923. tool_dia = dia
  924. else:
  925. tool_dia = self.on_calculate_tooldia()
  926. if tool_dia is None:
  927. self.build_ui()
  928. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter to add, in Float format."))
  929. return
  930. # construct a list of all 'tooluid' in the self.tools
  931. tool_uid_list = []
  932. for tooluid_key in self.paint_tools:
  933. tool_uid_item = int(tooluid_key)
  934. tool_uid_list.append(tool_uid_item)
  935. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  936. if not tool_uid_list:
  937. max_uid = 0
  938. else:
  939. max_uid = max(tool_uid_list)
  940. self.tooluid = int(max_uid + 1)
  941. tool_dias = []
  942. for k, v in self.paint_tools.items():
  943. for tool_v in v.keys():
  944. if tool_v == 'tooldia':
  945. tool_dias.append(float('%.*f' % (self.decimals, v[tool_v])))
  946. if float('%.*f' % (self.decimals, tool_dia)) in tool_dias:
  947. if muted is None:
  948. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Adding tool cancelled. Tool already in Tool Table."))
  949. self.tools_table.itemChanged.connect(self.on_tool_edit)
  950. return
  951. else:
  952. if muted is None:
  953. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  954. self.paint_tools.update({
  955. int(self.tooluid): {
  956. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  957. 'offset': 'Path',
  958. 'offset_value': 0.0,
  959. 'type': 'Iso',
  960. 'tool_type': self.tool_type_radio.get_value(),
  961. 'data': dict(self.default_data),
  962. 'solid_geometry': []
  963. }
  964. })
  965. self.blockSignals(False)
  966. self.build_ui()
  967. def on_tool_edit(self):
  968. self.blockSignals(True)
  969. old_tool_dia = ''
  970. tool_dias = []
  971. for k, v in self.paint_tools.items():
  972. for tool_v in v.keys():
  973. if tool_v == 'tooldia':
  974. tool_dias.append(float('%.*f' % (self.decimals, v[tool_v])))
  975. for row in range(self.tools_table.rowCount()):
  976. try:
  977. new_tool_dia = float(self.tools_table.item(row, 1).text())
  978. except ValueError:
  979. # try to convert comma to decimal point. if it's still not working error message and return
  980. try:
  981. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  982. except ValueError:
  983. self.app.inform.emit('[ERROR_NOTCL] %s' %
  984. _("Wrong value format entered, use a number."))
  985. return
  986. tooluid = int(self.tools_table.item(row, 3).text())
  987. # identify the tool that was edited and get it's tooluid
  988. if new_tool_dia not in tool_dias:
  989. self.paint_tools[tooluid]['tooldia'] = new_tool_dia
  990. self.app.inform.emit('[success] %s' %
  991. _("Tool from Tool Table was edited."))
  992. self.build_ui()
  993. return
  994. else:
  995. # identify the old tool_dia and restore the text in tool table
  996. for k, v in self.paint_tools.items():
  997. if k == tooluid:
  998. old_tool_dia = v['tooldia']
  999. break
  1000. restore_dia_item = self.tools_table.item(row, 1)
  1001. restore_dia_item.setText(str(old_tool_dia))
  1002. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1003. _("Edit cancelled. New diameter value is already in the Tool Table."))
  1004. self.blockSignals(False)
  1005. self.build_ui()
  1006. # def on_tool_copy(self, all=None):
  1007. # try:
  1008. # self.tools_table.itemChanged.disconnect()
  1009. # except:
  1010. # pass
  1011. #
  1012. # # find the tool_uid maximum value in the self.tools
  1013. # uid_list = []
  1014. # for key in self.paint_tools:
  1015. # uid_list.append(int(key))
  1016. # try:
  1017. # max_uid = max(uid_list, key=int)
  1018. # except ValueError:
  1019. # max_uid = 0
  1020. #
  1021. # if all is None:
  1022. # if self.tools_table.selectedItems():
  1023. # for current_row in self.tools_table.selectedItems():
  1024. # # sometime the header get selected and it has row number -1
  1025. # # we don't want to do anything with the header :)
  1026. # if current_row.row() < 0:
  1027. # continue
  1028. # try:
  1029. # tooluid_copy = int(self.tools_table.item(current_row.row(), 3).text())
  1030. # max_uid += 1
  1031. # self.paint_tools[int(max_uid)] = dict(self.paint_tools[tooluid_copy])
  1032. # for td in self.paint_tools:
  1033. # print("COPIED", self.paint_tools[td])
  1034. # self.build_ui()
  1035. # except AttributeError:
  1036. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  1037. # self.build_ui()
  1038. # return
  1039. # except Exception as e:
  1040. # log.debug("on_tool_copy() --> " + str(e))
  1041. # # deselect the table
  1042. # # self.ui.geo_tools_table.clearSelection()
  1043. # else:
  1044. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  1045. # self.build_ui()
  1046. # return
  1047. # else:
  1048. # # we copy all tools in geo_tools_table
  1049. # try:
  1050. # temp_tools = dict(self.paint_tools)
  1051. # max_uid += 1
  1052. # for tooluid in temp_tools:
  1053. # self.paint_tools[int(max_uid)] = dict(temp_tools[tooluid])
  1054. # temp_tools.clear()
  1055. # self.build_ui()
  1056. # except Exception as e:
  1057. # log.debug("on_tool_copy() --> " + str(e))
  1058. #
  1059. # self.app.inform.emit("[success] Tool was copied in the Tool Table.")
  1060. def on_tool_delete(self, rows_to_delete=None, all_tools=None):
  1061. self.blockSignals(True)
  1062. deleted_tools_list = []
  1063. if all_tools:
  1064. self.paint_tools.clear()
  1065. self.blockSignals(False)
  1066. self.build_ui()
  1067. return
  1068. if rows_to_delete:
  1069. try:
  1070. for row in rows_to_delete:
  1071. tooluid_del = int(self.tools_table.item(row, 3).text())
  1072. deleted_tools_list.append(tooluid_del)
  1073. except TypeError:
  1074. deleted_tools_list.append(rows_to_delete)
  1075. for t in deleted_tools_list:
  1076. self.paint_tools.pop(t, None)
  1077. self.blockSignals(False)
  1078. self.build_ui()
  1079. return
  1080. try:
  1081. if self.tools_table.selectedItems():
  1082. for row_sel in self.tools_table.selectedItems():
  1083. row = row_sel.row()
  1084. if row < 0:
  1085. continue
  1086. tooluid_del = int(self.tools_table.item(row, 3).text())
  1087. deleted_tools_list.append(tooluid_del)
  1088. for t in deleted_tools_list:
  1089. self.paint_tools.pop(t, None)
  1090. except AttributeError:
  1091. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Delete failed. Select a tool to delete."))
  1092. self.blockSignals(False)
  1093. return
  1094. except Exception as e:
  1095. log.debug(str(e))
  1096. self.app.inform.emit('[success] %s' % _("Tool(s) deleted from Tool Table."))
  1097. self.blockSignals(False)
  1098. self.build_ui()
  1099. def on_paint_button_click(self):
  1100. # init values for the next usage
  1101. self.reset_usage()
  1102. self.app.report_usage("on_paint_button_click")
  1103. # self.app.call_source = 'paint'
  1104. # #####################################################
  1105. # ######### Reading Parameters ########################
  1106. # #####################################################
  1107. self.app.inform.emit(_("Paint Tool. Reading parameters."))
  1108. self.overlap = float(self.paintoverlap_entry.get_value()) / 100.0
  1109. self.connect = self.pathconnect_cb.get_value()
  1110. self.contour = self.paintcontour_cb.get_value()
  1111. self.select_method = self.selectmethod_combo.get_value()
  1112. self.obj_name = self.obj_combo.currentText()
  1113. # Get source object.
  1114. try:
  1115. self.paint_obj = self.app.collection.get_by_name(str(self.obj_name))
  1116. except Exception as e:
  1117. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  1118. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object: %s"), self.obj_name))
  1119. return
  1120. if self.paint_obj is None:
  1121. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), self.paint_obj))
  1122. return
  1123. # test if the Geometry Object is multigeo and return Fail if True because
  1124. # for now Paint don't work on MultiGeo
  1125. if self.paint_obj.multigeo is True:
  1126. self.app.inform.emit('[ERROR_NOTCL] %s...' % _("Can't do Paint on MultiGeo geometries"))
  1127. return 'Fail'
  1128. self.o_name = '%s_mt_paint' % self.obj_name
  1129. # use the selected tools in the tool table; get diameters
  1130. self.tooldia_list = list()
  1131. if self.tools_table.selectedItems():
  1132. for x in self.tools_table.selectedItems():
  1133. try:
  1134. self.tooldia = float(self.tools_table.item(x.row(), 1).text())
  1135. except ValueError:
  1136. # try to convert comma to decimal point. if it's still not working error message and return
  1137. try:
  1138. self.tooldia = float(self.tools_table.item(x.row(), 1).text().replace(',', '.'))
  1139. except ValueError:
  1140. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1141. continue
  1142. self.tooldia_list.append(self.tooldia)
  1143. else:
  1144. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No selected tools in Tool Table."))
  1145. return
  1146. if self.select_method == _("All Polygons"):
  1147. self.paint_poly_all(self.paint_obj,
  1148. tooldia=self.tooldia_list,
  1149. outname=self.o_name,
  1150. overlap=self.overlap,
  1151. connect=self.connect,
  1152. contour=self.contour)
  1153. elif self.select_method == _("Polygon Selection"):
  1154. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click on a polygon to paint it."))
  1155. # disengage the grid snapping since it may be hard to click on polygons with grid snapping on
  1156. if self.app.ui.grid_snap_btn.isChecked():
  1157. self.grid_status_memory = True
  1158. self.app.ui.grid_snap_btn.trigger()
  1159. else:
  1160. self.grid_status_memory = False
  1161. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_single_poly_mouse_release)
  1162. if self.app.is_legacy is False:
  1163. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1164. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1165. else:
  1166. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  1167. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  1168. elif self.select_method == _("Area Selection"):
  1169. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the paint area."))
  1170. if self.app.is_legacy is False:
  1171. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1172. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1173. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1174. else:
  1175. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  1176. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  1177. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  1178. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  1179. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  1180. elif self.select_method == _("Reference Object"):
  1181. self.bound_obj_name = self.box_combo.currentText()
  1182. # Get source object.
  1183. try:
  1184. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  1185. except Exception:
  1186. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.obj_name))
  1187. return "Could not retrieve object: %s" % self.obj_name
  1188. self.paint_poly_ref(obj=self.paint_obj,
  1189. sel_obj=self.bound_obj,
  1190. tooldia=self.tooldia_list,
  1191. overlap=self.overlap,
  1192. outname=self.o_name,
  1193. connect=self.connect,
  1194. contour=self.contour)
  1195. # To be called after clicking on the plot.
  1196. def on_single_poly_mouse_release(self, event):
  1197. if self.app.is_legacy is False:
  1198. event_pos = event.pos
  1199. right_button = 2
  1200. event_is_dragging = self.app.event_is_dragging
  1201. else:
  1202. event_pos = (event.xdata, event.ydata)
  1203. right_button = 3
  1204. event_is_dragging = self.app.ui.popMenu.mouse_is_panning
  1205. try:
  1206. x = float(event_pos[0])
  1207. y = float(event_pos[1])
  1208. except TypeError:
  1209. return
  1210. event_pos = (x, y)
  1211. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  1212. # do paint single only for left mouse clicks
  1213. if event.button == 1:
  1214. clicked_poly = self.find_polygon(point=(curr_pos[0], curr_pos[1]), geoset=self.paint_obj.solid_geometry)
  1215. if clicked_poly:
  1216. if clicked_poly not in self.poly_dict.values():
  1217. shape_id = self.app.tool_shapes.add(tolerance=self.paint_obj.drawing_tolerance,
  1218. layer=0,
  1219. shape=clicked_poly,
  1220. color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1221. face_color=self.app.defaults['global_sel_draw_color'] + 'AF',
  1222. visible=True)
  1223. self.poly_dict[shape_id] = clicked_poly
  1224. self.app.inform.emit(
  1225. '%s: %d. %s' % (_("Added polygon"),
  1226. int(len(self.poly_dict)),
  1227. _("Click to add next polygon or right click to start painting."))
  1228. )
  1229. else:
  1230. try:
  1231. for k, v in list(self.poly_dict.items()):
  1232. if v == clicked_poly:
  1233. self.app.tool_shapes.remove(k)
  1234. self.poly_dict.pop(k)
  1235. break
  1236. except TypeError:
  1237. return
  1238. self.app.inform.emit(
  1239. '%s. %s' % (_("Removed polygon"),
  1240. _("Click to add/remove next polygon or right click to start painting."))
  1241. )
  1242. self.app.tool_shapes.redraw()
  1243. else:
  1244. self.app.inform.emit(_("No polygon detected under click position."))
  1245. elif event.button == right_button and event_is_dragging is False:
  1246. # restore the Grid snapping if it was active before
  1247. if self.grid_status_memory is True:
  1248. self.app.ui.grid_snap_btn.trigger()
  1249. if self.app.is_legacy is False:
  1250. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_single_poly_mouse_release)
  1251. else:
  1252. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1253. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1254. self.app.on_mouse_click_over_plot)
  1255. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1256. self.app.on_mouse_click_release_over_plot)
  1257. self.app.tool_shapes.clear(update=True)
  1258. if self.poly_dict:
  1259. poly_list = deepcopy(list(self.poly_dict.values()))
  1260. self.paint_poly(self.paint_obj,
  1261. inside_pt=(curr_pos[0], curr_pos[1]),
  1262. poly_list=poly_list,
  1263. tooldia=self.tooldia_list,
  1264. overlap=self.overlap,
  1265. connect=self.connect,
  1266. contour=self.contour)
  1267. self.poly_dict.clear()
  1268. else:
  1269. self.app.inform.emit('[ERROR_NOTCL] %s' % _("List of single polygons is empty. Aborting."))
  1270. # To be called after clicking on the plot.
  1271. def on_mouse_release(self, event):
  1272. if self.app.is_legacy is False:
  1273. event_pos = event.pos
  1274. event_is_dragging = event.is_dragging
  1275. right_button = 2
  1276. else:
  1277. event_pos = (event.xdata, event.ydata)
  1278. event_is_dragging = self.app.plotcanvas.is_dragging
  1279. right_button = 3
  1280. try:
  1281. x = float(event_pos[0])
  1282. y = float(event_pos[1])
  1283. except TypeError:
  1284. return
  1285. event_pos = (x, y)
  1286. # do paint single only for left mouse clicks
  1287. if event.button == 1:
  1288. if not self.first_click:
  1289. self.first_click = True
  1290. self.app.inform.emit('[WARNING_NOTCL] %s' %
  1291. _("Click the end point of the paint area."))
  1292. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  1293. if self.app.grid_status():
  1294. self.cursor_pos = self.app.geo_editor.snap(self.cursor_pos[0], self.cursor_pos[1])
  1295. else:
  1296. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  1297. self.app.delete_selection_shape()
  1298. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  1299. if self.app.grid_status():
  1300. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1301. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  1302. x1, y1 = curr_pos[0], curr_pos[1]
  1303. pt1 = (x0, y0)
  1304. pt2 = (x1, y0)
  1305. pt3 = (x1, y1)
  1306. pt4 = (x0, y1)
  1307. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  1308. self.sel_rect.append(new_rectangle)
  1309. # add a temporary shape on canvas
  1310. self.draw_tool_selection_shape(old_coords=(x0, y0), coords=(x1, y1))
  1311. self.first_click = False
  1312. return
  1313. elif event.button == right_button and self.mouse_is_dragging is False:
  1314. self.first_click = False
  1315. self.delete_tool_selection_shape()
  1316. if self.app.is_legacy is False:
  1317. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1318. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1319. else:
  1320. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1321. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1322. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1323. self.app.on_mouse_click_over_plot)
  1324. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1325. self.app.on_mouse_move_over_plot)
  1326. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1327. self.app.on_mouse_click_release_over_plot)
  1328. if len(self.sel_rect) == 0:
  1329. return
  1330. self.sel_rect = cascaded_union(self.sel_rect)
  1331. self.paint_poly_area(obj=self.paint_obj,
  1332. tooldia=self.tooldia_list,
  1333. sel_obj=self.sel_rect,
  1334. outname=self.o_name,
  1335. overlap=self.overlap,
  1336. connect=self.connect,
  1337. contour=self.contour)
  1338. # called on mouse move
  1339. def on_mouse_move(self, event):
  1340. if self.app.is_legacy is False:
  1341. event_pos = event.pos
  1342. event_is_dragging = event.is_dragging
  1343. right_button = 2
  1344. else:
  1345. event_pos = (event.xdata, event.ydata)
  1346. event_is_dragging = self.app.plotcanvas.is_dragging
  1347. right_button = 3
  1348. try:
  1349. x = float(event_pos[0])
  1350. y = float(event_pos[1])
  1351. except TypeError:
  1352. return
  1353. curr_pos = self.app.plotcanvas.translate_coords((x, y))
  1354. # detect mouse dragging motion
  1355. if event_is_dragging == 1:
  1356. self.mouse_is_dragging = True
  1357. else:
  1358. self.mouse_is_dragging = False
  1359. # update the cursor position
  1360. if self.app.grid_status():
  1361. # Update cursor
  1362. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1363. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1364. symbol='++', edge_color=self.app.cursor_color_3D,
  1365. edge_width=self.app.defaults["global_cursor_width"],
  1366. size=self.app.defaults["global_cursor_size"])
  1367. # update the positions on status bar
  1368. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  1369. "<b>Y</b>: %.4f" % (curr_pos[0], curr_pos[1]))
  1370. if self.cursor_pos is None:
  1371. self.cursor_pos = (0, 0)
  1372. dx = curr_pos[0] - float(self.cursor_pos[0])
  1373. dy = curr_pos[1] - float(self.cursor_pos[1])
  1374. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1375. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  1376. # draw the utility geometry
  1377. if self.first_click:
  1378. self.app.delete_selection_shape()
  1379. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  1380. coords=(curr_pos[0], curr_pos[1]))
  1381. def paint_poly(self, obj, inside_pt=None, poly_list=None, tooldia=None, overlap=None, order=None,
  1382. margin=None, method=None, outname=None, connect=None, contour=None, tools_storage=None,
  1383. plot=True, run_threaded=True):
  1384. """
  1385. Paints a polygon selected by clicking on its interior or by having a point coordinates given
  1386. Note:
  1387. * The margin is taken directly from the form.
  1388. :param run_threaded:
  1389. :param plot:
  1390. :param poly_list:
  1391. :param obj: painted object
  1392. :param inside_pt: [x, y]
  1393. :param tooldia: Diameter of the painting tool
  1394. :param overlap: Overlap of the tool between passes.
  1395. :param order: if the tools are ordered and how
  1396. :param margin: a border around painting area
  1397. :param outname: Name of the resulting Geometry Object.
  1398. :param connect: Connect lines to avoid tool lifts.
  1399. :param contour: Paint around the edges.
  1400. :param method: choice out of _("Seed"), 'normal', 'lines'
  1401. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1402. Usage of the different one is related to when this function is called from a TcL command.
  1403. :return: None
  1404. """
  1405. if isinstance(obj, FlatCAMGerber):
  1406. if self.app.defaults["gerber_buffering"] == 'no':
  1407. self.app.inform.emit('%s %s %s' %
  1408. (_("Paint Tool."), _("Normal painting polygon task started."),
  1409. _("Buffering geometry...")))
  1410. else:
  1411. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Normal painting polygon task started.")))
  1412. else:
  1413. self.app.inform.emit('%s %s' % (_("Paint Tool."), _("Normal painting polygon task started.")))
  1414. if isinstance(obj, FlatCAMGerber):
  1415. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1416. if isinstance(obj.solid_geometry, list):
  1417. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1418. else:
  1419. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1420. polygon_list = None
  1421. if inside_pt and poly_list is None:
  1422. polygon_list = [self.find_polygon(point=inside_pt, geoset=obj.solid_geometry)]
  1423. elif (inside_pt is None and poly_list) or (inside_pt and poly_list):
  1424. polygon_list = poly_list
  1425. # No polygon?
  1426. if polygon_list is None:
  1427. self.app.log.warning('No polygon found.')
  1428. self.app.inform.emit('[WARNING] %s' % _('No polygon found.'))
  1429. return
  1430. paint_method = method if method is not None else self.paintmethod_combo.get_value()
  1431. paint_margin = float(self.paintmargin_entry.get_value()) if margin is None else margin
  1432. # determine if to use the progressive plotting
  1433. prog_plot = True if self.app.defaults["tools_paint_plotting"] == 'progressive' else False
  1434. name = outname if outname is not None else self.obj_name + "_paint"
  1435. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"]) / 100.0
  1436. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1437. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1438. order = order if order is not None else self.order_radio.get_value()
  1439. tools_storage = self.paint_tools if tools_storage is None else tools_storage
  1440. sorted_tools = []
  1441. if tooldia is not None:
  1442. try:
  1443. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1444. except AttributeError:
  1445. if not isinstance(tooldia, list):
  1446. sorted_tools = [float(tooldia)]
  1447. else:
  1448. sorted_tools = tooldia
  1449. else:
  1450. for row in range(self.tools_table.rowCount()):
  1451. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1452. # sort the tools if we have an order selected in the UI
  1453. if order == 'fwd':
  1454. sorted_tools.sort(reverse=False)
  1455. elif order == 'rev':
  1456. sorted_tools.sort(reverse=True)
  1457. proc = self.app.proc_container.new(_("Painting polygon..."))
  1458. # Initializes the new geometry object
  1459. def gen_paintarea(geo_obj, app_obj):
  1460. geo_obj.solid_geometry = list()
  1461. def paint_p(polyg, tooldiameter):
  1462. cpoly = None
  1463. try:
  1464. if paint_method == _("Standard"):
  1465. # Type(cp) == FlatCAMRTreeStorage | None
  1466. cpoly = self.clear_polygon(polyg,
  1467. tooldia=tooldiameter,
  1468. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1469. overlap=over,
  1470. contour=cont,
  1471. connect=conn,
  1472. prog_plot=prog_plot)
  1473. elif paint_method == _("Seed"):
  1474. # Type(cp) == FlatCAMRTreeStorage | None
  1475. cpoly = self.clear_polygon2(polyg,
  1476. tooldia=tooldiameter,
  1477. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1478. overlap=over,
  1479. contour=cont,
  1480. connect=conn,
  1481. prog_plot=prog_plot)
  1482. elif paint_method == _("Lines"):
  1483. # Type(cp) == FlatCAMRTreeStorage | None
  1484. cpoly = self.clear_polygon3(polyg,
  1485. tooldia=tooldiameter,
  1486. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1487. overlap=over,
  1488. contour=cont,
  1489. connect=conn,
  1490. prog_plot=prog_plot)
  1491. elif paint_method == _("Laser_lines"):
  1492. # line = None
  1493. # aperture_size = None
  1494. # the key is the aperture type and the val is a list of geo elements
  1495. flash_el_dict = dict()
  1496. # the key is the aperture size, the val is a list of geo elements
  1497. traces_el_dict = dict()
  1498. # find the flashes and the lines that are in the selected polygon and store them separately
  1499. for apid, apval in obj.apertures.items():
  1500. for geo_el in apval['geometry']:
  1501. if apval["size"] == 0.0:
  1502. if apval["size"] in traces_el_dict:
  1503. traces_el_dict[apval["size"]].append(geo_el)
  1504. else:
  1505. traces_el_dict[apval["size"]] = [geo_el]
  1506. if 'follow' in geo_el and geo_el['follow'].within(polyg):
  1507. if isinstance(geo_el['follow'], Point):
  1508. if apval["type"] == 'C':
  1509. if 'C' in flash_el_dict:
  1510. flash_el_dict['C'].append(geo_el)
  1511. else:
  1512. flash_el_dict['C'] = [geo_el]
  1513. elif apval["type"] == 'O':
  1514. if 'O' in flash_el_dict:
  1515. flash_el_dict['O'].append(geo_el)
  1516. else:
  1517. flash_el_dict['O'] = [geo_el]
  1518. elif apval["type"] == 'R':
  1519. if 'R' in flash_el_dict:
  1520. flash_el_dict['R'].append(geo_el)
  1521. else:
  1522. flash_el_dict['R'] = [geo_el]
  1523. else:
  1524. aperture_size = apval['size']
  1525. if aperture_size in traces_el_dict:
  1526. traces_el_dict[aperture_size].append(geo_el)
  1527. else:
  1528. traces_el_dict[aperture_size] = [geo_el]
  1529. cpoly = FlatCAMRTreeStorage()
  1530. pads_lines_list = list()
  1531. # process the flashes found in the selected polygon with the 'lines' method for rectangular
  1532. # flashes and with _("Seed") for oblong and circular flashes
  1533. # and pads (flahes) need the contour therefore I override the GUI settings with always True
  1534. for ap_type in flash_el_dict:
  1535. for elem in flash_el_dict[ap_type]:
  1536. if 'solid' in elem:
  1537. if ap_type == 'C':
  1538. f_o = self.clear_polygon2(elem['solid'],
  1539. tooldia=tooldiameter,
  1540. steps_per_circle=self.app.defaults[
  1541. "geometry_circle_steps"],
  1542. overlap=over,
  1543. contour=True,
  1544. connect=conn,
  1545. prog_plot=prog_plot)
  1546. pads_lines_list += [p for p in f_o.get_objects() if p]
  1547. elif ap_type == 'O':
  1548. f_o = self.clear_polygon2(elem['solid'],
  1549. tooldia=tooldiameter,
  1550. steps_per_circle=self.app.defaults[
  1551. "geometry_circle_steps"],
  1552. overlap=over,
  1553. contour=True,
  1554. connect=conn,
  1555. prog_plot=prog_plot)
  1556. pads_lines_list += [p for p in f_o.get_objects() if p]
  1557. elif ap_type == 'R':
  1558. f_o = self.clear_polygon3(elem['solid'],
  1559. tooldia=tooldiameter,
  1560. steps_per_circle=self.app.defaults[
  1561. "geometry_circle_steps"],
  1562. overlap=over,
  1563. contour=True,
  1564. connect=conn,
  1565. prog_plot=prog_plot)
  1566. pads_lines_list += [p for p in f_o.get_objects() if p]
  1567. # add the lines from pads to the storage
  1568. try:
  1569. for lin in pads_lines_list:
  1570. if lin:
  1571. cpoly.insert(lin)
  1572. except TypeError:
  1573. cpoly.insert(pads_lines_list)
  1574. copper_lines_list = list()
  1575. # process the traces found in the selected polygon using the 'laser_lines' method,
  1576. # method which will follow the 'follow' line therefore use the longer path possible for the
  1577. # laser, therefore the acceleration will play a smaller factor
  1578. for aperture_size in traces_el_dict:
  1579. for elem in traces_el_dict[aperture_size]:
  1580. line = elem['follow']
  1581. if line:
  1582. t_o = self.fill_with_lines(line, aperture_size,
  1583. tooldia=tooldiameter,
  1584. steps_per_circle=self.app.defaults[
  1585. "geometry_circle_steps"],
  1586. overlap=over,
  1587. contour=cont,
  1588. connect=conn,
  1589. prog_plot=prog_plot)
  1590. copper_lines_list += [p for p in t_o.get_objects() if p]
  1591. # add the lines from copper features to storage but first try to make as few lines as possible
  1592. # by trying to fuse them
  1593. lines_union = linemerge(unary_union(copper_lines_list))
  1594. try:
  1595. for lin in lines_union:
  1596. if lin:
  1597. cpoly.insert(lin)
  1598. except TypeError:
  1599. cpoly.insert(lines_union)
  1600. # # determine the Gerber follow line
  1601. # for apid, apval in obj.apertures.items():
  1602. # for geo_el in apval['geometry']:
  1603. # if 'solid' in geo_el:
  1604. # if Point(inside_pt).within(geo_el['solid']):
  1605. # if not isinstance(geo_el['follow'], Point):
  1606. # line = geo_el['follow']
  1607. #
  1608. # if apval['type'] == 'C':
  1609. # aperture_size = apval['size']
  1610. # else:
  1611. # if apval['width'] > apval['height']:
  1612. # aperture_size = apval['height']
  1613. # else:
  1614. # aperture_size = apval['width']
  1615. #
  1616. # if line:
  1617. # cpoly = self.fill_with_lines(line, aperture_size,
  1618. # tooldia=tooldiameter,
  1619. # steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1620. # overlap=over,
  1621. # contour=cont,
  1622. # connect=conn,
  1623. # prog_plot=prog_plot)
  1624. elif paint_method == _("Combo"):
  1625. self.app.inform.emit(_("Painting polygon with method: lines."))
  1626. cpoly = self.clear_polygon3(polyg,
  1627. tooldia=tooldiameter,
  1628. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1629. overlap=over,
  1630. contour=cont,
  1631. connect=conn,
  1632. prog_plot=prog_plot)
  1633. if cpoly and cpoly.objects:
  1634. pass
  1635. else:
  1636. self.app.inform.emit(_("Failed. Painting polygon with method: seed."))
  1637. cpoly = self.clear_polygon2(polyg,
  1638. tooldia=tooldiameter,
  1639. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1640. overlap=over,
  1641. contour=cont,
  1642. connect=conn,
  1643. prog_plot=prog_plot)
  1644. if cpoly and cpoly.objects:
  1645. pass
  1646. else:
  1647. self.app.inform.emit(_("Failed. Painting polygon with method: standard."))
  1648. cpoly = self.clear_polygon(polyg,
  1649. tooldia=tooldiameter,
  1650. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1651. overlap=over,
  1652. contour=cont,
  1653. connect=conn,
  1654. prog_plot=prog_plot)
  1655. except FlatCAMApp.GracefulException:
  1656. return "fail"
  1657. except Exception as ee:
  1658. log.debug("ToolPaint.paint_poly().gen_paintarea().paint_p() --> %s" % str(ee))
  1659. if cpoly and cpoly.objects:
  1660. geo_obj.solid_geometry += list(cpoly.get_objects())
  1661. return cpoly
  1662. else:
  1663. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('Geometry could not be painted completely'))
  1664. return None
  1665. current_uid = int(1)
  1666. tool_dia = None
  1667. for tool_dia in sorted_tools:
  1668. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1669. for k, v in tools_storage.items():
  1670. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1671. current_uid = int(k)
  1672. break
  1673. try:
  1674. poly_buf = [pol.buffer(-paint_margin) for pol in polygon_list]
  1675. cp = list()
  1676. try:
  1677. for pp in poly_buf:
  1678. cp.append(paint_p(pp, tooldiameter=tool_dia))
  1679. except TypeError:
  1680. cp = paint_p(poly_buf, tooldiameter=tool_dia)
  1681. total_geometry = list()
  1682. if cp:
  1683. try:
  1684. for x in cp:
  1685. total_geometry += list(x.get_objects())
  1686. except TypeError:
  1687. total_geometry = list(cp.get_objects())
  1688. except FlatCAMApp.GracefulException:
  1689. return "fail"
  1690. except Exception as e:
  1691. log.debug("Could not Paint the polygons. %s" % str(e))
  1692. app_obj.inform.emit('[ERROR] %s\n%s' %
  1693. (_("Could not do Paint. Try a different combination of parameters. "
  1694. "Or a different strategy of paint"),
  1695. str(e)
  1696. )
  1697. )
  1698. return "fail"
  1699. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1700. # dictionary and then reset the temporary list that stored that solid_geometry
  1701. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1702. tools_storage[current_uid]['data']['name'] = name
  1703. # clean the progressive plotted shapes if it was used
  1704. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1705. self.temp_shapes.clear(update=True)
  1706. # delete tools with empty geometry
  1707. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1708. for uid in list(tools_storage.keys()):
  1709. # if the solid_geometry (type=list) is empty
  1710. if not tools_storage[uid]['solid_geometry']:
  1711. tools_storage.pop(uid, None)
  1712. geo_obj.options["cnctooldia"] = str(tool_dia)
  1713. # this will turn on the FlatCAMCNCJob plot for multiple tools
  1714. geo_obj.multigeo = True
  1715. geo_obj.multitool = True
  1716. geo_obj.tools.clear()
  1717. geo_obj.tools = dict(tools_storage)
  1718. geo_obj.solid_geometry = cascaded_union(tools_storage[current_uid]['solid_geometry'])
  1719. try:
  1720. if isinstance(geo_obj.solid_geometry, list):
  1721. a, b, c, d = MultiPolygon(geo_obj.solid_geometry).bounds
  1722. else:
  1723. a, b, c, d = geo_obj.solid_geometry.bounds
  1724. geo_obj.options['xmin'] = a
  1725. geo_obj.options['ymin'] = b
  1726. geo_obj.options['xmax'] = c
  1727. geo_obj.options['ymax'] = d
  1728. except Exception as e:
  1729. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1730. return
  1731. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1732. has_solid_geo = 0
  1733. for tooluid in geo_obj.tools:
  1734. if geo_obj.tools[tooluid]['solid_geometry']:
  1735. has_solid_geo += 1
  1736. if has_solid_geo == 0:
  1737. self.app.inform.emit('[ERROR] %s' %
  1738. _("There is no Painting Geometry in the file.\n"
  1739. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1740. "Change the painting parameters and try again."))
  1741. return
  1742. total_geometry[:] = []
  1743. self.app.inform.emit('[success] %s' % _("Paint Single Done."))
  1744. # Experimental...
  1745. # print("Indexing...", end=' ')
  1746. # geo_obj.make_index()
  1747. # if errors == 0:
  1748. # print("[success] Paint single polygon Done")
  1749. # self.app.inform.emit("[success] Paint single polygon Done")
  1750. # else:
  1751. # print("[WARNING] Paint single polygon done with errors")
  1752. # self.app.inform.emit("[WARNING] Paint single polygon done with errors. "
  1753. # "%d area(s) could not be painted.\n"
  1754. # "Use different paint parameters or edit the paint geometry and correct"
  1755. # "the issue."
  1756. # % errors)
  1757. def job_thread(app_obj):
  1758. try:
  1759. app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  1760. except FlatCAMApp.GracefulException:
  1761. proc.done()
  1762. return
  1763. except Exception as e:
  1764. proc.done()
  1765. self.app.inform.emit('[ERROR_NOTCL] %s --> %s' %
  1766. ('PaintTool.paint_poly()',
  1767. str(e)))
  1768. return
  1769. proc.done()
  1770. # focus on Selected Tab
  1771. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1772. self.app.inform.emit(_("Polygon Paint started ..."))
  1773. # Promise object with the new name
  1774. self.app.collection.promise(name)
  1775. if run_threaded:
  1776. # Background
  1777. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1778. else:
  1779. job_thread(app_obj=self.app)
  1780. def paint_poly_all(self, obj, tooldia=None, overlap=None, order=None, margin=None, method=None, outname=None,
  1781. connect=None, contour=None, tools_storage=None, plot=True, run_threaded=True):
  1782. """
  1783. Paints all polygons in this object.
  1784. :param run_threaded:
  1785. :param plot:
  1786. :param obj: painted object
  1787. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1788. :param overlap: value by which the paths will overlap
  1789. :param order: if the tools are ordered and how
  1790. :param margin: a border around painting area
  1791. :param outname: name of the resulting object
  1792. :param connect: Connect lines to avoid tool lifts.
  1793. :param contour: Paint around the edges.
  1794. :param method: choice out of _("Seed"), 'normal', 'lines'
  1795. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1796. Usage of the different one is related to when this function is called from a TcL command.
  1797. :return:
  1798. """
  1799. paint_method = method if method is not None else self.paintmethod_combo.get_value()
  1800. if margin is not None:
  1801. paint_margin = margin
  1802. else:
  1803. paint_margin = float(self.paintmargin_entry.get_value())
  1804. # determine if to use the progressive plotting
  1805. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1806. prog_plot = True
  1807. else:
  1808. prog_plot = False
  1809. proc = self.app.proc_container.new(_("Painting polygons..."))
  1810. name = outname if outname is not None else self.obj_name + "_paint"
  1811. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"]) / 100.0
  1812. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1813. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1814. order = order if order is not None else self.order_radio.get_value()
  1815. sorted_tools = []
  1816. if tooldia is not None:
  1817. try:
  1818. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1819. except AttributeError:
  1820. if not isinstance(tooldia, list):
  1821. sorted_tools = [float(tooldia)]
  1822. else:
  1823. sorted_tools = tooldia
  1824. else:
  1825. for row in range(self.tools_table.rowCount()):
  1826. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1827. if tools_storage is not None:
  1828. tools_storage = tools_storage
  1829. else:
  1830. tools_storage = self.paint_tools
  1831. # This is a recursive generator of individual Polygons.
  1832. # Note: Double check correct implementation. Might exit
  1833. # early if it finds something that is not a Polygon?
  1834. # def recurse(geo):
  1835. # try:
  1836. # for subg in geo:
  1837. # for subsubg in recurse(subg):
  1838. # yield subsubg
  1839. # except TypeError:
  1840. # if isinstance(geo, Polygon):
  1841. # yield geo
  1842. #
  1843. # raise StopIteration
  1844. def recurse(geometry, reset=True):
  1845. """
  1846. Creates a list of non-iterable linear geometry objects.
  1847. Results are placed in self.flat_geometry
  1848. :param geometry: Shapely type or list or list of list of such.
  1849. :param reset: Clears the contents of self.flat_geometry.
  1850. """
  1851. if self.app.abort_flag:
  1852. # graceful abort requested by the user
  1853. raise FlatCAMApp.GracefulException
  1854. if geometry is None:
  1855. return
  1856. if reset:
  1857. self.flat_geometry = []
  1858. # ## If iterable, expand recursively.
  1859. try:
  1860. for geo in geometry:
  1861. if geo is not None:
  1862. recurse(geometry=geo, reset=False)
  1863. # ## Not iterable, do the actual indexing and add.
  1864. except TypeError:
  1865. if isinstance(geometry, LinearRing):
  1866. g = Polygon(geometry)
  1867. self.flat_geometry.append(g)
  1868. else:
  1869. self.flat_geometry.append(geometry)
  1870. return self.flat_geometry
  1871. # Initializes the new geometry object
  1872. def gen_paintarea(geo_obj, app_obj):
  1873. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1874. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1875. log.debug("Paint Tool. Normal painting all task started.")
  1876. if isinstance(obj, FlatCAMGerber):
  1877. if app_obj.defaults["gerber_buffering"] == 'no':
  1878. app_obj.inform.emit('%s %s' %
  1879. (_("Paint Tool. Normal painting all task started."),
  1880. _("Buffering geometry...")))
  1881. else:
  1882. app_obj.inform.emit(_("Paint Tool. Normal painting all task started."))
  1883. else:
  1884. app_obj.inform.emit(_("Paint Tool. Normal painting all task started."))
  1885. tool_dia = None
  1886. if order == 'fwd':
  1887. sorted_tools.sort(reverse=False)
  1888. elif order == 'rev':
  1889. sorted_tools.sort(reverse=True)
  1890. else:
  1891. pass
  1892. if isinstance(obj, FlatCAMGerber):
  1893. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1894. if isinstance(obj.solid_geometry, list):
  1895. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1896. else:
  1897. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1898. try:
  1899. a, b, c, d = obj.bounds()
  1900. geo_obj.options['xmin'] = a
  1901. geo_obj.options['ymin'] = b
  1902. geo_obj.options['xmax'] = c
  1903. geo_obj.options['ymax'] = d
  1904. except Exception as e:
  1905. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1906. return
  1907. total_geometry = []
  1908. current_uid = int(1)
  1909. geo_obj.solid_geometry = []
  1910. for tool_dia in sorted_tools:
  1911. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1912. app_obj.inform.emit(
  1913. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1914. str(tool_dia),
  1915. self.units.lower(),
  1916. _('started'))
  1917. )
  1918. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1919. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1920. for k, v in tools_storage.items():
  1921. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1922. current_uid = int(k)
  1923. break
  1924. painted_area = recurse(obj.solid_geometry)
  1925. # variables to display the percentage of work done
  1926. geo_len = len(painted_area)
  1927. old_disp_number = 0
  1928. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1929. pol_nr = 0
  1930. for geo in painted_area:
  1931. # provide the app with a way to process the GUI events when in a blocking loop
  1932. QtWidgets.QApplication.processEvents()
  1933. if self.app.abort_flag:
  1934. # graceful abort requested by the user
  1935. raise FlatCAMApp.GracefulException
  1936. # try to clean the Polygon but it may result into a MultiPolygon
  1937. geo = geo.buffer(0)
  1938. poly_buf = geo.buffer(-paint_margin)
  1939. if geo is not None and geo.is_valid:
  1940. poly_processed = list()
  1941. try:
  1942. for pol in poly_buf:
  1943. if pol is not None and isinstance(pol, Polygon):
  1944. cp = None
  1945. if paint_method == _("Standard"):
  1946. cp = self.clear_polygon(pol,
  1947. tooldia=tool_dia,
  1948. steps_per_circle=self.app.defaults[
  1949. "geometry_circle_steps"],
  1950. overlap=over,
  1951. contour=cont,
  1952. connect=conn,
  1953. prog_plot=prog_plot)
  1954. elif paint_method == _("Seed"):
  1955. cp = self.clear_polygon2(pol,
  1956. tooldia=tool_dia,
  1957. steps_per_circle=self.app.defaults[
  1958. "geometry_circle_steps"],
  1959. overlap=over,
  1960. contour=cont,
  1961. connect=conn,
  1962. prog_plot=prog_plot)
  1963. elif paint_method == _("Lines"):
  1964. cp = self.clear_polygon3(pol,
  1965. tooldia=tool_dia,
  1966. steps_per_circle=self.app.defaults[
  1967. "geometry_circle_steps"],
  1968. overlap=over,
  1969. contour=cont,
  1970. connect=conn,
  1971. prog_plot=prog_plot)
  1972. elif paint_method == _("Laser_lines"):
  1973. # line = None
  1974. # aperture_size = None
  1975. # the key is the aperture type and the val is a list of geo elements
  1976. flash_el_dict = dict()
  1977. # the key is the aperture size, the val is a list of geo elements
  1978. traces_el_dict = dict()
  1979. # find the flashes and the lines that are in the selected polygon and store
  1980. # them separately
  1981. for apid, apval in obj.apertures.items():
  1982. for geo_el in apval['geometry']:
  1983. if apval["size"] == 0.0:
  1984. if apval["size"] in traces_el_dict:
  1985. traces_el_dict[apval["size"]].append(geo_el)
  1986. else:
  1987. traces_el_dict[apval["size"]] = [geo_el]
  1988. if 'follow' in geo_el and geo_el['follow'].within(pol):
  1989. if isinstance(geo_el['follow'], Point):
  1990. if apval["type"] == 'C':
  1991. if 'C' in flash_el_dict:
  1992. flash_el_dict['C'].append(geo_el)
  1993. else:
  1994. flash_el_dict['C'] = [geo_el]
  1995. elif apval["type"] == 'O':
  1996. if 'O' in flash_el_dict:
  1997. flash_el_dict['O'].append(geo_el)
  1998. else:
  1999. flash_el_dict['O'] = [geo_el]
  2000. elif apval["type"] == 'R':
  2001. if 'R' in flash_el_dict:
  2002. flash_el_dict['R'].append(geo_el)
  2003. else:
  2004. flash_el_dict['R'] = [geo_el]
  2005. else:
  2006. aperture_size = apval['size']
  2007. if aperture_size in traces_el_dict:
  2008. traces_el_dict[aperture_size].append(geo_el)
  2009. else:
  2010. traces_el_dict[aperture_size] = [geo_el]
  2011. cp = FlatCAMRTreeStorage()
  2012. pads_lines_list = list()
  2013. # process the flashes found in the selected polygon with the 'lines' method
  2014. # for rectangular flashes and with _("Seed") for oblong and circular flashes
  2015. # and pads (flahes) need the contour therefore I override the GUI settings
  2016. # with always True
  2017. for ap_type in flash_el_dict:
  2018. for elem in flash_el_dict[ap_type]:
  2019. if 'solid' in elem:
  2020. if ap_type == 'C':
  2021. f_o = self.clear_polygon2(elem['solid'],
  2022. tooldia=tool_dia,
  2023. steps_per_circle=self.app.defaults[
  2024. "geometry_circle_steps"],
  2025. overlap=over,
  2026. contour=True,
  2027. connect=conn,
  2028. prog_plot=prog_plot)
  2029. pads_lines_list += [p for p in f_o.get_objects() if p]
  2030. elif ap_type == 'O':
  2031. f_o = self.clear_polygon2(elem['solid'],
  2032. tooldia=tool_dia,
  2033. steps_per_circle=self.app.defaults[
  2034. "geometry_circle_steps"],
  2035. overlap=over,
  2036. contour=True,
  2037. connect=conn,
  2038. prog_plot=prog_plot)
  2039. pads_lines_list += [p for p in f_o.get_objects() if p]
  2040. elif ap_type == 'R':
  2041. f_o = self.clear_polygon3(elem['solid'],
  2042. tooldia=tool_dia,
  2043. steps_per_circle=self.app.defaults[
  2044. "geometry_circle_steps"],
  2045. overlap=over,
  2046. contour=True,
  2047. connect=conn,
  2048. prog_plot=prog_plot)
  2049. pads_lines_list += [p for p in f_o.get_objects() if p]
  2050. # add the lines from pads to the storage
  2051. try:
  2052. for lin in pads_lines_list:
  2053. if lin:
  2054. cp.insert(lin)
  2055. except TypeError:
  2056. cp.insert(pads_lines_list)
  2057. copper_lines_list = list()
  2058. # process the traces found in the selected polygon using the 'laser_lines'
  2059. # method, method which will follow the 'follow' line therefore use the longer
  2060. # path possible for the laser, therefore the acceleration will play
  2061. # a smaller factor
  2062. for aperture_size in traces_el_dict:
  2063. for elem in traces_el_dict[aperture_size]:
  2064. line = elem['follow']
  2065. if line:
  2066. t_o = self.fill_with_lines(line, aperture_size,
  2067. tooldia=tool_dia,
  2068. steps_per_circle=self.app.defaults[
  2069. "geometry_circle_steps"],
  2070. overlap=over,
  2071. contour=cont,
  2072. connect=conn,
  2073. prog_plot=prog_plot)
  2074. copper_lines_list += [p for p in t_o.get_objects() if p]
  2075. # add the lines from copper features to storage but first try to make as few
  2076. # lines as possible
  2077. # by trying to fuse them
  2078. lines_union = linemerge(unary_union(copper_lines_list))
  2079. try:
  2080. for lin in lines_union:
  2081. if lin:
  2082. cp.insert(lin)
  2083. except TypeError:
  2084. cp.insert(lines_union)
  2085. elif paint_method == _("Combo"):
  2086. self.app.inform.emit(_("Painting polygons with method: lines."))
  2087. cp = self.clear_polygon3(pol,
  2088. tooldia=tool_dia,
  2089. steps_per_circle=self.app.defaults[
  2090. "geometry_circle_steps"],
  2091. overlap=over,
  2092. contour=cont,
  2093. connect=conn,
  2094. prog_plot=prog_plot)
  2095. if cp and cp.objects:
  2096. pass
  2097. else:
  2098. self.app.inform.emit(_("Failed. Painting polygons with method: seed."))
  2099. cp = self.clear_polygon2(pol,
  2100. tooldia=tool_dia,
  2101. steps_per_circle=self.app.defaults[
  2102. "geometry_circle_steps"],
  2103. overlap=over,
  2104. contour=cont,
  2105. connect=conn,
  2106. prog_plot=prog_plot)
  2107. if cp and cp.objects:
  2108. pass
  2109. else:
  2110. self.app.inform.emit(
  2111. _("Failed. Painting polygons with method: standard."))
  2112. cp = self.clear_polygon(pol,
  2113. tooldia=tool_dia,
  2114. steps_per_circle=self.app.defaults[
  2115. "geometry_circle_steps"],
  2116. overlap=over,
  2117. contour=cont,
  2118. connect=conn,
  2119. prog_plot=prog_plot)
  2120. if cp and cp.objects:
  2121. total_geometry += list(cp.get_objects())
  2122. poly_processed.append(True)
  2123. else:
  2124. poly_processed.append(False)
  2125. log.warning("Polygon in MultiPolygon can not be cleared.")
  2126. else:
  2127. log.warning("Geo in Iterable can not be cleared because it is not Polygon. "
  2128. "It is: %s" % str(type(pol)))
  2129. except TypeError:
  2130. if isinstance(poly_buf, Polygon):
  2131. cp = None
  2132. if paint_method == _("Standard"):
  2133. cp = self.clear_polygon(poly_buf,
  2134. tooldia=tool_dia,
  2135. steps_per_circle=self.app.defaults[
  2136. "geometry_circle_steps"],
  2137. overlap=over,
  2138. contour=cont,
  2139. connect=conn,
  2140. prog_plot=prog_plot)
  2141. elif paint_method == _("Seed"):
  2142. cp = self.clear_polygon2(poly_buf,
  2143. tooldia=tool_dia,
  2144. steps_per_circle=self.app.defaults[
  2145. "geometry_circle_steps"],
  2146. overlap=over,
  2147. contour=cont,
  2148. connect=conn,
  2149. prog_plot=prog_plot)
  2150. elif paint_method == _("Lines"):
  2151. cp = self.clear_polygon3(poly_buf,
  2152. tooldia=tool_dia,
  2153. steps_per_circle=self.app.defaults[
  2154. "geometry_circle_steps"],
  2155. overlap=over,
  2156. contour=cont,
  2157. connect=conn,
  2158. prog_plot=prog_plot)
  2159. elif paint_method == _("Laser_lines"):
  2160. # line = None
  2161. # aperture_size = None
  2162. # the key is the aperture type and the val is a list of geo elements
  2163. flash_el_dict = dict()
  2164. # the key is the aperture size, the val is a list of geo elements
  2165. traces_el_dict = dict()
  2166. # find the flashes and the lines that are in the selected polygon and store
  2167. # them separately
  2168. for apid, apval in obj.apertures.items():
  2169. for geo_el in apval['geometry']:
  2170. if apval["size"] == 0.0:
  2171. if apval["size"] in traces_el_dict:
  2172. traces_el_dict[apval["size"]].append(geo_el)
  2173. else:
  2174. traces_el_dict[apval["size"]] = [geo_el]
  2175. if 'follow' in geo_el and geo_el['follow'].within(poly_buf):
  2176. if isinstance(geo_el['follow'], Point):
  2177. if apval["type"] == 'C':
  2178. if 'C' in flash_el_dict:
  2179. flash_el_dict['C'].append(geo_el)
  2180. else:
  2181. flash_el_dict['C'] = [geo_el]
  2182. elif apval["type"] == 'O':
  2183. if 'O' in flash_el_dict:
  2184. flash_el_dict['O'].append(geo_el)
  2185. else:
  2186. flash_el_dict['O'] = [geo_el]
  2187. elif apval["type"] == 'R':
  2188. if 'R' in flash_el_dict:
  2189. flash_el_dict['R'].append(geo_el)
  2190. else:
  2191. flash_el_dict['R'] = [geo_el]
  2192. else:
  2193. aperture_size = apval['size']
  2194. if aperture_size in traces_el_dict:
  2195. traces_el_dict[aperture_size].append(geo_el)
  2196. else:
  2197. traces_el_dict[aperture_size] = [geo_el]
  2198. cp = FlatCAMRTreeStorage()
  2199. pads_lines_list = list()
  2200. # process the flashes found in the selected polygon with the 'lines' method
  2201. # for rectangular flashes and with _("Seed") for oblong and circular flashes
  2202. # and pads (flahes) need the contour therefore I override the GUI settings
  2203. # with always True
  2204. for ap_type in flash_el_dict:
  2205. for elem in flash_el_dict[ap_type]:
  2206. if 'solid' in elem:
  2207. if ap_type == 'C':
  2208. f_o = self.clear_polygon2(elem['solid'],
  2209. tooldia=tool_dia,
  2210. steps_per_circle=self.app.defaults[
  2211. "geometry_circle_steps"],
  2212. overlap=over,
  2213. contour=True,
  2214. connect=conn,
  2215. prog_plot=prog_plot)
  2216. pads_lines_list += [p for p in f_o.get_objects() if p]
  2217. elif ap_type == 'O':
  2218. f_o = self.clear_polygon2(elem['solid'],
  2219. tooldia=tool_dia,
  2220. steps_per_circle=self.app.defaults[
  2221. "geometry_circle_steps"],
  2222. overlap=over,
  2223. contour=True,
  2224. connect=conn,
  2225. prog_plot=prog_plot)
  2226. pads_lines_list += [p for p in f_o.get_objects() if p]
  2227. elif ap_type == 'R':
  2228. f_o = self.clear_polygon3(elem['solid'],
  2229. tooldia=tool_dia,
  2230. steps_per_circle=self.app.defaults[
  2231. "geometry_circle_steps"],
  2232. overlap=over,
  2233. contour=True,
  2234. connect=conn,
  2235. prog_plot=prog_plot)
  2236. pads_lines_list += [p for p in f_o.get_objects() if p]
  2237. # add the lines from pads to the storage
  2238. try:
  2239. for lin in pads_lines_list:
  2240. if lin:
  2241. cp.insert(lin)
  2242. except TypeError:
  2243. cp.insert(pads_lines_list)
  2244. copper_lines_list = list()
  2245. # process the traces found in the selected polygon using the 'laser_lines'
  2246. # method, method which will follow the 'follow' line therefore use the longer
  2247. # path possible for the laser, therefore the acceleration will play
  2248. # a smaller factor
  2249. for aperture_size in traces_el_dict:
  2250. for elem in traces_el_dict[aperture_size]:
  2251. line = elem['follow']
  2252. if line:
  2253. t_o = self.fill_with_lines(line, aperture_size,
  2254. tooldia=tool_dia,
  2255. steps_per_circle=self.app.defaults[
  2256. "geometry_circle_steps"],
  2257. overlap=over,
  2258. contour=cont,
  2259. connect=conn,
  2260. prog_plot=prog_plot)
  2261. copper_lines_list += [p for p in t_o.get_objects() if p]
  2262. # add the lines from copper features to storage but first try to make as few
  2263. # lines as possible
  2264. # by trying to fuse them
  2265. lines_union = linemerge(unary_union(copper_lines_list))
  2266. try:
  2267. for lin in lines_union:
  2268. if lin:
  2269. cp.insert(lin)
  2270. except TypeError:
  2271. cp.insert(lines_union)
  2272. elif paint_method == _("Combo"):
  2273. self.app.inform.emit(_("Painting polygons with method: lines."))
  2274. cp = self.clear_polygon3(poly_buf,
  2275. tooldia=tool_dia,
  2276. steps_per_circle=self.app.defaults[
  2277. "geometry_circle_steps"],
  2278. overlap=over,
  2279. contour=cont,
  2280. connect=conn,
  2281. prog_plot=prog_plot)
  2282. if cp and cp.objects:
  2283. pass
  2284. else:
  2285. self.app.inform.emit(_("Failed. Painting polygons with method: seed."))
  2286. cp = self.clear_polygon2(poly_buf,
  2287. tooldia=tool_dia,
  2288. steps_per_circle=self.app.defaults[
  2289. "geometry_circle_steps"],
  2290. overlap=over,
  2291. contour=cont,
  2292. connect=conn,
  2293. prog_plot=prog_plot)
  2294. if cp and cp.objects:
  2295. pass
  2296. else:
  2297. self.app.inform.emit(_("Failed. Painting polygons with method: standard."))
  2298. cp = self.clear_polygon(poly_buf,
  2299. tooldia=tool_dia,
  2300. steps_per_circle=self.app.defaults[
  2301. "geometry_circle_steps"],
  2302. overlap=over,
  2303. contour=cont,
  2304. connect=conn,
  2305. prog_plot=prog_plot)
  2306. if cp:
  2307. total_geometry += list(cp.get_objects())
  2308. poly_processed.append(True)
  2309. else:
  2310. poly_processed.append(False)
  2311. log.warning("Polygon can not be cleared.")
  2312. else:
  2313. log.warning("Geo can not be cleared because it is: %s" % str(type(poly_buf)))
  2314. p_cleared = poly_processed.count(True)
  2315. p_not_cleared = poly_processed.count(False)
  2316. if p_not_cleared:
  2317. app_obj.poly_not_cleared = True
  2318. if p_cleared == 0:
  2319. continue
  2320. # try:
  2321. # # Polygons are the only really paintable geometries,
  2322. # # lines in theory have no area to be painted
  2323. # if not isinstance(geo, Polygon):
  2324. # continue
  2325. # poly_buf = geo.buffer(-paint_margin)
  2326. #
  2327. # if paint_method == _("Seed"):
  2328. # # Type(cp) == FlatCAMRTreeStorage | None
  2329. # cp = self.clear_polygon2(poly_buf,
  2330. # tooldia=tool_dia,
  2331. # steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2332. # overlap=over,
  2333. # contour=cont,
  2334. # connect=conn,
  2335. # prog_plot=prog_plot)
  2336. #
  2337. # elif paint_method == _("Lines"):
  2338. # # Type(cp) == FlatCAMRTreeStorage | None
  2339. # cp = self.clear_polygon3(poly_buf,
  2340. # tooldia=tool_dia,
  2341. # steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2342. # overlap=over,
  2343. # contour=cont,
  2344. # connect=conn,
  2345. # prog_plot=prog_plot)
  2346. #
  2347. # else:
  2348. # # Type(cp) == FlatCAMRTreeStorage | None
  2349. # cp = self.clear_polygon(poly_buf,
  2350. # tooldia=tool_dia,
  2351. # steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2352. # overlap=over,
  2353. # contour=cont,
  2354. # connect=conn,
  2355. # prog_plot=prog_plot)
  2356. #
  2357. # if cp is not None:
  2358. # total_geometry += list(cp.get_objects())
  2359. # except FlatCAMApp.GracefulException:
  2360. # return "fail"
  2361. # except Exception as e:
  2362. # log.debug("Could not Paint the polygons. %s" % str(e))
  2363. # self.app.inform.emit('[ERROR] %s\n%s' %
  2364. # (_("Could not do Paint All. Try a different combination of parameters. "
  2365. # "Or a different Method of paint"),
  2366. # str(e)))
  2367. # return "fail"
  2368. pol_nr += 1
  2369. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2370. # log.debug("Polygons cleared: %d" % pol_nr)
  2371. if old_disp_number < disp_number <= 100:
  2372. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  2373. old_disp_number = disp_number
  2374. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2375. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  2376. # dictionary and then reset the temporary list that stored that solid_geometry
  2377. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  2378. tools_storage[current_uid]['data']['name'] = name
  2379. total_geometry[:] = []
  2380. # clean the progressive plotted shapes if it was used
  2381. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2382. self.temp_shapes.clear(update=True)
  2383. # # delete tools with empty geometry
  2384. # keys_to_delete = []
  2385. # # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  2386. # for uid in tools_storage:
  2387. # # if the solid_geometry (type=list) is empty
  2388. # if not tools_storage[uid]['solid_geometry']:
  2389. # keys_to_delete.append(uid)
  2390. #
  2391. # # actual delete of keys from the tools_storage dict
  2392. # for k in keys_to_delete:
  2393. # tools_storage.pop(k, None)
  2394. # delete tools with empty geometry
  2395. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  2396. for uid in list(tools_storage.keys()):
  2397. # if the solid_geometry (type=list) is empty
  2398. if not tools_storage[uid]['solid_geometry']:
  2399. tools_storage.pop(uid, None)
  2400. geo_obj.options["cnctooldia"] = str(tool_dia)
  2401. # this turn on the FlatCAMCNCJob plot for multiple tools
  2402. geo_obj.multigeo = True
  2403. geo_obj.multitool = True
  2404. geo_obj.tools.clear()
  2405. geo_obj.tools = dict(tools_storage)
  2406. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2407. has_solid_geo = 0
  2408. for tooluid in geo_obj.tools:
  2409. if geo_obj.tools[tooluid]['solid_geometry']:
  2410. has_solid_geo += 1
  2411. if has_solid_geo == 0:
  2412. self.app.inform.emit('[ERROR] %s' %
  2413. _("There is no Painting Geometry in the file.\n"
  2414. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2415. "Change the painting parameters and try again."))
  2416. return
  2417. # Experimental...
  2418. # print("Indexing...", end=' ')
  2419. # geo_obj.make_index()
  2420. self.app.inform.emit('[success] %s' % _("Paint All Done."))
  2421. # Initializes the new geometry object
  2422. def gen_paintarea_rest_machining(geo_obj, app_obj):
  2423. assert isinstance(geo_obj, FlatCAMGeometry), \
  2424. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2425. log.debug("Paint Tool. Rest machining painting all task started.")
  2426. if isinstance(obj, FlatCAMGerber):
  2427. if app_obj.defaults["gerber_buffering"] == 'no':
  2428. app_obj.inform.emit('%s %s %s' %
  2429. (_("Paint Tool."), _("Rest machining painting all task started."),
  2430. _("Buffering geometry...")))
  2431. else:
  2432. app_obj.inform.emit('%s %s' %
  2433. (_("Paint Tool."), _("Rest machining painting all task started.")))
  2434. else:
  2435. app_obj.inform.emit('%s %s' %
  2436. (_("Paint Tool."), _("Rest machining painting all task started.")))
  2437. tool_dia = None
  2438. sorted_tools.sort(reverse=True)
  2439. cleared_geo = []
  2440. current_uid = int(1)
  2441. geo_obj.solid_geometry = []
  2442. if isinstance(obj, FlatCAMGerber):
  2443. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2444. if isinstance(obj.solid_geometry, list):
  2445. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  2446. else:
  2447. obj.solid_geometry = obj.solid_geometry.buffer(0)
  2448. try:
  2449. a, b, c, d = obj.bounds()
  2450. geo_obj.options['xmin'] = a
  2451. geo_obj.options['ymin'] = b
  2452. geo_obj.options['xmax'] = c
  2453. geo_obj.options['ymax'] = d
  2454. except Exception as e:
  2455. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  2456. return
  2457. for tool_dia in sorted_tools:
  2458. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  2459. app_obj.inform.emit(
  2460. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  2461. str(tool_dia),
  2462. self.units.lower(),
  2463. _('started'))
  2464. )
  2465. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2466. painted_area = recurse(obj.solid_geometry)
  2467. # variables to display the percentage of work done
  2468. geo_len = int(len(painted_area) / 100)
  2469. old_disp_number = 0
  2470. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2471. pol_nr = 0
  2472. for geo in painted_area:
  2473. try:
  2474. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  2475. poly_buf = geo.buffer(-paint_margin)
  2476. cp = None
  2477. if paint_method == _("Standard"):
  2478. # Type(cp) == FlatCAMRTreeStorage | None
  2479. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  2480. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2481. overlap=over, contour=cont, connect=conn,
  2482. prog_plot=prog_plot)
  2483. elif paint_method == _("Seed"):
  2484. # Type(cp) == FlatCAMRTreeStorage | None
  2485. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  2486. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2487. overlap=over, contour=cont, connect=conn,
  2488. prog_plot=prog_plot)
  2489. elif paint_method == _("Lines"):
  2490. # Type(cp) == FlatCAMRTreeStorage | None
  2491. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  2492. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2493. overlap=over, contour=cont, connect=conn,
  2494. prog_plot=prog_plot)
  2495. elif paint_method == _("Laser_lines"):
  2496. # line = None
  2497. # aperture_size = None
  2498. # the key is the aperture type and the val is a list of geo elements
  2499. flash_el_dict = dict()
  2500. # the key is the aperture size, the val is a list of geo elements
  2501. traces_el_dict = dict()
  2502. # find the flashes and the lines that are in the selected polygon and store
  2503. # them separately
  2504. for apid, apval in obj.apertures.items():
  2505. for geo_el in apval['geometry']:
  2506. if apval["size"] == 0.0:
  2507. if apval["size"] in traces_el_dict:
  2508. traces_el_dict[apval["size"]].append(geo_el)
  2509. else:
  2510. traces_el_dict[apval["size"]] = [geo_el]
  2511. if 'follow' in geo_el and geo_el['follow'].within(poly_buf):
  2512. if isinstance(geo_el['follow'], Point):
  2513. if apval["type"] == 'C':
  2514. if 'C' in flash_el_dict:
  2515. flash_el_dict['C'].append(geo_el)
  2516. else:
  2517. flash_el_dict['C'] = [geo_el]
  2518. elif apval["type"] == 'O':
  2519. if 'O' in flash_el_dict:
  2520. flash_el_dict['O'].append(geo_el)
  2521. else:
  2522. flash_el_dict['O'] = [geo_el]
  2523. elif apval["type"] == 'R':
  2524. if 'R' in flash_el_dict:
  2525. flash_el_dict['R'].append(geo_el)
  2526. else:
  2527. flash_el_dict['R'] = [geo_el]
  2528. else:
  2529. aperture_size = apval['size']
  2530. if aperture_size in traces_el_dict:
  2531. traces_el_dict[aperture_size].append(geo_el)
  2532. else:
  2533. traces_el_dict[aperture_size] = [geo_el]
  2534. cp = FlatCAMRTreeStorage()
  2535. pads_lines_list = list()
  2536. # process the flashes found in the selected polygon with the 'lines' method
  2537. # for rectangular flashes and with _("Seed") for oblong and circular flashes
  2538. # and pads (flahes) need the contour therefore I override the GUI settings
  2539. # with always True
  2540. for ap_type in flash_el_dict:
  2541. for elem in flash_el_dict[ap_type]:
  2542. if 'solid' in elem:
  2543. if ap_type == 'C':
  2544. f_o = self.clear_polygon2(elem['solid'],
  2545. tooldia=tool_dia,
  2546. steps_per_circle=self.app.defaults[
  2547. "geometry_circle_steps"],
  2548. overlap=over,
  2549. contour=True,
  2550. connect=conn,
  2551. prog_plot=prog_plot)
  2552. pads_lines_list += [p for p in f_o.get_objects() if p]
  2553. elif ap_type == 'O':
  2554. f_o = self.clear_polygon2(elem['solid'],
  2555. tooldia=tool_dia,
  2556. steps_per_circle=self.app.defaults[
  2557. "geometry_circle_steps"],
  2558. overlap=over,
  2559. contour=True,
  2560. connect=conn,
  2561. prog_plot=prog_plot)
  2562. pads_lines_list += [p for p in f_o.get_objects() if p]
  2563. elif ap_type == 'R':
  2564. f_o = self.clear_polygon3(elem['solid'],
  2565. tooldia=tool_dia,
  2566. steps_per_circle=self.app.defaults[
  2567. "geometry_circle_steps"],
  2568. overlap=over,
  2569. contour=True,
  2570. connect=conn,
  2571. prog_plot=prog_plot)
  2572. pads_lines_list += [p for p in f_o.get_objects() if p]
  2573. # add the lines from pads to the storage
  2574. try:
  2575. for lin in pads_lines_list:
  2576. if lin:
  2577. cp.insert(lin)
  2578. except TypeError:
  2579. cp.insert(pads_lines_list)
  2580. copper_lines_list = list()
  2581. # process the traces found in the selected polygon using the 'laser_lines'
  2582. # method, method which will follow the 'follow' line therefore use the longer
  2583. # path possible for the laser, therefore the acceleration will play
  2584. # a smaller factor
  2585. for aperture_size in traces_el_dict:
  2586. for elem in traces_el_dict[aperture_size]:
  2587. line = elem['follow']
  2588. if line:
  2589. t_o = self.fill_with_lines(line, aperture_size,
  2590. tooldia=tool_dia,
  2591. steps_per_circle=self.app.defaults[
  2592. "geometry_circle_steps"],
  2593. overlap=over,
  2594. contour=cont,
  2595. connect=conn,
  2596. prog_plot=prog_plot)
  2597. copper_lines_list += [p for p in t_o.get_objects() if p]
  2598. # add the lines from copper features to storage but first try to make as few
  2599. # lines as possible
  2600. # by trying to fuse them
  2601. lines_union = linemerge(unary_union(copper_lines_list))
  2602. try:
  2603. for lin in lines_union:
  2604. if lin:
  2605. cp.insert(lin)
  2606. except TypeError:
  2607. cp.insert(lines_union)
  2608. elif paint_method == _("Combo"):
  2609. self.app.inform.emit(_("Painting polygons with method: lines."))
  2610. cp = self.clear_polygon3(poly_buf,
  2611. tooldia=tool_dia,
  2612. steps_per_circle=self.app.defaults[
  2613. "geometry_circle_steps"],
  2614. overlap=over,
  2615. contour=cont,
  2616. connect=conn,
  2617. prog_plot=prog_plot)
  2618. if cp and cp.objects:
  2619. pass
  2620. else:
  2621. self.app.inform.emit(_("Failed. Painting polygons with method: seed."))
  2622. cp = self.clear_polygon2(poly_buf,
  2623. tooldia=tool_dia,
  2624. steps_per_circle=self.app.defaults[
  2625. "geometry_circle_steps"],
  2626. overlap=over,
  2627. contour=cont,
  2628. connect=conn,
  2629. prog_plot=prog_plot)
  2630. if cp and cp.objects:
  2631. pass
  2632. else:
  2633. self.app.inform.emit(_("Failed. Painting polygons with method: standard."))
  2634. cp = self.clear_polygon(poly_buf,
  2635. tooldia=tool_dia,
  2636. steps_per_circle=self.app.defaults[
  2637. "geometry_circle_steps"],
  2638. overlap=over,
  2639. contour=cont,
  2640. connect=conn,
  2641. prog_plot=prog_plot)
  2642. if cp is not None:
  2643. cleared_geo += list(cp.get_objects())
  2644. except FlatCAMApp.GracefulException:
  2645. return "fail"
  2646. except Exception as e:
  2647. log.debug("Could not Paint the polygons. %s" % str(e))
  2648. self.app.inform.emit('[ERROR] %s\n%s' %
  2649. (_("Could not do Paint All. Try a different combination of parameters. "
  2650. "Or a different Method of paint"),
  2651. str(e)))
  2652. return "fail"
  2653. pol_nr += 1
  2654. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2655. # log.debug("Polygons cleared: %d" % pol_nr)
  2656. if old_disp_number < disp_number <= 100:
  2657. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  2658. old_disp_number = disp_number
  2659. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2660. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  2661. for k, v in tools_storage.items():
  2662. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  2663. current_uid = int(k)
  2664. break
  2665. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  2666. # then reset the temporary list that stored that solid_geometry
  2667. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  2668. tools_storage[current_uid]['data']['name'] = name
  2669. cleared_geo[:] = []
  2670. geo_obj.options["cnctooldia"] = str(tool_dia)
  2671. # this turn on the FlatCAMCNCJob plot for multiple tools
  2672. geo_obj.multigeo = True
  2673. geo_obj.multitool = True
  2674. geo_obj.tools.clear()
  2675. geo_obj.tools = dict(tools_storage)
  2676. # clean the progressive plotted shapes if it was used
  2677. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2678. self.temp_shapes.clear(update=True)
  2679. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2680. has_solid_geo = 0
  2681. for tooluid in geo_obj.tools:
  2682. if geo_obj.tools[tooluid]['solid_geometry']:
  2683. has_solid_geo += 1
  2684. if has_solid_geo == 0:
  2685. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2686. _("There is no Painting Geometry in the file.\n"
  2687. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2688. "Change the painting parameters and try again."))
  2689. return
  2690. # Experimental...
  2691. # print("Indexing...", end=' ')
  2692. # geo_obj.make_index()
  2693. self.app.inform.emit('[success] %s' % _("Paint All with Rest-Machining done."))
  2694. def job_thread(app_obj):
  2695. try:
  2696. if self.rest_cb.isChecked():
  2697. app_obj.new_object("geometry", name, gen_paintarea_rest_machining, plot=plot)
  2698. else:
  2699. app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  2700. except FlatCAMApp.GracefulException:
  2701. proc.done()
  2702. return
  2703. except Exception:
  2704. proc.done()
  2705. traceback.print_stack()
  2706. return
  2707. proc.done()
  2708. # focus on Selected Tab
  2709. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2710. self.app.inform.emit(_("Polygon Paint started ..."))
  2711. # Promise object with the new name
  2712. self.app.collection.promise(name)
  2713. if run_threaded:
  2714. # Background
  2715. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2716. else:
  2717. job_thread(app_obj=self.app)
  2718. def paint_poly_area(self, obj, sel_obj,
  2719. tooldia=None,
  2720. overlap=None,
  2721. order=None,
  2722. margin=None,
  2723. method=None,
  2724. outname=None,
  2725. connect=None,
  2726. contour=None,
  2727. tools_storage=None,
  2728. plot=True,
  2729. run_threaded=True):
  2730. """
  2731. Paints all polygons in this object that are within the sel_obj object
  2732. :param run_threaded:
  2733. :param plot:
  2734. :param obj: painted object
  2735. :param sel_obj: paint only what is inside this object bounds
  2736. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  2737. :param overlap: value by which the paths will overlap
  2738. :param order: if the tools are ordered and how
  2739. :param margin: a border around painting area
  2740. :param outname: name of the resulting object
  2741. :param connect: Connect lines to avoid tool lifts.
  2742. :param contour: Paint around the edges.
  2743. :param method: choice out of _("Seed"), 'normal', 'lines'
  2744. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  2745. Usage of the different one is related to when this function is called from a TcL command.
  2746. :return:
  2747. """
  2748. paint_method = method if method is not None else self.paintmethod_combo.get_value()
  2749. if margin is not None:
  2750. paint_margin = margin
  2751. else:
  2752. try:
  2753. paint_margin = float(self.paintmargin_entry.get_value())
  2754. except ValueError:
  2755. # try to convert comma to decimal point. if it's still not working error message and return
  2756. try:
  2757. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  2758. except ValueError:
  2759. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2760. _("Wrong value format entered, use a number."))
  2761. return
  2762. # determine if to use the progressive plotting
  2763. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2764. prog_plot = True
  2765. else:
  2766. prog_plot = False
  2767. proc = self.app.proc_container.new(_("Painting polygons..."))
  2768. name = outname if outname is not None else self.obj_name + "_paint"
  2769. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"]) / 100.0
  2770. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  2771. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  2772. order = order if order is not None else self.order_radio.get_value()
  2773. sorted_tools = []
  2774. if tooldia is not None:
  2775. try:
  2776. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  2777. except AttributeError:
  2778. if not isinstance(tooldia, list):
  2779. sorted_tools = [float(tooldia)]
  2780. else:
  2781. sorted_tools = tooldia
  2782. else:
  2783. for row in range(self.tools_table.rowCount()):
  2784. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  2785. if tools_storage is not None:
  2786. tools_storage = tools_storage
  2787. else:
  2788. tools_storage = self.paint_tools
  2789. def recurse(geometry, reset=True):
  2790. """
  2791. Creates a list of non-iterable linear geometry objects.
  2792. Results are placed in self.flat_geometry
  2793. :param geometry: Shapely type or list or list of list of such.
  2794. :param reset: Clears the contents of self.flat_geometry.
  2795. """
  2796. if self.app.abort_flag:
  2797. # graceful abort requested by the user
  2798. raise FlatCAMApp.GracefulException
  2799. if geometry is None:
  2800. return
  2801. if reset:
  2802. self.flat_geometry = []
  2803. # ## If iterable, expand recursively.
  2804. try:
  2805. for geo in geometry:
  2806. if geo is not None:
  2807. recurse(geometry=geo, reset=False)
  2808. # ## Not iterable, do the actual indexing and add.
  2809. except TypeError:
  2810. if isinstance(geometry, LinearRing):
  2811. g = Polygon(geometry)
  2812. self.flat_geometry.append(g)
  2813. else:
  2814. self.flat_geometry.append(geometry)
  2815. return self.flat_geometry
  2816. # Initializes the new geometry object
  2817. def gen_paintarea(geo_obj, app_obj):
  2818. # assert isinstance(geo_obj, FlatCAMGeometry), \
  2819. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2820. log.debug("Paint Tool. Normal painting area task started.")
  2821. if isinstance(obj, FlatCAMGerber):
  2822. if app_obj.defaults["gerber_buffering"] == 'no':
  2823. app_obj.inform.emit('%s %s %s' %
  2824. (_("Paint Tool."),
  2825. _("Normal painting area task started."),
  2826. _("Buffering geometry...")))
  2827. else:
  2828. app_obj.inform.emit('%s %s' %
  2829. (_("Paint Tool."), _("Normal painting area task started.")))
  2830. else:
  2831. app_obj.inform.emit('%s %s' %
  2832. (_("Paint Tool."), _("Normal painting area task started.")))
  2833. tool_dia = None
  2834. if order == 'fwd':
  2835. sorted_tools.sort(reverse=False)
  2836. elif order == 'rev':
  2837. sorted_tools.sort(reverse=True)
  2838. else:
  2839. pass
  2840. # this is were heavy lifting is done and creating the geometry to be painted
  2841. target_geo = MultiPolygon(obj.solid_geometry)
  2842. if isinstance(obj, FlatCAMGerber):
  2843. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2844. if isinstance(target_geo, list):
  2845. target_geo = MultiPolygon(target_geo).buffer(0)
  2846. else:
  2847. target_geo = target_geo.buffer(0)
  2848. geo_to_paint = target_geo.intersection(sel_obj)
  2849. painted_area = recurse(geo_to_paint)
  2850. try:
  2851. a, b, c, d = self.paint_bounds(geo_to_paint)
  2852. geo_obj.options['xmin'] = a
  2853. geo_obj.options['ymin'] = b
  2854. geo_obj.options['xmax'] = c
  2855. geo_obj.options['ymax'] = d
  2856. except Exception as e:
  2857. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  2858. return
  2859. total_geometry = []
  2860. current_uid = int(1)
  2861. geo_obj.solid_geometry = []
  2862. for tool_dia in sorted_tools:
  2863. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  2864. app_obj.inform.emit(
  2865. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  2866. str(tool_dia),
  2867. self.units.lower(),
  2868. _('started'))
  2869. )
  2870. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2871. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  2872. for k, v in tools_storage.items():
  2873. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  2874. current_uid = int(k)
  2875. break
  2876. # variables to display the percentage of work done
  2877. geo_len = len(painted_area)
  2878. old_disp_number = 0
  2879. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2880. pol_nr = 0
  2881. for geo in painted_area:
  2882. try:
  2883. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  2884. if not isinstance(geo, Polygon):
  2885. continue
  2886. poly_buf = geo.buffer(-paint_margin)
  2887. cp = None
  2888. if paint_method == _("Seed"):
  2889. # Type(cp) == FlatCAMRTreeStorage | None
  2890. cp = self.clear_polygon2(poly_buf,
  2891. tooldia=tool_dia,
  2892. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2893. overlap=over,
  2894. contour=cont,
  2895. connect=conn,
  2896. prog_plot=prog_plot)
  2897. elif paint_method == _("Lines"):
  2898. # Type(cp) == FlatCAMRTreeStorage | None
  2899. cp = self.clear_polygon3(poly_buf,
  2900. tooldia=tool_dia,
  2901. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2902. overlap=over,
  2903. contour=cont,
  2904. connect=conn,
  2905. prog_plot=prog_plot)
  2906. elif paint_method == _("Standard"):
  2907. # Type(cp) == FlatCAMRTreeStorage | None
  2908. cp = self.clear_polygon(poly_buf,
  2909. tooldia=tool_dia,
  2910. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2911. overlap=over,
  2912. contour=cont,
  2913. connect=conn,
  2914. prog_plot=prog_plot)
  2915. elif paint_method == _("Laser_lines"):
  2916. # line = None
  2917. # aperture_size = None
  2918. # the key is the aperture type and the val is a list of geo elements
  2919. flash_el_dict = dict()
  2920. # the key is the aperture size, the val is a list of geo elements
  2921. traces_el_dict = dict()
  2922. # find the flashes and the lines that are in the selected polygon and store
  2923. # them separately
  2924. for apid, apval in obj.apertures.items():
  2925. for geo_el in apval['geometry']:
  2926. if apval["size"] == 0.0:
  2927. if apval["size"] in traces_el_dict:
  2928. traces_el_dict[apval["size"]].append(geo_el)
  2929. else:
  2930. traces_el_dict[apval["size"]] = [geo_el]
  2931. if 'follow' in geo_el and geo_el['follow'].within(poly_buf):
  2932. if isinstance(geo_el['follow'], Point):
  2933. if apval["type"] == 'C':
  2934. if 'C' in flash_el_dict:
  2935. flash_el_dict['C'].append(geo_el)
  2936. else:
  2937. flash_el_dict['C'] = [geo_el]
  2938. elif apval["type"] == 'O':
  2939. if 'O' in flash_el_dict:
  2940. flash_el_dict['O'].append(geo_el)
  2941. else:
  2942. flash_el_dict['O'] = [geo_el]
  2943. elif apval["type"] == 'R':
  2944. if 'R' in flash_el_dict:
  2945. flash_el_dict['R'].append(geo_el)
  2946. else:
  2947. flash_el_dict['R'] = [geo_el]
  2948. else:
  2949. aperture_size = apval['size']
  2950. if aperture_size in traces_el_dict:
  2951. traces_el_dict[aperture_size].append(geo_el)
  2952. else:
  2953. traces_el_dict[aperture_size] = [geo_el]
  2954. cp = FlatCAMRTreeStorage()
  2955. pads_lines_list = list()
  2956. # process the flashes found in the selected polygon with the 'lines' method
  2957. # for rectangular flashes and with _("Seed") for oblong and circular flashes
  2958. # and pads (flahes) need the contour therefore I override the GUI settings
  2959. # with always True
  2960. for ap_type in flash_el_dict:
  2961. for elem in flash_el_dict[ap_type]:
  2962. if 'solid' in elem:
  2963. if ap_type == 'C':
  2964. f_o = self.clear_polygon2(elem['solid'],
  2965. tooldia=tool_dia,
  2966. steps_per_circle=self.app.defaults[
  2967. "geometry_circle_steps"],
  2968. overlap=over,
  2969. contour=True,
  2970. connect=conn,
  2971. prog_plot=prog_plot)
  2972. pads_lines_list += [p for p in f_o.get_objects() if p]
  2973. elif ap_type == 'O':
  2974. f_o = self.clear_polygon2(elem['solid'],
  2975. tooldia=tool_dia,
  2976. steps_per_circle=self.app.defaults[
  2977. "geometry_circle_steps"],
  2978. overlap=over,
  2979. contour=True,
  2980. connect=conn,
  2981. prog_plot=prog_plot)
  2982. pads_lines_list += [p for p in f_o.get_objects() if p]
  2983. elif ap_type == 'R':
  2984. f_o = self.clear_polygon3(elem['solid'],
  2985. tooldia=tool_dia,
  2986. steps_per_circle=self.app.defaults[
  2987. "geometry_circle_steps"],
  2988. overlap=over,
  2989. contour=True,
  2990. connect=conn,
  2991. prog_plot=prog_plot)
  2992. pads_lines_list += [p for p in f_o.get_objects() if p]
  2993. # add the lines from pads to the storage
  2994. try:
  2995. for lin in pads_lines_list:
  2996. if lin:
  2997. cp.insert(lin)
  2998. except TypeError:
  2999. cp.insert(pads_lines_list)
  3000. copper_lines_list = list()
  3001. # process the traces found in the selected polygon using the 'laser_lines'
  3002. # method, method which will follow the 'follow' line therefore use the longer
  3003. # path possible for the laser, therefore the acceleration will play
  3004. # a smaller factor
  3005. for aperture_size in traces_el_dict:
  3006. for elem in traces_el_dict[aperture_size]:
  3007. line = elem['follow']
  3008. if line:
  3009. t_o = self.fill_with_lines(line, aperture_size,
  3010. tooldia=tool_dia,
  3011. steps_per_circle=self.app.defaults[
  3012. "geometry_circle_steps"],
  3013. overlap=over,
  3014. contour=cont,
  3015. connect=conn,
  3016. prog_plot=prog_plot)
  3017. copper_lines_list += [p for p in t_o.get_objects() if p]
  3018. # add the lines from copper features to storage but first try to make as few
  3019. # lines as possible
  3020. # by trying to fuse them
  3021. lines_union = linemerge(unary_union(copper_lines_list))
  3022. try:
  3023. for lin in lines_union:
  3024. if lin:
  3025. cp.insert(lin)
  3026. except TypeError:
  3027. cp.insert(lines_union)
  3028. elif paint_method == _("Combo"):
  3029. self.app.inform.emit(_("Painting polygons with method: lines."))
  3030. cp = self.clear_polygon3(poly_buf,
  3031. tooldia=tool_dia,
  3032. steps_per_circle=self.app.defaults[
  3033. "geometry_circle_steps"],
  3034. overlap=over,
  3035. contour=cont,
  3036. connect=conn,
  3037. prog_plot=prog_plot)
  3038. if cp and cp.objects:
  3039. pass
  3040. else:
  3041. self.app.inform.emit(_("Failed. Painting polygons with method: seed."))
  3042. cp = self.clear_polygon2(poly_buf,
  3043. tooldia=tool_dia,
  3044. steps_per_circle=self.app.defaults[
  3045. "geometry_circle_steps"],
  3046. overlap=over,
  3047. contour=cont,
  3048. connect=conn,
  3049. prog_plot=prog_plot)
  3050. if cp and cp.objects:
  3051. pass
  3052. else:
  3053. self.app.inform.emit(_("Failed. Painting polygons with method: standard."))
  3054. cp = self.clear_polygon(poly_buf,
  3055. tooldia=tool_dia,
  3056. steps_per_circle=self.app.defaults[
  3057. "geometry_circle_steps"],
  3058. overlap=over,
  3059. contour=cont,
  3060. connect=conn,
  3061. prog_plot=prog_plot)
  3062. if cp and cp.objects:
  3063. total_geometry += list(cp.get_objects())
  3064. except FlatCAMApp.GracefulException:
  3065. return "fail"
  3066. except Exception as e:
  3067. log.debug("Could not Paint the polygons. %s" % str(e))
  3068. self.app.inform.emit('[ERROR] %s\n%s' %
  3069. (_("Could not do Paint All. Try a different combination of parameters. "
  3070. "Or a different Method of paint"), str(e)))
  3071. return
  3072. pol_nr += 1
  3073. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  3074. # log.debug("Polygons cleared: %d" % pol_nr)
  3075. if old_disp_number < disp_number <= 100:
  3076. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  3077. old_disp_number = disp_number
  3078. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  3079. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  3080. # dictionary and then reset the temporary list that stored that solid_geometry
  3081. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  3082. tools_storage[current_uid]['data']['name'] = name
  3083. total_geometry[:] = []
  3084. # clean the progressive plotted shapes if it was used
  3085. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  3086. self.temp_shapes.clear(update=True)
  3087. # delete tools with empty geometry
  3088. keys_to_delete = []
  3089. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  3090. for uid in tools_storage:
  3091. # if the solid_geometry (type=list) is empty
  3092. if not tools_storage[uid]['solid_geometry']:
  3093. keys_to_delete.append(uid)
  3094. # actual delete of keys from the tools_storage dict
  3095. for k in keys_to_delete:
  3096. tools_storage.pop(k, None)
  3097. geo_obj.options["cnctooldia"] = str(tool_dia)
  3098. # this turn on the FlatCAMCNCJob plot for multiple tools
  3099. geo_obj.multigeo = True
  3100. geo_obj.multitool = True
  3101. geo_obj.tools.clear()
  3102. geo_obj.tools = dict(tools_storage)
  3103. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  3104. has_solid_geo = 0
  3105. for tooluid in geo_obj.tools:
  3106. if geo_obj.tools[tooluid]['solid_geometry']:
  3107. has_solid_geo += 1
  3108. if has_solid_geo == 0:
  3109. self.app.inform.emit('[ERROR] %s' %
  3110. _("There is no Painting Geometry in the file.\n"
  3111. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  3112. "Change the painting parameters and try again."))
  3113. return
  3114. # Experimental...
  3115. # print("Indexing...", end=' ')
  3116. # geo_obj.make_index()
  3117. self.app.inform.emit('[success] %s' % _("Paint Area Done."))
  3118. # Initializes the new geometry object
  3119. def gen_paintarea_rest_machining(geo_obj, app_obj):
  3120. assert isinstance(geo_obj, FlatCAMGeometry), \
  3121. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  3122. log.debug("Paint Tool. Rest machining painting area task started.")
  3123. if isinstance(obj, FlatCAMGerber):
  3124. if app_obj.defaults["gerber_buffering"] == 'no':
  3125. app_obj.inform.emit('%s %s %s' %
  3126. (_("Paint Tool."),
  3127. _("Rest machining painting area task started."),
  3128. _("Buffering geometry...")))
  3129. else:
  3130. app_obj.inform.emit(_("Paint Tool. Rest machining painting area task started."))
  3131. else:
  3132. app_obj.inform.emit('%s %s' %
  3133. (_("Paint Tool."), _("Rest machining painting area task started.")))
  3134. tool_dia = None
  3135. sorted_tools.sort(reverse=True)
  3136. cleared_geo = []
  3137. current_uid = int(1)
  3138. geo_obj.solid_geometry = []
  3139. # this is were heavy lifting is done and creating the geometry to be painted
  3140. target_geo = obj.solid_geometry
  3141. if isinstance(obj, FlatCAMGerber):
  3142. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  3143. if isinstance(target_geo, list):
  3144. target_geo = MultiPolygon(target_geo).buffer(0)
  3145. else:
  3146. target_geo = target_geo.buffer(0)
  3147. geo_to_paint = target_geo.intersection(sel_obj)
  3148. painted_area = recurse(geo_to_paint)
  3149. try:
  3150. a, b, c, d = obj.bounds()
  3151. geo_obj.options['xmin'] = a
  3152. geo_obj.options['ymin'] = b
  3153. geo_obj.options['xmax'] = c
  3154. geo_obj.options['ymax'] = d
  3155. except Exception as e:
  3156. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  3157. return
  3158. for tool_dia in sorted_tools:
  3159. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  3160. app_obj.inform.emit(
  3161. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  3162. str(tool_dia),
  3163. self.units.lower(),
  3164. _('started'))
  3165. )
  3166. app_obj.proc_container.update_view_text(' %d%%' % 0)
  3167. # variables to display the percentage of work done
  3168. geo_len = len(painted_area)
  3169. old_disp_number = 0
  3170. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  3171. pol_nr = 0
  3172. for geo in painted_area:
  3173. try:
  3174. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  3175. poly_buf = geo.buffer(-paint_margin)
  3176. cp = None
  3177. if paint_method == _("Standard"):
  3178. # Type(cp) == FlatCAMRTreeStorage | None
  3179. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  3180. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  3181. overlap=over, contour=cont, connect=conn,
  3182. prog_plot=prog_plot)
  3183. elif paint_method == _("Seed"):
  3184. # Type(cp) == FlatCAMRTreeStorage | None
  3185. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  3186. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  3187. overlap=over, contour=cont, connect=conn,
  3188. prog_plot=prog_plot)
  3189. elif paint_method == _("Lines"):
  3190. # Type(cp) == FlatCAMRTreeStorage | None
  3191. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  3192. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  3193. overlap=over, contour=cont, connect=conn,
  3194. prog_plot=prog_plot)
  3195. elif paint_method == _("Laser_lines"):
  3196. # line = None
  3197. # aperture_size = None
  3198. # the key is the aperture type and the val is a list of geo elements
  3199. flash_el_dict = dict()
  3200. # the key is the aperture size, the val is a list of geo elements
  3201. copper_el_dict = dict()
  3202. # find the flashes and the lines that are in the selected polygon and store
  3203. # them separately
  3204. for apid, apval in obj.apertures.items():
  3205. for geo_el in apval['geometry']:
  3206. if apval["size"] == 0.0:
  3207. if apval["size"] in copper_el_dict:
  3208. copper_el_dict[apval["size"]].append(geo_el)
  3209. else:
  3210. copper_el_dict[apval["size"]] = [geo_el]
  3211. if 'follow' in geo_el and geo_el['follow'].within(poly_buf):
  3212. if isinstance(geo_el['follow'], Point):
  3213. if apval["type"] == 'C':
  3214. if 'C' in flash_el_dict:
  3215. flash_el_dict['C'].append(geo_el)
  3216. else:
  3217. flash_el_dict['C'] = [geo_el]
  3218. elif apval["type"] == 'O':
  3219. if 'O' in flash_el_dict:
  3220. flash_el_dict['O'].append(geo_el)
  3221. else:
  3222. flash_el_dict['O'] = [geo_el]
  3223. elif apval["type"] == 'R':
  3224. if 'R' in flash_el_dict:
  3225. flash_el_dict['R'].append(geo_el)
  3226. else:
  3227. flash_el_dict['R'] = [geo_el]
  3228. else:
  3229. aperture_size = apval['size']
  3230. if aperture_size in copper_el_dict:
  3231. copper_el_dict[aperture_size].append(geo_el)
  3232. else:
  3233. copper_el_dict[aperture_size] = [geo_el]
  3234. cp = FlatCAMRTreeStorage()
  3235. pads_lines_list = list()
  3236. # process the flashes found in the selected polygon with the 'lines' method
  3237. # for rectangular flashes and with _("Seed") for oblong and circular flashes
  3238. # and pads (flahes) need the contour therefore I override the GUI settings
  3239. # with always True
  3240. for ap_type in flash_el_dict:
  3241. for elem in flash_el_dict[ap_type]:
  3242. if 'solid' in elem:
  3243. if ap_type == 'C':
  3244. f_o = self.clear_polygon2(elem['solid'],
  3245. tooldia=tool_dia,
  3246. steps_per_circle=self.app.defaults[
  3247. "geometry_circle_steps"],
  3248. overlap=over,
  3249. contour=True,
  3250. connect=conn,
  3251. prog_plot=prog_plot)
  3252. pads_lines_list += [p for p in f_o.get_objects() if p]
  3253. elif ap_type == 'O':
  3254. f_o = self.clear_polygon2(elem['solid'],
  3255. tooldia=tool_dia,
  3256. steps_per_circle=self.app.defaults[
  3257. "geometry_circle_steps"],
  3258. overlap=over,
  3259. contour=True,
  3260. connect=conn,
  3261. prog_plot=prog_plot)
  3262. pads_lines_list += [p for p in f_o.get_objects() if p]
  3263. elif ap_type == 'R':
  3264. f_o = self.clear_polygon3(elem['solid'],
  3265. tooldia=tool_dia,
  3266. steps_per_circle=self.app.defaults[
  3267. "geometry_circle_steps"],
  3268. overlap=over,
  3269. contour=True,
  3270. connect=conn,
  3271. prog_plot=prog_plot)
  3272. pads_lines_list += [p for p in f_o.get_objects() if p]
  3273. # add the lines from pads to the storage
  3274. try:
  3275. for lin in pads_lines_list:
  3276. if lin:
  3277. cp.insert(lin)
  3278. except TypeError:
  3279. cp.insert(pads_lines_list)
  3280. copper_lines_list = list()
  3281. # process the traces found in the selected polygon using the 'laser_lines'
  3282. # method, method which will follow the 'follow' line therefore use the longer
  3283. # path possible for the laser, therefore the acceleration will play
  3284. # a smaller factor
  3285. for aperture_size in copper_el_dict:
  3286. for elem in copper_el_dict[aperture_size]:
  3287. line = elem['follow']
  3288. if line:
  3289. t_o = self.fill_with_lines(line, aperture_size,
  3290. tooldia=tool_dia,
  3291. steps_per_circle=self.app.defaults[
  3292. "geometry_circle_steps"],
  3293. overlap=over,
  3294. contour=cont,
  3295. connect=conn,
  3296. prog_plot=prog_plot)
  3297. copper_lines_list += [p for p in t_o.get_objects() if p]
  3298. # add the lines from copper features to storage but first try to make as few
  3299. # lines as possible
  3300. # by trying to fuse them
  3301. lines_union = linemerge(unary_union(copper_lines_list))
  3302. try:
  3303. for lin in lines_union:
  3304. if lin:
  3305. cp.insert(lin)
  3306. except TypeError:
  3307. cp.insert(lines_union)
  3308. elif paint_method == _("Combo"):
  3309. self.app.inform.emit(_("Painting polygons with method: lines."))
  3310. cp = self.clear_polygon3(poly_buf,
  3311. tooldia=tool_dia,
  3312. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  3313. overlap=over,
  3314. contour=cont,
  3315. connect=conn,
  3316. prog_plot=prog_plot)
  3317. if cp and cp.objects:
  3318. pass
  3319. else:
  3320. self.app.inform.emit(_("Failed. Painting polygons with method: seed."))
  3321. cp = self.clear_polygon2(poly_buf,
  3322. tooldia=tool_dia,
  3323. steps_per_circle=self.app.defaults[
  3324. "geometry_circle_steps"],
  3325. overlap=over,
  3326. contour=cont,
  3327. connect=conn,
  3328. prog_plot=prog_plot)
  3329. if cp and cp.objects:
  3330. pass
  3331. else:
  3332. self.app.inform.emit(_("Failed. Painting polygons with method: standard."))
  3333. cp = self.clear_polygon(poly_buf,
  3334. tooldia=tool_dia,
  3335. steps_per_circle=self.app.defaults[
  3336. "geometry_circle_steps"],
  3337. overlap=over,
  3338. contour=cont,
  3339. connect=conn,
  3340. prog_plot=prog_plot)
  3341. if cp and cp.objects:
  3342. cleared_geo += list(cp.get_objects())
  3343. except FlatCAMApp.GracefulException:
  3344. return "fail"
  3345. except Exception as e:
  3346. log.debug("Could not Paint the polygons. %s" % str(e))
  3347. self.app.inform.emit('[ERROR] %s\n%s' %
  3348. (_("Could not do Paint All. Try a different combination of parameters. "
  3349. "Or a different Method of paint"), str(e)))
  3350. return
  3351. pol_nr += 1
  3352. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  3353. # log.debug("Polygons cleared: %d" % pol_nr)
  3354. if old_disp_number < disp_number <= 100:
  3355. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  3356. old_disp_number = disp_number
  3357. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  3358. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  3359. for k, v in tools_storage.items():
  3360. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  3361. current_uid = int(k)
  3362. break
  3363. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  3364. # then reset the temporary list that stored that solid_geometry
  3365. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  3366. tools_storage[current_uid]['data']['name'] = name
  3367. cleared_geo[:] = []
  3368. geo_obj.options["cnctooldia"] = str(tool_dia)
  3369. # this turn on the FlatCAMCNCJob plot for multiple tools
  3370. geo_obj.multigeo = True
  3371. geo_obj.multitool = True
  3372. geo_obj.tools.clear()
  3373. geo_obj.tools = dict(self.paint_tools)
  3374. # clean the progressive plotted shapes if it was used
  3375. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  3376. self.temp_shapes.clear(update=True)
  3377. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  3378. has_solid_geo = 0
  3379. for tooluid in geo_obj.tools:
  3380. if geo_obj.tools[tooluid]['solid_geometry']:
  3381. has_solid_geo += 1
  3382. if has_solid_geo == 0:
  3383. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3384. _("There is no Painting Geometry in the file.\n"
  3385. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  3386. "Change the painting parameters and try again."))
  3387. return
  3388. # Experimental...
  3389. # print("Indexing...", end=' ')
  3390. # geo_obj.make_index()
  3391. self.app.inform.emit('[success] %s' % _("Paint All with Rest-Machining done."))
  3392. def job_thread(app_obj):
  3393. try:
  3394. if self.rest_cb.isChecked():
  3395. app_obj.new_object("geometry", name, gen_paintarea_rest_machining, plot=plot)
  3396. else:
  3397. app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  3398. except FlatCAMApp.GracefulException:
  3399. proc.done()
  3400. return
  3401. except Exception:
  3402. proc.done()
  3403. traceback.print_stack()
  3404. return
  3405. proc.done()
  3406. # focus on Selected Tab
  3407. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  3408. self.app.inform.emit(_("Polygon Paint started ..."))
  3409. # Promise object with the new name
  3410. self.app.collection.promise(name)
  3411. if run_threaded:
  3412. # Background
  3413. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3414. else:
  3415. job_thread(app_obj=self.app)
  3416. def paint_poly_ref(self, obj, sel_obj,
  3417. tooldia=None,
  3418. overlap=None,
  3419. order=None,
  3420. margin=None,
  3421. method=None,
  3422. outname=None,
  3423. connect=None,
  3424. contour=None,
  3425. tools_storage=None,
  3426. plot=True,
  3427. run_threaded=True):
  3428. """
  3429. Paints all polygons in this object that are within the sel_obj object
  3430. :param run_threaded:
  3431. :param plot:
  3432. :param obj: painted object
  3433. :param sel_obj: paint only what is inside this object bounds
  3434. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  3435. :param overlap: value by which the paths will overlap
  3436. :param order: if the tools are ordered and how
  3437. :param margin: a border around painting area
  3438. :param outname: name of the resulting object
  3439. :param connect: Connect lines to avoid tool lifts.
  3440. :param contour: Paint around the edges.
  3441. :param method: choice out of _("Seed"), 'normal', 'lines'
  3442. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  3443. Usage of the different one is related to when this function is called from a TcL command.
  3444. :return:
  3445. """
  3446. geo = sel_obj.solid_geometry
  3447. try:
  3448. if isinstance(geo, MultiPolygon):
  3449. env_obj = geo.convex_hull
  3450. elif (isinstance(geo, MultiPolygon) and len(geo) == 1) or \
  3451. (isinstance(geo, list) and len(geo) == 1) and isinstance(geo[0], Polygon):
  3452. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  3453. else:
  3454. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  3455. env_obj = env_obj.convex_hull
  3456. sel_rect = env_obj.buffer(distance=0.0000001, join_style=base.JOIN_STYLE.mitre)
  3457. except Exception as e:
  3458. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  3459. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  3460. return
  3461. self.paint_poly_area(obj=obj,
  3462. sel_obj=sel_rect,
  3463. tooldia=tooldia,
  3464. overlap=overlap,
  3465. order=order,
  3466. margin=margin,
  3467. method=method,
  3468. outname=outname,
  3469. connect=connect,
  3470. contour=contour,
  3471. tools_storage=tools_storage,
  3472. plot=plot,
  3473. run_threaded=run_threaded)
  3474. def ui_connect(self):
  3475. self.tools_table.itemChanged.connect(self.on_tool_edit)
  3476. # rows selected
  3477. self.tools_table.clicked.connect(self.on_row_selection_change)
  3478. self.tools_table.horizontalHeader().sectionClicked.connect(self.on_row_selection_change)
  3479. for row in range(self.tools_table.rowCount()):
  3480. try:
  3481. self.tools_table.cellWidget(row, 2).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  3482. except AttributeError:
  3483. pass
  3484. try:
  3485. self.tools_table.cellWidget(row, 4).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  3486. except AttributeError:
  3487. pass
  3488. self.tool_type_radio.activated_custom.connect(self.on_tool_type)
  3489. # first disconnect
  3490. for opt in self.form_fields:
  3491. current_widget = self.form_fields[opt]
  3492. if isinstance(current_widget, FCCheckBox):
  3493. try:
  3494. current_widget.stateChanged.disconnect()
  3495. except (TypeError, ValueError):
  3496. pass
  3497. if isinstance(current_widget, RadioSet):
  3498. try:
  3499. current_widget.activated_custom.disconnect()
  3500. except (TypeError, ValueError):
  3501. pass
  3502. elif isinstance(current_widget, FCDoubleSpinner):
  3503. try:
  3504. current_widget.returnPressed.disconnect()
  3505. except (TypeError, ValueError):
  3506. pass
  3507. # then reconnect
  3508. for opt in self.form_fields:
  3509. current_widget = self.form_fields[opt]
  3510. if isinstance(current_widget, FCCheckBox):
  3511. current_widget.stateChanged.connect(self.form_to_storage)
  3512. if isinstance(current_widget, RadioSet):
  3513. current_widget.activated_custom.connect(self.form_to_storage)
  3514. elif isinstance(current_widget, FCDoubleSpinner):
  3515. current_widget.returnPressed.connect(self.form_to_storage)
  3516. elif isinstance(current_widget, FCComboBox):
  3517. current_widget.currentIndexChanged.connect(self.form_to_storage)
  3518. self.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  3519. self.order_radio.activated_custom[str].connect(self.on_order_changed)
  3520. def ui_disconnect(self):
  3521. try:
  3522. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  3523. self.tools_table.itemChanged.disconnect()
  3524. except (TypeError, AttributeError):
  3525. pass
  3526. # rows selected
  3527. try:
  3528. self.tools_table.clicked.disconnect(self.on_row_selection_change)
  3529. except (TypeError, AttributeError):
  3530. pass
  3531. try:
  3532. self.tools_table.horizontalHeader().sectionClicked.disconnect(self.on_row_selection_change)
  3533. except (TypeError, AttributeError):
  3534. pass
  3535. try:
  3536. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  3537. self.tool_type_radio.activated_custom.disconnect()
  3538. except (TypeError, AttributeError):
  3539. pass
  3540. for row in range(self.tools_table.rowCount()):
  3541. for col in [2, 4]:
  3542. try:
  3543. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  3544. except (TypeError, AttributeError):
  3545. pass
  3546. for opt in self.form_fields:
  3547. current_widget = self.form_fields[opt]
  3548. if isinstance(current_widget, FCCheckBox):
  3549. try:
  3550. current_widget.stateChanged.disconnect(self.form_to_storage)
  3551. except (TypeError, ValueError):
  3552. pass
  3553. if isinstance(current_widget, RadioSet):
  3554. try:
  3555. current_widget.activated_custom.disconnect(self.form_to_storage)
  3556. except (TypeError, ValueError):
  3557. pass
  3558. elif isinstance(current_widget, FCDoubleSpinner):
  3559. try:
  3560. current_widget.returnPressed.disconnect(self.form_to_storage)
  3561. except (TypeError, ValueError):
  3562. pass
  3563. elif isinstance(current_widget, FCComboBox):
  3564. try:
  3565. current_widget.currentIndexChanged.connect(self.form_to_storage)
  3566. except (TypeError, ValueError):
  3567. pass
  3568. def reset_usage(self):
  3569. self.obj_name = ""
  3570. self.paint_obj = None
  3571. self.bound_obj = None
  3572. self.first_click = False
  3573. self.cursor_pos = None
  3574. self.mouse_is_dragging = False
  3575. self.sel_rect = []
  3576. @staticmethod
  3577. def paint_bounds(geometry):
  3578. def bounds_rec(o):
  3579. if type(o) is list:
  3580. minx = Inf
  3581. miny = Inf
  3582. maxx = -Inf
  3583. maxy = -Inf
  3584. for k in o:
  3585. try:
  3586. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  3587. except Exception as e:
  3588. log.debug("ToolPaint.bounds() --> %s" % str(e))
  3589. return
  3590. minx = min(minx, minx_)
  3591. miny = min(miny, miny_)
  3592. maxx = max(maxx, maxx_)
  3593. maxy = max(maxy, maxy_)
  3594. return minx, miny, maxx, maxy
  3595. else:
  3596. # it's a Shapely object, return it's bounds
  3597. return o.bounds
  3598. return bounds_rec(geometry)
  3599. def reset_fields(self):
  3600. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))