Skip to content

Commit 510fce9

Browse files
authored
Allow fog density texture to be scrolled over time with an offset (bevyengine#14868)
# Objective - The goal of this PR is to make it possible to move the density texture of a `FogVolume` over time in order to create dynamic effects like fog moving in the wind. - You could theoretically move the `FogVolume` itself, but this is not ideal, because the `FogVolume` AABB would eventually leave the area. If you want an area to remain foggy while also creating the impression that the fog is moving in the wind, a scrolling density texture is a better solution. ## Solution - The PR adds a `density_texture_offset` field to the `FogVolume` component. This offset is in the UVW coordinates of the density texture, meaning that a value of `(0.5, 0.0, 0.0)` moves the 3d texture by half along the x-axis. - Values above 1.0 are wrapped, a 1.5 offset is the same as a 0.5 offset. This makes it so that the density texture wraps around on the other side, meaning that a repeating 3d noise texture can seamlessly scroll forever. It also makes it easy to move the density texture over time by simply increasing the offset every frame. ## Testing - A `scrolling_fog` example has been added to demonstrate the feature. It uses the offset to scroll a repeating 3d noise density texture to create the impression of fog moving in the wind. - The camera is looking at a pillar with the sun peaking behind it. This highlights the effect the changing density has on the volumetric lighting interactions. - Temporal anti-aliasing combined with the `jitter` option of `VolumetricFogSettings` is used to improve the quality of the effect. --- ## Showcase https://github.com/user-attachments/assets/3aa50ebd-771c-4c99-ab5d-255c0c3be1a8
1 parent e4b7408 commit 510fce9

File tree

7 files changed

+151
-1
lines changed

7 files changed

+151
-1
lines changed

Cargo.toml

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3330,6 +3330,17 @@ description = "Demonstrates fog volumes"
33303330
category = "3D Rendering"
33313331
wasm = false
33323332

3333+
[[example]]
3334+
name = "scrolling_fog"
3335+
path = "examples/3d/scrolling_fog.rs"
3336+
doc-scrape-examples = true
3337+
3338+
[package.metadata.example.scrolling_fog]
3339+
name = "Scrolling fog"
3340+
description = "Demonstrates how to create the effect of fog moving in the wind"
3341+
category = "3D Rendering"
3342+
wasm = false
3343+
33333344
[[example]]
33343345
name = "physics_in_fixed_timestep"
33353346
path = "examples/movement/physics_in_fixed_timestep.rs"

assets/volumes/fog_noise.ktx2

1 MB
Binary file not shown.

crates/bevy_pbr/src/volumetric_fog/mod.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,8 +150,20 @@ pub struct FogVolume {
150150
/// The default value is 0.1.
151151
pub density_factor: f32,
152152

153+
/// Optional 3D voxel density texture for the fog.
153154
pub density_texture: Option<Handle<Image>>,
154155

156+
/// Configurable offset of the density texture in UVW coordinates. Values 1.0 or higher
157+
/// will be wrapped into the (0.0..1.0) range.
158+
///
159+
/// This can be used to scroll a repeating density texture in a direction over time
160+
/// to create effects like fog moving in the wind.
161+
///
162+
/// Has no effect when no density texture is present.
163+
///
164+
/// The default value is (0, 0, 0).
165+
pub density_texture_offset: Vec3,
166+
155167
/// The absorption coefficient, which measures what fraction of light is
156168
/// absorbed by the fog at each step.
157169
///
@@ -268,6 +280,7 @@ impl Default for FogVolume {
268280
scattering: 0.3,
269281
density_factor: 0.1,
270282
density_texture: None,
283+
density_texture_offset: Vec3::ZERO,
271284
scattering_asymmetry: 0.5,
272285
fog_color: Color::WHITE,
273286
light_tint: Color::WHITE,

crates/bevy_pbr/src/volumetric_fog/render.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,7 @@ pub struct VolumetricFogUniform {
183183
absorption: f32,
184184
scattering: f32,
185185
density: f32,
186+
density_texture_offset: Vec3,
186187
scattering_asymmetry: f32,
187188
light_intensity: f32,
188189
jitter_strength: f32,
@@ -727,6 +728,7 @@ pub fn prepare_volumetric_fog_uniforms(
727728
absorption: fog_volume.absorption,
728729
scattering: fog_volume.scattering,
729730
density: fog_volume.density_factor,
731+
density_texture_offset: fog_volume.density_texture_offset,
730732
scattering_asymmetry: fog_volume.scattering_asymmetry,
731733
light_intensity: fog_volume.light_intensity,
732734
jitter_strength: volumetric_fog_settings.jitter,

crates/bevy_pbr/src/volumetric_fog/volumetric_fog.wgsl

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ struct VolumetricFog {
4343
absorption: f32,
4444
scattering: f32,
4545
density_factor: f32,
46+
density_texture_offset: vec3<f32>,
4647
scattering_asymmetry: f32,
4748
light_intensity: f32,
4849
jitter_strength: f32,
@@ -101,6 +102,7 @@ fn fragment(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
101102
let absorption = volumetric_fog.absorption;
102103
let scattering = volumetric_fog.scattering;
103104
let density_factor = volumetric_fog.density_factor;
105+
let density_texture_offset = volumetric_fog.density_texture_offset;
104106
let light_tint = volumetric_fog.light_tint;
105107
let light_intensity = volumetric_fog.light_intensity;
106108
let jitter_strength = volumetric_fog.jitter_strength;
@@ -236,7 +238,11 @@ fn fragment(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
236238
// case.
237239
let P_uvw = Ro_uvw + Rd_step_uvw * f32(step);
238240
if (all(P_uvw >= vec3(0.0)) && all(P_uvw <= vec3(1.0))) {
239-
density *= textureSample(density_texture, density_sampler, P_uvw).r;
241+
// Add density texture offset and wrap values exceeding the (0, 0, 0) to (1, 1, 1) range.
242+
var uvw = P_uvw + density_texture_offset;
243+
uvw -= floor(uvw);
244+
245+
density *= textureSample(density_texture, density_sampler, uvw).r;
240246
} else {
241247
density = 0.0;
242248
}

examples/3d/scrolling_fog.rs

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
//! Showcases a `FogVolume`'s density texture being scrolled over time to create
2+
//! the effect of fog moving in the wind.
3+
//!
4+
//! The density texture is a repeating 3d noise texture and the `density_texture_offset`
5+
//! is moved every frame to achieve this.
6+
//!
7+
//! The example also utilizes the jitter option of `VolumetricFogSettings` in tandem
8+
//! with temporal anti-aliasing to improve the visual quality of the effect.
9+
//!
10+
//! The camera is looking at a pillar with the sun peaking behind it. The light
11+
//! interactions change based on the density of the fog.
12+
13+
use bevy::core_pipeline::bloom::BloomSettings;
14+
use bevy::core_pipeline::experimental::taa::{TemporalAntiAliasBundle, TemporalAntiAliasPlugin};
15+
use bevy::pbr::{DirectionalLightShadowMap, FogVolume, VolumetricFogSettings, VolumetricLight};
16+
use bevy::prelude::*;
17+
18+
/// Initializes the example.
19+
fn main() {
20+
App::new()
21+
.add_plugins(DefaultPlugins.set(WindowPlugin {
22+
primary_window: Some(Window {
23+
title: "Bevy Scrolling Fog".into(),
24+
..default()
25+
}),
26+
..default()
27+
}))
28+
.insert_resource(DirectionalLightShadowMap { size: 4096 })
29+
.add_plugins(TemporalAntiAliasPlugin)
30+
.add_systems(Startup, setup)
31+
.add_systems(Update, scroll_fog)
32+
.run();
33+
}
34+
35+
/// Spawns all entities into the scene.
36+
fn setup(
37+
mut commands: Commands,
38+
mut meshes: ResMut<Assets<Mesh>>,
39+
mut materials: ResMut<Assets<StandardMaterial>>,
40+
assets: Res<AssetServer>,
41+
) {
42+
// Spawn camera with temporal anti-aliasing and a VolumetricFogSettings configuration.
43+
commands.spawn((
44+
Camera3dBundle {
45+
transform: Transform::from_xyz(0.0, 2.0, 0.0)
46+
.looking_at(Vec3::new(-5.0, 3.5, -6.0), Vec3::Y),
47+
camera: Camera {
48+
hdr: true,
49+
..default()
50+
},
51+
msaa: Msaa::Off,
52+
..default()
53+
},
54+
TemporalAntiAliasBundle::default(),
55+
BloomSettings::default(),
56+
VolumetricFogSettings {
57+
ambient_intensity: 0.0,
58+
jitter: 0.5,
59+
..default()
60+
},
61+
));
62+
63+
// Spawn a directional light shining at the camera with the VolumetricLight component.
64+
commands.spawn((
65+
DirectionalLightBundle {
66+
transform: Transform::from_xyz(-5.0, 5.0, -7.0)
67+
.looking_at(Vec3::new(0.0, 0.0, 0.0), Vec3::Y),
68+
directional_light: DirectionalLight {
69+
shadows_enabled: true,
70+
..default()
71+
},
72+
..default()
73+
},
74+
VolumetricLight,
75+
));
76+
77+
// Spawn ground mesh.
78+
commands.spawn(PbrBundle {
79+
transform: Transform::from_xyz(0.0, -0.5, 0.0),
80+
mesh: meshes.add(Cuboid::new(64.0, 1.0, 64.0)),
81+
material: materials.add(StandardMaterial {
82+
base_color: Color::BLACK,
83+
perceptual_roughness: 1.0,
84+
..default()
85+
}),
86+
..default()
87+
});
88+
89+
// Spawn pillar standing between the camera and the sun.
90+
commands.spawn(PbrBundle {
91+
transform: Transform::from_xyz(-10.0, 4.5, -11.0),
92+
mesh: meshes.add(Cuboid::new(2.0, 9.0, 2.0)),
93+
material: materials.add(Color::BLACK),
94+
..default()
95+
});
96+
97+
// Spawn FogVolume with repeating 3d noise density texture.
98+
commands.spawn((
99+
SpatialBundle {
100+
visibility: Visibility::Visible,
101+
transform: Transform::from_xyz(0.0, 32.0, 0.0).with_scale(Vec3::splat(64.0)),
102+
..default()
103+
},
104+
FogVolume {
105+
density_texture: Some(assets.load("volumes/fog_noise.ktx2")),
106+
density_factor: 0.05,
107+
..default()
108+
},
109+
));
110+
}
111+
112+
/// Moves fog density texture offset every frame.
113+
fn scroll_fog(time: Res<Time>, mut query: Query<&mut FogVolume>) {
114+
for mut fog_volume in query.iter_mut() {
115+
fog_volume.density_texture_offset += Vec3::new(0.0, 0.0, 0.04) * time.delta_seconds();
116+
}
117+
}

examples/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,7 @@ Example | Description
162162
[Rotate Environment Map](../examples/3d/rotate_environment_map.rs) | Demonstrates how to rotate the skybox and the environment map simultaneously
163163
[Screen Space Ambient Occlusion](../examples/3d/ssao.rs) | A scene showcasing screen space ambient occlusion
164164
[Screen Space Reflections](../examples/3d/ssr.rs) | Demonstrates screen space reflections with water ripples
165+
[Scrolling fog](../examples/3d/scrolling_fog.rs) | Demonstrates how to create the effect of fog moving in the wind
165166
[Shadow Biases](../examples/3d/shadow_biases.rs) | Demonstrates how shadow biases affect shadows in a 3d scene
166167
[Shadow Caster and Receiver](../examples/3d/shadow_caster_receiver.rs) | Demonstrates how to prevent meshes from casting/receiving shadows in a 3d scene
167168
[Skybox](../examples/3d/skybox.rs) | Load a cubemap texture onto a cube like a skybox and cycle through different compressed texture formats.

0 commit comments

Comments
 (0)