ToolNCC.py 196 KB

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