rust_3d/
is_buildable_nd.rs

1/*
2Copyright 2017 Martin Buck
3
4Permission is hereby granted, free of charge, to any person obtaining a copy
5of this software and associated documentation files (the "Software"),
6to deal in the Software without restriction, including without limitation the
7rights to use, copy, modify, merge, publish, distribute, sublicense,
8and/or sell copies of the Software, and to permit persons to whom the Software
9is furnished to do so, subject to the following conditions:
10
11The above copyright notice and this permission notice shall
12be included all copies or substantial portions of the Software.
13
14THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
20OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21*/
22
23//! IsBuildableND trait used for types which are positioned in n-dimensional space and can be constructed
24
25use crate::*;
26
27//------------------------------------------------------------------------------
28
29/// IsBuildableND is a trait used for types which are positioned in n-dimensional space and can be constructed
30pub trait IsBuildableND: Sized + IsND {
31    /// Should build an object from the correct number of coordinates
32    fn new_nd(coords: &[f64]) -> Result<Self>;
33    /// Should use the coordinates of another as its own
34    fn from_nd<P>(&mut self, other: P) -> Result<()>
35    where
36        P: IsBuildableND;
37
38    /// Returns a new object with 0 for all coordinates
39    #[inline(always)]
40    fn zero_nd() -> Result<Self> {
41        Self::new_nd(&vec![0.0; Self::n_dimensions()])
42    }
43    /// Returns the center between this and other
44    fn center_nd<P>(&self, other: &P, buffer: &mut Vec<f64>) -> Result<Self>
45    where
46        P: IsND,
47    {
48        let n = Self::n_dimensions();
49
50        if n != P::n_dimensions() {
51            return Err(ErrorKind::IncorrectDimension);
52        }
53
54        buffer.clear();
55        for i in 0..n {
56            buffer.push(0.5 * (self.position_nd(i)? + other.position_nd(i)?));
57        }
58
59        Self::new_nd(&buffer)
60    }
61}