VisPyVisuals.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # File Author: Dennis Hayrullin #
  5. # Date: 2/5/2016 #
  6. # MIT Licence #
  7. # ##########################################################
  8. from vispy.visuals import CompoundVisual, LineVisual, MeshVisual, TextVisual, MarkersVisual
  9. from vispy.scene.visuals import VisualNode, generate_docstring, visuals
  10. from vispy.gloo import set_state
  11. from vispy.color import Color
  12. from shapely.geometry import Polygon, LineString, LinearRing
  13. import threading
  14. import numpy as np
  15. from appGUI.VisPyTesselators import GLUTess
  16. class FlatCAMLineVisual(LineVisual):
  17. def __init__(self, pos=None, color=(0.5, 0.5, 0.5, 1), width=1, connect='strip', method='gl', antialias=False):
  18. LineVisual.__init__(self, pos=pos, color=color, width=width, connect=connect,
  19. method=method, antialias=True)
  20. def clear_data(self):
  21. self._bounds = None
  22. self._pos = None
  23. self._changed['pos'] = True
  24. self.update()
  25. def _update_shape_buffers(data, triangulation='glu'):
  26. """
  27. Translates Shapely geometry to internal buffers for speedup redraws
  28. :param data: dict
  29. Input shape data
  30. :param triangulation: str
  31. Triangulation engine
  32. """
  33. mesh_vertices = [] # Vertices for mesh
  34. mesh_tris = [] # Faces for mesh
  35. mesh_colors = [] # Face colors
  36. line_pts = [] # Vertices for line
  37. line_colors = [] # Line color
  38. geo, color, face_color, tolerance = data['geometry'], data['color'], data['face_color'], data['tolerance']
  39. if geo is not None and not geo.is_empty:
  40. simplified_geo = geo.simplify(tolerance) if tolerance else geo # Simplified shape
  41. pts = [] # Shape line points
  42. tri_pts = [] # Mesh vertices
  43. tri_tris = [] # Mesh faces
  44. if type(geo) == LineString:
  45. # Prepare lines
  46. pts = _linestring_to_segments(list(simplified_geo.coords))
  47. elif type(geo) == LinearRing:
  48. # Prepare lines
  49. pts = _linearring_to_segments(list(simplified_geo.coords))
  50. elif type(geo) == Polygon:
  51. # Prepare polygon faces
  52. if face_color is not None:
  53. if triangulation == 'glu':
  54. gt = GLUTess()
  55. tri_tris, tri_pts = gt.triangulate(simplified_geo)
  56. else:
  57. print("Triangulation type '%s' isn't implemented. Drawing only edges." % triangulation)
  58. # Prepare polygon edges
  59. if color is not None:
  60. pts = _linearring_to_segments(list(simplified_geo.exterior.coords))
  61. for ints in simplified_geo.interiors:
  62. pts += _linearring_to_segments(list(ints.coords))
  63. # Appending data for mesh
  64. if len(tri_pts) > 0 and len(tri_tris) > 0:
  65. mesh_tris += tri_tris
  66. mesh_vertices += tri_pts
  67. face_color_rgba = Color(face_color).rgba
  68. # mesh_colors += [face_color_rgba] * (len(tri_tris) // 3)
  69. mesh_colors += [face_color_rgba for __ in range(len(tri_tris) // 3)]
  70. # Appending data for line
  71. if len(pts) > 0:
  72. line_pts += pts
  73. colo_rgba = Color(color).rgba
  74. # line_colors += [colo_rgba] * len(pts)
  75. line_colors += [colo_rgba for __ in range(len(pts))]
  76. # Store buffers
  77. data['line_pts'] = line_pts
  78. data['line_colors'] = line_colors
  79. data['mesh_vertices'] = mesh_vertices
  80. data['mesh_tris'] = mesh_tris
  81. data['mesh_colors'] = mesh_colors
  82. # Clear shapely geometry
  83. del data['geometry']
  84. return data
  85. def _linearring_to_segments(arr):
  86. # Close linear ring
  87. """
  88. Translates linear ring to line segments
  89. :param arr: numpy.array
  90. Array of linear ring vertices
  91. :return: numpy.array
  92. Line segments
  93. """
  94. if arr[0] != arr[-1]:
  95. arr.append(arr[0])
  96. return _linestring_to_segments(arr)
  97. def _linestring_to_segments(arr):
  98. """
  99. Translates line strip to segments
  100. :param arr: numpy.array
  101. Array of line strip vertices
  102. :return: numpy.array
  103. Line segments
  104. """
  105. return [arr[i // 2] for i in range(0, len(arr) * 2)][1:-1]
  106. class ShapeGroup(object):
  107. def __init__(self, collection):
  108. """
  109. Represents group of shapes in collection
  110. :param collection: ShapeCollection
  111. Collection to work with
  112. """
  113. self._collection = collection
  114. self._indexes = []
  115. self._visible = True
  116. self._color = None
  117. def add(self, **kwargs):
  118. """
  119. Adds shape to collection and store index in group
  120. :param kwargs: keyword arguments
  121. Arguments for ShapeCollection.add function
  122. """
  123. key = self._collection.add(**kwargs)
  124. self._indexes.append(key)
  125. return key
  126. def remove(self, idx, update=False):
  127. self._indexes.remove(idx)
  128. self._collection.remove(idx, False)
  129. if update:
  130. self._collection.redraw([]) # Skip waiting results
  131. def clear(self, update=False):
  132. """
  133. Removes group shapes from collection, clear indexes
  134. :param update: bool
  135. Set True to redraw collection
  136. """
  137. for i in self._indexes:
  138. self._collection.remove(i, False)
  139. del self._indexes[:]
  140. if update:
  141. self._collection.redraw([]) # Skip waiting results
  142. def redraw(self, update_colors=None):
  143. """
  144. Redraws shape collection
  145. """
  146. if update_colors:
  147. self._collection.redraw(self._indexes, update_colors=update_colors)
  148. else:
  149. self._collection.redraw(self._indexes)
  150. @property
  151. def visible(self):
  152. """
  153. Visibility of group
  154. :return: bool
  155. """
  156. return self._visible
  157. @visible.setter
  158. def visible(self, value):
  159. """
  160. Visibility of group
  161. :param value: bool
  162. """
  163. self._visible = value
  164. for i in self._indexes:
  165. self._collection.data[i]['visible'] = value
  166. self._collection.redraw([])
  167. def update_visibility(self, state, indexes=None):
  168. if indexes:
  169. for i in indexes:
  170. if i in self._indexes:
  171. self._collection.data[i]['visible'] = state
  172. else:
  173. for i in self._indexes:
  174. self._collection.data[i]['visible'] = state
  175. self._collection.redraw([])
  176. class ShapeCollectionVisual(CompoundVisual):
  177. def __init__(self, linewidth=1, triangulation='vispy', layers=3, pool=None, **kwargs):
  178. """
  179. Represents collection of shapes to draw on VisPy scene
  180. :param linewidth: float
  181. Width of lines/edges
  182. :param triangulation: str
  183. Triangulation method used for polygons translation
  184. 'vispy' - VisPy lib triangulation
  185. 'gpc' - Polygon2 lib
  186. :param layers: int
  187. Layers count
  188. Each layer adds 2 visuals on VisPy scene. Be careful: more layers cause less fps
  189. :param kwargs:
  190. """
  191. self.data = {}
  192. self.last_key = -1
  193. # Thread locks
  194. self.key_lock = threading.Lock()
  195. self.results_lock = threading.Lock()
  196. self.update_lock = threading.Lock()
  197. # Process pool
  198. self.pool = pool
  199. self.results = {}
  200. self._meshes = [MeshVisual() for _ in range(0, layers)]
  201. # self._lines = [LineVisual(antialias=True) for _ in range(0, layers)]
  202. self._lines = [FlatCAMLineVisual(antialias=True) for _ in range(0, layers)]
  203. self._line_width = linewidth
  204. self._triangulation = triangulation
  205. visuals_ = [self._lines[i // 2] if i % 2 else self._meshes[i // 2] for i in range(0, layers * 2)]
  206. CompoundVisual.__init__(self, visuals_, **kwargs)
  207. for m in self._meshes:
  208. pass
  209. m.set_gl_state(polygon_offset_fill=True, polygon_offset=(1, 1), cull_face=False)
  210. for lne in self._lines:
  211. pass
  212. lne.set_gl_state(blend=True)
  213. self.freeze()
  214. def add(self, shape=None, color=None, face_color=None, alpha=None, visible=True,
  215. update=False, layer=1, tolerance=0.01, linewidth=None):
  216. """
  217. Adds shape to collection
  218. :return:
  219. :param shape: shapely.geometry
  220. Shapely geometry object
  221. :param color: str, tuple
  222. Line/edge color
  223. :param face_color: str, tuple
  224. Polygon face color
  225. :param alpha: str
  226. Polygon transparency
  227. :param visible: bool
  228. Shape visibility
  229. :param update: bool
  230. Set True to redraw collection
  231. :param layer: int
  232. Layer number. 0 - lowest.
  233. :param tolerance: float
  234. Geometry simplifying tolerance
  235. :param linewidth: int
  236. Width of the line
  237. :return: int
  238. Index of shape
  239. """
  240. # Get new key
  241. self.key_lock.acquire(True)
  242. self.last_key += 1
  243. key = self.last_key
  244. self.key_lock.release()
  245. # Prepare data for translation
  246. self.data[key] = {'geometry': shape, 'color': color, 'alpha': alpha, 'face_color': face_color,
  247. 'visible': visible, 'layer': layer, 'tolerance': tolerance}
  248. if linewidth:
  249. self._line_width = linewidth
  250. # Add data to process pool if pool exists
  251. try:
  252. self.results[key] = self.pool.map_async(_update_shape_buffers, [self.data[key]])
  253. except Exception:
  254. self.data[key] = _update_shape_buffers(self.data[key])
  255. if update:
  256. self.redraw() # redraw() waits for pool process end
  257. return key
  258. def remove(self, key, update=False):
  259. """
  260. Removes shape from collection
  261. :param key: int
  262. Shape index to remove
  263. :param update:
  264. Set True to redraw collection
  265. """
  266. # Remove process result
  267. self.results_lock.acquire(True)
  268. if key in list(self.results.copy().keys()):
  269. del self.results[key]
  270. self.results_lock.release()
  271. # Remove data
  272. del self.data[key]
  273. if update:
  274. self.__update()
  275. def clear(self, update=False):
  276. """
  277. Removes all shapes from collection
  278. :param update: bool
  279. Set True to redraw collection
  280. """
  281. self.data.clear()
  282. if update:
  283. self.__update()
  284. def update_visibility(self, state: bool, indexes=None) -> None:
  285. # Lock sub-visuals updates
  286. self.update_lock.acquire(True)
  287. if indexes is None:
  288. for k, data in list(self.data.items()):
  289. self.data[k]['visible'] = state
  290. else:
  291. for k, data in list(self.data.items()):
  292. if k in indexes:
  293. self.data[k]['visible'] = state
  294. self.update_lock.release()
  295. def update_color(self, new_mesh_color=None, new_line_color=None, indexes=None):
  296. if new_mesh_color is None and new_line_color is None:
  297. return
  298. if not self.data:
  299. return
  300. # if a new color is empty string then make it None so it will not be updated
  301. # if a new color is valid then transform it here in a format palatable
  302. mesh_color_rgba = None
  303. line_color_rgba = None
  304. if new_mesh_color:
  305. if new_mesh_color != '':
  306. mesh_color_rgba = Color(new_mesh_color).rgba
  307. else:
  308. new_mesh_color = None
  309. if new_line_color:
  310. if new_line_color != '':
  311. line_color_rgba = Color(new_line_color).rgba
  312. else:
  313. new_line_color = None
  314. mesh_colors = [[] for _ in range(0, len(self._meshes))] # Face colors
  315. line_colors = [[] for _ in range(0, len(self._meshes))] # Line colors
  316. line_pts = [[] for _ in range(0, len(self._lines))] # Vertices for line
  317. # Lock sub-visuals updates
  318. self.update_lock.acquire(True)
  319. # Merge shapes buffers
  320. if indexes is None:
  321. for k, data in list(self.data.items()):
  322. if data['visible'] and 'line_pts' in data:
  323. if new_mesh_color and new_mesh_color != '':
  324. dim_mesh_tris = (len(data['mesh_tris']) // 3)
  325. if dim_mesh_tris != 0:
  326. try:
  327. mesh_colors[data['layer']] += [mesh_color_rgba] * dim_mesh_tris
  328. self.data[k]['face_color'] = new_mesh_color
  329. data['mesh_colors'] = [mesh_color_rgba for __ in range(len(data['mesh_colors']))]
  330. except Exception as e:
  331. print("VisPyVisuals.ShapeCollectionVisual.update_color(). "
  332. "Create mesh colors --> Data error. %s" % str(e))
  333. if new_line_color and new_line_color != '':
  334. dim_line_pts = (len(data['line_pts']))
  335. if dim_line_pts != 0:
  336. try:
  337. line_pts[data['layer']] += data['line_pts']
  338. line_colors[data['layer']] += [line_color_rgba] * dim_line_pts
  339. self.data[k]['color'] = new_line_color
  340. data['line_colors'] = [mesh_color_rgba for __ in range(len(data['line_colors']))]
  341. except Exception as e:
  342. print("VisPyVisuals.ShapeCollectionVisual.update_color(). "
  343. "Create line colors --> Data error. %s" % str(e))
  344. else:
  345. for k, data in list(self.data.items()):
  346. if data['visible'] and 'line_pts' in data:
  347. dim_mesh_tris = (len(data['mesh_tris']) // 3)
  348. dim_line_pts = (len(data['line_pts']))
  349. if k in indexes:
  350. if new_mesh_color and new_mesh_color != '':
  351. if dim_mesh_tris != 0:
  352. try:
  353. mesh_colors[data['layer']] += [mesh_color_rgba] * dim_mesh_tris
  354. self.data[k]['face_color'] = new_mesh_color
  355. data['mesh_colors'] = [mesh_color_rgba for __ in range(len(data['mesh_colors']))]
  356. except Exception as e:
  357. print("VisPyVisuals.ShapeCollectionVisual.update_color(). "
  358. "Create mesh colors --> Data error. %s" % str(e))
  359. if new_line_color and new_line_color != '':
  360. if dim_line_pts != 0:
  361. try:
  362. line_pts[data['layer']] += data['line_pts']
  363. line_colors[data['layer']] += [line_color_rgba] * dim_line_pts
  364. self.data[k]['color'] = new_line_color
  365. data['line_colors'] = [mesh_color_rgba for __ in range(len(data['line_colors']))]
  366. except Exception as e:
  367. print("VisPyVisuals.ShapeCollectionVisual.update_color(). "
  368. "Create line colors --> Data error. %s" % str(e))
  369. else:
  370. if dim_mesh_tris != 0:
  371. try:
  372. mesh_colors[data['layer']] += [Color(data['face_color']).rgba] * dim_mesh_tris
  373. except Exception as e:
  374. print("VisPyVisuals.ShapeCollectionVisual.update_color(). "
  375. "Create mesh colors --> Data error. %s" % str(e))
  376. if dim_line_pts != 0:
  377. try:
  378. line_pts[data['layer']] += data['line_pts']
  379. line_colors[data['layer']] += [Color(data['color']).rgba] * dim_line_pts
  380. except Exception as e:
  381. print("VisPyVisuals.ShapeCollectionVisual.update_color(). "
  382. "Create line colors --> Data error. %s" % str(e))
  383. # Updating meshes
  384. if new_mesh_color and new_mesh_color != '':
  385. for i, mesh in enumerate(self._meshes):
  386. if mesh_colors[i]:
  387. try:
  388. mesh._meshdata.set_face_colors(colors=np.asarray(mesh_colors[i]))
  389. mesh.mesh_data_changed()
  390. except Exception as e:
  391. print("VisPyVisuals.ShapeCollectionVisual.update_color(). "
  392. "Apply mesh colors --> Data error. %s" % str(e))
  393. # Updating lines
  394. if new_line_color and new_line_color != '':
  395. for i, line in enumerate(self._lines):
  396. if len(line_pts[i]) > 0:
  397. try:
  398. line._color = np.asarray(line_colors[i])
  399. line._changed['color'] = True
  400. line.update()
  401. except Exception as e:
  402. print("VisPyVisuals.ShapeCollectionVisual.update_color(). "
  403. "Apply line colors --> Data error. %s" % str(e))
  404. else:
  405. line.clear_data()
  406. self.update_lock.release()
  407. def __update(self):
  408. """
  409. Merges internal buffers, sets data to visuals, redraws collection on scene
  410. """
  411. mesh_vertices = [[] for _ in range(0, len(self._meshes))] # Vertices for mesh
  412. mesh_tris = [[] for _ in range(0, len(self._meshes))] # Faces for mesh
  413. mesh_colors = [[] for _ in range(0, len(self._meshes))] # Face colors
  414. line_pts = [[] for _ in range(0, len(self._lines))] # Vertices for line
  415. line_colors = [[] for _ in range(0, len(self._lines))] # Line color
  416. # Lock sub-visuals updates
  417. self.update_lock.acquire(True)
  418. # Merge shapes buffers
  419. for data in list(self.data.values()):
  420. if data['visible'] and 'line_pts' in data:
  421. try:
  422. line_pts[data['layer']] += data['line_pts']
  423. line_colors[data['layer']] += data['line_colors']
  424. mesh_tris[data['layer']] += [x + len(mesh_vertices[data['layer']]) for x in data['mesh_tris']]
  425. mesh_vertices[data['layer']] += data['mesh_vertices']
  426. mesh_colors[data['layer']] += data['mesh_colors']
  427. except Exception as e:
  428. print("VisPyVisuals.ShapeCollectionVisual._update() --> Data error. %s" % str(e))
  429. # Updating meshes
  430. for i, mesh in enumerate(self._meshes):
  431. if len(mesh_vertices[i]) > 0:
  432. set_state(polygon_offset_fill=False)
  433. faces_array = np.asarray(mesh_tris[i], dtype=np.uint32)
  434. mesh.set_data(
  435. vertices=np.asarray(mesh_vertices[i]),
  436. faces=faces_array.reshape((-1, 3)),
  437. face_colors=np.asarray(mesh_colors[i])
  438. )
  439. else:
  440. mesh.set_data()
  441. mesh._bounds_changed()
  442. # Updating lines
  443. for i, line in enumerate(self._lines):
  444. if len(line_pts[i]) > 0:
  445. line.set_data(
  446. pos=np.asarray(line_pts[i]),
  447. color=np.asarray(line_colors[i]),
  448. width=self._line_width,
  449. connect='segments')
  450. else:
  451. line.clear_data()
  452. line._bounds_changed()
  453. self._bounds_changed()
  454. self.update_lock.release()
  455. def redraw(self, indexes=None, update_colors=None):
  456. """
  457. Redraws collection
  458. :param indexes: list
  459. Shape indexes to get from process pool
  460. :param update_colors:
  461. """
  462. # Only one thread can update data
  463. self.results_lock.acquire(True)
  464. for i in list(self.data.keys()) if not indexes else indexes:
  465. if i in list(self.results.keys()):
  466. try:
  467. self.results[i].wait() # Wait for process results
  468. if i in self.data:
  469. self.data[i] = self.results[i].get()[0] # Store translated data
  470. del self.results[i]
  471. except Exception as e:
  472. print("VisPyVisuals.ShapeCollectionVisual.redraw() --> Data error = %s. Indexes = %s" %
  473. (str(e), str(indexes)))
  474. self.results_lock.release()
  475. if update_colors is None or update_colors is False:
  476. self.__update()
  477. else:
  478. try:
  479. self.update_color(
  480. new_mesh_color=update_colors[0],
  481. new_line_color=update_colors[1],
  482. indexes=indexes
  483. )
  484. except Exception as e:
  485. print("VisPyVisuals.ShapeCollectionVisual.redraw() --> Update colors error = %s." % str(e))
  486. def lock_updates(self):
  487. self.update_lock.acquire(True)
  488. def unlock_updates(self):
  489. self.update_lock.release()
  490. class TextGroup(object):
  491. def __init__(self, collection):
  492. self._collection = collection
  493. self._index = None
  494. self._visible = None
  495. def set(self, **kwargs):
  496. """
  497. Adds text to collection and store index
  498. :param kwargs: keyword arguments
  499. Arguments for TextCollection.add function
  500. """
  501. self._index = self._collection.add(**kwargs)
  502. def clear(self, update=False):
  503. """
  504. Removes text from collection, clear index
  505. :param update: bool
  506. Set True to redraw collection
  507. """
  508. if self._index is not None:
  509. self._collection.remove(self._index, False)
  510. self._index = None
  511. if update:
  512. self._collection.redraw()
  513. def redraw(self):
  514. """
  515. Redraws text collection
  516. """
  517. self._collection.redraw()
  518. @property
  519. def visible(self):
  520. """
  521. Visibility of group
  522. :return: bool
  523. """
  524. return self._visible
  525. @visible.setter
  526. def visible(self, value):
  527. """
  528. Visibility of group
  529. :param value: bool
  530. """
  531. self._visible = value
  532. if self._index:
  533. try:
  534. self._collection.data[self._index]['visible'] = value
  535. except KeyError as e:
  536. print("VisPyVisuals.TextGroup.visible --> KeyError --> %s" % str(e))
  537. pass
  538. self._collection.redraw()
  539. class TextCollectionVisual(TextVisual):
  540. def __init__(self, **kwargs):
  541. """
  542. Represents collection of shapes to draw on VisPy scene
  543. :param kwargs: keyword arguments
  544. Arguments to pass for TextVisual
  545. """
  546. self.data = {}
  547. self.last_key = -1
  548. self.lock = threading.Lock()
  549. self.method = 'gpu'
  550. super(TextCollectionVisual, self).__init__(**kwargs)
  551. self.freeze()
  552. def add(self, text, pos, visible=True, update=True, font_size=9, color='black'):
  553. """
  554. Adds array of text to collection
  555. :param text: list
  556. Array of strings ['str1', 'str2', ... ]
  557. :param pos: list
  558. Array of string positions [(0, 0), (10, 10), ... ]
  559. :param visible: bool
  560. | Set True to make it visible
  561. :param update: bool
  562. Set True to redraw collection
  563. :param font_size: int
  564. Set font size to redraw collection
  565. :param color: string
  566. Set font color to redraw collection
  567. :return: int
  568. Index of array
  569. """
  570. # Get new key
  571. self.lock.acquire(True)
  572. self.last_key += 1
  573. key = self.last_key
  574. self.lock.release()
  575. # Prepare data for translation
  576. self.data[key] = {'text': text, 'pos': pos, 'visible': visible, 'font_size': font_size, 'color': color}
  577. if update:
  578. self.redraw()
  579. return key
  580. def remove(self, key, update=False):
  581. """
  582. Removes shape from collection
  583. :param key: int
  584. Shape index to remove
  585. :param update:
  586. Set True to redraw collection
  587. """
  588. del self.data[key]
  589. if update:
  590. self.__update()
  591. def clear(self, update=False):
  592. """
  593. Removes all shapes from collection
  594. :param update: bool
  595. Set True to redraw collection
  596. """
  597. self.data.clear()
  598. if update:
  599. self.__update()
  600. def __update(self):
  601. """
  602. Merges internal buffers, sets data to visuals, redraws collection on scene
  603. """
  604. labels = []
  605. pos = []
  606. font_s = 9
  607. color = 'black'
  608. # Merge buffers
  609. for data in list(self.data.values()):
  610. if data['visible']:
  611. try:
  612. labels += data['text']
  613. pos += data['pos']
  614. font_s = data['font_size']
  615. color = data['color']
  616. except Exception as e:
  617. print("VisPyVisuals.TextCollectionVisual._update() --> Data error. %s" % str(e))
  618. # Updating text
  619. if len(labels) > 0:
  620. self.text = labels
  621. self.pos = pos
  622. self.font_size = font_s
  623. self.color = color
  624. else:
  625. self.text = None
  626. self.pos = (0, 0)
  627. self._bounds_changed()
  628. def redraw(self):
  629. """
  630. Redraws collection
  631. """
  632. self.__update()
  633. # Add 'enabled' property to visual nodes
  634. def create_fast_node(subclass):
  635. # Create a new subclass of Node.
  636. # Decide on new class name
  637. clsname = subclass.__name__
  638. if not (clsname.endswith('Visual') and
  639. issubclass(subclass, visuals.BaseVisual)):
  640. raise RuntimeError('Class "%s" must end with Visual, and must '
  641. 'subclass BaseVisual' % clsname)
  642. clsname = clsname[:-6]
  643. # Generate new docstring based on visual docstring
  644. try:
  645. doc = generate_docstring(subclass, clsname)
  646. except Exception:
  647. # If parsing fails, just return the original Visual docstring
  648. doc = subclass.__doc__
  649. # New __init__ method
  650. def __init__(self, *args, **kwargs):
  651. parent = kwargs.pop('parent', None)
  652. name = kwargs.pop('name', None)
  653. self.name = name # to allow __str__ before Node.__init__
  654. self._visual_superclass = subclass
  655. # parent: property,
  656. # _parent: attribute of Node class
  657. # __parent: attribute of fast_node class
  658. self.__parent = parent
  659. self._enabled = False
  660. subclass.__init__(self, *args, **kwargs)
  661. self.unfreeze()
  662. VisualNode.__init__(self, parent=parent, name=name)
  663. self.freeze()
  664. # Create new class
  665. cls = type(clsname, (VisualNode, subclass),
  666. {'__init__': __init__, '__doc__': doc})
  667. # 'Enabled' property clears/restores 'parent' property of Node class
  668. # Scene will be painted quicker than when using 'visible' property
  669. def get_enabled(self):
  670. return self._enabled
  671. def set_enabled(self, enabled):
  672. if enabled:
  673. self.parent = self.__parent # Restore parent
  674. else:
  675. if self.parent: # Store parent
  676. self.__parent = self.parent
  677. self.parent = None
  678. cls.enabled = property(get_enabled, set_enabled)
  679. return cls
  680. ShapeCollection = create_fast_node(ShapeCollectionVisual)
  681. TextCollection = create_fast_node(TextCollectionVisual)
  682. Cursor = create_fast_node(MarkersVisual)