ToolNonCopperClear.py 176 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679
  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_tool_add)
  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. self.tools_table.currentItemChanged.connect(self.on_row_selection_change)
  575. def on_type_obj_index_changed(self, index):
  576. obj_type = self.type_obj_combo.currentIndex()
  577. self.object_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  578. self.object_combo.setCurrentIndex(0)
  579. def on_row_selection_change(self):
  580. self.update_ui()
  581. def update_ui(self, row=None):
  582. self.blockSignals(True)
  583. if row is None:
  584. try:
  585. current_row = self.tools_table.currentRow()
  586. except Exception:
  587. current_row = 0
  588. else:
  589. current_row = row
  590. if current_row < 0:
  591. current_row = 0
  592. # populate the form with the data from the tool associated with the row parameter
  593. try:
  594. item = self.tools_table.item(current_row, 3)
  595. if item is not None:
  596. tooluid = int(item.text())
  597. else:
  598. return
  599. except Exception as e:
  600. log.debug("Tool missing. Add a tool in the Tool Table. %s" % str(e))
  601. return
  602. # update the QLabel that shows for which Tool we have the parameters in the UI form
  603. self.tool_data_label.setText(
  604. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), (current_row + 1))
  605. )
  606. try:
  607. # set the form with data from the newly selected tool
  608. for tooluid_key, tooluid_value in list(self.ncc_tools.items()):
  609. if int(tooluid_key) == tooluid:
  610. for key, value in tooluid_value.items():
  611. if key == 'data':
  612. form_value_storage = tooluid_value[key]
  613. self.storage_to_form(form_value_storage)
  614. except Exception as e:
  615. log.debug("NonCopperClear ---> update_ui() " + str(e))
  616. self.blockSignals(False)
  617. def storage_to_form(self, dict_storage):
  618. for form_key in self.form_fields:
  619. for storage_key in dict_storage:
  620. if form_key == storage_key:
  621. try:
  622. self.form_fields[form_key].set_value(dict_storage[form_key])
  623. except Exception:
  624. pass
  625. def form_to_storage(self):
  626. if self.tools_table.rowCount() == 0:
  627. # there is no tool in tool table so we can't save the GUI elements values to storage
  628. return
  629. self.blockSignals(True)
  630. widget_changed = self.sender()
  631. wdg_objname = widget_changed.objectName()
  632. option_changed = self.name2option[wdg_objname]
  633. row = self.tools_table.currentRow()
  634. if row < 0:
  635. row = 0
  636. tooluid_item = int(self.tools_table.item(row, 3).text())
  637. for tooluid_key, tooluid_val in self.ncc_tools.items():
  638. if int(tooluid_key) == tooluid_item:
  639. new_option_value = self.form_fields[option_changed].get_value()
  640. if option_changed in tooluid_val:
  641. tooluid_val[option_changed] = new_option_value
  642. if option_changed in tooluid_val['data']:
  643. tooluid_val['data'][option_changed] = new_option_value
  644. self.blockSignals(False)
  645. def on_apply_param_to_all_clicked(self):
  646. if self.tools_table.rowCount() == 0:
  647. # there is no tool in tool table so we can't save the GUI elements values to storage
  648. log.debug("NonCopperClear.on_apply_param_to_all_clicked() --> no tool in Tools Table, aborting.")
  649. return
  650. self.blockSignals(True)
  651. row = self.tools_table.currentRow()
  652. if row < 0:
  653. row = 0
  654. # store all the data associated with the row parameter to the self.tools storage
  655. tooldia_item = float(self.tools_table.item(row, 1).text())
  656. type_item = self.tools_table.cellWidget(row, 2).currentText()
  657. operation_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  658. nccoffset_item = self.ncc_choice_offset_cb.get_value()
  659. nccoffset_value_item = float(self.ncc_offset_spinner.get_value())
  660. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  661. temp_tools = {}
  662. temp_dia = {}
  663. temp_data = {}
  664. for tooluid_key, tooluid_value in self.ncc_tools.items():
  665. for key, value in tooluid_value.items():
  666. if key == 'data':
  667. # update the 'data' section
  668. for data_key in tooluid_value[key].keys():
  669. for form_key, form_value in self.form_fields.items():
  670. if form_key == data_key:
  671. temp_data[data_key] = form_value.get_value()
  672. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  673. # updated from self.app.defaults
  674. if data_key not in self.form_fields:
  675. temp_data[data_key] = value[data_key]
  676. temp_dia[key] = deepcopy(temp_data)
  677. temp_data.clear()
  678. elif key == 'solid_geometry':
  679. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  680. else:
  681. temp_dia[key] = deepcopy(value)
  682. temp_tools[tooluid_key] = deepcopy(temp_dia)
  683. self.ncc_tools.clear()
  684. self.ncc_tools = deepcopy(temp_tools)
  685. temp_tools.clear()
  686. self.blockSignals(False)
  687. def on_add_tool_by_key(self):
  688. tool_add_popup = FCInputDialog(title='%s...' % _("New Tool"),
  689. text='%s:' % _('Enter a Tool Diameter'),
  690. min=0.0001, max=9999.9999, decimals=self.decimals)
  691. tool_add_popup.setWindowIcon(QtGui.QIcon(self.app.resource_location + '/letter_t_32.png'))
  692. val, ok = tool_add_popup.get_value()
  693. if ok:
  694. if float(val) == 0:
  695. self.app.inform.emit('[WARNING_NOTCL] %s' %
  696. _("Please enter a tool diameter with non-zero value, in Float format."))
  697. return
  698. self.on_tool_add(dia=float(val))
  699. else:
  700. self.app.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  701. def install(self, icon=None, separator=None, **kwargs):
  702. FlatCAMTool.install(self, icon, separator, shortcut='ALT+N', **kwargs)
  703. def run(self, toggle=True):
  704. self.app.report_usage("ToolNonCopperClear()")
  705. if toggle:
  706. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  707. if self.app.ui.splitter.sizes()[0] == 0:
  708. self.app.ui.splitter.setSizes([1, 1])
  709. else:
  710. try:
  711. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  712. # if tab is populated with the tool but it does not have the focus, focus on it
  713. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  714. # focus on Tool Tab
  715. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  716. else:
  717. self.app.ui.splitter.setSizes([0, 1])
  718. except AttributeError:
  719. pass
  720. else:
  721. if self.app.ui.splitter.sizes()[0] == 0:
  722. self.app.ui.splitter.setSizes([1, 1])
  723. FlatCAMTool.run(self)
  724. self.set_tool_ui()
  725. # reset those objects on a new run
  726. self.ncc_obj = None
  727. self.bound_obj = None
  728. self.obj_name = ''
  729. self.bound_obj_name = ''
  730. self.build_ui()
  731. self.app.ui.notebook.setTabText(2, _("NCC Tool"))
  732. def set_tool_ui(self):
  733. self.units = self.app.defaults['units'].upper()
  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. for row in range(self.tools_table.rowCount()):
  895. try:
  896. self.tools_table.cellWidget(row, 2).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  897. except AttributeError:
  898. pass
  899. try:
  900. self.tools_table.cellWidget(row, 4).currentIndexChanged.connect(self.on_tooltable_cellwidget_change)
  901. except AttributeError:
  902. pass
  903. self.tool_type_radio.activated_custom.connect(self.on_tool_type)
  904. # first disconnect
  905. for opt in self.form_fields:
  906. current_widget = self.form_fields[opt]
  907. if isinstance(current_widget, FCCheckBox):
  908. try:
  909. current_widget.stateChanged.disconnect()
  910. except (TypeError, ValueError):
  911. pass
  912. if isinstance(current_widget, RadioSet):
  913. try:
  914. current_widget.activated_custom.disconnect()
  915. except (TypeError, ValueError):
  916. pass
  917. elif isinstance(current_widget, FCDoubleSpinner):
  918. try:
  919. current_widget.returnPressed.disconnect()
  920. except (TypeError, ValueError):
  921. pass
  922. # then reconnect
  923. for opt in self.form_fields:
  924. current_widget = self.form_fields[opt]
  925. if isinstance(current_widget, FCCheckBox):
  926. current_widget.stateChanged.connect(self.form_to_storage)
  927. if isinstance(current_widget, RadioSet):
  928. current_widget.activated_custom.connect(self.form_to_storage)
  929. elif isinstance(current_widget, FCDoubleSpinner):
  930. current_widget.returnPressed.connect(self.form_to_storage)
  931. self.ncc_choice_offset_cb.stateChanged.connect(self.on_offset_choice)
  932. self.ncc_rest_cb.stateChanged.connect(self.on_rest_machining_check)
  933. self.ncc_order_radio.activated_custom[str].connect(self.on_order_changed)
  934. def ui_disconnect(self):
  935. try:
  936. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  937. self.tools_table.itemChanged.disconnect()
  938. except (TypeError, AttributeError):
  939. pass
  940. try:
  941. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  942. self.tool_type_radio.activated_custom.disconnect()
  943. except (TypeError, AttributeError):
  944. pass
  945. for row in range(self.tools_table.rowCount()):
  946. for col in [2, 4]:
  947. try:
  948. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  949. except (TypeError, AttributeError):
  950. pass
  951. for opt in self.form_fields:
  952. current_widget = self.form_fields[opt]
  953. if isinstance(current_widget, FCCheckBox):
  954. try:
  955. current_widget.stateChanged.disconnect()
  956. except (TypeError, ValueError):
  957. pass
  958. if isinstance(current_widget, RadioSet):
  959. try:
  960. current_widget.activated_custom.disconnect()
  961. except (TypeError, ValueError):
  962. pass
  963. elif isinstance(current_widget, FCDoubleSpinner):
  964. try:
  965. current_widget.returnPressed.disconnect()
  966. except (TypeError, ValueError):
  967. pass
  968. def on_combo_box_type(self):
  969. obj_type = self.box_combo_type.currentIndex()
  970. self.box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  971. self.box_combo.setCurrentIndex(0)
  972. def on_toggle_reference(self):
  973. if self.reference_radio.get_value() == "itself" or self.reference_radio.get_value() == "area":
  974. self.box_combo.hide()
  975. self.box_combo_label.hide()
  976. self.box_combo_type.hide()
  977. self.box_combo_type_label.hide()
  978. else:
  979. self.box_combo.show()
  980. self.box_combo_label.show()
  981. self.box_combo_type.show()
  982. self.box_combo_type_label.show()
  983. def on_offset_choice(self, state):
  984. # if state:
  985. # self.ncc_offset_label.show()
  986. # self.ncc_offset_spinner.show()
  987. # else:
  988. # self.ncc_offset_label.hide()
  989. # self.ncc_offset_spinner.hide()
  990. self.ncc_offset_spinner.setEnabled(state)
  991. def on_order_changed(self, order):
  992. if order != 'no':
  993. self.build_ui()
  994. def on_rest_machining_check(self, state):
  995. if state:
  996. self.ncc_order_radio.set_value('rev')
  997. self.ncc_order_label.setDisabled(True)
  998. self.ncc_order_radio.setDisabled(True)
  999. else:
  1000. self.ncc_order_label.setDisabled(False)
  1001. self.ncc_order_radio.setDisabled(False)
  1002. def on_tooltable_cellwidget_change(self):
  1003. cw = self.sender()
  1004. cw_index = self.tools_table.indexAt(cw.pos())
  1005. cw_row = cw_index.row()
  1006. cw_col = cw_index.column()
  1007. current_uid = int(self.tools_table.item(cw_row, 3).text())
  1008. # if the sender is in the column with index 2 then we update the tool_type key
  1009. if cw_col == 2:
  1010. tt = cw.currentText()
  1011. typ = 'Iso' if tt == 'V' else "Rough"
  1012. self.ncc_tools[current_uid].update({
  1013. 'type': typ,
  1014. 'tool_type': tt,
  1015. })
  1016. if cw_col == 4:
  1017. op = cw.currentText()
  1018. if op == 'iso_op':
  1019. self.milling_type_label.show()
  1020. self.milling_type_radio.show()
  1021. else:
  1022. self.milling_type_label.hide()
  1023. self.milling_type_radio.hide()
  1024. self.ncc_tools[current_uid].update({
  1025. 'operation': op
  1026. })
  1027. def on_tool_type(self, val):
  1028. if val == 'V':
  1029. self.addtool_entry_lbl.setDisabled(True)
  1030. self.addtool_entry.setDisabled(True)
  1031. self.tipdialabel.show()
  1032. self.tipdia_entry.show()
  1033. self.tipanglelabel.show()
  1034. self.tipangle_entry.show()
  1035. self.on_calculate_tooldia()
  1036. else:
  1037. self.addtool_entry_lbl.setDisabled(False)
  1038. self.addtool_entry.setDisabled(False)
  1039. self.tipdialabel.hide()
  1040. self.tipdia_entry.hide()
  1041. self.tipanglelabel.hide()
  1042. self.tipangle_entry.hide()
  1043. self.addtool_entry.set_value(self.old_tool_dia)
  1044. def on_calculate_tooldia(self):
  1045. if self.tool_type_radio.get_value() == 'V':
  1046. tip_dia = float(self.tipdia_entry.get_value())
  1047. tip_angle = float(self.tipangle_entry.get_value()) / 2.0
  1048. cut_z = float(self.cutz_entry.get_value())
  1049. cut_z = -cut_z if cut_z < 0 else cut_z
  1050. # calculated tool diameter so the cut_z parameter is obeyed
  1051. tool_dia = tip_dia + (2 * cut_z * math.tan(math.radians(tip_angle)))
  1052. # update the default_data so it is used in the ncc_tools dict
  1053. self.default_data.update({
  1054. "vtipdia": tip_dia,
  1055. "vtipangle": (tip_angle * 2),
  1056. })
  1057. self.addtool_entry.set_value(tool_dia)
  1058. return tool_dia
  1059. else:
  1060. return float(self.addtool_entry.get_value())
  1061. def on_tool_add(self, dia=None, muted=None):
  1062. self.blockSignals(True)
  1063. self.units = self.app.defaults['units'].upper()
  1064. if dia:
  1065. tool_dia = dia
  1066. else:
  1067. tool_dia = self.on_calculate_tooldia()
  1068. if tool_dia is None:
  1069. self.build_ui()
  1070. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter to add, in Float format."))
  1071. return
  1072. tool_dia = float('%.*f' % (self.decimals, tool_dia))
  1073. if tool_dia == 0:
  1074. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Please enter a tool diameter with non-zero value, "
  1075. "in Float format."))
  1076. return
  1077. # construct a list of all 'tooluid' in the self.tools
  1078. tool_uid_list = []
  1079. for tooluid_key in self.ncc_tools:
  1080. tool_uid_item = int(tooluid_key)
  1081. tool_uid_list.append(tool_uid_item)
  1082. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  1083. if not tool_uid_list:
  1084. max_uid = 0
  1085. else:
  1086. max_uid = max(tool_uid_list)
  1087. self.tooluid = int(max_uid + 1)
  1088. tool_dias = []
  1089. for k, v in self.ncc_tools.items():
  1090. for tool_v in v.keys():
  1091. if tool_v == 'tooldia':
  1092. tool_dias.append(float('%.*f' % (self.decimals, (v[tool_v]))))
  1093. if float('%.*f' % (self.decimals, tool_dia)) in tool_dias:
  1094. if muted is None:
  1095. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Adding tool cancelled. Tool already in Tool Table."))
  1096. # self.tools_table.itemChanged.connect(self.on_tool_edit)
  1097. self.blockSignals(False)
  1098. return
  1099. else:
  1100. if muted is None:
  1101. self.app.inform.emit('[success] %s' % _("New tool added to Tool Table."))
  1102. self.ncc_tools.update({
  1103. int(self.tooluid): {
  1104. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  1105. 'offset': 'Path',
  1106. 'offset_value': 0.0,
  1107. 'type': 'Iso',
  1108. 'tool_type': self.tool_type_radio.get_value(),
  1109. 'operation': 'clear_op',
  1110. 'data': deepcopy(self.default_data),
  1111. 'solid_geometry': []
  1112. }
  1113. })
  1114. self.blockSignals(False)
  1115. self.build_ui()
  1116. def on_tool_edit(self):
  1117. self.blockSignals(True)
  1118. old_tool_dia = ''
  1119. tool_dias = []
  1120. for k, v in self.ncc_tools.items():
  1121. for tool_v in v.keys():
  1122. if tool_v == 'tooldia':
  1123. tool_dias.append(float('%.*f' % (self.decimals, v[tool_v])))
  1124. for row in range(self.tools_table.rowCount()):
  1125. try:
  1126. new_tool_dia = float(self.tools_table.item(row, 1).text())
  1127. except ValueError:
  1128. # try to convert comma to decimal point. if it's still not working error message and return
  1129. try:
  1130. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  1131. except ValueError:
  1132. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1133. self.blockSignals(False)
  1134. return
  1135. tooluid = int(self.tools_table.item(row, 3).text())
  1136. # identify the tool that was edited and get it's tooluid
  1137. if new_tool_dia not in tool_dias:
  1138. self.ncc_tools[tooluid]['tooldia'] = new_tool_dia
  1139. self.app.inform.emit('[success] %s' % _("Tool from Tool Table was edited."))
  1140. self.blockSignals(False)
  1141. self.build_ui()
  1142. return
  1143. else:
  1144. # identify the old tool_dia and restore the text in tool table
  1145. for k, v in self.ncc_tools.items():
  1146. if k == tooluid:
  1147. old_tool_dia = v['tooldia']
  1148. break
  1149. restore_dia_item = self.tools_table.item(row, 1)
  1150. restore_dia_item.setText(str(old_tool_dia))
  1151. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Edit cancelled. "
  1152. "New diameter value is already in the Tool Table."))
  1153. self.blockSignals(False)
  1154. self.build_ui()
  1155. def on_tool_delete(self, rows_to_delete=None, all_tools=None):
  1156. """
  1157. Will delete a tool in the tool table
  1158. :param rows_to_delete: which rows to delete; can be a list
  1159. :param all_tools: delete all tools in the tool table
  1160. :return:
  1161. """
  1162. self.blockSignals(True)
  1163. deleted_tools_list = []
  1164. if all_tools:
  1165. self.ncc_tools.clear()
  1166. self.blockSignals(False)
  1167. self.build_ui()
  1168. return
  1169. if rows_to_delete:
  1170. try:
  1171. for row in rows_to_delete:
  1172. tooluid_del = int(self.tools_table.item(row, 3).text())
  1173. deleted_tools_list.append(tooluid_del)
  1174. except TypeError:
  1175. tooluid_del = int(self.tools_table.item(rows_to_delete, 3).text())
  1176. deleted_tools_list.append(tooluid_del)
  1177. for t in deleted_tools_list:
  1178. self.ncc_tools.pop(t, None)
  1179. self.blockSignals(False)
  1180. self.build_ui()
  1181. return
  1182. try:
  1183. if self.tools_table.selectedItems():
  1184. for row_sel in self.tools_table.selectedItems():
  1185. row = row_sel.row()
  1186. if row < 0:
  1187. continue
  1188. tooluid_del = int(self.tools_table.item(row, 3).text())
  1189. deleted_tools_list.append(tooluid_del)
  1190. for t in deleted_tools_list:
  1191. self.ncc_tools.pop(t, None)
  1192. except AttributeError:
  1193. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Delete failed. Select a tool to delete."))
  1194. self.blockSignals(False)
  1195. return
  1196. except Exception as e:
  1197. log.debug(str(e))
  1198. self.app.inform.emit('[success] %s' % _("Tool(s) deleted from Tool Table."))
  1199. self.blockSignals(False)
  1200. self.build_ui()
  1201. def on_ncc_click(self):
  1202. """
  1203. Slot for clicking signal of the self.generate.ncc_button
  1204. :return: None
  1205. """
  1206. # init values for the next usage
  1207. self.reset_usage()
  1208. self.app.report_usage("on_paint_button_click")
  1209. self.grb_circle_steps = int(self.app.defaults["gerber_circle_steps"])
  1210. self.obj_name = self.object_combo.currentText()
  1211. # Get source object.
  1212. try:
  1213. self.ncc_obj = self.app.collection.get_by_name(self.obj_name)
  1214. except Exception as e:
  1215. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  1216. return "Could not retrieve object: %s with error: %s" % (self.obj_name, str(e))
  1217. if self.ncc_obj is None:
  1218. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(self.obj_name)))
  1219. return
  1220. # use the selected tools in the tool table; get diameters for non-copper clear
  1221. self.iso_dia_list = list()
  1222. # use the selected tools in the tool table; get diameters for non-copper clear
  1223. self.ncc_dia_list = list()
  1224. if self.tools_table.selectedItems():
  1225. for x in self.tools_table.selectedItems():
  1226. try:
  1227. self.tooldia = float(self.tools_table.item(x.row(), 1).text())
  1228. except ValueError:
  1229. # try to convert comma to decimal point. if it's still not working error message and return
  1230. try:
  1231. self.tooldia = float(self.tools_table.item(x.row(), 1).text().replace(',', '.'))
  1232. except ValueError:
  1233. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong Tool Dia value format entered, "
  1234. "use a number."))
  1235. continue
  1236. if self.tools_table.cellWidget(x.row(), 4).currentText() == 'iso_op':
  1237. self.iso_dia_list.append(self.tooldia)
  1238. else:
  1239. self.ncc_dia_list.append(self.tooldia)
  1240. else:
  1241. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No selected tools in Tool Table."))
  1242. return
  1243. self.o_name = '%s_ncc' % self.obj_name
  1244. self.select_method = self.reference_radio.get_value()
  1245. if self.select_method == 'itself':
  1246. self.bound_obj_name = self.object_combo.currentText()
  1247. # Get source object.
  1248. try:
  1249. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  1250. except Exception as e:
  1251. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.bound_obj_name))
  1252. return "Could not retrieve object: %s with error: %s" % (self.bound_obj_name, str(e))
  1253. self.clear_copper(ncc_obj=self.ncc_obj,
  1254. ncctooldia=self.ncc_dia_list,
  1255. isotooldia=self.iso_dia_list,
  1256. outname=self.o_name)
  1257. elif self.select_method == 'area':
  1258. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the area."))
  1259. if self.app.is_legacy is False:
  1260. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1261. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1262. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1263. else:
  1264. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  1265. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  1266. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  1267. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  1268. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  1269. elif self.select_method == 'box':
  1270. self.bound_obj_name = self.box_combo.currentText()
  1271. # Get source object.
  1272. try:
  1273. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  1274. except Exception as e:
  1275. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.bound_obj_name))
  1276. return "Could not retrieve object: %s. Error: %s" % (self.bound_obj_name, str(e))
  1277. self.clear_copper(ncc_obj=self.ncc_obj,
  1278. sel_obj=self.bound_obj,
  1279. ncctooldia=self.ncc_dia_list,
  1280. isotooldia=self.iso_dia_list,
  1281. outname=self.o_name)
  1282. # To be called after clicking on the plot.
  1283. def on_mouse_release(self, event):
  1284. if self.app.is_legacy is False:
  1285. event_pos = event.pos
  1286. # event_is_dragging = event.is_dragging
  1287. right_button = 2
  1288. else:
  1289. event_pos = (event.xdata, event.ydata)
  1290. # event_is_dragging = self.app.plotcanvas.is_dragging
  1291. right_button = 3
  1292. event_pos = self.app.plotcanvas.translate_coords(event_pos)
  1293. # do clear area only for left mouse clicks
  1294. if event.button == 1:
  1295. if self.first_click is False:
  1296. self.first_click = True
  1297. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the end point of the paint area."))
  1298. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  1299. if self.app.grid_status():
  1300. self.cursor_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  1301. else:
  1302. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  1303. self.app.delete_selection_shape()
  1304. if self.app.grid_status():
  1305. curr_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  1306. else:
  1307. curr_pos = (event_pos[0], event_pos[1])
  1308. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  1309. x1, y1 = curr_pos[0], curr_pos[1]
  1310. pt1 = (x0, y0)
  1311. pt2 = (x1, y0)
  1312. pt3 = (x1, y1)
  1313. pt4 = (x0, y1)
  1314. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  1315. self.sel_rect.append(new_rectangle)
  1316. # add a temporary shape on canvas
  1317. self.draw_tool_selection_shape(old_coords=(x0, y0), coords=(x1, y1))
  1318. self.first_click = False
  1319. return
  1320. elif event.button == right_button and self.mouse_is_dragging is False:
  1321. self.first_click = False
  1322. self.delete_tool_selection_shape()
  1323. if self.app.is_legacy is False:
  1324. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  1325. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1326. else:
  1327. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1328. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1329. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  1330. self.app.on_mouse_click_over_plot)
  1331. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  1332. self.app.on_mouse_move_over_plot)
  1333. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1334. self.app.on_mouse_click_release_over_plot)
  1335. if len(self.sel_rect) == 0:
  1336. return
  1337. self.sel_rect = cascaded_union(self.sel_rect)
  1338. self.clear_copper(ncc_obj=self.ncc_obj,
  1339. sel_obj=self.bound_obj,
  1340. ncctooldia=self.ncc_dia_list,
  1341. isotooldia=self.iso_dia_list,
  1342. outname=self.o_name)
  1343. # called on mouse move
  1344. def on_mouse_move(self, event):
  1345. if self.app.is_legacy is False:
  1346. event_pos = event.pos
  1347. event_is_dragging = event.is_dragging
  1348. # right_button = 2
  1349. else:
  1350. event_pos = (event.xdata, event.ydata)
  1351. event_is_dragging = self.app.plotcanvas.is_dragging
  1352. # right_button = 3
  1353. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  1354. # detect mouse dragging motion
  1355. if event_is_dragging is True:
  1356. self.mouse_is_dragging = True
  1357. else:
  1358. self.mouse_is_dragging = False
  1359. # update the cursor position
  1360. if self.app.grid_status():
  1361. # Update cursor
  1362. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1363. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1364. symbol='++', edge_color=self.app.cursor_color_3D,
  1365. edge_width=self.app.defaults["global_cursor_width"],
  1366. size=self.app.defaults["global_cursor_size"])
  1367. # update the positions on status bar
  1368. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  1369. "<b>Y</b>: %.4f" % (curr_pos[0], curr_pos[1]))
  1370. if self.cursor_pos is None:
  1371. self.cursor_pos = (0, 0)
  1372. dx = curr_pos[0] - float(self.cursor_pos[0])
  1373. dy = curr_pos[1] - float(self.cursor_pos[1])
  1374. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1375. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  1376. # draw the utility geometry
  1377. if self.first_click:
  1378. self.app.delete_selection_shape()
  1379. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  1380. coords=(curr_pos[0], curr_pos[1]))
  1381. def get_tool_bounding_box(self, ncc_obj, sel_obj, ncc_select, ncc_margin):
  1382. """
  1383. Prepare non-copper polygons.
  1384. Create the bounding box area from which the copper features will be subtracted
  1385. :param ncc_obj: the Gerber object to be non-copper cleared
  1386. :param sel_obj: the FlatCAM object to be used as a area delimitator
  1387. :param ncc_select: the kind of area to be copper cleared
  1388. :param ncc_margin: the margin around the area to be copper cleared
  1389. :return: an geometric element (Polygon or MultiPolygon) that specify the area to be copper cleared
  1390. """
  1391. log.debug("NCC Tool. Preparing non-copper polygons.")
  1392. self.app.inform.emit(_("NCC Tool. Preparing non-copper polygons."))
  1393. try:
  1394. if sel_obj is None or sel_obj == 'itself':
  1395. ncc_sel_obj = ncc_obj
  1396. else:
  1397. ncc_sel_obj = sel_obj
  1398. except Exception as e:
  1399. log.debug("NonCopperClear.clear_copper() --> %s" % str(e))
  1400. return 'fail'
  1401. bounding_box = None
  1402. if ncc_select == 'itself':
  1403. geo_n = ncc_sel_obj.solid_geometry
  1404. try:
  1405. if isinstance(geo_n, MultiPolygon):
  1406. env_obj = geo_n.convex_hull
  1407. elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  1408. (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  1409. env_obj = cascaded_union(geo_n)
  1410. else:
  1411. env_obj = cascaded_union(geo_n)
  1412. env_obj = env_obj.convex_hull
  1413. bounding_box = env_obj.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1414. except Exception as e:
  1415. log.debug("NonCopperClear.clear_copper() 'itself' --> %s" % str(e))
  1416. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  1417. return 'fail'
  1418. elif ncc_select == 'area':
  1419. geo_n = cascaded_union(self.sel_rect)
  1420. try:
  1421. __ = iter(geo_n)
  1422. except Exception as e:
  1423. log.debug("NonCopperClear.clear_copper() 'area' --> %s" % str(e))
  1424. geo_n = [geo_n]
  1425. geo_buff_list = []
  1426. for poly in geo_n:
  1427. if self.app.abort_flag:
  1428. # graceful abort requested by the user
  1429. raise FlatCAMApp.GracefulException
  1430. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1431. bounding_box = cascaded_union(geo_buff_list)
  1432. elif ncc_select == 'box':
  1433. geo_n = ncc_sel_obj.solid_geometry
  1434. if ncc_sel_obj.kind == 'geometry':
  1435. try:
  1436. __ = iter(geo_n)
  1437. except Exception as e:
  1438. log.debug("NonCopperClear.clear_copper() 'box' --> %s" % str(e))
  1439. geo_n = [geo_n]
  1440. geo_buff_list = []
  1441. for poly in geo_n:
  1442. if self.app.abort_flag:
  1443. # graceful abort requested by the user
  1444. raise FlatCAMApp.GracefulException
  1445. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1446. bounding_box = cascaded_union(geo_buff_list)
  1447. elif ncc_sel_obj.kind == 'gerber':
  1448. geo_n = cascaded_union(geo_n).convex_hull
  1449. bounding_box = cascaded_union(self.ncc_obj.solid_geometry).convex_hull.intersection(geo_n)
  1450. bounding_box = bounding_box.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1451. else:
  1452. self.app.inform.emit('[ERROR_NOTCL] %s' % _("The reference object type is not supported."))
  1453. return 'fail'
  1454. log.debug("NCC Tool. Finished non-copper polygons.")
  1455. return bounding_box
  1456. def get_tool_empty_area(self, name, ncc_obj, geo_obj, isotooldia, has_offset, ncc_offset, ncc_margin,
  1457. bounding_box, tools_storage):
  1458. """
  1459. Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry.
  1460. :param name:
  1461. :param ncc_obj:
  1462. :param geo_obj:
  1463. :param isotooldia:
  1464. :param has_offset:
  1465. :param ncc_offset:
  1466. :param ncc_margin:
  1467. :param bounding_box:
  1468. :param tools_storage:
  1469. :return:
  1470. """
  1471. log.debug("NCC Tool. Calculate 'empty' area.")
  1472. self.app.inform.emit(_("NCC Tool. Calculate 'empty' area."))
  1473. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  1474. # will store the number of tools for which the isolation is broken
  1475. warning_flag = 0
  1476. if ncc_obj.kind == 'gerber' and not isotooldia:
  1477. # unfortunately for this function to work time efficient,
  1478. # if the Gerber was loaded without buffering then it require the buffering now.
  1479. if self.app.defaults['gerber_buffering'] == 'no':
  1480. sol_geo = ncc_obj.solid_geometry.buffer(0)
  1481. else:
  1482. sol_geo = ncc_obj.solid_geometry
  1483. if has_offset is True:
  1484. self.app.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1485. if isinstance(sol_geo, list):
  1486. sol_geo = MultiPolygon(sol_geo)
  1487. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1488. self.app.inform.emit('[success] %s ...' % _("Buffering finished"))
  1489. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1490. if empty == 'fail':
  1491. return 'fail'
  1492. if empty.is_empty:
  1493. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1494. _("Could not get the extent of the area to be non copper cleared."))
  1495. return 'fail'
  1496. elif ncc_obj.kind == 'gerber' and isotooldia:
  1497. isolated_geo = []
  1498. # unfortunately for this function to work time efficient,
  1499. # if the Gerber was loaded without buffering then it require the buffering now.
  1500. if self.app.defaults['gerber_buffering'] == 'no':
  1501. self.solid_geometry = ncc_obj.solid_geometry.buffer(0)
  1502. else:
  1503. self.solid_geometry = ncc_obj.solid_geometry
  1504. # if milling type is climb then the move is counter-clockwise around features
  1505. milling_type = self.milling_type_radio.get_value()
  1506. for tool_iso in isotooldia:
  1507. new_geometry = []
  1508. if milling_type == 'cl':
  1509. isolated_geo = self.generate_envelope(tool_iso / 2, 1)
  1510. else:
  1511. isolated_geo = self.generate_envelope(tool_iso / 2, 0)
  1512. if isolated_geo == 'fail':
  1513. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1514. else:
  1515. if ncc_margin < tool_iso:
  1516. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  1517. "than isolation tool diameter."))
  1518. try:
  1519. for geo_elem in isolated_geo:
  1520. # provide the app with a way to process the GUI events when in a blocking loop
  1521. QtWidgets.QApplication.processEvents()
  1522. if self.app.abort_flag:
  1523. # graceful abort requested by the user
  1524. raise FlatCAMApp.GracefulException
  1525. if isinstance(geo_elem, Polygon):
  1526. for ring in self.poly2rings(geo_elem):
  1527. new_geo = ring.intersection(bounding_box)
  1528. if new_geo and not new_geo.is_empty:
  1529. new_geometry.append(new_geo)
  1530. elif isinstance(geo_elem, MultiPolygon):
  1531. for poly in geo_elem:
  1532. for ring in self.poly2rings(poly):
  1533. new_geo = ring.intersection(bounding_box)
  1534. if new_geo and not new_geo.is_empty:
  1535. new_geometry.append(new_geo)
  1536. elif isinstance(geo_elem, LineString):
  1537. new_geo = geo_elem.intersection(bounding_box)
  1538. if new_geo:
  1539. if not new_geo.is_empty:
  1540. new_geometry.append(new_geo)
  1541. elif isinstance(geo_elem, MultiLineString):
  1542. for line_elem in geo_elem:
  1543. new_geo = line_elem.intersection(bounding_box)
  1544. if new_geo and not new_geo.is_empty:
  1545. new_geometry.append(new_geo)
  1546. except TypeError:
  1547. if isinstance(isolated_geo, Polygon):
  1548. for ring in self.poly2rings(isolated_geo):
  1549. new_geo = ring.intersection(bounding_box)
  1550. if new_geo:
  1551. if not new_geo.is_empty:
  1552. new_geometry.append(new_geo)
  1553. elif isinstance(isolated_geo, LineString):
  1554. new_geo = isolated_geo.intersection(bounding_box)
  1555. if new_geo and not new_geo.is_empty:
  1556. new_geometry.append(new_geo)
  1557. elif isinstance(isolated_geo, MultiLineString):
  1558. for line_elem in isolated_geo:
  1559. new_geo = line_elem.intersection(bounding_box)
  1560. if new_geo and not new_geo.is_empty:
  1561. new_geometry.append(new_geo)
  1562. # a MultiLineString geometry element will show that the isolation is broken for this tool
  1563. for geo_e in new_geometry:
  1564. if type(geo_e) == MultiLineString:
  1565. warning_flag += 1
  1566. break
  1567. current_uid = 0
  1568. for k, v in tools_storage.items():
  1569. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  1570. tool_iso)):
  1571. current_uid = int(k)
  1572. # add the solid_geometry to the current too in self.paint_tools dictionary
  1573. # and then reset the temporary list that stored that solid_geometry
  1574. v['solid_geometry'] = deepcopy(new_geometry)
  1575. v['data']['name'] = name
  1576. break
  1577. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1578. sol_geo = cascaded_union(isolated_geo)
  1579. if has_offset is True:
  1580. self.app.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1581. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1582. self.app.inform.emit('[success] %s ...' % _("Buffering finished"))
  1583. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1584. if empty == 'fail':
  1585. return 'fail'
  1586. if empty.is_empty:
  1587. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1588. _("Isolation geometry is broken. Margin is less than isolation tool diameter."))
  1589. return 'fail'
  1590. elif ncc_obj.kind == 'geometry':
  1591. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  1592. if has_offset is True:
  1593. self.app.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  1594. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1595. self.app.inform.emit('[success] %s ...' % _("Buffering finished"))
  1596. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1597. if empty == 'fail':
  1598. return 'fail'
  1599. if empty.is_empty:
  1600. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1601. _("Could not get the extent of the area to be non copper cleared."))
  1602. return 'fail'
  1603. else:
  1604. self.app.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  1605. return 'fail'
  1606. if type(empty) is Polygon:
  1607. empty = MultiPolygon([empty])
  1608. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  1609. self.app.inform.emit(_("NCC Tool. Finished calculation of 'empty' area."))
  1610. return empty, warning_flag
  1611. def clear_copper(self, ncc_obj,
  1612. sel_obj=None,
  1613. ncctooldia=None,
  1614. isotooldia=None,
  1615. outname=None,
  1616. order=None,
  1617. tools_storage=None,
  1618. run_threaded=True):
  1619. """
  1620. Clear the excess copper from the entire object.
  1621. :param ncc_obj: ncc cleared object
  1622. :param ncctooldia: a tuple or single element made out of diameters of the tools to be used to ncc clear
  1623. :param isotooldia: a tuple or single element made out of diameters of the tools to be used for isolation
  1624. :param outname: name of the resulting object
  1625. :param tools_storage: whether to use the current tools_storage self.ncc_tools or a different one.
  1626. Usage of the different one is related to when this function is called from a TcL command.
  1627. :param run_threaded: If True the method will be run in a threaded way suitable for GUI usage; if False it will
  1628. run non-threaded for TclShell usage
  1629. :return:
  1630. """
  1631. if run_threaded:
  1632. proc = self.app.proc_container.new(_("Non-Copper clearing ..."))
  1633. else:
  1634. self.app.proc_container.view.set_busy(_("Non-Copper clearing ..."))
  1635. QtWidgets.QApplication.processEvents()
  1636. # #####################################################################
  1637. # ####### Read the parameters #########################################
  1638. # #####################################################################
  1639. units = self.app.defaults['units']
  1640. order = order if order else self.ncc_order_radio.get_value()
  1641. ncc_select = self.reference_radio.get_value()
  1642. rest_machining_choice = self.ncc_rest_cb.get_value()
  1643. # determine if to use the progressive plotting
  1644. prog_plot = True if self.app.defaults["tools_ncc_plotting"] == 'progressive' else False
  1645. tools_storage = tools_storage if tools_storage is not None else self.ncc_tools
  1646. # ######################################################################################################
  1647. # # Read the tooldia parameter and create a sorted list out them - they may be more than one diameter ##
  1648. # ######################################################################################################
  1649. sorted_tools = []
  1650. if ncctooldia is not None:
  1651. try:
  1652. sorted_tools = [float(eval(dia)) for dia in ncctooldia.split(",") if dia != '']
  1653. except AttributeError:
  1654. if not isinstance(ncctooldia, list):
  1655. sorted_tools = [float(ncctooldia)]
  1656. else:
  1657. sorted_tools = ncctooldia
  1658. else:
  1659. for row in range(self.tools_table.rowCount()):
  1660. if self.tools_table.cellWidget(row, 1).currentText() == 'clear_op':
  1661. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1662. # ########################################################################################################
  1663. # set the name for the future Geometry object
  1664. # I do it here because it is also stored inside the gen_clear_area() and gen_clear_area_rest() methods
  1665. # ########################################################################################################
  1666. name = outname if outname is not None else self.obj_name + "_ncc"
  1667. # ##########################################################################################
  1668. # Initializes the new geometry object ######################################################
  1669. # ##########################################################################################
  1670. def gen_clear_area(geo_obj, app_obj):
  1671. assert geo_obj.kind == 'geometry', \
  1672. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1673. # provide the app with a way to process the GUI events when in a blocking loop
  1674. if not run_threaded:
  1675. QtWidgets.QApplication.processEvents()
  1676. log.debug("NCC Tool. Normal copper clearing task started.")
  1677. self.app.inform.emit(_("NCC Tool. Finished non-copper polygons. Normal copper clearing task started."))
  1678. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  1679. # will store the number of tools for which the isolation is broken
  1680. warning_flag = 0
  1681. if order == 'fwd':
  1682. sorted_tools.sort(reverse=False)
  1683. elif order == 'rev':
  1684. sorted_tools.sort(reverse=True)
  1685. else:
  1686. pass
  1687. cleared_geo = []
  1688. # Already cleared area
  1689. cleared = MultiPolygon()
  1690. # flag for polygons not cleared
  1691. app_obj.poly_not_cleared = False
  1692. # Generate area for each tool
  1693. offset = sum(sorted_tools)
  1694. current_uid = int(1)
  1695. try:
  1696. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1697. except TypeError:
  1698. tool = eval(self.app.defaults["tools_ncctools"])
  1699. # COPPER CLEARING #
  1700. cp = None
  1701. for tool in sorted_tools:
  1702. log.debug("Starting geometry processing for tool: %s" % str(tool))
  1703. if self.app.abort_flag:
  1704. # graceful abort requested by the user
  1705. raise FlatCAMApp.GracefulException
  1706. # provide the app with a way to process the GUI events when in a blocking loop
  1707. QtWidgets.QApplication.processEvents()
  1708. app_obj.inform.emit('[success] %s = %s%s %s' % (
  1709. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  1710. )
  1711. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1712. tooluid = 0
  1713. for k, v in self.ncc_tools.items():
  1714. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool)):
  1715. tooluid = int(k)
  1716. break
  1717. ncc_overlap = float(self.ncc_tools[tooluid]["data"]["nccoverlap"]) / 100.0
  1718. ncc_margin = float(self.ncc_tools[tooluid]["data"]["nccmargin"])
  1719. ncc_method = self.ncc_tools[tooluid]["data"]["nccmethod"]
  1720. ncc_connect = self.ncc_tools[tooluid]["data"]["nccconnect"]
  1721. ncc_contour = self.ncc_tools[tooluid]["data"]["ncccontour"]
  1722. has_offset = self.ncc_tools[tooluid]["data"]["nccoffset"]
  1723. ncc_offset = float(self.ncc_tools[tooluid]["data"]["nccoffset_value"])
  1724. cleared_geo[:] = []
  1725. # Get remaining tools offset
  1726. offset -= (tool - 1e-12)
  1727. # Bounding box for current tool
  1728. bbox = self.get_tool_bounding_box(ncc_obj=ncc_obj, sel_obj=sel_obj, ncc_select=ncc_select,
  1729. ncc_margin=ncc_margin)
  1730. # Area to clear
  1731. empty, warning_flag = self.get_tool_empty_area(name=name, ncc_obj=ncc_obj, geo_obj=geo_obj,
  1732. isotooldia=isotooldia,
  1733. has_offset=has_offset, ncc_offset=ncc_offset,
  1734. ncc_margin=ncc_margin, tools_storage=tools_storage,
  1735. bounding_box=bbox)
  1736. area = empty.buffer(-offset)
  1737. try:
  1738. area = area.difference(cleared)
  1739. except Exception:
  1740. continue
  1741. # Transform area to MultiPolygon
  1742. if type(area) is Polygon:
  1743. area = MultiPolygon([area])
  1744. # variables to display the percentage of work done
  1745. geo_len = len(area.geoms)
  1746. old_disp_number = 0
  1747. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1748. if area.geoms:
  1749. if len(area.geoms) > 0:
  1750. pol_nr = 0
  1751. for p in area.geoms:
  1752. # provide the app with a way to process the GUI events when in a blocking loop
  1753. QtWidgets.QApplication.processEvents()
  1754. if self.app.abort_flag:
  1755. # graceful abort requested by the user
  1756. raise FlatCAMApp.GracefulException
  1757. # clean the polygon
  1758. p = p.buffer(0)
  1759. if p is not None and p.is_valid:
  1760. poly_processed = list()
  1761. try:
  1762. for pol in p:
  1763. if pol is not None and isinstance(pol, Polygon):
  1764. if ncc_method == 'standard':
  1765. cp = self.clear_polygon(pol, tool,
  1766. self.grb_circle_steps,
  1767. overlap=ncc_overlap, contour=ncc_contour,
  1768. connect=ncc_connect,
  1769. prog_plot=prog_plot)
  1770. elif ncc_method == 'seed':
  1771. cp = self.clear_polygon2(pol, tool,
  1772. self.grb_circle_steps,
  1773. overlap=ncc_overlap, contour=ncc_contour,
  1774. connect=ncc_connect,
  1775. prog_plot=prog_plot)
  1776. else:
  1777. cp = self.clear_polygon3(pol, tool,
  1778. self.grb_circle_steps,
  1779. overlap=ncc_overlap, contour=ncc_contour,
  1780. connect=ncc_connect,
  1781. prog_plot=prog_plot)
  1782. if cp:
  1783. cleared_geo += list(cp.get_objects())
  1784. poly_processed.append(True)
  1785. else:
  1786. poly_processed.append(False)
  1787. log.warning("Polygon in MultiPolygon can not be cleared.")
  1788. else:
  1789. log.warning("Geo in Iterable can not be cleared because it is not Polygon. "
  1790. "It is: %s" % str(type(pol)))
  1791. except TypeError:
  1792. if isinstance(p, Polygon):
  1793. if ncc_method == 'standard':
  1794. cp = self.clear_polygon(p, tool, self.grb_circle_steps,
  1795. overlap=ncc_overlap, contour=ncc_contour,
  1796. connect=ncc_connect,
  1797. prog_plot=prog_plot)
  1798. elif ncc_method == 'seed':
  1799. cp = self.clear_polygon2(p, tool, self.grb_circle_steps,
  1800. overlap=ncc_overlap, contour=ncc_contour,
  1801. connect=ncc_connect,
  1802. prog_plot=prog_plot)
  1803. else:
  1804. cp = self.clear_polygon3(p, tool, self.grb_circle_steps,
  1805. overlap=ncc_overlap, contour=ncc_contour,
  1806. connect=ncc_connect,
  1807. prog_plot=prog_plot)
  1808. if cp:
  1809. cleared_geo += list(cp.get_objects())
  1810. poly_processed.append(True)
  1811. else:
  1812. poly_processed.append(False)
  1813. log.warning("Polygon can not be cleared.")
  1814. else:
  1815. log.warning("Geo can not be cleared because it is: %s" % str(type(p)))
  1816. p_cleared = poly_processed.count(True)
  1817. p_not_cleared = poly_processed.count(False)
  1818. if p_not_cleared:
  1819. app_obj.poly_not_cleared = True
  1820. if p_cleared == 0:
  1821. continue
  1822. pol_nr += 1
  1823. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1824. # log.debug("Polygons cleared: %d" % pol_nr)
  1825. if old_disp_number < disp_number <= 100:
  1826. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1827. old_disp_number = disp_number
  1828. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1829. # check if there is a geometry at all in the cleared geometry
  1830. if cleared_geo:
  1831. # Overall cleared area
  1832. cleared = empty.buffer(-offset * (1 + ncc_overlap)).buffer(-tool / 1.999999).buffer(
  1833. tool / 1.999999)
  1834. # clean-up cleared geo
  1835. cleared = cleared.buffer(0)
  1836. # find the tooluid associated with the current tool_dia so we know where to add the tool
  1837. # solid_geometry
  1838. for k, v in tools_storage.items():
  1839. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  1840. tool)):
  1841. current_uid = int(k)
  1842. # add the solid_geometry to the current too in self.paint_tools dictionary
  1843. # and then reset the temporary list that stored that solid_geometry
  1844. v['solid_geometry'] = deepcopy(cleared_geo)
  1845. v['data']['name'] = name
  1846. break
  1847. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1848. else:
  1849. log.debug("There are no geometries in the cleared polygon.")
  1850. # clean the progressive plotted shapes if it was used
  1851. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  1852. self.temp_shapes.clear(update=True)
  1853. # delete tools with empty geometry
  1854. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1855. for uid, uid_val in list(tools_storage.items()):
  1856. try:
  1857. # if the solid_geometry (type=list) is empty
  1858. if not uid_val['solid_geometry']:
  1859. tools_storage.pop(uid, None)
  1860. except KeyError:
  1861. tools_storage.pop(uid, None)
  1862. geo_obj.options["cnctooldia"] = str(tool)
  1863. geo_obj.multigeo = True
  1864. geo_obj.tools.clear()
  1865. geo_obj.tools = dict(tools_storage)
  1866. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1867. has_solid_geo = 0
  1868. for tooluid in geo_obj.tools:
  1869. if geo_obj.tools[tooluid]['solid_geometry']:
  1870. has_solid_geo += 1
  1871. if has_solid_geo == 0:
  1872. app_obj.inform.emit('[ERROR] %s' %
  1873. _("There is no NCC Geometry in the file.\n"
  1874. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1875. "Change the painting parameters and try again."))
  1876. return 'fail'
  1877. # check to see if geo_obj.tools is empty
  1878. # it will be updated only if there is a solid_geometry for tools
  1879. if geo_obj.tools:
  1880. if warning_flag == 0:
  1881. self.app.inform.emit('[success] %s' % _("NCC Tool clear all done."))
  1882. else:
  1883. self.app.inform.emit('[WARNING] %s: %s %s.' % (
  1884. _("NCC Tool clear all done but the copper features isolation is broken for"),
  1885. str(warning_flag),
  1886. _("tools")))
  1887. return
  1888. # create the solid_geometry
  1889. geo_obj.solid_geometry = list()
  1890. for tooluid in geo_obj.tools:
  1891. if geo_obj.tools[tooluid]['solid_geometry']:
  1892. try:
  1893. for geo in geo_obj.tools[tooluid]['solid_geometry']:
  1894. geo_obj.solid_geometry.append(geo)
  1895. except TypeError:
  1896. geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  1897. else:
  1898. # I will use this variable for this purpose although it was meant for something else
  1899. # signal that we have no geo in the object therefore don't create it
  1900. app_obj.poly_not_cleared = False
  1901. return "fail"
  1902. # # Experimental...
  1903. # # print("Indexing...", end=' ')
  1904. # # geo_obj.make_index()
  1905. # ###########################################################################################
  1906. # Initializes the new geometry object for the case of the rest-machining ####################
  1907. # ###########################################################################################
  1908. def gen_clear_area_rest(geo_obj, app_obj):
  1909. assert geo_obj.kind == 'geometry', \
  1910. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1911. log.debug("NCC Tool. Rest machining copper clearing task started.")
  1912. app_obj.inform.emit('_(NCC Tool. Rest machining copper clearing task started.')
  1913. # provide the app with a way to process the GUI events when in a blocking loop
  1914. if not run_threaded:
  1915. QtWidgets.QApplication.processEvents()
  1916. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  1917. # will store the number of tools for which the isolation is broken
  1918. warning_flag = 0
  1919. sorted_tools.sort(reverse=True)
  1920. cleared_geo = []
  1921. cleared_by_last_tool = []
  1922. rest_geo = []
  1923. current_uid = 1
  1924. try:
  1925. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1926. except TypeError:
  1927. tool = eval(self.app.defaults["tools_ncctools"])
  1928. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  1929. app_obj.poly_not_cleared = True
  1930. log.debug("NCC Tool. Calculate 'empty' area.")
  1931. app_obj.inform.emit("NCC Tool. Calculate 'empty' area.")
  1932. # Generate area for each tool
  1933. while sorted_tools:
  1934. log.debug("Starting geometry processing for tool: %s" % str(tool))
  1935. if self.app.abort_flag:
  1936. # graceful abort requested by the user
  1937. raise FlatCAMApp.GracefulException
  1938. # provide the app with a way to process the GUI events when in a blocking loop
  1939. QtWidgets.QApplication.processEvents()
  1940. app_obj.inform.emit('[success] %s = %s%s %s' % (
  1941. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  1942. )
  1943. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1944. tool = sorted_tools.pop(0)
  1945. tooluid = 0
  1946. for k, v in self.ncc_tools.items():
  1947. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool)):
  1948. tooluid = int(k)
  1949. break
  1950. ncc_overlap = float(self.ncc_tools[tooluid]["data"]["nccoverlap"]) / 100.0
  1951. ncc_margin = float(self.ncc_tools[tooluid]["data"]["nccmargin"])
  1952. ncc_method = self.ncc_tools[tooluid]["data"]["nccmethod"]
  1953. ncc_connect = self.ncc_tools[tooluid]["data"]["nccconnect"]
  1954. ncc_contour = self.ncc_tools[tooluid]["data"]["ncccontour"]
  1955. has_offset = self.ncc_tools[tooluid]["data"]["nccoffset"]
  1956. ncc_offset = float(self.ncc_tools[tooluid]["data"]["nccoffset_value"])
  1957. tool_used = tool - 1e-12
  1958. cleared_geo[:] = []
  1959. # Bounding box for current tool
  1960. bbox = self.get_tool_bounding_box(ncc_obj=ncc_obj, sel_obj=sel_obj, ncc_select=ncc_select,
  1961. ncc_margin=ncc_margin)
  1962. # Area to clear
  1963. empty, warning_flag = self.get_tool_empty_area(name=name, ncc_obj=ncc_obj, geo_obj=geo_obj,
  1964. isotooldia=isotooldia,
  1965. has_offset=has_offset, ncc_offset=ncc_offset,
  1966. ncc_margin=ncc_margin, tools_storage=tools_storage,
  1967. bounding_box=bbox)
  1968. area = empty.buffer(0)
  1969. # Area to clear
  1970. for poly in cleared_by_last_tool:
  1971. # provide the app with a way to process the GUI events when in a blocking loop
  1972. QtWidgets.QApplication.processEvents()
  1973. if self.app.abort_flag:
  1974. # graceful abort requested by the user
  1975. raise FlatCAMApp.GracefulException
  1976. try:
  1977. area = area.difference(poly)
  1978. except Exception:
  1979. pass
  1980. cleared_by_last_tool[:] = []
  1981. # Transform area to MultiPolygon
  1982. if type(area) is Polygon:
  1983. area = MultiPolygon([area])
  1984. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  1985. # and rest_geo it's a list
  1986. allparts = [p.buffer(0) for p in area.geoms]
  1987. allparts += deepcopy(rest_geo)
  1988. rest_geo[:] = []
  1989. area = MultiPolygon(deepcopy(allparts))
  1990. allparts[:] = []
  1991. # variables to display the percentage of work done
  1992. geo_len = len(area.geoms)
  1993. old_disp_number = 0
  1994. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1995. if area.geoms:
  1996. if len(area.geoms) > 0:
  1997. pol_nr = 0
  1998. for p in area.geoms:
  1999. if self.app.abort_flag:
  2000. # graceful abort requested by the user
  2001. raise FlatCAMApp.GracefulException
  2002. # clean the polygon
  2003. p = p.buffer(0)
  2004. if p is not None and p.is_valid:
  2005. # provide the app with a way to process the GUI events when in a blocking loop
  2006. QtWidgets.QApplication.processEvents()
  2007. if isinstance(p, Polygon):
  2008. try:
  2009. if ncc_method == 'standard':
  2010. cp = self.clear_polygon(p, tool_used,
  2011. self.grb_circle_steps,
  2012. overlap=ncc_overlap, contour=ncc_contour,
  2013. connect=ncc_connect,
  2014. prog_plot=prog_plot)
  2015. elif ncc_method == 'seed':
  2016. cp = self.clear_polygon2(p, tool_used,
  2017. self.grb_circle_steps,
  2018. overlap=ncc_overlap, contour=ncc_contour,
  2019. connect=ncc_connect,
  2020. prog_plot=prog_plot)
  2021. else:
  2022. cp = self.clear_polygon3(p, tool_used,
  2023. self.grb_circle_steps,
  2024. overlap=ncc_overlap, contour=ncc_contour,
  2025. connect=ncc_connect,
  2026. prog_plot=prog_plot)
  2027. cleared_geo.append(list(cp.get_objects()))
  2028. except Exception as e:
  2029. log.warning("Polygon can't be cleared. %s" % str(e))
  2030. # this polygon should be added to a list and then try clear it with
  2031. # a smaller tool
  2032. rest_geo.append(p)
  2033. elif isinstance(p, MultiPolygon):
  2034. for poly in p:
  2035. if poly is not None:
  2036. # provide the app with a way to process the GUI events when
  2037. # in a blocking loop
  2038. QtWidgets.QApplication.processEvents()
  2039. try:
  2040. if ncc_method == 'standard':
  2041. cp = self.clear_polygon(poly, 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(poly, 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(poly, 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(poly)
  2064. pol_nr += 1
  2065. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2066. # log.debug("Polygons cleared: %d" % pol_nr)
  2067. if old_disp_number < disp_number <= 100:
  2068. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2069. old_disp_number = disp_number
  2070. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2071. if self.app.abort_flag:
  2072. # graceful abort requested by the user
  2073. raise FlatCAMApp.GracefulException
  2074. # check if there is a geometry at all in the cleared geometry
  2075. if cleared_geo:
  2076. # Overall cleared area
  2077. cleared_area = list(self.flatten_list(cleared_geo))
  2078. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  2079. # for p in cleared_area])
  2080. # here we store the poly's already processed in the original geometry by the current tool
  2081. # into cleared_by_last_tool list
  2082. # this will be sutracted from the original geometry_to_be_cleared and make data for
  2083. # the next tool
  2084. buffer_value = tool_used / 2
  2085. for p in cleared_area:
  2086. if self.app.abort_flag:
  2087. # graceful abort requested by the user
  2088. raise FlatCAMApp.GracefulException
  2089. poly = p.buffer(buffer_value)
  2090. cleared_by_last_tool.append(poly)
  2091. # find the tooluid associated with the current tool_dia so we know
  2092. # where to add the tool solid_geometry
  2093. for k, v in tools_storage.items():
  2094. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2095. tool)):
  2096. current_uid = int(k)
  2097. # add the solid_geometry to the current too in self.paint_tools dictionary
  2098. # and then reset the temporary list that stored that solid_geometry
  2099. v['solid_geometry'] = deepcopy(cleared_area)
  2100. v['data']['name'] = name
  2101. cleared_area[:] = []
  2102. break
  2103. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2104. else:
  2105. log.debug("There are no geometries in the cleared polygon.")
  2106. geo_obj.multigeo = True
  2107. geo_obj.options["cnctooldia"] = str(tool)
  2108. # clean the progressive plotted shapes if it was used
  2109. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  2110. self.temp_shapes.clear(update=True)
  2111. # check to see if geo_obj.tools is empty
  2112. # it will be updated only if there is a solid_geometry for tools
  2113. if geo_obj.tools:
  2114. if warning_flag == 0:
  2115. self.app.inform.emit('[success] %s' % _("NCC Tool Rest Machining clear all done."))
  2116. else:
  2117. self.app.inform.emit(
  2118. '[WARNING] %s: %s %s.' % (_("NCC Tool Rest Machining clear all done but the copper features "
  2119. "isolation is broken for"), str(warning_flag), _("tools")))
  2120. return
  2121. # create the solid_geometry
  2122. geo_obj.solid_geometry = list()
  2123. for tooluid in geo_obj.tools:
  2124. if geo_obj.tools[tooluid]['solid_geometry']:
  2125. try:
  2126. for geo in geo_obj.tools[tooluid]['solid_geometry']:
  2127. geo_obj.solid_geometry.append(geo)
  2128. except TypeError:
  2129. geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  2130. else:
  2131. # I will use this variable for this purpose although it was meant for something else
  2132. # signal that we have no geo in the object therefore don't create it
  2133. app_obj.poly_not_cleared = False
  2134. return "fail"
  2135. # ###########################################################################################
  2136. # Create the Job function and send it to the worker to be processed in another thread #######
  2137. # ###########################################################################################
  2138. def job_thread(app_obj):
  2139. try:
  2140. if rest_machining_choice is True:
  2141. app_obj.new_object("geometry", name, gen_clear_area_rest)
  2142. else:
  2143. app_obj.new_object("geometry", name, gen_clear_area)
  2144. except FlatCAMApp.GracefulException:
  2145. if run_threaded:
  2146. proc.done()
  2147. return
  2148. except Exception:
  2149. if run_threaded:
  2150. proc.done()
  2151. traceback.print_stack()
  2152. return
  2153. if run_threaded:
  2154. proc.done()
  2155. else:
  2156. app_obj.proc_container.view.set_idle()
  2157. # focus on Selected Tab
  2158. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2159. if run_threaded:
  2160. # Promise object with the new name
  2161. self.app.collection.promise(name)
  2162. # Background
  2163. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2164. else:
  2165. job_thread(app_obj=self.app)
  2166. def clear_copper_tcl(self, ncc_obj,
  2167. sel_obj=None,
  2168. ncctooldia=None,
  2169. isotooldia=None,
  2170. margin=None,
  2171. has_offset=None,
  2172. offset=None,
  2173. select_method=None,
  2174. outname=None,
  2175. overlap=None,
  2176. connect=None,
  2177. contour=None,
  2178. order=None,
  2179. method=None,
  2180. rest=None,
  2181. tools_storage=None,
  2182. plot=True,
  2183. run_threaded=False):
  2184. """
  2185. Clear the excess copper from the entire object. To be used only in a TCL command.
  2186. :param ncc_obj: ncc cleared object
  2187. :param ncctooldia: a tuple or single element made out of diameters of the tools to be used to ncc clear
  2188. :param isotooldia: a tuple or single element made out of diameters of the tools to be used for isolation
  2189. :param overlap: value by which the paths will overlap
  2190. :param order: if the tools are ordered and how
  2191. :param select_method: if to do ncc on the whole object, on an defined area or on an area defined by
  2192. another object
  2193. :param has_offset: True if an offset is needed
  2194. :param offset: distance from the copper features where the copper clearing is stopping
  2195. :param margin: a border around cleared area
  2196. :param outname: name of the resulting object
  2197. :param connect: Connect lines to avoid tool lifts.
  2198. :param contour: Paint around the edges.
  2199. :param method: choice out of 'seed', 'normal', 'lines'
  2200. :param rest: True if to use rest-machining
  2201. :param tools_storage: whether to use the current tools_storage self.ncc_tools or a different one.
  2202. Usage of the different one is related to when this function is called from a TcL command.
  2203. :param plot: if True after the job is finished the result will be plotted, else it will not.
  2204. :param run_threaded: If True the method will be run in a threaded way suitable for GUI usage; if False it will
  2205. run non-threaded for TclShell usage
  2206. :return:
  2207. """
  2208. if run_threaded:
  2209. proc = self.app.proc_container.new(_("Non-Copper clearing ..."))
  2210. else:
  2211. self.app.proc_container.view.set_busy(_("Non-Copper clearing ..."))
  2212. QtWidgets.QApplication.processEvents()
  2213. # #####################################################################
  2214. # ####### Read the parameters #########################################
  2215. # #####################################################################
  2216. units = self.app.defaults['units']
  2217. log.debug("NCC Tool started. Reading parameters.")
  2218. self.app.inform.emit(_("NCC Tool started. Reading parameters."))
  2219. ncc_method = method
  2220. ncc_margin = margin
  2221. ncc_select = select_method
  2222. overlap = overlap
  2223. connect = connect
  2224. contour = contour
  2225. order = order
  2226. if tools_storage is not None:
  2227. tools_storage = tools_storage
  2228. else:
  2229. tools_storage = self.ncc_tools
  2230. ncc_offset = 0.0
  2231. if has_offset is True:
  2232. ncc_offset = offset
  2233. # ######################################################################################################
  2234. # # Read the tooldia parameter and create a sorted list out them - they may be more than one diameter ##
  2235. # ######################################################################################################
  2236. sorted_tools = []
  2237. try:
  2238. sorted_tools = [float(eval(dia)) for dia in ncctooldia.split(",") if dia != '']
  2239. except AttributeError:
  2240. if not isinstance(ncctooldia, list):
  2241. sorted_tools = [float(ncctooldia)]
  2242. else:
  2243. sorted_tools = ncctooldia
  2244. # ##############################################################################################################
  2245. # Prepare non-copper polygons. Create the bounding box area from which the copper features will be subtracted ##
  2246. # ##############################################################################################################
  2247. log.debug("NCC Tool. Preparing non-copper polygons.")
  2248. self.app.inform.emit(_("NCC Tool. Preparing non-copper polygons."))
  2249. try:
  2250. if sel_obj is None or sel_obj == 'itself':
  2251. ncc_sel_obj = ncc_obj
  2252. else:
  2253. ncc_sel_obj = sel_obj
  2254. except Exception as e:
  2255. log.debug("NonCopperClear.clear_copper() --> %s" % str(e))
  2256. return 'fail'
  2257. bounding_box = None
  2258. if ncc_select == 'itself':
  2259. geo_n = ncc_sel_obj.solid_geometry
  2260. try:
  2261. if isinstance(geo_n, MultiPolygon):
  2262. env_obj = geo_n.convex_hull
  2263. elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  2264. (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  2265. env_obj = cascaded_union(geo_n)
  2266. else:
  2267. env_obj = cascaded_union(geo_n)
  2268. env_obj = env_obj.convex_hull
  2269. bounding_box = env_obj.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  2270. except Exception as e:
  2271. log.debug("NonCopperClear.clear_copper() 'itself' --> %s" % str(e))
  2272. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  2273. return 'fail'
  2274. elif ncc_select == 'area':
  2275. geo_n = cascaded_union(self.sel_rect)
  2276. try:
  2277. __ = iter(geo_n)
  2278. except Exception as e:
  2279. log.debug("NonCopperClear.clear_copper() 'area' --> %s" % str(e))
  2280. geo_n = [geo_n]
  2281. geo_buff_list = []
  2282. for poly in geo_n:
  2283. if self.app.abort_flag:
  2284. # graceful abort requested by the user
  2285. raise FlatCAMApp.GracefulException
  2286. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  2287. bounding_box = cascaded_union(geo_buff_list)
  2288. elif ncc_select == 'box':
  2289. geo_n = ncc_sel_obj.solid_geometry
  2290. if ncc_sel_obj.kind == 'geometry':
  2291. try:
  2292. __ = iter(geo_n)
  2293. except Exception as e:
  2294. log.debug("NonCopperClear.clear_copper() 'box' --> %s" % str(e))
  2295. geo_n = [geo_n]
  2296. geo_buff_list = []
  2297. for poly in geo_n:
  2298. if self.app.abort_flag:
  2299. # graceful abort requested by the user
  2300. raise FlatCAMApp.GracefulException
  2301. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  2302. bounding_box = cascaded_union(geo_buff_list)
  2303. elif ncc_sel_obj.kind == 'gerber':
  2304. geo_n = cascaded_union(geo_n).convex_hull
  2305. bounding_box = cascaded_union(self.ncc_obj.solid_geometry).convex_hull.intersection(geo_n)
  2306. bounding_box = bounding_box.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  2307. else:
  2308. self.app.inform.emit('[ERROR_NOTCL] %s' % _("The reference object type is not supported."))
  2309. return 'fail'
  2310. log.debug("NCC Tool. Finished non-copper polygons.")
  2311. # ########################################################################################################
  2312. # set the name for the future Geometry object
  2313. # I do it here because it is also stored inside the gen_clear_area() and gen_clear_area_rest() methods
  2314. # ########################################################################################################
  2315. rest_machining_choice = rest
  2316. if rest_machining_choice is True:
  2317. name = outname if outname is not None else self.obj_name + "_ncc_rm"
  2318. else:
  2319. name = outname if outname is not None else self.obj_name + "_ncc"
  2320. # ##########################################################################################
  2321. # Initializes the new geometry object ######################################################
  2322. # ##########################################################################################
  2323. def gen_clear_area(geo_obj, app_obj):
  2324. assert geo_obj.kind == 'geometry', \
  2325. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2326. # provide the app with a way to process the GUI events when in a blocking loop
  2327. if not run_threaded:
  2328. QtWidgets.QApplication.processEvents()
  2329. log.debug("NCC Tool. Normal copper clearing task started.")
  2330. self.app.inform.emit(_("NCC Tool. Finished non-copper polygons. Normal copper clearing task started."))
  2331. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  2332. # will store the number of tools for which the isolation is broken
  2333. warning_flag = 0
  2334. if order == 'fwd':
  2335. sorted_tools.sort(reverse=False)
  2336. elif order == 'rev':
  2337. sorted_tools.sort(reverse=True)
  2338. else:
  2339. pass
  2340. cleared_geo = []
  2341. # Already cleared area
  2342. cleared = MultiPolygon()
  2343. # flag for polygons not cleared
  2344. app_obj.poly_not_cleared = False
  2345. # Generate area for each tool
  2346. offset = sum(sorted_tools)
  2347. current_uid = int(1)
  2348. try:
  2349. tool = eval(self.app.defaults["tools_ncctools"])[0]
  2350. except TypeError:
  2351. tool = eval(self.app.defaults["tools_ncctools"])
  2352. # ###################################################################################################
  2353. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  2354. # ###################################################################################################
  2355. log.debug("NCC Tool. Calculate 'empty' area.")
  2356. self.app.inform.emit(_("NCC Tool. Calculate 'empty' area."))
  2357. if ncc_obj.kind == 'gerber' and not isotooldia:
  2358. # unfortunately for this function to work time efficient,
  2359. # if the Gerber was loaded without buffering then it require the buffering now.
  2360. if self.app.defaults['gerber_buffering'] == 'no':
  2361. sol_geo = ncc_obj.solid_geometry.buffer(0)
  2362. else:
  2363. sol_geo = ncc_obj.solid_geometry
  2364. if has_offset is True:
  2365. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2366. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2367. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2368. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2369. if empty == 'fail':
  2370. return 'fail'
  2371. if empty.is_empty:
  2372. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2373. _("Could not get the extent of the area to be non copper cleared."))
  2374. return 'fail'
  2375. elif ncc_obj.kind == 'gerber' and isotooldia:
  2376. isolated_geo = []
  2377. # unfortunately for this function to work time efficient,
  2378. # if the Gerber was loaded without buffering then it require the buffering now.
  2379. if self.app.defaults['gerber_buffering'] == 'no':
  2380. self.solid_geometry = ncc_obj.solid_geometry.buffer(0)
  2381. else:
  2382. self.solid_geometry = ncc_obj.solid_geometry
  2383. # if milling type is climb then the move is counter-clockwise around features
  2384. milling_type = self.app.defaults["tools_nccmilling_type"]
  2385. for tool_iso in isotooldia:
  2386. new_geometry = []
  2387. if milling_type == 'cl':
  2388. isolated_geo = self.generate_envelope(tool_iso / 2, 1)
  2389. else:
  2390. isolated_geo = self.generate_envelope(tool_iso / 2, 0)
  2391. if isolated_geo == 'fail':
  2392. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  2393. else:
  2394. if ncc_margin < tool_iso:
  2395. app_obj.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  2396. "than isolation tool diameter."))
  2397. try:
  2398. for geo_elem in isolated_geo:
  2399. # provide the app with a way to process the GUI events when in a blocking loop
  2400. QtWidgets.QApplication.processEvents()
  2401. if self.app.abort_flag:
  2402. # graceful abort requested by the user
  2403. raise FlatCAMApp.GracefulException
  2404. if isinstance(geo_elem, Polygon):
  2405. for ring in self.poly2rings(geo_elem):
  2406. new_geo = ring.intersection(bounding_box)
  2407. if new_geo and not new_geo.is_empty:
  2408. new_geometry.append(new_geo)
  2409. elif isinstance(geo_elem, MultiPolygon):
  2410. for poly in geo_elem:
  2411. for ring in self.poly2rings(poly):
  2412. new_geo = ring.intersection(bounding_box)
  2413. if new_geo and not new_geo.is_empty:
  2414. new_geometry.append(new_geo)
  2415. elif isinstance(geo_elem, LineString):
  2416. new_geo = geo_elem.intersection(bounding_box)
  2417. if new_geo:
  2418. if not new_geo.is_empty:
  2419. new_geometry.append(new_geo)
  2420. elif isinstance(geo_elem, MultiLineString):
  2421. for line_elem in geo_elem:
  2422. new_geo = line_elem.intersection(bounding_box)
  2423. if new_geo and not new_geo.is_empty:
  2424. new_geometry.append(new_geo)
  2425. except TypeError:
  2426. if isinstance(isolated_geo, Polygon):
  2427. for ring in self.poly2rings(isolated_geo):
  2428. new_geo = ring.intersection(bounding_box)
  2429. if new_geo:
  2430. if not new_geo.is_empty:
  2431. new_geometry.append(new_geo)
  2432. elif isinstance(isolated_geo, LineString):
  2433. new_geo = isolated_geo.intersection(bounding_box)
  2434. if new_geo and not new_geo.is_empty:
  2435. new_geometry.append(new_geo)
  2436. elif isinstance(isolated_geo, MultiLineString):
  2437. for line_elem in isolated_geo:
  2438. new_geo = line_elem.intersection(bounding_box)
  2439. if new_geo and not new_geo.is_empty:
  2440. new_geometry.append(new_geo)
  2441. # a MultiLineString geometry element will show that the isolation is broken for this tool
  2442. for geo_e in new_geometry:
  2443. if type(geo_e) == MultiLineString:
  2444. warning_flag += 1
  2445. break
  2446. for k, v in tools_storage.items():
  2447. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2448. tool_iso)):
  2449. current_uid = int(k)
  2450. # add the solid_geometry to the current too in self.paint_tools dictionary
  2451. # and then reset the temporary list that stored that solid_geometry
  2452. v['solid_geometry'] = deepcopy(new_geometry)
  2453. v['data']['name'] = name
  2454. break
  2455. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2456. sol_geo = cascaded_union(isolated_geo)
  2457. if has_offset is True:
  2458. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2459. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2460. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2461. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2462. if empty == 'fail':
  2463. return 'fail'
  2464. if empty.is_empty:
  2465. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2466. _("Isolation geometry is broken. Margin is less than isolation tool diameter."))
  2467. return 'fail'
  2468. elif ncc_obj.kind == 'geometry':
  2469. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  2470. if has_offset is True:
  2471. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2472. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2473. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2474. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2475. if empty == 'fail':
  2476. return 'fail'
  2477. if empty.is_empty:
  2478. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2479. _("Could not get the extent of the area to be non copper cleared."))
  2480. return 'fail'
  2481. else:
  2482. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  2483. return 'fail'
  2484. if type(empty) is Polygon:
  2485. empty = MultiPolygon([empty])
  2486. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  2487. self.app.inform.emit(_("NCC Tool. Finished calculation of 'empty' area."))
  2488. # COPPER CLEARING #
  2489. cp = None
  2490. for tool in sorted_tools:
  2491. log.debug("Starting geometry processing for tool: %s" % str(tool))
  2492. if self.app.abort_flag:
  2493. # graceful abort requested by the user
  2494. raise FlatCAMApp.GracefulException
  2495. # provide the app with a way to process the GUI events when in a blocking loop
  2496. QtWidgets.QApplication.processEvents()
  2497. app_obj.inform.emit('[success] %s = %s%s %s' % (
  2498. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  2499. )
  2500. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2501. cleared_geo[:] = []
  2502. # Get remaining tools offset
  2503. offset -= (tool - 1e-12)
  2504. # Area to clear
  2505. area = empty.buffer(-offset)
  2506. try:
  2507. area = area.difference(cleared)
  2508. except Exception:
  2509. continue
  2510. # Transform area to MultiPolygon
  2511. if type(area) is Polygon:
  2512. area = MultiPolygon([area])
  2513. # variables to display the percentage of work done
  2514. geo_len = len(area.geoms)
  2515. old_disp_number = 0
  2516. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2517. if area.geoms:
  2518. if len(area.geoms) > 0:
  2519. pol_nr = 0
  2520. for p in area.geoms:
  2521. # provide the app with a way to process the GUI events when in a blocking loop
  2522. QtWidgets.QApplication.processEvents()
  2523. if self.app.abort_flag:
  2524. # graceful abort requested by the user
  2525. raise FlatCAMApp.GracefulException
  2526. # clean the polygon
  2527. p = p.buffer(0)
  2528. if p is not None and p.is_valid:
  2529. poly_processed = list()
  2530. try:
  2531. for pol in p:
  2532. if pol is not None and isinstance(pol, Polygon):
  2533. if ncc_method == 'standard':
  2534. cp = self.clear_polygon(pol, tool,
  2535. self.grb_circle_steps,
  2536. overlap=overlap, contour=contour,
  2537. connect=connect,
  2538. prog_plot=False)
  2539. elif ncc_method == 'seed':
  2540. cp = self.clear_polygon2(pol, tool,
  2541. self.grb_circle_steps,
  2542. overlap=overlap, contour=contour,
  2543. connect=connect,
  2544. prog_plot=False)
  2545. else:
  2546. cp = self.clear_polygon3(pol, tool,
  2547. self.grb_circle_steps,
  2548. overlap=overlap, contour=contour,
  2549. connect=connect,
  2550. prog_plot=False)
  2551. if cp:
  2552. cleared_geo += list(cp.get_objects())
  2553. poly_processed.append(True)
  2554. else:
  2555. poly_processed.append(False)
  2556. log.warning("Polygon in MultiPolygon can not be cleared.")
  2557. else:
  2558. log.warning("Geo in Iterable can not be cleared because it is not Polygon. "
  2559. "It is: %s" % str(type(pol)))
  2560. except TypeError:
  2561. if isinstance(p, Polygon):
  2562. if ncc_method == 'standard':
  2563. cp = self.clear_polygon(p, tool, self.grb_circle_steps,
  2564. overlap=overlap, contour=contour, connect=connect,
  2565. prog_plot=False)
  2566. elif ncc_method == 'seed':
  2567. cp = self.clear_polygon2(p, tool, self.grb_circle_steps,
  2568. overlap=overlap, contour=contour, connect=connect,
  2569. prog_plot=False)
  2570. else:
  2571. cp = self.clear_polygon3(p, tool, self.grb_circle_steps,
  2572. overlap=overlap, contour=contour, connect=connect,
  2573. prog_plot=False)
  2574. if cp:
  2575. cleared_geo += list(cp.get_objects())
  2576. poly_processed.append(True)
  2577. else:
  2578. poly_processed.append(False)
  2579. log.warning("Polygon can not be cleared.")
  2580. else:
  2581. log.warning("Geo can not be cleared because it is: %s" % str(type(p)))
  2582. p_cleared = poly_processed.count(True)
  2583. p_not_cleared = poly_processed.count(False)
  2584. if p_not_cleared:
  2585. app_obj.poly_not_cleared = True
  2586. if p_cleared == 0:
  2587. continue
  2588. pol_nr += 1
  2589. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2590. # log.debug("Polygons cleared: %d" % pol_nr)
  2591. if old_disp_number < disp_number <= 100:
  2592. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2593. old_disp_number = disp_number
  2594. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2595. # check if there is a geometry at all in the cleared geometry
  2596. if cleared_geo:
  2597. # Overall cleared area
  2598. cleared = empty.buffer(-offset * (1 + overlap)).buffer(-tool / 1.999999).buffer(
  2599. tool / 1.999999)
  2600. # clean-up cleared geo
  2601. cleared = cleared.buffer(0)
  2602. # find the tooluid associated with the current tool_dia so we know where to add the tool
  2603. # solid_geometry
  2604. for k, v in tools_storage.items():
  2605. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2606. tool)):
  2607. current_uid = int(k)
  2608. # add the solid_geometry to the current too in self.paint_tools dictionary
  2609. # and then reset the temporary list that stored that solid_geometry
  2610. v['solid_geometry'] = deepcopy(cleared_geo)
  2611. v['data']['name'] = name
  2612. break
  2613. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2614. else:
  2615. log.debug("There are no geometries in the cleared polygon.")
  2616. # delete tools with empty geometry
  2617. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  2618. for uid, uid_val in list(tools_storage.items()):
  2619. try:
  2620. # if the solid_geometry (type=list) is empty
  2621. if not uid_val['solid_geometry']:
  2622. tools_storage.pop(uid, None)
  2623. except KeyError:
  2624. tools_storage.pop(uid, None)
  2625. geo_obj.options["cnctooldia"] = str(tool)
  2626. geo_obj.multigeo = True
  2627. geo_obj.tools.clear()
  2628. geo_obj.tools = dict(tools_storage)
  2629. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2630. has_solid_geo = 0
  2631. for tooluid in geo_obj.tools:
  2632. if geo_obj.tools[tooluid]['solid_geometry']:
  2633. has_solid_geo += 1
  2634. if has_solid_geo == 0:
  2635. app_obj.inform.emit('[ERROR] %s' %
  2636. _("There is no NCC Geometry in the file.\n"
  2637. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2638. "Change the painting parameters and try again."))
  2639. return 'fail'
  2640. # check to see if geo_obj.tools is empty
  2641. # it will be updated only if there is a solid_geometry for tools
  2642. if geo_obj.tools:
  2643. if warning_flag == 0:
  2644. self.app.inform.emit('[success] %s' % _("NCC Tool clear all done."))
  2645. else:
  2646. self.app.inform.emit('[WARNING] %s: %s %s.' % (
  2647. _("NCC Tool clear all done but the copper features isolation is broken for"),
  2648. str(warning_flag),
  2649. _("tools")))
  2650. return
  2651. # create the solid_geometry
  2652. geo_obj.solid_geometry = list()
  2653. for tooluid in geo_obj.tools:
  2654. if geo_obj.tools[tooluid]['solid_geometry']:
  2655. try:
  2656. for geo in geo_obj.tools[tooluid]['solid_geometry']:
  2657. geo_obj.solid_geometry.append(geo)
  2658. except TypeError:
  2659. geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  2660. else:
  2661. # I will use this variable for this purpose although it was meant for something else
  2662. # signal that we have no geo in the object therefore don't create it
  2663. app_obj.poly_not_cleared = False
  2664. return "fail"
  2665. # ###########################################################################################
  2666. # Initializes the new geometry object for the case of the rest-machining ####################
  2667. # ###########################################################################################
  2668. def gen_clear_area_rest(geo_obj, app_obj):
  2669. assert geo_obj.kind == 'geometry', \
  2670. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2671. log.debug("NCC Tool. Rest machining copper clearing task started.")
  2672. app_obj.inform.emit('_(NCC Tool. Rest machining copper clearing task started.')
  2673. # provide the app with a way to process the GUI events when in a blocking loop
  2674. if not run_threaded:
  2675. QtWidgets.QApplication.processEvents()
  2676. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  2677. # will store the number of tools for which the isolation is broken
  2678. warning_flag = 0
  2679. sorted_tools.sort(reverse=True)
  2680. cleared_geo = []
  2681. cleared_by_last_tool = []
  2682. rest_geo = []
  2683. current_uid = 1
  2684. try:
  2685. tool = eval(self.app.defaults["tools_ncctools"])[0]
  2686. except TypeError:
  2687. tool = eval(self.app.defaults["tools_ncctools"])
  2688. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  2689. app_obj.poly_not_cleared = True
  2690. log.debug("NCC Tool. Calculate 'empty' area.")
  2691. app_obj.inform.emit("NCC Tool. Calculate 'empty' area.")
  2692. # ###################################################################################################
  2693. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  2694. # ###################################################################################################
  2695. if ncc_obj.kind == 'gerber' and not isotooldia:
  2696. sol_geo = ncc_obj.solid_geometry
  2697. if has_offset is True:
  2698. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2699. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2700. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2701. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2702. if empty == 'fail':
  2703. return 'fail'
  2704. if empty.is_empty:
  2705. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2706. _("Could not get the extent of the area to be non copper cleared."))
  2707. return 'fail'
  2708. elif ncc_obj.kind == 'gerber' and isotooldia:
  2709. isolated_geo = []
  2710. self.solid_geometry = ncc_obj.solid_geometry
  2711. # if milling type is climb then the move is counter-clockwise around features
  2712. milling_type = self.app.defaults["tools_nccmilling_type"]
  2713. for tool_iso in isotooldia:
  2714. new_geometry = []
  2715. if milling_type == 'cl':
  2716. isolated_geo = self.generate_envelope(tool_iso, 1)
  2717. else:
  2718. isolated_geo = self.generate_envelope(tool_iso, 0)
  2719. if isolated_geo == 'fail':
  2720. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  2721. else:
  2722. app_obj.inform.emit('[WARNING_NOTCL] %s' % _("Isolation geometry is broken. Margin is less "
  2723. "than isolation tool diameter."))
  2724. try:
  2725. for geo_elem in isolated_geo:
  2726. # provide the app with a way to process the GUI events when in a blocking loop
  2727. QtWidgets.QApplication.processEvents()
  2728. if self.app.abort_flag:
  2729. # graceful abort requested by the user
  2730. raise FlatCAMApp.GracefulException
  2731. if isinstance(geo_elem, Polygon):
  2732. for ring in self.poly2rings(geo_elem):
  2733. new_geo = ring.intersection(bounding_box)
  2734. if new_geo and not new_geo.is_empty:
  2735. new_geometry.append(new_geo)
  2736. elif isinstance(geo_elem, MultiPolygon):
  2737. for poly in geo_elem:
  2738. for ring in self.poly2rings(poly):
  2739. new_geo = ring.intersection(bounding_box)
  2740. if new_geo and not new_geo.is_empty:
  2741. new_geometry.append(new_geo)
  2742. elif isinstance(geo_elem, LineString):
  2743. new_geo = geo_elem.intersection(bounding_box)
  2744. if new_geo:
  2745. if not new_geo.is_empty:
  2746. new_geometry.append(new_geo)
  2747. elif isinstance(geo_elem, MultiLineString):
  2748. for line_elem in geo_elem:
  2749. new_geo = line_elem.intersection(bounding_box)
  2750. if new_geo and not new_geo.is_empty:
  2751. new_geometry.append(new_geo)
  2752. except TypeError:
  2753. try:
  2754. if isinstance(isolated_geo, Polygon):
  2755. for ring in self.poly2rings(isolated_geo):
  2756. new_geo = ring.intersection(bounding_box)
  2757. if new_geo:
  2758. if not new_geo.is_empty:
  2759. new_geometry.append(new_geo)
  2760. elif isinstance(isolated_geo, LineString):
  2761. new_geo = isolated_geo.intersection(bounding_box)
  2762. if new_geo and not new_geo.is_empty:
  2763. new_geometry.append(new_geo)
  2764. elif isinstance(isolated_geo, MultiLineString):
  2765. for line_elem in isolated_geo:
  2766. new_geo = line_elem.intersection(bounding_box)
  2767. if new_geo and not new_geo.is_empty:
  2768. new_geometry.append(new_geo)
  2769. except Exception as e:
  2770. pass
  2771. # a MultiLineString geometry element will show that the isolation is broken for this tool
  2772. for geo_e in new_geometry:
  2773. if type(geo_e) == MultiLineString:
  2774. warning_flag += 1
  2775. break
  2776. for k, v in tools_storage.items():
  2777. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2778. tool_iso)):
  2779. current_uid = int(k)
  2780. # add the solid_geometry to the current too in self.paint_tools dictionary
  2781. # and then reset the temporary list that stored that solid_geometry
  2782. v['solid_geometry'] = deepcopy(new_geometry)
  2783. v['data']['name'] = name
  2784. break
  2785. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2786. sol_geo = cascaded_union(isolated_geo)
  2787. if has_offset is True:
  2788. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2789. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2790. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2791. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2792. if empty == 'fail':
  2793. return 'fail'
  2794. if empty.is_empty:
  2795. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2796. _("Isolation geometry is broken. Margin is less than isolation tool diameter."))
  2797. return 'fail'
  2798. elif ncc_obj.kind == 'geometry':
  2799. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  2800. if has_offset is True:
  2801. app_obj.inform.emit('[WARNING_NOTCL] %s ...' % _("Buffering"))
  2802. sol_geo = sol_geo.buffer(distance=ncc_offset)
  2803. app_obj.inform.emit('[success] %s ...' % _("Buffering finished"))
  2804. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  2805. if empty == 'fail':
  2806. return 'fail'
  2807. if empty.is_empty:
  2808. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  2809. _("Could not get the extent of the area to be non copper cleared."))
  2810. return 'fail'
  2811. else:
  2812. app_obj.inform.emit('[ERROR_NOTCL] %s' % _('The selected object is not suitable for copper clearing.'))
  2813. return
  2814. if self.app.abort_flag:
  2815. # graceful abort requested by the user
  2816. raise FlatCAMApp.GracefulException
  2817. if type(empty) is Polygon:
  2818. empty = MultiPolygon([empty])
  2819. area = empty.buffer(0)
  2820. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  2821. app_obj.inform.emit("NCC Tool. Finished calculation of 'empty' area.")
  2822. # Generate area for each tool
  2823. while sorted_tools:
  2824. if self.app.abort_flag:
  2825. # graceful abort requested by the user
  2826. raise FlatCAMApp.GracefulException
  2827. tool = sorted_tools.pop(0)
  2828. log.debug("Starting geometry processing for tool: %s" % str(tool))
  2829. app_obj.inform.emit('[success] %s = %s%s %s' % (
  2830. _('NCC Tool clearing with tool diameter'), str(tool), units.lower(), _('started.'))
  2831. )
  2832. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2833. tool_used = tool - 1e-12
  2834. cleared_geo[:] = []
  2835. # Area to clear
  2836. for poly in cleared_by_last_tool:
  2837. # provide the app with a way to process the GUI events when in a blocking loop
  2838. QtWidgets.QApplication.processEvents()
  2839. if self.app.abort_flag:
  2840. # graceful abort requested by the user
  2841. raise FlatCAMApp.GracefulException
  2842. try:
  2843. area = area.difference(poly)
  2844. except Exception:
  2845. pass
  2846. cleared_by_last_tool[:] = []
  2847. # Transform area to MultiPolygon
  2848. if type(area) is Polygon:
  2849. area = MultiPolygon([area])
  2850. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  2851. # and rest_geo it's a list
  2852. allparts = [p.buffer(0) for p in area.geoms]
  2853. allparts += deepcopy(rest_geo)
  2854. rest_geo[:] = []
  2855. area = MultiPolygon(deepcopy(allparts))
  2856. allparts[:] = []
  2857. # variables to display the percentage of work done
  2858. geo_len = len(area.geoms)
  2859. old_disp_number = 0
  2860. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2861. if area.geoms:
  2862. if len(area.geoms) > 0:
  2863. pol_nr = 0
  2864. for p in area.geoms:
  2865. if self.app.abort_flag:
  2866. # graceful abort requested by the user
  2867. raise FlatCAMApp.GracefulException
  2868. # clean the polygon
  2869. p = p.buffer(0)
  2870. if p is not None and p.is_valid:
  2871. # provide the app with a way to process the GUI events when in a blocking loop
  2872. QtWidgets.QApplication.processEvents()
  2873. if isinstance(p, Polygon):
  2874. try:
  2875. if ncc_method == 'standard':
  2876. cp = self.clear_polygon(p, tool_used,
  2877. self.grb_circle_steps,
  2878. overlap=overlap, contour=contour, connect=connect,
  2879. prog_plot=False)
  2880. elif ncc_method == 'seed':
  2881. cp = self.clear_polygon2(p, tool_used,
  2882. self.grb_circle_steps,
  2883. overlap=overlap, contour=contour, connect=connect,
  2884. prog_plot=False)
  2885. else:
  2886. cp = self.clear_polygon3(p, tool_used,
  2887. self.grb_circle_steps,
  2888. overlap=overlap, contour=contour, connect=connect,
  2889. prog_plot=False)
  2890. cleared_geo.append(list(cp.get_objects()))
  2891. except Exception as e:
  2892. log.warning("Polygon can't be cleared. %s" % str(e))
  2893. # this polygon should be added to a list and then try clear it with
  2894. # a smaller tool
  2895. rest_geo.append(p)
  2896. elif isinstance(p, MultiPolygon):
  2897. for poly in p:
  2898. if poly is not None:
  2899. # provide the app with a way to process the GUI events when
  2900. # in a blocking loop
  2901. QtWidgets.QApplication.processEvents()
  2902. try:
  2903. if ncc_method == 'standard':
  2904. cp = self.clear_polygon(poly, tool_used,
  2905. self.grb_circle_steps,
  2906. overlap=overlap, contour=contour,
  2907. connect=connect,
  2908. prog_plot=False)
  2909. elif ncc_method == 'seed':
  2910. cp = self.clear_polygon2(poly, tool_used,
  2911. self.grb_circle_steps,
  2912. overlap=overlap, contour=contour,
  2913. connect=connect,
  2914. prog_plot=False)
  2915. else:
  2916. cp = self.clear_polygon3(poly, tool_used,
  2917. self.grb_circle_steps,
  2918. overlap=overlap, contour=contour,
  2919. connect=connect,
  2920. prog_plot=False)
  2921. cleared_geo.append(list(cp.get_objects()))
  2922. except Exception as e:
  2923. log.warning("Polygon can't be cleared. %s" % str(e))
  2924. # this polygon should be added to a list and then try clear it with
  2925. # a smaller tool
  2926. rest_geo.append(poly)
  2927. pol_nr += 1
  2928. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2929. # log.debug("Polygons cleared: %d" % pol_nr)
  2930. if old_disp_number < disp_number <= 100:
  2931. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2932. old_disp_number = disp_number
  2933. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2934. if self.app.abort_flag:
  2935. # graceful abort requested by the user
  2936. raise FlatCAMApp.GracefulException
  2937. # check if there is a geometry at all in the cleared geometry
  2938. if cleared_geo:
  2939. # Overall cleared area
  2940. cleared_area = list(self.flatten_list(cleared_geo))
  2941. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  2942. # for p in cleared_area])
  2943. # here we store the poly's already processed in the original geometry by the current tool
  2944. # into cleared_by_last_tool list
  2945. # this will be sutracted from the original geometry_to_be_cleared and make data for
  2946. # the next tool
  2947. buffer_value = tool_used / 2
  2948. for p in cleared_area:
  2949. if self.app.abort_flag:
  2950. # graceful abort requested by the user
  2951. raise FlatCAMApp.GracefulException
  2952. poly = p.buffer(buffer_value)
  2953. cleared_by_last_tool.append(poly)
  2954. # find the tooluid associated with the current tool_dia so we know
  2955. # where to add the tool solid_geometry
  2956. for k, v in tools_storage.items():
  2957. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals,
  2958. tool)):
  2959. current_uid = int(k)
  2960. # add the solid_geometry to the current too in self.paint_tools dictionary
  2961. # and then reset the temporary list that stored that solid_geometry
  2962. v['solid_geometry'] = deepcopy(cleared_area)
  2963. v['data']['name'] = name
  2964. cleared_area[:] = []
  2965. break
  2966. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  2967. else:
  2968. log.debug("There are no geometries in the cleared polygon.")
  2969. geo_obj.multigeo = True
  2970. geo_obj.options["cnctooldia"] = str(tool)
  2971. # check to see if geo_obj.tools is empty
  2972. # it will be updated only if there is a solid_geometry for tools
  2973. if geo_obj.tools:
  2974. if warning_flag == 0:
  2975. self.app.inform.emit('[success] %s' % _("NCC Tool Rest Machining clear all done."))
  2976. else:
  2977. self.app.inform.emit(
  2978. '[WARNING] %s: %s %s.' % (_("NCC Tool Rest Machining clear all done but the copper features "
  2979. "isolation is broken for"), str(warning_flag), _("tools")))
  2980. return
  2981. # create the solid_geometry
  2982. geo_obj.solid_geometry = list()
  2983. for tooluid in geo_obj.tools:
  2984. if geo_obj.tools[tooluid]['solid_geometry']:
  2985. try:
  2986. for geo in geo_obj.tools[tooluid]['solid_geometry']:
  2987. geo_obj.solid_geometry.append(geo)
  2988. except TypeError:
  2989. geo_obj.solid_geometry.append(geo_obj.tools[tooluid]['solid_geometry'])
  2990. else:
  2991. # I will use this variable for this purpose although it was meant for something else
  2992. # signal that we have no geo in the object therefore don't create it
  2993. app_obj.poly_not_cleared = False
  2994. return "fail"
  2995. # ###########################################################################################
  2996. # Create the Job function and send it to the worker to be processed in another thread #######
  2997. # ###########################################################################################
  2998. def job_thread(app_obj):
  2999. try:
  3000. if rest_machining_choice is True:
  3001. app_obj.new_object("geometry", name, gen_clear_area_rest, plot=plot)
  3002. else:
  3003. app_obj.new_object("geometry", name, gen_clear_area, plot=plot)
  3004. except FlatCAMApp.GracefulException:
  3005. if run_threaded:
  3006. proc.done()
  3007. return
  3008. except Exception:
  3009. if run_threaded:
  3010. proc.done()
  3011. traceback.print_stack()
  3012. return
  3013. if run_threaded:
  3014. proc.done()
  3015. else:
  3016. app_obj.proc_container.view.set_idle()
  3017. # focus on Selected Tab
  3018. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  3019. if run_threaded:
  3020. # Promise object with the new name
  3021. self.app.collection.promise(name)
  3022. # Background
  3023. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  3024. else:
  3025. job_thread(app_obj=self.app)
  3026. def get_ncc_empty_area(self, target, boundary=None):
  3027. """
  3028. Returns the complement of target geometry within
  3029. the given boundary polygon. If not specified, it defaults to
  3030. the rectangular bounding box of target geometry.
  3031. """
  3032. if isinstance(target, Polygon):
  3033. geo_len = 1
  3034. else:
  3035. geo_len = len(target)
  3036. pol_nr = 0
  3037. old_disp_number = 0
  3038. if boundary is None:
  3039. boundary = target.envelope
  3040. else:
  3041. boundary = boundary
  3042. try:
  3043. ret_val = boundary.difference(target)
  3044. except Exception as e:
  3045. try:
  3046. for el in target:
  3047. # provide the app with a way to process the GUI events when in a blocking loop
  3048. QtWidgets.QApplication.processEvents()
  3049. if self.app.abort_flag:
  3050. # graceful abort requested by the user
  3051. raise FlatCAMApp.GracefulException
  3052. boundary = boundary.difference(el)
  3053. pol_nr += 1
  3054. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  3055. if old_disp_number < disp_number <= 100:
  3056. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3057. old_disp_number = disp_number
  3058. return boundary
  3059. except Exception as e:
  3060. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3061. _("Try to use the Buffering Type = Full in Preferences -> Gerber General. "
  3062. "Reload the Gerber file after this change."))
  3063. return 'fail'
  3064. return ret_val
  3065. def reset_fields(self):
  3066. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  3067. def reset_usage(self):
  3068. self.obj_name = ""
  3069. self.ncc_obj = None
  3070. self.bound_obj = None
  3071. self.first_click = False
  3072. self.cursor_pos = None
  3073. self.mouse_is_dragging = False
  3074. self.sel_rect = []
  3075. @staticmethod
  3076. def poly2rings(poly):
  3077. return [poly.exterior] + [interior for interior in poly.interiors]
  3078. def generate_envelope(self, offset, invert, envelope_iso_type=2, follow=None):
  3079. # isolation_geometry produces an envelope that is going on the left of the geometry
  3080. # (the copper features). To leave the least amount of burrs on the features
  3081. # the tool needs to travel on the right side of the features (this is called conventional milling)
  3082. # the first pass is the one cutting all of the features, so it needs to be reversed
  3083. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  3084. # to cut on the right side of the left over copper i.e on the left side of the features.
  3085. try:
  3086. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type, follow=follow)
  3087. except Exception as e:
  3088. log.debug('NonCopperClear.generate_envelope() --> %s' % str(e))
  3089. return 'fail'
  3090. if invert:
  3091. try:
  3092. try:
  3093. pl = []
  3094. for p in geom:
  3095. if p is not None:
  3096. if isinstance(p, Polygon):
  3097. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  3098. elif isinstance(p, LinearRing):
  3099. pl.append(Polygon(p.coords[::-1]))
  3100. geom = MultiPolygon(pl)
  3101. except TypeError:
  3102. if isinstance(geom, Polygon) and geom is not None:
  3103. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  3104. elif isinstance(geom, LinearRing) and geom is not None:
  3105. geom = Polygon(geom.coords[::-1])
  3106. else:
  3107. log.debug("NonCopperClear.generate_envelope() Error --> Unexpected Geometry %s" %
  3108. type(geom))
  3109. except Exception as e:
  3110. log.debug("NonCopperClear.generate_envelope() Error --> %s" % str(e))
  3111. return 'fail'
  3112. return geom