buildling health bars
This commit is contained in:
parent
6c0ac7f66d
commit
56a4f8b597
10 changed files with 581 additions and 10 deletions
430
crates/ui_health_bar/src/lib.rs
Normal file
430
crates/ui_health_bar/src/lib.rs
Normal file
|
|
@ -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::<BarMaterial>::default());
|
||||
|
||||
load_internal_asset!(
|
||||
app,
|
||||
BAR_SHADER_HANDLE,
|
||||
"../../../assets/shaders/bar.wgsl",
|
||||
Shader::from_wgsl
|
||||
);
|
||||
|
||||
app.init_resource::<MeshHandles>()
|
||||
.init_resource::<ColorScheme>()
|
||||
.register_type::<BarSettings>()
|
||||
.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<Shader> =
|
||||
weak_handle!("c41a3557-a08d-4e56-b2aa-708e27acaeaa");
|
||||
|
||||
#[derive(Component)]
|
||||
struct WithBar(Entity);
|
||||
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn spawn(
|
||||
mut commands: Commands,
|
||||
mut materials: ResMut<Assets<BarMaterial>>,
|
||||
mut meshes: ResMut<Assets<Mesh>>,
|
||||
mut mesh_handles: ResMut<MeshHandles>,
|
||||
color_scheme: Res<ColorScheme>,
|
||||
query: Query<(Entity, &Health, &BarSettings), (Changed<Health>, Without<WithBar>)>,
|
||||
) {
|
||||
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<Assets<BarMaterial>>,
|
||||
parent_query: Query<(&WithBar, &Health), Changed<Health>>,
|
||||
bar_query: Query<&MeshMaterial3d<BarMaterial>>,
|
||||
) {
|
||||
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<Assets<BarMaterial>>,
|
||||
mut meshes: ResMut<Assets<Mesh>>,
|
||||
mut mesh_handles: ResMut<MeshHandles>,
|
||||
parent_query: Query<(&WithBar, &BarSettings), Changed<BarSettings>>,
|
||||
bar_query: Query<(Entity, &MeshMaterial3d<BarMaterial>, &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<Health>,
|
||||
parent_query: Query<&WithBar>,
|
||||
query: Query<(Entity, &Health, &WithBar), (Changed<Health>, With<WithBar>)>,
|
||||
) {
|
||||
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::<WithBar>();
|
||||
}
|
||||
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<MeshMaterial3d<BarMaterial>>>,
|
||||
q_transform: Query<&Transform, Without<MeshMaterial3d<BarMaterial>>>,
|
||||
) {
|
||||
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::<Health>::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::<Mana>::new().foreground_color(ForegroundColor::Static(BLUE.into()));
|
||||
/// let health_scheme = ColorScheme::<Health>::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<Self>,
|
||||
descriptor: &mut RenderPipelineDescriptor,
|
||||
layout: &MeshVertexBufferLayoutRef,
|
||||
key: MaterialPipelineKey<Self>,
|
||||
) -> 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<u32, Handle<Mesh>>);
|
||||
|
||||
impl MeshHandles {
|
||||
pub fn get(&self, width: u32) -> Option<Mesh3d> {
|
||||
self.0.get(&width).cloned().map(Mesh3d)
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, width: u32, handle: Handle<Mesh>) -> Mesh3d {
|
||||
self.0.insert(width, handle.clone());
|
||||
|
||||
Mesh3d(handle)
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue