ToolNonCopperClear.py 128 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666
  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', self.app.on_mouse_click_release_over_plot)
  1022. elif event.button == 2 and self.mouse_is_dragging == False:
  1023. self.first_click = False
  1024. self.app.plotcanvas.graph_event_disconnect('mouse_release', on_mouse_release)
  1025. self.app.plotcanvas.graph_event_disconnect('mouse_move', on_mouse_move)
  1026. self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  1027. self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  1028. self.app.plotcanvas.graph_event_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1029. if len(self.sel_rect) == 0:
  1030. return
  1031. self.sel_rect = cascaded_union(self.sel_rect)
  1032. self.clear_copper(ncc_obj=self.ncc_obj,
  1033. sel_obj=self.bound_obj,
  1034. ncctooldia=ncc_dia_list,
  1035. isotooldia=iso_dia_list,
  1036. has_offset=has_offset,
  1037. outname=o_name,
  1038. overlap=overlap,
  1039. connect=connect,
  1040. contour=contour,
  1041. rest=rest)
  1042. # called on mouse move
  1043. def on_mouse_move(event):
  1044. curr_pos = self.app.plotcanvas.translate_coords(event.pos)
  1045. # detect mouse dragging motion
  1046. if event.is_dragging is True:
  1047. self.mouse_is_dragging = True
  1048. else:
  1049. self.mouse_is_dragging = False
  1050. # update the cursor position
  1051. if self.app.grid_status() == True:
  1052. # Update cursor
  1053. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1054. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1055. symbol='++', edge_color='black', size=20)
  1056. # draw the utility geometry
  1057. if self.first_click:
  1058. self.app.delete_selection_shape()
  1059. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  1060. coords=(curr_pos[0], curr_pos[1]),
  1061. face_alpha=0.0)
  1062. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  1063. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  1064. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  1065. self.app.plotcanvas.graph_event_connect('mouse_release', on_mouse_release)
  1066. self.app.plotcanvas.graph_event_connect('mouse_move', on_mouse_move)
  1067. elif select_method == 'box':
  1068. self.bound_obj_name = self.box_combo.currentText()
  1069. # Get source object.
  1070. try:
  1071. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  1072. except Exception as e:
  1073. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), self.bound_obj_name))
  1074. return "Could not retrieve object: %s. Error: %s" % (self.bound_obj_name, str(e))
  1075. self.clear_copper(ncc_obj=self.ncc_obj,
  1076. sel_obj=self.bound_obj,
  1077. ncctooldia=ncc_dia_list,
  1078. isotooldia=iso_dia_list,
  1079. has_offset=has_offset,
  1080. outname=o_name,
  1081. overlap=overlap,
  1082. connect=connect,
  1083. contour=contour,
  1084. rest=rest)
  1085. def clear_copper(self, ncc_obj,
  1086. sel_obj=None,
  1087. ncctooldia=None,
  1088. isotooldia=None,
  1089. margin=None,
  1090. has_offset=None,
  1091. offset=None,
  1092. select_method=None,
  1093. outname=None,
  1094. overlap=None,
  1095. connect=None,
  1096. contour=None,
  1097. order=None,
  1098. method=None,
  1099. rest=None,
  1100. tools_storage=None,
  1101. plot=True,
  1102. run_threaded=True):
  1103. """
  1104. Clear the excess copper from the entire object.
  1105. :param ncc_obj: ncc cleared object
  1106. :param ncctooldia: a tuple or single element made out of diameters of the tools to be used to ncc clear
  1107. :param isotooldia: a tuple or single element made out of diameters of the tools to be used for isolation
  1108. :param overlap: value by which the paths will overlap
  1109. :param order: if the tools are ordered and how
  1110. :param select_method: if to do ncc on the whole object, on an defined area or on an area defined by
  1111. another object
  1112. :param has_offset: True if an offset is needed
  1113. :param offset: distance from the copper features where the copper clearing is stopping
  1114. :param margin: a border around cleared area
  1115. :param outname: name of the resulting object
  1116. :param connect: Connect lines to avoid tool lifts.
  1117. :param contour: Paint around the edges.
  1118. :param method: choice out of 'seed', 'normal', 'lines'
  1119. :param rest: True if to use rest-machining
  1120. :param tools_storage: whether to use the current tools_storage self.ncc_tools or a different one.
  1121. Usage of the different one is related to when this function is called from a TcL command.
  1122. :param run_threaded: If True the method will be run in a threaded way suitable for GUI usage; if False it will
  1123. run non-threaded for TclShell usage
  1124. :return:
  1125. """
  1126. proc = self.app.proc_container.new(_("Non-Copper clearing ..."))
  1127. # #####################################################################
  1128. # ####### Read the parameters #########################################
  1129. # #####################################################################
  1130. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value()
  1131. log.debug("NCC Tool started. Reading parameters.")
  1132. self.app.inform.emit(_("NCC Tool started. Reading parameters."))
  1133. ncc_method = method if method else self.ncc_method_radio.get_value()
  1134. if margin is not None:
  1135. ncc_margin = margin
  1136. else:
  1137. try:
  1138. ncc_margin = float(self.ncc_margin_entry.get_value())
  1139. except ValueError:
  1140. # try to convert comma to decimal point. if it's still not working error message and return
  1141. try:
  1142. ncc_margin = float(self.ncc_margin_entry.get_value().replace(',', '.'))
  1143. except ValueError:
  1144. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1145. return
  1146. if select_method is not None:
  1147. ncc_select = select_method
  1148. else:
  1149. ncc_select = self.reference_radio.get_value()
  1150. overlap = overlap if overlap else self.app.defaults["tools_nccoverlap"]
  1151. connect = connect if connect else self.app.defaults["tools_nccconnect"]
  1152. contour = contour if contour else self.app.defaults["tools_ncccontour"]
  1153. order = order if order else self.ncc_order_radio.get_value()
  1154. # determine if to use the progressive plotting
  1155. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  1156. prog_plot = True
  1157. else:
  1158. prog_plot = False
  1159. if tools_storage is not None:
  1160. tools_storage = tools_storage
  1161. else:
  1162. tools_storage = self.ncc_tools
  1163. ncc_offset = 0.0
  1164. if has_offset is True:
  1165. if offset is not None:
  1166. ncc_offset = offset
  1167. else:
  1168. try:
  1169. ncc_offset = float(self.ncc_offset_spinner.get_value())
  1170. except ValueError:
  1171. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1172. return
  1173. # ######################################################################################################
  1174. # # Read the tooldia parameter and create a sorted list out them - they may be more than one diameter ##
  1175. # ######################################################################################################
  1176. sorted_tools = []
  1177. if ncctooldia is not None:
  1178. try:
  1179. sorted_tools = [float(eval(dia)) for dia in ncctooldia.split(",") if dia != '']
  1180. except AttributeError:
  1181. if not isinstance(ncctooldia, list):
  1182. sorted_tools = [float(ncctooldia)]
  1183. else:
  1184. sorted_tools = ncctooldia
  1185. else:
  1186. for row in range(self.tools_table.rowCount()):
  1187. if self.tools_table.cellWidget(row, 1).currentText() == 'clear_op':
  1188. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1189. # ##############################################################################################################
  1190. # Prepare non-copper polygons. Create the bounding box area from which the copper features will be subtracted ##
  1191. # ##############################################################################################################
  1192. log.debug("NCC Tool. Preparing non-copper polygons.")
  1193. self.app.inform.emit(_("NCC Tool. Preparing non-copper polygons."))
  1194. try:
  1195. if sel_obj is None or sel_obj == 'itself':
  1196. ncc_sel_obj = ncc_obj
  1197. else:
  1198. ncc_sel_obj = sel_obj
  1199. except Exception as e:
  1200. log.debug("NonCopperClear.clear_copper() --> %s" % str(e))
  1201. return 'fail'
  1202. bounding_box = None
  1203. if ncc_select == 'itself':
  1204. geo_n = ncc_sel_obj.solid_geometry
  1205. try:
  1206. if isinstance(geo_n, MultiPolygon):
  1207. env_obj = geo_n.convex_hull
  1208. elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  1209. (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  1210. env_obj = cascaded_union(geo_n)
  1211. else:
  1212. env_obj = cascaded_union(geo_n)
  1213. env_obj = env_obj.convex_hull
  1214. bounding_box = env_obj.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1215. except Exception as e:
  1216. log.debug("NonCopperClear.clear_copper() 'itself' --> %s" % str(e))
  1217. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  1218. return 'fail'
  1219. elif ncc_select == 'area':
  1220. geo_n = cascaded_union(self.sel_rect)
  1221. try:
  1222. __ = iter(geo_n)
  1223. except Exception as e:
  1224. log.debug("NonCopperClear.clear_copper() 'area' --> %s" % str(e))
  1225. geo_n = [geo_n]
  1226. geo_buff_list = []
  1227. for poly in geo_n:
  1228. if self.app.abort_flag:
  1229. # graceful abort requested by the user
  1230. raise FlatCAMApp.GracefulException
  1231. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1232. bounding_box = cascaded_union(geo_buff_list)
  1233. elif ncc_select == 'box':
  1234. geo_n = ncc_sel_obj.solid_geometry
  1235. if isinstance(ncc_sel_obj, FlatCAMGeometry):
  1236. try:
  1237. __ = iter(geo_n)
  1238. except Exception as e:
  1239. log.debug("NonCopperClear.clear_copper() 'box' --> %s" % str(e))
  1240. geo_n = [geo_n]
  1241. geo_buff_list = []
  1242. for poly in geo_n:
  1243. if self.app.abort_flag:
  1244. # graceful abort requested by the user
  1245. raise FlatCAMApp.GracefulException
  1246. geo_buff_list.append(poly.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre))
  1247. bounding_box = cascaded_union(geo_buff_list)
  1248. elif isinstance(ncc_sel_obj, FlatCAMGerber):
  1249. geo_n = cascaded_union(geo_n).convex_hull
  1250. bounding_box = cascaded_union(self.ncc_obj.solid_geometry).convex_hull.intersection(geo_n)
  1251. bounding_box = bounding_box.buffer(distance=ncc_margin, join_style=base.JOIN_STYLE.mitre)
  1252. else:
  1253. self.app.inform.emit('[ERROR_NOTCL] %s' % _("The reference object type is not supported."))
  1254. return 'fail'
  1255. log.debug("NCC Tool. Finished non-copper polygons.")
  1256. # ########################################################################################################
  1257. # set the name for the future Geometry object
  1258. # I do it here because it is also stored inside the gen_clear_area() and gen_clear_area_rest() methods
  1259. # ########################################################################################################
  1260. rest_machining_choice = rest if rest is not None else self.app.defaults["tools_nccrest"]
  1261. if rest_machining_choice is True:
  1262. name = outname if outname is not None else self.obj_name + "_ncc_rm"
  1263. else:
  1264. name = outname if outname is not None else self.obj_name + "_ncc"
  1265. # ##########################################################################################
  1266. # Initializes the new geometry object ######################################################
  1267. # ##########################################################################################
  1268. def gen_clear_area(geo_obj, app_obj):
  1269. assert isinstance(geo_obj, FlatCAMGeometry), \
  1270. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1271. log.debug("NCC Tool. Normal copper clearing task started.")
  1272. self.app.inform.emit(_("NCC Tool. Finished non-copper polygons. Normal copper clearing task started."))
  1273. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  1274. # will store the number of tools for which the isolation is broken
  1275. warning_flag = 0
  1276. if order == 'fwd':
  1277. sorted_tools.sort(reverse=False)
  1278. elif order == 'rev':
  1279. sorted_tools.sort(reverse=True)
  1280. else:
  1281. pass
  1282. cleared_geo = []
  1283. # Already cleared area
  1284. cleared = MultiPolygon()
  1285. # flag for polygons not cleared
  1286. app_obj.poly_not_cleared = False
  1287. # Generate area for each tool
  1288. offset = sum(sorted_tools)
  1289. current_uid = int(1)
  1290. try:
  1291. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1292. except TypeError:
  1293. tool = eval(self.app.defaults["tools_ncctools"])
  1294. # ###################################################################################################
  1295. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  1296. # ###################################################################################################
  1297. log.debug("NCC Tool. Calculate 'empty' area.")
  1298. self.app.inform.emit(_("NCC Tool. Calculate 'empty' area."))
  1299. if isinstance(ncc_obj, FlatCAMGerber) and not isotooldia:
  1300. # unfortunately for this function to work time efficient,
  1301. # if the Gerber was loaded without buffering then it require the buffering now.
  1302. if self.app.defaults['gerber_buffering'] == 'no':
  1303. sol_geo = ncc_obj.solid_geometry.buffer(0)
  1304. else:
  1305. sol_geo = ncc_obj.solid_geometry
  1306. if has_offset is True:
  1307. app_obj.inform.emit('[WARNING_NOTCL] %s ...' %
  1308. _("Buffering"))
  1309. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1310. app_obj.inform.emit('[success] %s ...' %
  1311. _("Buffering finished"))
  1312. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1313. if empty == 'fail':
  1314. return 'fail'
  1315. elif isinstance(ncc_obj, FlatCAMGerber) and isotooldia:
  1316. isolated_geo = []
  1317. # unfortunately for this function to work time efficient,
  1318. # if the Gerber was loaded without buffering then it require the buffering now.
  1319. if self.app.defaults['gerber_buffering'] == 'no':
  1320. self.solid_geometry = ncc_obj.solid_geometry.buffer(0)
  1321. else:
  1322. self.solid_geometry = ncc_obj.solid_geometry
  1323. # if milling type is climb then the move is counter-clockwise around features
  1324. milling_type = self.milling_type_radio.get_value()
  1325. for tool_iso in isotooldia:
  1326. new_geometry = []
  1327. if milling_type == 'cl':
  1328. isolated_geo = self.generate_envelope(tool_iso / 2, 1)
  1329. else:
  1330. isolated_geo = self.generate_envelope(tool_iso / 2, 0)
  1331. if isolated_geo == 'fail':
  1332. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1333. else:
  1334. try:
  1335. for geo_elem in isolated_geo:
  1336. if self.app.abort_flag:
  1337. # graceful abort requested by the user
  1338. raise FlatCAMApp.GracefulException
  1339. if isinstance(geo_elem, Polygon):
  1340. for ring in self.poly2rings(geo_elem):
  1341. new_geo = ring.intersection(bounding_box)
  1342. if new_geo and not new_geo.is_empty:
  1343. new_geometry.append(new_geo)
  1344. elif isinstance(geo_elem, MultiPolygon):
  1345. for poly in geo_elem:
  1346. for ring in self.poly2rings(poly):
  1347. new_geo = ring.intersection(bounding_box)
  1348. if new_geo and not new_geo.is_empty:
  1349. new_geometry.append(new_geo)
  1350. elif isinstance(geo_elem, LineString):
  1351. new_geo = geo_elem.intersection(bounding_box)
  1352. if new_geo:
  1353. if not new_geo.is_empty:
  1354. new_geometry.append(new_geo)
  1355. elif isinstance(geo_elem, MultiLineString):
  1356. for line_elem in geo_elem:
  1357. new_geo = line_elem.intersection(bounding_box)
  1358. if new_geo and not new_geo.is_empty:
  1359. new_geometry.append(new_geo)
  1360. except TypeError:
  1361. if isinstance(isolated_geo, Polygon):
  1362. for ring in self.poly2rings(isolated_geo):
  1363. new_geo = ring.intersection(bounding_box)
  1364. if new_geo:
  1365. if not new_geo.is_empty:
  1366. new_geometry.append(new_geo)
  1367. elif isinstance(isolated_geo, LineString):
  1368. new_geo = isolated_geo.intersection(bounding_box)
  1369. if new_geo and not new_geo.is_empty:
  1370. new_geometry.append(new_geo)
  1371. elif isinstance(isolated_geo, MultiLineString):
  1372. for line_elem in isolated_geo:
  1373. new_geo = line_elem.intersection(bounding_box)
  1374. if new_geo and not new_geo.is_empty:
  1375. new_geometry.append(new_geo)
  1376. # a MultiLineString geometry element will show that the isolation is broken for this tool
  1377. for geo_e in new_geometry:
  1378. if type(geo_e) == MultiLineString:
  1379. warning_flag += 1
  1380. break
  1381. for k, v in tools_storage.items():
  1382. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_iso):
  1383. current_uid = int(k)
  1384. # add the solid_geometry to the current too in self.paint_tools dictionary
  1385. # and then reset the temporary list that stored that solid_geometry
  1386. v['solid_geometry'] = deepcopy(new_geometry)
  1387. v['data']['name'] = name
  1388. break
  1389. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1390. sol_geo = cascaded_union(isolated_geo)
  1391. if has_offset is True:
  1392. app_obj.inform.emit('[WARNING_NOTCL] %s ...' %
  1393. _("Buffering"))
  1394. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1395. app_obj.inform.emit('[success] %s ...' %
  1396. _("Buffering finished"))
  1397. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1398. if empty == 'fail':
  1399. return 'fail'
  1400. elif isinstance(ncc_obj, FlatCAMGeometry):
  1401. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  1402. if has_offset is True:
  1403. app_obj.inform.emit('[WARNING_NOTCL] %s ...' %
  1404. _("Buffering"))
  1405. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1406. app_obj.inform.emit('[success] %s ...' %
  1407. _("Buffering finished"))
  1408. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1409. if empty == 'fail':
  1410. return 'fail'
  1411. else:
  1412. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1413. _('The selected object is not suitable for copper clearing.'))
  1414. return
  1415. if empty.is_empty:
  1416. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1417. _("Could not get the extent of the area to be non copper cleared."))
  1418. return 'fail'
  1419. if type(empty) is Polygon:
  1420. empty = MultiPolygon([empty])
  1421. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  1422. self.app.inform.emit(_("NCC Tool. Finished calculation of 'empty' area."))
  1423. cp = None
  1424. for tool in sorted_tools:
  1425. log.debug("Starting geometry processing for tool: %s" % str(tool))
  1426. if self.app.abort_flag:
  1427. # graceful abort requested by the user
  1428. raise FlatCAMApp.GracefulException
  1429. app_obj.inform.emit(
  1430. '[success] %s %s%s %s' % (_('NCC Tool clearing with tool diameter = '),
  1431. str(tool),
  1432. units.lower(),
  1433. _('started.'))
  1434. )
  1435. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1436. cleared_geo[:] = []
  1437. # Get remaining tools offset
  1438. offset -= (tool - 1e-12)
  1439. # Area to clear
  1440. area = empty.buffer(-offset)
  1441. try:
  1442. area = area.difference(cleared)
  1443. except Exception as e:
  1444. continue
  1445. # Transform area to MultiPolygon
  1446. if type(area) is Polygon:
  1447. area = MultiPolygon([area])
  1448. # variables to display the percentage of work done
  1449. geo_len = len(area.geoms)
  1450. disp_number = 0
  1451. old_disp_number = 0
  1452. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1453. if area.geoms:
  1454. if len(area.geoms) > 0:
  1455. pol_nr = 0
  1456. for p in area.geoms:
  1457. if self.app.abort_flag:
  1458. # graceful abort requested by the user
  1459. raise FlatCAMApp.GracefulException
  1460. if p is not None:
  1461. try:
  1462. if isinstance(p, Polygon):
  1463. if ncc_method == 'standard':
  1464. cp = self.clear_polygon(p, tool, self.app.defaults["gerber_circle_steps"],
  1465. overlap=overlap, contour=contour, connect=connect,
  1466. prog_plot=prog_plot)
  1467. elif ncc_method == 'seed':
  1468. cp = self.clear_polygon2(p, tool, self.app.defaults["gerber_circle_steps"],
  1469. overlap=overlap, contour=contour, connect=connect,
  1470. prog_plot=prog_plot)
  1471. else:
  1472. cp = self.clear_polygon3(p, tool, self.app.defaults["gerber_circle_steps"],
  1473. overlap=overlap, contour=contour, connect=connect,
  1474. prog_plot=prog_plot)
  1475. if cp:
  1476. cleared_geo += list(cp.get_objects())
  1477. elif isinstance(p, MultiPolygon):
  1478. for pol in p:
  1479. if pol is not None:
  1480. if ncc_method == 'standard':
  1481. cp = self.clear_polygon(pol, tool,
  1482. self.app.defaults["gerber_circle_steps"],
  1483. overlap=overlap, contour=contour,
  1484. connect=connect,
  1485. prog_plot=prog_plot)
  1486. elif ncc_method == 'seed':
  1487. cp = self.clear_polygon2(pol, tool,
  1488. self.app.defaults["gerber_circle_steps"],
  1489. overlap=overlap, contour=contour,
  1490. connect=connect,
  1491. prog_plot=prog_plot)
  1492. else:
  1493. cp = self.clear_polygon3(pol, tool,
  1494. self.app.defaults["gerber_circle_steps"],
  1495. overlap=overlap, contour=contour,
  1496. connect=connect,
  1497. prog_plot=prog_plot)
  1498. if cp:
  1499. cleared_geo += list(cp.get_objects())
  1500. except Exception as e:
  1501. log.warning("Polygon can not be cleared. %s" % str(e))
  1502. app_obj.poly_not_cleared = True
  1503. continue
  1504. pol_nr += 1
  1505. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1506. # log.debug("Polygons cleared: %d" % pol_nr)
  1507. if old_disp_number < disp_number <= 100:
  1508. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1509. old_disp_number = disp_number
  1510. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1511. # check if there is a geometry at all in the cleared geometry
  1512. if cleared_geo:
  1513. # Overall cleared area
  1514. cleared = empty.buffer(-offset * (1 + overlap)).buffer(-tool / 1.999999).buffer(
  1515. tool / 1.999999)
  1516. # clean-up cleared geo
  1517. cleared = cleared.buffer(0)
  1518. # find the tooluid associated with the current tool_dia so we know where to add the tool
  1519. # solid_geometry
  1520. for k, v in tools_storage.items():
  1521. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1522. current_uid = int(k)
  1523. # add the solid_geometry to the current too in self.paint_tools dictionary
  1524. # and then reset the temporary list that stored that solid_geometry
  1525. v['solid_geometry'] = deepcopy(cleared_geo)
  1526. v['data']['name'] = name
  1527. break
  1528. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1529. else:
  1530. log.debug("There are no geometries in the cleared polygon.")
  1531. # clean the progressive plotted shapes if it was used
  1532. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  1533. self.temp_shapes.clear(update=True)
  1534. # delete tools with empty geometry
  1535. keys_to_delete = []
  1536. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1537. for uid in tools_storage:
  1538. # if the solid_geometry (type=list) is empty
  1539. if not tools_storage[uid]['solid_geometry']:
  1540. keys_to_delete.append(uid)
  1541. # actual delete of keys from the tools_storage dict
  1542. for k in keys_to_delete:
  1543. tools_storage.pop(k, None)
  1544. geo_obj.options["cnctooldia"] = str(tool)
  1545. geo_obj.multigeo = True
  1546. geo_obj.tools.clear()
  1547. geo_obj.tools = dict(tools_storage)
  1548. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1549. has_solid_geo = 0
  1550. for tooluid in geo_obj.tools:
  1551. if geo_obj.tools[tooluid]['solid_geometry']:
  1552. has_solid_geo += 1
  1553. if has_solid_geo == 0:
  1554. app_obj.inform.emit('[ERROR] %s' % _("There is no Painting Geometry in the file.\n"
  1555. "Usually it means that the tool diameter is too big "
  1556. "for the painted geometry.\n"
  1557. "Change the painting parameters and try again."))
  1558. return
  1559. # Experimental...
  1560. # print("Indexing...", end=' ')
  1561. # geo_obj.make_index()
  1562. if warning_flag == 0:
  1563. self.app.inform.emit('[success] %s' % _("NCC Tool clear all done."))
  1564. else:
  1565. self.app.inform.emit('[WARNING] %s: %s %s.' % (_("NCC Tool clear all done but the copper features "
  1566. "isolation is broken for"),
  1567. str(warning_flag),
  1568. _("tools")))
  1569. # ###########################################################################################
  1570. # Initializes the new geometry object for the case of the rest-machining ####################
  1571. # ###########################################################################################
  1572. def gen_clear_area_rest(geo_obj, app_obj):
  1573. assert isinstance(geo_obj, FlatCAMGeometry), \
  1574. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1575. log.debug("NCC Tool. Rest machining copper clearing task started.")
  1576. app_obj.inform.emit('_(NCC Tool. Rest machining copper clearing task started.')
  1577. # a flag to signal that the isolation is broken by the bounding box in 'area' and 'box' cases
  1578. # will store the number of tools for which the isolation is broken
  1579. warning_flag = 0
  1580. sorted_tools.sort(reverse=True)
  1581. cleared_geo = []
  1582. cleared_by_last_tool = []
  1583. rest_geo = []
  1584. current_uid = 1
  1585. try:
  1586. tool = eval(self.app.defaults["tools_ncctools"])[0]
  1587. except TypeError:
  1588. tool = eval(self.app.defaults["tools_ncctools"])
  1589. # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  1590. app_obj.poly_not_cleared = True
  1591. log.debug("NCC Tool. Calculate 'empty' area.")
  1592. app_obj.inform.emit("NCC Tool. Calculate 'empty' area.")
  1593. # ###################################################################################################
  1594. # Calculate the empty area by subtracting the solid_geometry from the object bounding box geometry ##
  1595. # ###################################################################################################
  1596. if isinstance(ncc_obj, FlatCAMGerber) and not isotooldia:
  1597. sol_geo = ncc_obj.solid_geometry
  1598. if has_offset is True:
  1599. app_obj.inform.emit('[WARNING_NOTCL] %s ...' %
  1600. _("Buffering"))
  1601. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1602. app_obj.inform.emit('[success] %s ...' %
  1603. _("Buffering finished"))
  1604. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1605. if empty == 'fail':
  1606. return 'fail'
  1607. elif isinstance(ncc_obj, FlatCAMGerber) and isotooldia:
  1608. isolated_geo = []
  1609. self.solid_geometry = ncc_obj.solid_geometry
  1610. # if milling type is climb then the move is counter-clockwise around features
  1611. milling_type = self.milling_type_radio.get_value()
  1612. for tool_iso in isotooldia:
  1613. new_geometry = []
  1614. if milling_type == 'cl':
  1615. isolated_geo = self.generate_envelope(tool_iso, 1)
  1616. else:
  1617. isolated_geo = self.generate_envelope(tool_iso, 0)
  1618. if isolated_geo == 'fail':
  1619. app_obj.inform.emit('[ERROR_NOTCL] %s' % _("Isolation geometry could not be generated."))
  1620. else:
  1621. try:
  1622. for geo_elem in isolated_geo:
  1623. if self.app.abort_flag:
  1624. # graceful abort requested by the user
  1625. raise FlatCAMApp.GracefulException
  1626. if isinstance(geo_elem, Polygon):
  1627. for ring in self.poly2rings(geo_elem):
  1628. new_geo = ring.intersection(bounding_box)
  1629. if new_geo and not new_geo.is_empty:
  1630. new_geometry.append(new_geo)
  1631. elif isinstance(geo_elem, MultiPolygon):
  1632. for poly in geo_elem:
  1633. for ring in self.poly2rings(poly):
  1634. new_geo = ring.intersection(bounding_box)
  1635. if new_geo and not new_geo.is_empty:
  1636. new_geometry.append(new_geo)
  1637. elif isinstance(geo_elem, LineString):
  1638. new_geo = geo_elem.intersection(bounding_box)
  1639. if new_geo:
  1640. if not new_geo.is_empty:
  1641. new_geometry.append(new_geo)
  1642. elif isinstance(geo_elem, MultiLineString):
  1643. for line_elem in geo_elem:
  1644. new_geo = line_elem.intersection(bounding_box)
  1645. if new_geo and not new_geo.is_empty:
  1646. new_geometry.append(new_geo)
  1647. except TypeError:
  1648. try:
  1649. if isinstance(isolated_geo, Polygon):
  1650. for ring in self.poly2rings(isolated_geo):
  1651. new_geo = ring.intersection(bounding_box)
  1652. if new_geo:
  1653. if not new_geo.is_empty:
  1654. new_geometry.append(new_geo)
  1655. elif isinstance(isolated_geo, LineString):
  1656. new_geo = isolated_geo.intersection(bounding_box)
  1657. if new_geo and not new_geo.is_empty:
  1658. new_geometry.append(new_geo)
  1659. elif isinstance(isolated_geo, MultiLineString):
  1660. for line_elem in isolated_geo:
  1661. new_geo = line_elem.intersection(bounding_box)
  1662. if new_geo and not new_geo.is_empty:
  1663. new_geometry.append(new_geo)
  1664. except Exception as e:
  1665. pass
  1666. # a MultiLineString geometry element will show that the isolation is broken for this tool
  1667. for geo_e in new_geometry:
  1668. if type(geo_e) == MultiLineString:
  1669. warning_flag += 1
  1670. break
  1671. for k, v in tools_storage.items():
  1672. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_iso):
  1673. current_uid = int(k)
  1674. # add the solid_geometry to the current too in self.paint_tools dictionary
  1675. # and then reset the temporary list that stored that solid_geometry
  1676. v['solid_geometry'] = deepcopy(new_geometry)
  1677. v['data']['name'] = name
  1678. break
  1679. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1680. sol_geo = cascaded_union(isolated_geo)
  1681. if has_offset is True:
  1682. app_obj.inform.emit('[WARNING_NOTCL] %s ...' %
  1683. _("Buffering"))
  1684. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1685. app_obj.inform.emit('[success] %s ...' %
  1686. _("Buffering finished"))
  1687. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1688. if empty == 'fail':
  1689. return 'fail'
  1690. elif isinstance(ncc_obj, FlatCAMGeometry):
  1691. sol_geo = cascaded_union(ncc_obj.solid_geometry)
  1692. if has_offset is True:
  1693. app_obj.inform.emit('[WARNING_NOTCL] %s ...' %
  1694. _("Buffering"))
  1695. sol_geo = sol_geo.buffer(distance=ncc_offset)
  1696. app_obj.inform.emit('[success] %s ...' %
  1697. _("Buffering finished"))
  1698. empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1699. if empty == 'fail':
  1700. return 'fail'
  1701. else:
  1702. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1703. _('The selected object is not suitable for copper clearing.'))
  1704. return
  1705. if empty.is_empty:
  1706. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1707. _("Could not get the extent of the area to be non copper cleared."))
  1708. return 'fail'
  1709. if self.app.abort_flag:
  1710. # graceful abort requested by the user
  1711. raise FlatCAMApp.GracefulException
  1712. if type(empty) is Polygon:
  1713. empty = MultiPolygon([empty])
  1714. area = empty.buffer(0)
  1715. log.debug("NCC Tool. Finished calculation of 'empty' area.")
  1716. app_obj.inform.emit("NCC Tool. Finished calculation of 'empty' area.")
  1717. # Generate area for each tool
  1718. while sorted_tools:
  1719. if self.app.abort_flag:
  1720. # graceful abort requested by the user
  1721. raise FlatCAMApp.GracefulException
  1722. tool = sorted_tools.pop(0)
  1723. log.debug("Starting geometry processing for tool: %s" % str(tool))
  1724. app_obj.inform.emit(
  1725. '[success] %s %s%s %s' % (_('NCC Tool clearing with tool diameter = '),
  1726. str(tool),
  1727. units.lower(),
  1728. _('started.'))
  1729. )
  1730. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1731. tool_used = tool - 1e-12
  1732. cleared_geo[:] = []
  1733. # Area to clear
  1734. for poly in cleared_by_last_tool:
  1735. if self.app.abort_flag:
  1736. # graceful abort requested by the user
  1737. raise FlatCAMApp.GracefulException
  1738. try:
  1739. area = area.difference(poly)
  1740. except Exception as e:
  1741. pass
  1742. cleared_by_last_tool[:] = []
  1743. # Transform area to MultiPolygon
  1744. if type(area) is Polygon:
  1745. area = MultiPolygon([area])
  1746. # add the rest that was not able to be cleared previously; area is a MultyPolygon
  1747. # and rest_geo it's a list
  1748. allparts = [p.buffer(0) for p in area.geoms]
  1749. allparts += deepcopy(rest_geo)
  1750. rest_geo[:] = []
  1751. area = MultiPolygon(deepcopy(allparts))
  1752. allparts[:] = []
  1753. # variables to display the percentage of work done
  1754. geo_len = len(area.geoms)
  1755. disp_number = 0
  1756. old_disp_number = 0
  1757. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1758. if area.geoms:
  1759. if len(area.geoms) > 0:
  1760. pol_nr = 0
  1761. for p in area.geoms:
  1762. if self.app.abort_flag:
  1763. # graceful abort requested by the user
  1764. raise FlatCAMApp.GracefulException
  1765. if p is not None:
  1766. if isinstance(p, Polygon):
  1767. try:
  1768. if ncc_method == 'standard':
  1769. cp = self.clear_polygon(p, tool_used,
  1770. self.app.defaults["gerber_circle_steps"],
  1771. overlap=overlap, contour=contour, connect=connect,
  1772. prog_plot=prog_plot)
  1773. elif ncc_method == 'seed':
  1774. cp = self.clear_polygon2(p, tool_used,
  1775. self.app.defaults["gerber_circle_steps"],
  1776. overlap=overlap, contour=contour, connect=connect,
  1777. prog_plot=prog_plot)
  1778. else:
  1779. cp = self.clear_polygon3(p, tool_used,
  1780. self.app.defaults["gerber_circle_steps"],
  1781. overlap=overlap, contour=contour, connect=connect,
  1782. prog_plot=prog_plot)
  1783. cleared_geo.append(list(cp.get_objects()))
  1784. except Exception as e:
  1785. log.warning("Polygon can't be cleared. %s" % str(e))
  1786. # this polygon should be added to a list and then try clear it with
  1787. # a smaller tool
  1788. rest_geo.append(p)
  1789. elif isinstance(p, MultiPolygon):
  1790. for poly in p:
  1791. if poly is not None:
  1792. try:
  1793. if ncc_method == 'standard':
  1794. cp = self.clear_polygon(poly, tool_used,
  1795. self.app.defaults["gerber_circle_steps"],
  1796. overlap=overlap, contour=contour,
  1797. connect=connect,
  1798. prog_plot=prog_plot)
  1799. elif ncc_method == 'seed':
  1800. cp = self.clear_polygon2(poly, tool_used,
  1801. self.app.defaults["gerber_circle_steps"],
  1802. overlap=overlap, contour=contour,
  1803. connect=connect,
  1804. prog_plot=prog_plot)
  1805. else:
  1806. cp = self.clear_polygon3(poly, tool_used,
  1807. self.app.defaults["gerber_circle_steps"],
  1808. overlap=overlap, contour=contour,
  1809. connect=connect,
  1810. prog_plot=prog_plot)
  1811. cleared_geo.append(list(cp.get_objects()))
  1812. except Exception as e:
  1813. log.warning("Polygon can't be cleared. %s" % str(e))
  1814. # this polygon should be added to a list and then try clear it with
  1815. # a smaller tool
  1816. rest_geo.append(poly)
  1817. pol_nr += 1
  1818. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1819. # log.debug("Polygons cleared: %d" % pol_nr)
  1820. if old_disp_number < disp_number <= 100:
  1821. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1822. old_disp_number = disp_number
  1823. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1824. if self.app.abort_flag:
  1825. # graceful abort requested by the user
  1826. raise FlatCAMApp.GracefulException
  1827. # check if there is a geometry at all in the cleared geometry
  1828. if cleared_geo:
  1829. # Overall cleared area
  1830. cleared_area = list(self.flatten_list(cleared_geo))
  1831. # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  1832. # for p in cleared_area])
  1833. # here we store the poly's already processed in the original geometry by the current tool
  1834. # into cleared_by_last_tool list
  1835. # this will be sutracted from the original geometry_to_be_cleared and make data for
  1836. # the next tool
  1837. buffer_value = tool_used / 2
  1838. for p in cleared_area:
  1839. if self.app.abort_flag:
  1840. # graceful abort requested by the user
  1841. raise FlatCAMApp.GracefulException
  1842. poly = p.buffer(buffer_value)
  1843. cleared_by_last_tool.append(poly)
  1844. # find the tooluid associated with the current tool_dia so we know
  1845. # where to add the tool solid_geometry
  1846. for k, v in tools_storage.items():
  1847. if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  1848. current_uid = int(k)
  1849. # add the solid_geometry to the current too in self.paint_tools dictionary
  1850. # and then reset the temporary list that stored that solid_geometry
  1851. v['solid_geometry'] = deepcopy(cleared_area)
  1852. v['data']['name'] = name
  1853. cleared_area[:] = []
  1854. break
  1855. geo_obj.tools[current_uid] = dict(tools_storage[current_uid])
  1856. else:
  1857. log.debug("There are no geometries in the cleared polygon.")
  1858. geo_obj.multigeo = True
  1859. geo_obj.options["cnctooldia"] = str(tool)
  1860. # clean the progressive plotted shapes if it was used
  1861. if self.app.defaults["tools_ncc_plotting"] == 'progressive':
  1862. self.temp_shapes.clear(update=True)
  1863. # check to see if geo_obj.tools is empty
  1864. # it will be updated only if there is a solid_geometry for tools
  1865. if geo_obj.tools:
  1866. if warning_flag == 0:
  1867. self.app.inform.emit('[success] %s' % _("NCC Tool Rest Machining clear all done."))
  1868. else:
  1869. self.app.inform.emit(
  1870. '[WARNING] %s: %s %s.' % (_("NCC Tool Rest Machining clear all done but the copper features "
  1871. "isolation is broken for"), str(warning_flag), _("tools")))
  1872. return
  1873. else:
  1874. # I will use this variable for this purpose although it was meant for something else
  1875. # signal that we have no geo in the object therefore don't create it
  1876. app_obj.poly_not_cleared = False
  1877. return "fail"
  1878. # ###########################################################################################
  1879. # Create the Job function and send it to the worker to be processed in another thread #######
  1880. # ###########################################################################################
  1881. def job_thread(app_obj):
  1882. try:
  1883. if rest_machining_choice is True:
  1884. app_obj.new_object("geometry", name, gen_clear_area_rest, plot=plot)
  1885. else:
  1886. app_obj.new_object("geometry", name, gen_clear_area, plot=plot)
  1887. except FlatCAMApp.GracefulException:
  1888. proc.done()
  1889. return
  1890. except Exception as e:
  1891. proc.done()
  1892. traceback.print_stack()
  1893. return
  1894. proc.done()
  1895. # focus on Selected Tab
  1896. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1897. if run_threaded:
  1898. # Promise object with the new name
  1899. self.app.collection.promise(name)
  1900. # Background
  1901. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1902. else:
  1903. job_thread(app_obj=self.app)
  1904. # def on_ncc(self):
  1905. #
  1906. # # Prepare non-copper polygons
  1907. # if self.reference_radio.get_value() == 'area':
  1908. # geo_n = self.sel_rect
  1909. #
  1910. # geo_buff_list = []
  1911. # for poly in geo_n:
  1912. # geo_buff_list.append(poly.buffer(distance=margin, join_style=base.JOIN_STYLE.mitre))
  1913. # bounding_box = cascaded_union(geo_buff_list)
  1914. # else:
  1915. # geo_n = self.bound_obj.solid_geometry
  1916. #
  1917. # try:
  1918. # if isinstance(geo_n, MultiPolygon):
  1919. # env_obj = geo_n.convex_hull
  1920. # elif (isinstance(geo_n, MultiPolygon) and len(geo_n) == 1) or \
  1921. # (isinstance(geo_n, list) and len(geo_n) == 1) and isinstance(geo_n[0], Polygon):
  1922. # env_obj = cascaded_union(geo_n)
  1923. # else:
  1924. # env_obj = cascaded_union(geo_n)
  1925. # env_obj = env_obj.convex_hull
  1926. # bounding_box = env_obj.buffer(distance=margin, join_style=base.JOIN_STYLE.mitre)
  1927. # except Exception as e:
  1928. # log.debug("NonCopperClear.on_ncc() --> %s" % str(e))
  1929. # self.app.inform.emit(_("[ERROR_NOTCL] No object available."))
  1930. # return
  1931. #
  1932. # # calculate the empty area by subtracting the solid_geometry from the object bounding box geometry
  1933. # if isinstance(self.ncc_obj, FlatCAMGerber):
  1934. # if self.ncc_choice_offset_cb.isChecked():
  1935. # self.app.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1936. # offseted_geo = self.ncc_obj.solid_geometry.buffer(distance=ncc_offset_value)
  1937. # self.app.inform.emit(_("[success] Buffering finished ..."))
  1938. # empty = self.get_ncc_empty_area(target=offseted_geo, boundary=bounding_box)
  1939. # else:
  1940. # empty = self.get_ncc_empty_area(target=self.ncc_obj.solid_geometry, boundary=bounding_box)
  1941. # elif isinstance(self.ncc_obj, FlatCAMGeometry):
  1942. # sol_geo = cascaded_union(self.ncc_obj.solid_geometry)
  1943. # if self.ncc_choice_offset_cb.isChecked():
  1944. # self.app.inform.emit(_("[WARNING_NOTCL] Buffering ..."))
  1945. # offseted_geo = sol_geo.buffer(distance=ncc_offset_value)
  1946. # self.app.inform.emit(_("[success] Buffering finished ..."))
  1947. # empty = self.get_ncc_empty_area(target=offseted_geo, boundary=bounding_box)
  1948. # else:
  1949. # empty = self.get_ncc_empty_area(target=sol_geo, boundary=bounding_box)
  1950. # else:
  1951. # self.inform.emit(_('[ERROR_NOTCL] The selected object is not suitable for copper clearing.'))
  1952. # return
  1953. #
  1954. # if type(empty) is Polygon:
  1955. # empty = MultiPolygon([empty])
  1956. #
  1957. # if empty.is_empty:
  1958. # self.app.inform.emit(_("[ERROR_NOTCL] Could not get the extent of the area to be non copper cleared."))
  1959. # return
  1960. #
  1961. # # clear non copper using standard algorithm
  1962. # if clearing_method is False:
  1963. # self.clear_non_copper(
  1964. # empty=empty,
  1965. # over=over,
  1966. # pol_method=pol_method,
  1967. # connect=connect,
  1968. # contour=contour
  1969. # )
  1970. # # clear non copper using rest machining algorithm
  1971. # else:
  1972. # self.clear_non_copper_rest(
  1973. # empty=empty,
  1974. # over=over,
  1975. # pol_method=pol_method,
  1976. # connect=connect,
  1977. # contour=contour
  1978. # )
  1979. #
  1980. # def clear_non_copper(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  1981. #
  1982. # name = outname if outname else self.obj_name + "_ncc"
  1983. #
  1984. # # Sort tools in descending order
  1985. # sorted_tools = []
  1986. # for k, v in self.ncc_tools.items():
  1987. # sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  1988. #
  1989. # order = self.ncc_order_radio.get_value()
  1990. # if order == 'fwd':
  1991. # sorted_tools.sort(reverse=False)
  1992. # elif order == 'rev':
  1993. # sorted_tools.sort(reverse=True)
  1994. # else:
  1995. # pass
  1996. #
  1997. # # Do job in background
  1998. # proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  1999. #
  2000. # def initialize(geo_obj, app_obj):
  2001. # assert isinstance(geo_obj, FlatCAMGeometry), \
  2002. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2003. #
  2004. # cleared_geo = []
  2005. # # Already cleared area
  2006. # cleared = MultiPolygon()
  2007. #
  2008. # # flag for polygons not cleared
  2009. # app_obj.poly_not_cleared = False
  2010. #
  2011. # # Generate area for each tool
  2012. # offset = sum(sorted_tools)
  2013. # current_uid = int(1)
  2014. # tool = eval(self.app.defaults["tools_ncctools"])[0]
  2015. #
  2016. # for tool in sorted_tools:
  2017. # self.app.inform.emit(_('[success] Non-Copper Clearing with ToolDia = %s started.') % str(tool))
  2018. # cleared_geo[:] = []
  2019. #
  2020. # # Get remaining tools offset
  2021. # offset -= (tool - 1e-12)
  2022. #
  2023. # # Area to clear
  2024. # area = empty.buffer(-offset)
  2025. # try:
  2026. # area = area.difference(cleared)
  2027. # except Exception as e:
  2028. # continue
  2029. #
  2030. # # Transform area to MultiPolygon
  2031. # if type(area) is Polygon:
  2032. # area = MultiPolygon([area])
  2033. #
  2034. # if area.geoms:
  2035. # if len(area.geoms) > 0:
  2036. # for p in area.geoms:
  2037. # try:
  2038. # if pol_method == 'standard':
  2039. # cp = self.clear_polygon(p, tool, self.app.defaults["gerber_circle_steps"],
  2040. # overlap=over, contour=contour, connect=connect)
  2041. # elif pol_method == 'seed':
  2042. # cp = self.clear_polygon2(p, tool, self.app.defaults["gerber_circle_steps"],
  2043. # overlap=over, contour=contour, connect=connect)
  2044. # else:
  2045. # cp = self.clear_polygon3(p, tool, self.app.defaults["gerber_circle_steps"],
  2046. # overlap=over, contour=contour, connect=connect)
  2047. # if cp:
  2048. # cleared_geo += list(cp.get_objects())
  2049. # except Exception as e:
  2050. # log.warning("Polygon can not be cleared. %s" % str(e))
  2051. # app_obj.poly_not_cleared = True
  2052. # continue
  2053. #
  2054. # # check if there is a geometry at all in the cleared geometry
  2055. # if cleared_geo:
  2056. # # Overall cleared area
  2057. # cleared = empty.buffer(-offset * (1 + over)).buffer(-tool / 1.999999).buffer(
  2058. # tool / 1.999999)
  2059. #
  2060. # # clean-up cleared geo
  2061. # cleared = cleared.buffer(0)
  2062. #
  2063. # # find the tooluid associated with the current tool_dia so we know where to add the tool
  2064. # # solid_geometry
  2065. # for k, v in self.ncc_tools.items():
  2066. # if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  2067. # current_uid = int(k)
  2068. #
  2069. # # add the solid_geometry to the current too in self.paint_tools dictionary
  2070. # # and then reset the temporary list that stored that solid_geometry
  2071. # v['solid_geometry'] = deepcopy(cleared_geo)
  2072. # v['data']['name'] = name
  2073. # break
  2074. # geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  2075. # else:
  2076. # log.debug("There are no geometries in the cleared polygon.")
  2077. #
  2078. # geo_obj.options["cnctooldia"] = str(tool)
  2079. # geo_obj.multigeo = True
  2080. #
  2081. # def job_thread(app_obj):
  2082. # try:
  2083. # app_obj.new_object("geometry", name, initialize)
  2084. # except Exception as e:
  2085. # proc.done()
  2086. # self.app.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper() --> %s') % str(e))
  2087. # return
  2088. # proc.done()
  2089. #
  2090. # if app_obj.poly_not_cleared is False:
  2091. # self.app.inform.emit(_('[success] NCC Tool finished.'))
  2092. # else:
  2093. # self.app.inform.emit(_('[WARNING_NOTCL] NCC Tool finished but some PCB features could not be cleared. '
  2094. # 'Check the result.'))
  2095. # # reset the variable for next use
  2096. # app_obj.poly_not_cleared = False
  2097. #
  2098. # # focus on Selected Tab
  2099. # self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2100. #
  2101. # # Promise object with the new name
  2102. # self.app.collection.promise(name)
  2103. #
  2104. # # Background
  2105. # self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2106. #
  2107. # # clear copper with 'rest-machining' algorithm
  2108. # def clear_non_copper_rest(self, empty, over, pol_method, outname=None, connect=True, contour=True):
  2109. #
  2110. # name = outname if outname is not None else self.obj_name + "_ncc_rm"
  2111. #
  2112. # # Sort tools in descending order
  2113. # sorted_tools = []
  2114. # for k, v in self.ncc_tools.items():
  2115. # sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  2116. # sorted_tools.sort(reverse=True)
  2117. #
  2118. # # Do job in background
  2119. # proc = self.app.proc_container.new(_("Clearing Non-Copper areas."))
  2120. #
  2121. # def initialize_rm(geo_obj, app_obj):
  2122. # assert isinstance(geo_obj, FlatCAMGeometry), \
  2123. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  2124. #
  2125. # cleared_geo = []
  2126. # cleared_by_last_tool = []
  2127. # rest_geo = []
  2128. # current_uid = 1
  2129. # tool = eval(self.app.defaults["tools_ncctools"])[0]
  2130. #
  2131. # # repurposed flag for final object, geo_obj. True if it has any solid_geometry, False if not.
  2132. # app_obj.poly_not_cleared = True
  2133. #
  2134. # area = empty.buffer(0)
  2135. # # Generate area for each tool
  2136. # while sorted_tools:
  2137. # tool = sorted_tools.pop(0)
  2138. # self.app.inform.emit(_('[success] Non-Copper Rest Clearing with ToolDia = %s started.') % str(tool))
  2139. #
  2140. # tool_used = tool - 1e-12
  2141. # cleared_geo[:] = []
  2142. #
  2143. # # Area to clear
  2144. # for poly in cleared_by_last_tool:
  2145. # try:
  2146. # area = area.difference(poly)
  2147. # except Exception as e:
  2148. # pass
  2149. # cleared_by_last_tool[:] = []
  2150. #
  2151. # # Transform area to MultiPolygon
  2152. # if type(area) is Polygon:
  2153. # area = MultiPolygon([area])
  2154. #
  2155. # # add the rest that was not able to be cleared previously; area is a MultyPolygon
  2156. # # and rest_geo it's a list
  2157. # allparts = [p.buffer(0) for p in area.geoms]
  2158. # allparts += deepcopy(rest_geo)
  2159. # rest_geo[:] = []
  2160. # area = MultiPolygon(deepcopy(allparts))
  2161. # allparts[:] = []
  2162. #
  2163. # if area.geoms:
  2164. # if len(area.geoms) > 0:
  2165. # for p in area.geoms:
  2166. # try:
  2167. # if pol_method == 'standard':
  2168. # cp = self.clear_polygon(p, tool_used, self.app.defaults["gerber_circle_steps"],
  2169. # overlap=over, contour=contour, connect=connect)
  2170. # elif pol_method == 'seed':
  2171. # cp = self.clear_polygon2(p, tool_used,
  2172. # self.app.defaults["gerber_circle_steps"],
  2173. # overlap=over, contour=contour, connect=connect)
  2174. # else:
  2175. # cp = self.clear_polygon3(p, tool_used,
  2176. # self.app.defaults["gerber_circle_steps"],
  2177. # overlap=over, contour=contour, connect=connect)
  2178. # cleared_geo.append(list(cp.get_objects()))
  2179. # except:
  2180. # log.warning("Polygon can't be cleared.")
  2181. # # this polygon should be added to a list and then try clear it with a smaller tool
  2182. # rest_geo.append(p)
  2183. #
  2184. # # check if there is a geometry at all in the cleared geometry
  2185. # if cleared_geo:
  2186. # # Overall cleared area
  2187. # cleared_area = list(self.flatten_list(cleared_geo))
  2188. #
  2189. # # cleared = MultiPolygon([p.buffer(tool_used / 2).buffer(-tool_used / 2)
  2190. # # for p in cleared_area])
  2191. #
  2192. # # here we store the poly's already processed in the original geometry by the current tool
  2193. # # into cleared_by_last_tool list
  2194. # # this will be sustracted from the original geometry_to_be_cleared and make data for
  2195. # # the next tool
  2196. # buffer_value = tool_used / 2
  2197. # for p in cleared_area:
  2198. # poly = p.buffer(buffer_value)
  2199. # cleared_by_last_tool.append(poly)
  2200. #
  2201. # # find the tooluid associated with the current tool_dia so we know
  2202. # # where to add the tool solid_geometry
  2203. # for k, v in self.ncc_tools.items():
  2204. # if float('%.4f' % v['tooldia']) == float('%.4f' % tool):
  2205. # current_uid = int(k)
  2206. #
  2207. # # add the solid_geometry to the current too in self.paint_tools dictionary
  2208. # # and then reset the temporary list that stored that solid_geometry
  2209. # v['solid_geometry'] = deepcopy(cleared_area)
  2210. # v['data']['name'] = name
  2211. # cleared_area[:] = []
  2212. # break
  2213. #
  2214. # geo_obj.tools[current_uid] = dict(self.ncc_tools[current_uid])
  2215. # else:
  2216. # log.debug("There are no geometries in the cleared polygon.")
  2217. #
  2218. # geo_obj.multigeo = True
  2219. # geo_obj.options["cnctooldia"] = str(tool)
  2220. #
  2221. # # check to see if geo_obj.tools is empty
  2222. # # it will be updated only if there is a solid_geometry for tools
  2223. # if geo_obj.tools:
  2224. # return
  2225. # else:
  2226. # # I will use this variable for this purpose although it was meant for something else
  2227. # # signal that we have no geo in the object therefore don't create it
  2228. # app_obj.poly_not_cleared = False
  2229. # return "fail"
  2230. #
  2231. # def job_thread(app_obj):
  2232. # try:
  2233. # app_obj.new_object("geometry", name, initialize_rm)
  2234. # except Exception as e:
  2235. # proc.done()
  2236. # app_obj.inform.emit(_('[ERROR_NOTCL] NCCTool.clear_non_copper_rest() --> %s') % str(e))
  2237. # return
  2238. #
  2239. # if app_obj.poly_not_cleared is True:
  2240. # app_obj.inform.emit('[success] NCC Tool finished.')
  2241. # # focus on Selected Tab
  2242. # app_obj.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2243. # else:
  2244. # app_obj.inform.emit(_('[ERROR_NOTCL] NCC Tool finished but could not clear the object '
  2245. # 'with current settings.'))
  2246. # # focus on Project Tab
  2247. # app_obj.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  2248. # proc.done()
  2249. # # reset the variable for next use
  2250. # app_obj.poly_not_cleared = False
  2251. #
  2252. # # Promise object with the new name
  2253. # self.app.collection.promise(name)
  2254. #
  2255. # # Background
  2256. # self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2257. def get_ncc_empty_area(self, target, boundary=None):
  2258. """
  2259. Returns the complement of target geometry within
  2260. the given boundary polygon. If not specified, it defaults to
  2261. the rectangular bounding box of target geometry.
  2262. """
  2263. if isinstance(target, Polygon):
  2264. geo_len = 1
  2265. else:
  2266. geo_len = len(target)
  2267. pol_nr = 0
  2268. old_disp_number = 0
  2269. if boundary is None:
  2270. boundary = target.envelope
  2271. else:
  2272. boundary = boundary
  2273. try:
  2274. ret_val = boundary.difference(target)
  2275. except Exception as e:
  2276. try:
  2277. for el in target:
  2278. if self.app.abort_flag:
  2279. # graceful abort requested by the user
  2280. raise FlatCAMApp.GracefulException
  2281. boundary = boundary.difference(el)
  2282. pol_nr += 1
  2283. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2284. if old_disp_number < disp_number <= 100:
  2285. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2286. old_disp_number = disp_number
  2287. return boundary
  2288. except Exception as e:
  2289. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2290. _("Try to use the Buffering Type = Full in Preferences -> Gerber General. "
  2291. "Reload the Gerber file after this change."))
  2292. return 'fail'
  2293. return ret_val
  2294. def reset_fields(self):
  2295. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  2296. def reset_usage(self):
  2297. self.obj_name = ""
  2298. self.ncc_obj = None
  2299. self.bound_obj = None
  2300. self.first_click = False
  2301. self.cursor_pos = None
  2302. self.mouse_is_dragging = False
  2303. self.sel_rect = []
  2304. @staticmethod
  2305. def poly2rings(poly):
  2306. return [poly.exterior] + [interior for interior in poly.interiors]
  2307. def generate_envelope(self, offset, invert, envelope_iso_type=2, follow=None):
  2308. # isolation_geometry produces an envelope that is going on the left of the geometry
  2309. # (the copper features). To leave the least amount of burrs on the features
  2310. # the tool needs to travel on the right side of the features (this is called conventional milling)
  2311. # the first pass is the one cutting all of the features, so it needs to be reversed
  2312. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  2313. # to cut on the right side of the left over copper i.e on the left side of the features.
  2314. try:
  2315. geom = self.isolation_geometry(offset, iso_type=envelope_iso_type, follow=follow)
  2316. except Exception as e:
  2317. log.debug('NonCopperClear.generate_envelope() --> %s' % str(e))
  2318. return 'fail'
  2319. if invert:
  2320. try:
  2321. try:
  2322. pl = []
  2323. for p in geom:
  2324. if p is not None:
  2325. if isinstance(p, Polygon):
  2326. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  2327. elif isinstance(p, LinearRing):
  2328. pl.append(Polygon(p.coords[::-1]))
  2329. geom = MultiPolygon(pl)
  2330. except TypeError:
  2331. if isinstance(geom, Polygon) and geom is not None:
  2332. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  2333. elif isinstance(geom, LinearRing) and geom is not None:
  2334. geom = Polygon(geom.coords[::-1])
  2335. else:
  2336. log.debug("NonCopperClear.generate_envelope() Error --> Unexpected Geometry %s" %
  2337. type(geom))
  2338. except Exception as e:
  2339. log.debug("NonCopperClear.generate_envelope() Error --> %s" % str(e))
  2340. return 'fail'
  2341. return geom