Common.py 33 KB

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