ToolNonCopperClear.py 181 KB

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