scene.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. from dataclasses import dataclass
  2. from pathlib import Path
  3. from typing import Any, Callable, Dict, List, Optional, Union
  4. from .. import binding, globals
  5. from ..dependencies import register_library, register_vue_component
  6. from ..element import Element
  7. from ..events import GenericEventArguments, SceneClickEventArguments, SceneClickHit, handle_event
  8. from ..helpers import KWONLY_SLOTS
  9. from .scene_object3d import Object3D
  10. register_vue_component('scene', Path(__file__).parent / 'scene.js')
  11. lib = Path('three')
  12. library_names = [
  13. register_library(lib / 'three.module.js', expose=True),
  14. register_library(lib / 'modules' / 'CSS2DRenderer.js', expose=True),
  15. register_library(lib / 'modules' / 'CSS3DRenderer.js', expose=True),
  16. register_library(lib / 'modules' / 'OrbitControls.js', expose=True),
  17. register_library(lib / 'modules' / 'STLLoader.js', expose=True),
  18. register_library(lib / 'tween' / 'tween.umd.js'),
  19. ]
  20. @dataclass(**KWONLY_SLOTS)
  21. class SceneCamera:
  22. x: float = 0
  23. y: float = -3
  24. z: float = 5
  25. look_at_x: float = 0
  26. look_at_y: float = 0
  27. look_at_z: float = 0
  28. up_x: float = 0
  29. up_y: float = 0
  30. up_z: float = 1
  31. @dataclass(**KWONLY_SLOTS)
  32. class SceneObject:
  33. id: str = 'scene'
  34. class Scene(Element):
  35. from .scene_objects import Box as box
  36. from .scene_objects import Curve as curve
  37. from .scene_objects import Cylinder as cylinder
  38. from .scene_objects import Extrusion as extrusion
  39. from .scene_objects import Group as group
  40. from .scene_objects import Line as line
  41. from .scene_objects import PointCloud as point_cloud
  42. from .scene_objects import QuadraticBezierTube as quadratic_bezier_tube
  43. from .scene_objects import Ring as ring
  44. from .scene_objects import Sphere as sphere
  45. from .scene_objects import SpotLight as spot_light
  46. from .scene_objects import Stl as stl
  47. from .scene_objects import Text as text
  48. from .scene_objects import Text3d as text3d
  49. from .scene_objects import Texture as texture
  50. def __init__(self,
  51. width: int = 400,
  52. height: int = 300,
  53. grid: bool = True,
  54. on_click: Optional[Callable[..., Any]] = None,
  55. ) -> None:
  56. """3D Scene
  57. Display a 3d scene using `three.js <https://threejs.org/>`_.
  58. Currently NiceGUI supports boxes, spheres, cylinders/cones, extrusions, straight lines, curves and textured meshes.
  59. Objects can be translated, rotated and displayed with different color, opacity or as wireframes.
  60. They can also be grouped to apply joint movements.
  61. :param width: width of the canvas
  62. :param height: height of the canvas
  63. :param grid: whether to display a grid
  64. :param on_click: callback to execute when a 3d object is clicked
  65. """
  66. super().__init__('scene')
  67. self._props['width'] = width
  68. self._props['height'] = height
  69. self._props['grid'] = grid
  70. self.objects: Dict[str, Object3D] = {}
  71. self.stack: List[Union[Object3D, SceneObject]] = [SceneObject()]
  72. self.camera: SceneCamera = SceneCamera()
  73. self.on_click = on_click
  74. self.is_initialized = False
  75. self.on('init', self.handle_init)
  76. self.on('click3d', self.handle_click)
  77. self.use_component('scene')
  78. for library_name in library_names:
  79. self.use_library(library_name)
  80. def handle_init(self, e: GenericEventArguments) -> None:
  81. self.is_initialized = True
  82. with globals.socket_id(e.args):
  83. self.move_camera(duration=0)
  84. for object in self.objects.values():
  85. object.send()
  86. def run_method(self, name: str, *args: Any) -> None:
  87. if not self.is_initialized:
  88. return
  89. super().run_method(name, *args)
  90. def handle_click(self, e: GenericEventArguments) -> None:
  91. arguments = SceneClickEventArguments(
  92. sender=self,
  93. client=self.client,
  94. click_type=e.args['click_type'],
  95. button=e.args['button'],
  96. alt=e.args['alt_key'],
  97. ctrl=e.args['ctrl_key'],
  98. meta=e.args['meta_key'],
  99. shift=e.args['shift_key'],
  100. hits=[SceneClickHit(
  101. object_id=hit['object_id'],
  102. object_name=hit['object_name'],
  103. x=hit['point']['x'],
  104. y=hit['point']['y'],
  105. z=hit['point']['z'],
  106. ) for hit in e.args['hits']],
  107. )
  108. handle_event(self.on_click, arguments)
  109. def __len__(self) -> int:
  110. return len(self.objects)
  111. def move_camera(self,
  112. x: Optional[float] = None,
  113. y: Optional[float] = None,
  114. z: Optional[float] = None,
  115. look_at_x: Optional[float] = None,
  116. look_at_y: Optional[float] = None,
  117. look_at_z: Optional[float] = None,
  118. up_x: Optional[float] = None,
  119. up_y: Optional[float] = None,
  120. up_z: Optional[float] = None,
  121. duration: float = 0.5) -> None:
  122. self.camera.x = self.camera.x if x is None else x
  123. self.camera.y = self.camera.y if y is None else y
  124. self.camera.z = self.camera.z if z is None else z
  125. self.camera.look_at_x = self.camera.look_at_x if look_at_x is None else look_at_x
  126. self.camera.look_at_y = self.camera.look_at_y if look_at_y is None else look_at_y
  127. self.camera.look_at_z = self.camera.look_at_z if look_at_z is None else look_at_z
  128. self.camera.up_x = self.camera.up_x if up_x is None else up_x
  129. self.camera.up_y = self.camera.up_y if up_y is None else up_y
  130. self.camera.up_z = self.camera.up_z if up_z is None else up_z
  131. self.run_method('move_camera',
  132. self.camera.x, self.camera.y, self.camera.z,
  133. self.camera.look_at_x, self.camera.look_at_y, self.camera.look_at_z,
  134. self.camera.up_x, self.camera.up_y, self.camera.up_z, duration)
  135. def delete(self) -> None:
  136. binding.remove(list(self.objects.values()), Object3D)
  137. super().delete()