ToolCutOut.py 47 KB

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