ToolCutOut.py 19 KB

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