Common.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ##########################################################
  8. # ##########################################################
  9. # File Modified (major mod): Marius Adrian Stanciu #
  10. # Date: 11/4/2019 #
  11. # ##########################################################
  12. from PyQt5 import QtCore
  13. from shapely.geometry import Polygon, Point, LineString, MultiPoint
  14. from shapely.ops import unary_union
  15. from appGUI.VisPyVisuals import ShapeCollection
  16. from appTool import AppTool
  17. from copy import deepcopy
  18. import collections
  19. import traceback
  20. import numpy as np
  21. # from voronoi import Voronoi
  22. # from voronoi import Polygon as voronoi_polygon
  23. import gettext
  24. import appTranslation as fcTranslate
  25. import builtins
  26. fcTranslate.apply_language('strings')
  27. if '_' not in builtins.__dict__:
  28. _ = gettext.gettext
  29. class GracefulException(Exception):
  30. """
  31. Graceful Exception raised when the user is requesting to cancel the current threaded task
  32. """
  33. def __init__(self):
  34. super().__init__()
  35. def __str__(self):
  36. return '\n\n%s' % _("The user requested a graceful exit of the current task.")
  37. class LoudDict(dict):
  38. """
  39. A Dictionary with a callback for item changes.
  40. """
  41. def __init__(self, *args, **kwargs):
  42. dict.__init__(self, *args, **kwargs)
  43. self.callback = lambda x: None
  44. def __setitem__(self, key, value):
  45. """
  46. Overridden __setitem__ method. Will emit 'changed(QString)' if the item was changed, with key as parameter.
  47. """
  48. if key in self and self.__getitem__(key) == value:
  49. return
  50. dict.__setitem__(self, key, value)
  51. self.callback(key)
  52. def update(self, *args, **kwargs):
  53. if len(args) > 1:
  54. raise TypeError("update expected at most 1 arguments, got %d" % len(args))
  55. other = dict(*args, **kwargs)
  56. for key in other:
  57. self[key] = other[key]
  58. def set_change_callback(self, callback):
  59. """
  60. Assigns a function as callback on item change. The callback
  61. will receive the key of the object that was changed.
  62. :param callback: Function to call on item change.
  63. :type callback: func
  64. :return: None
  65. """
  66. self.callback = callback
  67. class LoudUniqueList(list, collections.MutableSequence):
  68. """
  69. A List with a callback for item changes, callback which returns the index where the items are added/modified.
  70. A List that will allow adding only items that are not in the list.
  71. """
  72. def __init__(self, arg=None):
  73. super().__init__()
  74. self.callback = lambda x: None
  75. if not arg is None:
  76. if isinstance(arg, list):
  77. self.extend(arg)
  78. else:
  79. self.extend([arg])
  80. def insert(self, i, v):
  81. if v in self:
  82. raise ValueError("One of the added items is already in the list.")
  83. self.callback(i)
  84. return super().insert(i, v)
  85. def append(self, v):
  86. if v in self:
  87. raise ValueError("One of the added items is already in the list.")
  88. l = len(self)
  89. self.callback(l)
  90. return super().append(v)
  91. def extend(self, t):
  92. for v in t:
  93. if v in self:
  94. raise ValueError("One of the added items is already in the list.")
  95. l = len(self)
  96. self.callback(l)
  97. return super().extend(t)
  98. def __add__(self, t): # This is for something like `LoudUniqueList([1, 2, 3]) + list([4, 5, 6])`...
  99. for v in t:
  100. if v in self:
  101. raise ValueError("One of the added items is already in the list.")
  102. l = len(self)
  103. self.callback(l)
  104. return super().__add__(t)
  105. def __iadd__(self, t): # This is for something like `l = LoudUniqueList(); l += [1, 2, 3]`
  106. for v in t:
  107. if v in self:
  108. raise ValueError("One of the added items is already in the list.")
  109. l = len(self)
  110. self.callback(l)
  111. return super().__iadd__(t)
  112. def __setitem__(self, i, v):
  113. try:
  114. for v1 in v:
  115. if v1 in self:
  116. raise ValueError("One of the modified items is already in the list.")
  117. except TypeError:
  118. if v in self:
  119. raise ValueError("One of the modified items is already in the list.")
  120. if not v is None:
  121. self.callback(i)
  122. return super().__setitem__(i, v)
  123. def set_callback(self, callback):
  124. """
  125. Assigns a function as callback on item change. The callback
  126. will receive the index of the object that was changed.
  127. :param callback: Function to call on item change.
  128. :type callback: func
  129. :return: None
  130. """
  131. self.callback = callback
  132. class FCSignal:
  133. """
  134. Taken from here: https://blog.abstractfactory.io/dynamic-signals-in-pyqt/
  135. """
  136. def __init__(self):
  137. self.__subscribers = []
  138. def emit(self, *args, **kwargs):
  139. for subs in self.__subscribers:
  140. subs(*args, **kwargs)
  141. def connect(self, func):
  142. self.__subscribers.append(func)
  143. def disconnect(self, func):
  144. try:
  145. self.__subscribers.remove(func)
  146. except ValueError:
  147. print('Warning: function %s not removed '
  148. 'from signal %s' % (func, self))
  149. def color_variant(hex_color, bright_factor=1):
  150. """
  151. Takes a color in HEX format #FF00FF and produces a lighter or darker variant
  152. :param hex_color: color to change
  153. :type hex_color: str
  154. :param bright_factor: factor to change the color brightness [0 ... 1]
  155. :type bright_factor: float
  156. :return: Modified color
  157. :rtype: str
  158. """
  159. if len(hex_color) != 7:
  160. print("Color is %s, but needs to be in #FF00FF format. Returning original color." % hex_color)
  161. return hex_color
  162. if bright_factor > 1.0:
  163. bright_factor = 1.0
  164. if bright_factor < 0.0:
  165. bright_factor = 0.0
  166. rgb_hex = [hex_color[x:x + 2] for x in [1, 3, 5]]
  167. new_rgb = []
  168. for hex_value in rgb_hex:
  169. # adjust each color channel and turn it into a INT suitable as argument for hex()
  170. mod_color = round(int(hex_value, 16) * bright_factor)
  171. # make sure that each color channel has two digits without the 0x prefix
  172. mod_color_hex = str(hex(mod_color)[2:]).zfill(2)
  173. new_rgb.append(mod_color_hex)
  174. return "#" + "".join([i for i in new_rgb])
  175. class ExclusionAreas(QtCore.QObject):
  176. """
  177. Functionality for adding Exclusion Areas for the Excellon and Geometry FlatCAM Objects
  178. """
  179. e_shape_modified = QtCore.pyqtSignal()
  180. def __init__(self, app):
  181. super().__init__()
  182. self.app = app
  183. self.app.log.debug("+ Adding Exclusion Areas")
  184. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  185. # VisPy visuals
  186. if self.app.is_legacy is False:
  187. try:
  188. self.exclusion_shapes = ShapeCollection(parent=self.app.plotcanvas.view.scene, layers=1)
  189. except AttributeError:
  190. self.exclusion_shapes = None
  191. else:
  192. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  193. self.exclusion_shapes = ShapeCollectionLegacy(obj=self, app=self.app, name="exclusion")
  194. # Event signals disconnect id holders
  195. self.mr = None
  196. self.mm = None
  197. self.kp = None
  198. # variables to be used in area exclusion
  199. self.cursor_pos = (0, 0)
  200. self.first_click = False
  201. self.points = []
  202. self.poly_drawn = False
  203. '''
  204. Here we store the exclusion shapes and some other information's
  205. Each list element is a dictionary with the format:
  206. {
  207. "obj_type": string ("excellon" or "geometry") <- self.obj_type
  208. "shape": Shapely polygon
  209. "strategy": string ("over" or "around") <- self.strategy_button
  210. "overz": float <- self.over_z_button
  211. }
  212. '''
  213. self.exclusion_areas_storage = []
  214. self.mouse_is_dragging = False
  215. self.solid_geometry = []
  216. self.obj_type = None
  217. self.shape_type_button = None
  218. self.over_z_button = None
  219. self.strategy_button = None
  220. self.cnc_button = None
  221. def on_add_area_click(self, shape_button, overz_button, strategy_radio, cnc_button, solid_geo, obj_type):
  222. """
  223. :param shape_button: a FCButton that has the value for the shape
  224. :param overz_button: a FCDoubleSpinner that holds the Over Z value
  225. :param strategy_radio: a RadioSet button with the strategy_button value
  226. :param cnc_button: a FCButton in Object UI that when clicked the CNCJob is created
  227. We have a reference here so we can change the color signifying that exclusion areas are
  228. available.
  229. :param solid_geo: reference to the object solid geometry for which we add exclusion areas
  230. :param obj_type: Type of FlatCAM object that called this method. String: "excellon" or "geometry"
  231. :type obj_type: str
  232. :return: None
  233. """
  234. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the start point of the area."))
  235. self.app.call_source = 'geometry'
  236. self.shape_type_button = shape_button
  237. self.over_z_button = overz_button
  238. self.strategy_button = strategy_radio
  239. self.cnc_button = cnc_button
  240. self.solid_geometry = solid_geo
  241. self.obj_type = obj_type
  242. if self.app.is_legacy is False:
  243. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  244. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  245. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  246. else:
  247. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  248. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  249. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  250. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  251. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  252. # self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  253. # To be called after clicking on the plot.
  254. def on_mouse_release(self, event):
  255. """
  256. Called on mouse click release.
  257. :param event: Mouse event
  258. :type event:
  259. :return: None
  260. :rtype:
  261. """
  262. if self.app.is_legacy is False:
  263. event_pos = event.pos
  264. # event_is_dragging = event.is_dragging
  265. right_button = 2
  266. else:
  267. event_pos = (event.xdata, event.ydata)
  268. # event_is_dragging = self.app.plotcanvas.is_dragging
  269. right_button = 3
  270. event_pos = self.app.plotcanvas.translate_coords(event_pos)
  271. if self.app.grid_status():
  272. curr_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  273. else:
  274. curr_pos = (event_pos[0], event_pos[1])
  275. x1, y1 = curr_pos[0], curr_pos[1]
  276. # shape_type_button = self.ui.area_shape_radio.get_value()
  277. # do clear area only for left mouse clicks
  278. if event.button == 1:
  279. if self.shape_type_button.get_value() == "square":
  280. if self.first_click is False:
  281. self.first_click = True
  282. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Click the end point of the area."))
  283. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  284. if self.app.grid_status():
  285. self.cursor_pos = self.app.geo_editor.snap(event_pos[0], event_pos[1])
  286. else:
  287. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  288. self.app.delete_selection_shape()
  289. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  290. pt1 = (x0, y0)
  291. pt2 = (x1, y0)
  292. pt3 = (x1, y1)
  293. pt4 = (x0, y1)
  294. new_rectangle = Polygon([pt1, pt2, pt3, pt4])
  295. # {
  296. # "obj_type": string("excellon" or "geometry") < - self.obj_type
  297. # "shape": Shapely polygon
  298. # "strategy_button": string("over" or "around") < - self.strategy_button
  299. # "overz": float < - self.over_z_button
  300. # }
  301. new_el = {
  302. "obj_type": self.obj_type,
  303. "shape": new_rectangle,
  304. "strategy": self.strategy_button.get_value(),
  305. "overz": self.over_z_button.get_value()
  306. }
  307. self.exclusion_areas_storage.append(new_el)
  308. if self.obj_type == 'excellon':
  309. color = "#FF7400"
  310. face_color = "#FF7400BF"
  311. else:
  312. color = "#098a8f"
  313. face_color = "#FF7400BF"
  314. # add a temporary shape on canvas
  315. AppTool.draw_tool_selection_shape(
  316. self, old_coords=(x0, y0), coords=(x1, y1),
  317. color=color,
  318. face_color=face_color,
  319. shapes_storage=self.exclusion_shapes)
  320. self.first_click = False
  321. return
  322. else:
  323. self.points.append((x1, y1))
  324. if len(self.points) > 1:
  325. self.poly_drawn = True
  326. self.app.inform.emit(_("Click on next Point or click right mouse button to complete ..."))
  327. return ""
  328. elif event.button == right_button and self.mouse_is_dragging is False:
  329. shape_type = self.shape_type_button.get_value()
  330. if shape_type == "square":
  331. self.first_click = False
  332. else:
  333. # if we finish to add a polygon
  334. if self.poly_drawn is True:
  335. try:
  336. # try to add the point where we last clicked if it is not already in the self.points
  337. last_pt = (x1, y1)
  338. if last_pt != self.points[-1]:
  339. self.points.append(last_pt)
  340. except IndexError:
  341. pass
  342. # we need to add a Polygon and a Polygon can be made only from at least 3 points
  343. if len(self.points) > 2:
  344. AppTool.delete_moving_selection_shape(self)
  345. pol = Polygon(self.points)
  346. # do not add invalid polygons even if they are drawn by utility geometry
  347. if pol.is_valid:
  348. """
  349. {
  350. "obj_type": string("excellon" or "geometry") < - self.obj_type
  351. "shape": Shapely polygon
  352. "strategy": string("over" or "around") < - self.strategy_button
  353. "overz": float < - self.over_z_button
  354. }
  355. """
  356. new_el = {
  357. "obj_type": self.obj_type,
  358. "shape": pol,
  359. "strategy": self.strategy_button.get_value(),
  360. "overz": self.over_z_button.get_value()
  361. }
  362. self.exclusion_areas_storage.append(new_el)
  363. if self.obj_type == 'excellon':
  364. color = "#FF7400"
  365. face_color = "#FF7400BF"
  366. else:
  367. color = "#098a8f"
  368. face_color = "#FF7400BF"
  369. AppTool.draw_selection_shape_polygon(
  370. self, points=self.points,
  371. color=color,
  372. face_color=face_color,
  373. shapes_storage=self.exclusion_shapes)
  374. self.app.inform.emit(
  375. _("Zone added. Click to start adding next zone or right click to finish."))
  376. self.points = []
  377. self.poly_drawn = False
  378. return
  379. # AppTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes)
  380. if self.app.is_legacy is False:
  381. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  382. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  383. # self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  384. else:
  385. self.app.plotcanvas.graph_event_disconnect(self.mr)
  386. self.app.plotcanvas.graph_event_disconnect(self.mm)
  387. # self.app.plotcanvas.graph_event_disconnect(self.kp)
  388. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  389. self.app.on_mouse_click_over_plot)
  390. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  391. self.app.on_mouse_move_over_plot)
  392. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  393. self.app.on_mouse_click_release_over_plot)
  394. self.app.call_source = 'app'
  395. if len(self.exclusion_areas_storage) == 0:
  396. return
  397. # since the exclusion areas should apply to all objects in the app collection, this check is limited to
  398. # only the current object therefore it will not guarantee success
  399. self.app.inform.emit("%s" % _("Exclusion areas added. Checking overlap with the object geometry ..."))
  400. for el in self.exclusion_areas_storage:
  401. if el["shape"].intersects(unary_union(self.solid_geometry)):
  402. self.on_clear_area_click()
  403. self.app.inform.emit(
  404. "[ERROR_NOTCL] %s" % _("Failed. Exclusion areas intersects the object geometry ..."))
  405. return
  406. self.app.inform.emit("[success] %s" % _("Exclusion areas added."))
  407. self.cnc_button.setStyleSheet("""
  408. QPushButton
  409. {
  410. font-weight: bold;
  411. color: orange;
  412. }
  413. """)
  414. self.cnc_button.setToolTip(
  415. '%s %s' % (_("Generate the CNC Job object."), _("With Exclusion areas."))
  416. )
  417. self.e_shape_modified.emit()
  418. def area_disconnect(self):
  419. """
  420. Will do the cleanup. Will disconnect the mouse events for the custom handlers in this class and initialize
  421. certain class attributes.
  422. :return: None
  423. :rtype:
  424. """
  425. if self.app.is_legacy is False:
  426. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  427. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  428. else:
  429. self.app.plotcanvas.graph_event_disconnect(self.mr)
  430. self.app.plotcanvas.graph_event_disconnect(self.mm)
  431. self.app.plotcanvas.graph_event_disconnect(self.kp)
  432. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  433. self.app.on_mouse_click_over_plot)
  434. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  435. self.app.on_mouse_move_over_plot)
  436. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  437. self.app.on_mouse_click_release_over_plot)
  438. self.points = []
  439. self.poly_drawn = False
  440. self.exclusion_areas_storage = []
  441. AppTool.delete_moving_selection_shape(self)
  442. # AppTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes)
  443. self.app.call_source = "app"
  444. self.app.inform.emit("[WARNING_NOTCL] %s" % _("Cancelled. Area exclusion drawing was interrupted."))
  445. def on_mouse_move(self, event):
  446. """
  447. Called on mouse move
  448. :param event: mouse event
  449. :type event:
  450. :return: None
  451. :rtype:
  452. """
  453. shape_type = self.shape_type_button.get_value()
  454. if self.app.is_legacy is False:
  455. event_pos = event.pos
  456. event_is_dragging = event.is_dragging
  457. # right_button = 2
  458. else:
  459. event_pos = (event.xdata, event.ydata)
  460. event_is_dragging = self.app.plotcanvas.is_dragging
  461. # right_button = 3
  462. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  463. # detect mouse dragging motion
  464. if event_is_dragging is True:
  465. self.mouse_is_dragging = True
  466. else:
  467. self.mouse_is_dragging = False
  468. # update the cursor position
  469. if self.app.grid_status():
  470. # Update cursor
  471. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  472. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  473. symbol='++', edge_color=self.app.cursor_color_3D,
  474. edge_width=self.app.defaults["global_cursor_width"],
  475. size=self.app.defaults["global_cursor_size"])
  476. # update the positions on status bar
  477. if self.cursor_pos is None:
  478. self.cursor_pos = (0, 0)
  479. self.app.dx = curr_pos[0] - float(self.cursor_pos[0])
  480. self.app.dy = curr_pos[1] - float(self.cursor_pos[1])
  481. self.app.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  482. "<b>Y</b>: %.4f&nbsp;" % (curr_pos[0], curr_pos[1]))
  483. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  484. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.app.dx, self.app.dy))
  485. units = self.app.defaults["units"].lower()
  486. self.app.plotcanvas.text_hud.text = \
  487. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  488. self.app.dx, units, self.app.dy, units, curr_pos[0], units, curr_pos[1], units)
  489. if self.obj_type == 'excellon':
  490. color = "#FF7400"
  491. face_color = "#FF7400BF"
  492. else:
  493. color = "#098a8f"
  494. face_color = "#FF7400BF"
  495. # draw the utility geometry
  496. if shape_type == "square":
  497. if self.first_click:
  498. self.app.delete_selection_shape()
  499. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  500. color=color,
  501. face_color=face_color,
  502. coords=(curr_pos[0], curr_pos[1]))
  503. else:
  504. AppTool.delete_moving_selection_shape(self)
  505. AppTool.draw_moving_selection_shape_poly(
  506. self, points=self.points,
  507. color=color,
  508. face_color=face_color,
  509. data=(curr_pos[0], curr_pos[1]))
  510. def on_clear_area_click(self):
  511. """
  512. Slot for clicking the button for Deleting all the Exclusion areas.
  513. :return: None
  514. :rtype:
  515. """
  516. self.clear_shapes()
  517. # restore the default StyleSheet
  518. self.cnc_button.setStyleSheet("")
  519. # update the StyleSheet
  520. self.cnc_button.setStyleSheet("""
  521. QPushButton
  522. {
  523. font-weight: bold;
  524. }
  525. """)
  526. self.cnc_button.setToolTip('%s' % _("Generate the CNC Job object."))
  527. def clear_shapes(self):
  528. """
  529. Will delete all the Exclusion areas; will delete on canvas any possible selection box for the Exclusion areas.
  530. :return: None
  531. :rtype:
  532. """
  533. if self.exclusion_areas_storage:
  534. self.app.inform.emit('%s' % _("All exclusion zones deleted."))
  535. self.exclusion_areas_storage.clear()
  536. AppTool.delete_moving_selection_shape(self)
  537. self.app.delete_selection_shape()
  538. AppTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes)
  539. def delete_sel_shapes(self, idxs):
  540. """
  541. :param idxs: list of indexes in self.exclusion_areas_storage list to be deleted
  542. :type idxs: list
  543. :return: None
  544. """
  545. # delete all plotted shapes
  546. AppTool.delete_tool_selection_shape(self, shapes_storage=self.exclusion_shapes)
  547. # delete shapes
  548. for idx in sorted(idxs, reverse=True):
  549. del self.exclusion_areas_storage[idx]
  550. # re-add what's left after deletion in first step
  551. if self.obj_type == 'excellon':
  552. color = "#FF7400"
  553. face_color = "#FF7400BF"
  554. else:
  555. color = "#098a8f"
  556. face_color = "#FF7400BF"
  557. face_alpha = 0.3
  558. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  559. for geo_el in self.exclusion_areas_storage:
  560. if isinstance(geo_el['shape'], Polygon):
  561. self.exclusion_shapes.add(
  562. geo_el['shape'], color=color, face_color=color_t, update=True, layer=0, tolerance=None)
  563. if self.app.is_legacy is True:
  564. self.exclusion_shapes.redraw()
  565. # if there are still some exclusion areas in the storage
  566. if self.exclusion_areas_storage:
  567. self.app.inform.emit('[success] %s' % _("Selected exclusion zones deleted."))
  568. else:
  569. # restore the default StyleSheet
  570. self.cnc_button.setStyleSheet("")
  571. # update the StyleSheet
  572. self.cnc_button.setStyleSheet("""
  573. QPushButton
  574. {
  575. font-weight: bold;
  576. }
  577. """)
  578. self.cnc_button.setToolTip('%s' % _("Generate the CNC Job object."))
  579. # there are no more exclusion areas in the storage, all have been selected and deleted
  580. self.app.inform.emit('%s' % _("All exclusion zones deleted."))
  581. def travel_coordinates(self, start_point, end_point, tooldia):
  582. """
  583. WIll create a path the go around the exclusion areas on the shortest path when travelling (at a Z above the
  584. material).
  585. :param start_point: X,Y coordinates for the start point of the travel line
  586. :type start_point: tuple
  587. :param end_point: X,Y coordinates for the destination point of the travel line
  588. :type end_point: tuple
  589. :param tooldia: THe tool diameter used and which generates the travel lines
  590. :type tooldia float
  591. :return: A list of x,y tuples that describe the avoiding path
  592. :rtype: list
  593. """
  594. ret_list = []
  595. # Travel lines: rapids. Should not pass through Exclusion areas
  596. travel_line = LineString([start_point, end_point])
  597. origin_point = Point(start_point)
  598. buffered_storage = []
  599. # add a little something to the half diameter, to make sure that we really don't enter in the exclusion zones
  600. buffered_distance = (tooldia / 2.0) + (0.1 if self.app.defaults['units'] == 'MM' else 0.00393701)
  601. for area in self.exclusion_areas_storage:
  602. new_area = deepcopy(area)
  603. new_area['shape'] = area['shape'].buffer(buffered_distance, join_style=2)
  604. buffered_storage.append(new_area)
  605. # sort the Exclusion areas from the closest to the start_point to the farthest
  606. tmp = []
  607. for area in buffered_storage:
  608. dist = Point(start_point).distance(area['shape'])
  609. tmp.append((dist, area))
  610. tmp.sort(key=lambda k: k[0])
  611. sorted_area_storage = [k[1] for k in tmp]
  612. # process the ordered exclusion areas list
  613. for area in sorted_area_storage:
  614. outline = area['shape'].exterior
  615. if travel_line.intersects(outline):
  616. intersection_pts = travel_line.intersection(outline)
  617. if isinstance(intersection_pts, Point):
  618. # it's just a touch, continue
  619. continue
  620. entry_pt = nearest_point(origin_point, intersection_pts)
  621. exit_pt = farthest_point(origin_point, intersection_pts)
  622. if area['strategy'] == 'around':
  623. full_vertex_points = [Point(x) for x in list(outline.coords)]
  624. # the last coordinate in outline, a LinearRing, is the closing one
  625. # therefore a duplicate of the first one; discard it
  626. vertex_points = full_vertex_points[:-1]
  627. # dist_from_entry = [(entry_pt.distance(vt), vertex_points.index(vt)) for vt in vertex_points]
  628. # closest_point_entry = nsmallest(1, dist_from_entry, key=lambda x: x[0])
  629. # start_idx = closest_point_entry[0][1]
  630. #
  631. # dist_from_exit = [(exit_pt.distance(vt), vertex_points.index(vt)) for vt in vertex_points]
  632. # closest_point_exit = nsmallest(1, dist_from_exit, key=lambda x: x[0])
  633. # end_idx = closest_point_exit[0][1]
  634. # pts_line_entry = None
  635. # pts_line_exit = None
  636. # for i in range(len(full_vertex_points)):
  637. # try:
  638. # line = LineString(
  639. # [
  640. # (full_vertex_points[i].x, full_vertex_points[i].y),
  641. # (full_vertex_points[i + 1].x, full_vertex_points[i + 1].y)
  642. # ]
  643. # )
  644. # except IndexError:
  645. # continue
  646. #
  647. # if entry_pt.within(line) or entry_pt.equals(Point(line.coords[0])) or \
  648. # entry_pt.equals(Point(line.coords[1])):
  649. # pts_line_entry = [Point(x) for x in line.coords]
  650. #
  651. # if exit_pt.within(line) or exit_pt.equals(Point(line.coords[0])) or \
  652. # exit_pt.equals(Point(line.coords[1])):
  653. # pts_line_exit = [Point(x) for x in line.coords]
  654. #
  655. # closest_point_entry = nearest_point(entry_pt, pts_line_entry)
  656. # start_idx = vertex_points.index(closest_point_entry)
  657. #
  658. # closest_point_exit = nearest_point(exit_pt, pts_line_exit)
  659. # end_idx = vertex_points.index(closest_point_exit)
  660. # find all vertexes for which a line from start_point does not cross the Exclusion area polygon
  661. # the same for end_point
  662. # we don't need closest points for which the path leads to crosses of the Exclusion area
  663. close_start_points = []
  664. close_end_points = []
  665. for i in range(len(vertex_points)):
  666. try:
  667. start_line = LineString(
  668. [
  669. start_point,
  670. (vertex_points[i].x, vertex_points[i].y)
  671. ]
  672. )
  673. end_line = LineString(
  674. [
  675. end_point,
  676. (vertex_points[i].x, vertex_points[i].y)
  677. ]
  678. )
  679. except IndexError:
  680. continue
  681. if not start_line.crosses(area['shape']):
  682. close_start_points.append(vertex_points[i])
  683. if not end_line.crosses(area['shape']):
  684. close_end_points.append(vertex_points[i])
  685. closest_point_entry = nearest_point(entry_pt, close_start_points)
  686. closest_point_exit = nearest_point(exit_pt, close_end_points)
  687. start_idx = vertex_points.index(closest_point_entry)
  688. end_idx = vertex_points.index(closest_point_exit)
  689. # calculate possible paths: one clockwise the other counterclockwise on the exterior of the
  690. # exclusion area outline (Polygon.exterior)
  691. vp_len = len(vertex_points)
  692. if end_idx > start_idx:
  693. path_1 = vertex_points[start_idx:(end_idx + 1)]
  694. path_2 = [vertex_points[start_idx]]
  695. idx = start_idx
  696. for __ in range(vp_len):
  697. idx = idx - 1 if idx > 0 else (vp_len - 1)
  698. path_2.append(vertex_points[idx])
  699. if idx == end_idx:
  700. break
  701. else:
  702. path_1 = vertex_points[end_idx:(start_idx + 1)]
  703. path_2 = [vertex_points[end_idx]]
  704. idx = end_idx
  705. for __ in range(vp_len):
  706. idx = idx - 1 if idx > 0 else (vp_len - 1)
  707. path_2.append(vertex_points[idx])
  708. if idx == start_idx:
  709. break
  710. path_1.reverse()
  711. path_2.reverse()
  712. # choose the one with the lesser length
  713. length_path_1 = 0
  714. for i in range(len(path_1)):
  715. try:
  716. length_path_1 += path_1[i].distance(path_1[i + 1])
  717. except IndexError:
  718. pass
  719. length_path_2 = 0
  720. for i in range(len(path_2)):
  721. try:
  722. length_path_2 += path_2[i].distance(path_2[i + 1])
  723. except IndexError:
  724. pass
  725. path = path_1 if length_path_1 < length_path_2 else path_2
  726. # transform the list of Points into a list of Points coordinates
  727. path_coords = [[None, (p.x, p.y)] for p in path]
  728. ret_list += path_coords
  729. else:
  730. path_coords = [[float(area['overz']), (entry_pt.x, entry_pt.y)], [None, (exit_pt.x, exit_pt.y)]]
  731. ret_list += path_coords
  732. # create a new LineString to test again for possible other Exclusion zones
  733. last_pt_in_path = path_coords[-1][1]
  734. travel_line = LineString([last_pt_in_path, end_point])
  735. ret_list.append([None, end_point])
  736. return ret_list
  737. def farthest_point(origin, points_list):
  738. """
  739. Calculate the farthest Point in a list from another Point
  740. :param origin: Reference Point
  741. :type origin: Point
  742. :param points_list: List of Points or a MultiPoint
  743. :type points_list: list
  744. :return: Farthest Point
  745. :rtype: Point
  746. """
  747. old_dist = 0
  748. fartherst_pt = None
  749. for pt in points_list:
  750. dist = abs(origin.distance(pt))
  751. if dist >= old_dist:
  752. fartherst_pt = pt
  753. old_dist = dist
  754. return fartherst_pt
  755. # def voronoi_diagram(geom, envelope, edges=False):
  756. # """
  757. #
  758. # :param geom: a collection of Shapely Points from which to build the Voronoi diagram
  759. # :type geom: MultiPoint
  760. # :param envelope: a bounding box to constrain the diagram (Shapely Polygon)
  761. # :type envelope: Polygon
  762. # :param edges: If False, return regions as polygons. Else, return only
  763. # edges e.g. LineStrings.
  764. # :type edges: bool, False
  765. # :return:
  766. # :rtype:
  767. # """
  768. #
  769. # if not isinstance(geom, MultiPoint):
  770. # return False
  771. #
  772. # coords = list(envelope.exterior.coords)
  773. # v_poly = voronoi_polygon(coords)
  774. #
  775. # vp = Voronoi(v_poly)
  776. #
  777. # points = []
  778. # for pt in geom:
  779. # points.append((pt.x, pt.y))
  780. # vp.create_diagram(points=points, vis_steps=False, verbose=False, vis_result=False, vis_tree=False)
  781. #
  782. # if edges is True:
  783. # return vp.edges
  784. # else:
  785. # voronoi_polygons = []
  786. # for pt in vp.points:
  787. # try:
  788. # poly_coords = list(pt.get_coordinates())
  789. # new_poly_coords = []
  790. # for coord in poly_coords:
  791. # new_poly_coords.append((coord.x, coord.y))
  792. #
  793. # voronoi_polygons.append(Polygon(new_poly_coords))
  794. # except Exception:
  795. # print(traceback.format_exc())
  796. #
  797. # return voronoi_polygons
  798. def nearest_point(origin, points_list):
  799. """
  800. Calculate the nearest Point in a list from another Point
  801. :param origin: Reference Point
  802. :type origin: Point
  803. :param points_list: List of Points or a MultiPoint
  804. :type points_list: list
  805. :return: Nearest Point
  806. :rtype: Point
  807. """
  808. old_dist = np.Inf
  809. nearest_pt = None
  810. for pt in points_list:
  811. dist = abs(origin.distance(pt))
  812. if dist <= old_dist:
  813. nearest_pt = pt
  814. old_dist = dist
  815. return nearest_pt