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
#![doc = include_str!("../Readme.md")]
mod commands;
#[cfg(feature = "bevy-ui")]
pub mod components;
mod events;
pub mod marker;
pub mod systems;
use std::cmp::Ordering;
use std::fmt;
use std::num::NonZeroUsize;
use bevy::ecs::system::{QuerySingleError, SystemParam};
use bevy::math::Vec3Swizzles;
use bevy::prelude::*;
pub use non_empty_vec::NonEmpty;
pub use crate::events::{Direction, NavEvent, NavRequest, ScopeDirection};
#[derive(SystemParam)]
struct NavQueries<'w, 's> {
children: Query<'w, 's, &'static Children>,
parents: Query<'w, 's, &'static Parent>,
focusables: Query<'w, 's, (Entity, &'static Focusable), With<Focusable>>,
menus: Query<'w, 's, (Entity, &'static NavMenu), With<NavMenu>>,
transform: Query<'w, 's, &'static GlobalTransform>,
}
#[derive(Clone, Debug, Copy, PartialEq)]
pub enum FocusState {
Dormant,
Focused,
Active,
Inert,
}
#[derive(Default)]
pub struct NavLock {
entity: Option<Entity>,
}
impl NavLock {
pub fn entity(&self) -> Option<Entity> {
self.entity
}
pub fn is_locked(&self) -> bool {
self.entity.is_some()
}
}
#[derive(Clone, Debug, Copy, PartialEq)]
enum MenuSetting {
ClosedXY,
CycleXY,
ClosedScope,
CycleScope,
}
impl MenuSetting {
fn closed(self) -> Self {
use MenuSetting::*;
match self {
ClosedXY | CycleXY => ClosedXY,
ClosedScope | CycleScope => ClosedScope,
}
}
fn cycling(self) -> Self {
use MenuSetting::*;
match self {
ClosedXY | CycleXY => CycleXY,
ClosedScope | CycleScope => CycleScope,
}
}
fn scope(self) -> Self {
use MenuSetting::*;
match self {
ClosedScope | ClosedXY => ClosedScope,
CycleScope | CycleXY => CycleScope,
}
}
fn cycles(&self) -> bool {
use MenuSetting::*;
match self {
CycleScope | CycleXY => true,
ClosedScope | ClosedXY => false,
}
}
fn is_2d(&self) -> bool {
!self.is_scope()
}
fn is_scope(&self) -> bool {
use MenuSetting::*;
match self {
ClosedScope | CycleScope => true,
ClosedXY | CycleXY => false,
}
}
}
#[derive(Debug, Clone, Copy)]
enum CacheOption<T> {
NotYetCached,
Cached(T),
}
impl<T> From<Option<T>> for CacheOption<T> {
fn from(value: Option<T>) -> Self {
match value {
Some(value) => CacheOption::Cached(value),
None => CacheOption::NotYetCached,
}
}
}
impl<T> From<CacheOption<T>> for Option<T> {
fn from(value: CacheOption<T>) -> Self {
match value {
CacheOption::NotYetCached => None,
CacheOption::Cached(value) => Some(value),
}
}
}
#[derive(Debug, Component, Clone)]
pub struct NavMenu {
focus_parent: Option<Entity>,
setting: MenuSetting,
non_inert_child: CacheOption<Entity>,
}
impl NavMenu {
pub fn new(focus_parent: Option<Entity>) -> Self {
NavMenu {
focus_parent,
setting: MenuSetting::ClosedXY,
non_inert_child: CacheOption::NotYetCached,
}
}
pub fn root() -> Self {
Self::new(None)
}
pub fn closed(mut self) -> Self {
self.setting = self.setting.closed();
self
}
pub fn cycling(mut self) -> Self {
self.setting = self.setting.cycling();
self
}
pub fn scope(mut self) -> Self {
self.setting = self.setting.scope();
self
}
pub fn reachable_from(focusable: Entity) -> Self {
Self::new(Some(focusable))
}
fn with_non_inert_child(self, child: Option<Entity>) -> Self {
NavMenu {
non_inert_child: child.into(),
..self
}
}
fn non_inert_child(&self) -> Option<Entity> {
self.non_inert_child.into()
}
}
#[derive(Clone)]
enum ActionType {
Normal,
Cancel,
Lock,
}
#[derive(Component, Clone)]
pub struct Focusable {
focus_state: FocusState,
action: ActionType,
}
impl Default for Focusable {
fn default() -> Self {
Focusable {
focus_state: FocusState::Inert,
action: ActionType::Normal,
}
}
}
impl fmt::Debug for Focusable {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "F({:?})", self.focus_state)
}
}
impl Focusable {
pub fn state(&self) -> FocusState {
self.focus_state
}
pub fn is_focused(&self) -> bool {
self.focus_state == FocusState::Focused
}
pub fn is_active(&self) -> bool {
matches!(self.focus_state, FocusState::Active | FocusState::Focused)
}
pub fn is_dormant(&self) -> bool {
self.focus_state == FocusState::Dormant
}
pub fn is_inert(&self) -> bool {
self.focus_state == FocusState::Inert
}
pub fn is_cancel(&self) -> bool {
matches!(self.action, ActionType::Cancel)
}
pub fn is_lock(&self) -> bool {
matches!(self.action, ActionType::Lock)
}
pub fn cancel() -> Self {
Focusable {
focus_state: FocusState::Inert,
action: ActionType::Cancel,
}
}
pub fn lock() -> Self {
Focusable {
focus_state: FocusState::Inert,
action: ActionType::Lock,
}
}
}
#[derive(Component)]
#[non_exhaustive]
pub struct Focused;
fn resolve_2d<'a, 'b, 'c>(
focused: Entity,
direction: Direction,
cycles: bool,
siblings: &'a [Entity],
transform: &'b Query<&'c GlobalTransform>,
) -> Option<&'a Entity> {
use Direction::*;
let pos_of = |entity: Entity| {
transform
.get(entity)
.expect("Focusable entities must have a GlobalTransform component")
.translation
.xy()
};
let focused_pos = pos_of(focused);
let closest = siblings
.iter()
.filter(|sibling| direction.is_in(focused_pos, pos_of(**sibling)) && **sibling != focused);
let closest = max_by_in_iter(closest, |s| -focused_pos.distance_squared(pos_of(**s)));
match closest {
None if cycles => {
let focused_pos = match direction {
South => Vec2::new(focused_pos.x, 3000.0),
North => Vec2::new(focused_pos.x, 0.0),
East => Vec2::new(0.0, focused_pos.y),
West => Vec2::new(3000.0, focused_pos.y),
};
max_by_in_iter(siblings.iter(), |s| {
-focused_pos.distance_squared(pos_of(**s))
})
}
anyelse => anyelse,
}
}
fn max_by_in_iter<U, T: PartialOrd>(
iter: impl Iterator<Item = U>,
f: impl Fn(&U) -> T,
) -> Option<U> {
iter.max_by(|s1, s2| {
let s1_val = f(s1);
let s2_val = f(s2);
s1_val.partial_cmp(&s2_val).unwrap_or(Ordering::Equal)
})
}
fn resolve_scope(
focused: Entity,
direction: ScopeDirection,
cycles: bool,
siblings: &NonEmpty<Entity>,
) -> Option<&Entity> {
let focused_index = siblings
.iter()
.enumerate()
.find(|e| *e.1 == focused)
.map(|e| e.0)?;
let new_index = resolve_index(focused_index, cycles, direction, siblings.len().get() - 1);
new_index.and_then(|i| siblings.get(i))
}
fn resolve(
focused: Entity,
request: NavRequest,
queries: &NavQueries,
lock: &mut NavLock,
from: Vec<Entity>,
) -> NavEvent {
use NavRequest::*;
assert!(
queries.focusables.get(focused).is_ok(),
"The resolution algorithm MUST go from a focusable element"
);
assert!(
!from.contains(&focused),
"Navigation graph cycle detected! This panic has prevented a stack overflow, \
please check usages of `NavMenu::reachable_from`"
);
let mut from = (from, focused).into();
macro_rules! or_none {
($to_match:expr) => {
match $to_match {
Some(x) => x,
None => return NavEvent::NoChanges { from, request },
}
};
}
match request {
Move(direction) => {
let (parent, cycles) = match parent_menu(focused, queries) {
Some(val) if !val.1.setting.is_2d() => {
return NavEvent::NoChanges { from, request }
}
Some(val) => (Some(val.0), val.1.setting.cycles()),
None => (None, true),
};
let siblings = match parent {
Some(parent) => children_focusables(parent, queries),
None => {
let focusables: Vec<_> = queries.focusables.iter().map(|tpl| tpl.0).collect();
NonEmpty::try_from(focusables).expect(
"There must be at least one `Focusable` when sending a `NavRequest`!",
)
}
};
let to = resolve_2d(focused, direction, cycles, &siblings, &queries.transform);
let to = or_none!(to);
NavEvent::focus_changed(*to, from)
}
Cancel => {
let to = or_none!(parent_menu(focused, queries));
let to = or_none!(to.1.focus_parent);
from.push(to);
NavEvent::focus_changed(to, from)
}
Action => {
if let Ok((_, focusable)) = queries.focusables.get(focused) {
match focusable.action {
ActionType::Cancel => {
let mut from = from.to_vec();
from.truncate(from.len() - 1);
return resolve(focused, NavRequest::Cancel, queries, lock, from);
}
ActionType::Lock => {
lock.entity = Some(focused);
return NavEvent::Locked(focused);
}
ActionType::Normal => {}
}
}
let child_menu = child_menu(focused, queries);
let (child_menu, menu) = or_none!(child_menu);
let to = menu.non_inert_child().unwrap_or_else(|| {
let ret = children_focusables(child_menu, queries);
*non_inert_within(&ret, queries)
});
let to = (to, from.clone().into()).into();
NavEvent::FocusChanged { to, from }
}
ScopeMove(scope_dir) => {
let (parent, menu) = or_none!(parent_menu(focused, queries));
let siblings = children_focusables(parent, queries);
if !menu.setting.is_scope() {
let focused = or_none!(menu.focus_parent);
resolve(focused, request, queries, lock, from.into())
} else {
let cycles = menu.setting.cycles();
let to = or_none!(resolve_scope(focused, scope_dir, cycles, &siblings));
let extra = match child_menu(*to, queries) {
Some((_, menu)) => focus_deep(menu, queries),
None => Vec::new(),
};
let to = (extra, *to).into();
NavEvent::FocusChanged { to, from }
}
}
FocusOn(new_to_focus) => {
let mut from = root_path(focused, queries);
let mut to = root_path(new_to_focus, queries);
trim_common_tail(&mut from, &mut to);
if from == to {
NavEvent::NoChanges { from, request }
} else {
NavEvent::FocusChanged { from, to }
}
}
Free => {
if let Some(lock_entity) = lock.entity.take() {
NavEvent::Unlocked(lock_entity)
} else {
bevy::log::warn!("Received a NavRequest::Free while not locked");
NavEvent::NoChanges { from, request }
}
}
}
}
fn cache_non_inert(child: Entity, queries: &NavQueries, cmds: &mut Commands) {
if let Some((menu, nav_menu)) = parent_menu(child, queries) {
if let Some(entity) = nav_menu.non_inert_child() {
cmds.add(commands::set_focus_state(entity, FocusState::Inert));
}
let updated_menu = nav_menu.with_non_inert_child(Some(child));
cmds.entity(menu).insert(updated_menu);
}
}
fn listen_nav_requests(
focused: Query<Entity, With<Focused>>,
queries: NavQueries,
mut lock: ResMut<NavLock>,
mut requests: EventReader<NavRequest>,
mut events: EventWriter<NavEvent>,
mut commands: Commands,
) {
use FocusState as Fs;
let mut requests = requests.iter();
if let Some(request) = requests.next() {
if requests.next().is_some() {
bevy::log::warn!(
"Unhandled additional NavRequests, can only handle one per frame, sorry!"
)
}
if lock.is_locked() && *request != NavRequest::Free {
return;
}
let focused_id = focused.get_single().unwrap_or_else(|err| {
assert!(
!matches!(err, QuerySingleError::MultipleEntities(_)),
"Multiple entities with Focused component, this should not happen"
);
queries
.focusables
.iter()
.next()
.expect("Before sending a NavRequest, AT LEAST ONE `Focusable` should exist")
.0
});
let event = resolve(focused_id, *request, &queries, &mut lock, Vec::new());
if let NavEvent::FocusChanged { to, from } = &event {
if to == from {
return;
}
let (&disable, put_to_sleep) = from.split_last();
commands.add(commands::set_focus_state(disable, Fs::Inert));
for &entity in put_to_sleep {
cache_non_inert(entity, &queries, &mut commands);
commands.add(commands::set_focus_state(entity, Fs::Dormant));
}
let (&focus, activate) = to.split_first();
cache_non_inert(focus, &queries, &mut commands);
commands.add(commands::set_focus_state(focus, Fs::Focused));
for &entity in activate {
cache_non_inert(entity, &queries, &mut commands);
commands.add(commands::set_focus_state(entity, Fs::Active));
}
};
events.send(event);
}
}
fn child_menu<'a>(focusable: Entity, queries: &'a NavQueries) -> Option<(Entity, &'a NavMenu)> {
queries
.menus
.iter()
.find(|e| e.1.focus_parent == Some(focusable))
}
fn parent_menu(focusable: Entity, queries: &NavQueries) -> Option<(Entity, NavMenu)> {
let &Parent(parent) = queries.parents.get(focusable).ok()?;
match queries.menus.get(parent) {
Ok(menu) => Some((parent, menu.1.clone())),
Err(_) => parent_menu(parent, queries),
}
}
fn children_focusables(menu: Entity, queries: &NavQueries) -> NonEmpty<Entity> {
let ret = children_focusables_helper(menu, queries);
NonEmpty::try_from(ret)
.expect("A NavMenu MUST AT LEAST HAVE ONE Focusable child, {menu:?} has none")
}
fn children_focusables_helper(menu: Entity, queries: &NavQueries) -> Vec<Entity> {
match queries.children.get(menu).ok() {
Some(direct_children) => {
let focusables = direct_children
.iter()
.filter(|e| queries.focusables.get(**e).is_ok())
.cloned();
let transitive_focusables = direct_children
.iter()
.filter(|e| queries.focusables.get(**e).is_err())
.filter(|e| queries.menus.get(**e).is_err())
.flat_map(|e| children_focusables_helper(*e, queries));
focusables.chain(transitive_focusables).collect()
}
None => Vec::new(),
}
}
fn non_inert_within<'a, 'b>(siblings: &'a NonEmpty<Entity>, queries: &'b NavQueries) -> &'a Entity {
siblings
.iter()
.find(|e| queries.focusables.get(**e).iter().any(|f| !f.1.is_inert()))
.unwrap_or_else(|| siblings.first())
}
fn trim_common_tail<T: PartialEq>(v1: &mut NonEmpty<T>, v2: &mut NonEmpty<T>) {
let mut i1 = v1.len().get() - 1;
let mut i2 = v2.len().get() - 1;
loop {
if v1[i1] != v2[i2] {
let l1 = NonZeroUsize::new(i1.saturating_add(1)).unwrap();
let l2 = NonZeroUsize::new(i2.saturating_add(1)).unwrap();
v1.truncate(l1);
v2.truncate(l2);
return;
} else if i1 != 0 && i2 != 0 {
i1 -= 1;
i2 -= 1;
} else {
return;
}
}
}
fn root_path(mut from: Entity, queries: &NavQueries) -> NonEmpty<Entity> {
let mut ret = NonEmpty::new(from);
loop {
from = match parent_menu(from, queries) {
Some((_, menu)) if menu.focus_parent.is_some() => menu.focus_parent.unwrap(),
_ => return ret,
};
assert!(
!ret.contains(&from),
"Navigation graph cycle detected! This panic has prevented a stack \
overflow, please check usages of `NavMenu::reachable_from`"
);
ret.push(from);
}
}
fn focus_deep<'a>(mut menu: &'a NavMenu, queries: &'a NavQueries) -> Vec<Entity> {
let mut ret = Vec::with_capacity(4);
loop {
let last = match menu.non_inert_child() {
Some(additional) => {
ret.insert(0, additional);
additional
}
None => return ret,
};
menu = match child_menu(last, queries) {
Some((_, menu)) => menu,
None => return ret,
};
}
}
fn resolve_index(
from: usize,
cycles: bool,
direction: ScopeDirection,
max_value: usize,
) -> Option<usize> {
use ScopeDirection::*;
match (direction, from) {
(Previous, 0) => cycles.then(|| max_value),
(Previous, from) => Some(from - 1),
(Next, from) if from == max_value => cycles.then(|| 0),
(Next, from) => Some(from + 1),
}
}
pub struct NavigationPlugin;
impl Plugin for NavigationPlugin {
fn build(&self, app: &mut App) {
app.add_event::<NavRequest>()
.add_event::<NavEvent>()
.init_resource::<NavLock>()
.add_system(listen_nav_requests);
}
}
#[cfg(test)]
mod tests {
use super::trim_common_tail;
#[test]
fn test_trim_common_tail() {
use non_empty_vec::ne_vec;
let mut v1 = ne_vec![1, 2, 3, 4, 5, 6, 7];
let mut v2 = ne_vec![3, 2, 1, 4, 5, 6, 7];
trim_common_tail(&mut v1, &mut v2);
assert_eq!(v1, ne_vec![1, 2, 3]);
assert_eq!(v2, ne_vec![3, 2, 1]);
}
}