VisPyVisuals.py 27 KB

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