ToolNonCopperClear.py 149 KB

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