VisPyVisuals.py 26 KB

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