ToolNonCopperClear.py 111 KB

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