diff --git a/Cargo.lock b/Cargo.lock index 457e035..d464352 100755 --- a/Cargo.lock +++ b/Cargo.lock @@ -1630,6 +1630,7 @@ dependencies = [ "input", "resources", "state", + "ui_health_bar", "upgrade", ] @@ -2012,6 +2013,7 @@ dependencies = [ "state", "ui", "ui_debug", + "ui_health_bar", "ui_ingame", "ui_pause", "ui_state", @@ -5289,6 +5291,14 @@ dependencies = [ "state", ] +[[package]] +name = "ui_health_bar" +version = "0.1.0" +dependencies = [ + "bevy", + "combat", +] + [[package]] name = "ui_ingame" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 60961f2..1456ab4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -56,4 +56,5 @@ resources = { path = "crates/resources" } building_barrager = { path = "crates/building_barrager" } resource_graveyard = { path = "crates/resource_graveyard" } upgrade = { path = "crates/upgrade" } +ui_health_bar = { path = "crates/ui_health_bar" } #new internal crates go here diff --git a/assets/settings/input_map.ron b/assets/settings/input_map.ron index b82ce27..03d50a5 100755 --- a/assets/settings/input_map.ron +++ b/assets/settings/input_map.ron @@ -1,22 +1,22 @@ ( map: { - MouseButton(Middle): [ - CameraOrbitEnable, - ], KeyCode(ShiftLeft): [ MultiPlaceTower, ], - KeyCode(F1): [ - ToggleDebugUI, - ], MouseButton(Right): [ PlaceTower, ], + MouseButton(Left): [ + CameraPanEnable, + ], + MouseButton(Middle): [ + CameraOrbitEnable, + ], MouseScroll: [ CameraZoom, ], - MouseButton(Left): [ - CameraPanEnable, + KeyCode(F1): [ + ToggleDebugUI, ], MouseMovementX: [ CameraYaw, diff --git a/assets/shaders/bar.wgsl b/assets/shaders/bar.wgsl new file mode 100644 index 0000000..296dd18 --- /dev/null +++ b/assets/shaders/bar.wgsl @@ -0,0 +1,102 @@ +#import bevy_pbr::{ + mesh_view_bindings::view, + mesh_functions::get_world_from_local +} + +// taken from https://github.com/sparten11740/bevy_health_bar3d/blob/main/assets/shaders/bar.wgsl +// MIT license + +@group(2) @binding(0) +var value_and_dimensions: vec4; +@group(2) @binding(1) +var background_color: vec4; +@group(2) @binding(2) +var high_color: vec4; +@group(2) @binding(3) +var moderate_color: vec4; +@group(2) @binding(4) +var low_color: vec4; +@group(2) @binding(5) +var offset: vec4; +#ifdef HAS_BORDER +@group(2) @binding(6) +var border_color: vec4; +#endif + +struct Vertex { + @builtin(instance_index) instance_index: u32, + @location(0) position: vec3, + @location(1) uv: vec2, +}; + +struct VertexOutput { + @builtin(position) clip_position: vec4, + @location(0) uv: vec2 +}; + +@vertex +fn vertex(vertex: Vertex) -> VertexOutput { + var out: VertexOutput; + + let clip_from_world = view.clip_from_world; + let camera_right = normalize(vec3(clip_from_world[0].x, clip_from_world[1].x, clip_from_world[2].x)); + let camera_up = normalize(vec3(clip_from_world[0].y, clip_from_world[1].y, clip_from_world[2].y)); + + let world_space = camera_right * (vertex.position.x + offset.x) + camera_up * (vertex.position.y + offset.y); + let position = view.clip_from_world * get_world_from_local(vertex.instance_index) * vec4(world_space, 1.); + + out.uv = vertex.uv; + out.clip_position = position; + + return out; +} + +struct FragmentInput { + @location(0) uv: vec2 +}; + +@fragment +fn fragment(in: FragmentInput) -> @location(0) vec4 { + let value = value_and_dimensions.x; + #ifdef HAS_BORDER + let resolution = value_and_dimensions.yz; + let border_width = value_and_dimensions.w; + let border_y = border_width / resolution.y; + let border_x = border_width / resolution.x; + + if in.uv.y < border_y || in.uv.y > 1. - border_y || in.uv.x < border_x || in.uv.x > 1. - border_x { + return border_color; + } + #endif + + #ifdef IS_VERTICAL + let val = 1.0 - value; + if in.uv.y < val { + return background_color; + } + + if val > 0.6 { + return low_color; + } + + if val > 0.2 { + return moderate_color; + } + + return high_color; + #else + if in.uv.x > value { + return background_color; + } + + if value < 0.4 { + return low_color; + } + + if value < 0.8 { + return moderate_color; + } + + return high_color; + #endif +} diff --git a/crates/building/Cargo.toml b/crates/building/Cargo.toml index 84d5799..6322521 100755 --- a/crates/building/Cargo.toml +++ b/crates/building/Cargo.toml @@ -11,6 +11,7 @@ state = { path = "../state" } resources = { path = "../resources" } input = { path = "../input" } upgrade = { path = "../upgrade" } +ui_health_bar = { path = "../ui_health_bar" } [lints] workspace = true diff --git a/crates/building/src/lib.rs b/crates/building/src/lib.rs index 5ea4c6d..4325ddc 100755 --- a/crates/building/src/lib.rs +++ b/crates/building/src/lib.rs @@ -12,6 +12,7 @@ use combat::{Health, Team}; use input::Selectable; use resources::{Cost, Resources}; use state::GameSystemSet; +use ui_health_bar::BarSettings; use upgrade::{Upgradable, UpgradeTree}; pub struct BuildingPlugin; @@ -234,6 +235,11 @@ fn place_building( RigidBody::Static, Team::Core.collision_layers(), Upgradable::new(*info_entity), + BarSettings { + offset: size_v3.y / 2. + 0.5, + width: (size_v3.x.max(size_v3.z) * 8.).ceil() as u32, + ..default() + }, )) .id(); building_map.place_building(*location, info, *info_entity, instance); diff --git a/crates/combat/src/lib.rs b/crates/combat/src/lib.rs index 41d0663..ca9bf79 100755 --- a/crates/combat/src/lib.rs +++ b/crates/combat/src/lib.rs @@ -23,7 +23,8 @@ impl Plugin for CombatPlugin { FixedUpdate, tick_invulnerability.in_set(GameSystemSet::StatusEffects), ) - .register_type::(); + .register_type::() + .register_type::(); } } @@ -68,7 +69,7 @@ pub struct Died { pub slayer: Option, } -#[derive(Component, Clone, Debug)] +#[derive(Component, Clone, Debug, Reflect)] #[require(InvulnerabilityTime)] pub struct Health { pub max: f32, @@ -82,6 +83,13 @@ impl Health { current: health, } } + + pub fn percentage(&self) -> f32 { + if self.max == 0. { + return 1.; + } + self.current / self.max + } } impl Default for Health { diff --git a/crates/ui_health_bar/Cargo.toml b/crates/ui_health_bar/Cargo.toml new file mode 100644 index 0000000..a94b412 --- /dev/null +++ b/crates/ui_health_bar/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "ui_health_bar" +version = "0.1.0" +edition = "2024" + +[dependencies] +bevy = { workspace = true } + +combat = { path = "../combat" } + +[lints] +workspace = true diff --git a/crates/ui_health_bar/src/lib.rs b/crates/ui_health_bar/src/lib.rs new file mode 100644 index 0000000..6601293 --- /dev/null +++ b/crates/ui_health_bar/src/lib.rs @@ -0,0 +1,430 @@ +// based on https://github.com/sparten11740/bevy_health_bar3d/ +// stripped down to be more fit for my use case + +use bevy::asset::{load_internal_asset, weak_handle}; +use bevy::pbr::{MaterialPipeline, MaterialPipelineKey, NotShadowCaster, NotShadowReceiver}; +use bevy::platform::collections::HashMap; +use bevy::prelude::*; +use bevy::render::mesh::*; +use bevy::render::render_resource::{ + AsBindGroup, RenderPipelineDescriptor, ShaderRef, SpecializedMeshPipelineError, +}; +use combat::Health; + +pub struct UiHealthBarPlugin; + +impl Plugin for UiHealthBarPlugin { + fn build(&self, app: &mut App) { + app.add_plugins(MaterialPlugin::::default()); + + load_internal_asset!( + app, + BAR_SHADER_HANDLE, + "../../../assets/shaders/bar.wgsl", + Shader::from_wgsl + ); + + app.init_resource::() + .init_resource::() + .register_type::() + .add_systems(PostUpdate, reset_rotation) + .add_systems(Update, (spawn, remove, update, update_settings)); + } +} + +pub const DEFAULT_BACKGROUND_COLOR: Color = Color::srgba(0., 0., 0., 0.75); +pub const DEFAULT_BORDER_COLOR: Color = Color::srgba(0.02, 0.02, 0.02, 0.95); +pub const DEFAULT_HIGH_COLOR: Color = Color::srgba(0., 1., 0., 0.95); +pub const DEFAULT_MODERATE_COLOR: Color = Color::srgba(1., 1., 0., 0.95); +pub const DEFAULT_LOW_COLOR: Color = Color::srgba(1., 0., 0., 0.95); + +pub(crate) const BAR_SHADER_HANDLE: Handle = + weak_handle!("c41a3557-a08d-4e56-b2aa-708e27acaeaa"); + +#[derive(Component)] +struct WithBar(Entity); + +#[allow(clippy::type_complexity)] +fn spawn( + mut commands: Commands, + mut materials: ResMut>, + mut meshes: ResMut>, + mut mesh_handles: ResMut, + color_scheme: Res, + query: Query<(Entity, &Health, &BarSettings), (Changed, Without)>, +) { + query.iter().for_each(|(entity, health, settings)| { + if health.current == health.max { + // don't create health bar if their health is full + return; + } + let width = settings.normalized_width(); + let height = settings.normalized_height(); + let key_width = settings.width; + let mesh = mesh_handles.get(key_width).unwrap_or_else(|| { + mesh_handles.insert( + key_width, + meshes.add(Mesh::from(Rectangle::new(width, height))), + ) + }); + + let (high, moderate, low) = match color_scheme.foreground_color { + ForegroundColor::Static(color) => (color, color, color), + ForegroundColor::TriSpectrum { + high, + moderate, + low, + } => (high, moderate, low), + }; + + let material = materials.add(BarMaterial { + value_and_dimensions: (health.percentage(), width, height, settings.border.width) + .into(), + background_color: color_scheme.background_color.into(), + high_color: high.into(), + moderate_color: moderate.into(), + low_color: low.into(), + vertical: false, + offset: settings.normalized_offset().extend(0.), + border_color: settings.border.color.into(), + }); + + let health_bar = commands + .spawn(( + Name::new("Health Bar"), + Mesh3d(mesh.0), + MeshMaterial3d(material), + NotShadowCaster, + NotShadowReceiver, + )) + .id(); + + commands + .entity(entity) + .insert(WithBar(health_bar)) + .add_child(health_bar); + }); +} + +fn update( + mut materials: ResMut>, + parent_query: Query<(&WithBar, &Health), Changed>, + bar_query: Query<&MeshMaterial3d>, +) { + parent_query.iter().for_each(|(bar, health)| { + let Ok(material_handle) = bar_query.get(bar.0) else { + return; + }; + let material = materials.get_mut(material_handle).unwrap(); + material.value_and_dimensions.x = health.percentage(); + }); +} + +fn update_settings( + mut commands: Commands, + mut materials: ResMut>, + mut meshes: ResMut>, + mut mesh_handles: ResMut, + parent_query: Query<(&WithBar, &BarSettings), Changed>, + bar_query: Query<(Entity, &MeshMaterial3d, &Mesh3d)>, +) { + parent_query.iter().for_each(|(bar, settings)| { + let Ok((entity, material_handle, mesh_handle)) = bar_query.get(bar.0) else { + return; + }; + + let material = materials.get_mut(material_handle).unwrap(); + let offset = settings.normalized_offset().extend(0.); + let width = settings.normalized_width(); + let key_width = settings.width; + let height = settings.normalized_height(); + + let mesh_for_settings_dimensions = mesh_handles.get(key_width); + let mesh_changed = mesh_for_settings_dimensions == Some(mesh_handle.clone()); + + if mesh_changed { + let new_mesh = mesh_for_settings_dimensions.unwrap_or(mesh_handles.insert( + key_width, + meshes.add(Mesh::from(Rectangle::new(width, height))), + )); + commands.entity(entity).insert(new_mesh); + material.value_and_dimensions.y = width; + material.value_and_dimensions.z = height; + } + + material.offset = offset; + material.border_color = settings.border.color.into(); + material.value_and_dimensions.w = settings.border.width; + material.vertical = false; + }); +} + +fn remove( + mut commands: Commands, + mut removals: RemovedComponents, + parent_query: Query<&WithBar>, + query: Query<(Entity, &Health, &WithBar), (Changed, With)>, +) { + for (entity, health, WithBar(bar_entity)) in query.iter() { + if health.current >= health.max { + if let Ok(mut ec) = commands.get_entity(entity) { + ec.remove::(); + } + if let Ok(mut bar_ec) = commands.get_entity(*bar_entity) { + bar_ec.despawn(); + } + } + } + removals.read().for_each(|entity| { + let Ok(&WithBar(bar_entity)) = parent_query.get(entity) else { + return; + }; + + if commands.get_entity(bar_entity).is_err() { + return; + } + + commands.entity(bar_entity).despawn() + }); +} + +fn reset_rotation( + mut bar_query: Query<(&ChildOf, &mut Transform), With>>, + q_transform: Query<&Transform, Without>>, +) { + for (child_of, mut transform) in bar_query.iter_mut() { + if let Ok(parent_transform) = q_transform.get(child_of.parent()) { + transform.rotation = parent_transform.rotation.inverse(); + } + } +} + +/// Component to configure a bar +#[derive(Component, Debug, Clone, Reflect)] +pub struct BarSettings { + /// Configure the width of the bar each number = 0.125 world units + pub width: u32, + /// Configures the offset of the bar relative to the entity its attached to. + /// For horizontal bars, this is an offset along the y-axis, for vertical bars along the x-axis. + pub offset: f32, + pub border: BarBorder, +} + +impl BarSettings { + fn world_width(&self) -> f32 { + self.width as f32 * 0.125 + } + + pub fn normalized_height(&self) -> f32 { + 0.125 + } + + pub fn normalized_width(&self) -> f32 { + self.world_width() + } + + pub fn normalized_offset(&self) -> Vec3 { + self.offset * Vec3::Y + } +} + +impl Default for BarSettings { + fn default() -> Self { + Self { + width: 16, + offset: 2.0, + border: default(), + } + } +} + +/// Describes the border of a bar. Defaults to no border +#[derive(Debug, Clone, Reflect)] +pub struct BarBorder { + pub width: f32, + pub color: Color, +} + +impl BarBorder { + pub fn new(width: f32) -> Self { + Self { + width, + color: DEFAULT_BORDER_COLOR, + } + } + + pub fn color(mut self, color: Color) -> Self { + self.color = color; + self + } +} + +impl Default for BarBorder { + fn default() -> Self { + Self { + width: 0., + color: DEFAULT_BORDER_COLOR, + } + } +} + +/// ForegroundColor enum. The foreground color can either be static or a tri-color spectrum +/// The tri-color spectrum defines three colors: high, moderate, and low. +/// The high color is applied when the tracked component's value is more than or equal to 80%, +/// moderate when it's between 40% and 80%, and low when it is less than 40%. +#[derive(Debug, Clone, Reflect)] +pub enum ForegroundColor { + Static(Color), + TriSpectrum { + high: Color, + moderate: Color, + low: Color, + }, +} + +/// Resource to customize the appearance of bars per tracked component type. +#[derive(Resource, Debug, Clone, Reflect)] +pub struct ColorScheme { + pub foreground_color: ForegroundColor, + pub background_color: Color, +} + +impl ColorScheme { + /// Returns a default initialized ColorScheme for the given component type + /// + /// # Examples + /// + /// ``` + /// use bevy_health_bar3d::prelude::ColorScheme; + /// let color_scheme = ColorScheme::::new(); + /// ``` + pub fn new() -> Self { + Self { ..default() } + } + + pub fn background_color(mut self, color: Color) -> Self { + self.background_color = color; + self + } + + /// Sets the foreground color to either a static value or a tri-color spectrum + /// + /// # Examples + /// + /// ``` + /// use bevy::prelude::Color; + /// use bevy_health_bar3d::prelude::{ColorScheme, ForegroundColor}; + /// let mana_scheme = ColorScheme::::new().foreground_color(ForegroundColor::Static(BLUE.into())); + /// let health_scheme = ColorScheme::::new().foreground_color(ForegroundColor::TriSpectrum { + /// high: GREEN.into(), + /// moderate: YELLOW.into(), + /// low: RED.into(), + /// }); + /// ``` + pub fn foreground_color(mut self, color: ForegroundColor) -> Self { + self.foreground_color = color; + self + } +} + +impl Default for ColorScheme { + fn default() -> Self { + Self { + foreground_color: ForegroundColor::TriSpectrum { + high: DEFAULT_HIGH_COLOR, + moderate: DEFAULT_MODERATE_COLOR, + low: DEFAULT_LOW_COLOR, + }, + background_color: DEFAULT_BACKGROUND_COLOR, + } + } +} + +#[derive(Asset, AsBindGroup, Debug, Clone, Reflect)] +#[bind_group_data(BarMaterialKey)] +pub(crate) struct BarMaterial { + #[uniform(0)] + pub value_and_dimensions: Vec4, + // (value, width, height, border_width) vec4 to be 16byte aligned + #[uniform(1)] + pub background_color: LinearRgba, + #[uniform(2)] + pub high_color: LinearRgba, + #[uniform(3)] + pub moderate_color: LinearRgba, + #[uniform(4)] + pub low_color: LinearRgba, + #[uniform(5)] + pub offset: Vec4, + #[uniform(6)] + pub border_color: LinearRgba, + pub vertical: bool, +} + +#[derive(Eq, PartialEq, Hash, Clone)] +pub(crate) struct BarMaterialKey { + vertical: bool, + border: bool, +} + +impl From<&BarMaterial> for BarMaterialKey { + fn from(material: &BarMaterial) -> Self { + Self { + vertical: material.vertical, + border: material.value_and_dimensions.w > 0., + } + } +} + +impl Material for BarMaterial { + fn vertex_shader() -> ShaderRef { + BAR_SHADER_HANDLE.into() + } + + fn fragment_shader() -> ShaderRef { + BAR_SHADER_HANDLE.into() + } + + fn alpha_mode(&self) -> AlphaMode { + AlphaMode::Blend + } + + fn specialize( + _pipeline: &MaterialPipeline, + descriptor: &mut RenderPipelineDescriptor, + layout: &MeshVertexBufferLayoutRef, + key: MaterialPipelineKey, + ) -> Result<(), SpecializedMeshPipelineError> { + let vertex_layout = layout.0.get_layout(&[ + Mesh::ATTRIBUTE_POSITION.at_shader_location(0), + Mesh::ATTRIBUTE_UV_0.at_shader_location(1), + ])?; + + let fragment = descriptor.fragment.as_mut().unwrap(); + if key.bind_group_data.vertical { + fragment.shader_defs.push("IS_VERTICAL".into()); + } + + if key.bind_group_data.border { + fragment.shader_defs.push("HAS_BORDER".into()); + } + + descriptor.vertex.buffers = vec![vertex_layout]; + Ok(()) + } +} + +#[derive(Resource, Default)] +pub(crate) struct MeshHandles(pub HashMap>); + +impl MeshHandles { + pub fn get(&self, width: u32) -> Option { + self.0.get(&width).cloned().map(Mesh3d) + } + + pub fn insert(&mut self, width: u32, handle: Handle) -> Mesh3d { + self.0.insert(width, handle.clone()); + + Mesh3d(handle) + } +} diff --git a/src/main.rs b/src/main.rs index 3d628f0..c62f49f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -37,6 +37,7 @@ fn main() { building_barrager::BuildingBarragerPlugin, resource_graveyard::ResourceGraveyardPlugin, upgrade::UpgradePlugin, + ui_health_bar::UiHealthBarPlugin, // new internal crates go here ));