Distance fog¶
Add distance-based fog to fade objects into a background color.
This example demonstrates viser.SceneApi.configure_fog(), which applies
linear fog to the scene. Objects between near and far will gradually
blend into the fog color, giving a sense of depth.
Source: examples/01_scene/10_fog.py
Code¶
1import time
2
3import numpy as np
4import viser
5
6
7def main() -> None:
8 server = viser.ViserServer()
9
10 # Ground grid.
11 server.scene.add_grid(
12 "/grid",
13 width=40.0,
14 height=40.0,
15 cell_size=1.0,
16 position=(0.0, 0.0, -1.0),
17 )
18
19 # A row of boxes receding into the distance.
20 for i in range(12):
21 server.scene.add_box(
22 f"/boxes/{i}",
23 color=(60, 120, 200),
24 position=(3.0 + i * -2.0, 3.0 + i * -2.0, 0.0),
25 )
26
27 # Point cloud spread along the depth axis.
28 rng = np.random.default_rng(0)
29 num_points = 2000
30 server.scene.add_point_cloud(
31 "/points",
32 points=rng.uniform((-5, 0, -2), (5, 35, 2), size=(num_points, 3)).astype(
33 np.float32
34 ),
35 colors=rng.integers(80, 255, size=(num_points, 3), dtype=np.uint8),
36 point_size=0.06,
37 position=(-8.0, 0.0, 0.0),
38 )
39
40 # Gaussian splats scattered into the distance.
41 num_splats = 500
42 server.scene.add_gaussian_splats(
43 "/splats",
44 centers=rng.uniform((-4, 2, -1), (4, 35, 2), size=(num_splats, 3)).astype(
45 np.float32
46 ),
47 covariances=np.tile(0.01 * np.eye(3, dtype=np.float32), (num_splats, 1, 1)),
48 rgbs=rng.uniform(0.3, 1.0, size=(num_splats, 3)).astype(np.float32),
49 opacities=rng.uniform(0.6, 1.0, size=(num_splats, 1)).astype(np.float32),
50 position=(8.0, 0.0, 0.0),
51 )
52
53 # Configure fog.
54 server.scene.configure_fog(near=3.0, far=20.0, color=(255, 255, 255))
55
56 # GUI controls.
57 with server.gui.add_folder("Fog"):
58 gui_enabled = server.gui.add_checkbox("Enabled", initial_value=True)
59 gui_near = server.gui.add_slider(
60 "Near", min=0.0, max=50.0, step=0.5, initial_value=3.0
61 )
62 gui_far = server.gui.add_slider(
63 "Far", min=1.0, max=50.0, step=0.5, initial_value=20.0
64 )
65 gui_color = server.gui.add_rgb("Color", initial_value=(255, 255, 255))
66
67 def update_fog(_) -> None:
68 server.scene.configure_fog(
69 gui_near.value,
70 gui_far.value,
71 color=gui_color.value,
72 enabled=gui_enabled.value,
73 )
74
75 gui_enabled.on_update(update_fog)
76 gui_near.on_update(update_fog)
77 gui_far.on_update(update_fog)
78 gui_color.on_update(update_fog)
79
80 while True:
81 time.sleep(10.0)
82
83
84if __name__ == "__main__":
85 main()