use super::{
Attr3, check_both_or_neither, check_keys_match, check_len, check_reserved, check_same_variant,
clone_indexed, clone_masked, extend_option,
};
use crate::common::IndexMask;
use crate::{Iso3, Point2, Result, UnitVec3};
use std::collections::HashMap;
#[derive(Debug, Clone, Default, PartialEq)]
pub struct PointAttrSet3 {
normals: Option<Vec<UnitVec3>>,
colors: Option<Vec<[u8; 3]>>,
stdev: Option<Vec<f64>>,
flat: Option<Vec<Point2>>,
open: HashMap<String, Attr3>,
}
impl PointAttrSet3 {
pub fn empty() -> Self {
Self::default()
}
pub fn is_empty(&self) -> bool {
self.normals.is_none()
&& self.colors.is_none()
&& self.stdev.is_none()
&& self.flat.is_none()
&& self.open.is_empty()
}
pub fn attr_labels(&self) -> Vec<&str> {
let mut names = Vec::new();
if self.normals.is_some() {
names.push("point_normals");
}
if self.colors.is_some() {
names.push("point_colors");
}
if self.stdev.is_some() {
names.push("point_stdev");
}
if self.flat.is_some() {
names.push("point_flat");
}
names.extend(self.open.keys().map(|k| k.as_str()));
names
}
pub fn normals(&self) -> Option<&[UnitVec3]> {
self.normals.as_deref()
}
pub fn colors(&self) -> Option<&[[u8; 3]]> {
self.colors.as_deref()
}
pub fn stdev(&self) -> Option<&[f64]> {
self.stdev.as_deref()
}
pub fn flat(&self) -> Option<&[Point2]> {
self.flat.as_deref()
}
pub fn attr(&self, name: &str) -> Option<&Attr3> {
self.open.get(name)
}
pub fn attr_names(&self) -> impl Iterator<Item = &str> {
self.open.keys().map(|k| k.as_str())
}
}
impl PointAttrSet3 {
pub fn set_normals(&mut self, values: Option<Vec<UnitVec3>>, n_points: usize) -> Result<()> {
check_len(
values.as_deref().map(|v| v.len()),
n_points,
"point_normals",
)?;
self.normals = values;
Ok(())
}
pub fn set_colors(&mut self, values: Option<Vec<[u8; 3]>>, n_points: usize) -> Result<()> {
check_len(values.as_deref().map(|v| v.len()), n_points, "point_colors")?;
self.colors = values;
Ok(())
}
pub fn set_stdev(&mut self, values: Option<Vec<f64>>, n_points: usize) -> Result<()> {
check_len(values.as_deref().map(|v| v.len()), n_points, "point_stdev")?;
if let Some(v) = &values
&& let Some(i) = v.iter().position(|s| *s < 0.0 || s.is_nan())
{
return Err(format!(
"point_stdev[{}] is {}, but a standard deviation must be finite and non-negative",
i, v[i]
)
.into());
}
self.stdev = values;
Ok(())
}
pub fn set_flat(&mut self, values: Option<Vec<Point2>>, n_points: usize) -> Result<()> {
check_len(values.as_deref().map(|v| v.len()), n_points, "point_flat")?;
self.flat = values;
Ok(())
}
pub fn insert_attr(&mut self, name: &str, attr: Attr3, n_points: usize) -> Result<()> {
check_reserved(name)?;
check_len(Some(attr.len()), n_points, name)?;
self.open.insert(name.to_string(), attr);
Ok(())
}
pub fn remove_attr(&mut self, name: &str) -> Option<Attr3> {
self.open.remove(name)
}
}
impl PointAttrSet3 {
pub fn validate(&self, n_points: usize) -> Result<()> {
check_len(
self.normals.as_ref().map(|v| v.len()),
n_points,
"point_normals",
)?;
check_len(
self.colors.as_ref().map(|v| v.len()),
n_points,
"point_colors",
)?;
check_len(
self.stdev.as_ref().map(|v| v.len()),
n_points,
"point_stdev",
)?;
check_len(self.flat.as_ref().map(|v| v.len()), n_points, "point_flat")?;
for (name, attr) in self.open.iter() {
check_len(Some(attr.len()), n_points, name)?;
}
Ok(())
}
pub fn subset(&self, mask: &IndexMask) -> Result<Self> {
let mut open = HashMap::with_capacity(self.open.len());
for (name, attr) in self.open.iter() {
open.insert(name.clone(), attr.clone_indices_of(mask)?);
}
Ok(Self {
normals: clone_masked(self.normals.as_deref(), mask)?,
colors: clone_masked(self.colors.as_deref(), mask)?,
stdev: clone_masked(self.stdev.as_deref(), mask)?,
flat: clone_masked(self.flat.as_deref(), mask)?,
open,
})
}
pub fn subset_indices(&self, indices: &[usize]) -> Result<Self> {
let mut open = HashMap::with_capacity(self.open.len());
for (name, attr) in self.open.iter() {
open.insert(name.clone(), attr.clone_indices(indices)?);
}
Ok(Self {
normals: clone_indexed(self.normals.as_deref(), indices)?,
colors: clone_indexed(self.colors.as_deref(), indices)?,
stdev: clone_indexed(self.stdev.as_deref(), indices)?,
flat: clone_indexed(self.flat.as_deref(), indices)?,
open,
})
}
pub fn extend_from(&mut self, other: &Self) -> Result<()> {
self.check_extend_from(other)?;
self.apply_extend_from(other)
}
pub(crate) fn check_extend_from(&self, other: &Self) -> Result<()> {
check_both_or_neither(
self.normals.is_some(),
other.normals.is_some(),
"point_normals",
)?;
check_both_or_neither(
self.colors.is_some(),
other.colors.is_some(),
"point_colors",
)?;
check_both_or_neither(self.stdev.is_some(), other.stdev.is_some(), "point_stdev")?;
check_both_or_neither(self.flat.is_some(), other.flat.is_some(), "point_flat")?;
check_keys_match(&self.open, &other.open, "point")?;
for (name, attr) in self.open.iter() {
check_same_variant(attr, &other.open[name], name)?;
}
Ok(())
}
pub(crate) fn apply_extend_from(&mut self, other: &Self) -> Result<()> {
extend_option(&mut self.normals, other.normals.as_deref());
extend_option(&mut self.colors, other.colors.as_deref());
extend_option(&mut self.stdev, other.stdev.as_deref());
extend_option(&mut self.flat, other.flat.as_deref());
for (name, attr) in self.open.iter_mut() {
attr.extend_from(&other.open[name])?;
}
Ok(())
}
}
impl PointAttrSet3 {
pub fn transform_in_place(&mut self, iso: &Iso3) {
if let Some(normals) = &mut self.normals {
for n in normals.iter_mut() {
*n = iso * *n;
}
}
for attr in self.open.values_mut() {
attr.transform_in_place(iso);
}
}
pub fn scale_in_place(&mut self, scale: f64) {
let k = scale.abs();
if let Some(stdev) = &mut self.stdev {
for s in stdev.iter_mut() {
*s *= k;
}
}
if let Some(flat) = &mut self.flat {
for f in flat.iter_mut() {
*f = Point2::from(f.coords * k);
}
}
}
pub fn flip_in_place(&mut self) {
if let Some(normals) = &mut self.normals {
for n in normals.iter_mut() {
*n = -*n;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Vector3;
use crate::geom3::attributes3::RESERVED_ATTR_NAMES;
use approx::assert_relative_eq;
use std::f64::consts::FRAC_PI_2;
const N: usize = 4;
fn full_attrs() -> PointAttrSet3 {
let mut attrs = PointAttrSet3::empty();
attrs
.set_normals(
Some(vec![
UnitVec3::new_normalize(Vector3::new(1.0, 0.0, 0.0)),
UnitVec3::new_normalize(Vector3::new(0.0, 1.0, 0.0)),
UnitVec3::new_normalize(Vector3::new(0.0, 0.0, 1.0)),
UnitVec3::new_normalize(Vector3::new(1.0, 1.0, 1.0)),
]),
N,
)
.unwrap();
attrs
.set_colors(Some(vec![[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3]]), N)
.unwrap();
attrs.set_stdev(Some(vec![0.1, 0.2, 0.3, 0.4]), N).unwrap();
attrs
.set_flat(
Some(vec![
Point2::new(0.0, 0.0),
Point2::new(1.0, 0.0),
Point2::new(1.0, 1.0),
Point2::new(0.0, 1.0),
]),
N,
)
.unwrap();
attrs
.insert_attr("confidence", Attr3::Scalar(vec![0.5, 0.6, 0.7, 0.8]), N)
.unwrap();
attrs
}
#[test]
fn empty_set_reports_empty() {
let attrs = PointAttrSet3::empty();
assert!(attrs.is_empty());
assert!(attrs.normals().is_none());
assert!(attrs.colors().is_none());
assert!(attrs.stdev().is_none());
assert!(attrs.flat().is_none());
assert_eq!(attrs.attr_names().count(), 0);
assert!(!full_attrs().is_empty());
}
#[test]
fn attr_labels_names_every_present_attribute() {
let attrs = full_attrs();
let labels = attrs.attr_labels();
for expected in [
"point_normals",
"point_colors",
"point_stdev",
"point_flat",
"confidence",
] {
assert!(
labels.contains(&expected),
"missing '{expected}' in {labels:?}"
);
}
assert!(PointAttrSet3::empty().attr_labels().is_empty());
}
#[test]
fn setters_reject_a_length_mismatch() {
let mut attrs = PointAttrSet3::empty();
assert!(attrs.set_colors(Some(vec![[0, 0, 0]]), N).is_err());
assert!(attrs.set_normals(Some(Vec::new()), N).is_err());
assert!(attrs.insert_attr("q", Attr3::Scalar(vec![1.0]), N).is_err());
assert!(attrs.is_empty());
}
#[test]
fn setters_accept_none_regardless_of_count() -> Result<()> {
let mut attrs = full_attrs();
attrs.set_colors(None, N)?;
assert!(attrs.colors().is_none());
Ok(())
}
#[test]
fn stdev_rejects_negative_and_nan() {
let mut attrs = PointAttrSet3::empty();
assert!(attrs.set_stdev(Some(vec![0.1, -0.2, 0.3, 0.4]), N).is_err());
assert!(
attrs
.set_stdev(Some(vec![0.1, f64::NAN, 0.3, 0.4]), N)
.is_err()
);
assert!(attrs.set_stdev(Some(vec![0.0, 0.2, 0.3, 0.4]), N).is_ok());
}
#[test]
fn open_map_rejects_reserved_names() {
let mut attrs = PointAttrSet3::empty();
for name in RESERVED_ATTR_NAMES {
assert!(
attrs
.insert_attr(name, Attr3::Scalar(vec![0.0; N]), N)
.is_err(),
"expected '{name}' to be rejected as an attribute name"
);
}
assert!(
attrs
.insert_attr("scanner_color_temp", Attr3::Scalar(vec![0.0; N]), N)
.is_ok()
);
}
#[test]
fn remove_attr_returns_what_was_stored() {
let mut attrs = full_attrs();
let taken = attrs.remove_attr("confidence").unwrap();
assert_eq!(taken.as_scalar().unwrap(), &[0.5, 0.6, 0.7, 0.8]);
assert!(attrs.attr("confidence").is_none());
assert!(attrs.remove_attr("confidence").is_none());
}
#[test]
fn validate_catches_a_mismatch() -> Result<()> {
let attrs = full_attrs();
attrs.validate(N)?;
assert!(attrs.validate(N + 1).is_err());
assert!(attrs.validate(0).is_err());
PointAttrSet3::empty().validate(0)?;
PointAttrSet3::empty().validate(9999)?;
Ok(())
}
#[test]
fn subset_selects_the_masked_points() -> Result<()> {
let attrs = full_attrs();
let mask = IndexMask::try_from_indices(&[1, 3], N)?;
let sub = attrs.subset(&mask)?;
sub.validate(2)?;
assert_eq!(sub.colors().unwrap(), &[[1, 1, 1], [3, 3, 3]]);
assert_eq!(sub.stdev().unwrap(), &[0.2, 0.4]);
assert_eq!(
sub.flat().unwrap(),
&[Point2::new(1.0, 0.0), Point2::new(0.0, 1.0)]
);
assert_eq!(
sub.attr("confidence").unwrap().as_scalar().unwrap(),
&[0.6, 0.8]
);
Ok(())
}
#[test]
fn extend_from_unions_matching_sets() -> Result<()> {
let mut attrs = full_attrs();
attrs.extend_from(&full_attrs())?;
attrs.validate(N * 2)?;
assert_eq!(attrs.stdev().unwrap().len(), N * 2);
assert_eq!(attrs.attr("confidence").unwrap().len(), N * 2);
Ok(())
}
#[test]
fn extend_from_rejects_a_typed_field_on_only_one_side() {
let mut attrs = full_attrs();
let mut other = full_attrs();
other.set_stdev(None, N).unwrap();
assert!(attrs.extend_from(&other).is_err());
assert_eq!(attrs, full_attrs());
}
#[test]
fn extend_from_rejects_an_open_key_on_only_one_side() {
let mut attrs = full_attrs();
let mut other = full_attrs();
other.remove_attr("confidence");
assert!(attrs.extend_from(&other).is_err());
assert_eq!(attrs, full_attrs());
let mut attrs = full_attrs();
attrs.remove_attr("confidence");
assert!(attrs.extend_from(&full_attrs()).is_err());
}
#[test]
fn extend_from_rejects_a_variant_mismatch_under_the_same_name() {
let mut attrs = full_attrs();
let mut other = full_attrs();
other.remove_attr("confidence");
other
.insert_attr("confidence", Attr3::Label(vec![1, 2, 3, 4]), N)
.unwrap();
assert!(attrs.extend_from(&other).is_err());
assert_eq!(attrs, full_attrs());
}
#[test]
fn transform_rotates_normals_and_vector_attrs() -> Result<()> {
let mut attrs = full_attrs();
attrs.insert_attr(
"principal_dir",
Attr3::Vector(vec![Vector3::new(1.0, 0.0, 0.0); N]),
N,
)?;
let iso = Iso3::new(Vector3::new(5.0, 6.0, 7.0), Vector3::z() * FRAC_PI_2);
attrs.transform_in_place(&iso);
assert_relative_eq!(
attrs.normals().unwrap()[0].into_inner(),
Vector3::new(0.0, 1.0, 0.0),
epsilon = 1.0e-12
);
assert_relative_eq!(
attrs.attr("principal_dir").unwrap().as_vector().unwrap()[0],
Vector3::new(0.0, 1.0, 0.0),
epsilon = 1.0e-12
);
assert_eq!(attrs.stdev().unwrap(), &[0.1, 0.2, 0.3, 0.4]);
assert_eq!(attrs.flat(), full_attrs().flat());
assert_eq!(
attrs.attr("confidence").unwrap().as_scalar().unwrap(),
&[0.5, 0.6, 0.7, 0.8]
);
Ok(())
}
#[test]
fn scale_affects_the_standard_deviations_and_flat_coordinates() {
let mut attrs = full_attrs();
attrs.scale_in_place(25.4);
for (actual, expected) in attrs
.flat()
.unwrap()
.iter()
.zip(full_attrs().flat().unwrap().iter())
{
assert_relative_eq!(actual.coords, expected.coords * 25.4, epsilon = 1.0e-12);
}
for (actual, expected) in attrs
.stdev()
.unwrap()
.iter()
.zip([0.1, 0.2, 0.3, 0.4].iter())
{
assert_relative_eq!(*actual, expected * 25.4, epsilon = 1.0e-12);
}
assert_eq!(
attrs.attr("confidence").unwrap().as_scalar().unwrap(),
&[0.5, 0.6, 0.7, 0.8]
);
}
#[test]
fn scale_keeps_standard_deviations_positive_under_mirroring() {
let mut attrs = full_attrs();
attrs.scale_in_place(-2.0);
for s in attrs.stdev().unwrap() {
assert!(*s >= 0.0, "a standard deviation must not go negative");
}
assert_relative_eq!(attrs.stdev().unwrap()[1], 0.4, epsilon = 1.0e-12);
assert_relative_eq!(
attrs.flat().unwrap()[1].coords,
Point2::new(2.0, 0.0).coords,
epsilon = 1.0e-12
);
}
#[test]
fn flip_negates_the_normals() {
let original = full_attrs();
let mut attrs = full_attrs();
attrs.flip_in_place();
for (flipped, source) in attrs
.normals()
.unwrap()
.iter()
.zip(original.normals().unwrap().iter())
{
assert_relative_eq!(
flipped.into_inner(),
-source.into_inner(),
epsilon = 1.0e-12
);
}
assert_eq!(attrs.colors(), original.colors());
assert_eq!(attrs.stdev(), original.stdev());
assert_eq!(attrs.flat(), original.flat());
}
}