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
// Linting
#![warn(rust_2018_idioms)]
#![deny(clippy::all)]
#![warn(clippy::pedantic, clippy::nursery)]
#![allow(clippy::module_name_repetitions)]

#[cfg(test)]
#[macro_use]
extern crate approx;

mod managed_octree;

pub use managed_octree::{
    ManagedHashMapOctree,
    ManagedOctree,
    ManagedOctreeData,
    ManagedVecOctree,
};
use std::{
    borrow::{Borrow, BorrowMut},
    convert::{AsMut, AsRef},
};

/// A barebones octree offering just the methods required for accessing and
/// modifying its contents. Other management structures/functions will be needed
/// to make this more useful, especially for the purpose of querying contents.
#[derive(Default)]
pub struct Octree<D>
where
    D: Default,
{
    children: [Option<Box<Octree<D>>>; 8],
    data: D,
}

#[derive(Debug)]
pub enum AddChildError {
    AlreadyAdded,
    OutOfBoundsIdx,
}

impl<D> Octree<D>
where
    D: Default,
{
    #[must_use]
    pub fn new() -> Self { Self::default() }

    #[must_use]
    pub fn new_with_data(data: D) -> Self {
        Self {
            data,
            ..Self::default()
        }
    }

    /// Adds and returns a reference to a child at a particular index.
    ///
    /// # Errors
    /// Returns an error if the idx is out of range (i.e. idx >= 8) or if the
    /// child is already added.
    pub fn add_child(
        &mut self,
        idx: usize,
        child: Self,
    ) -> Result<&mut Self, AddChildError> {
        if idx >= self.children.len() {
            Err(AddChildError::OutOfBoundsIdx)
        } else if self.children[idx].is_some() {
            Err(AddChildError::AlreadyAdded)
        } else {
            self.children[idx] = Some(Box::new(child));
            self.get_child_mut(idx).ok_or(AddChildError::OutOfBoundsIdx)
        }
    }

    /// Adds and returns a reference to a child at an index based on whether the
    /// child is at the positive or negative side of each axis.
    ///
    /// # Arguments
    /// * `pos_x` - positive x axis if true, negative if false.
    /// * `pos_y` - positive y axis if true, negative if false.
    /// * `pos_z` - positive z axis if true, negative if false.
    ///
    /// # Errors
    /// Returns an error if the child is already added.
    pub fn add_child_at_pos(
        &mut self,
        pos_x: bool,
        pos_y: bool,
        pos_z: bool,
        child: Self,
    ) -> Result<&mut Self, AddChildError> {
        self.add_child(Self::get_child_idx_at_pos(pos_x, pos_y, pos_z), child)
    }

    /// Removes a child and returns the owned value, if it exists.
    pub fn remove_child(&mut self, idx: usize) -> Option<Self> {
        if self.children.get(idx).is_none() {
            None
        } else {
            self.children[idx].take().map(|c| *c)
        }
    }

    /// Removes a child at an index based on whether the child is at the
    /// positive or negative side of each access and returns the owned value, if
    /// it exists.
    ///
    /// # Arguments
    /// * `pos_x` - positive x axis if true, negative if false.
    /// * `pos_y` - positive y axis if true, negative if false.
    /// * `pos_z` - positive z axis if true, negative if false.
    pub fn remove_child_at_pos(
        &mut self,
        pos_x: bool,
        pos_y: bool,
        pos_z: bool,
    ) -> Option<Self> {
        self.remove_child(Self::get_child_idx_at_pos(pos_x, pos_y, pos_z))
    }

    /// Gets a reference to a child given an index.
    #[must_use]
    pub fn get_child(&self, idx: usize) -> Option<&Self> {
        if idx >= self.children.len() {
            None
        } else {
            self.children[idx].as_ref().map(AsRef::as_ref)
        }
    }

    /// Gets a mutable reference to a child given an index.
    #[must_use]
    pub fn get_child_mut(&mut self, idx: usize) -> Option<&mut Self> {
        if idx >= self.children.len() {
            None
        } else {
            self.children[idx].as_mut().map(AsMut::as_mut)
        }
    }

    /// Gets a child index given whether the child is at the positive or
    /// negative side of an axis.
    ///
    /// ## Arguments
    /// * `pos_x` - positive x axis if true, negative if false.
    /// * `pos_y` - positive y axis if true, negative if false.
    /// * `pos_z` - positive z axis if true, negative if false.
    fn get_child_idx_at_pos(pos_x: bool, pos_y: bool, pos_z: bool) -> usize {
        match (pos_x, pos_y, pos_z) {
            (false, false, false) => 0,
            (false, false, true) => 1,
            (false, true, false) => 2,
            (false, true, true) => 3,
            (true, false, false) => 4,
            (true, false, true) => 5,
            (true, true, false) => 6,
            (true, true, true) => 7,
        }
    }

    /// Panics if idx > 7
    fn get_child_pos_at_idx(idx: usize) -> (bool, bool, bool) {
        match idx {
            0 => (false, false, false),
            1 => (false, false, true),
            2 => (false, true, false),
            3 => (false, true, true),
            4 => (true, false, false),
            5 => (true, false, true),
            6 => (true, true, false),
            7 => (true, true, true),
            _ => panic!("idx > 7"),
        }
    }

    /// Gets a reference to a child given whether the child is at the positive
    /// or negative side of an axis.
    ///
    /// ## Arguments
    /// * `pos_x` - positive x axis if true, negative if false.
    /// * `pos_y` - positive y axis if true, negative if false.
    /// * `pos_z` - positive z axis if true, negative if false.
    #[must_use]
    pub fn get_child_at_pos(
        &self,
        pos_x: bool,
        pos_y: bool,
        pos_z: bool,
    ) -> Option<&Self> {
        self.get_child(Self::get_child_idx_at_pos(pos_x, pos_y, pos_z))
    }

    /// Gets a mutable reference to a child given whether the child is at the
    /// positive or negative side of an axis.
    ///
    /// ## Arguments
    /// * `pos_x` - positive x axis if true, negative if false.
    /// * `pos_y` - positive y axis if true, negative if false.
    /// * `pos_z` - positive z axis if true, negative if false.
    #[must_use]
    pub fn get_child_mut_at_pos(
        &mut self,
        pos_x: bool,
        pos_y: bool,
        pos_z: bool,
    ) -> Option<&mut Self> {
        self.get_child_mut(Self::get_child_idx_at_pos(pos_x, pos_y, pos_z))
    }

    /// Gets a reference to the underlying data in the node.
    #[must_use]
    pub fn get_data(&self) -> &D { self.data.borrow() }

    /// Gets a mutable reference to the underlying data in the node.
    #[must_use]
    pub fn get_data_mut(&mut self) -> &mut D { self.data.borrow_mut() }
}

#[cfg(test)]
mod tests {
    use super::Octree;

    #[test]
    fn test_get_child_out_of_bounds_initial() {
        let o = Octree::<Vec<(f32, f32, f32)>>::new();
        assert!(o.get_child(999).is_none());
    }

    #[test]
    fn test_get_child_initial() {
        let o = Octree::<Vec<(f32, f32, f32)>>::new();
        assert!(o.get_child(0).is_none());
    }

    #[test]
    fn test_get_child_pos_initial() {
        let o = Octree::<Vec<(f32, f32, f32)>>::new();
        assert!(o.get_child_at_pos(false, false, false).is_none());
    }

    #[test]
    fn test_add_child() {
        let mut o = Octree::<Vec<(f32, f32, f32)>>::new();
        let result = o.add_child(0, Octree::new());
        assert!(result.is_ok());
    }

    #[test]
    fn test_add_child_at_pos() {
        let mut o = Octree::<Vec<(f32, f32, f32)>>::new();
        let result = o.add_child_at_pos(false, false, false, Octree::new());
        assert!(result.is_ok());
    }

    #[test]
    fn test_remove_child() {
        let mut o = Octree::<Vec<(f32, f32, f32)>>::new();
        o.add_child(0, Octree::new()).unwrap();
        let result = o.remove_child(0);
        assert!(result.is_some());
        assert!(o.get_child(0).is_none());
    }

    #[test]
    fn test_remove_child_at_pos() {
        let mut o = Octree::<Vec<(f32, f32, f32)>>::new();
        o.add_child_at_pos(false, false, false, Octree::new())
            .unwrap();
        let result = o.remove_child_at_pos(false, false, false);
        assert!(result.is_some());
        assert!(o.get_child_at_pos(false, false, false).is_none());
    }
}