ToolPaint.py 210 KB

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