ToolNonCopperClear.py 131 KB

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