ToolNCC.py 193 KB

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