1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use super::selection::*;
use bevy::{prelude::*, render::color::Color};

#[derive(Clone, Debug, Default)]
pub struct PickableButton {
    initial_material: Handle<StandardMaterial>,
}

pub struct MeshButtonMaterials {
    pub hovered: Handle<StandardMaterial>,
    pub pressed: Handle<StandardMaterial>,
    pub selected: Handle<StandardMaterial>,
}

impl FromWorld for MeshButtonMaterials {
    fn from_world(world: &mut World) -> Self {
        let mut materials = world
            .get_resource_mut::<Assets<StandardMaterial>>()
            .unwrap();
        MeshButtonMaterials {
            hovered: materials.add(Color::rgb(0.35, 0.35, 0.35).into()),
            pressed: materials.add(Color::rgb(0.35, 0.75, 0.35).into()),
            selected: materials.add(Color::rgb(0.35, 0.35, 0.75).into()),
        }
    }
}

pub fn get_initial_mesh_button_material(
    mut query: Query<(&mut PickableButton, &Handle<StandardMaterial>), Added<PickableButton>>,
) {
    for (mut button, material) in query.iter_mut() {
        button.initial_material = material.clone();
    }
}

#[allow(clippy::type_complexity)]
pub fn mesh_highlighting(
    button_materials: Res<MeshButtonMaterials>,
    mut interaction_query: Query<
        (
            &Interaction,
            &mut Handle<StandardMaterial>,
            Option<&Selection>,
            &PickableButton,
        ),
        Or<(Changed<Interaction>, Changed<Selection>)>,
    >,
) {
    for (interaction, mut material, selection, button) in interaction_query.iter_mut() {
        *material = match *interaction {
            Interaction::Clicked => button_materials.pressed.clone(),
            Interaction::Hovered => button_materials.hovered.clone(),
            Interaction::None => {
                if let Some(selection) = selection {
                    if selection.selected() {
                        button_materials.selected.clone()
                    } else {
                        button.initial_material.clone()
                    }
                } else {
                    button.initial_material.clone()
                }
            }
        }
    }
}