ToolNCC.py 193 KB

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