PlotCanvas.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. # ########################################################## ##
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://caram.cl/software/flatcam #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ########################################################## ##
  8. from PyQt5 import QtCore
  9. import logging
  10. from flatcamGUI.VisPyCanvas import VisPyCanvas, time
  11. from flatcamGUI.VisPyVisuals import ShapeGroup, ShapeCollection, TextCollection, TextGroup, Cursor
  12. from vispy.scene.visuals import InfiniteLine, Line
  13. import numpy as np
  14. from vispy.geometry import Rect
  15. log = logging.getLogger('base')
  16. class PlotCanvas(QtCore.QObject, VisPyCanvas):
  17. """
  18. Class handling the plotting area in the application.
  19. """
  20. def __init__(self, container, fcapp):
  21. """
  22. The constructor configures the VisPy figure that
  23. will contain all plots, creates the base axes and connects
  24. events to the plotting area.
  25. :param container: The parent container in which to draw plots.
  26. :rtype: PlotCanvas
  27. """
  28. super(PlotCanvas, self).__init__()
  29. # VisPyCanvas.__init__(self)
  30. # VisPyCanvas does not allow new attributes. Override.
  31. self.unfreeze()
  32. self.fcapp = fcapp
  33. # Parent container
  34. self.container = container
  35. # workspace lines; I didn't use the rectangle because I didn't want to add another VisPy Node,
  36. # which might decrease performance
  37. self.b_line, self.r_line, self.t_line, self.l_line = None, None, None, None
  38. # <VisPyCanvas>
  39. self.create_native()
  40. self.native.setParent(self.fcapp.ui)
  41. # <QtCore.QObject>
  42. self.container.addWidget(self.native)
  43. # ## AXIS # ##
  44. self.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  45. parent=self.view.scene)
  46. self.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  47. parent=self.view.scene)
  48. # draw a rectangle made out of 4 lines on the canvas to serve as a hint for the work area
  49. # all CNC have a limited workspace
  50. self.draw_workspace()
  51. self.line_parent = None
  52. self.line_color = (0.3, 0.0, 0.0, 1.0)
  53. self.cursor_v_line = InfiniteLine(pos=None, color=self.line_color, vertical=True,
  54. parent=self.line_parent)
  55. self.cursor_h_line = InfiniteLine(pos=None, color=self.line_color, vertical=False,
  56. parent=self.line_parent)
  57. # if self.app.defaults['global_workspace'] is True:
  58. # if self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  59. # self.wkspace_t = Line(pos=)
  60. self.shape_collections = []
  61. self.shape_collection = self.new_shape_collection()
  62. self.fcapp.pool_recreated.connect(self.on_pool_recreated)
  63. self.text_collection = self.new_text_collection()
  64. # TODO: Should be setting to show/hide CNC job annotations (global or per object)
  65. self.text_collection.enabled = True
  66. self.c = None
  67. self.big_cursor = None
  68. # Keep VisPy canvas happy by letting it be "frozen" again.
  69. self.freeze()
  70. # draw a rectangle made out of 4 lines on the canvas to serve as a hint for the work area
  71. # all CNC have a limited workspace
  72. def draw_workspace(self):
  73. a = np.empty((0, 0))
  74. a4p_in = np.array([(0, 0), (8.3, 0), (8.3, 11.7), (0, 11.7)])
  75. a4l_in = np.array([(0, 0), (11.7, 0), (11.7, 8.3), (0, 8.3)])
  76. a3p_in = np.array([(0, 0), (11.7, 0), (11.7, 16.5), (0, 16.5)])
  77. a3l_in = np.array([(0, 0), (16.5, 0), (16.5, 11.7), (0, 11.7)])
  78. a4p_mm = np.array([(0, 0), (210, 0), (210, 297), (0, 297)])
  79. a4l_mm = np.array([(0, 0), (297, 0), (297, 210), (0, 210)])
  80. a3p_mm = np.array([(0, 0), (297, 0), (297, 420), (0, 420)])
  81. a3l_mm = np.array([(0, 0), (420, 0), (420, 297), (0, 297)])
  82. if self.fcapp.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  83. if self.fcapp.defaults['global_workspaceT'] == 'A4P':
  84. a = a4p_mm
  85. elif self.fcapp.defaults['global_workspaceT'] == 'A4L':
  86. a = a4l_mm
  87. elif self.fcapp.defaults['global_workspaceT'] == 'A3P':
  88. a = a3p_mm
  89. elif self.fcapp.defaults['global_workspaceT'] == 'A3L':
  90. a = a3l_mm
  91. else:
  92. if self.fcapp.defaults['global_workspaceT'] == 'A4P':
  93. a = a4p_in
  94. elif self.fcapp.defaults['global_workspaceT'] == 'A4L':
  95. a = a4l_in
  96. elif self.fcapp.defaults['global_workspaceT'] == 'A3P':
  97. a = a3p_in
  98. elif self.fcapp.defaults['global_workspaceT'] == 'A3L':
  99. a = a3l_in
  100. self.delete_workspace()
  101. self.b_line = Line(pos=a[0:2], color=(0.70, 0.3, 0.3, 1.0),
  102. antialias=True, method='agg', parent=self.view.scene)
  103. self.r_line = Line(pos=a[1:3], color=(0.70, 0.3, 0.3, 1.0),
  104. antialias=True, method='agg', parent=self.view.scene)
  105. self.t_line = Line(pos=a[2:4], color=(0.70, 0.3, 0.3, 1.0),
  106. antialias=True, method='agg', parent=self.view.scene)
  107. self.l_line = Line(pos=np.array((a[0], a[3])), color=(0.70, 0.3, 0.3, 1.0),
  108. antialias=True, method='agg', parent=self.view.scene)
  109. if self.fcapp.defaults['global_workspace'] is False:
  110. self.delete_workspace()
  111. # delete the workspace lines from the plot by removing the parent
  112. def delete_workspace(self):
  113. try:
  114. self.b_line.parent = None
  115. self.r_line.parent = None
  116. self.t_line.parent = None
  117. self.l_line.parent = None
  118. except Exception as e:
  119. pass
  120. # redraw the workspace lines on the plot by readding them to the parent view.scene
  121. def restore_workspace(self):
  122. try:
  123. self.b_line.parent = self.view.scene
  124. self.r_line.parent = self.view.scene
  125. self.t_line.parent = self.view.scene
  126. self.l_line.parent = self.view.scene
  127. except Exception as e:
  128. pass
  129. def graph_event_connect(self, event_name, callback):
  130. return getattr(self.events, event_name).connect(callback)
  131. def graph_event_disconnect(self, event_name, callback=None):
  132. if callback is None:
  133. getattr(self.events, event_name).disconnect()
  134. else:
  135. getattr(self.events, event_name).disconnect(callback)
  136. def zoom(self, factor, center=None):
  137. """
  138. Zooms the plot by factor around a given
  139. center point. Takes care of re-drawing.
  140. :param factor: Number by which to scale the plot.
  141. :type factor: float
  142. :param center: Coordinates [x, y] of the point around which to scale the plot.
  143. :type center: list
  144. :return: None
  145. """
  146. self.view.camera.zoom(factor, center)
  147. def new_shape_group(self, shape_collection=None):
  148. if shape_collection:
  149. return ShapeGroup(shape_collection)
  150. return ShapeGroup(self.shape_collection)
  151. def new_shape_collection(self, **kwargs):
  152. # sc = ShapeCollection(parent=self.view.scene, pool=self.app.pool, **kwargs)
  153. # self.shape_collections.append(sc)
  154. # return sc
  155. return ShapeCollection(parent=self.view.scene, pool=self.fcapp.pool, **kwargs)
  156. def new_cursor(self, big=None):
  157. """
  158. Will create a mouse cursor pointer on canvas
  159. :param big: if True will create a mouse cursor made out of infinite lines
  160. :return: the mouse cursor object
  161. """
  162. if big is True:
  163. self.big_cursor = True
  164. self.c = CursorBig()
  165. # in case there are multiple new_cursor calls, best to disconnect first the signals
  166. try:
  167. self.c.mouse_state_updated.disconnect(self.on_mouse_state)
  168. except (TypeError, AttributeError):
  169. pass
  170. try:
  171. self.c.mouse_position_updated.disconnect(self.on_mouse_position)
  172. except (TypeError, AttributeError):
  173. pass
  174. self.c.mouse_state_updated.connect(self.on_mouse_state)
  175. self.c.mouse_position_updated.connect(self.on_mouse_position)
  176. else:
  177. self.big_cursor = False
  178. self.c = Cursor(pos=np.empty((0, 2)), parent=self.view.scene)
  179. self.c.antialias = 0
  180. return self.c
  181. def on_mouse_state(self, state):
  182. if state:
  183. self.cursor_h_line.parent = self.view.scene
  184. self.cursor_v_line.parent = self.view.scene
  185. else:
  186. self.cursor_h_line.parent = None
  187. self.cursor_v_line.parent = None
  188. def on_mouse_position(self, pos):
  189. # self.line_color = color
  190. self.cursor_h_line.set_data(pos=pos[1], color=self.line_color)
  191. self.cursor_v_line.set_data(pos=pos[0], color=self.line_color)
  192. self.view.scene.update()
  193. def new_text_group(self, collection=None):
  194. if collection:
  195. return TextGroup(collection)
  196. else:
  197. return TextGroup(self.text_collection)
  198. def new_text_collection(self, **kwargs):
  199. return TextCollection(parent=self.view.scene, **kwargs)
  200. def fit_view(self, rect=None):
  201. # Lock updates in other threads
  202. self.shape_collection.lock_updates()
  203. if not rect:
  204. rect = Rect(-1, -1, 20, 20)
  205. try:
  206. rect.left, rect.right = self.shape_collection.bounds(axis=0)
  207. rect.bottom, rect.top = self.shape_collection.bounds(axis=1)
  208. except TypeError:
  209. pass
  210. # adjust the view camera to be slightly bigger than the bounds so the shape colleaction can be seen clearly
  211. # otherwise the shape collection boundary will have no border
  212. rect.left *= 0.96
  213. rect.bottom *= 0.96
  214. rect.right *= 1.01
  215. rect.top *= 1.01
  216. self.view.camera.rect = rect
  217. self.shape_collection.unlock_updates()
  218. def fit_center(self, loc, rect=None):
  219. # Lock updates in other threads
  220. self.shape_collection.lock_updates()
  221. if not rect:
  222. try:
  223. rect = Rect(loc[0]-20, loc[1]-20, 40, 40)
  224. except TypeError:
  225. pass
  226. self.view.camera.rect = rect
  227. self.shape_collection.unlock_updates()
  228. def clear(self):
  229. pass
  230. def redraw(self):
  231. self.shape_collection.redraw([])
  232. self.text_collection.redraw()
  233. def on_pool_recreated(self, pool):
  234. self.shape_collection.pool = pool
  235. class CursorBig(QtCore.QObject):
  236. """
  237. This is a fake cursor to ensure compatibility with the OpenGL engine (VisPy).
  238. This way I don't have to chane (disable) things related to the cursor all over when
  239. using the low performance Matplotlib 2D graphic engine.
  240. """
  241. mouse_state_updated = QtCore.pyqtSignal(bool)
  242. mouse_position_updated = QtCore.pyqtSignal(list)
  243. def __init__(self):
  244. super().__init__()
  245. self._enabled = None
  246. @property
  247. def enabled(self):
  248. return True if self._enabled else False
  249. @enabled.setter
  250. def enabled(self, value):
  251. self._enabled = value
  252. self.mouse_state_updated.emit(value)
  253. def set_data(self, pos, **kwargs):
  254. """Internal event handler to draw the cursor when the mouse moves."""
  255. if 'edge_color' in kwargs:
  256. color = kwargs['edge_color']
  257. else:
  258. color = (0.0, 0.0, 0.0, 1.0)
  259. position = [pos[0][0], pos[0][1]]
  260. self.mouse_position_updated.emit(position)