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
use std::fmt;

use fj_math::{Point, Scalar};

use crate::objects::Edge;

pub fn validate_edge(
    edge: &Edge,
    max_distance: impl Into<Scalar>,
) -> Result<(), CoherenceIssues> {
    let max_distance = max_distance.into();

    // Validate that the local and global forms of the vertices match. As a side
    // effect, this also happens to validate that the global forms of the
    // vertices lie on the curve.

    let mut edge_vertex_mismatches = Vec::new();

    for vertex in edge.vertices().iter() {
        let local = vertex.position();
        let local_as_global =
            edge.curve().global().kind().point_from_curve_coords(local);
        let global = vertex.global().position();
        let distance = (local_as_global - global).magnitude();

        if distance > max_distance {
            edge_vertex_mismatches.push(CoherenceMismatch {
                local,
                local_as_global,
                global,
            });
        }
    }

    if !edge_vertex_mismatches.is_empty() {
        return Err(CoherenceIssues {
            edge_vertex_mismatches,
        });
    }

    Ok(())
}

/// Geometric issues found during validation
///
/// Used by [`ValidationError`].
///
/// [`ValidationError`]: super::ValidationError
#[derive(Debug, Default, thiserror::Error)]
pub struct CoherenceIssues {
    /// Mismatches between the local and global forms of edge vertices
    pub edge_vertex_mismatches: Vec<CoherenceMismatch<Point<1>, Point<3>>>,
}

impl fmt::Display for CoherenceIssues {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "Geometric issues found:")?;

        if !self.edge_vertex_mismatches.is_empty() {
            writeln!(f, "- Edge vertex mismatches:")?;

            for mismatch in &self.edge_vertex_mismatches {
                writeln!(f, "  - {}", mismatch)?;
            }
        }

        Ok(())
    }
}

/// A mismatch between the local and global forms of an object
///
/// Used in [`CoherenceIssues`].
#[derive(Debug)]
pub struct CoherenceMismatch<Local, Global> {
    /// The local form of the object
    pub local: Local,

    /// The local form of the object, converted into the global form
    pub local_as_global: Global,

    /// The global form of the object
    pub global: Global,
}

impl<Local, Canonical> fmt::Display for CoherenceMismatch<Local, Canonical>
where
    Local: fmt::Debug,
    Canonical: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "local: {:?} (converted to global: {:?}), global: {:?},",
            self.local, self.local_as_global, self.global,
        )
    }
}