ToolCutOut.py 47 KB

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