ToolCutOut.py 48 KB

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