Skip to main content

rapier2d/data/
modified_objects.rs

1use crate::alloc_prelude::*;
2use core::marker::PhantomData;
3use core::ops::Deref;
4
5/// Contains handles of modified objects.
6///
7/// This is a wrapper over a `Vec` to ensure we don’t forget to set the object’s
8/// MODIFIED flag when adding it to this set.
9/// It is possible to bypass the wrapper with `.as_mut_internal`. But this should only
10/// be done for internal engine usage (like the physics pipeline).
11#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
12#[derive(Clone, Debug)]
13pub struct ModifiedObjects<Handle, Object>(Vec<Handle>, PhantomData<Object>);
14
15impl<Handle, Object> Default for ModifiedObjects<Handle, Object> {
16    fn default() -> Self {
17        Self(Vec::new(), PhantomData)
18    }
19}
20
21/// Objects that internally track a flag indicating whether they've been modified
22pub trait HasModifiedFlag {
23    /// Whether the object has been modified
24    fn has_modified_flag(&self) -> bool;
25    /// Mark object as modified
26    fn set_modified_flag(&mut self);
27}
28
29impl<Handle, Object> Deref for ModifiedObjects<Handle, Object> {
30    type Target = Vec<Handle>;
31    fn deref(&self) -> &Self::Target {
32        &self.0
33    }
34}
35
36impl<Handle, Object: HasModifiedFlag> ModifiedObjects<Handle, Object> {
37    /// Preallocate memory for `capacity` handles
38    pub fn with_capacity(capacity: usize) -> Self {
39        Self(Vec::with_capacity(capacity), PhantomData)
40    }
41
42    /// Remove every handle from this set.
43    ///
44    /// Note that the corresponding object MODIFIED flags won’t be reset automatically by this function.
45    pub fn clear(&mut self) {
46        self.0.clear()
47    }
48
49    /// Pushes a object handle to this set after checking that it doesn’t have the MODIFIED
50    /// flag set.
51    ///
52    /// This will also set the object’s MODIFIED flag.
53    pub fn push_once(&mut self, handle: Handle, object: &mut Object) {
54        if !object.has_modified_flag() {
55            self.push_unchecked(handle, object);
56        }
57    }
58
59    /// Pushes an object handle to this set without checking if the object already has the MODIFIED
60    /// flags.
61    ///
62    /// Only use in situation where you are certain (due to other contextual information) that
63    /// the object isn’t already in the set.
64    ///
65    /// This will also set the object’s MODIFIED flag.
66    pub fn push_unchecked(&mut self, handle: Handle, object: &mut Object) {
67        object.set_modified_flag();
68        self.0.push(handle);
69    }
70}