ToolNCC.py 182 KB

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