ToolPaint.py 212 KB

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