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