ToolNonCopperClear.py 128 KB

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