ToolNonCopperClear.py 183 KB

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