ToolNonCopperClear.py 179 KB

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