ToolNCC.py 192 KB

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