Skip to content

Commit

Permalink
Do suggestion on edit_material_on_gltf
Browse files Browse the repository at this point in the history
  • Loading branch information
hukasu committed Feb 4, 2025
1 parent d68527b commit 2d7ce24
Showing 1 changed file with 19 additions and 14 deletions.
33 changes: 19 additions & 14 deletions examples/3d/edit_material_on_gltf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,27 +21,26 @@ fn main() {
.run();
}

/// Overrides the color of the `StandardMaterial` of a mesh
/// This is added to a [`SceneRoot`] and will cause the [`StandardMaterial::base_color`] of all materials
#[derive(Component)]
struct ColorOverride(Color);

fn setup_scene(mut commands: Commands, asset_server: Res<AssetServer>) {
// Camera
commands.spawn((
Camera3d::default(),
Transform::from_xyz(0., 1., 2.5).looking_at(Vec3::new(0., 0.25, 0.), Dir3::Y),
));

// Directional light
commands.spawn((
DirectionalLight::default(),
Transform::from_xyz(0., 1., 0.25).looking_at(Vec3::ZERO, Dir3::Y),
));

// Flight Helmets
commands.spawn((SceneRoot(asset_server.load(
// This model will keep its original material
commands.spawn(SceneRoot(asset_server.load(
GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf"),
)),));
)));
// This model will be tinted red
commands.spawn((
SceneRoot(
asset_server
Expand All @@ -50,6 +49,7 @@ fn setup_scene(mut commands: Commands, asset_server: Res<AssetServer>) {
Transform::from_xyz(-1.25, 0., 0.),
ColorOverride(palettes::tailwind::RED_300.into()),
));
// This model will be tinted green
commands.spawn((
SceneRoot(
asset_server
Expand All @@ -65,25 +65,30 @@ fn change_material(
mut commands: Commands,
children: Query<&Children>,
color_override: Query<&ColorOverride>,
materials: Query<&MeshMaterial3d<StandardMaterial>>,
mut standard_materials: ResMut<Assets<StandardMaterial>>,
mesh_materials: Query<&MeshMaterial3d<StandardMaterial>>,
mut asset_materials: ResMut<Assets<StandardMaterial>>,
) {
// Get the `ColorOverride` of the entity, if it does not have a color override, skip
let Ok(color_override) = color_override.get(trigger.target()) else {
return;
};

for child in children.iter_descendants(trigger.target()) {
if let Some(material) = materials
.get(child)
// Iterate over all children recursively
for descendants in children.iter_descendants(trigger.target()) {
// Get the material of the descendant
if let Some(material) = mesh_materials
.get(descendants)
.ok()
.and_then(|id| standard_materials.get_mut(id.id()))
.and_then(|id| asset_materials.get_mut(id.id()))
{
// Create a copy of the material and override base color
let mut new_material = material.clone();
new_material.base_color = color_override.0;

// Override `MeshMaterial3d` with new material
commands
.entity(child)
.insert(MeshMaterial3d(standard_materials.add(new_material)));
.entity(descendants)
.insert(MeshMaterial3d(asset_materials.add(new_material)));
}
}
}

0 comments on commit 2d7ce24

Please sign in to comment.