Skip to main content

anisotropy/
anisotropy.rs

1//! Demonstrates anisotropy with the glTF sample barn lamp model.
2
3use std::fmt::Display;
4
5use bevy::{
6    color::palettes::{self, css::WHITE},
7    light::Skybox,
8    math::vec3,
9    prelude::*,
10    time::Stopwatch,
11};
12
13/// The initial position of the camera.
14const CAMERA_INITIAL_POSITION: Vec3 = vec3(-0.4, 0.0, 0.0);
15
16/// The current settings of the app, as chosen by the user.
17#[derive(Resource)]
18struct AppStatus {
19    /// Which type of light is in the scene.
20    light_mode: LightMode,
21    /// Whether anisotropy is enabled.
22    anisotropy_enabled: bool,
23    /// Which mesh is visible
24    visible_scene: Scene,
25}
26
27/// Which type of light we're using: a directional light, a point light, or an
28/// environment map.
29#[derive(Clone, Copy, PartialEq, Default)]
30enum LightMode {
31    /// A rotating directional light.
32    #[default]
33    Directional,
34    /// A rotating point light.
35    Point,
36    /// An environment map (image-based lighting, including skybox).
37    EnvironmentMap,
38}
39
40/// A component that stores the version of the material with anisotropy and the
41/// version of the material without it.
42///
43/// This is placed on each mesh with a material. It exists so that the
44/// appropriate system can replace the materials when the user presses Enter to
45/// turn anisotropy on and off.
46#[derive(Component)]
47struct MaterialVariants {
48    /// The version of the material in the glTF file, with anisotropy.
49    anisotropic: Handle<StandardMaterial>,
50    /// The version of the material with anisotropy removed.
51    isotropic: Handle<StandardMaterial>,
52}
53
54#[derive(Default, Clone, Copy, PartialEq, Eq, Component)]
55enum Scene {
56    #[default]
57    BarnLamp,
58    Sphere,
59}
60
61impl Scene {
62    fn next(&self) -> Self {
63        match self {
64            Self::BarnLamp => Self::Sphere,
65            Self::Sphere => Self::BarnLamp,
66        }
67    }
68}
69
70impl Display for Scene {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        let scene_name = match self {
73            Self::BarnLamp => "Barn Lamp",
74            Self::Sphere => "Sphere",
75        };
76        write!(f, "{scene_name}")
77    }
78}
79
80/// The application entry point.
81fn main() {
82    App::new()
83        .init_resource::<AppStatus>()
84        .add_plugins(DefaultPlugins.set(WindowPlugin {
85            primary_window: Some(Window {
86                title: "Bevy Anisotropy Example".into(),
87                ..default()
88            }),
89            ..default()
90        }))
91        .add_systems(Startup, setup)
92        .add_systems(Update, create_material_variants)
93        .add_systems(Update, animate_light)
94        .add_systems(Update, rotate_camera)
95        .add_systems(Update, (handle_input, update_help_text).chain())
96        .run();
97}
98
99/// Creates the initial scene.
100fn setup(mut commands: Commands, asset_server: Res<AssetServer>, app_status: Res<AppStatus>) {
101    commands.spawn((
102        Camera3d::default(),
103        Transform::from_translation(CAMERA_INITIAL_POSITION).looking_at(Vec3::ZERO, Vec3::Y),
104    ));
105
106    spawn_directional_light(&mut commands);
107
108    commands.spawn((
109        WorldAssetRoot(
110            asset_server.load("models/AnisotropyBarnLamp/AnisotropyBarnLamp.gltf#Scene0"),
111        ),
112        Transform::from_xyz(0.0, 0.07, -0.13),
113        Scene::BarnLamp,
114    ));
115
116    commands.spawn((
117        Mesh3d(
118            asset_server.add(
119                Mesh::from(Sphere::new(0.1))
120                    .with_generated_tangents()
121                    .unwrap(),
122            ),
123        ),
124        MeshMaterial3d(asset_server.add(StandardMaterial {
125            base_color: palettes::tailwind::GRAY_300.into(),
126            anisotropy_rotation: 0.5,
127            anisotropy_strength: 1.,
128            ..default()
129        })),
130        Scene::Sphere,
131        Visibility::Hidden,
132    ));
133
134    spawn_text(&mut commands, &app_status);
135}
136
137/// Spawns the help text.
138fn spawn_text(commands: &mut Commands, app_status: &AppStatus) {
139    commands.spawn((
140        app_status.create_help_text(),
141        Node {
142            position_type: PositionType::Absolute,
143            bottom: px(12),
144            left: px(12),
145            ..default()
146        },
147    ));
148}
149
150/// For each material, creates a version with the anisotropy removed.
151///
152/// This allows the user to press Enter to toggle anisotropy on and off.
153fn create_material_variants(
154    mut commands: Commands,
155    mut materials: ResMut<Assets<StandardMaterial>>,
156    new_meshes: Query<
157        (Entity, &MeshMaterial3d<StandardMaterial>),
158        (
159            Added<MeshMaterial3d<StandardMaterial>>,
160            Without<MaterialVariants>,
161        ),
162    >,
163) {
164    for (entity, anisotropic_material_handle) in new_meshes.iter() {
165        let Some(anisotropic_material) = materials.get(anisotropic_material_handle).cloned() else {
166            continue;
167        };
168
169        commands.entity(entity).insert(MaterialVariants {
170            anisotropic: anisotropic_material_handle.0.clone(),
171            isotropic: materials.add(StandardMaterial {
172                anisotropy_texture: None,
173                anisotropy_strength: 0.0,
174                anisotropy_rotation: 0.0,
175                ..anisotropic_material
176            }),
177        });
178    }
179}
180
181/// A system that animates the light every frame, if there is one.
182fn animate_light(
183    mut lights: Query<&mut Transform, Or<(With<DirectionalLight>, With<PointLight>)>>,
184    time: Res<Time>,
185) {
186    let now = time.elapsed_secs();
187    for mut transform in lights.iter_mut() {
188        transform.translation = vec3(ops::cos(now), 1.0, ops::sin(now)) * vec3(3.0, 4.0, 3.0);
189        transform.look_at(Vec3::ZERO, Vec3::Y);
190    }
191}
192
193/// A system that rotates the camera if the environment map is enabled.
194fn rotate_camera(
195    mut camera: Query<&mut Transform, With<Camera>>,
196    app_status: Res<AppStatus>,
197    time: Res<Time>,
198    mut stopwatch: Local<Stopwatch>,
199) {
200    if app_status.light_mode == LightMode::EnvironmentMap {
201        stopwatch.tick(time.delta());
202    }
203
204    let now = stopwatch.elapsed_secs();
205    for mut transform in camera.iter_mut() {
206        *transform = Transform::from_translation(
207            Quat::from_rotation_y(now).mul_vec3(CAMERA_INITIAL_POSITION),
208        )
209        .looking_at(Vec3::ZERO, Vec3::Y);
210    }
211}
212
213/// Handles requests from the user to change the lighting or toggle anisotropy.
214fn handle_input(
215    mut commands: Commands,
216    asset_server: Res<AssetServer>,
217    cameras: Query<Entity, With<Camera>>,
218    lights: Query<Entity, Or<(With<DirectionalLight>, With<PointLight>)>>,
219    mut meshes: Query<(&mut MeshMaterial3d<StandardMaterial>, &MaterialVariants)>,
220    mut scenes: Query<(&mut Visibility, &Scene)>,
221    keyboard: Res<ButtonInput<KeyCode>>,
222    mut app_status: ResMut<AppStatus>,
223) {
224    // If Space was pressed, change the lighting.
225    if keyboard.just_pressed(KeyCode::Space) {
226        match app_status.light_mode {
227            LightMode::Directional => {
228                // Switch to a point light. Despawn all existing lights and
229                // create the light point.
230                app_status.light_mode = LightMode::Point;
231                for light in lights.iter() {
232                    commands.entity(light).despawn();
233                }
234                spawn_point_light(&mut commands);
235            }
236
237            LightMode::Point => {
238                // Switch to the environment map. Despawn all existing lights,
239                // and create the skybox and environment map.
240                app_status.light_mode = LightMode::EnvironmentMap;
241                for light in lights.iter() {
242                    commands.entity(light).despawn();
243                }
244                for camera in cameras.iter() {
245                    add_skybox_and_environment_map(&mut commands, &asset_server, camera);
246                }
247            }
248
249            LightMode::EnvironmentMap => {
250                // Switch back to a directional light. Despawn the skybox and
251                // environment map light, and recreate the directional light.
252                app_status.light_mode = LightMode::Directional;
253                for camera in cameras.iter() {
254                    commands
255                        .entity(camera)
256                        .remove::<Skybox>()
257                        .remove::<EnvironmentMapLight>();
258                }
259                spawn_directional_light(&mut commands);
260            }
261        }
262    }
263
264    // If Enter was pressed, toggle anisotropy on and off.
265    if keyboard.just_pressed(KeyCode::Enter) {
266        app_status.anisotropy_enabled = !app_status.anisotropy_enabled;
267
268        // Go through each mesh and alter its material.
269        for (mut material_handle, material_variants) in meshes.iter_mut() {
270            material_handle.0 = if app_status.anisotropy_enabled {
271                material_variants.anisotropic.clone()
272            } else {
273                material_variants.isotropic.clone()
274            }
275        }
276    }
277
278    if keyboard.just_pressed(KeyCode::KeyQ) {
279        app_status.visible_scene = app_status.visible_scene.next();
280        for (mut visibility, scene) in scenes.iter_mut() {
281            let new_vis = if *scene == app_status.visible_scene {
282                Visibility::Inherited
283            } else {
284                Visibility::Hidden
285            };
286            *visibility = new_vis;
287        }
288    }
289}
290
291/// A system that updates the help text based on the current app status.
292fn update_help_text(mut text_query: Query<&mut Text>, app_status: Res<AppStatus>) {
293    for mut text in text_query.iter_mut() {
294        *text = app_status.create_help_text();
295    }
296}
297
298/// Adds the skybox and environment map to the scene.
299fn add_skybox_and_environment_map(
300    commands: &mut Commands,
301    asset_server: &AssetServer,
302    entity: Entity,
303) {
304    commands
305        .entity(entity)
306        .insert(Skybox {
307            brightness: 5000.0,
308            image: Some(asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2")),
309            ..default()
310        })
311        .insert(EnvironmentMapLight {
312            diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
313            specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
314            intensity: 2500.0,
315            ..default()
316        });
317}
318
319/// Spawns a rotating directional light.
320fn spawn_directional_light(commands: &mut Commands) {
321    commands.spawn(DirectionalLight {
322        color: WHITE.into(),
323        illuminance: 3000.0,
324        ..default()
325    });
326}
327
328/// Spawns a rotating point light.
329fn spawn_point_light(commands: &mut Commands) {
330    commands.spawn(PointLight {
331        color: WHITE.into(),
332        intensity: 200000.0,
333        ..default()
334    });
335}
336
337impl AppStatus {
338    /// Creates the help text as appropriate for the current app status.
339    fn create_help_text(&self) -> Text {
340        // Choose the appropriate help text for the anisotropy toggle.
341        let material_variant_help_text = if self.anisotropy_enabled {
342            "Press Enter to disable anisotropy"
343        } else {
344            "Press Enter to enable anisotropy"
345        };
346
347        // Choose the appropriate help text for the light toggle.
348        let light_help_text = match self.light_mode {
349            LightMode::Directional => "Press Space to switch to a point light",
350            LightMode::Point => "Press Space to switch to an environment map",
351            LightMode::EnvironmentMap => "Press Space to switch to a directional light",
352        };
353
354        // Choose the appropriate help text for the scene selector.
355        let mesh_help_text = format!("Press Q to change to {}", self.visible_scene.next());
356
357        // Build the `Text` object.
358        format!("{material_variant_help_text}\n{light_help_text}\n{mesh_help_text}",).into()
359    }
360}
361
362impl Default for AppStatus {
363    fn default() -> Self {
364        Self {
365            light_mode: default(),
366            anisotropy_enabled: true,
367            visible_scene: default(),
368        }
369    }
370}