ToolNonCopperClear.py 128 KB

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