ToolCutOut.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. from FlatCAMTool import FlatCAMTool
  2. from copy import copy,deepcopy
  3. from ObjectCollection import *
  4. from FlatCAMApp import *
  5. from PyQt5 import QtGui, QtCore, QtWidgets
  6. from GUIElements import IntEntry, RadioSet, LengthEntry
  7. from FlatCAMObj import FlatCAMGeometry, FlatCAMExcellon, FlatCAMGerber
  8. class ToolCutOut(FlatCAMTool):
  9. toolName = "Cutout PCB"
  10. def __init__(self, app):
  11. FlatCAMTool.__init__(self, app)
  12. ## Title
  13. title_label = QtWidgets.QLabel("<font size=4><b>%s</b></font>" % self.toolName)
  14. self.layout.addWidget(title_label)
  15. ## Form Layout
  16. form_layout = QtWidgets.QFormLayout()
  17. self.layout.addLayout(form_layout)
  18. ## Type of object to be cutout
  19. self.type_obj_combo = QtWidgets.QComboBox()
  20. self.type_obj_combo.addItem("Gerber")
  21. self.type_obj_combo.addItem("Excellon")
  22. self.type_obj_combo.addItem("Geometry")
  23. # we get rid of item1 ("Excellon") as it is not suitable for creating film
  24. self.type_obj_combo.view().setRowHidden(1, True)
  25. self.type_obj_combo.setItemIcon(0, QtGui.QIcon("share/flatcam_icon16.png"))
  26. # self.type_obj_combo.setItemIcon(1, QtGui.QIcon("share/drill16.png"))
  27. self.type_obj_combo.setItemIcon(2, QtGui.QIcon("share/geometry16.png"))
  28. self.type_obj_combo_label = QtWidgets.QLabel("Object Type:")
  29. self.type_obj_combo_label.setToolTip(
  30. "Specify the type of object to be cutout.\n"
  31. "It can be of type: Gerber or Geometry.\n"
  32. "What is selected here will dictate the kind\n"
  33. "of objects that will populate the 'Object' combobox."
  34. )
  35. form_layout.addRow(self.type_obj_combo_label, self.type_obj_combo)
  36. ## Object to be cutout
  37. self.obj_combo = QtWidgets.QComboBox()
  38. self.obj_combo.setModel(self.app.collection)
  39. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  40. self.obj_combo.setCurrentIndex(1)
  41. self.object_label = QtWidgets.QLabel("Object:")
  42. self.object_label.setToolTip(
  43. "Object to be cutout. "
  44. )
  45. form_layout.addRow(self.object_label, self.obj_combo)
  46. # Tool Diameter
  47. self.dia = FCEntry()
  48. self.dia_label = QtWidgets.QLabel("Tool Dia:")
  49. self.dia_label.setToolTip(
  50. "Diameter of the tool used to cutout\n"
  51. "the PCB shape out of the surrounding material."
  52. )
  53. form_layout.addRow(self.dia_label, self.dia)
  54. # Margin
  55. self.margin = FCEntry()
  56. self.margin_label = QtWidgets.QLabel("Margin:")
  57. self.margin_label.setToolTip(
  58. "Margin over bounds. A positive value here\n"
  59. "will make the cutout of the PCB further from\n"
  60. "the actual PCB border"
  61. )
  62. form_layout.addRow(self.margin_label, self.margin)
  63. # Gapsize
  64. self.gapsize = FCEntry()
  65. self.gapsize_label = QtWidgets.QLabel("Gap size:")
  66. self.gapsize_label.setToolTip(
  67. "The size of the gaps in the cutout\n"
  68. "used to keep the board connected to\n"
  69. "the surrounding material (the one \n"
  70. "from which the PCB is cutout)."
  71. )
  72. form_layout.addRow(self.gapsize_label, self.gapsize)
  73. ## Title2
  74. title_ff_label = QtWidgets.QLabel("<font size=4><b>FreeForm Cutout</b></font>")
  75. self.layout.addWidget(title_ff_label)
  76. ## Form Layout
  77. form_layout_2 = QtWidgets.QFormLayout()
  78. self.layout.addLayout(form_layout_2)
  79. # How gaps wil be rendered:
  80. # lr - left + right
  81. # tb - top + bottom
  82. # 4 - left + right +top + bottom
  83. # 2lr - 2*left + 2*right
  84. # 2tb - 2*top + 2*bottom
  85. # 8 - 2*left + 2*right +2*top + 2*bottom
  86. # Gaps
  87. gaps_ff_label = QtWidgets.QLabel('Gaps FF: ')
  88. gaps_ff_label.setToolTip(
  89. "Number of gaps used for the FreeForm cutout.\n"
  90. "There can be maximum 8 bridges/gaps.\n"
  91. "The choices are:\n"
  92. "- lr - left + right\n"
  93. "- tb - top + bottom\n"
  94. "- 4 - left + right +top + bottom\n"
  95. "- 2lr - 2*left + 2*right\n"
  96. "- 2tb - 2*top + 2*bottom\n"
  97. "- 8 - 2*left + 2*right +2*top + 2*bottom"
  98. )
  99. self.gaps = FCComboBox()
  100. gaps_items = ['LR', 'TB', '4', '2LR', '2TB', '8']
  101. for it in gaps_items:
  102. self.gaps.addItem(it)
  103. self.gaps.setStyleSheet('background-color: rgb(255,255,255)')
  104. form_layout_2.addRow(gaps_ff_label, self.gaps)
  105. ## Buttons
  106. hlay = QtWidgets.QHBoxLayout()
  107. self.layout.addLayout(hlay)
  108. hlay.addStretch()
  109. self.ff_cutout_object_btn = QtWidgets.QPushButton(" FreeForm Cutout Object ")
  110. self.ff_cutout_object_btn.setToolTip(
  111. "Cutout the selected object.\n"
  112. "The cutout shape can be any shape.\n"
  113. "Useful when the PCB has a non-rectangular shape.\n"
  114. "But if the object to be cutout is of Gerber Type,\n"
  115. "it needs to be an outline of the actual board shape."
  116. )
  117. hlay.addWidget(self.ff_cutout_object_btn)
  118. ## Title3
  119. title_rct_label = QtWidgets.QLabel("<font size=4><b>Rectangular Cutout</b></font>")
  120. self.layout.addWidget(title_rct_label)
  121. ## Form Layout
  122. form_layout_3 = QtWidgets.QFormLayout()
  123. self.layout.addLayout(form_layout_3)
  124. gapslabel_rect = QtWidgets.QLabel('Type of gaps:')
  125. gapslabel_rect.setToolTip(
  126. "Where to place the gaps:\n"
  127. "- one gap Top / one gap Bottom\n"
  128. "- one gap Left / one gap Right\n"
  129. "- one gap on each of the 4 sides."
  130. )
  131. self.gaps_rect_radio = RadioSet([{'label': '2(T/B)', 'value': 'tb'},
  132. {'label': '2(L/R)', 'value': 'lr'},
  133. {'label': '4', 'value': '4'}])
  134. form_layout_3.addRow(gapslabel_rect, self.gaps_rect_radio)
  135. hlay2 = QtWidgets.QHBoxLayout()
  136. self.layout.addLayout(hlay2)
  137. hlay2.addStretch()
  138. self.rect_cutout_object_btn = QtWidgets.QPushButton("Rectangular Cutout Object")
  139. self.rect_cutout_object_btn.setToolTip(
  140. "Cutout the selected object.\n"
  141. "The resulting cutout shape is\n"
  142. "always of a rectangle form and it will be\n"
  143. "the bounding box of the Object."
  144. )
  145. hlay2.addWidget(self.rect_cutout_object_btn)
  146. self.layout.addStretch()
  147. ## Init GUI
  148. # self.dia.set_value(1)
  149. # self.margin.set_value(0)
  150. # self.gapsize.set_value(1)
  151. # self.gaps.set_value(4)
  152. # self.gaps_rect_radio.set_value("4")
  153. ## Signals
  154. self.ff_cutout_object_btn.clicked.connect(self.on_freeform_cutout)
  155. self.rect_cutout_object_btn.clicked.connect(self.on_rectangular_cutout)
  156. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  157. def on_type_obj_index_changed(self, index):
  158. obj_type = self.type_obj_combo.currentIndex()
  159. self.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  160. self.obj_combo.setCurrentIndex(0)
  161. def run(self):
  162. self.app.report_usage("ToolCutOut()")
  163. FlatCAMTool.run(self)
  164. self.set_tool_ui()
  165. self.app.ui.notebook.setTabText(2, "Cutout Tool")
  166. def install(self, icon=None, separator=None, **kwargs):
  167. FlatCAMTool.install(self, icon, separator, shortcut='ALT+U', **kwargs)
  168. def set_tool_ui(self):
  169. self.reset_fields()
  170. self.dia.set_value(float(self.app.defaults["tools_cutouttooldia"]))
  171. self.margin.set_value(float(self.app.defaults["tools_cutoutmargin"]))
  172. self.gapsize.set_value(float(self.app.defaults["tools_cutoutgapsize"]))
  173. self.gaps.set_value(4)
  174. self.gaps_rect_radio.set_value(str(self.app.defaults["tools_gaps_rect"]))
  175. def on_freeform_cutout(self):
  176. def subtract_rectangle(obj_, x0, y0, x1, y1):
  177. pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  178. obj_.subtract_polygon(pts)
  179. name = self.obj_combo.currentText()
  180. # Get source object.
  181. try:
  182. cutout_obj = self.app.collection.get_by_name(str(name))
  183. except:
  184. self.app.inform.emit("[ERROR_NOTCL]Could not retrieve object: %s" % name)
  185. return "Could not retrieve object: %s" % name
  186. if cutout_obj is None:
  187. self.app.inform.emit("[ERROR_NOTCL]There is no object selected for Cutout.\nSelect one and try again.")
  188. return
  189. try:
  190. dia = float(self.dia.get_value())
  191. except ValueError:
  192. # try to convert comma to decimal point. if it's still not working error message and return
  193. try:
  194. dia = float(self.dia.get_value().replace(',', '.'))
  195. except ValueError:
  196. self.app.inform.emit("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  197. "Add it and retry.")
  198. return
  199. try:
  200. margin = float(self.margin.get_value())
  201. except ValueError:
  202. # try to convert comma to decimal point. if it's still not working error message and return
  203. try:
  204. margin = float(self.margin.get_value().replace(',', '.'))
  205. except ValueError:
  206. self.app.inform.emit("[WARNING_NOTCL] Margin value is missing or wrong format. "
  207. "Add it and retry.")
  208. return
  209. try:
  210. gapsize = float(self.gapsize.get_value())
  211. except ValueError:
  212. # try to convert comma to decimal point. if it's still not working error message and return
  213. try:
  214. gapsize = float(self.gapsize.get_value().replace(',', '.'))
  215. except ValueError:
  216. self.app.inform.emit("[WARNING_NOTCL] Gap size value is missing or wrong format. "
  217. "Add it and retry.")
  218. return
  219. try:
  220. gaps = self.gaps.get_value()
  221. except TypeError:
  222. self.app.inform.emit("[WARNING_NOTCL] Number of gaps value is missing. Add it and retry.")
  223. return
  224. if 0 in {dia}:
  225. self.app.inform.emit("[WARNING_NOTCL]Tool Diameter is zero value. Change it to a positive integer.")
  226. return "Tool Diameter is zero value. Change it to a positive integer."
  227. if gaps not in ['lr', 'tb', '2lr', '2tb', '4', '8']:
  228. self.app.inform.emit("[WARNING_NOTCL] Gaps value can be only one of: 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  229. "Fill in a correct value and retry. ")
  230. return
  231. if cutout_obj.multigeo is True:
  232. self.app.inform.emit("[ERROR]Cutout operation cannot be done on a multi-geo Geometry.\n"
  233. "Optionally, this Multi-geo Geometry can be converted to Single-geo Geometry,\n"
  234. "and after that perform Cutout.")
  235. return
  236. # Get min and max data for each object as we just cut rectangles across X or Y
  237. xmin, ymin, xmax, ymax = cutout_obj.bounds()
  238. px = 0.5 * (xmin + xmax) + margin
  239. py = 0.5 * (ymin + ymax) + margin
  240. lenghtx = (xmax - xmin) + (margin * 2)
  241. lenghty = (ymax - ymin) + (margin * 2)
  242. gapsize = gapsize / 2 + (dia / 2)
  243. if isinstance(cutout_obj,FlatCAMGeometry):
  244. # rename the obj name so it can be identified as cutout
  245. cutout_obj.options["name"] += "_cutout"
  246. else:
  247. cutout_obj.isolate(dia=dia, passes=1, overlap=1, combine=False, outname="_temp")
  248. ext_obj = self.app.collection.get_by_name("_temp")
  249. def geo_init(geo_obj, app_obj):
  250. geo_obj.solid_geometry = obj_exteriors
  251. outname = cutout_obj.options["name"] + "_cutout"
  252. obj_exteriors = ext_obj.get_exteriors()
  253. self.app.new_object('geometry', outname, geo_init)
  254. self.app.collection.set_all_inactive()
  255. self.app.collection.set_active("_temp")
  256. self.app.on_delete()
  257. cutout_obj = self.app.collection.get_by_name(outname)
  258. if int(gaps) == 8 or gaps == '2lr':
  259. subtract_rectangle(cutout_obj,
  260. xmin - gapsize, # botleft_x
  261. py - gapsize + lenghty / 4, # botleft_y
  262. xmax + gapsize, # topright_x
  263. py + gapsize + lenghty / 4) # topright_y
  264. subtract_rectangle(cutout_obj,
  265. xmin - gapsize,
  266. py - gapsize - lenghty / 4,
  267. xmax + gapsize,
  268. py + gapsize - lenghty / 4)
  269. if int(gaps) == 8 or gaps == '2tb':
  270. subtract_rectangle(cutout_obj,
  271. px - gapsize + lenghtx / 4,
  272. ymin - gapsize,
  273. px + gapsize + lenghtx / 4,
  274. ymax + gapsize)
  275. subtract_rectangle(cutout_obj,
  276. px - gapsize - lenghtx / 4,
  277. ymin - gapsize,
  278. px + gapsize - lenghtx / 4,
  279. ymax + gapsize)
  280. if int(gaps) == 4 or gaps == 'lr':
  281. subtract_rectangle(cutout_obj,
  282. xmin - gapsize,
  283. py - gapsize,
  284. xmax + gapsize,
  285. py + gapsize)
  286. if int(gaps) == 4 or gaps == 'tb':
  287. subtract_rectangle(cutout_obj,
  288. px - gapsize,
  289. ymin - gapsize,
  290. px + gapsize,
  291. ymax + gapsize)
  292. cutout_obj.plot()
  293. self.app.inform.emit("[success] Any form CutOut operation finished.")
  294. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  295. def on_rectangular_cutout(self):
  296. name = self.obj_combo.currentText()
  297. # Get source object.
  298. try:
  299. cutout_obj = self.app.collection.get_by_name(str(name))
  300. except:
  301. self.app.inform.emit("[ERROR_NOTCL]Could not retrieve object: %s" % name)
  302. return "Could not retrieve object: %s" % name
  303. if cutout_obj is None:
  304. self.app.inform.emit("[ERROR_NOTCL]Object not found: %s" % cutout_obj)
  305. try:
  306. dia = float(self.dia.get_value())
  307. except ValueError:
  308. # try to convert comma to decimal point. if it's still not working error message and return
  309. try:
  310. dia = float(self.dia.get_value().replace(',', '.'))
  311. except ValueError:
  312. self.app.inform.emit("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  313. "Add it and retry.")
  314. return
  315. try:
  316. margin = float(self.margin.get_value())
  317. except ValueError:
  318. # try to convert comma to decimal point. if it's still not working error message and return
  319. try:
  320. margin = float(self.margin.get_value().replace(',', '.'))
  321. except ValueError:
  322. self.app.inform.emit("[WARNING_NOTCL] Margin value is missing or wrong format. "
  323. "Add it and retry.")
  324. return
  325. try:
  326. gapsize = float(self.gapsize.get_value())
  327. except ValueError:
  328. # try to convert comma to decimal point. if it's still not working error message and return
  329. try:
  330. gapsize = float(self.gapsize.get_value().replace(',', '.'))
  331. except ValueError:
  332. self.app.inform.emit("[WARNING_NOTCL] Gap size value is missing or wrong format. "
  333. "Add it and retry.")
  334. return
  335. try:
  336. gaps = self.gaps_rect_radio.get_value()
  337. except TypeError:
  338. self.app.inform.emit("[WARNING_NOTCL] Number of gaps value is missing. Add it and retry.")
  339. return
  340. if 0 in {dia}:
  341. self.app.inform.emit("[ERROR_NOTCL]Tool Diameter is zero value. Change it to a positive integer.")
  342. return "Tool Diameter is zero value. Change it to a positive integer."
  343. if cutout_obj.multigeo is True:
  344. self.app.inform.emit("[ERROR]Cutout operation cannot be done on a multi-geo Geometry.\n"
  345. "Optionally, this Multi-geo Geometry can be converted to Single-geo Geometry,\n"
  346. "and after that perform Cutout.")
  347. return
  348. def geo_init(geo_obj, app_obj):
  349. real_margin = margin + (dia / 2)
  350. real_gap_size = gapsize + dia
  351. minx, miny, maxx, maxy = cutout_obj.bounds()
  352. minx -= real_margin
  353. maxx += real_margin
  354. miny -= real_margin
  355. maxy += real_margin
  356. midx = 0.5 * (minx + maxx)
  357. midy = 0.5 * (miny + maxy)
  358. hgap = 0.5 * real_gap_size
  359. pts = [[midx - hgap, maxy],
  360. [minx, maxy],
  361. [minx, midy + hgap],
  362. [minx, midy - hgap],
  363. [minx, miny],
  364. [midx - hgap, miny],
  365. [midx + hgap, miny],
  366. [maxx, miny],
  367. [maxx, midy - hgap],
  368. [maxx, midy + hgap],
  369. [maxx, maxy],
  370. [midx + hgap, maxy]]
  371. cases = {"tb": [[pts[0], pts[1], pts[4], pts[5]],
  372. [pts[6], pts[7], pts[10], pts[11]]],
  373. "lr": [[pts[9], pts[10], pts[1], pts[2]],
  374. [pts[3], pts[4], pts[7], pts[8]]],
  375. "4": [[pts[0], pts[1], pts[2]],
  376. [pts[3], pts[4], pts[5]],
  377. [pts[6], pts[7], pts[8]],
  378. [pts[9], pts[10], pts[11]]]}
  379. cuts = cases[gaps]
  380. geo_obj.solid_geometry = cascaded_union([LineString(segment) for segment in cuts])
  381. # TODO: Check for None
  382. self.app.new_object("geometry", name + "_cutout", geo_init)
  383. self.app.inform.emit("[success] Rectangular CutOut operation finished.")
  384. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  385. def reset_fields(self):
  386. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))