Mesh click events#

Click on meshes to select them. The index of the last clicked mesh is displayed in the GUI.

 1import time
 2
 3import matplotlib
 4import viser
 5
 6
 7def main() -> None:
 8    grid_shape = (4, 5)
 9    server = viser.ViserServer()
10
11    with server.gui.add_folder("Last clicked"):
12        x_value = server.gui.add_number(
13            label="x",
14            initial_value=0,
15            disabled=True,
16            hint="x coordinate of the last clicked mesh",
17        )
18        y_value = server.gui.add_number(
19            label="y",
20            initial_value=0,
21            disabled=True,
22            hint="y coordinate of the last clicked mesh",
23        )
24
25    def add_swappable_mesh(i: int, j: int) -> None:
26        """Simple callback that swaps between:
27         - a gray box
28         - a colored box
29         - a colored sphere
30
31        Color is chosen based on the position (i, j) of the mesh in the grid.
32        """
33
34        colormap = matplotlib.colormaps["tab20"]
35
36        def create_mesh(counter: int) -> None:
37            if counter == 0:
38                color = (0.8, 0.8, 0.8)
39            else:
40                index = (i * grid_shape[1] + j) / (grid_shape[0] * grid_shape[1])
41                color = colormap(index)[:3]
42
43            if counter in (0, 1):
44                handle = server.scene.add_box(
45                    name=f"/sphere_{i}_{j}",
46                    position=(i, j, 0.0),
47                    color=color,
48                    dimensions=(0.5, 0.5, 0.5),
49                )
50            else:
51                handle = server.scene.add_icosphere(
52                    name=f"/sphere_{i}_{j}",
53                    radius=0.4,
54                    color=color,
55                    position=(i, j, 0.0),
56                )
57
58            @handle.on_click
59            def _(_) -> None:
60                x_value.value = i
61                y_value.value = j
62
63                # The new mesh will replace the old one because the names
64                # /sphere_{i}_{j} are the same.
65                create_mesh((counter + 1) % 3)
66
67        create_mesh(0)
68
69    for i in range(grid_shape[0]):
70        for j in range(grid_shape[1]):
71            add_swappable_mesh(i, j)
72
73    while True:
74        time.sleep(10.0)
75
76
77if __name__ == "__main__":
78    main()