ToolNonCopperClear.py 86 KB

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