ToolNonCopperClear.py 179 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753
  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_tooldia_updated)
  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. def on_type_obj_index_changed(self, index):
  575. obj_type = self.type_obj_combo.currentIndex()
  576. self.object_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  577. self.object_combo.setCurrentIndex(0)
  578. def on_row_selection_change(self):
  579. self.update_ui()
  580. def update_ui(self, row=None):
  581. self.blockSignals(True)
  582. if row is None:
  583. try:
  584. current_row = self.tools_table.currentRow()
  585. except Exception:
  586. current_row = 0
  587. else:
  588. current_row = row
  589. if current_row < 0:
  590. current_row = 0
  591. # populate the form with the data from the tool associated with the row parameter
  592. try:
  593. item = self.tools_table.item(current_row, 3)
  594. if item is not None:
  595. tooluid = int(item.text())
  596. else:
  597. return
  598. except Exception as e:
  599. log.debug("Tool missing. Add a tool in the Tool Table. %s" % str(e))
  600. return
  601. # update the QLabel that shows for which Tool we have the parameters in the UI form
  602. self.tool_data_label.setText(
  603. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), (current_row + 1))
  604. )
  605. try:
  606. # set the form with data from the newly selected tool
  607. for tooluid_key, tooluid_value in list(self.ncc_tools.items()):
  608. if int(tooluid_key) == tooluid:
  609. for key, value in tooluid_value.items():
  610. if key == 'data':
  611. form_value_storage = tooluid_value[key]
  612. self.storage_to_form(form_value_storage)
  613. except Exception as e:
  614. log.debug("NonCopperClear ---> update_ui() " + str(e))
  615. self.blockSignals(False)
  616. def storage_to_form(self, dict_storage):
  617. for form_key in self.form_fields:
  618. for storage_key in dict_storage:
  619. if form_key == storage_key:
  620. try:
  621. self.form_fields[form_key].set_value(dict_storage[form_key])
  622. except Exception:
  623. pass
  624. def form_to_storage(self):
  625. if self.tools_table.rowCount() == 0:
  626. # there is no tool in tool table so we can't save the GUI elements values to storage
  627. return
  628. self.blockSignals(True)
  629. widget_changed = self.sender()
  630. wdg_objname = widget_changed.objectName()
  631. option_changed = self.name2option[wdg_objname]
  632. row = self.tools_table.currentRow()
  633. if row < 0:
  634. row = 0
  635. tooluid_item = int(self.tools_table.item(row, 3).text())
  636. for tooluid_key, tooluid_val in self.ncc_tools.items():
  637. if int(tooluid_key) == tooluid_item:
  638. new_option_value = self.form_fields[option_changed].get_value()
  639. if option_changed in tooluid_val:
  640. tooluid_val[option_changed] = new_option_value
  641. if option_changed in tooluid_val['data']:
  642. tooluid_val['data'][option_changed] = new_option_value
  643. self.blockSignals(False)
  644. def on_apply_param_to_all_clicked(self):
  645. if self.tools_table.rowCount() == 0:
  646. # there is no tool in tool table so we can't save the GUI elements values to storage
  647. log.debug("NonCopperClear.on_apply_param_to_all_clicked() --> no tool in Tools Table, aborting.")
  648. return
  649. self.blockSignals(True)
  650. row = self.tools_table.currentRow()
  651. if row < 0:
  652. row = 0
  653. # store all the data associated with the row parameter to the self.tools storage
  654. tooldia_item = float(self.tools_table.item(row, 1).text())
  655. type_item = self.tools_table.cellWidget(row, 2).currentText()
  656. operation_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  657. nccoffset_item = self.ncc_choice_offset_cb.get_value()
  658. nccoffset_value_item = float(self.ncc_offset_spinner.get_value())
  659. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  660. temp_tools = {}
  661. temp_dia = {}
  662. temp_data = {}
  663. for tooluid_key, tooluid_value in self.ncc_tools.items():
  664. for key, value in tooluid_value.items():
  665. if key == 'data':
  666. # update the 'data' section
  667. for data_key in tooluid_value[key].keys():
  668. for form_key, form_value in self.form_fields.items():
  669. if form_key == data_key:
  670. temp_data[data_key] = form_value.get_value()
  671. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  672. # updated from self.app.defaults
  673. if data_key not in self.form_fields:
  674. temp_data[data_key] = value[data_key]
  675. temp_dia[key] = deepcopy(temp_data)
  676. temp_data.clear()
  677. elif key == 'solid_geometry':
  678. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  679. else:
  680. temp_dia[key] = deepcopy(value)
  681. temp_tools[tooluid_key] = deepcopy(temp_dia)
  682. self.ncc_tools.clear()
  683. self.ncc_tools = deepcopy(temp_tools)
  684. temp_tools.clear()
  685. self.blockSignals(False)
  686. def on_add_tool_by_key(self):
  687. tool_add_popup = FCInputDialog(title='%s...' % _("New Tool"),
  688. text='%s:' % _('Enter a Tool Diameter'),
  689. min=0.0001, max=9999.9999, decimals=self.decimals)
  690. tool_add_popup.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/letter_t_32.png'))
  691. val, ok = tool_add_popup.get_value()
  692. if ok:
  693. if float(val) == 0:
  694. self.app.inform.emit('[WARNING_NOTCL] %s' %
  695. _("Please enter a tool diameter with non-zero value, in Float format."))
  696. return
  697. self.on_tool_add(dia=float(val))
  698. else:
  699. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  700. def install(self, icon=None, separator=None, **kwargs):
  701. FlatCAMTool.install(self, icon, separator, shortcut='ALT+N', **kwargs)
  702. def run(self, toggle=True):
  703. self.app.report_usage("ToolNonCopperClear()")
  704. if toggle:
  705. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  706. if self.app.ui.splitter.sizes()[0] == 0:
  707. self.app.ui.splitter.setSizes([1, 1])
  708. else:
  709. try:
  710. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  711. # if tab is populated with the tool but it does not have the focus, focus on it
  712. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  713. # focus on Tool Tab
  714. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  715. else:
  716. self.app.ui.splitter.setSizes([0, 1])
  717. except AttributeError:
  718. pass
  719. else:
  720. if self.app.ui.splitter.sizes()[0] == 0:
  721. self.app.ui.splitter.setSizes([1, 1])
  722. FlatCAMTool.run(self)
  723. self.set_tool_ui()
  724. # reset those objects on a new run
  725. self.ncc_obj = None
  726. self.bound_obj = None
  727. self.obj_name = ''
  728. self.bound_obj_name = ''
  729. self.build_ui()
  730. self.app.ui.notebook.setTabText(2, _("NCC Tool"))
  731. def set_tool_ui(self):
  732. self.units = self.app.defaults['units'].upper()
  733. self.old_tool_dia = self.app.defaults["tools_nccnewdia"]
  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. # rows selected
  895. self.tools_table.clicked.connect(self.on_row_selection_change)
  896. self.tools_table.horizontalHeader().sectionClicked.connect(self.on_row_selection_change)
  897. for row in range(self.tools_table.rowCount()):
  898. try:
  899. self.tools_table.cellWidget(row, 2).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  900. except AttributeError:
  901. pass
  902. try:
  903. self.tools_table.cellWidget(row, 4).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  904. except AttributeError:
  905. pass
  906. self.tool_type_radio.activated_custom.connect(self.on_tool_type)
  907. # first disconnect
  908. for opt in self.form_fields:
  909. current_widget = self.form_fields[opt]
  910. if isinstance(current_widget, FCCheckBox):
  911. try:
  912. current_widget.stateChanged.disconnect()
  913. except (TypeError, ValueError):
  914. pass
  915. if isinstance(current_widget, RadioSet):
  916. try:
  917. current_widget.activated_custom.disconnect()
  918. except (TypeError, ValueError):
  919. pass
  920. elif isinstance(current_widget, FCDoubleSpinner):
  921. try:
  922. current_widget.returnPressed.disconnect()
  923. except (TypeError, ValueError):
  924. pass
  925. try:
  926. self.ncc_rest_cb.stateChanged.disconnect()
  927. except (TypeError, ValueError):
  928. pass
  929. try:
  930. self.ncc_order_radio.activated_custom[str].disconnect()
  931. except (TypeError, ValueError):
  932. pass
  933. # then reconnect
  934. for opt in self.form_fields:
  935. current_widget = self.form_fields[opt]
  936. if isinstance(current_widget, FCCheckBox):
  937. current_widget.stateChanged.connect(self.form_to_storage)
  938. if isinstance(current_widget, RadioSet):
  939. current_widget.activated_custom.connect(self.form_to_storage)
  940. elif isinstance(current_widget, FCDoubleSpinner):
  941. current_widget.returnPressed.connect(self.form_to_storage)
  942. self.ncc_rest_cb.stateChanged.connect(self.on_rest_machining_check)
  943. self.ncc_order_radio.activated_custom[str].connect(self.on_order_changed)
  944. def ui_disconnect(self):
  945. try:
  946. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  947. self.tools_table.itemChanged.disconnect()
  948. except (TypeError, AttributeError):
  949. pass
  950. try:
  951. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  952. self.tool_type_radio.activated_custom.disconnect()
  953. except (TypeError, AttributeError):
  954. pass
  955. for row in range(self.tools_table.rowCount()):
  956. for col in [2, 4]:
  957. try:
  958. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  959. except (TypeError, AttributeError):
  960. pass
  961. for opt in self.form_fields:
  962. current_widget = self.form_fields[opt]
  963. if isinstance(current_widget, FCCheckBox):
  964. try:
  965. current_widget.stateChanged.disconnect()
  966. except (TypeError, ValueError):
  967. pass
  968. if isinstance(current_widget, RadioSet):
  969. try:
  970. current_widget.activated_custom.disconnect()
  971. except (TypeError, ValueError):
  972. pass
  973. elif isinstance(current_widget, FCDoubleSpinner):
  974. try:
  975. current_widget.returnPressed.disconnect()
  976. except (TypeError, ValueError):
  977. pass
  978. try:
  979. self.ncc_rest_cb.stateChanged.disconnect()
  980. except (TypeError, ValueError):
  981. pass
  982. try:
  983. self.ncc_order_radio.activated_custom[str].disconnect()
  984. except (TypeError, ValueError):
  985. pass
  986. # rows selected
  987. try:
  988. self.tools_table.clicked.disconnect()
  989. except (TypeError, AttributeError):
  990. pass
  991. try:
  992. self.tools_table.horizontalHeader().sectionClicked.disconnect()
  993. except (TypeError, AttributeError):
  994. pass
  995. def on_tooldia_updated(self):
  996. if self.tool_type_radio.get_value() == 'C1':
  997. self.old_tool_dia = self.addtool_entry.get_value()
  998. def on_combo_box_type(self):
  999. obj_type = self.box_combo_type.currentIndex()
  1000. self.box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  1001. self.box_combo.setCurrentIndex(0)
  1002. def on_toggle_reference(self):
  1003. if self.reference_radio.get_value() == "itself" or self.reference_radio.get_value() == "area":
  1004. self.box_combo.hide()
  1005. self.box_combo_label.hide()
  1006. self.box_combo_type.hide()
  1007. self.box_combo_type_label.hide()
  1008. else:
  1009. self.box_combo.show()
  1010. self.box_combo_label.show()
  1011. self.box_combo_type.show()
  1012. self.box_combo_type_label.show()
  1013. def on_offset_choice(self, state):
  1014. # if state:
  1015. # self.ncc_offset_label.show()
  1016. # self.ncc_offset_spinner.show()
  1017. # else:
  1018. # self.ncc_offset_label.hide()
  1019. # self.ncc_offset_spinner.hide()
  1020. self.ncc_offset_spinner.setEnabled(state)
  1021. def on_order_changed(self, order):
  1022. if order != 'no':
  1023. self.build_ui()
  1024. def on_rest_machining_check(self, state):
  1025. if state:
  1026. self.ncc_order_radio.set_value('rev')
  1027. self.ncc_order_label.setDisabled(True)
  1028. self.ncc_order_radio.setDisabled(True)
  1029. else:
  1030. self.ncc_order_label.setDisabled(False)
  1031. self.ncc_order_radio.setDisabled(False)
  1032. def on_tooltable_cellwidget_change(self):
  1033. cw = self.sender()
  1034. cw_index = self.tools_table.indexAt(cw.pos())
  1035. cw_row = cw_index.row()
  1036. cw_col = cw_index.column()
  1037. current_uid = int(self.tools_table.item(cw_row, 3).text())
  1038. # if the sender is in the column with index 2 then we update the tool_type key
  1039. if cw_col == 2:
  1040. tt = cw.currentText()
  1041. typ = 'Iso' if tt == 'V' else "Rough"
  1042. self.ncc_tools[current_uid].update({
  1043. 'type': typ,
  1044. 'tool_type': tt,
  1045. })
  1046. if cw_col == 4:
  1047. op = cw.currentText()
  1048. if op == 'iso_op':
  1049. self.milling_type_label.show()
  1050. self.milling_type_radio.show()
  1051. else:
  1052. self.milling_type_label.hide()
  1053. self.milling_type_radio.hide()
  1054. self.ncc_tools[current_uid].update({
  1055. 'operation': op
  1056. })
  1057. def on_tool_type(self, val):
  1058. if val == 'V':
  1059. self.addtool_entry_lbl.setDisabled(True)
  1060. self.addtool_entry.setDisabled(True)
  1061. self.tipdialabel.show()
  1062. self.tipdia_entry.show()
  1063. self.tipanglelabel.show()
  1064. self.tipangle_entry.show()
  1065. self.on_calculate_tooldia()
  1066. else:
  1067. self.addtool_entry_lbl.setDisabled(False)
  1068. self.addtool_entry.setDisabled(False)
  1069. self.tipdialabel.hide()
  1070. self.tipdia_entry.hide()
  1071. self.tipanglelabel.hide()
  1072. self.tipangle_entry.hide()
  1073. self.addtool_entry.set_value(self.old_tool_dia)
  1074. def on_calculate_tooldia(self):
  1075. if self.tool_type_radio.get_value() == 'V':
  1076. tip_dia = float(self.tipdia_entry.get_value())
  1077. tip_angle = float(self.tipangle_entry.get_value()) / 2.0
  1078. cut_z = float(self.cutz_entry.get_value())
  1079. cut_z = -cut_z if cut_z < 0 else cut_z
  1080. # calculated tool diameter so the cut_z parameter is obeyed
  1081. tool_dia = tip_dia + (2 * cut_z * math.tan(math.radians(tip_angle)))
  1082. # update the default_data so it is used in the ncc_tools dict
  1083. self.default_data.update({
  1084. "vtipdia": tip_dia,
  1085. "vtipangle": (tip_angle * 2),
  1086. })
  1087. self.addtool_entry.set_value(tool_dia)
  1088. return tool_dia
  1089. else:
  1090. return float(self.addtool_entry.get_value())
  1091. def on_tool_add(self, dia=None, muted=None):
  1092. self.blockSignals(True)
  1093. self.units = self.app.defaults['units'].upper()
  1094. if dia:
  1095. tool_dia = dia
  1096. else:
  1097. tool_dia = self.on_calculate_tooldia()
  1098. if tool_dia is None:
  1099. self.build_ui()
  1100. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter to add, in Float format."))
  1101. return
  1102. tool_dia = float('%.*f' % (self.decimals, tool_dia))
  1103. if tool_dia == 0:
  1104. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter with non-zero value, "
  1105. "in Float format."))
  1106. return
  1107. # construct a list of all 'tooluid' in the self.tools
  1108. tool_uid_list = []
  1109. for tooluid_key in self.ncc_tools:
  1110. tool_uid_item = int(tooluid_key)
  1111. tool_uid_list.append(tool_uid_item)
  1112. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  1113. if not tool_uid_list:
  1114. max_uid = 0
  1115. else:
  1116. max_uid = max(tool_uid_list)
  1117. self.tooluid = int(max_uid + 1)
  1118. tool_dias = []
  1119. for k, v in self.ncc_tools.items():
  1120. for tool_v in v.keys():
  1121. if tool_v == 'tooldia':
  1122. tool_dias.append(float('%.*f' % (self.decimals, (v[tool_v]))))
  1123. if float('%.*f' % (self.decimals, tool_dia)) in tool_dias:
  1124. if muted is None:
  1125. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Adding tool cancelled. Tool already in Tool Table."))
  1126. # self.tools_table.itemChanged.connect(self.on_tool_edit)
  1127. self.blockSignals(False)
  1128. return
  1129. else:
  1130. if muted is None:
  1131. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  1132. self.ncc_tools.update({
  1133. int(self.tooluid): {
  1134. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  1135. 'offset': 'Path',
  1136. 'offset_value': 0.0,
  1137. 'type': 'Iso',
  1138. 'tool_type': self.tool_type_radio.get_value(),
  1139. 'operation': 'clear_op',
  1140. 'data': deepcopy(self.default_data),
  1141. 'solid_geometry': []
  1142. }
  1143. })
  1144. self.blockSignals(False)
  1145. self.build_ui()
  1146. def on_tool_edit(self):
  1147. self.blockSignals(True)
  1148. old_tool_dia = ''
  1149. tool_dias = []
  1150. for k, v in self.ncc_tools.items():
  1151. for tool_v in v.keys():
  1152. if tool_v == 'tooldia':
  1153. tool_dias.append(float('%.*f' % (self.decimals, v[tool_v])))
  1154. for row in range(self.tools_table.rowCount()):
  1155. try:
  1156. new_tool_dia = float(self.tools_table.item(row, 1).text())
  1157. except ValueError:
  1158. # try to convert comma to decimal point. if it's still not working error message and return
  1159. try:
  1160. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  1161. except ValueError:
  1162. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1163. self.blockSignals(False)
  1164. return
  1165. tooluid = int(self.tools_table.item(row, 3).text())
  1166. # identify the tool that was edited and get it's tooluid
  1167. if new_tool_dia not in tool_dias:
  1168. self.ncc_tools[tooluid]['tooldia'] = new_tool_dia
  1169. self.app.inform.emit('[success] %s' % _("Tool from Tool Table was edited."))
  1170. self.blockSignals(False)
  1171. self.build_ui()
  1172. return
  1173. else:
  1174. # identify the old tool_dia and restore the text in tool table
  1175. for k, v in self.ncc_tools.items():
  1176. if k == tooluid:
  1177. old_tool_dia = v['tooldia']
  1178. break
  1179. restore_dia_item = self.tools_table.item(row, 1)
  1180. restore_dia_item.setText(str(old_tool_dia))
  1181. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Edit cancelled. "
  1182. "New diameter value is already in the Tool Table."))
  1183. self.blockSignals(False)
  1184. self.build_ui()
  1185. def on_tool_delete(self, rows_to_delete=None, all_tools=None):
  1186. """
  1187. Will delete a tool in the tool table
  1188. :param rows_to_delete: which rows to delete; can be a list
  1189. :param all_tools: delete all tools in the tool table
  1190. :return:
  1191. """
  1192. self.blockSignals(True)
  1193. deleted_tools_list = []
  1194. if all_tools:
  1195. self.ncc_tools.clear()
  1196. self.blockSignals(False)
  1197. self.build_ui()
  1198. return
  1199. if rows_to_delete:
  1200. try:
  1201. for row in rows_to_delete:
  1202. tooluid_del = int(self.tools_table.item(row, 3).text())
  1203. deleted_tools_list.append(tooluid_del)
  1204. except TypeError:
  1205. tooluid_del = int(self.tools_table.item(rows_to_delete, 3).text())
  1206. deleted_tools_list.append(tooluid_del)
  1207. for t in deleted_tools_list:
  1208. self.ncc_tools.pop(t, None)
  1209. self.blockSignals(False)
  1210. self.build_ui()
  1211. return
  1212. try:
  1213. if self.tools_table.selectedItems():
  1214. for row_sel in self.tools_table.selectedItems():
  1215. row = row_sel.row()
  1216. if row < 0:
  1217. continue
  1218. tooluid_del = int(self.tools_table.item(row, 3).text())
  1219. deleted_tools_list.append(tooluid_del)
  1220. for t in deleted_tools_list:
  1221. self.ncc_tools.pop(t, None)
  1222. except AttributeError:
  1223. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Delete failed. Select a tool to delete."))
  1224. self.blockSignals(False)
  1225. return
  1226. except Exception as e:
  1227. log.debug(str(e))
  1228. self.app.inform.emit('[success] %s' % _("Tool(s) deleted from Tool Table."))
  1229. self.blockSignals(False)
  1230. self.build_ui()
  1231. def on_ncc_click(self):
  1232. """
  1233. Slot for clicking signal of the self.generate.ncc_button
  1234. :return: None
  1235. """
  1236. # init values for the next usage
  1237. self.reset_usage()
  1238. self.app.report_usage("on_paint_button_click")
  1239. self.grb_circle_steps = int(self.app.defaults["gerber_circle_steps"])
  1240. self.obj_name = self.object_combo.currentText()
  1241. # Get source object.
  1242. try:
  1243. self.ncc_obj = self.app.collection.get_by_name(self.obj_name)
  1244. except Exception as e:
  1245. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  1246. return "Could not retrieve object: %s with error: %s" % (self.obj_name, str(e))
  1247. if self.ncc_obj is None:
  1248. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(self.obj_name)))
  1249. return
  1250. # use the selected tools in the tool table; get diameters for non-copper clear
  1251. self.iso_dia_list = list()
  1252. # use the selected tools in the tool table; get diameters for non-copper clear
  1253. self.ncc_dia_list = list()
  1254. if self.tools_table.selectedItems():
  1255. for x in self.tools_table.selectedItems():
  1256. try:
  1257. self.tooldia = float(self.tools_table.item(x.row(), 1).text())
  1258. except ValueError:
  1259. # try to convert comma to decimal point. if it's still not working error message and return
  1260. try:
  1261. self.tooldia = float(self.tools_table.item(x.row(), 1).text().replace(',', '.'))
  1262. except ValueError:
  1263. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong Tool Dia value format entered, "
  1264. "use a number."))
  1265. continue
  1266. if self.tools_table.cellWidget(x.row(), 4).currentText() == 'iso_op':
  1267. self.iso_dia_list.append(self.tooldia)
  1268. else:
  1269. self.ncc_dia_list.append(self.tooldia)
  1270. else:
  1271. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No selected tools in Tool Table."))
  1272. return
  1273. self.o_name = '%s_ncc' % self.obj_name
  1274. self.select_method = self.reference_radio.get_value()
  1275. if self.select_method == 'itself':
  1276. self.bound_obj_name = self.object_combo.currentText()
  1277. # Get source object.
  1278. try:
  1279. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  1280. except Exception as e:
  1281. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.bound_obj_name))
  1282. return "Could not retrieve object: %s with error: %s" % (self.bound_obj_name, str(e))
  1283. self.clear_copper(ncc_obj=self.ncc_obj,
  1284. ncctooldia=self.ncc_dia_list,
  1285. isotooldia=self.iso_dia_list,
  1286. outname=self.o_name)
  1287. elif self.select_method == 'area':
  1288. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the area."))
  1289. if self.app.is_legacy is False:
  1290. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1291. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1292. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1293. else:
  1294. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  1295. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  1296. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  1297. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  1298. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  1299. elif self.select_method == 'box':
  1300. self.bound_obj_name = self.box_combo.currentText()
  1301. # Get source object.
  1302. try:
  1303. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  1304. except Exception as e:
  1305. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.bound_obj_name))
  1306. return "Could not retrieve object: %s. Error: %s" % (self.bound_obj_name, str(e))
  1307. self.clear_copper(ncc_obj=self.ncc_obj,
  1308. sel_obj=self.bound_obj,
  1309. ncctooldia=self.ncc_dia_list,
  1310. isotooldia=self.iso_dia_list,
  1311. outname=self.o_name)
  1312. # To be called after clicking on the plot.
  1313. def on_mouse_release(self, event):
  1314. if self.app.is_legacy is False:
  1315. event_pos = event.pos
  1316. # event_is_dragging = event.is_dragging
  1317. right_button = 2
  1318. else:
  1319. event_pos = (event.xdata, event.ydata)
  1320. # event_is_dragging = self.app.plotcanvas.is_dragging
  1321. right_button = 3
  1322. event_pos = self.app.plotcanvas.translate_coords(event_pos)
  1323. # do clear area only for left mouse clicks
  1324. if event.button == 1:
  1325. if self.first_click is False:
  1326. self.first_click = True
  1327. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the end point of the paint area."))
  1328. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  1329. if self.app.grid_status():
  1330. self.cursor_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  1331. else:
  1332. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  1333. self.app.delete_selection_shape()
  1334. if self.app.grid_status():
  1335. curr_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  1336. else:
  1337. curr_pos = (event_pos[0], event_pos[1])
  1338. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  1339. x1, y1 = curr_pos[0], curr_pos[1]
  1340. pt1 = (x0, y0)
  1341. pt2 = (x1, y0)
  1342. pt3 = (x1, y1)
  1343. pt4 = (x0, y1)
  1344. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  1345. self.sel_rect.append(new_rectangle)
  1346. # add a temporary shape on canvas
  1347. self.draw_tool_selection_shape(old_coords=(x0, y0), coords=(x1, y1))
  1348. self.first_click = False
  1349. return
  1350. elif event.button == right_button and self.mouse_is_dragging is False:
  1351. self.first_click = False
  1352. self.delete_tool_selection_shape()
  1353. if self.app.is_legacy is False:
  1354. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1355. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1356. else:
  1357. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1358. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1359. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1360. self.app.on_mouse_click_over_plot)
  1361. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1362. self.app.on_mouse_move_over_plot)
  1363. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1364. self.app.on_mouse_click_release_over_plot)
  1365. if len(self.sel_rect) == 0:
  1366. return
  1367. self.sel_rect = cascaded_union(self.sel_rect)
  1368. self.clear_copper(ncc_obj=self.ncc_obj,
  1369. sel_obj=self.bound_obj,
  1370. ncctooldia=self.ncc_dia_list,
  1371. isotooldia=self.iso_dia_list,
  1372. outname=self.o_name)
  1373. # called on mouse move
  1374. def on_mouse_move(self, event):
  1375. if self.app.is_legacy is False:
  1376. event_pos = event.pos
  1377. event_is_dragging = event.is_dragging
  1378. # right_button = 2
  1379. else:
  1380. event_pos = (event.xdata, event.ydata)
  1381. event_is_dragging = self.app.plotcanvas.is_dragging
  1382. # right_button = 3
  1383. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  1384. # detect mouse dragging motion
  1385. if event_is_dragging is True:
  1386. self.mouse_is_dragging = True
  1387. else:
  1388. self.mouse_is_dragging = False
  1389. # update the cursor position
  1390. if self.app.grid_status():
  1391. # Update cursor
  1392. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1393. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1394. symbol='++', edge_color=self.app.cursor_color_3D,
  1395. edge_width=self.app.defaults["global_cursor_width"],
  1396. size=self.app.defaults["global_cursor_size"])
  1397. # update the positions on status bar
  1398. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  1399. "<b>Y</b>: %.4f" % (curr_pos[0], curr_pos[1]))
  1400. if self.cursor_pos is None:
  1401. self.cursor_pos = (0, 0)
  1402. dx = curr_pos[0] - float(self.cursor_pos[0])
  1403. dy = curr_pos[1] - float(self.cursor_pos[1])
  1404. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1405. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  1406. # draw the utility geometry
  1407. if self.first_click:
  1408. self.app.delete_selection_shape()
  1409. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  1410. coords=(curr_pos[0], curr_pos[1]))
  1411. def envelope_object(self, ncc_obj, ncc_select, box_obj=None):
  1412. """
  1413. :param ncc_obj:
  1414. :param box_obj:
  1415. :param ncc_select:
  1416. :return:
  1417. """
  1418. box_kind = box_obj.kind if box_obj is not None else None
  1419. env_obj = None
  1420. if ncc_select == 'itself':
  1421. geo_n = ncc_obj.solid_geometry
  1422. try:
  1423. if isinstance(geo_n, MultiPolygon):
  1424. env_obj = geo_n.convex_hull
  1425. elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  1426. (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  1427. env_obj = cascaded_union(geo_n)
  1428. else:
  1429. env_obj = cascaded_union(geo_n)
  1430. env_obj = env_obj.convex_hull
  1431. except Exception as e:
  1432. log.debug("NonCopperClear.envelope_object() 'itself' --> %s" % str(e))
  1433. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  1434. return None
  1435. elif ncc_select == 'area':
  1436. env_obj = cascaded_union(self.sel_rect)
  1437. try:
  1438. __ = iter(env_obj)
  1439. except Exception:
  1440. env_obj = [env_obj]
  1441. elif ncc_select == 'box':
  1442. if box_obj is None:
  1443. return None, None
  1444. box_geo = box_obj.solid_geometry
  1445. if box_kind == 'geometry':
  1446. try:
  1447. __ = iter(box_geo)
  1448. env_obj = box_geo
  1449. except Exception:
  1450. env_obj = [box_geo]
  1451. elif box_kind == 'gerber':
  1452. box_geo = cascaded_union(box_obj.solid_geometry).convex_hull
  1453. ncc_geo = cascaded_union(ncc_obj.solid_geometry).convex_hull
  1454. env_obj = ncc_geo.intersection(box_geo)
  1455. else:
  1456. self.app.inform.emit('[ERROR_NOTCL] %s' % _("The reference object type is not supported."))
  1457. return 'fail'
  1458. return env_obj, box_kind
  1459. def envelope_object_to_tool_bounding_box(self, env_obj, box_kind, ncc_select, ncc_margin):
  1460. """
  1461. Prepare non-copper polygons.
  1462. Create the bounding box area from which the copper features will be subtracted
  1463. :param env_obj: the Geometry to be used as bounding box after applying the ncc_margin
  1464. :param box_kind: "geometry" or "gerber"
  1465. :param ncc_select: the kind of area to be copper cleared
  1466. :param ncc_margin: the margin around the area to be copper cleared
  1467. :return: an geometric element (Polygon or MultiPolygon) that specify the area to be copper cleared
  1468. """
  1469. log.debug("NCC Tool. Preparing non-copper polygons.")
  1470. self.app.inform.emit(_("NCC Tool. Preparing non-copper polygons."))
  1471. if env_obj is None:
  1472. log.debug("NonCopperClear.envelope_object_to_tool_bounding_box() --> The object is None")
  1473. return 'fail'
  1474. bounding_box = None
  1475. if ncc_select == 'itself':
  1476. try:
  1477. bounding_box = env_obj.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1478. except Exception as e:
  1479. log.debug("NonCopperClear.envelope_object_to_tool_bounding_box() 'itself' --> %s" % str(e))
  1480. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  1481. return 'fail'
  1482. elif ncc_select == 'area':
  1483. geo_buff_list = []
  1484. for poly in env_obj:
  1485. if self.app.abort_flag:
  1486. # graceful abort requested by the user
  1487. raise FlatCAMApp.GracefulException
  1488. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1489. bounding_box = cascaded_union(geo_buff_list)
  1490. elif ncc_select == 'box':
  1491. if box_kind == 'geometry':
  1492. geo_buff_list = list()
  1493. for poly in env_obj:
  1494. if self.app.abort_flag:
  1495. # graceful abort requested by the user
  1496. raise FlatCAMApp.GracefulException
  1497. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1498. bounding_box = cascaded_union(geo_buff_list)
  1499. elif box_kind == 'gerber':
  1500. bounding_box = env_obj.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1501. else:
  1502. self.app.inform.emit('[ERROR_NOTCL] %s' % _("The reference object type is not supported."))
  1503. return 'fail'
  1504. log.debug("NCC Tool. Finished non-copper polygons.")
  1505. return bounding_box
  1506. def get_tool_empty_area(self, name, ncc_obj, geo_obj, isotooldia, has_offset, ncc_offset, ncc_margin,
  1507. bounding_box, tools_storage):
  1508. """
  1509. Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry.
  1510. :param name:
  1511. :param ncc_obj:
  1512. :param geo_obj:
  1513. :param isotooldia:
  1514. :param has_offset:
  1515. :param ncc_offset:
  1516. :param ncc_margin:
  1517. :param bounding_box:
  1518. :param tools_storage:
  1519. :return:
  1520. """
  1521. log.debug("NCC Tool. Calculate 'empty' area.")
  1522. self.app.inform.emit(_("NCC Tool. Calculate 'empty' area."))
  1523. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  1524. # will store the number of tools for which the isolation is broken
  1525. warning_flag = 0
  1526. if ncc_obj.kind == 'gerber' and not isotooldia:
  1527. # unfortunately for this function to work time efficient,
  1528. # if the Gerber was loaded without buffering then it require the buffering now.
  1529. if self.app.defaults['gerber_buffering'] == 'no':
  1530. sol_geo = ncc_obj.solid_geometry.buffer(0)
  1531. else:
  1532. sol_geo = ncc_obj.solid_geometry
  1533. if has_offset is True:
  1534. self.app.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1535. if isinstance(sol_geo, list):
  1536. sol_geo = MultiPolygon(sol_geo)
  1537. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1538. self.app.inform.emit('[success] %s ...' % _("Buffering finished"))
  1539. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1540. if empty == 'fail':
  1541. return 'fail'
  1542. if empty.is_empty:
  1543. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1544. _("Could not get the extent of the area to be non copper cleared."))
  1545. return 'fail'
  1546. elif ncc_obj.kind == 'gerber' and isotooldia:
  1547. isolated_geo = []
  1548. # unfortunately for this function to work time efficient,
  1549. # if the Gerber was loaded without buffering then it require the buffering now.
  1550. if self.app.defaults['gerber_buffering'] == 'no':
  1551. self.solid_geometry = ncc_obj.solid_geometry.buffer(0)
  1552. else:
  1553. self.solid_geometry = ncc_obj.solid_geometry
  1554. # if milling type is climb then the move is counter-clockwise around features
  1555. milling_type = self.milling_type_radio.get_value()
  1556. for tool_iso in isotooldia:
  1557. new_geometry = []
  1558. if milling_type == 'cl':
  1559. isolated_geo = self.generate_envelope(tool_iso / 2, 1)
  1560. else:
  1561. isolated_geo = self.generate_envelope(tool_iso / 2, 0)
  1562. if isolated_geo == 'fail':
  1563. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1564. else:
  1565. if ncc_margin < tool_iso:
  1566. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  1567. "than isolation tool diameter."))
  1568. try:
  1569. for geo_elem in isolated_geo:
  1570. # provide the app with a way to process the GUI events when in a blocking loop
  1571. QtWidgets.QApplication.processEvents()
  1572. if self.app.abort_flag:
  1573. # graceful abort requested by the user
  1574. raise FlatCAMApp.GracefulException
  1575. if isinstance(geo_elem, Polygon):
  1576. for ring in self.poly2rings(geo_elem):
  1577. new_geo = ring.intersection(bounding_box)
  1578. if new_geo and not new_geo.is_empty:
  1579. new_geometry.append(new_geo)
  1580. elif isinstance(geo_elem, MultiPolygon):
  1581. for poly in geo_elem:
  1582. for ring in self.poly2rings(poly):
  1583. new_geo = ring.intersection(bounding_box)
  1584. if new_geo and not new_geo.is_empty:
  1585. new_geometry.append(new_geo)
  1586. elif isinstance(geo_elem, LineString):
  1587. new_geo = geo_elem.intersection(bounding_box)
  1588. if new_geo:
  1589. if not new_geo.is_empty:
  1590. new_geometry.append(new_geo)
  1591. elif isinstance(geo_elem, MultiLineString):
  1592. for line_elem in geo_elem:
  1593. new_geo = line_elem.intersection(bounding_box)
  1594. if new_geo and not new_geo.is_empty:
  1595. new_geometry.append(new_geo)
  1596. except TypeError:
  1597. if isinstance(isolated_geo, Polygon):
  1598. for ring in self.poly2rings(isolated_geo):
  1599. new_geo = ring.intersection(bounding_box)
  1600. if new_geo:
  1601. if not new_geo.is_empty:
  1602. new_geometry.append(new_geo)
  1603. elif isinstance(isolated_geo, LineString):
  1604. new_geo = isolated_geo.intersection(bounding_box)
  1605. if new_geo and not new_geo.is_empty:
  1606. new_geometry.append(new_geo)
  1607. elif isinstance(isolated_geo, MultiLineString):
  1608. for line_elem in isolated_geo:
  1609. new_geo = line_elem.intersection(bounding_box)
  1610. if new_geo and not new_geo.is_empty:
  1611. new_geometry.append(new_geo)
  1612. # a MultiLineString geometry element will show that the isolation is broken for this tool
  1613. for geo_e in new_geometry:
  1614. if type(geo_e) == MultiLineString:
  1615. warning_flag += 1
  1616. break
  1617. current_uid = 0
  1618. for k, v in tools_storage.items():
  1619. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  1620. tool_iso)):
  1621. current_uid = int(k)
  1622. # add the solid_geometry to the current too in self.paint_tools dictionary
  1623. # and then reset the temporary list that stored that solid_geometry
  1624. v['solid_geometry'] = deepcopy(new_geometry)
  1625. v['data']['name'] = name
  1626. break
  1627. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1628. sol_geo = cascaded_union(isolated_geo)
  1629. if has_offset is True:
  1630. self.app.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1631. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1632. self.app.inform.emit('[success] %s ...' % _("Buffering finished"))
  1633. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1634. if empty == 'fail':
  1635. return 'fail'
  1636. if empty.is_empty:
  1637. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1638. _("Isolation geometry is broken. Margin is less than isolation tool diameter."))
  1639. return 'fail'
  1640. elif ncc_obj.kind == 'geometry':
  1641. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  1642. if has_offset is True:
  1643. self.app.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1644. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1645. self.app.inform.emit('[success] %s ...' % _("Buffering finished"))
  1646. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1647. if empty == 'fail':
  1648. return 'fail'
  1649. if empty.is_empty:
  1650. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1651. _("Could not get the extent of the area to be non copper cleared."))
  1652. return 'fail'
  1653. else:
  1654. self.app.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  1655. return 'fail'
  1656. if type(empty) is Polygon:
  1657. empty = MultiPolygon([empty])
  1658. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  1659. self.app.inform.emit(_("NCC Tool. Finished calculation of 'empty' area."))
  1660. return empty, warning_flag
  1661. def clear_copper(self, ncc_obj,
  1662. sel_obj=None,
  1663. ncctooldia=None,
  1664. isotooldia=None,
  1665. outname=None,
  1666. order=None,
  1667. tools_storage=None,
  1668. run_threaded=True):
  1669. """
  1670. Clear the excess copper from the entire object.
  1671. :param ncc_obj: ncc cleared object
  1672. :param sel_obj:
  1673. :param ncctooldia: a tuple or single element made out of diameters of the tools to be used to ncc clear
  1674. :param isotooldia: a tuple or single element made out of diameters of the tools to be used for isolation
  1675. :param outname: name of the resulting object
  1676. :param order:
  1677. :param tools_storage: whether to use the current tools_storage self.ncc_tools or a different one.
  1678. Usage of the different one is related to when this function is called from a TcL command.
  1679. :param run_threaded: If True the method will be run in a threaded way suitable for GUI usage; if False it will
  1680. run non-threaded for TclShell usage
  1681. :return:
  1682. """
  1683. if run_threaded:
  1684. proc = self.app.proc_container.new(_("Non-Copper clearing ..."))
  1685. else:
  1686. self.app.proc_container.view.set_busy(_("Non-Copper clearing ..."))
  1687. QtWidgets.QApplication.processEvents()
  1688. # #####################################################################
  1689. # ####### Read the parameters #########################################
  1690. # #####################################################################
  1691. units = self.app.defaults['units']
  1692. order = order if order else self.ncc_order_radio.get_value()
  1693. ncc_select = self.reference_radio.get_value()
  1694. rest_machining_choice = self.ncc_rest_cb.get_value()
  1695. # determine if to use the progressive plotting
  1696. prog_plot = True if self.app.defaults["tools_ncc_plotting"] == 'progressive' else False
  1697. tools_storage = tools_storage if tools_storage is not None else self.ncc_tools
  1698. # ######################################################################################################
  1699. # # Read the tooldia parameter and create a sorted list out them - they may be more than one diameter ##
  1700. # ######################################################################################################
  1701. sorted_tools = []
  1702. if ncctooldia is not None:
  1703. try:
  1704. sorted_tools = [float(eval(dia)) for dia in ncctooldia.split(",") if dia != '']
  1705. except AttributeError:
  1706. if not isinstance(ncctooldia, list):
  1707. sorted_tools = [float(ncctooldia)]
  1708. else:
  1709. sorted_tools = ncctooldia
  1710. else:
  1711. for row in range(self.tools_table.rowCount()):
  1712. if self.tools_table.cellWidget(row, 1).currentText() == 'clear_op':
  1713. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1714. # ########################################################################################################
  1715. # set the name for the future Geometry object
  1716. # I do it here because it is also stored inside the gen_clear_area() and gen_clear_area_rest() methods
  1717. # ########################################################################################################
  1718. name = outname if outname is not None else self.obj_name + "_ncc"
  1719. # ##########################################################################################
  1720. # Initializes the new geometry object ######################################################
  1721. # ##########################################################################################
  1722. def gen_clear_area(geo_obj, app_obj):
  1723. assert geo_obj.kind == 'geometry', \
  1724. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1725. # provide the app with a way to process the GUI events when in a blocking loop
  1726. if not run_threaded:
  1727. QtWidgets.QApplication.processEvents()
  1728. log.debug("NCC Tool. Normal copper clearing task started.")
  1729. self.app.inform.emit(_("NCC Tool. Finished non-copper polygons. Normal copper clearing task started."))
  1730. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  1731. # will store the number of tools for which the isolation is broken
  1732. warning_flag = 0
  1733. if order == 'fwd':
  1734. sorted_tools.sort(reverse=False)
  1735. elif order == 'rev':
  1736. sorted_tools.sort(reverse=True)
  1737. else:
  1738. pass
  1739. cleared_geo = []
  1740. # Already cleared area
  1741. cleared = MultiPolygon()
  1742. # flag for polygons not cleared
  1743. app_obj.poly_not_cleared = False
  1744. # Generate area for each tool
  1745. offset = sum(sorted_tools)
  1746. current_uid = int(1)
  1747. try:
  1748. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1749. except TypeError:
  1750. tool = eval(self.app.defaults["tools_ncctools"])
  1751. if ncc_select == 'box':
  1752. env_obj, box_obj_kind = self.envelope_object(ncc_obj=ncc_obj, box_obj=sel_obj, ncc_select=ncc_select)
  1753. else:
  1754. env_obj, box_obj_kind = self.envelope_object(ncc_obj=ncc_obj, ncc_select=ncc_select)
  1755. if env_obj is None and box_obj_kind is None:
  1756. self.app.inform.emit("[ERROR_NOTCL] %s" % _("NCC Tool failed creating bounding box."))
  1757. return "fail"
  1758. # COPPER CLEARING #
  1759. for tool in sorted_tools:
  1760. log.debug("Starting geometry processing for tool: %s" % str(tool))
  1761. if self.app.abort_flag:
  1762. # graceful abort requested by the user
  1763. raise FlatCAMApp.GracefulException
  1764. # provide the app with a way to process the GUI events when in a blocking loop
  1765. QtWidgets.QApplication.processEvents()
  1766. app_obj.inform.emit('[success] %s = %s%s %s' % (
  1767. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  1768. )
  1769. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1770. tooluid = 0
  1771. for k, v in self.ncc_tools.items():
  1772. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool)):
  1773. tooluid = int(k)
  1774. break
  1775. ncc_overlap = float(self.ncc_tools[tooluid]["data"]["nccoverlap"]) / 100.0
  1776. ncc_margin = float(self.ncc_tools[tooluid]["data"]["nccmargin"])
  1777. ncc_method = self.ncc_tools[tooluid]["data"]["nccmethod"]
  1778. ncc_connect = self.ncc_tools[tooluid]["data"]["nccconnect"]
  1779. ncc_contour = self.ncc_tools[tooluid]["data"]["ncccontour"]
  1780. has_offset = self.ncc_tools[tooluid]["data"]["nccoffset"]
  1781. ncc_offset = float(self.ncc_tools[tooluid]["data"]["nccoffset_value"])
  1782. cleared_geo[:] = []
  1783. # Get remaining tools offset
  1784. offset -= (tool - 1e-12)
  1785. # Bounding box for current tool
  1786. bbox = self.envelope_object_to_tool_bounding_box(env_obj=env_obj, box_kind=box_obj_kind,
  1787. ncc_select=ncc_select, ncc_margin=ncc_margin)
  1788. # Area to clear
  1789. empty, warning_flag = self.get_tool_empty_area(name=name, ncc_obj=ncc_obj, geo_obj=geo_obj,
  1790. isotooldia=isotooldia,
  1791. has_offset=has_offset, ncc_offset=ncc_offset,
  1792. ncc_margin=ncc_margin, tools_storage=tools_storage,
  1793. bounding_box=bbox)
  1794. area = empty.buffer(-offset)
  1795. try:
  1796. area = area.difference(cleared)
  1797. except Exception:
  1798. continue
  1799. # Transform area to MultiPolygon
  1800. if type(area) is Polygon:
  1801. area = MultiPolygon([area])
  1802. # variables to display the percentage of work done
  1803. geo_len = len(area.geoms)
  1804. old_disp_number = 0
  1805. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1806. if area.geoms:
  1807. if len(area.geoms) > 0:
  1808. pol_nr = 0
  1809. for p in area.geoms:
  1810. # provide the app with a way to process the GUI events when in a blocking loop
  1811. QtWidgets.QApplication.processEvents()
  1812. if self.app.abort_flag:
  1813. # graceful abort requested by the user
  1814. raise FlatCAMApp.GracefulException
  1815. # clean the polygon
  1816. p = p.buffer(0)
  1817. if p is not None and p.is_valid:
  1818. poly_processed = list()
  1819. try:
  1820. for pol in p:
  1821. if pol is not None and isinstance(pol, Polygon):
  1822. if ncc_method == 'standard':
  1823. cp = self.clear_polygon(pol, tool,
  1824. self.grb_circle_steps,
  1825. overlap=ncc_overlap, contour=ncc_contour,
  1826. connect=ncc_connect,
  1827. prog_plot=prog_plot)
  1828. elif ncc_method == 'seed':
  1829. cp = self.clear_polygon2(pol, tool,
  1830. self.grb_circle_steps,
  1831. overlap=ncc_overlap, contour=ncc_contour,
  1832. connect=ncc_connect,
  1833. prog_plot=prog_plot)
  1834. else:
  1835. cp = self.clear_polygon3(pol, tool,
  1836. self.grb_circle_steps,
  1837. overlap=ncc_overlap, contour=ncc_contour,
  1838. connect=ncc_connect,
  1839. prog_plot=prog_plot)
  1840. if cp:
  1841. cleared_geo += list(cp.get_objects())
  1842. poly_processed.append(True)
  1843. else:
  1844. poly_processed.append(False)
  1845. log.warning("Polygon in MultiPolygon can not be cleared.")
  1846. else:
  1847. log.warning("Geo in Iterable can not be cleared because it is not Polygon. "
  1848. "It is: %s" % str(type(pol)))
  1849. except TypeError:
  1850. if isinstance(p, Polygon):
  1851. if ncc_method == 'standard':
  1852. cp = self.clear_polygon(p, tool, self.grb_circle_steps,
  1853. overlap=ncc_overlap, contour=ncc_contour,
  1854. connect=ncc_connect,
  1855. prog_plot=prog_plot)
  1856. elif ncc_method == 'seed':
  1857. cp = self.clear_polygon2(p, tool, self.grb_circle_steps,
  1858. overlap=ncc_overlap, contour=ncc_contour,
  1859. connect=ncc_connect,
  1860. prog_plot=prog_plot)
  1861. else:
  1862. cp = self.clear_polygon3(p, tool, self.grb_circle_steps,
  1863. overlap=ncc_overlap, contour=ncc_contour,
  1864. connect=ncc_connect,
  1865. prog_plot=prog_plot)
  1866. if cp:
  1867. cleared_geo += list(cp.get_objects())
  1868. poly_processed.append(True)
  1869. else:
  1870. poly_processed.append(False)
  1871. log.warning("Polygon can not be cleared.")
  1872. else:
  1873. log.warning("Geo can not be cleared because it is: %s" % str(type(p)))
  1874. p_cleared = poly_processed.count(True)
  1875. p_not_cleared = poly_processed.count(False)
  1876. if p_not_cleared:
  1877. app_obj.poly_not_cleared = True
  1878. if p_cleared == 0:
  1879. continue
  1880. pol_nr += 1
  1881. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1882. # log.debug("Polygons cleared: %d" % pol_nr)
  1883. if old_disp_number < disp_number <= 100:
  1884. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1885. old_disp_number = disp_number
  1886. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1887. # check if there is a geometry at all in the cleared geometry
  1888. if cleared_geo:
  1889. # Overall cleared area
  1890. cleared = empty.buffer(-offset * (1 + ncc_overlap)).buffer(-tool / 1.999999).buffer(
  1891. tool / 1.999999)
  1892. # clean-up cleared geo
  1893. cleared = cleared.buffer(0)
  1894. # find the tooluid associated with the current tool_dia so we know where to add the tool
  1895. # solid_geometry
  1896. for k, v in tools_storage.items():
  1897. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  1898. tool)):
  1899. current_uid = int(k)
  1900. # add the solid_geometry to the current too in self.paint_tools dictionary
  1901. # and then reset the temporary list that stored that solid_geometry
  1902. v['solid_geometry'] = deepcopy(cleared_geo)
  1903. v['data']['name'] = name
  1904. break
  1905. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1906. else:
  1907. log.debug("There are no geometries in the cleared polygon.")
  1908. # clean the progressive plotted shapes if it was used
  1909. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  1910. self.temp_shapes.clear(update=True)
  1911. # delete tools with empty geometry
  1912. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1913. for uid, uid_val in list(tools_storage.items()):
  1914. try:
  1915. # if the solid_geometry (type=list) is empty
  1916. if not uid_val['solid_geometry']:
  1917. tools_storage.pop(uid, None)
  1918. except KeyError:
  1919. tools_storage.pop(uid, None)
  1920. geo_obj.options["cnctooldia"] = str(tool)
  1921. geo_obj.multigeo = True
  1922. geo_obj.tools.clear()
  1923. geo_obj.tools = dict(tools_storage)
  1924. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1925. has_solid_geo = 0
  1926. for tooluid in geo_obj.tools:
  1927. if geo_obj.tools[tooluid]['solid_geometry']:
  1928. has_solid_geo += 1
  1929. if has_solid_geo == 0:
  1930. app_obj.inform.emit('[ERROR] %s' %
  1931. _("There is no NCC Geometry in the file.\n"
  1932. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1933. "Change the painting parameters and try again."))
  1934. return 'fail'
  1935. # check to see if geo_obj.tools is empty
  1936. # it will be updated only if there is a solid_geometry for tools
  1937. if geo_obj.tools:
  1938. if warning_flag == 0:
  1939. self.app.inform.emit('[success] %s' % _("NCC Tool clear all done."))
  1940. else:
  1941. self.app.inform.emit('[WARNING] %s: %s %s.' % (
  1942. _("NCC Tool clear all done but the copper features isolation is broken for"),
  1943. str(warning_flag),
  1944. _("tools")))
  1945. return
  1946. # create the solid_geometry
  1947. geo_obj.solid_geometry = list()
  1948. for tooluid in geo_obj.tools:
  1949. if geo_obj.tools[tooluid]['solid_geometry']:
  1950. try:
  1951. for geo in geo_obj.tools[tooluid]['solid_geometry']:
  1952. geo_obj.solid_geometry.append(geo)
  1953. except TypeError:
  1954. geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  1955. else:
  1956. # I will use this variable for this purpose although it was meant for something else
  1957. # signal that we have no geo in the object therefore don't create it
  1958. app_obj.poly_not_cleared = False
  1959. return "fail"
  1960. # # Experimental...
  1961. # # print("Indexing...", end=' ')
  1962. # # geo_obj.make_index()
  1963. # ###########################################################################################
  1964. # Initializes the new geometry object for the case of the rest-machining ####################
  1965. # ###########################################################################################
  1966. def gen_clear_area_rest(geo_obj, app_obj):
  1967. assert geo_obj.kind == 'geometry', \
  1968. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1969. log.debug("NCC Tool. Rest machining copper clearing task started.")
  1970. app_obj.inform.emit('_(NCC Tool. Rest machining copper clearing task started.')
  1971. # provide the app with a way to process the GUI events when in a blocking loop
  1972. if not run_threaded:
  1973. QtWidgets.QApplication.processEvents()
  1974. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  1975. # will store the number of tools for which the isolation is broken
  1976. warning_flag = 0
  1977. sorted_tools.sort(reverse=True)
  1978. cleared_geo = []
  1979. cleared_by_last_tool = []
  1980. rest_geo = []
  1981. current_uid = 1
  1982. try:
  1983. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1984. except TypeError:
  1985. tool = eval(self.app.defaults["tools_ncctools"])
  1986. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  1987. app_obj.poly_not_cleared = True
  1988. if ncc_select == 'box':
  1989. env_obj, box_obj_kind = self.envelope_object(ncc_obj=ncc_obj, box_obj=sel_obj, ncc_select=ncc_select)
  1990. else:
  1991. env_obj, box_obj_kind = self.envelope_object(ncc_obj=ncc_obj, ncc_select=ncc_select)
  1992. if env_obj is None and box_obj_kind is None:
  1993. self.app.inform.emit("[ERROR_NOTCL] %s" % _("NCC Tool failed creating bounding box."))
  1994. return "fail"
  1995. log.debug("NCC Tool. Calculate 'empty' area.")
  1996. app_obj.inform.emit("NCC Tool. Calculate 'empty' area.")
  1997. # Generate area for each tool
  1998. while sorted_tools:
  1999. log.debug("Starting geometry processing for tool: %s" % str(tool))
  2000. if self.app.abort_flag:
  2001. # graceful abort requested by the user
  2002. raise FlatCAMApp.GracefulException
  2003. # provide the app with a way to process the GUI events when in a blocking loop
  2004. QtWidgets.QApplication.processEvents()
  2005. app_obj.inform.emit('[success] %s = %s%s %s' % (
  2006. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  2007. )
  2008. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2009. tool = sorted_tools.pop(0)
  2010. tooluid = 0
  2011. for k, v in self.ncc_tools.items():
  2012. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool)):
  2013. tooluid = int(k)
  2014. break
  2015. ncc_overlap = float(self.ncc_tools[tooluid]["data"]["nccoverlap"]) / 100.0
  2016. ncc_margin = float(self.ncc_tools[tooluid]["data"]["nccmargin"])
  2017. ncc_method = self.ncc_tools[tooluid]["data"]["nccmethod"]
  2018. ncc_connect = self.ncc_tools[tooluid]["data"]["nccconnect"]
  2019. ncc_contour = self.ncc_tools[tooluid]["data"]["ncccontour"]
  2020. has_offset = self.ncc_tools[tooluid]["data"]["nccoffset"]
  2021. ncc_offset = float(self.ncc_tools[tooluid]["data"]["nccoffset_value"])
  2022. tool_used = tool - 1e-12
  2023. cleared_geo[:] = []
  2024. # Bounding box for current tool
  2025. bbox = self.envelope_object_to_tool_bounding_box(env_obj=env_obj, box_kind=box_obj_kind,
  2026. ncc_select=ncc_select, ncc_margin=ncc_margin)
  2027. # Area to clear
  2028. empty, warning_flag = self.get_tool_empty_area(name=name, ncc_obj=ncc_obj, geo_obj=geo_obj,
  2029. isotooldia=isotooldia,
  2030. has_offset=has_offset, ncc_offset=ncc_offset,
  2031. ncc_margin=ncc_margin, tools_storage=tools_storage,
  2032. bounding_box=bbox)
  2033. area = empty.buffer(0)
  2034. # Area to clear
  2035. for poly in cleared_by_last_tool:
  2036. # provide the app with a way to process the GUI events when in a blocking loop
  2037. QtWidgets.QApplication.processEvents()
  2038. if self.app.abort_flag:
  2039. # graceful abort requested by the user
  2040. raise FlatCAMApp.GracefulException
  2041. try:
  2042. area = area.difference(poly)
  2043. except Exception:
  2044. pass
  2045. cleared_by_last_tool[:] = []
  2046. # Transform area to MultiPolygon
  2047. if type(area) is Polygon:
  2048. area = MultiPolygon([area])
  2049. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  2050. # and rest_geo it's a list
  2051. allparts = [p.buffer(0) for p in area.geoms]
  2052. allparts += deepcopy(rest_geo)
  2053. rest_geo[:] = []
  2054. area = MultiPolygon(deepcopy(allparts))
  2055. allparts[:] = []
  2056. # variables to display the percentage of work done
  2057. geo_len = len(area.geoms)
  2058. old_disp_number = 0
  2059. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2060. if area.geoms:
  2061. if len(area.geoms) > 0:
  2062. pol_nr = 0
  2063. for p in area.geoms:
  2064. if self.app.abort_flag:
  2065. # graceful abort requested by the user
  2066. raise FlatCAMApp.GracefulException
  2067. # clean the polygon
  2068. p = p.buffer(0)
  2069. if p is not None and p.is_valid:
  2070. # provide the app with a way to process the GUI events when in a blocking loop
  2071. QtWidgets.QApplication.processEvents()
  2072. if isinstance(p, Polygon):
  2073. try:
  2074. if ncc_method == 'standard':
  2075. cp = self.clear_polygon(p, tool_used,
  2076. self.grb_circle_steps,
  2077. overlap=ncc_overlap, contour=ncc_contour,
  2078. connect=ncc_connect,
  2079. prog_plot=prog_plot)
  2080. elif ncc_method == 'seed':
  2081. cp = self.clear_polygon2(p, tool_used,
  2082. self.grb_circle_steps,
  2083. overlap=ncc_overlap, contour=ncc_contour,
  2084. connect=ncc_connect,
  2085. prog_plot=prog_plot)
  2086. else:
  2087. cp = self.clear_polygon3(p, tool_used,
  2088. self.grb_circle_steps,
  2089. overlap=ncc_overlap, contour=ncc_contour,
  2090. connect=ncc_connect,
  2091. prog_plot=prog_plot)
  2092. cleared_geo.append(list(cp.get_objects()))
  2093. except Exception as e:
  2094. log.warning("Polygon can't be cleared. %s" % str(e))
  2095. # this polygon should be added to a list and then try clear it with
  2096. # a smaller tool
  2097. rest_geo.append(p)
  2098. elif isinstance(p, MultiPolygon):
  2099. for poly in p:
  2100. if poly is not None:
  2101. # provide the app with a way to process the GUI events when
  2102. # in a blocking loop
  2103. QtWidgets.QApplication.processEvents()
  2104. try:
  2105. if ncc_method == 'standard':
  2106. cp = self.clear_polygon(poly, tool_used,
  2107. self.grb_circle_steps,
  2108. overlap=ncc_overlap, contour=ncc_contour,
  2109. connect=ncc_connect,
  2110. prog_plot=prog_plot)
  2111. elif ncc_method == 'seed':
  2112. cp = self.clear_polygon2(poly, tool_used,
  2113. self.grb_circle_steps,
  2114. overlap=ncc_overlap, contour=ncc_contour,
  2115. connect=ncc_connect,
  2116. prog_plot=prog_plot)
  2117. else:
  2118. cp = self.clear_polygon3(poly, tool_used,
  2119. self.grb_circle_steps,
  2120. overlap=ncc_overlap, contour=ncc_contour,
  2121. connect=ncc_connect,
  2122. prog_plot=prog_plot)
  2123. cleared_geo.append(list(cp.get_objects()))
  2124. except Exception as e:
  2125. log.warning("Polygon can't be cleared. %s" % str(e))
  2126. # this polygon should be added to a list and then try clear it with
  2127. # a smaller tool
  2128. rest_geo.append(poly)
  2129. pol_nr += 1
  2130. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2131. # log.debug("Polygons cleared: %d" % pol_nr)
  2132. if old_disp_number < disp_number <= 100:
  2133. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2134. old_disp_number = disp_number
  2135. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2136. if self.app.abort_flag:
  2137. # graceful abort requested by the user
  2138. raise FlatCAMApp.GracefulException
  2139. # check if there is a geometry at all in the cleared geometry
  2140. if cleared_geo:
  2141. # Overall cleared area
  2142. cleared_area = list(self.flatten_list(cleared_geo))
  2143. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  2144. # for p in cleared_area])
  2145. # here we store the poly's already processed in the original geometry by the current tool
  2146. # into cleared_by_last_tool list
  2147. # this will be sutracted from the original geometry_to_be_cleared and make data for
  2148. # the next tool
  2149. buffer_value = tool_used / 2
  2150. for p in cleared_area:
  2151. if self.app.abort_flag:
  2152. # graceful abort requested by the user
  2153. raise FlatCAMApp.GracefulException
  2154. poly = p.buffer(buffer_value)
  2155. cleared_by_last_tool.append(poly)
  2156. # find the tooluid associated with the current tool_dia so we know
  2157. # where to add the tool solid_geometry
  2158. for k, v in tools_storage.items():
  2159. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2160. tool)):
  2161. current_uid = int(k)
  2162. # add the solid_geometry to the current too in self.paint_tools dictionary
  2163. # and then reset the temporary list that stored that solid_geometry
  2164. v['solid_geometry'] = deepcopy(cleared_area)
  2165. v['data']['name'] = name
  2166. cleared_area[:] = []
  2167. break
  2168. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2169. else:
  2170. log.debug("There are no geometries in the cleared polygon.")
  2171. geo_obj.multigeo = True
  2172. geo_obj.options["cnctooldia"] = str(tool)
  2173. # clean the progressive plotted shapes if it was used
  2174. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  2175. self.temp_shapes.clear(update=True)
  2176. # check to see if geo_obj.tools is empty
  2177. # it will be updated only if there is a solid_geometry for tools
  2178. if geo_obj.tools:
  2179. if warning_flag == 0:
  2180. self.app.inform.emit('[success] %s' % _("NCC Tool Rest Machining clear all done."))
  2181. else:
  2182. self.app.inform.emit(
  2183. '[WARNING] %s: %s %s.' % (_("NCC Tool Rest Machining clear all done but the copper features "
  2184. "isolation is broken for"), str(warning_flag), _("tools")))
  2185. return
  2186. # create the solid_geometry
  2187. geo_obj.solid_geometry = list()
  2188. for tooluid in geo_obj.tools:
  2189. if geo_obj.tools[tooluid]['solid_geometry']:
  2190. try:
  2191. for geo in geo_obj.tools[tooluid]['solid_geometry']:
  2192. geo_obj.solid_geometry.append(geo)
  2193. except TypeError:
  2194. geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  2195. else:
  2196. # I will use this variable for this purpose although it was meant for something else
  2197. # signal that we have no geo in the object therefore don't create it
  2198. app_obj.poly_not_cleared = False
  2199. return "fail"
  2200. # ###########################################################################################
  2201. # Create the Job function and send it to the worker to be processed in another thread #######
  2202. # ###########################################################################################
  2203. def job_thread(app_obj):
  2204. try:
  2205. if rest_machining_choice is True:
  2206. app_obj.new_object("geometry", name, gen_clear_area_rest)
  2207. else:
  2208. app_obj.new_object("geometry", name, gen_clear_area)
  2209. except FlatCAMApp.GracefulException:
  2210. if run_threaded:
  2211. proc.done()
  2212. return
  2213. except Exception:
  2214. if run_threaded:
  2215. proc.done()
  2216. traceback.print_stack()
  2217. return
  2218. if run_threaded:
  2219. proc.done()
  2220. else:
  2221. app_obj.proc_container.view.set_idle()
  2222. # focus on Selected Tab
  2223. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2224. if run_threaded:
  2225. # Promise object with the new name
  2226. self.app.collection.promise(name)
  2227. # Background
  2228. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2229. else:
  2230. job_thread(app_obj=self.app)
  2231. def clear_copper_tcl(self, ncc_obj,
  2232. sel_obj=None,
  2233. ncctooldia=None,
  2234. isotooldia=None,
  2235. margin=None,
  2236. has_offset=None,
  2237. offset=None,
  2238. select_method=None,
  2239. outname=None,
  2240. overlap=None,
  2241. connect=None,
  2242. contour=None,
  2243. order=None,
  2244. method=None,
  2245. rest=None,
  2246. tools_storage=None,
  2247. plot=True,
  2248. run_threaded=False):
  2249. """
  2250. Clear the excess copper from the entire object. To be used only in a TCL command.
  2251. :param ncc_obj: ncc cleared object
  2252. :param sel_obj:
  2253. :param ncctooldia: a tuple or single element made out of diameters of the tools to be used to ncc clear
  2254. :param isotooldia: a tuple or single element made out of diameters of the tools to be used for isolation
  2255. :param overlap: value by which the paths will overlap
  2256. :param order: if the tools are ordered and how
  2257. :param select_method: if to do ncc on the whole object, on an defined area or on an area defined by
  2258. another object
  2259. :param has_offset: True if an offset is needed
  2260. :param offset: distance from the copper features where the copper clearing is stopping
  2261. :param margin: a border around cleared area
  2262. :param outname: name of the resulting object
  2263. :param connect: Connect lines to avoid tool lifts.
  2264. :param contour: Paint around the edges.
  2265. :param method: choice out of 'seed', 'normal', 'lines'
  2266. :param rest: True if to use rest-machining
  2267. :param tools_storage: whether to use the current tools_storage self.ncc_tools or a different one.
  2268. Usage of the different one is related to when this function is called from a TcL command.
  2269. :param plot: if True after the job is finished the result will be plotted, else it will not.
  2270. :param run_threaded: If True the method will be run in a threaded way suitable for GUI usage; if False it will
  2271. run non-threaded for TclShell usage
  2272. :return:
  2273. """
  2274. if run_threaded:
  2275. proc = self.app.proc_container.new(_("Non-Copper clearing ..."))
  2276. else:
  2277. self.app.proc_container.view.set_busy(_("Non-Copper clearing ..."))
  2278. QtWidgets.QApplication.processEvents()
  2279. # #####################################################################
  2280. # ####### Read the parameters #########################################
  2281. # #####################################################################
  2282. units = self.app.defaults['units']
  2283. log.debug("NCC Tool started. Reading parameters.")
  2284. self.app.inform.emit(_("NCC Tool started. Reading parameters."))
  2285. ncc_method = method
  2286. ncc_margin = margin
  2287. ncc_select = select_method
  2288. overlap = overlap
  2289. connect = connect
  2290. contour = contour
  2291. order = order
  2292. if tools_storage is not None:
  2293. tools_storage = tools_storage
  2294. else:
  2295. tools_storage = self.ncc_tools
  2296. ncc_offset = 0.0
  2297. if has_offset is True:
  2298. ncc_offset = offset
  2299. # ######################################################################################################
  2300. # # Read the tooldia parameter and create a sorted list out them - they may be more than one diameter ##
  2301. # ######################################################################################################
  2302. sorted_tools = []
  2303. try:
  2304. sorted_tools = [float(eval(dia)) for dia in ncctooldia.split(",") if dia != '']
  2305. except AttributeError:
  2306. if not isinstance(ncctooldia, list):
  2307. sorted_tools = [float(ncctooldia)]
  2308. else:
  2309. sorted_tools = ncctooldia
  2310. # ##############################################################################################################
  2311. # Prepare non-copper polygons. Create the bounding box area from which the copper features will be subtracted ##
  2312. # ##############################################################################################################
  2313. log.debug("NCC Tool. Preparing non-copper polygons.")
  2314. self.app.inform.emit(_("NCC Tool. Preparing non-copper polygons."))
  2315. try:
  2316. if sel_obj is None or sel_obj == 'itself':
  2317. ncc_sel_obj = ncc_obj
  2318. else:
  2319. ncc_sel_obj = sel_obj
  2320. except Exception as e:
  2321. log.debug("NonCopperClear.clear_copper() --> %s" % str(e))
  2322. return 'fail'
  2323. bounding_box = None
  2324. if ncc_select == 'itself':
  2325. geo_n = ncc_sel_obj.solid_geometry
  2326. try:
  2327. if isinstance(geo_n, MultiPolygon):
  2328. env_obj = geo_n.convex_hull
  2329. elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  2330. (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  2331. env_obj = cascaded_union(geo_n)
  2332. else:
  2333. env_obj = cascaded_union(geo_n)
  2334. env_obj = env_obj.convex_hull
  2335. bounding_box = env_obj.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  2336. except Exception as e:
  2337. log.debug("NonCopperClear.clear_copper() 'itself' --> %s" % str(e))
  2338. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  2339. return 'fail'
  2340. elif ncc_select == 'area':
  2341. geo_n = cascaded_union(self.sel_rect)
  2342. try:
  2343. __ = iter(geo_n)
  2344. except Exception as e:
  2345. log.debug("NonCopperClear.clear_copper() 'area' --> %s" % str(e))
  2346. geo_n = [geo_n]
  2347. geo_buff_list = []
  2348. for poly in geo_n:
  2349. if self.app.abort_flag:
  2350. # graceful abort requested by the user
  2351. raise FlatCAMApp.GracefulException
  2352. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  2353. bounding_box = cascaded_union(geo_buff_list)
  2354. elif ncc_select == 'box':
  2355. geo_n = ncc_sel_obj.solid_geometry
  2356. if ncc_sel_obj.kind == 'geometry':
  2357. try:
  2358. __ = iter(geo_n)
  2359. except Exception as e:
  2360. log.debug("NonCopperClear.clear_copper() 'box' --> %s" % str(e))
  2361. geo_n = [geo_n]
  2362. geo_buff_list = []
  2363. for poly in geo_n:
  2364. if self.app.abort_flag:
  2365. # graceful abort requested by the user
  2366. raise FlatCAMApp.GracefulException
  2367. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  2368. bounding_box = cascaded_union(geo_buff_list)
  2369. elif ncc_sel_obj.kind == 'gerber':
  2370. geo_n = cascaded_union(geo_n).convex_hull
  2371. bounding_box = cascaded_union(self.ncc_obj.solid_geometry).convex_hull.intersection(geo_n)
  2372. bounding_box = bounding_box.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  2373. else:
  2374. self.app.inform.emit('[ERROR_NOTCL] %s' % _("The reference object type is not supported."))
  2375. return 'fail'
  2376. log.debug("NCC Tool. Finished non-copper polygons.")
  2377. # ########################################################################################################
  2378. # set the name for the future Geometry object
  2379. # I do it here because it is also stored inside the gen_clear_area() and gen_clear_area_rest() methods
  2380. # ########################################################################################################
  2381. rest_machining_choice = rest
  2382. if rest_machining_choice is True:
  2383. name = outname if outname is not None else self.obj_name + "_ncc_rm"
  2384. else:
  2385. name = outname if outname is not None else self.obj_name + "_ncc"
  2386. # ##########################################################################################
  2387. # Initializes the new geometry object ######################################################
  2388. # ##########################################################################################
  2389. def gen_clear_area(geo_obj, app_obj):
  2390. assert geo_obj.kind == 'geometry', \
  2391. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2392. # provide the app with a way to process the GUI events when in a blocking loop
  2393. if not run_threaded:
  2394. QtWidgets.QApplication.processEvents()
  2395. log.debug("NCC Tool. Normal copper clearing task started.")
  2396. self.app.inform.emit(_("NCC Tool. Finished non-copper polygons. Normal copper clearing task started."))
  2397. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  2398. # will store the number of tools for which the isolation is broken
  2399. warning_flag = 0
  2400. if order == 'fwd':
  2401. sorted_tools.sort(reverse=False)
  2402. elif order == 'rev':
  2403. sorted_tools.sort(reverse=True)
  2404. else:
  2405. pass
  2406. cleared_geo = []
  2407. # Already cleared area
  2408. cleared = MultiPolygon()
  2409. # flag for polygons not cleared
  2410. app_obj.poly_not_cleared = False
  2411. # Generate area for each tool
  2412. offset = sum(sorted_tools)
  2413. current_uid = int(1)
  2414. try:
  2415. tool = eval(self.app.defaults["tools_ncctools"])[0]
  2416. except TypeError:
  2417. tool = eval(self.app.defaults["tools_ncctools"])
  2418. # ###################################################################################################
  2419. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  2420. # ###################################################################################################
  2421. log.debug("NCC Tool. Calculate 'empty' area.")
  2422. self.app.inform.emit(_("NCC Tool. Calculate 'empty' area."))
  2423. if ncc_obj.kind == 'gerber' and not isotooldia:
  2424. # unfortunately for this function to work time efficient,
  2425. # if the Gerber was loaded without buffering then it require the buffering now.
  2426. if self.app.defaults['gerber_buffering'] == 'no':
  2427. sol_geo = ncc_obj.solid_geometry.buffer(0)
  2428. else:
  2429. sol_geo = ncc_obj.solid_geometry
  2430. if has_offset is True:
  2431. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2432. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2433. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2434. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2435. if empty == 'fail':
  2436. return 'fail'
  2437. if empty.is_empty:
  2438. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2439. _("Could not get the extent of the area to be non copper cleared."))
  2440. return 'fail'
  2441. elif ncc_obj.kind == 'gerber' and isotooldia:
  2442. isolated_geo = []
  2443. # unfortunately for this function to work time efficient,
  2444. # if the Gerber was loaded without buffering then it require the buffering now.
  2445. if self.app.defaults['gerber_buffering'] == 'no':
  2446. self.solid_geometry = ncc_obj.solid_geometry.buffer(0)
  2447. else:
  2448. self.solid_geometry = ncc_obj.solid_geometry
  2449. # if milling type is climb then the move is counter-clockwise around features
  2450. milling_type = self.app.defaults["tools_nccmilling_type"]
  2451. for tool_iso in isotooldia:
  2452. new_geometry = []
  2453. if milling_type == 'cl':
  2454. isolated_geo = self.generate_envelope(tool_iso / 2, 1)
  2455. else:
  2456. isolated_geo = self.generate_envelope(tool_iso / 2, 0)
  2457. if isolated_geo == 'fail':
  2458. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  2459. else:
  2460. if ncc_margin < tool_iso:
  2461. app_obj.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  2462. "than isolation tool diameter."))
  2463. try:
  2464. for geo_elem in isolated_geo:
  2465. # provide the app with a way to process the GUI events when in a blocking loop
  2466. QtWidgets.QApplication.processEvents()
  2467. if self.app.abort_flag:
  2468. # graceful abort requested by the user
  2469. raise FlatCAMApp.GracefulException
  2470. if isinstance(geo_elem, Polygon):
  2471. for ring in self.poly2rings(geo_elem):
  2472. new_geo = ring.intersection(bounding_box)
  2473. if new_geo and not new_geo.is_empty:
  2474. new_geometry.append(new_geo)
  2475. elif isinstance(geo_elem, MultiPolygon):
  2476. for poly in geo_elem:
  2477. for ring in self.poly2rings(poly):
  2478. new_geo = ring.intersection(bounding_box)
  2479. if new_geo and not new_geo.is_empty:
  2480. new_geometry.append(new_geo)
  2481. elif isinstance(geo_elem, LineString):
  2482. new_geo = geo_elem.intersection(bounding_box)
  2483. if new_geo:
  2484. if not new_geo.is_empty:
  2485. new_geometry.append(new_geo)
  2486. elif isinstance(geo_elem, MultiLineString):
  2487. for line_elem in geo_elem:
  2488. new_geo = line_elem.intersection(bounding_box)
  2489. if new_geo and not new_geo.is_empty:
  2490. new_geometry.append(new_geo)
  2491. except TypeError:
  2492. if isinstance(isolated_geo, Polygon):
  2493. for ring in self.poly2rings(isolated_geo):
  2494. new_geo = ring.intersection(bounding_box)
  2495. if new_geo:
  2496. if not new_geo.is_empty:
  2497. new_geometry.append(new_geo)
  2498. elif isinstance(isolated_geo, LineString):
  2499. new_geo = isolated_geo.intersection(bounding_box)
  2500. if new_geo and not new_geo.is_empty:
  2501. new_geometry.append(new_geo)
  2502. elif isinstance(isolated_geo, MultiLineString):
  2503. for line_elem in isolated_geo:
  2504. new_geo = line_elem.intersection(bounding_box)
  2505. if new_geo and not new_geo.is_empty:
  2506. new_geometry.append(new_geo)
  2507. # a MultiLineString geometry element will show that the isolation is broken for this tool
  2508. for geo_e in new_geometry:
  2509. if type(geo_e) == MultiLineString:
  2510. warning_flag += 1
  2511. break
  2512. for k, v in tools_storage.items():
  2513. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2514. tool_iso)):
  2515. current_uid = int(k)
  2516. # add the solid_geometry to the current too in self.paint_tools dictionary
  2517. # and then reset the temporary list that stored that solid_geometry
  2518. v['solid_geometry'] = deepcopy(new_geometry)
  2519. v['data']['name'] = name
  2520. break
  2521. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2522. sol_geo = cascaded_union(isolated_geo)
  2523. if has_offset is True:
  2524. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2525. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2526. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2527. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2528. if empty == 'fail':
  2529. return 'fail'
  2530. if empty.is_empty:
  2531. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2532. _("Isolation geometry is broken. Margin is less than isolation tool diameter."))
  2533. return 'fail'
  2534. elif ncc_obj.kind == 'geometry':
  2535. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  2536. if has_offset is True:
  2537. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2538. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2539. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2540. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2541. if empty == 'fail':
  2542. return 'fail'
  2543. if empty.is_empty:
  2544. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2545. _("Could not get the extent of the area to be non copper cleared."))
  2546. return 'fail'
  2547. else:
  2548. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  2549. return 'fail'
  2550. if type(empty) is Polygon:
  2551. empty = MultiPolygon([empty])
  2552. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  2553. self.app.inform.emit(_("NCC Tool. Finished calculation of 'empty' area."))
  2554. # COPPER CLEARING #
  2555. for tool in sorted_tools:
  2556. log.debug("Starting geometry processing for tool: %s" % str(tool))
  2557. if self.app.abort_flag:
  2558. # graceful abort requested by the user
  2559. raise FlatCAMApp.GracefulException
  2560. # provide the app with a way to process the GUI events when in a blocking loop
  2561. QtWidgets.QApplication.processEvents()
  2562. app_obj.inform.emit('[success] %s = %s%s %s' % (
  2563. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  2564. )
  2565. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2566. cleared_geo[:] = []
  2567. # Get remaining tools offset
  2568. offset -= (tool - 1e-12)
  2569. # Area to clear
  2570. area = empty.buffer(-offset)
  2571. try:
  2572. area = area.difference(cleared)
  2573. except Exception:
  2574. continue
  2575. # Transform area to MultiPolygon
  2576. if type(area) is Polygon:
  2577. area = MultiPolygon([area])
  2578. # variables to display the percentage of work done
  2579. geo_len = len(area.geoms)
  2580. old_disp_number = 0
  2581. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2582. if area.geoms:
  2583. if len(area.geoms) > 0:
  2584. pol_nr = 0
  2585. for p in area.geoms:
  2586. # provide the app with a way to process the GUI events when in a blocking loop
  2587. QtWidgets.QApplication.processEvents()
  2588. if self.app.abort_flag:
  2589. # graceful abort requested by the user
  2590. raise FlatCAMApp.GracefulException
  2591. # clean the polygon
  2592. p = p.buffer(0)
  2593. if p is not None and p.is_valid:
  2594. poly_processed = list()
  2595. try:
  2596. for pol in p:
  2597. if pol is not None and isinstance(pol, Polygon):
  2598. if ncc_method == 'standard':
  2599. cp = self.clear_polygon(pol, tool,
  2600. self.grb_circle_steps,
  2601. overlap=overlap, contour=contour,
  2602. connect=connect,
  2603. prog_plot=False)
  2604. elif ncc_method == 'seed':
  2605. cp = self.clear_polygon2(pol, tool,
  2606. self.grb_circle_steps,
  2607. overlap=overlap, contour=contour,
  2608. connect=connect,
  2609. prog_plot=False)
  2610. else:
  2611. cp = self.clear_polygon3(pol, tool,
  2612. self.grb_circle_steps,
  2613. overlap=overlap, contour=contour,
  2614. connect=connect,
  2615. prog_plot=False)
  2616. if cp:
  2617. cleared_geo += list(cp.get_objects())
  2618. poly_processed.append(True)
  2619. else:
  2620. poly_processed.append(False)
  2621. log.warning("Polygon in MultiPolygon can not be cleared.")
  2622. else:
  2623. log.warning("Geo in Iterable can not be cleared because it is not Polygon. "
  2624. "It is: %s" % str(type(pol)))
  2625. except TypeError:
  2626. if isinstance(p, Polygon):
  2627. if ncc_method == 'standard':
  2628. cp = self.clear_polygon(p, tool, self.grb_circle_steps,
  2629. overlap=overlap, contour=contour, connect=connect,
  2630. prog_plot=False)
  2631. elif ncc_method == 'seed':
  2632. cp = self.clear_polygon2(p, tool, self.grb_circle_steps,
  2633. overlap=overlap, contour=contour, connect=connect,
  2634. prog_plot=False)
  2635. else:
  2636. cp = self.clear_polygon3(p, tool, self.grb_circle_steps,
  2637. overlap=overlap, contour=contour, connect=connect,
  2638. prog_plot=False)
  2639. if cp:
  2640. cleared_geo += list(cp.get_objects())
  2641. poly_processed.append(True)
  2642. else:
  2643. poly_processed.append(False)
  2644. log.warning("Polygon can not be cleared.")
  2645. else:
  2646. log.warning("Geo can not be cleared because it is: %s" % str(type(p)))
  2647. p_cleared = poly_processed.count(True)
  2648. p_not_cleared = poly_processed.count(False)
  2649. if p_not_cleared:
  2650. app_obj.poly_not_cleared = True
  2651. if p_cleared == 0:
  2652. continue
  2653. pol_nr += 1
  2654. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2655. # log.debug("Polygons cleared: %d" % pol_nr)
  2656. if old_disp_number < disp_number <= 100:
  2657. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2658. old_disp_number = disp_number
  2659. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2660. # check if there is a geometry at all in the cleared geometry
  2661. if cleared_geo:
  2662. # Overall cleared area
  2663. cleared = empty.buffer(-offset * (1 + overlap)).buffer(-tool / 1.999999).buffer(
  2664. tool / 1.999999)
  2665. # clean-up cleared geo
  2666. cleared = cleared.buffer(0)
  2667. # find the tooluid associated with the current tool_dia so we know where to add the tool
  2668. # solid_geometry
  2669. for k, v in tools_storage.items():
  2670. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2671. tool)):
  2672. current_uid = int(k)
  2673. # add the solid_geometry to the current too in self.paint_tools dictionary
  2674. # and then reset the temporary list that stored that solid_geometry
  2675. v['solid_geometry'] = deepcopy(cleared_geo)
  2676. v['data']['name'] = name
  2677. break
  2678. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2679. else:
  2680. log.debug("There are no geometries in the cleared polygon.")
  2681. # delete tools with empty geometry
  2682. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  2683. for uid, uid_val in list(tools_storage.items()):
  2684. try:
  2685. # if the solid_geometry (type=list) is empty
  2686. if not uid_val['solid_geometry']:
  2687. tools_storage.pop(uid, None)
  2688. except KeyError:
  2689. tools_storage.pop(uid, None)
  2690. geo_obj.options["cnctooldia"] = str(tool)
  2691. geo_obj.multigeo = True
  2692. geo_obj.tools.clear()
  2693. geo_obj.tools = dict(tools_storage)
  2694. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2695. has_solid_geo = 0
  2696. for tooluid in geo_obj.tools:
  2697. if geo_obj.tools[tooluid]['solid_geometry']:
  2698. has_solid_geo += 1
  2699. if has_solid_geo == 0:
  2700. app_obj.inform.emit('[ERROR] %s' %
  2701. _("There is no NCC Geometry in the file.\n"
  2702. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2703. "Change the painting parameters and try again."))
  2704. return 'fail'
  2705. # check to see if geo_obj.tools is empty
  2706. # it will be updated only if there is a solid_geometry for tools
  2707. if geo_obj.tools:
  2708. if warning_flag == 0:
  2709. self.app.inform.emit('[success] %s' % _("NCC Tool clear all done."))
  2710. else:
  2711. self.app.inform.emit('[WARNING] %s: %s %s.' % (
  2712. _("NCC Tool clear all done but the copper features isolation is broken for"),
  2713. str(warning_flag),
  2714. _("tools")))
  2715. return
  2716. # create the solid_geometry
  2717. geo_obj.solid_geometry = list()
  2718. for tooluid in geo_obj.tools:
  2719. if geo_obj.tools[tooluid]['solid_geometry']:
  2720. try:
  2721. for geo in geo_obj.tools[tooluid]['solid_geometry']:
  2722. geo_obj.solid_geometry.append(geo)
  2723. except TypeError:
  2724. geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  2725. else:
  2726. # I will use this variable for this purpose although it was meant for something else
  2727. # signal that we have no geo in the object therefore don't create it
  2728. app_obj.poly_not_cleared = False
  2729. return "fail"
  2730. # ###########################################################################################
  2731. # Initializes the new geometry object for the case of the rest-machining ####################
  2732. # ###########################################################################################
  2733. def gen_clear_area_rest(geo_obj, app_obj):
  2734. assert geo_obj.kind == 'geometry', \
  2735. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2736. log.debug("NCC Tool. Rest machining copper clearing task started.")
  2737. app_obj.inform.emit('_(NCC Tool. Rest machining copper clearing task started.')
  2738. # provide the app with a way to process the GUI events when in a blocking loop
  2739. if not run_threaded:
  2740. QtWidgets.QApplication.processEvents()
  2741. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  2742. # will store the number of tools for which the isolation is broken
  2743. warning_flag = 0
  2744. sorted_tools.sort(reverse=True)
  2745. cleared_geo = []
  2746. cleared_by_last_tool = []
  2747. rest_geo = []
  2748. current_uid = 1
  2749. try:
  2750. tool = eval(self.app.defaults["tools_ncctools"])[0]
  2751. except TypeError:
  2752. tool = eval(self.app.defaults["tools_ncctools"])
  2753. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  2754. app_obj.poly_not_cleared = True
  2755. log.debug("NCC Tool. Calculate 'empty' area.")
  2756. app_obj.inform.emit("NCC Tool. Calculate 'empty' area.")
  2757. # ###################################################################################################
  2758. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  2759. # ###################################################################################################
  2760. if ncc_obj.kind == 'gerber' and not isotooldia:
  2761. sol_geo = ncc_obj.solid_geometry
  2762. if has_offset is True:
  2763. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2764. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2765. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2766. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2767. if empty == 'fail':
  2768. return 'fail'
  2769. if empty.is_empty:
  2770. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2771. _("Could not get the extent of the area to be non copper cleared."))
  2772. return 'fail'
  2773. elif ncc_obj.kind == 'gerber' and isotooldia:
  2774. isolated_geo = []
  2775. self.solid_geometry = ncc_obj.solid_geometry
  2776. # if milling type is climb then the move is counter-clockwise around features
  2777. milling_type = self.app.defaults["tools_nccmilling_type"]
  2778. for tool_iso in isotooldia:
  2779. new_geometry = []
  2780. if milling_type == 'cl':
  2781. isolated_geo = self.generate_envelope(tool_iso, 1)
  2782. else:
  2783. isolated_geo = self.generate_envelope(tool_iso, 0)
  2784. if isolated_geo == 'fail':
  2785. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  2786. else:
  2787. app_obj.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  2788. "than isolation tool diameter."))
  2789. try:
  2790. for geo_elem in isolated_geo:
  2791. # provide the app with a way to process the GUI events when in a blocking loop
  2792. QtWidgets.QApplication.processEvents()
  2793. if self.app.abort_flag:
  2794. # graceful abort requested by the user
  2795. raise FlatCAMApp.GracefulException
  2796. if isinstance(geo_elem, Polygon):
  2797. for ring in self.poly2rings(geo_elem):
  2798. new_geo = ring.intersection(bounding_box)
  2799. if new_geo and not new_geo.is_empty:
  2800. new_geometry.append(new_geo)
  2801. elif isinstance(geo_elem, MultiPolygon):
  2802. for poly in geo_elem:
  2803. for ring in self.poly2rings(poly):
  2804. new_geo = ring.intersection(bounding_box)
  2805. if new_geo and not new_geo.is_empty:
  2806. new_geometry.append(new_geo)
  2807. elif isinstance(geo_elem, LineString):
  2808. new_geo = geo_elem.intersection(bounding_box)
  2809. if new_geo:
  2810. if not new_geo.is_empty:
  2811. new_geometry.append(new_geo)
  2812. elif isinstance(geo_elem, MultiLineString):
  2813. for line_elem in geo_elem:
  2814. new_geo = line_elem.intersection(bounding_box)
  2815. if new_geo and not new_geo.is_empty:
  2816. new_geometry.append(new_geo)
  2817. except TypeError:
  2818. try:
  2819. if isinstance(isolated_geo, Polygon):
  2820. for ring in self.poly2rings(isolated_geo):
  2821. new_geo = ring.intersection(bounding_box)
  2822. if new_geo:
  2823. if not new_geo.is_empty:
  2824. new_geometry.append(new_geo)
  2825. elif isinstance(isolated_geo, LineString):
  2826. new_geo = isolated_geo.intersection(bounding_box)
  2827. if new_geo and not new_geo.is_empty:
  2828. new_geometry.append(new_geo)
  2829. elif isinstance(isolated_geo, MultiLineString):
  2830. for line_elem in isolated_geo:
  2831. new_geo = line_elem.intersection(bounding_box)
  2832. if new_geo and not new_geo.is_empty:
  2833. new_geometry.append(new_geo)
  2834. except Exception:
  2835. pass
  2836. # a MultiLineString geometry element will show that the isolation is broken for this tool
  2837. for geo_e in new_geometry:
  2838. if type(geo_e) == MultiLineString:
  2839. warning_flag += 1
  2840. break
  2841. for k, v in tools_storage.items():
  2842. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2843. tool_iso)):
  2844. current_uid = int(k)
  2845. # add the solid_geometry to the current too in self.paint_tools dictionary
  2846. # and then reset the temporary list that stored that solid_geometry
  2847. v['solid_geometry'] = deepcopy(new_geometry)
  2848. v['data']['name'] = name
  2849. break
  2850. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2851. sol_geo = cascaded_union(isolated_geo)
  2852. if has_offset is True:
  2853. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2854. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2855. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2856. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2857. if empty == 'fail':
  2858. return 'fail'
  2859. if empty.is_empty:
  2860. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2861. _("Isolation geometry is broken. Margin is less than isolation tool diameter."))
  2862. return 'fail'
  2863. elif ncc_obj.kind == 'geometry':
  2864. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  2865. if has_offset is True:
  2866. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2867. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2868. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2869. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2870. if empty == 'fail':
  2871. return 'fail'
  2872. if empty.is_empty:
  2873. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2874. _("Could not get the extent of the area to be non copper cleared."))
  2875. return 'fail'
  2876. else:
  2877. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  2878. return
  2879. if self.app.abort_flag:
  2880. # graceful abort requested by the user
  2881. raise FlatCAMApp.GracefulException
  2882. if type(empty) is Polygon:
  2883. empty = MultiPolygon([empty])
  2884. area = empty.buffer(0)
  2885. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  2886. app_obj.inform.emit("NCC Tool. Finished calculation of 'empty' area.")
  2887. # Generate area for each tool
  2888. while sorted_tools:
  2889. if self.app.abort_flag:
  2890. # graceful abort requested by the user
  2891. raise FlatCAMApp.GracefulException
  2892. tool = sorted_tools.pop(0)
  2893. log.debug("Starting geometry processing for tool: %s" % str(tool))
  2894. app_obj.inform.emit('[success] %s = %s%s %s' % (
  2895. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  2896. )
  2897. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2898. tool_used = tool - 1e-12
  2899. cleared_geo[:] = []
  2900. # Area to clear
  2901. for poly in cleared_by_last_tool:
  2902. # provide the app with a way to process the GUI events when in a blocking loop
  2903. QtWidgets.QApplication.processEvents()
  2904. if self.app.abort_flag:
  2905. # graceful abort requested by the user
  2906. raise FlatCAMApp.GracefulException
  2907. try:
  2908. area = area.difference(poly)
  2909. except Exception:
  2910. pass
  2911. cleared_by_last_tool[:] = []
  2912. # Transform area to MultiPolygon
  2913. if type(area) is Polygon:
  2914. area = MultiPolygon([area])
  2915. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  2916. # and rest_geo it's a list
  2917. allparts = [p.buffer(0) for p in area.geoms]
  2918. allparts += deepcopy(rest_geo)
  2919. rest_geo[:] = []
  2920. area = MultiPolygon(deepcopy(allparts))
  2921. allparts[:] = []
  2922. # variables to display the percentage of work done
  2923. geo_len = len(area.geoms)
  2924. old_disp_number = 0
  2925. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2926. if area.geoms:
  2927. if len(area.geoms) > 0:
  2928. pol_nr = 0
  2929. for p in area.geoms:
  2930. if self.app.abort_flag:
  2931. # graceful abort requested by the user
  2932. raise FlatCAMApp.GracefulException
  2933. # clean the polygon
  2934. p = p.buffer(0)
  2935. if p is not None and p.is_valid:
  2936. # provide the app with a way to process the GUI events when in a blocking loop
  2937. QtWidgets.QApplication.processEvents()
  2938. if isinstance(p, Polygon):
  2939. try:
  2940. if ncc_method == 'standard':
  2941. cp = self.clear_polygon(p, tool_used,
  2942. self.grb_circle_steps,
  2943. overlap=overlap, contour=contour, connect=connect,
  2944. prog_plot=False)
  2945. elif ncc_method == 'seed':
  2946. cp = self.clear_polygon2(p, tool_used,
  2947. self.grb_circle_steps,
  2948. overlap=overlap, contour=contour, connect=connect,
  2949. prog_plot=False)
  2950. else:
  2951. cp = self.clear_polygon3(p, tool_used,
  2952. self.grb_circle_steps,
  2953. overlap=overlap, contour=contour, connect=connect,
  2954. prog_plot=False)
  2955. cleared_geo.append(list(cp.get_objects()))
  2956. except Exception as ee:
  2957. log.warning("Polygon can't be cleared. %s" % str(ee))
  2958. # this polygon should be added to a list and then try clear it with
  2959. # a smaller tool
  2960. rest_geo.append(p)
  2961. elif isinstance(p, MultiPolygon):
  2962. for poly in p:
  2963. if poly is not None:
  2964. # provide the app with a way to process the GUI events when
  2965. # in a blocking loop
  2966. QtWidgets.QApplication.processEvents()
  2967. try:
  2968. if ncc_method == 'standard':
  2969. cp = self.clear_polygon(poly, tool_used,
  2970. self.grb_circle_steps,
  2971. overlap=overlap, contour=contour,
  2972. connect=connect,
  2973. prog_plot=False)
  2974. elif ncc_method == 'seed':
  2975. cp = self.clear_polygon2(poly, tool_used,
  2976. self.grb_circle_steps,
  2977. overlap=overlap, contour=contour,
  2978. connect=connect,
  2979. prog_plot=False)
  2980. else:
  2981. cp = self.clear_polygon3(poly, tool_used,
  2982. self.grb_circle_steps,
  2983. overlap=overlap, contour=contour,
  2984. connect=connect,
  2985. prog_plot=False)
  2986. cleared_geo.append(list(cp.get_objects()))
  2987. except Exception as eee:
  2988. log.warning("Polygon can't be cleared. %s" % str(eee))
  2989. # this polygon should be added to a list and then try clear it with
  2990. # a smaller tool
  2991. rest_geo.append(poly)
  2992. pol_nr += 1
  2993. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2994. # log.debug("Polygons cleared: %d" % pol_nr)
  2995. if old_disp_number < disp_number <= 100:
  2996. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2997. old_disp_number = disp_number
  2998. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2999. if self.app.abort_flag:
  3000. # graceful abort requested by the user
  3001. raise FlatCAMApp.GracefulException
  3002. # check if there is a geometry at all in the cleared geometry
  3003. if cleared_geo:
  3004. # Overall cleared area
  3005. cleared_area = list(self.flatten_list(cleared_geo))
  3006. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  3007. # for p in cleared_area])
  3008. # here we store the poly's already processed in the original geometry by the current tool
  3009. # into cleared_by_last_tool list
  3010. # this will be sutracted from the original geometry_to_be_cleared and make data for
  3011. # the next tool
  3012. buffer_value = tool_used / 2
  3013. for p in cleared_area:
  3014. if self.app.abort_flag:
  3015. # graceful abort requested by the user
  3016. raise FlatCAMApp.GracefulException
  3017. poly = p.buffer(buffer_value)
  3018. cleared_by_last_tool.append(poly)
  3019. # find the tooluid associated with the current tool_dia so we know
  3020. # where to add the tool solid_geometry
  3021. for k, v in tools_storage.items():
  3022. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  3023. tool)):
  3024. current_uid = int(k)
  3025. # add the solid_geometry to the current too in self.paint_tools dictionary
  3026. # and then reset the temporary list that stored that solid_geometry
  3027. v['solid_geometry'] = deepcopy(cleared_area)
  3028. v['data']['name'] = name
  3029. cleared_area[:] = []
  3030. break
  3031. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  3032. else:
  3033. log.debug("There are no geometries in the cleared polygon.")
  3034. geo_obj.multigeo = True
  3035. geo_obj.options["cnctooldia"] = str(tool)
  3036. # check to see if geo_obj.tools is empty
  3037. # it will be updated only if there is a solid_geometry for tools
  3038. if geo_obj.tools:
  3039. if warning_flag == 0:
  3040. self.app.inform.emit('[success] %s' % _("NCC Tool Rest Machining clear all done."))
  3041. else:
  3042. self.app.inform.emit(
  3043. '[WARNING] %s: %s %s.' % (_("NCC Tool Rest Machining clear all done but the copper features "
  3044. "isolation is broken for"), str(warning_flag), _("tools")))
  3045. return
  3046. # create the solid_geometry
  3047. geo_obj.solid_geometry = list()
  3048. for tooluid in geo_obj.tools:
  3049. if geo_obj.tools[tooluid]['solid_geometry']:
  3050. try:
  3051. for geo in geo_obj.tools[tooluid]['solid_geometry']:
  3052. geo_obj.solid_geometry.append(geo)
  3053. except TypeError:
  3054. geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  3055. else:
  3056. # I will use this variable for this purpose although it was meant for something else
  3057. # signal that we have no geo in the object therefore don't create it
  3058. app_obj.poly_not_cleared = False
  3059. return "fail"
  3060. # ###########################################################################################
  3061. # Create the Job function and send it to the worker to be processed in another thread #######
  3062. # ###########################################################################################
  3063. def job_thread(app_obj):
  3064. try:
  3065. if rest_machining_choice is True:
  3066. app_obj.new_object("geometry", name, gen_clear_area_rest, plot=plot)
  3067. else:
  3068. app_obj.new_object("geometry", name, gen_clear_area, plot=plot)
  3069. except FlatCAMApp.GracefulException:
  3070. if run_threaded:
  3071. proc.done()
  3072. return
  3073. except Exception:
  3074. if run_threaded:
  3075. proc.done()
  3076. traceback.print_stack()
  3077. return
  3078. if run_threaded:
  3079. proc.done()
  3080. else:
  3081. app_obj.proc_container.view.set_idle()
  3082. # focus on Selected Tab
  3083. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  3084. if run_threaded:
  3085. # Promise object with the new name
  3086. self.app.collection.promise(name)
  3087. # Background
  3088. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3089. else:
  3090. job_thread(app_obj=self.app)
  3091. def get_ncc_empty_area(self, target, boundary=None):
  3092. """
  3093. Returns the complement of target geometry within
  3094. the given boundary polygon. If not specified, it defaults to
  3095. the rectangular bounding box of target geometry.
  3096. """
  3097. if isinstance(target, Polygon):
  3098. geo_len = 1
  3099. else:
  3100. geo_len = len(target)
  3101. pol_nr = 0
  3102. old_disp_number = 0
  3103. if boundary is None:
  3104. boundary = target.envelope
  3105. else:
  3106. boundary = boundary
  3107. try:
  3108. ret_val = boundary.difference(target)
  3109. except Exception:
  3110. try:
  3111. for el in target:
  3112. # provide the app with a way to process the GUI events when in a blocking loop
  3113. QtWidgets.QApplication.processEvents()
  3114. if self.app.abort_flag:
  3115. # graceful abort requested by the user
  3116. raise FlatCAMApp.GracefulException
  3117. boundary = boundary.difference(el)
  3118. pol_nr += 1
  3119. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  3120. if old_disp_number < disp_number <= 100:
  3121. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3122. old_disp_number = disp_number
  3123. return boundary
  3124. except Exception:
  3125. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3126. _("Try to use the Buffering Type = Full in Preferences -> Gerber General. "
  3127. "Reload the Gerber file after this change."))
  3128. return 'fail'
  3129. return ret_val
  3130. def reset_fields(self):
  3131. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  3132. def reset_usage(self):
  3133. self.obj_name = ""
  3134. self.ncc_obj = None
  3135. self.bound_obj = None
  3136. self.first_click = False
  3137. self.cursor_pos = None
  3138. self.mouse_is_dragging = False
  3139. self.sel_rect = []
  3140. @staticmethod
  3141. def poly2rings(poly):
  3142. return [poly.exterior] + [interior for interior in poly.interiors]
  3143. def generate_envelope(self, offset, invert, envelope_iso_type=2, follow=None):
  3144. # isolation_geometry produces an envelope that is going on the left of the geometry
  3145. # (the copper features). To leave the least amount of burrs on the features
  3146. # the tool needs to travel on the right side of the features (this is called conventional milling)
  3147. # the first pass is the one cutting all of the features, so it needs to be reversed
  3148. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  3149. # to cut on the right side of the left over copper i.e on the left side of the features.
  3150. try:
  3151. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type, follow=follow)
  3152. except Exception as e:
  3153. log.debug('NonCopperClear.generate_envelope() --> %s' % str(e))
  3154. return 'fail'
  3155. if invert:
  3156. try:
  3157. try:
  3158. pl = []
  3159. for p in geom:
  3160. if p is not None:
  3161. if isinstance(p, Polygon):
  3162. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  3163. elif isinstance(p, LinearRing):
  3164. pl.append(Polygon(p.coords[::-1]))
  3165. geom = MultiPolygon(pl)
  3166. except TypeError:
  3167. if isinstance(geom, Polygon) and geom is not None:
  3168. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  3169. elif isinstance(geom, LinearRing) and geom is not None:
  3170. geom = Polygon(geom.coords[::-1])
  3171. else:
  3172. log.debug("NonCopperClear.generate_envelope() Error --> Unexpected Geometry %s" %
  3173. type(geom))
  3174. except Exception as e:
  3175. log.debug("NonCopperClear.generate_envelope() Error --> %s" % str(e))
  3176. return 'fail'
  3177. return geom