ToolNonCopperClear.py 127 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. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1085. symbol='++', edge_color='black', size=20)
  1086. # update the positions on status bar
  1087. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  1088. "<b>Y</b>: %.4f" % (curr_pos[0], curr_pos[1]))
  1089. if self.cursor_pos is None:
  1090. self.cursor_pos = (0, 0)
  1091. dx = curr_pos[0] - float(self.cursor_pos[0])
  1092. dy = curr_pos[1] - float(self.cursor_pos[1])
  1093. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1094. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  1095. # draw the utility geometry
  1096. if self.first_click:
  1097. self.app.delete_selection_shape()
  1098. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  1099. coords=(curr_pos[0], curr_pos[1]))
  1100. def clear_copper(self, ncc_obj,
  1101. sel_obj=None,
  1102. ncctooldia=None,
  1103. isotooldia=None,
  1104. margin=None,
  1105. has_offset=None,
  1106. offset=None,
  1107. select_method=None,
  1108. outname=None,
  1109. overlap=None,
  1110. connect=None,
  1111. contour=None,
  1112. order=None,
  1113. method=None,
  1114. rest=None,
  1115. tools_storage=None,
  1116. plot=True,
  1117. run_threaded=True):
  1118. """
  1119. Clear the excess copper from the entire object.
  1120. :param ncc_obj: ncc cleared object
  1121. :param ncctooldia: a tuple or single element made out of diameters of the tools to be used to ncc clear
  1122. :param isotooldia: a tuple or single element made out of diameters of the tools to be used for isolation
  1123. :param overlap: value by which the paths will overlap
  1124. :param order: if the tools are ordered and how
  1125. :param select_method: if to do ncc on the whole object, on an defined area or on an area defined by
  1126. another object
  1127. :param has_offset: True if an offset is needed
  1128. :param offset: distance from the copper features where the copper clearing is stopping
  1129. :param margin: a border around cleared area
  1130. :param outname: name of the resulting object
  1131. :param connect: Connect lines to avoid tool lifts.
  1132. :param contour: Paint around the edges.
  1133. :param method: choice out of 'seed', 'normal', 'lines'
  1134. :param rest: True if to use rest-machining
  1135. :param tools_storage: whether to use the current tools_storage self.ncc_tools or a different one.
  1136. Usage of the different one is related to when this function is called from a TcL command.
  1137. :param run_threaded: If True the method will be run in a threaded way suitable for GUI usage; if False it will
  1138. run non-threaded for TclShell usage
  1139. :return:
  1140. """
  1141. proc = self.app.proc_container.new(_("Non-Copper clearing ..."))
  1142. # #####################################################################
  1143. # ####### Read the parameters #########################################
  1144. # #####################################################################
  1145. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value()
  1146. log.debug("NCC Tool started. Reading parameters.")
  1147. self.app.inform.emit(_("NCC Tool started. Reading parameters."))
  1148. ncc_method = method if method else self.ncc_method_radio.get_value()
  1149. if margin is not None:
  1150. ncc_margin = margin
  1151. else:
  1152. try:
  1153. ncc_margin = float(self.ncc_margin_entry.get_value())
  1154. except ValueError:
  1155. # try to convert comma to decimal point. if it's still not working error message and return
  1156. try:
  1157. ncc_margin = float(self.ncc_margin_entry.get_value().replace(',', '.'))
  1158. except ValueError:
  1159. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1160. return
  1161. if select_method is not None:
  1162. ncc_select = select_method
  1163. else:
  1164. ncc_select = self.reference_radio.get_value()
  1165. overlap = overlap if overlap else self.app.defaults["tools_nccoverlap"]
  1166. connect = connect if connect else self.app.defaults["tools_nccconnect"]
  1167. contour = contour if contour else self.app.defaults["tools_ncccontour"]
  1168. order = order if order else self.ncc_order_radio.get_value()
  1169. # determine if to use the progressive plotting
  1170. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  1171. prog_plot = True
  1172. else:
  1173. prog_plot = False
  1174. if tools_storage is not None:
  1175. tools_storage = tools_storage
  1176. else:
  1177. tools_storage = self.ncc_tools
  1178. ncc_offset = 0.0
  1179. if has_offset is True:
  1180. if offset is not None:
  1181. ncc_offset = offset
  1182. else:
  1183. try:
  1184. ncc_offset = float(self.ncc_offset_spinner.get_value())
  1185. except ValueError:
  1186. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1187. return
  1188. # ######################################################################################################
  1189. # # Read the tooldia parameter and create a sorted list out them - they may be more than one diameter ##
  1190. # ######################################################################################################
  1191. sorted_tools = []
  1192. if ncctooldia is not None:
  1193. try:
  1194. sorted_tools = [float(eval(dia)) for dia in ncctooldia.split(",") if dia != '']
  1195. except AttributeError:
  1196. if not isinstance(ncctooldia, list):
  1197. sorted_tools = [float(ncctooldia)]
  1198. else:
  1199. sorted_tools = ncctooldia
  1200. else:
  1201. for row in range(self.tools_table.rowCount()):
  1202. if self.tools_table.cellWidget(row, 1).currentText() == 'clear_op':
  1203. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1204. # ##############################################################################################################
  1205. # Prepare non-copper polygons. Create the bounding box area from which the copper features will be subtracted ##
  1206. # ##############################################################################################################
  1207. log.debug("NCC Tool. Preparing non-copper polygons.")
  1208. self.app.inform.emit(_("NCC Tool. Preparing non-copper polygons."))
  1209. try:
  1210. if sel_obj is None or sel_obj == 'itself':
  1211. ncc_sel_obj = ncc_obj
  1212. else:
  1213. ncc_sel_obj = sel_obj
  1214. except Exception as e:
  1215. log.debug("NonCopperClear.clear_copper() --> %s" % str(e))
  1216. return 'fail'
  1217. bounding_box = None
  1218. if ncc_select == 'itself':
  1219. geo_n = ncc_sel_obj.solid_geometry
  1220. try:
  1221. if isinstance(geo_n, MultiPolygon):
  1222. env_obj = geo_n.convex_hull
  1223. elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  1224. (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  1225. env_obj = cascaded_union(geo_n)
  1226. else:
  1227. env_obj = cascaded_union(geo_n)
  1228. env_obj = env_obj.convex_hull
  1229. bounding_box = env_obj.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1230. except Exception as e:
  1231. log.debug("NonCopperClear.clear_copper() 'itself' --> %s" % str(e))
  1232. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  1233. return 'fail'
  1234. elif ncc_select == 'area':
  1235. geo_n = cascaded_union(self.sel_rect)
  1236. try:
  1237. __ = iter(geo_n)
  1238. except Exception as e:
  1239. log.debug("NonCopperClear.clear_copper() 'area' --> %s" % str(e))
  1240. geo_n = [geo_n]
  1241. geo_buff_list = []
  1242. for poly in geo_n:
  1243. if self.app.abort_flag:
  1244. # graceful abort requested by the user
  1245. raise FlatCAMApp.GracefulException
  1246. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1247. bounding_box = cascaded_union(geo_buff_list)
  1248. elif ncc_select == 'box':
  1249. geo_n = ncc_sel_obj.solid_geometry
  1250. if isinstance(ncc_sel_obj, FlatCAMGeometry):
  1251. try:
  1252. __ = iter(geo_n)
  1253. except Exception as e:
  1254. log.debug("NonCopperClear.clear_copper() 'box' --> %s" % str(e))
  1255. geo_n = [geo_n]
  1256. geo_buff_list = []
  1257. for poly in geo_n:
  1258. if self.app.abort_flag:
  1259. # graceful abort requested by the user
  1260. raise FlatCAMApp.GracefulException
  1261. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1262. bounding_box = cascaded_union(geo_buff_list)
  1263. elif isinstance(ncc_sel_obj, FlatCAMGerber):
  1264. geo_n = cascaded_union(geo_n).convex_hull
  1265. bounding_box = cascaded_union(self.ncc_obj.solid_geometry).convex_hull.intersection(geo_n)
  1266. bounding_box = bounding_box.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1267. else:
  1268. self.app.inform.emit('[ERROR_NOTCL] %s' % _("The reference object type is not supported."))
  1269. return 'fail'
  1270. log.debug("NCC Tool. Finished non-copper polygons.")
  1271. # ########################################################################################################
  1272. # set the name for the future Geometry object
  1273. # I do it here because it is also stored inside the gen_clear_area() and gen_clear_area_rest() methods
  1274. # ########################################################################################################
  1275. rest_machining_choice = rest if rest is not None else self.app.defaults["tools_nccrest"]
  1276. if rest_machining_choice is True:
  1277. name = outname if outname is not None else self.obj_name + "_ncc_rm"
  1278. else:
  1279. name = outname if outname is not None else self.obj_name + "_ncc"
  1280. # ##########################################################################################
  1281. # Initializes the new geometry object ######################################################
  1282. # ##########################################################################################
  1283. def gen_clear_area(geo_obj, app_obj):
  1284. assert isinstance(geo_obj, FlatCAMGeometry), \
  1285. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1286. log.debug("NCC Tool. Normal copper clearing task started.")
  1287. self.app.inform.emit(_("NCC Tool. Finished non-copper polygons. Normal copper clearing task started."))
  1288. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  1289. # will store the number of tools for which the isolation is broken
  1290. warning_flag = 0
  1291. if order == 'fwd':
  1292. sorted_tools.sort(reverse=False)
  1293. elif order == 'rev':
  1294. sorted_tools.sort(reverse=True)
  1295. else:
  1296. pass
  1297. cleared_geo = []
  1298. # Already cleared area
  1299. cleared = MultiPolygon()
  1300. # flag for polygons not cleared
  1301. app_obj.poly_not_cleared = False
  1302. # Generate area for each tool
  1303. offset = sum(sorted_tools)
  1304. current_uid = int(1)
  1305. try:
  1306. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1307. except TypeError:
  1308. tool = eval(self.app.defaults["tools_ncctools"])
  1309. # ###################################################################################################
  1310. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  1311. # ###################################################################################################
  1312. log.debug("NCC Tool. Calculate 'empty' area.")
  1313. self.app.inform.emit(_("NCC Tool. Calculate 'empty' area."))
  1314. if isinstance(ncc_obj, FlatCAMGerber) and not isotooldia:
  1315. # unfortunately for this function to work time efficient,
  1316. # if the Gerber was loaded without buffering then it require the buffering now.
  1317. if self.app.defaults['gerber_buffering'] == 'no':
  1318. sol_geo = ncc_obj.solid_geometry.buffer(0)
  1319. else:
  1320. sol_geo = ncc_obj.solid_geometry
  1321. if has_offset is True:
  1322. app_obj.inform.emit('[WARNING_NOTCL] %s ...' %
  1323. _("Buffering"))
  1324. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1325. app_obj.inform.emit('[success] %s ...' %
  1326. _("Buffering finished"))
  1327. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1328. if empty == 'fail':
  1329. return 'fail'
  1330. elif isinstance(ncc_obj, FlatCAMGerber) and isotooldia:
  1331. isolated_geo = []
  1332. # unfortunately for this function to work time efficient,
  1333. # if the Gerber was loaded without buffering then it require the buffering now.
  1334. if self.app.defaults['gerber_buffering'] == 'no':
  1335. self.solid_geometry = ncc_obj.solid_geometry.buffer(0)
  1336. else:
  1337. self.solid_geometry = ncc_obj.solid_geometry
  1338. # if milling type is climb then the move is counter-clockwise around features
  1339. milling_type = self.milling_type_radio.get_value()
  1340. for tool_iso in isotooldia:
  1341. new_geometry = []
  1342. if milling_type == 'cl':
  1343. isolated_geo = self.generate_envelope(tool_iso / 2, 1)
  1344. else:
  1345. isolated_geo = self.generate_envelope(tool_iso / 2, 0)
  1346. if isolated_geo == 'fail':
  1347. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1348. else:
  1349. try:
  1350. for geo_elem in isolated_geo:
  1351. if self.app.abort_flag:
  1352. # graceful abort requested by the user
  1353. raise FlatCAMApp.GracefulException
  1354. if isinstance(geo_elem, Polygon):
  1355. for ring in self.poly2rings(geo_elem):
  1356. new_geo = ring.intersection(bounding_box)
  1357. if new_geo and not new_geo.is_empty:
  1358. new_geometry.append(new_geo)
  1359. elif isinstance(geo_elem, MultiPolygon):
  1360. for poly in geo_elem:
  1361. for ring in self.poly2rings(poly):
  1362. new_geo = ring.intersection(bounding_box)
  1363. if new_geo and not new_geo.is_empty:
  1364. new_geometry.append(new_geo)
  1365. elif isinstance(geo_elem, LineString):
  1366. new_geo = geo_elem.intersection(bounding_box)
  1367. if new_geo:
  1368. if not new_geo.is_empty:
  1369. new_geometry.append(new_geo)
  1370. elif isinstance(geo_elem, MultiLineString):
  1371. for line_elem in geo_elem:
  1372. new_geo = line_elem.intersection(bounding_box)
  1373. if new_geo and not new_geo.is_empty:
  1374. new_geometry.append(new_geo)
  1375. except TypeError:
  1376. if isinstance(isolated_geo, Polygon):
  1377. for ring in self.poly2rings(isolated_geo):
  1378. new_geo = ring.intersection(bounding_box)
  1379. if new_geo:
  1380. if not new_geo.is_empty:
  1381. new_geometry.append(new_geo)
  1382. elif isinstance(isolated_geo, LineString):
  1383. new_geo = isolated_geo.intersection(bounding_box)
  1384. if new_geo and not new_geo.is_empty:
  1385. new_geometry.append(new_geo)
  1386. elif isinstance(isolated_geo, MultiLineString):
  1387. for line_elem in isolated_geo:
  1388. new_geo = line_elem.intersection(bounding_box)
  1389. if new_geo and not new_geo.is_empty:
  1390. new_geometry.append(new_geo)
  1391. # a MultiLineString geometry element will show that the isolation is broken for this tool
  1392. for geo_e in new_geometry:
  1393. if type(geo_e) == MultiLineString:
  1394. warning_flag += 1
  1395. break
  1396. for k, v in tools_storage.items():
  1397. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_iso):
  1398. current_uid = int(k)
  1399. # add the solid_geometry to the current too in self.paint_tools dictionary
  1400. # and then reset the temporary list that stored that solid_geometry
  1401. v['solid_geometry'] = deepcopy(new_geometry)
  1402. v['data']['name'] = name
  1403. break
  1404. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1405. sol_geo = cascaded_union(isolated_geo)
  1406. if has_offset is True:
  1407. app_obj.inform.emit('[WARNING_NOTCL] %s ...' %
  1408. _("Buffering"))
  1409. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1410. app_obj.inform.emit('[success] %s ...' %
  1411. _("Buffering finished"))
  1412. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1413. if empty == 'fail':
  1414. return 'fail'
  1415. elif isinstance(ncc_obj, FlatCAMGeometry):
  1416. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  1417. if has_offset is True:
  1418. app_obj.inform.emit('[WARNING_NOTCL] %s ...' %
  1419. _("Buffering"))
  1420. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1421. app_obj.inform.emit('[success] %s ...' %
  1422. _("Buffering finished"))
  1423. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1424. if empty == 'fail':
  1425. return 'fail'
  1426. else:
  1427. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1428. _('The selected object is not suitable for copper clearing.'))
  1429. return
  1430. if empty.is_empty:
  1431. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1432. _("Could not get the extent of the area to be non copper cleared."))
  1433. return 'fail'
  1434. if type(empty) is Polygon:
  1435. empty = MultiPolygon([empty])
  1436. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  1437. self.app.inform.emit(_("NCC Tool. Finished calculation of 'empty' area."))
  1438. cp = None
  1439. for tool in sorted_tools:
  1440. log.debug("Starting geometry processing for tool: %s" % str(tool))
  1441. if self.app.abort_flag:
  1442. # graceful abort requested by the user
  1443. raise FlatCAMApp.GracefulException
  1444. app_obj.inform.emit(
  1445. '[success] %s %s%s %s' % (_('NCC Tool clearing with tool diameter = '),
  1446. str(tool),
  1447. units.lower(),
  1448. _('started.'))
  1449. )
  1450. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1451. cleared_geo[:] = []
  1452. # Get remaining tools offset
  1453. offset -= (tool - 1e-12)
  1454. # Area to clear
  1455. area = empty.buffer(-offset)
  1456. try:
  1457. area = area.difference(cleared)
  1458. except Exception as e:
  1459. continue
  1460. # Transform area to MultiPolygon
  1461. if type(area) is Polygon:
  1462. area = MultiPolygon([area])
  1463. # variables to display the percentage of work done
  1464. geo_len = len(area.geoms)
  1465. disp_number = 0
  1466. old_disp_number = 0
  1467. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1468. if area.geoms:
  1469. if len(area.geoms) > 0:
  1470. pol_nr = 0
  1471. for p in area.geoms:
  1472. if self.app.abort_flag:
  1473. # graceful abort requested by the user
  1474. raise FlatCAMApp.GracefulException
  1475. if p is not None:
  1476. try:
  1477. if isinstance(p, Polygon):
  1478. if ncc_method == 'standard':
  1479. cp = self.clear_polygon(p, tool, self.app.defaults["gerber_circle_steps"],
  1480. overlap=overlap, contour=contour, connect=connect,
  1481. prog_plot=prog_plot)
  1482. elif ncc_method == 'seed':
  1483. cp = self.clear_polygon2(p, tool, self.app.defaults["gerber_circle_steps"],
  1484. overlap=overlap, contour=contour, connect=connect,
  1485. prog_plot=prog_plot)
  1486. else:
  1487. cp = self.clear_polygon3(p, tool, self.app.defaults["gerber_circle_steps"],
  1488. overlap=overlap, contour=contour, connect=connect,
  1489. prog_plot=prog_plot)
  1490. if cp:
  1491. cleared_geo += list(cp.get_objects())
  1492. elif isinstance(p, MultiPolygon):
  1493. for pol in p:
  1494. if pol is not None:
  1495. if ncc_method == 'standard':
  1496. cp = self.clear_polygon(pol, tool,
  1497. self.app.defaults["gerber_circle_steps"],
  1498. overlap=overlap, contour=contour,
  1499. connect=connect,
  1500. prog_plot=prog_plot)
  1501. elif ncc_method == 'seed':
  1502. cp = self.clear_polygon2(pol, tool,
  1503. self.app.defaults["gerber_circle_steps"],
  1504. overlap=overlap, contour=contour,
  1505. connect=connect,
  1506. prog_plot=prog_plot)
  1507. else:
  1508. cp = self.clear_polygon3(pol, tool,
  1509. self.app.defaults["gerber_circle_steps"],
  1510. overlap=overlap, contour=contour,
  1511. connect=connect,
  1512. prog_plot=prog_plot)
  1513. if cp:
  1514. cleared_geo += list(cp.get_objects())
  1515. except Exception as e:
  1516. log.warning("Polygon can not be cleared. %s" % str(e))
  1517. app_obj.poly_not_cleared = True
  1518. continue
  1519. pol_nr += 1
  1520. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1521. # log.debug("Polygons cleared: %d" % pol_nr)
  1522. if old_disp_number < disp_number <= 100:
  1523. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1524. old_disp_number = disp_number
  1525. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1526. # check if there is a geometry at all in the cleared geometry
  1527. if cleared_geo:
  1528. # Overall cleared area
  1529. cleared = empty.buffer(-offset * (1 + overlap)).buffer(-tool / 1.999999).buffer(
  1530. tool / 1.999999)
  1531. # clean-up cleared geo
  1532. cleared = cleared.buffer(0)
  1533. # find the tooluid associated with the current tool_dia so we know where to add the tool
  1534. # solid_geometry
  1535. for k, v in tools_storage.items():
  1536. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1537. current_uid = int(k)
  1538. # add the solid_geometry to the current too in self.paint_tools dictionary
  1539. # and then reset the temporary list that stored that solid_geometry
  1540. v['solid_geometry'] = deepcopy(cleared_geo)
  1541. v['data']['name'] = name
  1542. break
  1543. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1544. else:
  1545. log.debug("There are no geometries in the cleared polygon.")
  1546. # clean the progressive plotted shapes if it was used
  1547. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  1548. self.temp_shapes.clear(update=True)
  1549. # delete tools with empty geometry
  1550. keys_to_delete = []
  1551. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1552. for uid in tools_storage:
  1553. # if the solid_geometry (type=list) is empty
  1554. if not tools_storage[uid]['solid_geometry']:
  1555. keys_to_delete.append(uid)
  1556. # actual delete of keys from the tools_storage dict
  1557. for k in keys_to_delete:
  1558. tools_storage.pop(k, None)
  1559. geo_obj.options["cnctooldia"] = str(tool)
  1560. geo_obj.multigeo = True
  1561. geo_obj.tools.clear()
  1562. geo_obj.tools = dict(tools_storage)
  1563. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1564. has_solid_geo = 0
  1565. for tooluid in geo_obj.tools:
  1566. if geo_obj.tools[tooluid]['solid_geometry']:
  1567. has_solid_geo += 1
  1568. if has_solid_geo == 0:
  1569. app_obj.inform.emit('[ERROR] %s' % _("There is no Painting Geometry in the file.\n"
  1570. "Usually it means that the tool diameter is too big "
  1571. "for the painted geometry.\n"
  1572. "Change the painting parameters and try again."))
  1573. return
  1574. # Experimental...
  1575. # print("Indexing...", end=' ')
  1576. # geo_obj.make_index()
  1577. if warning_flag == 0:
  1578. self.app.inform.emit('[success] %s' % _("NCC Tool clear all done."))
  1579. else:
  1580. self.app.inform.emit('[WARNING] %s: %s %s.' % (_("NCC Tool clear all done but the copper features "
  1581. "isolation is broken for"),
  1582. str(warning_flag),
  1583. _("tools")))
  1584. # ###########################################################################################
  1585. # Initializes the new geometry object for the case of the rest-machining ####################
  1586. # ###########################################################################################
  1587. def gen_clear_area_rest(geo_obj, app_obj):
  1588. assert isinstance(geo_obj, FlatCAMGeometry), \
  1589. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1590. log.debug("NCC Tool. Rest machining copper clearing task started.")
  1591. app_obj.inform.emit('_(NCC Tool. Rest machining copper clearing task started.')
  1592. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  1593. # will store the number of tools for which the isolation is broken
  1594. warning_flag = 0
  1595. sorted_tools.sort(reverse=True)
  1596. cleared_geo = []
  1597. cleared_by_last_tool = []
  1598. rest_geo = []
  1599. current_uid = 1
  1600. try:
  1601. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1602. except TypeError:
  1603. tool = eval(self.app.defaults["tools_ncctools"])
  1604. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  1605. app_obj.poly_not_cleared = True
  1606. log.debug("NCC Tool. Calculate 'empty' area.")
  1607. app_obj.inform.emit("NCC Tool. Calculate 'empty' area.")
  1608. # ###################################################################################################
  1609. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  1610. # ###################################################################################################
  1611. if isinstance(ncc_obj, FlatCAMGerber) and not isotooldia:
  1612. sol_geo = ncc_obj.solid_geometry
  1613. if has_offset is True:
  1614. app_obj.inform.emit('[WARNING_NOTCL] %s ...' %
  1615. _("Buffering"))
  1616. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1617. app_obj.inform.emit('[success] %s ...' %
  1618. _("Buffering finished"))
  1619. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1620. if empty == 'fail':
  1621. return 'fail'
  1622. elif isinstance(ncc_obj, FlatCAMGerber) and isotooldia:
  1623. isolated_geo = []
  1624. self.solid_geometry = ncc_obj.solid_geometry
  1625. # if milling type is climb then the move is counter-clockwise around features
  1626. milling_type = self.milling_type_radio.get_value()
  1627. for tool_iso in isotooldia:
  1628. new_geometry = []
  1629. if milling_type == 'cl':
  1630. isolated_geo = self.generate_envelope(tool_iso, 1)
  1631. else:
  1632. isolated_geo = self.generate_envelope(tool_iso, 0)
  1633. if isolated_geo == 'fail':
  1634. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1635. else:
  1636. try:
  1637. for geo_elem in isolated_geo:
  1638. if self.app.abort_flag:
  1639. # graceful abort requested by the user
  1640. raise FlatCAMApp.GracefulException
  1641. if isinstance(geo_elem, Polygon):
  1642. for ring in self.poly2rings(geo_elem):
  1643. new_geo = ring.intersection(bounding_box)
  1644. if new_geo and not new_geo.is_empty:
  1645. new_geometry.append(new_geo)
  1646. elif isinstance(geo_elem, MultiPolygon):
  1647. for poly in geo_elem:
  1648. for ring in self.poly2rings(poly):
  1649. new_geo = ring.intersection(bounding_box)
  1650. if new_geo and not new_geo.is_empty:
  1651. new_geometry.append(new_geo)
  1652. elif isinstance(geo_elem, LineString):
  1653. new_geo = geo_elem.intersection(bounding_box)
  1654. if new_geo:
  1655. if not new_geo.is_empty:
  1656. new_geometry.append(new_geo)
  1657. elif isinstance(geo_elem, MultiLineString):
  1658. for line_elem in geo_elem:
  1659. new_geo = line_elem.intersection(bounding_box)
  1660. if new_geo and not new_geo.is_empty:
  1661. new_geometry.append(new_geo)
  1662. except TypeError:
  1663. try:
  1664. if isinstance(isolated_geo, Polygon):
  1665. for ring in self.poly2rings(isolated_geo):
  1666. new_geo = ring.intersection(bounding_box)
  1667. if new_geo:
  1668. if not new_geo.is_empty:
  1669. new_geometry.append(new_geo)
  1670. elif isinstance(isolated_geo, LineString):
  1671. new_geo = isolated_geo.intersection(bounding_box)
  1672. if new_geo and not new_geo.is_empty:
  1673. new_geometry.append(new_geo)
  1674. elif isinstance(isolated_geo, MultiLineString):
  1675. for line_elem in isolated_geo:
  1676. new_geo = line_elem.intersection(bounding_box)
  1677. if new_geo and not new_geo.is_empty:
  1678. new_geometry.append(new_geo)
  1679. except Exception as e:
  1680. pass
  1681. # a MultiLineString geometry element will show that the isolation is broken for this tool
  1682. for geo_e in new_geometry:
  1683. if type(geo_e) == MultiLineString:
  1684. warning_flag += 1
  1685. break
  1686. for k, v in tools_storage.items():
  1687. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_iso):
  1688. current_uid = int(k)
  1689. # add the solid_geometry to the current too in self.paint_tools dictionary
  1690. # and then reset the temporary list that stored that solid_geometry
  1691. v['solid_geometry'] = deepcopy(new_geometry)
  1692. v['data']['name'] = name
  1693. break
  1694. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1695. sol_geo = cascaded_union(isolated_geo)
  1696. if has_offset is True:
  1697. app_obj.inform.emit('[WARNING_NOTCL] %s ...' %
  1698. _("Buffering"))
  1699. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1700. app_obj.inform.emit('[success] %s ...' %
  1701. _("Buffering finished"))
  1702. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1703. if empty == 'fail':
  1704. return 'fail'
  1705. elif isinstance(ncc_obj, FlatCAMGeometry):
  1706. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  1707. if has_offset is True:
  1708. app_obj.inform.emit('[WARNING_NOTCL] %s ...' %
  1709. _("Buffering"))
  1710. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1711. app_obj.inform.emit('[success] %s ...' %
  1712. _("Buffering finished"))
  1713. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1714. if empty == 'fail':
  1715. return 'fail'
  1716. else:
  1717. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1718. _('The selected object is not suitable for copper clearing.'))
  1719. return
  1720. if empty.is_empty:
  1721. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1722. _("Could not get the extent of the area to be non copper cleared."))
  1723. return 'fail'
  1724. if self.app.abort_flag:
  1725. # graceful abort requested by the user
  1726. raise FlatCAMApp.GracefulException
  1727. if type(empty) is Polygon:
  1728. empty = MultiPolygon([empty])
  1729. area = empty.buffer(0)
  1730. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  1731. app_obj.inform.emit("NCC Tool. Finished calculation of 'empty' area.")
  1732. # Generate area for each tool
  1733. while sorted_tools:
  1734. if self.app.abort_flag:
  1735. # graceful abort requested by the user
  1736. raise FlatCAMApp.GracefulException
  1737. tool = sorted_tools.pop(0)
  1738. log.debug("Starting geometry processing for tool: %s" % str(tool))
  1739. app_obj.inform.emit(
  1740. '[success] %s %s%s %s' % (_('NCC Tool clearing with tool diameter = '),
  1741. str(tool),
  1742. units.lower(),
  1743. _('started.'))
  1744. )
  1745. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1746. tool_used = tool - 1e-12
  1747. cleared_geo[:] = []
  1748. # Area to clear
  1749. for poly in cleared_by_last_tool:
  1750. if self.app.abort_flag:
  1751. # graceful abort requested by the user
  1752. raise FlatCAMApp.GracefulException
  1753. try:
  1754. area = area.difference(poly)
  1755. except Exception as e:
  1756. pass
  1757. cleared_by_last_tool[:] = []
  1758. # Transform area to MultiPolygon
  1759. if type(area) is Polygon:
  1760. area = MultiPolygon([area])
  1761. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  1762. # and rest_geo it's a list
  1763. allparts = [p.buffer(0) for p in area.geoms]
  1764. allparts += deepcopy(rest_geo)
  1765. rest_geo[:] = []
  1766. area = MultiPolygon(deepcopy(allparts))
  1767. allparts[:] = []
  1768. # variables to display the percentage of work done
  1769. geo_len = len(area.geoms)
  1770. disp_number = 0
  1771. old_disp_number = 0
  1772. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1773. if area.geoms:
  1774. if len(area.geoms) > 0:
  1775. pol_nr = 0
  1776. for p in area.geoms:
  1777. if self.app.abort_flag:
  1778. # graceful abort requested by the user
  1779. raise FlatCAMApp.GracefulException
  1780. if p is not None:
  1781. if isinstance(p, Polygon):
  1782. try:
  1783. if ncc_method == 'standard':
  1784. cp = self.clear_polygon(p, tool_used,
  1785. self.app.defaults["gerber_circle_steps"],
  1786. overlap=overlap, contour=contour, connect=connect,
  1787. prog_plot=prog_plot)
  1788. elif ncc_method == 'seed':
  1789. cp = self.clear_polygon2(p, tool_used,
  1790. self.app.defaults["gerber_circle_steps"],
  1791. overlap=overlap, contour=contour, connect=connect,
  1792. prog_plot=prog_plot)
  1793. else:
  1794. cp = self.clear_polygon3(p, tool_used,
  1795. self.app.defaults["gerber_circle_steps"],
  1796. overlap=overlap, contour=contour, connect=connect,
  1797. prog_plot=prog_plot)
  1798. cleared_geo.append(list(cp.get_objects()))
  1799. except Exception as e:
  1800. log.warning("Polygon can't be cleared. %s" % str(e))
  1801. # this polygon should be added to a list and then try clear it with
  1802. # a smaller tool
  1803. rest_geo.append(p)
  1804. elif isinstance(p, MultiPolygon):
  1805. for poly in p:
  1806. if poly is not None:
  1807. try:
  1808. if ncc_method == 'standard':
  1809. cp = self.clear_polygon(poly, tool_used,
  1810. self.app.defaults["gerber_circle_steps"],
  1811. overlap=overlap, contour=contour,
  1812. connect=connect,
  1813. prog_plot=prog_plot)
  1814. elif ncc_method == 'seed':
  1815. cp = self.clear_polygon2(poly, tool_used,
  1816. self.app.defaults["gerber_circle_steps"],
  1817. overlap=overlap, contour=contour,
  1818. connect=connect,
  1819. prog_plot=prog_plot)
  1820. else:
  1821. cp = self.clear_polygon3(poly, tool_used,
  1822. self.app.defaults["gerber_circle_steps"],
  1823. overlap=overlap, contour=contour,
  1824. connect=connect,
  1825. prog_plot=prog_plot)
  1826. cleared_geo.append(list(cp.get_objects()))
  1827. except Exception as e:
  1828. log.warning("Polygon can't be cleared. %s" % str(e))
  1829. # this polygon should be added to a list and then try clear it with
  1830. # a smaller tool
  1831. rest_geo.append(poly)
  1832. pol_nr += 1
  1833. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1834. # log.debug("Polygons cleared: %d" % pol_nr)
  1835. if old_disp_number < disp_number <= 100:
  1836. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1837. old_disp_number = disp_number
  1838. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1839. if self.app.abort_flag:
  1840. # graceful abort requested by the user
  1841. raise FlatCAMApp.GracefulException
  1842. # check if there is a geometry at all in the cleared geometry
  1843. if cleared_geo:
  1844. # Overall cleared area
  1845. cleared_area = list(self.flatten_list(cleared_geo))
  1846. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  1847. # for p in cleared_area])
  1848. # here we store the poly's already processed in the original geometry by the current tool
  1849. # into cleared_by_last_tool list
  1850. # this will be sutracted from the original geometry_to_be_cleared and make data for
  1851. # the next tool
  1852. buffer_value = tool_used / 2
  1853. for p in cleared_area:
  1854. if self.app.abort_flag:
  1855. # graceful abort requested by the user
  1856. raise FlatCAMApp.GracefulException
  1857. poly = p.buffer(buffer_value)
  1858. cleared_by_last_tool.append(poly)
  1859. # find the tooluid associated with the current tool_dia so we know
  1860. # where to add the tool solid_geometry
  1861. for k, v in tools_storage.items():
  1862. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1863. current_uid = int(k)
  1864. # add the solid_geometry to the current too in self.paint_tools dictionary
  1865. # and then reset the temporary list that stored that solid_geometry
  1866. v['solid_geometry'] = deepcopy(cleared_area)
  1867. v['data']['name'] = name
  1868. cleared_area[:] = []
  1869. break
  1870. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1871. else:
  1872. log.debug("There are no geometries in the cleared polygon.")
  1873. geo_obj.multigeo = True
  1874. geo_obj.options["cnctooldia"] = str(tool)
  1875. # clean the progressive plotted shapes if it was used
  1876. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  1877. self.temp_shapes.clear(update=True)
  1878. # check to see if geo_obj.tools is empty
  1879. # it will be updated only if there is a solid_geometry for tools
  1880. if geo_obj.tools:
  1881. if warning_flag == 0:
  1882. self.app.inform.emit('[success] %s' % _("NCC Tool Rest Machining clear all done."))
  1883. else:
  1884. self.app.inform.emit(
  1885. '[WARNING] %s: %s %s.' % (_("NCC Tool Rest Machining clear all done but the copper features "
  1886. "isolation is broken for"), str(warning_flag), _("tools")))
  1887. return
  1888. else:
  1889. # I will use this variable for this purpose although it was meant for something else
  1890. # signal that we have no geo in the object therefore don't create it
  1891. app_obj.poly_not_cleared = False
  1892. return "fail"
  1893. # ###########################################################################################
  1894. # Create the Job function and send it to the worker to be processed in another thread #######
  1895. # ###########################################################################################
  1896. def job_thread(app_obj):
  1897. try:
  1898. if rest_machining_choice is True:
  1899. app_obj.new_object("geometry", name, gen_clear_area_rest, plot=plot)
  1900. else:
  1901. app_obj.new_object("geometry", name, gen_clear_area, plot=plot)
  1902. except FlatCAMApp.GracefulException:
  1903. proc.done()
  1904. return
  1905. except Exception as e:
  1906. proc.done()
  1907. traceback.print_stack()
  1908. return
  1909. proc.done()
  1910. # focus on Selected Tab
  1911. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1912. if run_threaded:
  1913. # Promise object with the new name
  1914. self.app.collection.promise(name)
  1915. # Background
  1916. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1917. else:
  1918. job_thread(app_obj=self.app)
  1919. # def on_ncc(self):
  1920. #
  1921. # # Prepare non-copper polygons
  1922. # if self.reference_radio.get_value() == 'area':
  1923. # geo_n = self.sel_rect
  1924. #
  1925. # geo_buff_list = []
  1926. # for poly in geo_n:
  1927. # geo_buff_list.append(poly.buffer(distance=margin, join_style=base.JOIN_STYLE.mitre))
  1928. # bounding_box = cascaded_union(geo_buff_list)
  1929. # else:
  1930. # geo_n = self.bound_obj.solid_geometry
  1931. #
  1932. # try:
  1933. # if isinstance(geo_n, MultiPolygon):
  1934. # env_obj = geo_n.convex_hull
  1935. # elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  1936. # (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  1937. # env_obj = cascaded_union(geo_n)
  1938. # else:
  1939. # env_obj = cascaded_union(geo_n)
  1940. # env_obj = env_obj.convex_hull
  1941. # bounding_box = env_obj.buffer(distance=margin, join_style=base.JOIN_STYLE.mitre)
  1942. # except Exception as e:
  1943. # log.debug("NonCopperClear.on_ncc() --> %s" % str(e))
  1944. # self.app.inform.emit(_("[ERROR_NOTCL] No object available."))
  1945. # return
  1946. #
  1947. # # calculate the empty area by subtracting the solid_geometry from the object bounding box geometry
  1948. # if isinstance(self.ncc_obj, FlatCAMGerber):
  1949. # if self.ncc_choice_offset_cb.isChecked():
  1950. # self.app.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1951. # offseted_geo = self.ncc_obj.solid_geometry.buffer(distance=ncc_offset_value)
  1952. # self.app.inform.emit(_("[success] Buffering finished ..."))
  1953. # empty = self.get_ncc_empty_area(target=offseted_geo, boundary=bounding_box)
  1954. # else:
  1955. # empty = self.get_ncc_empty_area(target=self.ncc_obj.solid_geometry, boundary=bounding_box)
  1956. # elif isinstance(self.ncc_obj, FlatCAMGeometry):
  1957. # sol_geo = cascaded_union(self.ncc_obj.solid_geometry)
  1958. # if self.ncc_choice_offset_cb.isChecked():
  1959. # self.app.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1960. # offseted_geo = sol_geo.buffer(distance=ncc_offset_value)
  1961. # self.app.inform.emit(_("[success] Buffering finished ..."))
  1962. # empty = self.get_ncc_empty_area(target=offseted_geo, boundary=bounding_box)
  1963. # else:
  1964. # empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1965. # else:
  1966. # self.inform.emit(_('[ERROR_NOTCL] The selected object is not suitable for copper clearing.'))
  1967. # return
  1968. #
  1969. # if type(empty) is Polygon:
  1970. # empty = MultiPolygon([empty])
  1971. #
  1972. # if empty.is_empty:
  1973. # self.app.inform.emit(_("[ERROR_NOTCL] Could not get the extent of the area to be non copper cleared."))
  1974. # return
  1975. #
  1976. # # clear non copper using standard algorithm
  1977. # if clearing_method is False:
  1978. # self.clear_non_copper(
  1979. # empty=empty,
  1980. # over=over,
  1981. # pol_method=pol_method,
  1982. # connect=connect,
  1983. # contour=contour
  1984. # )
  1985. # # clear non copper using rest machining algorithm
  1986. # else:
  1987. # self.clear_non_copper_rest(
  1988. # empty=empty,
  1989. # over=over,
  1990. # pol_method=pol_method,
  1991. # connect=connect,
  1992. # contour=contour
  1993. # )
  1994. #
  1995. # def clear_non_copper(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  1996. #
  1997. # name = outname if outname else self.obj_name + "_ncc"
  1998. #
  1999. # # Sort tools in descending order
  2000. # sorted_tools = []
  2001. # for k, v in self.ncc_tools.items():
  2002. # sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  2003. #
  2004. # order = self.ncc_order_radio.get_value()
  2005. # if order == 'fwd':
  2006. # sorted_tools.sort(reverse=False)
  2007. # elif order == 'rev':
  2008. # sorted_tools.sort(reverse=True)
  2009. # else:
  2010. # pass
  2011. #
  2012. # # Do job in background
  2013. # proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  2014. #
  2015. # def initialize(geo_obj, app_obj):
  2016. # assert isinstance(geo_obj, FlatCAMGeometry), \
  2017. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2018. #
  2019. # cleared_geo = []
  2020. # # Already cleared area
  2021. # cleared = MultiPolygon()
  2022. #
  2023. # # flag for polygons not cleared
  2024. # app_obj.poly_not_cleared = False
  2025. #
  2026. # # Generate area for each tool
  2027. # offset = sum(sorted_tools)
  2028. # current_uid = int(1)
  2029. # tool = eval(self.app.defaults["tools_ncctools"])[0]
  2030. #
  2031. # for tool in sorted_tools:
  2032. # self.app.inform.emit(_('[success] Non-Copper Clearing with ToolDia = %s started.') % str(tool))
  2033. # cleared_geo[:] = []
  2034. #
  2035. # # Get remaining tools offset
  2036. # offset -= (tool - 1e-12)
  2037. #
  2038. # # Area to clear
  2039. # area = empty.buffer(-offset)
  2040. # try:
  2041. # area = area.difference(cleared)
  2042. # except Exception as e:
  2043. # continue
  2044. #
  2045. # # Transform area to MultiPolygon
  2046. # if type(area) is Polygon:
  2047. # area = MultiPolygon([area])
  2048. #
  2049. # if area.geoms:
  2050. # if len(area.geoms) > 0:
  2051. # for p in area.geoms:
  2052. # try:
  2053. # if pol_method == 'standard':
  2054. # cp = self.clear_polygon(p, tool, self.app.defaults["gerber_circle_steps"],
  2055. # overlap=over, contour=contour, connect=connect)
  2056. # elif pol_method == 'seed':
  2057. # cp = self.clear_polygon2(p, tool, self.app.defaults["gerber_circle_steps"],
  2058. # overlap=over, contour=contour, connect=connect)
  2059. # else:
  2060. # cp = self.clear_polygon3(p, tool, self.app.defaults["gerber_circle_steps"],
  2061. # overlap=over, contour=contour, connect=connect)
  2062. # if cp:
  2063. # cleared_geo += list(cp.get_objects())
  2064. # except Exception as e:
  2065. # log.warning("Polygon can not be cleared. %s" % str(e))
  2066. # app_obj.poly_not_cleared = True
  2067. # continue
  2068. #
  2069. # # check if there is a geometry at all in the cleared geometry
  2070. # if cleared_geo:
  2071. # # Overall cleared area
  2072. # cleared = empty.buffer(-offset * (1 + over)).buffer(-tool / 1.999999).buffer(
  2073. # tool / 1.999999)
  2074. #
  2075. # # clean-up cleared geo
  2076. # cleared = cleared.buffer(0)
  2077. #
  2078. # # find the tooluid associated with the current tool_dia so we know where to add the tool
  2079. # # solid_geometry
  2080. # for k, v in self.ncc_tools.items():
  2081. # if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  2082. # current_uid = int(k)
  2083. #
  2084. # # add the solid_geometry to the current too in self.paint_tools dictionary
  2085. # # and then reset the temporary list that stored that solid_geometry
  2086. # v['solid_geometry'] = deepcopy(cleared_geo)
  2087. # v['data']['name'] = name
  2088. # break
  2089. # geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  2090. # else:
  2091. # log.debug("There are no geometries in the cleared polygon.")
  2092. #
  2093. # geo_obj.options["cnctooldia"] = str(tool)
  2094. # geo_obj.multigeo = True
  2095. #
  2096. # def job_thread(app_obj):
  2097. # try:
  2098. # app_obj.new_object("geometry", name, initialize)
  2099. # except Exception as e:
  2100. # proc.done()
  2101. # self.app.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper() --> %s') % str(e))
  2102. # return
  2103. # proc.done()
  2104. #
  2105. # if app_obj.poly_not_cleared is False:
  2106. # self.app.inform.emit(_('[success] NCC Tool finished.'))
  2107. # else:
  2108. # self.app.inform.emit(_('[WARNING_NOTCL] NCC Tool finished but some PCB features could not be cleared. '
  2109. # 'Check the result.'))
  2110. # # reset the variable for next use
  2111. # app_obj.poly_not_cleared = False
  2112. #
  2113. # # focus on Selected Tab
  2114. # self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2115. #
  2116. # # Promise object with the new name
  2117. # self.app.collection.promise(name)
  2118. #
  2119. # # Background
  2120. # self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2121. #
  2122. # # clear copper with 'rest-machining' algorithm
  2123. # def clear_non_copper_rest(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  2124. #
  2125. # name = outname if outname is not None else self.obj_name + "_ncc_rm"
  2126. #
  2127. # # Sort tools in descending order
  2128. # sorted_tools = []
  2129. # for k, v in self.ncc_tools.items():
  2130. # sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  2131. # sorted_tools.sort(reverse=True)
  2132. #
  2133. # # Do job in background
  2134. # proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  2135. #
  2136. # def initialize_rm(geo_obj, app_obj):
  2137. # assert isinstance(geo_obj, FlatCAMGeometry), \
  2138. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2139. #
  2140. # cleared_geo = []
  2141. # cleared_by_last_tool = []
  2142. # rest_geo = []
  2143. # current_uid = 1
  2144. # tool = eval(self.app.defaults["tools_ncctools"])[0]
  2145. #
  2146. # # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  2147. # app_obj.poly_not_cleared = True
  2148. #
  2149. # area = empty.buffer(0)
  2150. # # Generate area for each tool
  2151. # while sorted_tools:
  2152. # tool = sorted_tools.pop(0)
  2153. # self.app.inform.emit(_('[success] Non-Copper Rest Clearing with ToolDia = %s started.') % str(tool))
  2154. #
  2155. # tool_used = tool - 1e-12
  2156. # cleared_geo[:] = []
  2157. #
  2158. # # Area to clear
  2159. # for poly in cleared_by_last_tool:
  2160. # try:
  2161. # area = area.difference(poly)
  2162. # except Exception as e:
  2163. # pass
  2164. # cleared_by_last_tool[:] = []
  2165. #
  2166. # # Transform area to MultiPolygon
  2167. # if type(area) is Polygon:
  2168. # area = MultiPolygon([area])
  2169. #
  2170. # # add the rest that was not able to be cleared previously; area is a MultyPolygon
  2171. # # and rest_geo it's a list
  2172. # allparts = [p.buffer(0) for p in area.geoms]
  2173. # allparts += deepcopy(rest_geo)
  2174. # rest_geo[:] = []
  2175. # area = MultiPolygon(deepcopy(allparts))
  2176. # allparts[:] = []
  2177. #
  2178. # if area.geoms:
  2179. # if len(area.geoms) > 0:
  2180. # for p in area.geoms:
  2181. # try:
  2182. # if pol_method == 'standard':
  2183. # cp = self.clear_polygon(p, tool_used, self.app.defaults["gerber_circle_steps"],
  2184. # overlap=over, contour=contour, connect=connect)
  2185. # elif pol_method == 'seed':
  2186. # cp = self.clear_polygon2(p, tool_used,
  2187. # self.app.defaults["gerber_circle_steps"],
  2188. # overlap=over, contour=contour, connect=connect)
  2189. # else:
  2190. # cp = self.clear_polygon3(p, tool_used,
  2191. # self.app.defaults["gerber_circle_steps"],
  2192. # overlap=over, contour=contour, connect=connect)
  2193. # cleared_geo.append(list(cp.get_objects()))
  2194. # except:
  2195. # log.warning("Polygon can't be cleared.")
  2196. # # this polygon should be added to a list and then try clear it with a smaller tool
  2197. # rest_geo.append(p)
  2198. #
  2199. # # check if there is a geometry at all in the cleared geometry
  2200. # if cleared_geo:
  2201. # # Overall cleared area
  2202. # cleared_area = list(self.flatten_list(cleared_geo))
  2203. #
  2204. # # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  2205. # # for p in cleared_area])
  2206. #
  2207. # # here we store the poly's already processed in the original geometry by the current tool
  2208. # # into cleared_by_last_tool list
  2209. # # this will be sustracted from the original geometry_to_be_cleared and make data for
  2210. # # the next tool
  2211. # buffer_value = tool_used / 2
  2212. # for p in cleared_area:
  2213. # poly = p.buffer(buffer_value)
  2214. # cleared_by_last_tool.append(poly)
  2215. #
  2216. # # find the tooluid associated with the current tool_dia so we know
  2217. # # where to add the tool solid_geometry
  2218. # for k, v in self.ncc_tools.items():
  2219. # if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  2220. # current_uid = int(k)
  2221. #
  2222. # # add the solid_geometry to the current too in self.paint_tools dictionary
  2223. # # and then reset the temporary list that stored that solid_geometry
  2224. # v['solid_geometry'] = deepcopy(cleared_area)
  2225. # v['data']['name'] = name
  2226. # cleared_area[:] = []
  2227. # break
  2228. #
  2229. # geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  2230. # else:
  2231. # log.debug("There are no geometries in the cleared polygon.")
  2232. #
  2233. # geo_obj.multigeo = True
  2234. # geo_obj.options["cnctooldia"] = str(tool)
  2235. #
  2236. # # check to see if geo_obj.tools is empty
  2237. # # it will be updated only if there is a solid_geometry for tools
  2238. # if geo_obj.tools:
  2239. # return
  2240. # else:
  2241. # # I will use this variable for this purpose although it was meant for something else
  2242. # # signal that we have no geo in the object therefore don't create it
  2243. # app_obj.poly_not_cleared = False
  2244. # return "fail"
  2245. #
  2246. # def job_thread(app_obj):
  2247. # try:
  2248. # app_obj.new_object("geometry", name, initialize_rm)
  2249. # except Exception as e:
  2250. # proc.done()
  2251. # app_obj.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper_rest() --> %s') % str(e))
  2252. # return
  2253. #
  2254. # if app_obj.poly_not_cleared is True:
  2255. # app_obj.inform.emit('[success] NCC Tool finished.')
  2256. # # focus on Selected Tab
  2257. # app_obj.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2258. # else:
  2259. # app_obj.inform.emit(_('[ERROR_NOTCL] NCC Tool finished but could not clear the object '
  2260. # 'with current settings.'))
  2261. # # focus on Project Tab
  2262. # app_obj.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  2263. # proc.done()
  2264. # # reset the variable for next use
  2265. # app_obj.poly_not_cleared = False
  2266. #
  2267. # # Promise object with the new name
  2268. # self.app.collection.promise(name)
  2269. #
  2270. # # Background
  2271. # self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2272. def get_ncc_empty_area(self, target, boundary=None):
  2273. """
  2274. Returns the complement of target geometry within
  2275. the given boundary polygon. If not specified, it defaults to
  2276. the rectangular bounding box of target geometry.
  2277. """
  2278. if isinstance(target, Polygon):
  2279. geo_len = 1
  2280. else:
  2281. geo_len = len(target)
  2282. pol_nr = 0
  2283. old_disp_number = 0
  2284. if boundary is None:
  2285. boundary = target.envelope
  2286. else:
  2287. boundary = boundary
  2288. try:
  2289. ret_val = boundary.difference(target)
  2290. except Exception as e:
  2291. try:
  2292. for el in target:
  2293. if self.app.abort_flag:
  2294. # graceful abort requested by the user
  2295. raise FlatCAMApp.GracefulException
  2296. boundary = boundary.difference(el)
  2297. pol_nr += 1
  2298. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2299. if old_disp_number < disp_number <= 100:
  2300. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2301. old_disp_number = disp_number
  2302. return boundary
  2303. except Exception as e:
  2304. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2305. _("Try to use the Buffering Type = Full in Preferences -> Gerber General. "
  2306. "Reload the Gerber file after this change."))
  2307. return 'fail'
  2308. return ret_val
  2309. def reset_fields(self):
  2310. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2311. def reset_usage(self):
  2312. self.obj_name = ""
  2313. self.ncc_obj = None
  2314. self.bound_obj = None
  2315. self.first_click = False
  2316. self.cursor_pos = None
  2317. self.mouse_is_dragging = False
  2318. self.sel_rect = []
  2319. @staticmethod
  2320. def poly2rings(poly):
  2321. return [poly.exterior] + [interior for interior in poly.interiors]
  2322. def generate_envelope(self, offset, invert, envelope_iso_type=2, follow=None):
  2323. # isolation_geometry produces an envelope that is going on the left of the geometry
  2324. # (the copper features). To leave the least amount of burrs on the features
  2325. # the tool needs to travel on the right side of the features (this is called conventional milling)
  2326. # the first pass is the one cutting all of the features, so it needs to be reversed
  2327. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  2328. # to cut on the right side of the left over copper i.e on the left side of the features.
  2329. try:
  2330. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type, follow=follow)
  2331. except Exception as e:
  2332. log.debug('NonCopperClear.generate_envelope() --> %s' % str(e))
  2333. return 'fail'
  2334. if invert:
  2335. try:
  2336. try:
  2337. pl = []
  2338. for p in geom:
  2339. if p is not None:
  2340. if isinstance(p, Polygon):
  2341. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  2342. elif isinstance(p, LinearRing):
  2343. pl.append(Polygon(p.coords[::-1]))
  2344. geom = MultiPolygon(pl)
  2345. except TypeError:
  2346. if isinstance(geom, Polygon) and geom is not None:
  2347. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  2348. elif isinstance(geom, LinearRing) and geom is not None:
  2349. geom = Polygon(geom.coords[::-1])
  2350. else:
  2351. log.debug("NonCopperClear.generate_envelope() Error --> Unexpected Geometry %s" %
  2352. type(geom))
  2353. except Exception as e:
  2354. log.debug("NonCopperClear.generate_envelope() Error --> %s" % str(e))
  2355. return 'fail'
  2356. return geom