ToolNonCopperClear.py 108 KB

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