VisPyVisuals.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. from vispy.visuals import CompoundVisual, LineVisual, MeshVisual, TextVisual, MarkersVisual
  2. from vispy.scene.visuals import VisualNode, generate_docstring, visuals
  3. from vispy.gloo import set_state
  4. from vispy.color import Color
  5. from shapely.geometry import Polygon, LineString, LinearRing
  6. import threading
  7. import numpy as np
  8. from VisPyTesselators import GLUTess
  9. class FlatCAMLineVisual(LineVisual):
  10. def __init__(self, pos=None, color=(0.5, 0.5, 0.5, 1), width=1, connect='strip',
  11. method='gl', antialias=False):
  12. LineVisual.__init__(self, pos=None, color=(0.5, 0.5, 0.5, 1), width=1, connect='strip',
  13. method='gl', antialias=True)
  14. def clear_data(self):
  15. self._bounds = None
  16. self._pos = None
  17. self._changed['pos'] = True
  18. self.update()
  19. def _update_shape_buffers(data, triangulation='glu'):
  20. """
  21. Translates Shapely geometry to internal buffers for speedup redraws
  22. :param data: dict
  23. Input shape data
  24. :param triangulation: str
  25. Triangulation engine
  26. """
  27. mesh_vertices = [] # Vertices for mesh
  28. mesh_tris = [] # Faces for mesh
  29. mesh_colors = [] # Face colors
  30. line_pts = [] # Vertices for line
  31. line_colors = [] # Line color
  32. geo, color, face_color, tolerance = data['geometry'], data['color'], data['face_color'], data['tolerance']
  33. if geo is not None and not geo.is_empty:
  34. simple = geo.simplify(tolerance) if tolerance else geo # Simplified shape
  35. pts = [] # Shape line points
  36. tri_pts = [] # Mesh vertices
  37. tri_tris = [] # Mesh faces
  38. if type(geo) == LineString:
  39. # Prepare lines
  40. pts = _linestring_to_segments(list(simple.coords))
  41. elif type(geo) == LinearRing:
  42. # Prepare lines
  43. pts = _linearring_to_segments(list(simple.coords))
  44. elif type(geo) == Polygon:
  45. # Prepare polygon faces
  46. if face_color is not None:
  47. if triangulation == 'glu':
  48. gt = GLUTess()
  49. tri_tris, tri_pts = gt.triangulate(simple)
  50. else:
  51. print("Triangulation type '%s' isn't implemented. Drawing only edges." % triangulation)
  52. # Prepare polygon edges
  53. if color is not None:
  54. pts = _linearring_to_segments(list(simple.exterior.coords))
  55. for ints in simple.interiors:
  56. pts += _linearring_to_segments(list(ints.coords))
  57. # Appending data for mesh
  58. if len(tri_pts) > 0 and len(tri_tris) > 0:
  59. mesh_tris += tri_tris
  60. mesh_vertices += tri_pts
  61. mesh_colors += [Color(face_color).rgba] * (len(tri_tris) // 3)
  62. # Appending data for line
  63. if len(pts) > 0:
  64. line_pts += pts
  65. line_colors += [Color(color).rgba] * len(pts)
  66. # Store buffers
  67. data['line_pts'] = line_pts
  68. data['line_colors'] = line_colors
  69. data['mesh_vertices'] = mesh_vertices
  70. data['mesh_tris'] = mesh_tris
  71. data['mesh_colors'] = mesh_colors
  72. # Clear shapely geometry
  73. del data['geometry']
  74. return data
  75. def _linearring_to_segments(arr):
  76. # Close linear ring
  77. """
  78. Translates linear ring to line segments
  79. :param arr: numpy.array
  80. Array of linear ring vertices
  81. :return: numpy.array
  82. Line segments
  83. """
  84. if arr[0] != arr[-1]:
  85. arr.append(arr[0])
  86. return _linestring_to_segments(arr)
  87. def _linestring_to_segments(arr):
  88. """
  89. Translates line strip to segments
  90. :param arr: numpy.array
  91. Array of line strip vertices
  92. :return: numpy.array
  93. Line segments
  94. """
  95. return [arr[i // 2] for i in range(0, len(arr) * 2)][1:-1]
  96. class ShapeGroup(object):
  97. def __init__(self, collection):
  98. """
  99. Represents group of shapes in collection
  100. :param collection: ShapeCollection
  101. Collection to work with
  102. """
  103. self._collection = collection
  104. self._indexes = []
  105. self._visible = True
  106. self._color = None
  107. def add(self, **kwargs):
  108. """
  109. Adds shape to collection and store index in group
  110. :param kwargs: keyword arguments
  111. Arguments for ShapeCollection.add function
  112. """
  113. self._indexes.append(self._collection.add(**kwargs))
  114. def clear(self, update=False):
  115. """
  116. Removes group shapes from collection, clear indexes
  117. :param update: bool
  118. Set True to redraw collection
  119. """
  120. for i in self._indexes:
  121. self._collection.remove(i, False)
  122. del self._indexes[:]
  123. if update:
  124. self._collection.redraw([]) # Skip waiting results
  125. def redraw(self):
  126. """
  127. Redraws shape collection
  128. """
  129. self._collection.redraw(self._indexes)
  130. @property
  131. def visible(self):
  132. """
  133. Visibility of group
  134. :return: bool
  135. """
  136. return self._visible
  137. @visible.setter
  138. def visible(self, value):
  139. """
  140. Visibility of group
  141. :param value: bool
  142. """
  143. self._visible = value
  144. for i in self._indexes:
  145. self._collection.data[i]['visible'] = value
  146. self._collection.redraw([])
  147. class ShapeCollectionVisual(CompoundVisual):
  148. def __init__(self, line_width=1, triangulation='gpc', layers=3, pool=None, **kwargs):
  149. """
  150. Represents collection of shapes to draw on VisPy scene
  151. :param line_width: float
  152. Width of lines/edges
  153. :param triangulation: str
  154. Triangulation method used for polygons translation
  155. 'vispy' - VisPy lib triangulation
  156. 'gpc' - Polygon2 lib
  157. :param layers: int
  158. Layers count
  159. Each layer adds 2 visuals on VisPy scene. Be careful: more layers cause less fps
  160. :param kwargs:
  161. """
  162. self.data = {}
  163. self.last_key = -1
  164. # Thread locks
  165. self.key_lock = threading.Lock()
  166. self.results_lock = threading.Lock()
  167. self.update_lock = threading.Lock()
  168. # Process pool
  169. self.pool = pool
  170. self.results = {}
  171. self._meshes = [MeshVisual() for _ in range(0, layers)]
  172. # self._lines = [LineVisual(antialias=True) for _ in range(0, layers)]
  173. self._lines = [FlatCAMLineVisual(antialias=True) for _ in range(0, layers)]
  174. self._line_width = line_width
  175. self._triangulation = triangulation
  176. visuals_ = [self._lines[i // 2] if i % 2 else self._meshes[i // 2] for i in range(0, layers * 2)]
  177. CompoundVisual.__init__(self, visuals_, **kwargs)
  178. for m in self._meshes:
  179. pass
  180. m.set_gl_state(polygon_offset_fill=True, polygon_offset=(1, 1), cull_face=False)
  181. for l in self._lines:
  182. pass
  183. l.set_gl_state(blend=True)
  184. self.freeze()
  185. def add(self, shape=None, color=None, face_color=None, alpha=None, visible=True,
  186. update=False, layer=1, tolerance=0.01):
  187. """
  188. Adds shape to collection
  189. :return:
  190. :param shape: shapely.geometry
  191. Shapely geometry object
  192. :param color: str, tuple
  193. Line/edge color
  194. :param face_color: str, tuple
  195. Polygon face color
  196. :param visible: bool
  197. Shape visibility
  198. :param update: bool
  199. Set True to redraw collection
  200. :param layer: int
  201. Layer number. 0 - lowest.
  202. :param tolerance: float
  203. Geometry simplifying tolerance
  204. :return: int
  205. Index of shape
  206. """
  207. # Get new key
  208. self.key_lock.acquire(True)
  209. self.last_key += 1
  210. key = self.last_key
  211. self.key_lock.release()
  212. # Prepare data for translation
  213. self.data[key] = {'geometry': shape, 'color': color, 'alpha': alpha, 'face_color': face_color,
  214. 'visible': visible, 'layer': layer, 'tolerance': tolerance}
  215. # Add data to process pool if pool exists
  216. try:
  217. self.results[key] = self.pool.map_async(_update_shape_buffers, [self.data[key]])
  218. except:
  219. self.data[key] = _update_shape_buffers(self.data[key])
  220. if update:
  221. self.redraw() # redraw() waits for pool process end
  222. return key
  223. def remove(self, key, update=False):
  224. """
  225. Removes shape from collection
  226. :param key: int
  227. Shape index to remove
  228. :param update:
  229. Set True to redraw collection
  230. """
  231. # Remove process result
  232. self.results_lock.acquire(True)
  233. if key in list(self.results.copy().keys()):
  234. del self.results[key]
  235. self.results_lock.release()
  236. # Remove data
  237. del self.data[key]
  238. if update:
  239. self.__update()
  240. def clear(self, update=False):
  241. """
  242. Removes all shapes from collection
  243. :param update: bool
  244. Set True to redraw collection
  245. """
  246. self.data.clear()
  247. if update:
  248. self.__update()
  249. def __update(self):
  250. """
  251. Merges internal buffers, sets data to visuals, redraws collection on scene
  252. """
  253. mesh_vertices = [[] for _ in range(0, len(self._meshes))] # Vertices for mesh
  254. mesh_tris = [[] for _ in range(0, len(self._meshes))] # Faces for mesh
  255. mesh_colors = [[] for _ in range(0, len(self._meshes))] # Face colors
  256. line_pts = [[] for _ in range(0, len(self._lines))] # Vertices for line
  257. line_colors = [[] for _ in range(0, len(self._lines))] # Line color
  258. # Lock sub-visuals updates
  259. self.update_lock.acquire(True)
  260. # Merge shapes buffers
  261. for data in list(self.data.values()):
  262. if data['visible'] and 'line_pts' in data:
  263. try:
  264. line_pts[data['layer']] += data['line_pts']
  265. line_colors[data['layer']] += data['line_colors']
  266. mesh_tris[data['layer']] += [x + len(mesh_vertices[data['layer']])
  267. for x in data['mesh_tris']]
  268. mesh_vertices[data['layer']] += data['mesh_vertices']
  269. mesh_colors[data['layer']] += data['mesh_colors']
  270. except Exception as e:
  271. print("Data error", e)
  272. # Updating meshes
  273. for i, mesh in enumerate(self._meshes):
  274. if len(mesh_vertices[i]) > 0:
  275. set_state(polygon_offset_fill=False)
  276. mesh.set_data(np.asarray(mesh_vertices[i]), np.asarray(mesh_tris[i], dtype=np.uint32)
  277. .reshape((-1, 3)), face_colors=np.asarray(mesh_colors[i]))
  278. else:
  279. mesh.set_data()
  280. mesh._bounds_changed()
  281. # Updating lines
  282. for i, line in enumerate(self._lines):
  283. if len(line_pts[i]) > 0:
  284. line.set_data(np.asarray(line_pts[i]), np.asarray(line_colors[i]), self._line_width, 'segments')
  285. else:
  286. line.clear_data()
  287. line._bounds_changed()
  288. self._bounds_changed()
  289. self.update_lock.release()
  290. def redraw(self, indexes=None):
  291. """
  292. Redraws collection
  293. :param indexes: list
  294. Shape indexes to get from process pool
  295. """
  296. # Only one thread can update data
  297. self.results_lock.acquire(True)
  298. for i in list(self.data.copy().keys()) if not indexes else indexes:
  299. if i in list(self.results.copy().keys()):
  300. try:
  301. self.results[i].wait() # Wait for process results
  302. if i in self.data:
  303. self.data[i] = self.results[i].get()[0] # Store translated data
  304. del self.results[i]
  305. except Exception as e:
  306. print(e, indexes)
  307. self.results_lock.release()
  308. self.__update()
  309. def lock_updates(self):
  310. self.update_lock.acquire(True)
  311. def unlock_updates(self):
  312. self.update_lock.release()
  313. class TextGroup(object):
  314. def __init__(self, collection):
  315. self._collection = collection
  316. self._index = None
  317. self._visible = None
  318. def set(self, **kwargs):
  319. """
  320. Adds text to collection and store index
  321. :param kwargs: keyword arguments
  322. Arguments for TextCollection.add function
  323. """
  324. self._index = self._collection.add(**kwargs)
  325. def clear(self, update=False):
  326. """
  327. Removes text from collection, clear index
  328. :param update: bool
  329. Set True to redraw collection
  330. """
  331. if self._index is not None:
  332. self._collection.remove(self._index, False)
  333. self._index = None
  334. if update:
  335. self._collection.redraw()
  336. def redraw(self):
  337. """
  338. Redraws text collection
  339. """
  340. self._collection.redraw()
  341. @property
  342. def visible(self):
  343. """
  344. Visibility of group
  345. :return: bool
  346. """
  347. return self._visible
  348. @visible.setter
  349. def visible(self, value):
  350. """
  351. Visibility of group
  352. :param value: bool
  353. """
  354. self._visible = value
  355. self._collection.data[self._index]['visible'] = value
  356. self._collection.redraw()
  357. class TextCollectionVisual(TextVisual):
  358. def __init__(self, **kwargs):
  359. """
  360. Represents collection of shapes to draw on VisPy scene
  361. :param kwargs: keyword arguments
  362. Arguments to pass for TextVisual
  363. """
  364. self.data = {}
  365. self.last_key = -1
  366. self.lock = threading.Lock()
  367. super(TextCollectionVisual, self).__init__(**kwargs)
  368. self.freeze()
  369. def add(self, text, pos, visible=True, update=True):
  370. """
  371. Adds array of text to collection
  372. :param text: list
  373. Array of strings ['str1', 'str2', ... ]
  374. :param pos: list
  375. Array of string positions [(0, 0), (10, 10), ... ]
  376. :param update: bool
  377. Set True to redraw collection
  378. :return: int
  379. Index of array
  380. """
  381. # Get new key
  382. self.lock.acquire(True)
  383. self.last_key += 1
  384. key = self.last_key
  385. self.lock.release()
  386. # Prepare data for translation
  387. self.data[key] = {'text': text, 'pos': pos, 'visible': visible}
  388. if update:
  389. self.redraw()
  390. return key
  391. def remove(self, key, update=False):
  392. """
  393. Removes shape from collection
  394. :param key: int
  395. Shape index to remove
  396. :param update:
  397. Set True to redraw collection
  398. """
  399. del self.data[key]
  400. if update:
  401. self.__update()
  402. def clear(self, update=False):
  403. """
  404. Removes all shapes from colleciton
  405. :param update: bool
  406. Set True to redraw collection
  407. """
  408. self.data.clear()
  409. if update:
  410. self.__update()
  411. def __update(self):
  412. """
  413. Merges internal buffers, sets data to visuals, redraws collection on scene
  414. """
  415. labels = []
  416. pos = []
  417. # Merge buffers
  418. for data in list(self.data.values()):
  419. if data['visible']:
  420. try:
  421. labels += data['text']
  422. pos += data['pos']
  423. except Exception as e:
  424. print("Data error", e)
  425. # Updating text
  426. if len(labels) > 0:
  427. self.text = labels
  428. self.pos = pos
  429. else:
  430. self.text = None
  431. self.pos = (0, 0)
  432. self._bounds_changed()
  433. def redraw(self):
  434. """
  435. Redraws collection
  436. """
  437. self.__update()
  438. # Add 'enabled' property to visual nodes
  439. def create_fast_node(subclass):
  440. # Create a new subclass of Node.
  441. # Decide on new class name
  442. clsname = subclass.__name__
  443. if not (clsname.endswith('Visual') and
  444. issubclass(subclass, visuals.BaseVisual)):
  445. raise RuntimeError('Class "%s" must end with Visual, and must '
  446. 'subclass BaseVisual' % clsname)
  447. clsname = clsname[:-6]
  448. # Generate new docstring based on visual docstring
  449. try:
  450. doc = generate_docstring(subclass, clsname)
  451. except Exception:
  452. # If parsing fails, just return the original Visual docstring
  453. doc = subclass.__doc__
  454. # New __init__ method
  455. def __init__(self, *args, **kwargs):
  456. parent = kwargs.pop('parent', None)
  457. name = kwargs.pop('name', None)
  458. self.name = name # to allow __str__ before Node.__init__
  459. self._visual_superclass = subclass
  460. # parent: property,
  461. # _parent: attribute of Node class
  462. # __parent: attribute of fast_node class
  463. self.__parent = parent
  464. self._enabled = False
  465. subclass.__init__(self, *args, **kwargs)
  466. self.unfreeze()
  467. VisualNode.__init__(self, parent=parent, name=name)
  468. self.freeze()
  469. # Create new class
  470. cls = type(clsname, (VisualNode, subclass),
  471. {'__init__': __init__, '__doc__': doc})
  472. # 'Enabled' property clears/restores 'parent' property of Node class
  473. # Scene will be painted quicker than when using 'visible' property
  474. def get_enabled(self):
  475. return self._enabled
  476. def set_enabled(self, enabled):
  477. if enabled:
  478. self.parent = self.__parent # Restore parent
  479. else:
  480. if self.parent: # Store parent
  481. self.__parent = self.parent
  482. self.parent = None
  483. cls.enabled = property(get_enabled, set_enabled)
  484. return cls
  485. ShapeCollection = create_fast_node(ShapeCollectionVisual)
  486. TextCollection = create_fast_node(TextCollectionVisual)
  487. Cursor = create_fast_node(MarkersVisual)