voxel-framework 0.13.2

A reusable voxel engine framework built on Bevy
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
//! Explicit item icons and the optional inventory-backed hotbar.
use std::{collections::HashMap, marker::PhantomData};

use bevy::ecs::message::MessageReader;
use bevy::prelude::*;
use bevy::ui::UiTransform;

use crate::items::{
    Container, ContainerComponent, HotbarState, ItemPickedUp, ItemType, PrimaryContainer,
};
use crate::voxel::VoxelType;

use super::{HotbarSlot, HotbarUiRoot, SlotContent, spawn_hotbar_ui};
use crate::ui::UiFonts;
use crate::ui::fonts::{UiFontRole, register_ui_fonts};

/// Explicit item-to-icon colors in linear RGBA. No byte-id or name inference is used.
///
/// An unregistered occupied item renders a generic `?`, even if it implements
/// `ItemType::color`. Use [`Self::register_voxel`] to reuse a material palette
/// without duplicating its color constants. Registration samples the voxel's
/// current color; register again if the game changes its palette.
#[derive(Resource, Debug)]
pub struct ItemIconPalette<I: ItemType> {
    colors: HashMap<I, [f32; 4]>,
}

impl<I: ItemType> Default for ItemIconPalette<I> {
    fn default() -> Self {
        Self {
            colors: HashMap::new(),
        }
    }
}

impl<I: ItemType> ItemIconPalette<I> {
    /// Creates an empty icon palette.
    pub fn new() -> Self {
        Self::default()
    }

    /// Registers/replaces a color. Channels follow the `VoxelType::color`
    /// contract: linear RGBA values in [0, 1].
    pub fn register(&mut self, item: I, color: [f32; 4]) {
        self.colors.insert(item, color);
    }

    /// Explicitly associates an item with any voxel material's color.
    /// The item and voxel types and their byte ids can differ.
    pub fn register_voxel<V: VoxelType>(&mut self, item: I, voxel: V) {
        self.register(item, voxel.color());
    }

    /// Returns the explicitly registered color, or None for a generic icon.
    pub fn color(&self, item: I) -> Option<[f32; 4]> {
        self.colors.get(&item).copied()
    }

    /// Removes an association; occupied slots revert to the generic symbol.
    pub fn remove(&mut self, item: I) -> Option<[f32; 4]> {
        self.colors.remove(&item)
    }
}

/// Optional reaction of a hotbar slot to a pickup: a brief change of scale.
///
/// [`HotbarContentPlugin`] initializes this resource disabled. Insert your own
/// value (before or after the plugin) to enable it; it is read every frame.
/// The framework only provides the mechanism: both values come from the game.
///
/// When an [`ItemPickedUp`] message for item `I` is read, every hotbar slot
/// that holds that item and whose quantity grew since the previous frame
/// starts a pulse: its scale goes from `1.0` to `scale` and back to `1.0` over
/// `duration` seconds, following half a sine wave. A pickup that lands in a
/// container slot outside the hotbar pulses nothing. A new pickup on a slot
/// that is still pulsing restarts its pulse.
///
/// The scale is applied to the slot's `UiTransform`, so it is purely visual:
/// the row layout and the neighboring slots do not move. The slot's content
/// (icon, count) scales with it.
///
/// The pulse is disabled unless `duration` is finite and positive and `scale`
/// is finite, positive and different from `1.0`. Disabling it returns pulsing
/// slots to rest. It needs Bevy's `Time` resource to advance.
///
/// Write the message in `Update` (as `DropsPlugin` does), in the same frame
/// the container changes; the reaction is evaluated in `PostUpdate`.
///
/// See [`HotbarSlotStyle`](super::HotbarSlotStyle) for a complete example.
#[derive(Resource, Debug, Clone, Copy, PartialEq)]
pub struct HotbarPickupPulse {
    /// Scale of the slot at the middle of the pulse; `1.0` is the resting size.
    pub scale: f32,
    /// Length of the pulse in seconds.
    pub duration: f32,
}

impl Default for HotbarPickupPulse {
    /// The disabled pulse: `scale` `1.0`, `duration` `0.0`.
    fn default() -> Self {
        Self {
            scale: 1.0,
            duration: 0.0,
        }
    }
}

impl HotbarPickupPulse {
    /// Returns `true` when these values produce a visible pulse.
    pub fn is_enabled(&self) -> bool {
        self.duration.is_finite()
            && self.duration > 0.0
            && self.scale.is_finite()
            && self.scale > 0.0
            && self.scale != 1.0
    }

    // Scale `elapsed` seconds into an enabled pulse.
    fn scale_at(&self, elapsed: f32) -> f32 {
        let phase = (elapsed / self.duration).clamp(0.0, 1.0);
        1.0 + (self.scale - 1.0) * (std::f32::consts::PI * phase).sin()
    }
}

/// Adds inventory icons, counts, and the selected name to `HotbarUiPlugin`.
///
/// Register exactly one item type per hotbar and explicitly add both plugins.
/// This plugin does not install input, inventory storage, or the legacy UI.
/// Configure `HotbarState::slots` and `HotbarUiConfig` before Startup. Register
/// colors before the first PostUpdate (for example, in a Startup system).
///
/// Reads the unique `PrimaryContainer` with `ContainerComponent<I>` each frame;
/// absent/ambiguous containers clear all content. A slot indexes the container
/// directly. The selected name is "Empty hands" for empty/out-of-range slots.
/// Presentation runs in PostUpdate before Bevy UI preparation, after Update
/// inventory/input writers, without changing inventory or selection.
///
/// The plugin also tells the slot row which slots are empty (see
/// `empty_slot_alpha` in [`HotbarSlotStyle`](super::HotbarSlotStyle)) and
/// drives the optional [`HotbarPickupPulse`].
///
/// The selected name, the symbols and the counts use
/// [`UiFonts::text`](crate::ui::UiFonts::text). A change to
/// [`UiFonts`](crate::ui::UiFonts) at runtime is applied to the spawned text.
///
/// ```no_run
/// use bevy::prelude::*;
/// use voxel_framework::prelude::*;
/// App::new()
///     .add_plugins(DefaultPlugins)
///     .insert_resource(HotbarState::new(14))
///     .add_plugins((HotbarPlugin, HotbarUiPlugin, HotbarContentPlugin::<DefaultItem>::new()))
///     .add_systems(Startup, |mut icons: ResMut<ItemIconPalette<DefaultItem>>| {
///         icons.register_voxel(DefaultItem::RockFragment, DefaultVoxel::Rock);
///     });
/// ```
pub struct HotbarContentPlugin<I: ItemType>(PhantomData<I>);

impl<I: ItemType> HotbarContentPlugin<I> {
    /// Creates the optional hotbar content extension.
    pub fn new() -> Self {
        Self(PhantomData)
    }
}

impl<I: ItemType> Default for HotbarContentPlugin<I> {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Resource)]
pub(super) struct ContentEnabled;

impl<I: ItemType> Plugin for HotbarContentPlugin<I> {
    fn build(&self, app: &mut App) {
        app.init_resource::<ItemIconPalette<I>>()
            .init_resource::<HotbarPickupPulse>()
            .insert_resource(ContentEnabled);
        register_ui_fonts(app);
        // Ensure the message is registered even if DropsPlugin<I> is not used.
        app.add_message::<ItemPickedUp<I>>()
            .add_systems(Startup, spawn_content.after(spawn_hotbar_ui))
            .add_systems(
                PostUpdate,
                (
                    (publish_content::<I>, fit_content_text)
                        .chain()
                        .after(super::fit_hotbar)
                        .before(super::update_hotbar_selection),
                    pulse_picked_slots::<I>,
                )
                    .before(bevy::ui::UiSystems::Prepare),
            );
    }
}

#[derive(Component)]
struct SlotIcon(usize);
#[derive(Component)]
struct SlotSymbol(usize);
#[derive(Component)]
struct SlotCount(usize);
#[derive(Component)]
struct SelectedName;

/// Seconds into the pickup pulse of a slot, or `None` while it is at rest.
#[derive(Component, Default)]
struct SlotPulse {
    elapsed: Option<f32>,
}

fn spawn_content(
    mut commands: Commands,
    roots: Query<Entity, With<HotbarUiRoot>>,
    slots: Query<(Entity, &HotbarSlot)>,
    fonts: Option<Res<UiFonts>>,
) {
    let role = UiFontRole::Text;
    let font = role.font(fonts.as_deref());
    for root in &roots {
        let name = commands
            .spawn((
                SelectedName,
                role,
                Text::new("Empty hands"),
                TextFont {
                    font: font.clone(),
                    font_size: 18.0,
                    ..default()
                },
                TextColor(Color::WHITE),
                Node {
                    margin: UiRect::bottom(px(6)),
                    ..default()
                },
            ))
            .id();
        commands.entity(root).insert_children(0, &[name]);
    }
    for (entity, slot) in &slots {
        commands
            .entity(entity)
            .insert((SlotContent { empty: true }, SlotPulse::default()));
        commands.entity(entity).with_children(|parent| {
            parent.spawn((
                SlotIcon(slot.0),
                Node {
                    position_type: PositionType::Absolute,
                    left: percent(22),
                    top: percent(22),
                    width: percent(56),
                    height: percent(56),
                    display: Display::None,
                    ..default()
                },
                BackgroundColor(Color::NONE),
            ));
            parent.spawn((
                SlotSymbol(slot.0),
                role,
                Text::new(""),
                TextFont {
                    font: font.clone(),
                    font_size: 22.0,
                    ..default()
                },
                TextColor(Color::WHITE),
            ));
            parent.spawn((
                SlotCount(slot.0),
                role,
                Text::new(""),
                TextFont {
                    font: font.clone(),
                    font_size: 14.0,
                    ..default()
                },
                TextColor(Color::WHITE),
                Node {
                    position_type: PositionType::Absolute,
                    right: px(2),
                    bottom: px(0),
                    ..default()
                },
            ));
        });
    }
}

fn publish_content<I: ItemType>(
    containers: Query<&ContainerComponent<I>, With<PrimaryContainer>>,
    hotbar: Res<HotbarState>,
    palette: Res<ItemIconPalette<I>>,
    mut icons: Query<(&SlotIcon, &mut Node, &mut BackgroundColor)>,
    mut texts: Query<(
        &mut Text,
        Option<&SlotSymbol>,
        Option<&SlotCount>,
        Option<&SelectedName>,
    )>,
    mut slots: Query<(&HotbarSlot, &mut SlotContent)>,
) {
    let container = containers.single().ok();
    let slot_at = |index| {
        container
            .and_then(|c| c.slot_at(index))
            .filter(|slot| slot.count > 0 && !slot.item.is_empty())
    };
    for (slot, mut content) in &mut slots {
        let empty = slot_at(slot.0).is_none();
        if content.empty != empty {
            content.empty = empty;
        }
    }
    for (icon, mut node, mut background) in &mut icons {
        let color = slot_at(icon.0).and_then(|slot| palette.color(slot.item));
        let display = if color.is_some() {
            Display::Flex
        } else {
            Display::None
        };
        if node.display != display {
            node.display = display;
        }
        let color = color
            .map(|[r, g, b, a]| Color::linear_rgba(r, g, b, a))
            .unwrap_or(Color::NONE);
        if background.0 != color {
            background.0 = color;
        }
    }
    for (mut text, symbol, count, name) in &mut texts {
        let value = if let Some(symbol) = symbol {
            if slot_at(symbol.0).is_some_and(|slot| palette.color(slot.item).is_none()) {
                "?"
            } else {
                ""
            }
            .to_string()
        } else if let Some(count) = count {
            slot_at(count.0)
                .map(|slot| slot.count.to_string())
                .unwrap_or_default()
        } else if name.is_some() {
            if hotbar.selected < hotbar.slots {
                slot_at(hotbar.selected)
                    .map(|slot| slot.item.name())
                    .unwrap_or("Empty hands")
            } else {
                "Empty hands"
            }
            .to_string()
        } else {
            continue;
        };
        if text.0 != value {
            text.0 = value;
        }
    }
}

// Starts a pulse on the slots that received a picked-up item and advances the
// running ones. `previous` holds last frame's (item, count) per hotbar slot; it
// is the only way to tell which of several stacks of one item grew, because the
// message carries no slot index.
fn pulse_picked_slots<I: ItemType>(
    mut pickups: MessageReader<ItemPickedUp<I>>,
    pulse: Option<Res<HotbarPickupPulse>>,
    time: Option<Res<Time>>,
    containers: Query<&ContainerComponent<I>, With<PrimaryContainer>>,
    mut previous: Local<Vec<Option<(I, u32)>>>,
    mut slots: Query<(&HotbarSlot, &mut SlotPulse, &mut UiTransform)>,
) {
    // Always drain, so pickups from a disabled period are never replayed.
    let picked: Vec<I> = pickups.read().map(|pickup| pickup.item).collect();
    let pulse = pulse
        .as_deref()
        .copied()
        .filter(HotbarPickupPulse::is_enabled);
    let delta = time.map_or(0.0, |time| time.delta_secs());
    let container = containers.single().ok();
    for (slot, mut state, mut transform) in &mut slots {
        let now = container
            .and_then(|c| c.slot_at(slot.0))
            .filter(|stack| stack.count > 0 && !stack.item.is_empty())
            .map(|stack| (stack.item, stack.count));
        if previous.len() <= slot.0 {
            previous.resize(slot.0 + 1, None);
        }
        let before = std::mem::replace(&mut previous[slot.0], now);
        let received = now.is_some_and(|(item, count)| {
            picked.contains(&item)
                && !matches!(before, Some((old, had)) if old == item && had >= count)
        });
        let elapsed = match pulse {
            None => None,
            Some(_) if received => Some(0.0),
            Some(pulse) => state
                .elapsed
                .map(|elapsed| elapsed + delta)
                .filter(|elapsed| *elapsed < pulse.duration),
        };
        // Leave the transform alone while the slot is at rest: a game may use it.
        if state.elapsed.is_none() && elapsed.is_none() {
            continue;
        }
        let scale = match (pulse, elapsed) {
            (Some(pulse), Some(elapsed)) => Vec2::splat(pulse.scale_at(elapsed)),
            _ => Vec2::ONE,
        };
        if transform.scale != scale {
            transform.scale = scale;
        }
        state.elapsed = elapsed;
    }
}

// Keep every decimal digit visible without changing the stored stack quantity.
// One em per ASCII digit is a conservative bound for the engine default font
// and for any `UiFonts::text` whose digits are not wider than one em.
fn fit_content_text(
    slots: Query<&Node, With<HotbarSlot>>,
    mut texts: Query<
        (&ChildOf, &Text, &mut TextFont, Option<&SlotCount>),
        Or<(With<SlotCount>, With<SlotSymbol>)>,
    >,
) {
    for (parent, text, mut font, count) in &mut texts {
        let Ok(node) = slots.get(parent.parent()) else {
            continue;
        };
        let Val::Px(width) = node.width else {
            continue;
        };
        let available = (width - 8.0).max(0.0);
        let size = if count.is_some() {
            14.0_f32.min(available / text.0.len().max(1) as f32)
        } else {
            22.0_f32.min(available)
        };
        if font.font_size != size {
            font.font_size = size;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::items::{DefaultItem, HotbarPlugin, InventorySlot};
    use crate::ui::{HotbarSlotStyle, HotbarUiConfig, HotbarUiPlugin};
    use crate::voxel::DefaultVoxel;
    use bevy::input::mouse::{MouseScrollUnit, MouseWheel};

    fn app() -> App {
        let mut app = App::new();
        app.init_resource::<ButtonInput<KeyCode>>()
            .add_message::<MouseWheel>()
            .insert_resource(HotbarState::new(14))
            .add_plugins((
                HotbarPlugin,
                HotbarUiPlugin,
                HotbarContentPlugin::<DefaultItem>::new(),
            ));
        app.world_mut()
            .resource_mut::<ItemIconPalette<DefaultItem>>()
            .register_voxel(DefaultItem::RockFragment, DefaultVoxel::Rock);
        app
    }

    fn container(app: &mut App) -> Entity {
        let mut container = ContainerComponent::new(14);
        container.0.slots[0] = Some(InventorySlot {
            item: DefaultItem::RockFragment,
            count: 1,
        });
        container.0.slots[2] = Some(InventorySlot {
            item: DefaultItem::Crystal,
            count: 7,
        });
        app.world_mut().spawn((PrimaryContainer, container)).id()
    }

    fn count(app: &mut App, index: usize) -> String {
        let world = app.world_mut();
        world
            .query::<(&SlotCount, &Text)>()
            .iter(world)
            .find(|(s, _)| s.0 == index)
            .unwrap()
            .1
            .0
            .clone()
    }

    fn symbol(app: &mut App, index: usize) -> String {
        let world = app.world_mut();
        world
            .query::<(&SlotSymbol, &Text)>()
            .iter(world)
            .find(|(s, _)| s.0 == index)
            .unwrap()
            .1
            .0
            .clone()
    }

    fn name(app: &mut App) -> String {
        let world = app.world_mut();
        world
            .query_filtered::<&Text, With<SelectedName>>()
            .single(world)
            .unwrap()
            .0
            .clone()
    }

    fn icon(app: &mut App, index: usize) -> (Display, Color) {
        let world = app.world_mut();
        let (_, n, c) = world
            .query::<(&SlotIcon, &Node, &BackgroundColor)>()
            .iter(world)
            .find(|(s, _, _)| s.0 == index)
            .unwrap();
        (n.display, c.0)
    }

    fn slot_colors(app: &mut App, index: usize) -> (Color, BorderColor) {
        let world = app.world_mut();
        let (_, bg, border) = world
            .query::<(&HotbarSlot, &BackgroundColor, &BorderColor)>()
            .iter(world)
            .find(|(slot, _, _)| slot.0 == index)
            .unwrap();
        (bg.0, *border)
    }

    fn pulsing(app: &mut App) -> Vec<usize> {
        let world = app.world_mut();
        let mut indices: Vec<usize> = world
            .query::<(&HotbarSlot, &SlotPulse)>()
            .iter(world)
            .filter(|(_, pulse)| pulse.elapsed.is_some())
            .map(|(slot, _)| slot.0)
            .collect();
        indices.sort_unstable();
        indices
    }

    fn scale(app: &mut App, index: usize) -> Vec2 {
        let world = app.world_mut();
        world
            .query::<(&HotbarSlot, &UiTransform)>()
            .iter(world)
            .find(|(slot, _)| slot.0 == index)
            .unwrap()
            .1
            .scale
    }

    // Adds to the container and reports it the way the drop pipeline does.
    fn pick_up(app: &mut App, entity: Entity, item: DefaultItem, count: u32) {
        let rejected = app
            .world_mut()
            .get_mut::<ContainerComponent<DefaultItem>>(entity)
            .unwrap()
            .0
            .add(item, count);
        assert_eq!(rejected, 0);
        app.world_mut().write_message(ItemPickedUp { item, count });
    }

    fn advance(app: &mut App, secs: f32) {
        app.world_mut()
            .resource_mut::<Time>()
            .advance_by(std::time::Duration::from_secs_f32(secs));
        app.update();
    }

    // Slot 0: rock x1, slot 2: crystal x7, slot 3: a second rock stack x5.
    fn pulse_app(pulse: HotbarPickupPulse) -> (App, Entity) {
        let mut app = app();
        app.init_resource::<Time>().insert_resource(pulse);
        let entity = container(&mut app);
        app.world_mut()
            .get_mut::<ContainerComponent<DefaultItem>>(entity)
            .unwrap()
            .0
            .slots[3] = Some(InventorySlot {
            item: DefaultItem::RockFragment,
            count: 5,
        });
        app.update();
        (app, entity)
    }

    const PULSE: HotbarPickupPulse = HotbarPickupPulse {
        scale: 1.5,
        duration: 0.4,
    };

    #[test]
    fn empty_slots_fade_fill_and_border_but_never_the_selection() {
        let mut app = app();
        app.insert_resource(HotbarSlotStyle {
            border_color: [0.2, 0.4, 0.6, 0.8],
            selected_border_color: [1.0, 0.9, 0.8, 0.7],
            empty_slot_alpha: 0.25,
            ..default()
        });
        let entity = container(&mut app);
        app.update();
        let config = app.world().resource::<HotbarUiConfig>().clone();
        let [r, g, b, a] = config.slot_color;
        let full = (
            Color::srgba(r, g, b, a),
            BorderColor::all(Color::srgba(0.2, 0.4, 0.6, 0.8)),
        );
        let faded = (
            Color::srgba(r, g, b, a * 0.25),
            BorderColor::all(Color::srgba(0.2, 0.4, 0.6, 0.8 * 0.25)),
        );
        let [r, g, b, a] = config.selected_color;
        let selected = (
            Color::srgba(r, g, b, a),
            BorderColor::all(Color::srgba(1.0, 0.9, 0.8, 0.7)),
        );
        // Slot 0 is selected and occupied, 1 is empty, 2 is occupied.
        assert_eq!(slot_colors(&mut app, 0), selected);
        assert_eq!(slot_colors(&mut app, 1), faded);
        assert_eq!(slot_colors(&mut app, 2), full);
        // Selecting the empty slot shows the full selected style.
        app.world_mut().resource_mut::<HotbarState>().select(1);
        app.update();
        assert_eq!(slot_colors(&mut app, 0), full);
        assert_eq!(slot_colors(&mut app, 1), selected);
        // Emptying a slot fades it in the same frame.
        app.world_mut()
            .get_mut::<ContainerComponent<DefaultItem>>(entity)
            .unwrap()
            .0
            .slots[2] = None;
        app.update();
        assert_eq!(slot_colors(&mut app, 2), faded);
        // Without a container every unselected slot is empty.
        app.world_mut().despawn(entity);
        app.update();
        assert_eq!(slot_colors(&mut app, 0), faded);
        assert_eq!(slot_colors(&mut app, 1), selected);
    }

    #[test]
    fn invalid_empty_slot_alpha_is_clamped_or_ignored() {
        let mut app = app();
        container(&mut app);
        let [r, g, b, a] = HotbarUiConfig::default().slot_color;
        for (alpha, expected) in [
            (f32::NAN, 1.0),
            (f32::INFINITY, 1.0),
            (7.0, 1.0),
            (-1.0, 0.0),
            (0.5, 0.5),
        ] {
            app.insert_resource(HotbarSlotStyle {
                empty_slot_alpha: alpha,
                ..default()
            });
            app.update();
            let (bg, border) = slot_colors(&mut app, 1);
            assert_eq!(bg, Color::srgba(r, g, b, a * expected), "alpha {alpha}");
            assert_eq!(
                border,
                BorderColor::all(Color::srgba(0.6, 0.6, 0.6, 0.6 * expected)),
                "alpha {alpha}"
            );
        }
    }

    #[test]
    fn pickup_pulses_the_slot_that_received_the_item_and_ends_after_its_duration() {
        let (mut app, entity) = pulse_app(PULSE);
        assert_eq!(pulsing(&mut app), Vec::<usize>::new());
        // `add` stacks onto the first rock stack (slot 0), not the one in slot 3.
        pick_up(&mut app, entity, DefaultItem::RockFragment, 2);
        advance(&mut app, 0.0);
        assert_eq!(count(&mut app, 0), "3");
        assert_eq!(pulsing(&mut app), vec![0]);
        assert_eq!(scale(&mut app, 0), Vec2::ONE);
        // Halfway through, the slot is at the configured scale; the rest are not.
        advance(&mut app, 0.2);
        assert!((scale(&mut app, 0) - Vec2::splat(1.5)).abs().max_element() < 1e-3);
        for index in 1..14 {
            assert_eq!(scale(&mut app, index), Vec2::ONE);
        }
        assert_eq!(pulsing(&mut app), vec![0]);
        // Past the duration the slot is back at rest.
        advance(&mut app, 0.25);
        assert_eq!(pulsing(&mut app), Vec::<usize>::new());
        assert_eq!(scale(&mut app, 0), Vec2::ONE);
        // A pickup that opens a new stack pulses that slot.
        pick_up(&mut app, entity, DefaultItem::Dirt, 1);
        advance(&mut app, 0.0);
        assert_eq!(count(&mut app, 1), "1");
        assert_eq!(pulsing(&mut app), vec![1]);
    }

    #[test]
    fn a_new_pickup_restarts_a_running_pulse() {
        let (mut app, entity) = pulse_app(PULSE);
        pick_up(&mut app, entity, DefaultItem::RockFragment, 1);
        advance(&mut app, 0.0);
        advance(&mut app, 0.3);
        pick_up(&mut app, entity, DefaultItem::RockFragment, 1);
        advance(&mut app, 0.3);
        assert_eq!(scale(&mut app, 0), Vec2::ONE);
        // 0.3 s after the restart the pulse is still running.
        advance(&mut app, 0.3);
        assert_eq!(pulsing(&mut app), vec![0]);
        assert_ne!(scale(&mut app, 0), Vec2::ONE);
    }

    #[test]
    fn pickup_outside_the_hotbar_or_without_a_matching_slot_pulses_nothing() {
        let mut app = app();
        app.init_resource::<Time>().insert_resource(PULSE);
        // Twenty container slots behind a fourteen-slot hotbar, the first
        // fourteen taken by other stacks so the pickup lands in slot 14.
        let mut container = ContainerComponent::new(20);
        for slot in container.0.slots.iter_mut().take(14) {
            *slot = Some(InventorySlot {
                item: DefaultItem::Crystal,
                count: 1,
            });
        }
        let entity = app.world_mut().spawn((PrimaryContainer, container)).id();
        app.update();
        pick_up(&mut app, entity, DefaultItem::RockFragment, 3);
        assert_eq!(
            app.world()
                .get::<ContainerComponent<DefaultItem>>(entity)
                .unwrap()
                .0
                .slots[14],
            Some(InventorySlot {
                item: DefaultItem::RockFragment,
                count: 3,
            })
        );
        advance(&mut app, 0.0);
        advance(&mut app, 0.2);
        assert_eq!(pulsing(&mut app), Vec::<usize>::new());
        // A message alone, with no slot that grew, starts nothing either.
        app.world_mut().write_message(ItemPickedUp {
            item: DefaultItem::Crystal,
            count: 1,
        });
        advance(&mut app, 0.0);
        advance(&mut app, 0.2);
        assert_eq!(pulsing(&mut app), Vec::<usize>::new());
        for index in 0..14 {
            assert_eq!(scale(&mut app, index), Vec2::ONE);
        }
    }

    #[test]
    fn default_invalid_or_missing_pulse_never_starts() {
        assert!(PULSE.is_enabled());
        assert!(
            HotbarPickupPulse {
                scale: 0.8,
                duration: 0.1
            }
            .is_enabled()
        );
        let invalid = [
            HotbarPickupPulse::default(),
            HotbarPickupPulse {
                scale: 1.0,
                ..PULSE
            },
            HotbarPickupPulse {
                scale: f32::NAN,
                ..PULSE
            },
            HotbarPickupPulse {
                scale: f32::INFINITY,
                ..PULSE
            },
            HotbarPickupPulse {
                scale: -1.5,
                ..PULSE
            },
            HotbarPickupPulse {
                scale: 0.0,
                ..PULSE
            },
            HotbarPickupPulse {
                duration: f32::NAN,
                ..PULSE
            },
            HotbarPickupPulse {
                duration: f32::INFINITY,
                ..PULSE
            },
            HotbarPickupPulse {
                duration: -0.4,
                ..PULSE
            },
            HotbarPickupPulse {
                duration: 0.0,
                ..PULSE
            },
        ];
        // The plugin initializes the disabled default.
        let mut app = app();
        app.init_resource::<Time>();
        let entity = container(&mut app);
        app.update();
        assert_eq!(
            *app.world().resource::<HotbarPickupPulse>(),
            HotbarPickupPulse {
                scale: 1.0,
                duration: 0.0
            }
        );
        for pulse in invalid {
            assert!(!pulse.is_enabled(), "{pulse:?}");
            app.insert_resource(pulse);
            pick_up(&mut app, entity, DefaultItem::RockFragment, 1);
            advance(&mut app, 0.0);
            advance(&mut app, 0.1);
            assert_eq!(pulsing(&mut app), Vec::<usize>::new(), "{pulse:?}");
            assert_eq!(scale(&mut app, 0), Vec2::ONE, "{pulse:?}");
        }
        // The resource is optional: removing it disables the reaction.
        app.world_mut().remove_resource::<HotbarPickupPulse>();
        pick_up(&mut app, entity, DefaultItem::RockFragment, 1);
        advance(&mut app, 0.0);
        advance(&mut app, 0.1);
        assert_eq!(pulsing(&mut app), Vec::<usize>::new());
        assert_eq!(scale(&mut app, 0), Vec2::ONE);
    }

    #[test]
    fn disabling_the_pulse_returns_a_pulsing_slot_to_rest() {
        let (mut app, entity) = pulse_app(PULSE);
        pick_up(&mut app, entity, DefaultItem::RockFragment, 1);
        advance(&mut app, 0.0);
        advance(&mut app, 0.2);
        assert_ne!(scale(&mut app, 0), Vec2::ONE);
        app.insert_resource(HotbarPickupPulse::default());
        advance(&mut app, 0.01);
        assert_eq!(pulsing(&mut app), Vec::<usize>::new());
        assert_eq!(scale(&mut app, 0), Vec2::ONE);
    }

    #[test]
    fn a_resting_slot_keeps_a_scale_set_by_the_game() {
        let (mut app, _) = pulse_app(PULSE);
        let world = app.world_mut();
        for mut transform in world
            .query_filtered::<&mut UiTransform, With<HotbarSlot>>()
            .iter_mut(world)
        {
            transform.scale = Vec2::splat(0.9);
        }
        advance(&mut app, 0.1);
        assert_eq!(scale(&mut app, 0), Vec2::splat(0.9));
    }

    #[test]
    fn pulse_without_a_time_resource_does_not_panic_and_stays_at_rest() {
        let mut app = app();
        app.insert_resource(PULSE);
        let entity = container(&mut app);
        app.update();
        pick_up(&mut app, entity, DefaultItem::RockFragment, 1);
        app.update();
        app.update();
        assert_eq!(scale(&mut app, 0), Vec2::ONE);
    }

    #[test]
    fn explicit_voxel_mapping_does_not_use_item_byte_or_default_item_color() {
        let mut palette = ItemIconPalette::new();
        assert_ne!(
            DefaultItem::RockFragment.to_byte(),
            DefaultVoxel::IronOre.to_byte()
        );
        palette.register_voxel(DefaultItem::RockFragment, DefaultVoxel::IronOre);
        assert_eq!(
            palette.color(DefaultItem::RockFragment),
            Some(DefaultVoxel::IronOre.color())
        );
        assert_eq!(palette.color(DefaultItem::Crystal), None);
        let replacement = DefaultVoxel::SiliconCrystal.color();
        palette.register(DefaultItem::RockFragment, replacement);
        assert_eq!(palette.color(DefaultItem::RockFragment), Some(replacement));
        assert_eq!(palette.remove(DefaultItem::RockFragment), Some(replacement));
        assert_eq!(palette.color(DefaultItem::RockFragment), None);
    }

    #[test]
    fn content_tracks_exact_indices_quantities_replacement_emptying_and_palette_edits() {
        let mut app = app();
        let entity = container(&mut app);
        app.update();
        let [r, g, b, a] = DefaultVoxel::Rock.color();
        assert_eq!(
            icon(&mut app, 0),
            (Display::Flex, Color::linear_rgba(r, g, b, a))
        );
        assert_eq!(symbol(&mut app, 0), "");
        assert_eq!(count(&mut app, 0), "1");
        assert_eq!(count(&mut app, 1), "");
        assert_eq!(count(&mut app, 2), "7");
        assert_eq!(symbol(&mut app, 2), "?");
        assert_eq!(icon(&mut app, 2).0, Display::None);
        assert_eq!(name(&mut app), "Rock Fragment");
        app.world_mut()
            .get_mut::<ContainerComponent<DefaultItem>>(entity)
            .unwrap()
            .0
            .add(DefaultItem::RockFragment, 4);
        app.update();
        assert_eq!(count(&mut app, 0), "5");
        app.world_mut()
            .get_mut::<ContainerComponent<DefaultItem>>(entity)
            .unwrap()
            .0
            .slots[0] = Some(InventorySlot {
            item: DefaultItem::Crystal,
            count: 1,
        });
        app.update();
        assert_eq!(count(&mut app, 0), "1");
        assert_eq!(name(&mut app), "Crystal");
        assert_eq!(symbol(&mut app, 0), "?");
        app.world_mut()
            .resource_mut::<ItemIconPalette<DefaultItem>>()
            .register_voxel(DefaultItem::Crystal, DefaultVoxel::SiliconCrystal);
        app.update();
        assert_eq!(symbol(&mut app, 0), "");
        assert_eq!(icon(&mut app, 0).0, Display::Flex);
        app.world_mut()
            .get_mut::<ContainerComponent<DefaultItem>>(entity)
            .unwrap()
            .0
            .slots[0] = None;
        app.update();
        assert_eq!(count(&mut app, 0), "");
        assert_eq!(symbol(&mut app, 0), "");
        assert_eq!(icon(&mut app, 0), (Display::None, Color::NONE));
        assert_eq!(name(&mut app), "Empty hands");
    }

    #[test]
    fn selection_and_wheel_update_name_and_highlight_without_inventory_mutation() {
        let mut app = app();
        let entity = container(&mut app);
        let before = app
            .world()
            .get::<ContainerComponent<DefaultItem>>(entity)
            .unwrap()
            .0
            .slots
            .clone();
        app.update();
        app.world_mut()
            .resource_mut::<ButtonInput<KeyCode>>()
            .press(KeyCode::Digit3);
        app.update();
        assert_eq!(name(&mut app), "Crystal");
        let config = app.world().resource::<HotbarUiConfig>().clone();
        let [r, g, b, a] = config.selected_color;
        let world = app.world_mut();
        for (slot, bg) in world.query::<(&HotbarSlot, &BackgroundColor)>().iter(world) {
            assert_eq!(bg.0 == Color::srgba(r, g, b, a), slot.0 == 2);
        }
        app.world_mut()
            .resource_mut::<ButtonInput<KeyCode>>()
            .reset_all();
        app.world_mut().resource_mut::<HotbarState>().select(0);
        // Actual wheel input crosses every slot and wraps back to zero.
        for expected in (1..14).chain(std::iter::once(0)) {
            app.world_mut().write_message(MouseWheel {
                unit: MouseScrollUnit::Line,
                x: 0.0,
                y: -1.0,
                window: Entity::PLACEHOLDER,
            });
            app.update();
            assert_eq!(app.world().resource::<HotbarState>().selected, expected);
            assert_eq!(
                name(&mut app),
                match expected {
                    0 => "Rock Fragment",
                    2 => "Crystal",
                    _ => "Empty hands",
                }
            );
        }
        app.world_mut().write_message(MouseWheel {
            unit: MouseScrollUnit::Pixel,
            x: 0.0,
            y: 53.0,
            window: Entity::PLACEHOLDER,
        });
        app.update();
        assert_eq!(app.world().resource::<HotbarState>().selected, 13);
        for (index, key) in [
            KeyCode::Digit1,
            KeyCode::Digit2,
            KeyCode::Digit3,
            KeyCode::Digit4,
            KeyCode::Digit5,
            KeyCode::Digit6,
            KeyCode::Digit7,
            KeyCode::Digit8,
            KeyCode::Digit9,
        ]
        .into_iter()
        .enumerate()
        {
            app.world_mut()
                .resource_mut::<ButtonInput<KeyCode>>()
                .reset_all();
            app.world_mut()
                .resource_mut::<ButtonInput<KeyCode>>()
                .press(key);
            app.update();
            assert_eq!(app.world().resource::<HotbarState>().selected, index);
        }
        assert_eq!(
            app.world()
                .get::<ContainerComponent<DefaultItem>>(entity)
                .unwrap()
                .0
                .slots,
            before
        );
    }

    #[test]
    fn missing_replaced_and_ambiguous_containers_clear_all_stale_content() {
        let mut app = app();
        app.update();
        assert_eq!(name(&mut app), "Empty hands");
        let entity = container(&mut app);
        app.update();
        assert_eq!(count(&mut app, 0), "1");
        let other = container(&mut app);
        app.update();
        for i in 0..14 {
            assert_eq!(count(&mut app, i), "");
            assert_eq!(symbol(&mut app, i), "");
            assert_eq!(icon(&mut app, i).0, Display::None);
        }
        assert_eq!(name(&mut app), "Empty hands");
        app.world_mut().despawn(entity);
        app.update();
        assert_eq!(name(&mut app), "Rock Fragment");
        app.world_mut().despawn(other);
        app.update();
        assert_eq!(name(&mut app), "Empty hands");
        assert_eq!(count(&mut app, 0), "");
        // Short replacement inventory leaves all out-of-range slots empty.
        app.world_mut()
            .spawn((PrimaryContainer, ContainerComponent::<DefaultItem>::new(1)));
        app.world_mut().resource_mut::<HotbarState>().select(13);
        app.update();
        assert_eq!(count(&mut app, 13), "");
        assert_eq!(name(&mut app), "Empty hands");
    }

    #[test]
    fn disabled_hotbar_does_not_spawn_content() {
        let mut app = app();
        app.insert_resource(HotbarUiConfig {
            visible: false,
            ..default()
        });
        app.update();
        let world = app.world_mut();
        assert_eq!(world.query::<&SelectedName>().iter(world).count(), 0);
        assert_eq!(world.query::<&SlotIcon>().iter(world).count(), 0);
    }
    #[test]
    fn preconfigured_palette_and_reverse_ui_plugin_order_are_supported() {
        let mut app = App::new();
        let mut palette = ItemIconPalette::new();
        palette.register_voxel(DefaultItem::RockFragment, DefaultVoxel::IronOre);
        app.insert_resource(palette)
            .insert_resource(HotbarState::new(14))
            .add_plugins((HotbarContentPlugin::<DefaultItem>::new(), HotbarUiPlugin));
        container(&mut app);
        app.update();
        let [r, g, b, a] = DefaultVoxel::IronOre.color();
        assert_eq!(
            icon(&mut app, 0),
            (Display::Flex, Color::linear_rgba(r, g, b, a))
        );
    }
    #[test]
    fn full_u32_quantity_is_preserved_and_text_fits_the_slot() {
        let mut app = app();
        let entity = container(&mut app);
        app.world_mut()
            .get_mut::<ContainerComponent<DefaultItem>>(entity)
            .unwrap()
            .0
            .slots[0]
            .as_mut()
            .unwrap()
            .count = u32::MAX;
        app.update();
        assert_eq!(count(&mut app, 0), u32::MAX.to_string());
        let world = app.world_mut();
        let (_, text, font) = world
            .query::<(&SlotCount, &Text, &TextFont)>()
            .iter(world)
            .find(|(slot, _, _)| slot.0 == 0)
            .unwrap();
        assert!(font.font_size * text.0.len() as f32 <= 42.0);
        assert_eq!(
            world
                .get::<ContainerComponent<DefaultItem>>(entity)
                .unwrap()
                .0
                .slots[0]
                .as_ref()
                .unwrap()
                .count,
            u32::MAX
        );
    }

    /// Fonts of the selected name, the 14 symbols and the 14 counts.
    fn text_fonts(app: &mut App) -> Vec<Handle<Font>> {
        let world = app.world_mut();
        let mut query = world.query_filtered::<&TextFont, Or<(
            With<SelectedName>,
            With<SlotSymbol>,
            With<SlotCount>,
        )>>();
        query.iter(world).map(|font| font.font.clone()).collect()
    }

    #[test]
    fn default_fonts_keep_the_engine_default_font() {
        let mut app = app();
        container(&mut app);
        app.update();
        assert_eq!(*app.world().resource::<UiFonts>(), UiFonts::default());
        let fonts = text_fonts(&mut app);
        assert_eq!(fonts.len(), 29);
        assert!(fonts.iter().all(|font| *font == Handle::<Font>::default()));
    }

    #[test]
    fn name_symbols_and_counts_use_the_text_font() {
        use crate::ui::fonts::test_fonts;

        let mut app = app();
        app.insert_resource(UiFonts::new(test_fonts::display(), test_fonts::text()));
        container(&mut app);
        app.update();
        let fonts = text_fonts(&mut app);
        assert_eq!(fonts.len(), 29);
        assert!(fonts.iter().all(|font| *font == test_fonts::text()));
    }

    #[test]
    fn fonts_changed_at_runtime_update_the_spawned_text_and_keep_fitted_sizes() {
        use crate::ui::fonts::test_fonts;

        let mut app = app();
        let entity = container(&mut app);
        app.world_mut()
            .get_mut::<ContainerComponent<DefaultItem>>(entity)
            .unwrap()
            .0
            .slots[0]
            .as_mut()
            .unwrap()
            .count = u32::MAX;
        app.update();
        let count_size = |app: &mut App| {
            let world = app.world_mut();
            world
                .query::<(&SlotCount, &TextFont)>()
                .iter(world)
                .find(|(slot, _)| slot.0 == 0)
                .unwrap()
                .1
                .font_size
        };
        let fitted = count_size(&mut app);
        assert!(fitted < 14.0);

        app.insert_resource(UiFonts::uniform(test_fonts::other()));
        app.update();
        let fonts = text_fonts(&mut app);
        assert_eq!(fonts.len(), 29);
        assert!(fonts.iter().all(|font| *font == test_fonts::other()));
        assert_eq!(count_size(&mut app), fitted);
    }
}