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
use bevy_ecs::prelude::*;
use bevy_property::Properties;
use bevy_utils::{HashMap, HashSet};
use std::{
borrow::Cow,
fmt::Debug,
ops::{Deref, DerefMut},
};
#[derive(Default, Properties)]
pub struct Labels {
labels: HashSet<Cow<'static, str>>,
}
impl Debug for Labels {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut list = f.debug_list();
for label in self.iter() {
list.entry(&label);
}
list.finish()
}
}
impl<'a, T, L: Into<Cow<'static, str>>> From<T> for Labels
where
T: IntoIterator<Item = L>,
{
fn from(value: T) -> Self {
let mut labels = HashSet::default();
for label in value {
labels.insert(label.into());
}
Self { labels }
}
}
impl Labels {
pub fn contains<T: Into<Cow<'static, str>>>(&self, label: T) -> bool {
self.labels.contains(&label.into())
}
pub fn insert<T: Into<Cow<'static, str>>>(&mut self, label: T) {
self.labels.insert(label.into());
}
pub fn iter(&self) -> impl Iterator<Item = &str> {
self.labels.iter().map(|label| label.deref())
}
}
#[derive(Debug, Default)]
pub struct EntityLabels {
label_entities: HashMap<Cow<'static, str>, Vec<Entity>>,
entity_labels: HashMap<Entity, HashSet<Cow<'static, str>>>,
}
impl EntityLabels {
pub fn get(&self, label: &str) -> Option<&[Entity]> {
self.label_entities
.get(label)
.map(|entities| entities.as_slice())
}
}
pub(crate) fn entity_labels_system(
mut entity_labels: ResMut<EntityLabels>,
query: Query<(Entity, &Labels)>,
) {
let entity_labels = entity_labels.deref_mut();
for (entity, labels) in query.iter() {
let current_labels = entity_labels
.entity_labels
.entry(entity)
.or_insert_with(HashSet::default);
for removed_label in current_labels.difference(&labels.labels) {
if let Some(entities) = entity_labels.label_entities.get_mut(removed_label) {
entities.retain(|e| *e != entity);
}
}
for added_label in labels.labels.difference(¤t_labels) {
if let Some(entities) = entity_labels.label_entities.get_mut(added_label) {
entities.push(entity);
}
}
*current_labels = labels.labels.clone();
}
}