ToolNonCopperClear.py 179 KB

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