fix(ecs): some replacement issues

This commit is contained in:
lisk77 2025-11-25 13:24:59 +01:00
parent a01a52766d
commit eced6ddf3f
8 changed files with 176 additions and 112 deletions

View file

@ -272,6 +272,22 @@ impl Column {
}
}
/// Overwrites an existing element in place, dropping the previous value.
pub fn set<T: 'static>(&mut self, index: usize, item: T) -> Option<()> {
assert_eq!(TypeId::of::<T>(), TypeId::of::<T>(), "Type mismatch");
if index >= self.data.len() {
return None;
}
unsafe {
let ptr = self.data.get_unchecked_mut(index) as *mut T;
ptr::drop_in_place(ptr);
ptr::write(ptr, item);
}
Some(())
}
pub fn swap(&mut self, index1: usize, index2: usize) {
assert!(
index1 < self.data.len() && index2 < self.data.len(),

View file

@ -67,6 +67,10 @@ impl ComponentSet {
self.set.is_subset(&other.set)
}
pub fn is_superset(&self, other: &ComponentSet) -> bool {
self.set.is_superset(&other.set)
}
pub fn to_vec(&self) -> Vec<TypeId> {
self.set.iter().cloned().collect()
}

View file

@ -44,6 +44,39 @@ impl<K: PartialEq + Clone, V: Clone> FlatMap<K, V> {
}
}
pub fn get_two_mut(&mut self, a: &K, b: &K) -> (Option<&mut V>, Option<&mut V>) {
if a == b {
let first = self.get_mut(a);
return (first, None);
}
let mut first_index = None;
let mut second_index = None;
for (idx, (key, _)) in self.map.iter().enumerate() {
if key == a {
first_index = Some(idx);
} else if key == b {
second_index = Some(idx);
}
}
match (first_index, second_index) {
(Some(i), Some(j)) => {
if i < j {
let (left, right) = self.map.split_at_mut(j);
(Some(&mut left[i].1), Some(&mut right[0].1))
} else {
let (left, right) = self.map.split_at_mut(i);
(Some(&mut right[0].1), Some(&mut left[j].1))
}
}
(Some(i), None) => (self.map.get_mut(i).map(|pair| &mut pair.1), None),
(None, Some(j)) => (None, self.map.get_mut(j).map(|pair| &mut pair.1)),
_ => (None, None),
}
}
pub fn contains(&self, key: &K) -> bool {
self.map.iter().any(|node| node.0 == *key)
}
@ -51,4 +84,4 @@ impl<K: PartialEq + Clone, V: Clone> FlatMap<K, V> {
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut (K, V)> {
self.map.iter_mut()
}
}
}

View file

@ -28,6 +28,12 @@ impl SparseSet {
}
if let Some(page_vec) = &mut self.sparse[page] {
// If there is already a mapping, overwrite the existing dense value instead of pushing.
if let Some(sparse_index) = page_vec[index % self.page_size] {
let _ = self.dense.set::<T>(sparse_index, value);
return;
}
page_vec[index % self.page_size] = Some(self.dense.data.len());
}