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

use fj_math::{Point, Scalar};

use crate::{
    objects::{GlobalVertex, Surface, SurfaceVertex, Vertex},
    storage::Handle,
};

use super::{Validate, ValidationConfig};

impl Validate for Vertex {
    type Error = VertexValidationError;

    fn validate_with_config(
        &self,
        config: &ValidationConfig,
    ) -> Result<(), Self::Error> {
        VertexValidationError::check_surface_identity(self)?;
        VertexValidationError::check_position(self, config)?;
        Ok(())
    }
}

impl Validate for SurfaceVertex {
    type Error = SurfaceVertexValidationError;

    fn validate_with_config(
        &self,
        config: &ValidationConfig,
    ) -> Result<(), Self::Error> {
        SurfaceVertexValidationError::check_position(self, config)?;
        Ok(())
    }
}

impl Validate for GlobalVertex {
    type Error = Infallible;

    fn validate_with_config(
        &self,
        _: &ValidationConfig,
    ) -> Result<(), Self::Error> {
        Ok(())
    }
}

/// [`Vertex`] validation failed
#[derive(Clone, Debug, thiserror::Error)]
pub enum VertexValidationError {
    /// Mismatch between the surface's of the curve and surface form
    #[error(
        "Surface form of vertex must be defined on same surface as curve\n\
        - `Surface` of curve: {curve_surface:#?}\n\
        - `Surface` of surface form: {surface_form_surface:#?}"
    )]
    SurfaceMismatch {
        /// The surface of the vertex' curve
        curve_surface: Handle<Surface>,

        /// The surface of the vertex' surface form
        surface_form_surface: Handle<Surface>,
    },

    /// Mismatch between position of the vertex and position of its surface form
    #[error(
        "`Vertex` position doesn't match position of its surface form\n\
        - `Vertex`: {vertex:#?}\n\
        - `SurfaceVertex`: {surface_vertex:#?}\n\
        - `Vertex` position as surface: {curve_position_as_surface:?}\n\
        - Distance between the positions: {distance}"
    )]
    PositionMismatch {
        /// The vertex
        vertex: Vertex,

        /// The mismatched surface vertex
        surface_vertex: SurfaceVertex,

        /// The curve position converted into a surface position
        curve_position_as_surface: Point<2>,

        /// The distance between the positions
        distance: Scalar,
    },
}

impl VertexValidationError {
    fn check_surface_identity(vertex: &Vertex) -> Result<(), Self> {
        let curve_surface = vertex.curve().surface();
        let surface_form_surface = vertex.surface_form().surface();

        if curve_surface.id() != surface_form_surface.id() {
            return Err(VertexValidationError::SurfaceMismatch {
                curve_surface: curve_surface.clone(),
                surface_form_surface: surface_form_surface.clone(),
            });
        }

        Ok(())
    }

    fn check_position(
        vertex: &Vertex,
        config: &ValidationConfig,
    ) -> Result<(), Self> {
        let curve_position_as_surface = vertex
            .curve()
            .path()
            .point_from_path_coords(vertex.position());
        let surface_position = vertex.surface_form().position();

        let distance = curve_position_as_surface.distance_to(&surface_position);

        if distance > config.identical_max_distance {
            return Err(VertexValidationError::PositionMismatch {
                vertex: vertex.clone(),
                surface_vertex: vertex.surface_form().clone_object(),
                curve_position_as_surface,
                distance,
            });
        }

        Ok(())
    }
}

/// [`SurfaceVertex`] validation error
#[derive(Clone, Debug, thiserror::Error)]
pub enum SurfaceVertexValidationError {
    /// Mismatch between position and position of global form
    #[error(
        "`SurfaceVertex` position doesn't match position of its global form\n\
    - `SurfaceVertex`: {surface_vertex:#?}\n\
    - `GlobalVertex`: {global_vertex:#?}\n\
    - `SurfaceVertex` position as global: {surface_position_as_global:?}\n\
    - Distance between the positions: {distance}"
    )]
    PositionMismatch {
        /// The surface vertex
        surface_vertex: SurfaceVertex,

        /// The mismatched global vertex
        global_vertex: GlobalVertex,

        /// The surface position converted into a global position
        surface_position_as_global: Point<3>,

        /// The distance between the positions
        distance: Scalar,
    },
}

impl SurfaceVertexValidationError {
    fn check_position(
        surface_vertex: &SurfaceVertex,
        config: &ValidationConfig,
    ) -> Result<(), Self> {
        let surface_position_as_global = surface_vertex
            .surface()
            .geometry()
            .point_from_surface_coords(surface_vertex.position());
        let global_position = surface_vertex.global_form().position();

        let distance = surface_position_as_global.distance_to(&global_position);

        if distance > config.identical_max_distance {
            return Err(Self::PositionMismatch {
                surface_vertex: surface_vertex.clone(),
                global_vertex: surface_vertex.global_form().clone_object(),
                surface_position_as_global,
                distance,
            });
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        builder::{CurveBuilder, SurfaceVertexBuilder},
        insert::Insert,
        objects::{GlobalVertex, SurfaceVertex, Vertex},
        partial::{
            HasPartial, PartialCurve, PartialSurfaceVertex, PartialVertex,
        },
        services::Services,
        validate::Validate,
    };

    #[test]
    fn vertex_surface_mismatch() {
        let mut services = Services::new();

        let mut curve = PartialCurve {
            surface: Some(services.objects.surfaces.xy_plane()),
            ..Default::default()
        };
        curve.update_as_u_axis();

        let valid = PartialVertex {
            position: Some([0.].into()),
            curve: curve.into(),
            ..Default::default()
        }
        .build(&mut services.objects);
        let invalid = Vertex::new(valid.position(), valid.curve().clone(), {
            let mut tmp = valid.surface_form().to_partial();
            tmp.surface = Some(services.objects.surfaces.xz_plane());
            tmp.build(&mut services.objects)
                .insert(&mut services.objects)
        });

        assert!(valid.validate().is_ok());
        assert!(invalid.validate().is_err());
    }

    #[test]
    fn vertex_position_mismatch() {
        let mut services = Services::new();

        let valid = {
            let mut curve = PartialCurve {
                surface: Some(services.objects.surfaces.xy_plane()),
                ..Default::default()
            };
            curve.update_as_u_axis();

            PartialVertex {
                position: Some([0.].into()),
                curve: curve.into(),
                ..Default::default()
            }
            .build(&mut services.objects)
        };
        let invalid = Vertex::new(valid.position(), valid.curve().clone(), {
            let mut tmp = valid.surface_form().to_partial();
            tmp.position = Some([1., 0.].into());
            tmp.infer_global_form();
            tmp.build(&mut services.objects)
                .insert(&mut services.objects)
        });

        assert!(valid.validate().is_ok());
        assert!(invalid.validate().is_err());
    }

    #[test]
    fn surface_vertex_position_mismatch() {
        let mut services = Services::new();

        let valid = PartialSurfaceVertex {
            position: Some([0., 0.].into()),
            surface: Some(services.objects.surfaces.xy_plane()),
            ..Default::default()
        }
        .build(&mut services.objects);
        let invalid = SurfaceVertex::new(
            valid.position(),
            valid.surface().clone(),
            GlobalVertex::new([1., 0., 0.]).insert(&mut services.objects),
        );

        assert!(valid.validate().is_ok());
        assert!(invalid.validate().is_err());
    }
}