ToolNonCopperClear.py 131 KB

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