ToolNonCopperClear.py 177 KB

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