bevy_stat_bars 0.3.1

plugin for drawing floating stat bars
Documentation
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
mod extraction;

use bevy::prelude::*;
use std::marker::PhantomData;

/// Insert as a resource to set z depth of Statbars
pub struct StatbarDepth(pub f32);

/// Implement `StatbarObservable` for a component you want to visualise with a stat bar.
/// Should return a value between 0.0 (= empty) and 1.0 (= full).
/// If the value is larger or smaller it is clamped before rendering.
pub trait StatbarObservable {
    fn get_statbar_value(&self) -> f32;
}

/// Insert this component to observe components from another entity.
/// Does not have a generic parameter for a marker component.
///
/// Overrides any local observeable components.
/// Overriden by StatbarObserveParent.
///
/// Does not have a marker component because I think it would be very confusing to have
/// an entity with three statbars observing components on three other entities.
/// If you really want a many to one capability, it should be trivial to write your own system.
#[derive(Component, Reflect)]
pub struct StatbarObserveEntity(pub Entity);

/// Insert this component to observe components from the entities parent.
/// Overrides any local obversable components and StatbarObservedEntity.
#[derive(Component, Reflect)]
pub struct StatbarObserveParent;

// observe a resource that implements 'StatbarOversable'
#[derive(Reflect)]
pub struct StatbarObserveResource<T>
where
    T: 'static,
{
    #[reflect(ignore)]
    #[doc(hidden)]
    pub _phantom: PhantomData<fn() -> T>,
}

impl<T> Default for StatbarObserveResource<T>
where
    T: 'static,
{
    fn default() -> Self {
        Self {
            _phantom: Default::default(),
        }
    }
}

/// Insert this component to add a statbar to an entity.
/// Multiple statbars can be inserted on a single entity by using different marker components.
#[derive(Component, Reflect)]
#[reflect(Component)]
pub struct Statbar<T = ()>
where
    T: 'static,
{
    /// color of the full part of the bar
    pub color: Color,
    /// color of the empty part of the bar
    pub empty_color: Color,
    /// length of the bar
    pub length: f32,
    /// thickness of the bar
    pub thickness: f32,
    /// absolute displacement from the GlobalTransform's position
    /// not part of the transform hierarchy, won't be scaled or rotated.
    pub displacement: Vec2,
    /// false => horizontally orientated bar,
    /// true => vertically orientated bar,
    pub vertical: bool,
    /// false =>
    /// * horizontal bar increasing from left to right
    /// * vertical bar increasing from bottom to top
    /// true =>
    /// * horizontal bar increasing from right to left
    /// * vertical bar increasing from bottom to top
    pub reverse: bool,
    /// if true, do not draw
    pub hide: bool,
    /// value of bar
    /// * 0.0 => bar entirely colored with empty color
    /// * 0.75 => bar three quarters full color, one quarter empty color
    /// * 1.0 => bar entity colored with full color
    pub value: f32,
    #[reflect(ignore)]
    #[doc(hidden)]
    pub _phantom: PhantomData<fn() -> T>,
}

impl<T> Default for Statbar<T> {
    fn default() -> Self {
        Self {
            color: Color::YELLOW,
            empty_color: Color::rgb(0.2, 0.2, 0.0),
            length: 100.,
            thickness: 16.,
            displacement: Vec2::ZERO,
            vertical: false,
            reverse: false,
            hide: false,
            value: 0.75,
            _phantom: PhantomData,
        }
    }
}

/// Adds a border around the corresponding Statbar
#[derive(Clone, Copy, Debug, Component, Reflect)]
#[reflect(Component)]
pub struct StatbarBorder<T>
where
    T: 'static,
{
    /// color of the border
    pub color: Color,
    /// thickness of the border on the left
    left: f32,
    /// thickness of the border on the right
    right: f32,
    /// thickness of the border on the bottom
    bottom: f32,
    /// thickness of the border on the top
    top: f32,
    #[reflect(ignore)]
    phantom: PhantomData<fn() -> T>,
}

impl<T> StatbarBorder<T>
where
    T: 'static,
{
    /// A StarbarBorder with the same thickness on all four sides
    pub fn all(color: Color, thickness: f32) -> Self {
        Self {
            color,
            left: thickness,
            right: thickness,
            bottom: thickness,
            top: thickness,
            phantom: PhantomData,
        }
    }
}

impl<T> Default for StatbarBorder<T>
where
    T: 'static,
{
    fn default() -> Self {
        Self::all(Color::WHITE, 2.0)
    }
}

/// Linearly interpolate the value of the bar color
/// between `min` and `max` using the value of the Statbar
/// * statbar.value == 0. => statbar.color == min
/// * statbar.value == 1. => statbar.color == max
#[derive(Clone, Copy, Debug, Component, Reflect)]
#[reflect(Component)]
pub struct StatbarColorLerp<T>
where
    T: 'static,
{
    /// bar color when value is 0.0
    pub min: Color,
    /// bar color when value is 1.0
    pub max: Color,
    #[reflect(ignore)]
    phantom: PhantomData<fn() -> T>,
}

impl<T> Default for StatbarColorLerp<T>
where
    T: 'static,
{
    fn default() -> Self {
        Self {
            min: Color::RED,
            max: Color::GREEN,
            phantom: Default::default(),
        }
    }
}

impl<T> StatbarColorLerp<T>
where
    T: 'static,
{
    pub fn new(min: Color, max: Color) -> Self {
        Self {
            min,
            max,
            phantom: Default::default(),
        }
    }
}

/// Change the statbar color depending on the value of the statbar's subject
///
/// Could be used for a health bar that
/// turns to red when the character has less than 25% health remaining.
#[derive(Clone, Copy, Debug, Component, Reflect)]
#[reflect(Component)]
pub struct StatbarColorSwitch<T>
where
    T: 'static,
{
    /// * `statbar.value <= pivot`
    ///     => sets bar's color to `low`
    /// * `piviot < statbar.value
    ///     => sets bar's color to `high`
    pub pivot: f32,
    /// statbar color when the statbar's value is less than or equal to pivot
    pub low: Color,
    /// statbar color when the statbar's value is greater than pivot
    pub high: Color,
    #[reflect(ignore)]
    phantom: PhantomData<fn() -> T>,
}

impl<T> Default for StatbarColorSwitch<T>
where
    T: 'static,
{
    fn default() -> Self {
        Self {
            pivot: 0.25,
            low: Color::RED,
            high: Color::GREEN,
            phantom: Default::default(),
        }
    }
}

impl<T> StatbarColorSwitch<T>
where
    T: 'static,
{
    pub fn new(pivot: f32, low: Color, high: Color) -> Self {
        Self {
            pivot,
            low,
            high,
            phantom: Default::default(),
        }
    }
}

fn switch_stat_bar_colors<T>(
    mut color_switch_query: Query<
        (&mut Statbar<T>, &mut StatbarColorSwitch<T>),
        Changed<Statbar<T>>,
    >,
) where
    T: 'static,
{
    color_switch_query.for_each_mut(|(mut bar, switcher)| {
        bar.color = if bar.value <= switcher.pivot {
            switcher.low
        } else {
            switcher.high
        };
    });
}

fn lerp_stat_bar_colors<T>(
    mut color_lerp_query: Query<(&mut Statbar<T>, &mut StatbarColorLerp<T>), Changed<Statbar<T>>>,
) where
    T: 'static,
{
    color_lerp_query.for_each_mut(|(mut bar, lerper)| {
        bar.color = Vec4::from(lerper.min)
            .lerp(lerper.max.into(), bar.value)
            .into();
    });
}

fn update_statbar_values<T>(
    mut statbar_query: Query<
        (&mut Statbar<T>, &T),
        (
            Changed<T>,
            Without<StatbarObserveParent>,
            Without<StatbarObserveEntity>,
        ),
    >,
) where
    T: Component + StatbarObservable,
{
    statbar_query.for_each_mut(|(mut statbar, value)| {
        statbar.value = value.get_statbar_value();
    });
}

fn update_statbar_values_from_parents<T>(
    mut statbar_query: Query<
        (&mut Statbar<T>, &Parent),
        (With<StatbarObserveParent>, Without<StatbarObserveEntity>),
    >,
    parent_value_query: Query<&T, Changed<T>>,
) where
    T: Component + StatbarObservable,
{
    statbar_query.for_each_mut(|(mut statbar, parent)| {
        if let Ok(value) = parent_value_query.get(parent.get()) {
            statbar.value = value.get_statbar_value();
        }
    });
}

fn update_statbar_values_from_other<T>(
    mut statbar_query: Query<
        (&mut Statbar<T>, &StatbarObserveEntity),
        Without<StatbarObserveParent>,
    >,
    other_value_query: Query<&T, Changed<T>>,
) where
    T: Component + StatbarObservable,
{
    statbar_query.for_each_mut(|(mut statbar, &StatbarObserveEntity(target))| {
        if let Ok(value) = other_value_query.get(target) {
            statbar.value = value.get_statbar_value();
        }
    });
}

fn update_statbar_from_resource<T>(resource: Res<T>, mut statbar_query: Query<&mut Statbar<T>>)
where
    T: StatbarObservable + 'static + Send + Sync,
{
    if resource.is_changed() {
        statbar_query.for_each_mut(|mut statbar| {
            statbar.value = resource.get_statbar_value();
        });
    }
}

#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemLabel)]
pub enum StatbarSystem {
    UpdateValues,
    UpdateColors,
    ExtractSprites,
}

pub trait RegisterStatbarSubject {
    fn add_statbar_component_observer<T: StatbarObservable + Component>(&mut self) -> &mut Self;
    fn add_statbar_resource_observer<T: StatbarObservable + 'static + Send + Sync>(
        &mut self,
    ) -> &mut Self;
    fn add_standalone_statbar<T: 'static>(&mut self) -> &mut Self;
}

impl RegisterStatbarSubject for App {
    fn add_statbar_component_observer<T: StatbarObservable + Component>(&mut self) -> &mut Self {
        if let Ok(render_app) = self.get_sub_app_mut(bevy::render::RenderApp) {
            render_app.add_system_to_stage(
                bevy::render::RenderStage::Extract,
                extraction::extract_stat_bars::<T>
                    .after(bevy::sprite::SpriteSystem::ExtractSprites),
            );
        }

        self.register_type::<Statbar<T>>()
            .register_type::<StatbarBorder<T>>()
            .register_type::<StatbarColorLerp<T>>()
            .register_type::<StatbarColorSwitch<T>>()
            .add_system_to_stage(
                CoreStage::PostUpdate,
                update_statbar_values::<T>.label(StatbarSystem::UpdateValues),
            )
            .add_system_to_stage(
                CoreStage::PostUpdate,
                update_statbar_values_from_other::<T>.label(StatbarSystem::UpdateValues),
            )
            .add_system_to_stage(
                CoreStage::PostUpdate,
                update_statbar_values_from_parents::<T>.label(StatbarSystem::UpdateValues),
            )
            .add_system_to_stage(
                CoreStage::PostUpdate,
                switch_stat_bar_colors::<T>
                    .after(StatbarSystem::UpdateValues)
                    .label(StatbarSystem::UpdateColors),
            )
            .add_system_to_stage(
                CoreStage::PostUpdate,
                lerp_stat_bar_colors::<T>
                    .after(StatbarSystem::UpdateValues)
                    .label(StatbarSystem::UpdateColors),
            )
    }

    fn add_statbar_resource_observer<T: StatbarObservable + 'static + Send + Sync>(
        &mut self,
    ) -> &mut Self {
        if let Ok(render_app) = self.get_sub_app_mut(bevy::render::RenderApp) {
            render_app.add_system_to_stage(
                bevy::render::RenderStage::Extract,
                extraction::extract_stat_bars::<T>
                    .after(bevy::sprite::SpriteSystem::ExtractSprites),
            );
        }

        self.register_type::<Statbar<T>>()
            .register_type::<StatbarBorder<T>>()
            .register_type::<StatbarColorLerp<T>>()
            .register_type::<StatbarColorSwitch<T>>()
            .add_system_to_stage(
                CoreStage::PostUpdate,
                update_statbar_from_resource::<T>.label(StatbarSystem::UpdateValues),
            )
            .add_system_to_stage(
                CoreStage::PostUpdate,
                switch_stat_bar_colors::<T>
                    .after(StatbarSystem::UpdateValues)
                    .label(StatbarSystem::UpdateColors),
            )
            .add_system_to_stage(
                CoreStage::PostUpdate,
                lerp_stat_bar_colors::<T>
                    .after(StatbarSystem::UpdateValues)
                    .label(StatbarSystem::UpdateColors),
            )
    }

    fn add_standalone_statbar<T: 'static>(&mut self) -> &mut Self {
        if let Ok(render_app) = self.get_sub_app_mut(bevy::render::RenderApp) {
            render_app.add_system_to_stage(
                bevy::render::RenderStage::Extract,
                extraction::extract_stat_bars::<T>
                    .after(bevy::sprite::SpriteSystem::ExtractSprites),
            );
        }

        self.register_type::<Statbar<T>>()
            .register_type::<StatbarBorder<T>>()
            .register_type::<StatbarColorLerp<T>>()
            .register_type::<StatbarColorSwitch<T>>()
            .add_system_to_stage(
                CoreStage::PostUpdate,
                switch_stat_bar_colors::<T>.label(StatbarSystem::UpdateColors),
            )
            .add_system_to_stage(
                CoreStage::PostUpdate,
                lerp_stat_bar_colors::<T>.label(StatbarSystem::UpdateColors),
            )
    }
}