ToolNonCopperClear.py 130 KB

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