3D GUI Elements#
add_3d_gui_container()
allows standard GUI elements to be incorporated directly into a
3D scene. In this example, we click on coordinate frames to show actions that can be
performed on them.
1import time
2from typing import Optional
3
4import numpy as onp
5import viser
6import viser.transforms as tf
7
8server = viser.ViserServer()
9num_frames = 20
10
11
12@server.on_client_connect
13def _(client: viser.ClientHandle) -> None:
14 """For each client that connects, we create a set of random frames + a click handler for each frame.
15
16 When a frame is clicked, we display a 3D gui node.
17 """
18
19 rng = onp.random.default_rng(0)
20
21 displayed_3d_container: Optional[viser.Gui3dContainerHandle] = None
22
23 def make_frame(i: int) -> None:
24 # Sample a random orientation + position.
25 wxyz = rng.normal(size=4)
26 wxyz /= onp.linalg.norm(wxyz)
27 position = rng.uniform(-3.0, 3.0, size=(3,))
28
29 # Create a coordinate frame and label.
30 frame = client.add_frame(f"/frame_{i}", wxyz=wxyz, position=position)
31
32 # Move the camera when we click a frame.
33 @frame.on_click
34 def _(_):
35 nonlocal displayed_3d_container
36
37 # Close previously opened GUI.
38 if displayed_3d_container is not None:
39 displayed_3d_container.remove()
40
41 displayed_3d_container = client.add_3d_gui_container(f"/frame_{i}/gui")
42 with displayed_3d_container:
43 go_to = client.add_gui_button("Go to")
44 randomize_orientation = client.add_gui_button("Randomize orientation")
45 close = client.add_gui_button("Close GUI")
46
47 @go_to.on_click
48 def _(_) -> None:
49 T_world_current = tf.SE3.from_rotation_and_translation(
50 tf.SO3(client.camera.wxyz), client.camera.position
51 )
52 T_world_target = tf.SE3.from_rotation_and_translation(
53 tf.SO3(frame.wxyz), frame.position
54 ) @ tf.SE3.from_translation(onp.array([0.0, 0.0, -0.5]))
55
56 T_current_target = T_world_current.inverse() @ T_world_target
57
58 for j in range(20):
59 T_world_set = T_world_current @ tf.SE3.exp(
60 T_current_target.log() * j / 19.0
61 )
62
63 # Important bit: we atomically set both the orientation and the position
64 # of the camera.
65 with client.atomic():
66 client.camera.wxyz = T_world_set.rotation().wxyz
67 client.camera.position = T_world_set.translation()
68 time.sleep(1.0 / 60.0)
69
70 # Mouse interactions should orbit around the frame origin.
71 client.camera.look_at = frame.position
72
73 @randomize_orientation.on_click
74 def _(_) -> None:
75 wxyz = rng.normal(size=4)
76 wxyz /= onp.linalg.norm(wxyz)
77 frame.wxyz = wxyz
78
79 @close.on_click
80 def _(_) -> None:
81 nonlocal displayed_3d_container
82 if displayed_3d_container is None:
83 return
84 displayed_3d_container.remove()
85 displayed_3d_container = None
86
87 for i in range(num_frames):
88 make_frame(i)
89
90
91while True:
92 time.sleep(1.0)