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
use std::ops::ControlFlow;
use num_traits::Num;
#[cfg(feature = "rayon")]
use rayon::join;
use crate::{contains, split, KdTree, Object, Point};
/// Defines a spatial query by its axis-aligned bounding box (AABB) and a method to test a single point
///
/// The AABB of the query is used to limit the points which are tested and therefore the AABB should be as tight as possible while staying aligned to the coordinate axes.
/// The test method itself can then be relatively expensive like determining the distance of the given position to an arbitrary polygon.
///
/// A very simple example of implementing this trait is [`WithinBoundingBox`] whereas a very common example is [`WithinDistance`].
pub trait Query<P: Point> {
/// Return the axis-aligned bounding box (AABB) of the query
///
/// Represented by the corners with first the smallest and then the largest coordinate values.
///
/// Note that calling this method is assumed to be cheap, returning a reference to an AABB stored in the interior of the object.
fn aabb(&self) -> &(P, P);
/// Check whether a given `position` inside the [axis-aligned bounding box (AABB)][Self::aabb] machtes the query.
fn test(&self, position: &P) -> bool;
}
/// A query which yields all objects within a given axis-aligned boundary box (AABB) in `N`-dimensional space
#[derive(Debug)]
pub struct WithinBoundingBox<T, const N: usize> {
aabb: ([T; N], [T; N]),
}
impl<T, const N: usize> WithinBoundingBox<T, N> {
/// Construct a query from first the corner smallest coordinate values `lower` and then the corner with the largest coordinate values `upper`
pub fn new(lower: [T; N], upper: [T; N]) -> Self {
Self {
aabb: (lower, upper),
}
}
}
impl<T, const N: usize> Query<[T; N]> for WithinBoundingBox<T, N>
where
T: Num + Copy + PartialOrd,
{
fn aabb(&self) -> &([T; N], [T; N]) {
&self.aabb
}
fn test(&self, _position: &[T; N]) -> bool {
true
}
}
/// A query which yields all objects within a given distance to a central point in `N`-dimensional real space
#[derive(Debug)]
pub struct WithinDistance<T, const N: usize> {
aabb: ([T; N], [T; N]),
center: [T; N],
distance_2: T,
}
impl<T, const N: usize> WithinDistance<T, N>
where
T: Num + Copy + PartialOrd,
{
/// Construct a query from the `center` and the largest allowed Euclidean `distance` to it
pub fn new(center: [T; N], distance: T) -> Self {
Self {
aabb: (
center.map(|coord| coord - distance),
center.map(|coord| coord + distance),
),
center,
distance_2: distance * distance,
}
}
}
impl<T, const N: usize> Query<[T; N]> for WithinDistance<T, N>
where
T: Num + Copy + PartialOrd,
{
fn aabb(&self) -> &([T; N], [T; N]) {
&self.aabb
}
fn test(&self, position: &[T; N]) -> bool {
self.center.distance_2(position) <= self.distance_2
}
}
impl<O, S> KdTree<O, S>
where
O: Object,
S: AsRef<[O]>,
{
/// Find objects matching the given `query`
///
/// Queries are defined by passing an implementor of the [`Query`] trait.
///
/// Objects matching the `query` are passed to the `visitor` as they are found.
/// Depending on its [return value][`ControlFlow`], the search is continued or stopped.
pub fn look_up<'a, Q, V>(&'a self, query: &Q, visitor: V) -> ControlFlow<()>
where
Q: Query<O::Point>,
V: FnMut(&'a O) -> ControlFlow<()>,
{
let objects = self.objects.as_ref();
if !objects.is_empty() {
look_up(&mut LookUpArgs { query, visitor }, objects, 0)?;
}
ControlFlow::Continue(())
}
#[cfg(feature = "rayon")]
/// Find objects matching the given `query`, in parallel
///
/// Queries are defined by passing an implementor of the [`Query`] trait.
///
/// Objects matching the `query` are passed to the `visitor` as they are found.
/// In contrast to the [serial version][Self::look_up], the search cannot be stopped early.
///
/// Requires the `rayon` feature and dispatches tasks into the current [thread pool][rayon::ThreadPool].
pub fn par_look_up<'a, Q, V>(&'a self, query: &Q, visitor: V)
where
O: Send + Sync,
O::Point: Sync,
Q: Query<O::Point> + Sync,
V: Fn(&'a O) + Sync,
{
let objects = self.objects.as_ref();
if !objects.is_empty() {
par_look_up(&LookUpArgs { query, visitor }, objects, 0);
}
}
}
struct LookUpArgs<'a, Q, V> {
query: &'a Q,
visitor: V,
}
fn look_up<'a, O, Q, V>(
args: &mut LookUpArgs<Q, V>,
mut objects: &'a [O],
mut axis: usize,
) -> ControlFlow<()>
where
O: Object,
Q: Query<O::Point>,
V: FnMut(&'a O) -> ControlFlow<()>,
{
loop {
let (left, object, right) = split(objects);
let position = object.position();
if contains(args.query.aabb(), position) && args.query.test(position) {
(args.visitor)(object)?;
}
let search_left =
!left.is_empty() && args.query.aabb().0.coord(axis) <= position.coord(axis);
let search_right =
!right.is_empty() && position.coord(axis) <= args.query.aabb().1.coord(axis);
axis = (axis + 1) % O::Point::DIM;
match (search_left, search_right) {
(true, true) => {
look_up(args, left, axis)?;
objects = right;
}
(true, false) => objects = left,
(false, true) => objects = right,
(false, false) => return ControlFlow::Continue(()),
}
}
}
#[cfg(feature = "rayon")]
fn par_look_up<'a, O, Q, V>(args: &LookUpArgs<Q, V>, mut objects: &'a [O], mut axis: usize)
where
O: Object + Send + Sync,
O::Point: Sync,
Q: Query<O::Point> + Sync,
V: Fn(&'a O) + Sync,
{
loop {
let (left, object, right) = split(objects);
let position = object.position();
if contains(args.query.aabb(), position) && args.query.test(position) {
(args.visitor)(object);
}
let search_left =
!left.is_empty() && args.query.aabb().0.coord(axis) <= position.coord(axis);
let search_right =
!right.is_empty() && position.coord(axis) <= args.query.aabb().1.coord(axis);
axis = (axis + 1) % O::Point::DIM;
match (search_left, search_right) {
(true, true) => {
join(
|| par_look_up(args, left, axis),
|| par_look_up(args, right, axis),
);
return;
}
(true, false) => objects = left,
(false, true) => objects = right,
(false, false) => return,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "rayon")]
use std::sync::Mutex;
use proptest::{collection::vec, strategy::Strategy, test_runner::TestRunner};
use crate::tests::{random_objects, random_points};
pub fn random_queries(len: usize) -> impl Strategy<Value = Vec<WithinDistance<f32, 2>>> {
(random_points(len), vec(0.0_f32..=1.0, len)).prop_map(|(centers, distances)| {
centers
.into_iter()
.zip(distances)
.map(|(center, distance)| WithinDistance::new(center, distance))
.collect()
})
}
#[test]
fn random_look_up() {
TestRunner::default()
.run(
&(random_objects(100), random_queries(10)),
|(objects, queries)| {
let index = KdTree::new(objects);
for query in queries {
let mut results1 = index
.iter()
.filter(|object| query.test(object.position()))
.collect::<Vec<_>>();
let mut results2 = Vec::new();
index.look_up(&query, |object| {
results2.push(object);
ControlFlow::Continue(())
});
results1.sort_unstable();
results2.sort_unstable();
assert_eq!(results1, results2);
}
Ok(())
},
)
.unwrap();
}
#[cfg(feature = "rayon")]
#[test]
fn random_par_look_up() {
TestRunner::default()
.run(
&(random_objects(100), random_queries(10)),
|(objects, queries)| {
let index = KdTree::par_new(objects);
for query in queries {
let mut results1 = index
.iter()
.filter(|object| query.test(object.position()))
.collect::<Vec<_>>();
let results2 = Mutex::new(Vec::new());
index.par_look_up(&query, |object| {
results2.lock().unwrap().push(object);
});
let mut results2 = results2.into_inner().unwrap();
results1.sort_unstable();
results2.sort_unstable();
assert_eq!(results1, results2);
}
Ok(())
},
)
.unwrap();
}
}