ToolNonCopperClear.py 133 KB

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