ToolNonCopperClear.py 130 KB

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