Allow fog density texture to be scrolled over time with an offset (#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
This commit is contained in:
Jiří Švejda 2024-08-22 20:43:14 +01:00 committed by GitHub
parent e4b740840f
commit 510fce9af3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 151 additions and 1 deletions

View file

@ -3330,6 +3330,17 @@ description = "Demonstrates fog volumes"
category = "3D Rendering"
wasm = false
[[example]]
name = "scrolling_fog"
path = "examples/3d/scrolling_fog.rs"
doc-scrape-examples = true
[package.metadata.example.scrolling_fog]
name = "Scrolling fog"
description = "Demonstrates how to create the effect of fog moving in the wind"
category = "3D Rendering"
wasm = false
[[example]]
name = "physics_in_fixed_timestep"
path = "examples/movement/physics_in_fixed_timestep.rs"

Binary file not shown.

View file

@ -150,8 +150,20 @@ pub struct FogVolume {
/// The default value is 0.1.
pub density_factor: f32,
/// Optional 3D voxel density texture for the fog.
pub density_texture: Option<Handle<Image>>,
/// Configurable offset of the density texture in UVW coordinates. Values 1.0 or higher
/// will be wrapped into the (0.0..1.0) range.
///
/// This can be used to scroll a repeating density texture in a direction over time
/// to create effects like fog moving in the wind.
///
/// Has no effect when no density texture is present.
///
/// The default value is (0, 0, 0).
pub density_texture_offset: Vec3,
/// The absorption coefficient, which measures what fraction of light is
/// absorbed by the fog at each step.
///
@ -268,6 +280,7 @@ impl Default for FogVolume {
scattering: 0.3,
density_factor: 0.1,
density_texture: None,
density_texture_offset: Vec3::ZERO,
scattering_asymmetry: 0.5,
fog_color: Color::WHITE,
light_tint: Color::WHITE,

View file

@ -183,6 +183,7 @@ pub struct VolumetricFogUniform {
absorption: f32,
scattering: f32,
density: f32,
density_texture_offset: Vec3,
scattering_asymmetry: f32,
light_intensity: f32,
jitter_strength: f32,
@ -727,6 +728,7 @@ pub fn prepare_volumetric_fog_uniforms(
absorption: fog_volume.absorption,
scattering: fog_volume.scattering,
density: fog_volume.density_factor,
density_texture_offset: fog_volume.density_texture_offset,
scattering_asymmetry: fog_volume.scattering_asymmetry,
light_intensity: fog_volume.light_intensity,
jitter_strength: volumetric_fog_settings.jitter,

View file

@ -43,6 +43,7 @@ struct VolumetricFog {
absorption: f32,
scattering: f32,
density_factor: f32,
density_texture_offset: vec3<f32>,
scattering_asymmetry: f32,
light_intensity: f32,
jitter_strength: f32,
@ -101,6 +102,7 @@ fn fragment(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
let absorption = volumetric_fog.absorption;
let scattering = volumetric_fog.scattering;
let density_factor = volumetric_fog.density_factor;
let density_texture_offset = volumetric_fog.density_texture_offset;
let light_tint = volumetric_fog.light_tint;
let light_intensity = volumetric_fog.light_intensity;
let jitter_strength = volumetric_fog.jitter_strength;
@ -236,7 +238,11 @@ fn fragment(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
// case.
let P_uvw = Ro_uvw + Rd_step_uvw * f32(step);
if (all(P_uvw >= vec3(0.0)) && all(P_uvw <= vec3(1.0))) {
density *= textureSample(density_texture, density_sampler, P_uvw).r;
// Add density texture offset and wrap values exceeding the (0, 0, 0) to (1, 1, 1) range.
var uvw = P_uvw + density_texture_offset;
uvw -= floor(uvw);
density *= textureSample(density_texture, density_sampler, uvw).r;
} else {
density = 0.0;
}

View file

@ -0,0 +1,117 @@
//! Showcases a `FogVolume`'s density texture being scrolled over time to create
//! the effect of fog moving in the wind.
//!
//! The density texture is a repeating 3d noise texture and the `density_texture_offset`
//! is moved every frame to achieve this.
//!
//! The example also utilizes the jitter option of `VolumetricFogSettings` in tandem
//! with temporal anti-aliasing to improve the visual quality of the effect.
//!
//! The camera is looking at a pillar with the sun peaking behind it. The light
//! interactions change based on the density of the fog.
use bevy::core_pipeline::bloom::BloomSettings;
use bevy::core_pipeline::experimental::taa::{TemporalAntiAliasBundle, TemporalAntiAliasPlugin};
use bevy::pbr::{DirectionalLightShadowMap, FogVolume, VolumetricFogSettings, VolumetricLight};
use bevy::prelude::*;
/// Initializes the example.
fn main() {
App::new()
.add_plugins(DefaultPlugins.set(WindowPlugin {
primary_window: Some(Window {
title: "Bevy Scrolling Fog".into(),
..default()
}),
..default()
}))
.insert_resource(DirectionalLightShadowMap { size: 4096 })
.add_plugins(TemporalAntiAliasPlugin)
.add_systems(Startup, setup)
.add_systems(Update, scroll_fog)
.run();
}
/// Spawns all entities into the scene.
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
assets: Res<AssetServer>,
) {
// Spawn camera with temporal anti-aliasing and a VolumetricFogSettings configuration.
commands.spawn((
Camera3dBundle {
transform: Transform::from_xyz(0.0, 2.0, 0.0)
.looking_at(Vec3::new(-5.0, 3.5, -6.0), Vec3::Y),
camera: Camera {
hdr: true,
..default()
},
msaa: Msaa::Off,
..default()
},
TemporalAntiAliasBundle::default(),
BloomSettings::default(),
VolumetricFogSettings {
ambient_intensity: 0.0,
jitter: 0.5,
..default()
},
));
// Spawn a directional light shining at the camera with the VolumetricLight component.
commands.spawn((
DirectionalLightBundle {
transform: Transform::from_xyz(-5.0, 5.0, -7.0)
.looking_at(Vec3::new(0.0, 0.0, 0.0), Vec3::Y),
directional_light: DirectionalLight {
shadows_enabled: true,
..default()
},
..default()
},
VolumetricLight,
));
// Spawn ground mesh.
commands.spawn(PbrBundle {
transform: Transform::from_xyz(0.0, -0.5, 0.0),
mesh: meshes.add(Cuboid::new(64.0, 1.0, 64.0)),
material: materials.add(StandardMaterial {
base_color: Color::BLACK,
perceptual_roughness: 1.0,
..default()
}),
..default()
});
// Spawn pillar standing between the camera and the sun.
commands.spawn(PbrBundle {
transform: Transform::from_xyz(-10.0, 4.5, -11.0),
mesh: meshes.add(Cuboid::new(2.0, 9.0, 2.0)),
material: materials.add(Color::BLACK),
..default()
});
// Spawn FogVolume with repeating 3d noise density texture.
commands.spawn((
SpatialBundle {
visibility: Visibility::Visible,
transform: Transform::from_xyz(0.0, 32.0, 0.0).with_scale(Vec3::splat(64.0)),
..default()
},
FogVolume {
density_texture: Some(assets.load("volumes/fog_noise.ktx2")),
density_factor: 0.05,
..default()
},
));
}
/// Moves fog density texture offset every frame.
fn scroll_fog(time: Res<Time>, mut query: Query<&mut FogVolume>) {
for mut fog_volume in query.iter_mut() {
fog_volume.density_texture_offset += Vec3::new(0.0, 0.0, 0.04) * time.delta_seconds();
}
}

View file

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