ToolNonCopperClear.py 131 KB

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