From afa8cad4cf778673633f95885f5da095ba96039f Mon Sep 17 00:00:00 2001 From: Silas Bartha Date: Sun, 24 Nov 2024 18:20:03 -0500 Subject: Initial Commit --- src/lib.rs | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 src/lib.rs (limited to 'src/lib.rs') diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..65dfc80 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,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::::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, + #[texture(1)] + #[sampler(2)] + pub base_texture: Option>, + 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_material_query: Query<&Handle>, + mut blacklight_materials: ResMut>, +) { + 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::>(); + for handle in blacklight_material_query.iter() { + let material = blacklight_materials.get_mut(handle).unwrap(); + material.lights = light_data.clone(); + } +} -- cgit v1.2.3