ToolNonCopperClear.py 131 KB

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