Skip to content

Commit

Permalink
simplify animated_material example (bevyengine#11576)
Browse files Browse the repository at this point in the history
# Objective

- example `animated_material` is more complex that needed to show how to
animate materials
- it makes CI crash because it uses too much memory

## Solution

- Simplify the example
  • Loading branch information
mockersf authored Jan 28, 2024
1 parent eb8de36 commit 79a2e5e
Showing 1 changed file with 13 additions and 31 deletions.
44 changes: 13 additions & 31 deletions examples/3d/animated_material.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
//! Shows how to animate material properties

use bevy::prelude::*;
use bevy::utils::HashSet;

fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.add_systems(Update, (animate_materials, make_materials_unique))
.add_systems(Update, animate_materials)
.run();
}

fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
commands.spawn((
Camera3dBundle {
transform: Transform::from_xyz(3.0, 1.0, 3.0)
Expand All @@ -25,11 +29,12 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
},
));

let helmet = asset_server.load("models/FlightHelmet/FlightHelmet.gltf#Scene0");
for x in -2..3 {
for z in -2..3 {
commands.spawn(SceneBundle {
scene: helmet.clone(),
let cube = meshes.add(shape::Cube { size: 0.5 });
for x in -1..2 {
for z in -1..2 {
commands.spawn(PbrBundle {
mesh: cube.clone(),
material: materials.add(Color::WHITE),
transform: Transform::from_translation(Vec3::new(x as f32, 0.0, z as f32)),
..default()
});
Expand All @@ -50,29 +55,6 @@ fn animate_materials(
0.5,
);
material.base_color = color;
material.emissive = color;
}
}
}

/// This is needed because by default assets are loaded with shared materials
/// But we want to animate every helmet independently of the others, so we must duplicate the materials
fn make_materials_unique(
mut material_handles: Query<&mut Handle<StandardMaterial>>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut ran: Local<bool>,
) {
if *ran {
return;
}
let mut set = HashSet::new();
for mut material_handle in material_handles.iter_mut() {
if set.contains(&material_handle.id()) {
let material = materials.get(&*material_handle).unwrap().clone();
*material_handle = materials.add(material);
} else {
set.insert(material_handle.id());
}
*ran = true;
}
}

0 comments on commit 79a2e5e

Please sign in to comment.