ToolCutOut.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  1. from FlatCAMTool import FlatCAMTool
  2. from ObjectCollection import *
  3. from FlatCAMApp import *
  4. from shapely.geometry import box
  5. from shapely.ops import cascaded_union, unary_union
  6. import gettext
  7. import FlatCAMTranslation as fcTranslate
  8. import builtins
  9. fcTranslate.apply_language('strings')
  10. if '_' not in builtins.__dict__:
  11. _ = gettext.gettext
  12. class CutOut(FlatCAMTool):
  13. toolName = _("Cutout PCB")
  14. gapFinished = pyqtSignal()
  15. def __init__(self, app):
  16. FlatCAMTool.__init__(self, app)
  17. self.app = app
  18. self.canvas = app.plotcanvas
  19. # Title
  20. title_label = QtWidgets.QLabel("%s" % self.toolName)
  21. title_label.setStyleSheet("""
  22. QLabel
  23. {
  24. font-size: 16px;
  25. font-weight: bold;
  26. }
  27. """)
  28. self.layout.addWidget(title_label)
  29. # Form Layout
  30. form_layout = QtWidgets.QFormLayout()
  31. self.layout.addLayout(form_layout)
  32. # Type of object to be cutout
  33. self.type_obj_combo = QtWidgets.QComboBox()
  34. self.type_obj_combo.addItem("Gerber")
  35. self.type_obj_combo.addItem("Excellon")
  36. self.type_obj_combo.addItem("Geometry")
  37. # we get rid of item1 ("Excellon") as it is not suitable for creating film
  38. self.type_obj_combo.view().setRowHidden(1, True)
  39. self.type_obj_combo.setItemIcon(0, QtGui.QIcon("share/flatcam_icon16.png"))
  40. # self.type_obj_combo.setItemIcon(1, QtGui.QIcon("share/drill16.png"))
  41. self.type_obj_combo.setItemIcon(2, QtGui.QIcon("share/geometry16.png"))
  42. self.type_obj_combo_label = QtWidgets.QLabel('%s:' % _("Obj Type"))
  43. self.type_obj_combo_label.setToolTip(
  44. _("Specify the type of object to be cutout.\n"
  45. "It can be of type: Gerber or Geometry.\n"
  46. "What is selected here will dictate the kind\n"
  47. "of objects that will populate the 'Object' combobox.")
  48. )
  49. self.type_obj_combo_label.setMinimumWidth(60)
  50. form_layout.addRow(self.type_obj_combo_label, self.type_obj_combo)
  51. # Object to be cutout
  52. self.obj_combo = QtWidgets.QComboBox()
  53. self.obj_combo.setModel(self.app.collection)
  54. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  55. self.obj_combo.setCurrentIndex(1)
  56. self.object_label = QtWidgets.QLabel('%s:' % _("Object"))
  57. self.object_label.setToolTip(
  58. _("Object to be cutout. ")
  59. )
  60. form_layout.addRow(self.object_label, self.obj_combo)
  61. # Object kind
  62. self.kindlabel = QtWidgets.QLabel('%s:' % _('Obj kind'))
  63. self.kindlabel.setToolTip(
  64. _("Choice of what kind the object we want to cutout is.<BR>"
  65. "- <B>Single</B>: contain a single PCB Gerber outline object.<BR>"
  66. "- <B>Panel</B>: a panel PCB Gerber object, which is made\n"
  67. "out of many individual PCB outlines.")
  68. )
  69. self.obj_kind_combo = RadioSet([
  70. {"label": _("Single"), "value": "single"},
  71. {"label": _("Panel"), "value": "panel"},
  72. ])
  73. form_layout.addRow(self.kindlabel, self.obj_kind_combo)
  74. # Tool Diameter
  75. self.dia = FCEntry()
  76. self.dia_label = QtWidgets.QLabel('%s:' % _("Tool dia"))
  77. self.dia_label.setToolTip(
  78. _("Diameter of the tool used to cutout\n"
  79. "the PCB shape out of the surrounding material.")
  80. )
  81. form_layout.addRow(self.dia_label, self.dia)
  82. # Margin
  83. self.margin = FCEntry()
  84. self.margin_label = QtWidgets.QLabel('%s:' % _("Margin:"))
  85. self.margin_label.setToolTip(
  86. _("Margin over bounds. A positive value here\n"
  87. "will make the cutout of the PCB further from\n"
  88. "the actual PCB border")
  89. )
  90. form_layout.addRow(self.margin_label, self.margin)
  91. # Gapsize
  92. self.gapsize = FCEntry()
  93. self.gapsize_label = QtWidgets.QLabel('%s:' % _("Gap size:"))
  94. self.gapsize_label.setToolTip(
  95. _("The size of the bridge gaps in the cutout\n"
  96. "used to keep the board connected to\n"
  97. "the surrounding material (the one \n"
  98. "from which the PCB is cutout).")
  99. )
  100. form_layout.addRow(self.gapsize_label, self.gapsize)
  101. # How gaps wil be rendered:
  102. # lr - left + right
  103. # tb - top + bottom
  104. # 4 - left + right +top + bottom
  105. # 2lr - 2*left + 2*right
  106. # 2tb - 2*top + 2*bottom
  107. # 8 - 2*left + 2*right +2*top + 2*bottom
  108. # Surrounding convex box shape
  109. self.convex_box = FCCheckBox()
  110. self.convex_box_label = QtWidgets.QLabel('%s:' % _("Convex Sh."))
  111. self.convex_box_label.setToolTip(
  112. _("Create a convex shape surrounding the entire PCB.\n"
  113. "Used only if the source object type is Gerber.")
  114. )
  115. form_layout.addRow(self.convex_box_label, self.convex_box)
  116. # Title2
  117. title_param_label = QtWidgets.QLabel("<font size=4><b>%s</b></font>" % _('A. Automatic Bridge Gaps'))
  118. title_param_label.setToolTip(
  119. _("This section handle creation of automatic bridge gaps.")
  120. )
  121. self.layout.addWidget(title_param_label)
  122. # Form Layout
  123. form_layout_2 = QtWidgets.QFormLayout()
  124. self.layout.addLayout(form_layout_2)
  125. # Gaps
  126. gaps_label = QtWidgets.QLabel('%s:' % _('Gaps'))
  127. gaps_label.setToolTip(
  128. _("Number of gaps used for the Automatic cutout.\n"
  129. "There can be maximum 8 bridges/gaps.\n"
  130. "The choices are:\n"
  131. "- lr - left + right\n"
  132. "- tb - top + bottom\n"
  133. "- 4 - left + right +top + bottom\n"
  134. "- 2lr - 2*left + 2*right\n"
  135. "- 2tb - 2*top + 2*bottom\n"
  136. "- 8 - 2*left + 2*right +2*top + 2*bottom")
  137. )
  138. gaps_label.setMinimumWidth(60)
  139. self.gaps = FCComboBox()
  140. gaps_items = ['LR', 'TB', '4', '2LR', '2TB', '8']
  141. for it in gaps_items:
  142. self.gaps.addItem(it)
  143. self.gaps.setStyleSheet('background-color: rgb(255,255,255)')
  144. form_layout_2.addRow(gaps_label, self.gaps)
  145. # Buttons
  146. hlay = QtWidgets.QHBoxLayout()
  147. self.layout.addLayout(hlay)
  148. title_ff_label = QtWidgets.QLabel("<b>%s:</b>" % _('FreeForm'))
  149. title_ff_label.setToolTip(
  150. _("The cutout shape can be of ny shape.\n"
  151. "Useful when the PCB has a non-rectangular shape.")
  152. )
  153. hlay.addWidget(title_ff_label)
  154. hlay.addStretch()
  155. self.ff_cutout_object_btn = QtWidgets.QPushButton(_("Generate Geo"))
  156. self.ff_cutout_object_btn.setToolTip(
  157. _("Cutout the selected object.\n"
  158. "The cutout shape can be of any shape.\n"
  159. "Useful when the PCB has a non-rectangular shape.")
  160. )
  161. hlay.addWidget(self.ff_cutout_object_btn)
  162. hlay2 = QtWidgets.QHBoxLayout()
  163. self.layout.addLayout(hlay2)
  164. title_rct_label = QtWidgets.QLabel("<b>%s:</b>" % _('Rectangular'))
  165. title_rct_label.setToolTip(
  166. _("The resulting cutout shape is\n"
  167. "always a rectangle shape and it will be\n"
  168. "the bounding box of the Object.")
  169. )
  170. hlay2.addWidget(title_rct_label)
  171. hlay2.addStretch()
  172. self.rect_cutout_object_btn = QtWidgets.QPushButton(_("Generate Geo"))
  173. self.rect_cutout_object_btn.setToolTip(
  174. _("Cutout the selected object.\n"
  175. "The resulting cutout shape is\n"
  176. "always a rectangle shape and it will be\n"
  177. "the bounding box of the Object.")
  178. )
  179. hlay2.addWidget(self.rect_cutout_object_btn)
  180. # Title5
  181. title_manual_label = QtWidgets.QLabel("<font size=4><b>%s</b></font>" % _('B. Manual Bridge Gaps'))
  182. title_manual_label.setToolTip(
  183. _("This section handle creation of manual bridge gaps.\n"
  184. "This is done by mouse clicking on the perimeter of the\n"
  185. "Geometry object that is used as a cutout object. ")
  186. )
  187. self.layout.addWidget(title_manual_label)
  188. # Form Layout
  189. form_layout_3 = QtWidgets.QFormLayout()
  190. self.layout.addLayout(form_layout_3)
  191. # Manual Geo Object
  192. self.man_object_combo = QtWidgets.QComboBox()
  193. self.man_object_combo.setModel(self.app.collection)
  194. self.man_object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  195. self.man_object_combo.setCurrentIndex(1)
  196. self.man_object_label = QtWidgets.QLabel('%s:' % _("Geo Obj"))
  197. self.man_object_label.setToolTip(
  198. _("Geometry object used to create the manual cutout.")
  199. )
  200. self.man_object_label.setMinimumWidth(60)
  201. # e_lab_0 = QtWidgets.QLabel('')
  202. form_layout_3.addRow(self.man_object_label, self.man_object_combo)
  203. # form_layout_3.addRow(e_lab_0)
  204. hlay3 = QtWidgets.QHBoxLayout()
  205. self.layout.addLayout(hlay3)
  206. self.man_geo_label = QtWidgets.QLabel('%s:' % _("Manual Geo"))
  207. self.man_geo_label.setToolTip(
  208. _("If the object to be cutout is a Gerber\n"
  209. "first create a Geometry that surrounds it,\n"
  210. "to be used as the cutout, if one doesn't exist yet.\n"
  211. "Select the source Gerber file in the top object combobox.")
  212. )
  213. hlay3.addWidget(self.man_geo_label)
  214. hlay3.addStretch()
  215. self.man_geo_creation_btn = QtWidgets.QPushButton(_("Generate Geo"))
  216. self.man_geo_creation_btn.setToolTip(
  217. _("If the object to be cutout is a Gerber\n"
  218. "first create a Geometry that surrounds it,\n"
  219. "to be used as the cutout, if one doesn't exist yet.\n"
  220. "Select the source Gerber file in the top object combobox.")
  221. )
  222. hlay3.addWidget(self.man_geo_creation_btn)
  223. hlay4 = QtWidgets.QHBoxLayout()
  224. self.layout.addLayout(hlay4)
  225. self.man_bridge_gaps_label = QtWidgets.QLabel('%s:' % _("Manual Add Bridge Gaps"))
  226. self.man_bridge_gaps_label.setToolTip(
  227. _("Use the left mouse button (LMB) click\n"
  228. "to create a bridge gap to separate the PCB from\n"
  229. "the surrounding material.")
  230. )
  231. hlay4.addWidget(self.man_bridge_gaps_label)
  232. hlay4.addStretch()
  233. self.man_gaps_creation_btn = QtWidgets.QPushButton(_("Generate Gap"))
  234. self.man_gaps_creation_btn.setToolTip(
  235. _("Use the left mouse button (LMB) click\n"
  236. "to create a bridge gap to separate the PCB from\n"
  237. "the surrounding material.\n"
  238. "The LMB click has to be done on the perimeter of\n"
  239. "the Geometry object used as a cutout geometry.")
  240. )
  241. hlay4.addWidget(self.man_gaps_creation_btn)
  242. self.layout.addStretch()
  243. self.cutting_gapsize = 0.0
  244. self.cutting_dia = 0.0
  245. # true if we want to repeat the gap without clicking again on the button
  246. self.repeat_gap = False
  247. self.flat_geometry = []
  248. # Signals
  249. self.ff_cutout_object_btn.clicked.connect(self.on_freeform_cutout)
  250. self.rect_cutout_object_btn.clicked.connect(self.on_rectangular_cutout)
  251. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  252. self.man_geo_creation_btn.clicked.connect(self.on_manual_geo)
  253. self.man_gaps_creation_btn.clicked.connect(self.on_manual_gap_click)
  254. def on_type_obj_index_changed(self, index):
  255. obj_type = self.type_obj_combo.currentIndex()
  256. self.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  257. self.obj_combo.setCurrentIndex(0)
  258. def run(self, toggle=True):
  259. self.app.report_usage("ToolCutOut()")
  260. if toggle:
  261. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  262. if self.app.ui.splitter.sizes()[0] == 0:
  263. self.app.ui.splitter.setSizes([1, 1])
  264. else:
  265. try:
  266. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  267. self.app.ui.splitter.setSizes([0, 1])
  268. except AttributeError:
  269. pass
  270. else:
  271. if self.app.ui.splitter.sizes()[0] == 0:
  272. self.app.ui.splitter.setSizes([1, 1])
  273. FlatCAMTool.run(self)
  274. self.set_tool_ui()
  275. self.app.ui.notebook.setTabText(2, _("Cutout Tool"))
  276. def install(self, icon=None, separator=None, **kwargs):
  277. FlatCAMTool.install(self, icon, separator, shortcut='ALT+U', **kwargs)
  278. def set_tool_ui(self):
  279. self.reset_fields()
  280. self.dia.set_value(float(self.app.defaults["tools_cutouttooldia"]))
  281. self.obj_kind_combo.set_value(self.app.defaults["tools_cutoutkind"])
  282. self.margin.set_value(float(self.app.defaults["tools_cutoutmargin"]))
  283. self.gapsize.set_value(float(self.app.defaults["tools_cutoutgapsize"]))
  284. self.gaps.set_value(self.app.defaults["tools_gaps_ff"])
  285. self.convex_box.set_value(self.app.defaults['tools_cutout_convexshape'])
  286. self.gapFinished.connect(self.on_gap_finished)
  287. def on_freeform_cutout(self):
  288. # def subtract_rectangle(obj_, x0, y0, x1, y1):
  289. # pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  290. # obj_.subtract_polygon(pts)
  291. name = self.obj_combo.currentText()
  292. # Get source object.
  293. try:
  294. cutout_obj = self.app.collection.get_by_name(str(name))
  295. except Exception as e:
  296. log.debug("CutOut.on_freeform_cutout() --> %s" % str(e))
  297. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % name)
  298. return "Could not retrieve object: %s" % name
  299. if cutout_obj is None:
  300. self.app.inform.emit(_("[ERROR_NOTCL] There is no object selected for Cutout.\nSelect one and try again."))
  301. return
  302. try:
  303. dia = float(self.dia.get_value())
  304. except ValueError:
  305. # try to convert comma to decimal point. if it's still not working error message and return
  306. try:
  307. dia = float(self.dia.get_value().replace(',', '.'))
  308. except ValueError:
  309. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  310. "Add it and retry."))
  311. return
  312. if 0 in {dia}:
  313. self.app.inform.emit(_("[WARNING_NOTCL] Tool Diameter is zero value. Change it to a positive real number."))
  314. return "Tool Diameter is zero value. Change it to a positive real number."
  315. try:
  316. kind = self.obj_kind_combo.get_value()
  317. except ValueError:
  318. return
  319. try:
  320. margin = float(self.margin.get_value())
  321. except ValueError:
  322. # try to convert comma to decimal point. if it's still not working error message and return
  323. try:
  324. margin = float(self.margin.get_value().replace(',', '.'))
  325. except ValueError:
  326. self.app.inform.emit(_("[WARNING_NOTCL] Margin value is missing or wrong format. "
  327. "Add it and retry."))
  328. return
  329. try:
  330. gapsize = float(self.gapsize.get_value())
  331. except ValueError:
  332. # try to convert comma to decimal point. if it's still not working error message and return
  333. try:
  334. gapsize = float(self.gapsize.get_value().replace(',', '.'))
  335. except ValueError:
  336. self.app.inform.emit(_("[WARNING_NOTCL] Gap size value is missing or wrong format. "
  337. "Add it and retry."))
  338. return
  339. try:
  340. gaps = self.gaps.get_value()
  341. except TypeError:
  342. self.app.inform.emit(_("[WARNING_NOTCL] Number of gaps value is missing. Add it and retry."))
  343. return
  344. if gaps not in ['LR', 'TB', '2LR', '2TB', '4', '8']:
  345. self.app.inform.emit(_("[WARNING_NOTCL] Gaps value can be only one of: 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  346. "Fill in a correct value and retry. "))
  347. return
  348. if cutout_obj.multigeo is True:
  349. self.app.inform.emit(_("[ERROR]Cutout operation cannot be done on a multi-geo Geometry.\n"
  350. "Optionally, this Multi-geo Geometry can be converted to Single-geo Geometry,\n"
  351. "and after that perform Cutout."))
  352. return
  353. convex_box = self.convex_box.get_value()
  354. gapsize = gapsize / 2 + (dia / 2)
  355. def geo_init(geo_obj, app_obj):
  356. solid_geo = []
  357. if isinstance(cutout_obj, FlatCAMGerber):
  358. if convex_box:
  359. object_geo = cutout_obj.solid_geometry.convex_hull
  360. else:
  361. object_geo = cutout_obj.solid_geometry
  362. else:
  363. object_geo = cutout_obj.solid_geometry
  364. def cutout_handler(geom):
  365. # Get min and max data for each object as we just cut rectangles across X or Y
  366. xmin, ymin, xmax, ymax = recursive_bounds(geom)
  367. px = 0.5 * (xmin + xmax) + margin
  368. py = 0.5 * (ymin + ymax) + margin
  369. lenx = (xmax - xmin) + (margin * 2)
  370. leny = (ymax - ymin) + (margin * 2)
  371. proc_geometry = []
  372. if gaps == '8' or gaps == '2LR':
  373. geom = self.subtract_poly_from_geo(geom,
  374. xmin - gapsize, # botleft_x
  375. py - gapsize + leny / 4, # botleft_y
  376. xmax + gapsize, # topright_x
  377. py + gapsize + leny / 4) # topright_y
  378. geom = self.subtract_poly_from_geo(geom,
  379. xmin - gapsize,
  380. py - gapsize - leny / 4,
  381. xmax + gapsize,
  382. py + gapsize - leny / 4)
  383. if gaps == '8' or gaps == '2TB':
  384. geom = self.subtract_poly_from_geo(geom,
  385. px - gapsize + lenx / 4,
  386. ymin - gapsize,
  387. px + gapsize + lenx / 4,
  388. ymax + gapsize)
  389. geom = self.subtract_poly_from_geo(geom,
  390. px - gapsize - lenx / 4,
  391. ymin - gapsize,
  392. px + gapsize - lenx / 4,
  393. ymax + gapsize)
  394. if gaps == '4' or gaps == 'LR':
  395. geom = self.subtract_poly_from_geo(geom,
  396. xmin - gapsize,
  397. py - gapsize,
  398. xmax + gapsize,
  399. py + gapsize)
  400. if gaps == '4' or gaps == 'TB':
  401. geom = self.subtract_poly_from_geo(geom,
  402. px - gapsize,
  403. ymin - gapsize,
  404. px + gapsize,
  405. ymax + gapsize)
  406. try:
  407. for g in geom:
  408. proc_geometry.append(g)
  409. except TypeError:
  410. proc_geometry.append(geom)
  411. return proc_geometry
  412. if kind == 'single':
  413. object_geo = unary_union(object_geo)
  414. # for geo in object_geo:
  415. if isinstance(cutout_obj, FlatCAMGerber):
  416. if isinstance(object_geo, MultiPolygon):
  417. x0, y0, x1, y1 = object_geo.bounds
  418. object_geo = box(x0, y0, x1, y1)
  419. geo_buf = object_geo.buffer(margin + abs(dia / 2))
  420. geo = geo_buf.exterior
  421. else:
  422. geo = object_geo
  423. solid_geo = cutout_handler(geom=geo)
  424. else:
  425. try:
  426. __ = iter(object_geo)
  427. except TypeError:
  428. object_geo = [object_geo]
  429. for geom_struct in object_geo:
  430. if isinstance(cutout_obj, FlatCAMGerber):
  431. geom_struct = (geom_struct.buffer(margin + abs(dia / 2))).exterior
  432. solid_geo += cutout_handler(geom=geom_struct)
  433. geo_obj.solid_geometry = deepcopy(solid_geo)
  434. xmin, ymin, xmax, ymax = recursive_bounds(geo_obj.solid_geometry)
  435. geo_obj.options['xmin'] = xmin
  436. geo_obj.options['ymin'] = ymin
  437. geo_obj.options['xmax'] = xmax
  438. geo_obj.options['ymax'] = ymax
  439. geo_obj.options['cnctooldia'] = str(dia)
  440. outname = cutout_obj.options["name"] + "_cutout"
  441. self.app.new_object('geometry', outname, geo_init)
  442. cutout_obj.plot()
  443. self.app.inform.emit(_("[success] Any form CutOut operation finished."))
  444. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  445. self.app.should_we_save = True
  446. def on_rectangular_cutout(self):
  447. # def subtract_rectangle(obj_, x0, y0, x1, y1):
  448. # pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  449. # obj_.subtract_polygon(pts)
  450. name = self.obj_combo.currentText()
  451. # Get source object.
  452. try:
  453. cutout_obj = self.app.collection.get_by_name(str(name))
  454. except Exception as e:
  455. log.debug("CutOut.on_rectangular_cutout() --> %s" % str(e))
  456. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % name)
  457. return "Could not retrieve object: %s" % name
  458. if cutout_obj is None:
  459. self.app.inform.emit(_("[ERROR_NOTCL] Object not found: %s") % cutout_obj)
  460. try:
  461. dia = float(self.dia.get_value())
  462. except ValueError:
  463. # try to convert comma to decimal point. if it's still not working error message and return
  464. try:
  465. dia = float(self.dia.get_value().replace(',', '.'))
  466. except ValueError:
  467. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  468. "Add it and retry."))
  469. return
  470. if 0 in {dia}:
  471. self.app.inform.emit(_("[ERROR_NOTCL] Tool Diameter is zero value. Change it to a positive real number."))
  472. return "Tool Diameter is zero value. Change it to a positive real number."
  473. try:
  474. kind = self.obj_kind_combo.get_value()
  475. except ValueError:
  476. return
  477. try:
  478. margin = float(self.margin.get_value())
  479. except ValueError:
  480. # try to convert comma to decimal point. if it's still not working error message and return
  481. try:
  482. margin = float(self.margin.get_value().replace(',', '.'))
  483. except ValueError:
  484. self.app.inform.emit(_("[WARNING_NOTCL] Margin value is missing or wrong format. "
  485. "Add it and retry."))
  486. return
  487. try:
  488. gapsize = float(self.gapsize.get_value())
  489. except ValueError:
  490. # try to convert comma to decimal point. if it's still not working error message and return
  491. try:
  492. gapsize = float(self.gapsize.get_value().replace(',', '.'))
  493. except ValueError:
  494. self.app.inform.emit(_("[WARNING_NOTCL] Gap size value is missing or wrong format. "
  495. "Add it and retry."))
  496. return
  497. try:
  498. gaps = self.gaps.get_value()
  499. except TypeError:
  500. self.app.inform.emit(_("[WARNING_NOTCL] Number of gaps value is missing. Add it and retry."))
  501. return
  502. if gaps not in ['LR', 'TB', '2LR', '2TB', '4', '8']:
  503. self.app.inform.emit(_("[WARNING_NOTCL] Gaps value can be only one of: 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  504. "Fill in a correct value and retry. "))
  505. return
  506. if cutout_obj.multigeo is True:
  507. self.app.inform.emit(_("[ERROR]Cutout operation cannot be done on a multi-geo Geometry.\n"
  508. "Optionally, this Multi-geo Geometry can be converted to Single-geo Geometry,\n"
  509. "and after that perform Cutout."))
  510. return
  511. # Get min and max data for each object as we just cut rectangles across X or Y
  512. gapsize = gapsize / 2 + (dia / 2)
  513. def geo_init(geo_obj, app_obj):
  514. solid_geo = []
  515. object_geo = cutout_obj.solid_geometry
  516. def cutout_rect_handler(geom):
  517. proc_geometry = []
  518. px = 0.5 * (xmin + xmax) + margin
  519. py = 0.5 * (ymin + ymax) + margin
  520. lenx = (xmax - xmin) + (margin * 2)
  521. leny = (ymax - ymin) + (margin * 2)
  522. if gaps == '8' or gaps == '2LR':
  523. geom = self.subtract_poly_from_geo(geom,
  524. xmin - gapsize, # botleft_x
  525. py - gapsize + leny / 4, # botleft_y
  526. xmax + gapsize, # topright_x
  527. py + gapsize + leny / 4) # topright_y
  528. geom = self.subtract_poly_from_geo(geom,
  529. xmin - gapsize,
  530. py - gapsize - leny / 4,
  531. xmax + gapsize,
  532. py + gapsize - leny / 4)
  533. if gaps == '8' or gaps == '2TB':
  534. geom = self.subtract_poly_from_geo(geom,
  535. px - gapsize + lenx / 4,
  536. ymin - gapsize,
  537. px + gapsize + lenx / 4,
  538. ymax + gapsize)
  539. geom = self.subtract_poly_from_geo(geom,
  540. px - gapsize - lenx / 4,
  541. ymin - gapsize,
  542. px + gapsize - lenx / 4,
  543. ymax + gapsize)
  544. if gaps == '4' or gaps == 'LR':
  545. geom = self.subtract_poly_from_geo(geom,
  546. xmin - gapsize,
  547. py - gapsize,
  548. xmax + gapsize,
  549. py + gapsize)
  550. if gaps == '4' or gaps == 'TB':
  551. geom = self.subtract_poly_from_geo(geom,
  552. px - gapsize,
  553. ymin - gapsize,
  554. px + gapsize,
  555. ymax + gapsize)
  556. try:
  557. for g in geom:
  558. proc_geometry.append(g)
  559. except TypeError:
  560. proc_geometry.append(geom)
  561. return proc_geometry
  562. if kind == 'single':
  563. object_geo = unary_union(object_geo)
  564. xmin, ymin, xmax, ymax = object_geo.bounds
  565. geo = box(xmin, ymin, xmax, ymax)
  566. # if Gerber create a buffer at a distance
  567. # if Geometry then cut through the geometry
  568. if isinstance(cutout_obj, FlatCAMGerber):
  569. geo = geo.buffer(margin + abs(dia / 2))
  570. solid_geo = cutout_rect_handler(geom=geo)
  571. else:
  572. try:
  573. __ = iter(object_geo)
  574. except TypeError:
  575. object_geo = [object_geo]
  576. for geom_struct in object_geo:
  577. geom_struct = unary_union(geom_struct)
  578. xmin, ymin, xmax, ymax = geom_struct.bounds
  579. geom_struct = box(xmin, ymin, xmax, ymax)
  580. if isinstance(cutout_obj, FlatCAMGerber):
  581. geom_struct = geom_struct.buffer(margin + abs(dia / 2))
  582. solid_geo += cutout_rect_handler(geom=geom_struct)
  583. geo_obj.solid_geometry = deepcopy(solid_geo)
  584. geo_obj.options['cnctooldia'] = str(dia)
  585. outname = cutout_obj.options["name"] + "_cutout"
  586. self.app.new_object('geometry', outname, geo_init)
  587. # cutout_obj.plot()
  588. self.app.inform.emit(_("[success] Any form CutOut operation finished."))
  589. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  590. self.app.should_we_save = True
  591. def on_manual_gap_click(self):
  592. self.app.inform.emit(_("Click on the selected geometry object perimeter to create a bridge gap ..."))
  593. self.app.geo_editor.tool_shape.enabled = True
  594. try:
  595. self.cutting_dia = float(self.dia.get_value())
  596. except ValueError:
  597. # try to convert comma to decimal point. if it's still not working error message and return
  598. try:
  599. self.cutting_dia = float(self.dia.get_value().replace(',', '.'))
  600. except ValueError:
  601. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  602. "Add it and retry."))
  603. return
  604. if 0 in {self.cutting_dia}:
  605. self.app.inform.emit(_("[ERROR_NOTCL] Tool Diameter is zero value. Change it to a positive real number."))
  606. return "Tool Diameter is zero value. Change it to a positive real number."
  607. try:
  608. self.cutting_gapsize = float(self.gapsize.get_value())
  609. except ValueError:
  610. # try to convert comma to decimal point. if it's still not working error message and return
  611. try:
  612. self.cutting_gapsize = float(self.gapsize.get_value().replace(',', '.'))
  613. except ValueError:
  614. self.app.inform.emit(_("[WARNING_NOTCL] Gap size value is missing or wrong format. "
  615. "Add it and retry."))
  616. return
  617. self.app.plotcanvas.vis_disconnect('key_press', self.app.ui.keyPressEvent)
  618. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  619. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  620. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  621. self.app.plotcanvas.vis_connect('key_press', self.on_key_press)
  622. self.app.plotcanvas.vis_connect('mouse_move', self.on_mouse_move)
  623. self.app.plotcanvas.vis_connect('mouse_release', self.doit)
  624. # To be called after clicking on the plot.
  625. def doit(self, event):
  626. # do paint single only for left mouse clicks
  627. if event.button == 1:
  628. self.app.inform.emit(_("Making manual bridge gap..."))
  629. pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  630. self.on_manual_cutout(click_pos=pos)
  631. self.app.plotcanvas.vis_disconnect('key_press', self.on_key_press)
  632. self.app.plotcanvas.vis_disconnect('mouse_move', self.on_mouse_move)
  633. self.app.plotcanvas.vis_disconnect('mouse_release', self.doit)
  634. self.app.plotcanvas.vis_connect('key_press', self.app.ui.keyPressEvent)
  635. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  636. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  637. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  638. self.app.geo_editor.tool_shape.clear(update=True)
  639. self.app.geo_editor.tool_shape.enabled = False
  640. self.gapFinished.emit()
  641. def on_manual_cutout(self, click_pos):
  642. name = self.man_object_combo.currentText()
  643. # Get source object.
  644. try:
  645. cutout_obj = self.app.collection.get_by_name(str(name))
  646. except Exception as e:
  647. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  648. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve Geometry object: %s") % name)
  649. return "Could not retrieve object: %s" % name
  650. if cutout_obj is None:
  651. self.app.inform.emit(_("[ERROR_NOTCL] Geometry object for manual cutout not found: %s") % cutout_obj)
  652. return
  653. # use the snapped position as reference
  654. snapped_pos = self.app.geo_editor.snap(click_pos[0], click_pos[1])
  655. cut_poly = self.cutting_geo(pos=(snapped_pos[0], snapped_pos[1]))
  656. cutout_obj.subtract_polygon(cut_poly)
  657. cutout_obj.plot()
  658. self.app.inform.emit(_("[success] Added manual Bridge Gap."))
  659. self.app.should_we_save = True
  660. def on_gap_finished(self):
  661. # if CTRL key modifier is pressed then repeat the bridge gap cut
  662. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  663. if key_modifier == Qt.ControlModifier:
  664. self.on_manual_gap_click()
  665. def on_manual_geo(self):
  666. name = self.obj_combo.currentText()
  667. # Get source object.
  668. try:
  669. cutout_obj = self.app.collection.get_by_name(str(name))
  670. except Exception as e:
  671. log.debug("CutOut.on_manual_geo() --> %s" % str(e))
  672. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve Gerber object: %s") % name)
  673. return "Could not retrieve object: %s" % name
  674. if cutout_obj is None:
  675. self.app.inform.emit(_("[ERROR_NOTCL] There is no Gerber object selected for Cutout.\n"
  676. "Select one and try again."))
  677. return
  678. if not isinstance(cutout_obj, FlatCAMGerber):
  679. self.app.inform.emit(_("[ERROR_NOTCL] The selected object has to be of Gerber type.\n"
  680. "Select a Gerber file and try again."))
  681. return
  682. try:
  683. dia = float(self.dia.get_value())
  684. except ValueError:
  685. # try to convert comma to decimal point. if it's still not working error message and return
  686. try:
  687. dia = float(self.dia.get_value().replace(',', '.'))
  688. except ValueError:
  689. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  690. "Add it and retry."))
  691. return
  692. if 0 in {dia}:
  693. self.app.inform.emit(_("[ERROR_NOTCL] Tool Diameter is zero value. Change it to a positive real number."))
  694. return "Tool Diameter is zero value. Change it to a positive real number."
  695. try:
  696. kind = self.obj_kind_combo.get_value()
  697. except ValueError:
  698. return
  699. try:
  700. margin = float(self.margin.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. margin = float(self.margin.get_value().replace(',', '.'))
  705. except ValueError:
  706. self.app.inform.emit(_("[WARNING_NOTCL] Margin value is missing or wrong format. "
  707. "Add it and retry."))
  708. return
  709. convex_box = self.convex_box.get_value()
  710. def geo_init(geo_obj, app_obj):
  711. geo_union = unary_union(cutout_obj.solid_geometry)
  712. if convex_box:
  713. geo = geo_union.convex_hull
  714. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  715. elif kind == 'single':
  716. x0, y0, x1, y1 = geo_union.bounds
  717. geo = box(x0, y0, x1, y1)
  718. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  719. else:
  720. geo = geo_union
  721. geo = geo.buffer(margin + abs(dia / 2))
  722. if isinstance(geo, Polygon):
  723. geo_obj.solid_geometry = geo.exterior
  724. elif isinstance(geo, MultiPolygon):
  725. solid_geo = []
  726. for poly in geo:
  727. solid_geo.append(poly.exterior)
  728. geo_obj.solid_geometry = deepcopy(solid_geo)
  729. geo_obj.options['cnctooldia'] = str(dia)
  730. outname = cutout_obj.options["name"] + "_cutout"
  731. self.app.new_object('geometry', outname, geo_init)
  732. def cutting_geo(self, pos):
  733. offset = self.cutting_dia / 2 + self.cutting_gapsize / 2
  734. # cutting area definition
  735. orig_x = pos[0]
  736. orig_y = pos[1]
  737. xmin = orig_x - offset
  738. ymin = orig_y - offset
  739. xmax = orig_x + offset
  740. ymax = orig_y + offset
  741. cut_poly = box(xmin, ymin, xmax, ymax)
  742. return cut_poly
  743. def on_mouse_move(self, event):
  744. self.app.on_mouse_move_over_plot(event=event)
  745. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  746. event.xdata, event.ydata = pos[0], pos[1]
  747. try:
  748. x = float(event.xdata)
  749. y = float(event.ydata)
  750. except TypeError:
  751. return
  752. snap_x, snap_y = self.app.geo_editor.snap(x, y)
  753. geo = self.cutting_geo(pos=(snap_x, snap_y))
  754. # Remove any previous utility shape
  755. self.app.geo_editor.tool_shape.clear(update=True)
  756. self.draw_utility_geometry(geo=geo)
  757. def draw_utility_geometry(self, geo):
  758. self.app.geo_editor.tool_shape.add(
  759. shape=geo,
  760. color=(self.app.defaults["global_draw_color"] + '80'),
  761. update=False,
  762. layer=0,
  763. tolerance=None)
  764. self.app.geo_editor.tool_shape.redraw()
  765. def on_key_press(self, event):
  766. # events out of the self.app.collection view (it's about Project Tab) are of type int
  767. if type(event) is int:
  768. key = event
  769. # events from the GUI are of type QKeyEvent
  770. elif type(event) == QtGui.QKeyEvent:
  771. key = event.key()
  772. # events from Vispy are of type KeyEvent
  773. else:
  774. key = event.key
  775. # Escape = Deselect All
  776. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  777. self.app.plotcanvas.vis_disconnect('key_press', self.on_key_press)
  778. self.app.plotcanvas.vis_disconnect('mouse_move', self.on_mouse_move)
  779. self.app.plotcanvas.vis_disconnect('mouse_release', self.doit)
  780. self.app.plotcanvas.vis_connect('key_press', self.app.ui.keyPressEvent)
  781. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  782. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  783. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  784. # Remove any previous utility shape
  785. self.app.geo_editor.tool_shape.clear(update=True)
  786. self.app.geo_editor.tool_shape.enabled = False
  787. def subtract_poly_from_geo(self, solid_geo, x0, y0, x1, y1):
  788. """
  789. Subtract polygon made from points from the given object.
  790. This only operates on the paths in the original geometry,
  791. i.e. it converts polygons into paths.
  792. :param x0: x coord for lower left vertice of the polygon.
  793. :param y0: y coord for lower left vertice of the polygon.
  794. :param x1: x coord for upper right vertice of the polygon.
  795. :param y1: y coord for upper right vertice of the polygon.
  796. :param solid_geo: Geometry from which to substract. If none, use the solid_geomety property of the object
  797. :return: none
  798. """
  799. points = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  800. # pathonly should be allways True, otherwise polygons are not subtracted
  801. flat_geometry = flatten(geometry=solid_geo)
  802. log.debug("%d paths" % len(flat_geometry))
  803. polygon = Polygon(points)
  804. toolgeo = cascaded_union(polygon)
  805. diffs = []
  806. for target in flat_geometry:
  807. if type(target) == LineString or type(target) == LinearRing:
  808. diffs.append(target.difference(toolgeo))
  809. else:
  810. log.warning("Not implemented.")
  811. return unary_union(diffs)
  812. def reset_fields(self):
  813. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  814. def flatten(geometry):
  815. """
  816. Creates a list of non-iterable linear geometry objects.
  817. Polygons are expanded into its exterior and interiors.
  818. Results are placed in self.flat_geometry
  819. :param geometry: Shapely type or list or list of list of such.
  820. """
  821. flat_geo = []
  822. try:
  823. for geo in geometry:
  824. if type(geo) == Polygon:
  825. flat_geo.append(geo.exterior)
  826. for subgeo in geo.interiors:
  827. flat_geo.append(subgeo)
  828. else:
  829. flat_geo.append(geo)
  830. except TypeError:
  831. if type(geometry) == Polygon:
  832. flat_geo.append(geometry.exterior)
  833. for subgeo in geometry.interiors:
  834. flat_geo.append(subgeo)
  835. else:
  836. flat_geo.append(geometry)
  837. return flat_geo
  838. def recursive_bounds(geometry):
  839. """
  840. Returns coordinates of rectangular bounds
  841. of geometry: (xmin, ymin, xmax, ymax).
  842. """
  843. # now it can get bounds for nested lists of objects
  844. def bounds_rec(obj):
  845. try:
  846. minx = Inf
  847. miny = Inf
  848. maxx = -Inf
  849. maxy = -Inf
  850. for k in obj:
  851. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  852. minx = min(minx, minx_)
  853. miny = min(miny, miny_)
  854. maxx = max(maxx, maxx_)
  855. maxy = max(maxy, maxy_)
  856. return minx, miny, maxx, maxy
  857. except TypeError:
  858. # it's a Shapely object, return it's bounds
  859. return obj.bounds
  860. return bounds_rec(geometry)