post_processing/
post_processing.rs

1//! Demonstrates Bevy's built-in postprocessing features.
2//!
3//! Currently, this simply consists of chromatic aberration.
4
5use std::f32::consts::PI;
6
7use bevy::{
8    core_pipeline::post_process::ChromaticAberration, pbr::CascadeShadowConfigBuilder, prelude::*,
9};
10
11/// The number of units per frame to add to or subtract from intensity when the
12/// arrow keys are held.
13const CHROMATIC_ABERRATION_INTENSITY_ADJUSTMENT_SPEED: f32 = 0.002;
14
15/// The maximum supported chromatic aberration intensity level.
16const MAX_CHROMATIC_ABERRATION_INTENSITY: f32 = 0.4;
17
18/// The settings that the user can control.
19#[derive(Resource)]
20struct AppSettings {
21    /// The intensity of the chromatic aberration effect.
22    chromatic_aberration_intensity: f32,
23}
24
25/// The entry point.
26fn main() {
27    App::new()
28        .init_resource::<AppSettings>()
29        .add_plugins(DefaultPlugins.set(WindowPlugin {
30            primary_window: Some(Window {
31                title: "Bevy Chromatic Aberration Example".into(),
32                ..default()
33            }),
34            ..default()
35        }))
36        .add_systems(Startup, setup)
37        .add_systems(Update, handle_keyboard_input)
38        .add_systems(
39            Update,
40            (update_chromatic_aberration_settings, update_help_text)
41                .run_if(resource_changed::<AppSettings>)
42                .after(handle_keyboard_input),
43        )
44        .run();
45}
46
47/// Creates the example scene and spawns the UI.
48fn setup(mut commands: Commands, asset_server: Res<AssetServer>, app_settings: Res<AppSettings>) {
49    // Spawn the camera.
50    spawn_camera(&mut commands, &asset_server);
51
52    // Create the scene.
53    spawn_scene(&mut commands, &asset_server);
54
55    // Spawn the help text.
56    spawn_text(&mut commands, &app_settings);
57}
58
59/// Spawns the camera, including the [`ChromaticAberration`] component.
60fn spawn_camera(commands: &mut Commands, asset_server: &AssetServer) {
61    commands.spawn((
62        Camera3d::default(),
63        Camera {
64            hdr: true,
65            ..default()
66        },
67        Transform::from_xyz(0.7, 0.7, 1.0).looking_at(Vec3::new(0.0, 0.3, 0.0), Vec3::Y),
68        DistanceFog {
69            color: Color::srgb_u8(43, 44, 47),
70            falloff: FogFalloff::Linear {
71                start: 1.0,
72                end: 8.0,
73            },
74            ..default()
75        },
76        EnvironmentMapLight {
77            diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
78            specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
79            intensity: 2000.0,
80            ..default()
81        },
82        // Include the `ChromaticAberration` component.
83        ChromaticAberration::default(),
84    ));
85}
86
87/// Spawns the scene.
88///
89/// This is just the tonemapping test scene, chosen for the fact that it uses a
90/// variety of colors.
91fn spawn_scene(commands: &mut Commands, asset_server: &AssetServer) {
92    // Spawn the main scene.
93    commands.spawn(SceneRoot(asset_server.load(
94        GltfAssetLabel::Scene(0).from_asset("models/TonemappingTest/TonemappingTest.gltf"),
95    )));
96
97    // Spawn the flight helmet.
98    commands.spawn((
99        SceneRoot(
100            asset_server
101                .load(GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf")),
102        ),
103        Transform::from_xyz(0.5, 0.0, -0.5).with_rotation(Quat::from_rotation_y(-0.15 * PI)),
104    ));
105
106    // Spawn the light.
107    commands.spawn((
108        DirectionalLight {
109            illuminance: 15000.0,
110            shadows_enabled: true,
111            ..default()
112        },
113        Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, PI * -0.15, PI * -0.15)),
114        CascadeShadowConfigBuilder {
115            maximum_distance: 3.0,
116            first_cascade_far_bound: 0.9,
117            ..default()
118        }
119        .build(),
120    ));
121}
122
123/// Spawns the help text at the bottom of the screen.
124fn spawn_text(commands: &mut Commands, app_settings: &AppSettings) {
125    commands.spawn((
126        create_help_text(app_settings),
127        Node {
128            position_type: PositionType::Absolute,
129            bottom: Val::Px(12.0),
130            left: Val::Px(12.0),
131            ..default()
132        },
133    ));
134}
135
136impl Default for AppSettings {
137    fn default() -> Self {
138        Self {
139            chromatic_aberration_intensity: ChromaticAberration::default().intensity,
140        }
141    }
142}
143
144/// Creates help text at the bottom of the screen.
145fn create_help_text(app_settings: &AppSettings) -> Text {
146    format!(
147        "Chromatic aberration intensity: {} (Press Left or Right to change)",
148        app_settings.chromatic_aberration_intensity
149    )
150    .into()
151}
152
153/// Handles requests from the user to change the chromatic aberration intensity.
154fn handle_keyboard_input(mut app_settings: ResMut<AppSettings>, input: Res<ButtonInput<KeyCode>>) {
155    let mut delta = 0.0;
156    if input.pressed(KeyCode::ArrowLeft) {
157        delta -= CHROMATIC_ABERRATION_INTENSITY_ADJUSTMENT_SPEED;
158    } else if input.pressed(KeyCode::ArrowRight) {
159        delta += CHROMATIC_ABERRATION_INTENSITY_ADJUSTMENT_SPEED;
160    }
161
162    // If no arrow key was pressed, just bail out.
163    if delta == 0.0 {
164        return;
165    }
166
167    app_settings.chromatic_aberration_intensity = (app_settings.chromatic_aberration_intensity
168        + delta)
169        .clamp(0.0, MAX_CHROMATIC_ABERRATION_INTENSITY);
170}
171
172/// Updates the [`ChromaticAberration`] settings per the [`AppSettings`].
173fn update_chromatic_aberration_settings(
174    mut chromatic_aberration: Query<&mut ChromaticAberration>,
175    app_settings: Res<AppSettings>,
176) {
177    let intensity = app_settings.chromatic_aberration_intensity;
178
179    // Pick a reasonable maximum sample size for the intensity to avoid an
180    // artifact whereby the individual samples appear instead of producing
181    // smooth streaks of color.
182    //
183    // Don't take this formula too seriously; it hasn't been heavily tuned.
184    let max_samples = ((intensity - 0.02) / (0.20 - 0.02) * 56.0 + 8.0)
185        .clamp(8.0, 64.0)
186        .round() as u32;
187
188    for mut chromatic_aberration in &mut chromatic_aberration {
189        chromatic_aberration.intensity = intensity;
190        chromatic_aberration.max_samples = max_samples;
191    }
192}
193
194/// Updates the help text at the bottom of the screen to reflect the current
195/// [`AppSettings`].
196fn update_help_text(mut text: Query<&mut Text>, app_settings: Res<AppSettings>) {
197    for mut text in text.iter_mut() {
198        *text = create_help_text(&app_settings);
199    }
200}