ToolCutOut.py 49 KB

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