aboutsummaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: 65dfc80f82ad2432774f09acabe5dc6272822108 (plain)
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
67
68
69
70
71
72
73
74
75
76
77
78
use bevy::{
    asset::embedded_asset,
    prelude::*,
    render::render_resource::{AsBindGroup, ShaderType},
};

pub struct BlacklightPlugin;

impl Plugin for BlacklightPlugin {
    fn build(&self, app: &mut App) {
        embedded_asset!(app, "../assets/shaders/blacklight_material.wgsl");
        app.add_plugins(MaterialPlugin::<BlacklightMaterial>::default()).add_systems(Update, update_shader_blacklight_data);
    }
}

#[derive(Component, Debug)]
pub struct Blacklight;

#[derive(Clone, Debug, ShaderType)]
pub struct BlacklightData {
    pub position: Vec3,
    pub direction: Vec3,
    pub color: Vec4,
    pub range: f32,
    pub radius: f32,
}

#[derive(Asset, TypePath, AsBindGroup, Debug, Clone)]
pub struct BlacklightMaterial {
    #[storage(0, read_only)]
    pub lights: Vec<BlacklightData>,
    #[texture(1)]
    #[sampler(2)]
    pub base_texture: Option<Handle<Image>>,
    pub alpha_mode: AlphaMode,
}

impl Default for BlacklightMaterial {
    fn default() -> Self {
        Self {
            lights: vec![],
            base_texture: None,
            alpha_mode: AlphaMode::Blend,
        }
    }
}

impl Material for BlacklightMaterial {
    fn fragment_shader() -> bevy::render::render_resource::ShaderRef {
        "embedded://bevy_blacklight_material/../assets/shaders/blacklight_material.wgsl".into()
    }

    fn alpha_mode(&self) -> AlphaMode {
        self.alpha_mode
    }
}

fn update_shader_blacklight_data(
    blacklight_query: Query<(&ViewVisibility, &GlobalTransform, &Transform, &SpotLight), With<Blacklight>>,
    blacklight_material_query: Query<&Handle<BlacklightMaterial>>,
    mut blacklight_materials: ResMut<Assets<BlacklightMaterial>>,
) {
    let light_data = blacklight_query
        .iter()
        .filter(|(visibility, _, _, _)| visibility.get())
        .map(|(_, global_transform, transform, light)| BlacklightData {
            position: global_transform.translation(),
            direction: *global_transform.forward(),
            color: light.color.to_srgba().to_vec4(),
            range: light.range,
            radius: light.radius,
        })
        .collect::<Vec<_>>();
    for handle in blacklight_material_query.iter() {
        let material = blacklight_materials.get_mut(handle).unwrap();
        material.lights = light_data.clone();
    }
}