ToolNCC.py 182 KB

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