Struct truck_topology::Edge

source ·
pub struct Edge<P, C> { /* private fields */ }
Expand description

Edge, which consists two vertices.

The constructors Edge::new(), Edge::try_new(), and Edge::new_unchecked() create a different edge each time, even if the end vertices are the same one. An edge is uniquely identified by their id.

let v = Vertex::news(&[(), ()]);
let edge0 = Edge::new(&v[0], &v[1], ());
let edge1 = Edge::new(&v[0], &v[1], ());
assert_ne!(edge0.id(), edge1.id());

Implementations§

Generates the edge from front to back.

Failures

If front == back, then returns Error::SameVertex.

let v = Vertex::news(&[(), ()]);
assert!(Edge::try_new(&v[0], &v[1], ()).is_ok());
assert_eq!(Edge::try_new(&v[0], &v[0], ()), Err(Error::SameVertex));
Examples found in repository?
src/edge.rs (line 34)
33
34
35
    pub fn new(front: &Vertex<P>, back: &Vertex<P>, curve: C) -> Edge<P, C> {
        Edge::try_new(front, back, curve).remove_try()
    }
More examples
Hide additional examples
src/compress.rs (line 29)
26
27
28
29
30
    fn create_edge<P>(self, v: &[Vertex<P>]) -> Result<Edge<P, C>> {
        let front = &v[self.vertices.0];
        let back = &v[self.vertices.1];
        Edge::try_new(front, back, self.curve)
    }

Generates the edge from front to back.

Panic

The condition front == back is not allowed.

use truck_topology::*;
let v = Vertex::new(());
Edge::new(&v, &v, ()); // panic occurs
Examples found in repository?
src/edge.rs (line 57)
55
56
57
58
59
60
    pub fn debug_new(front: &Vertex<P>, back: &Vertex<P>, curve: C) -> Edge<P, C> {
        match cfg!(debug_assertions) {
            true => Edge::new(front, back, curve),
            false => Edge::new_unchecked(front, back, curve),
        }
    }

Generates the edge from front to back.

Remarks

This method is prepared only for performance-critical development and is not recommended.
This method does NOT check the condition front == back.
The programmer must guarantee this condition before using this method.

Examples found in repository?
src/edge.rs (line 21)
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
    pub fn try_new(front: &Vertex<P>, back: &Vertex<P>, curve: C) -> Result<Edge<P, C>> {
        if front == back {
            Err(Error::SameVertex)
        } else {
            Ok(Edge::new_unchecked(front, back, curve))
        }
    }
    /// Generates the edge from `front` to `back`.
    /// # Panic
    /// The condition `front == back` is not allowed.
    /// ```should_panic
    /// use truck_topology::*;
    /// let v = Vertex::new(());
    /// Edge::new(&v, &v, ()); // panic occurs
    /// ```
    #[inline(always)]
    pub fn new(front: &Vertex<P>, back: &Vertex<P>, curve: C) -> Edge<P, C> {
        Edge::try_new(front, back, curve).remove_try()
    }
    /// Generates the edge from `front` to `back`.
    /// # Remarks
    /// This method is prepared only for performance-critical development and is not recommended.  
    /// This method does NOT check the condition `front == back`.  
    /// The programmer must guarantee this condition before using this method.
    #[inline(always)]
    pub fn new_unchecked(front: &Vertex<P>, back: &Vertex<P>, curve: C) -> Edge<P, C> {
        Edge {
            vertices: (front.clone(), back.clone()),
            orientation: true,
            curve: Arc::new(Mutex::new(curve)),
        }
    }

    /// Generates the edge from `front` to `back`.
    /// # Remarks
    /// This method check the condition `front == back` in the debug mode.  
    /// The programmer must guarantee this condition before using this method.
    #[inline(always)]
    pub fn debug_new(front: &Vertex<P>, back: &Vertex<P>, curve: C) -> Edge<P, C> {
        match cfg!(debug_assertions) {
            true => Edge::new(front, back, curve),
            false => Edge::new_unchecked(front, back, curve),
        }
    }

Generates the edge from front to back.

Remarks

This method check the condition front == back in the debug mode.
The programmer must guarantee this condition before using this method.

Examples found in repository?
src/edge.rs (line 343)
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
    pub fn try_mapped<Q, D>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Option<Q>,
        mut curve_mapping: impl FnMut(&C) -> Option<D>,
    ) -> Option<Edge<Q, D>> {
        let v0 = self.absolute_front().try_mapped(&mut point_mapping)?;
        let v1 = self.absolute_back().try_mapped(&mut point_mapping)?;
        let curve = curve_mapping(&*self.curve.lock().unwrap())?;
        let mut edge = Edge::debug_new(&v0, &v1, curve);
        if !self.orientation() {
            edge.invert();
        }
        Some(edge)
    }

    /// Returns a new edge whose curve is mapped by `curve_mapping` and
    /// whose end points are mapped by `point_mapping`.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v0 = Vertex::new(0);
    /// let v1 = Vertex::new(1);
    /// let edge0 = Edge::new(&v0, &v1, 2);
    /// let edge1 = edge0.mapped(
    ///     &move |i: &usize| *i as f64 + 0.5,
    ///     &move |j: &usize| *j as f64 + 0.5,
    /// );
    ///
    /// assert_eq!(edge1.front().get_point(), 0.5);
    /// assert_eq!(edge1.back().get_point(), 1.5);
    /// assert_eq!(edge1.get_curve(), 2.5);
    /// ```
    /// # Remarks
    /// Accessing geometry elements directly in the closure will result in a deadlock.
    /// So, this method does not appear to the document.
    #[doc(hidden)]
    #[inline(always)]
    pub fn mapped<Q, D>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Q,
        mut curve_mapping: impl FnMut(&C) -> D,
    ) -> Edge<Q, D> {
        let v0 = self.absolute_front().mapped(&mut point_mapping);
        let v1 = self.absolute_back().mapped(&mut point_mapping);
        let curve = curve_mapping(&*self.curve.lock().unwrap());
        let mut edge = Edge::debug_new(&v0, &v1, curve);
        if edge.orientation() != self.orientation() {
            edge.invert();
        }
        edge
    }

    /// Returns the consistence of the geometry of end vertices
    /// and the geometry of edge.
    #[inline(always)]
    pub fn is_geometric_consistent(&self) -> bool
    where
        P: Tolerance,
        C: BoundedCurve<Point = P>, {
        let curve = self.curve.lock().unwrap();
        let geom_front = curve.front();
        let geom_back = curve.back();
        let top_front = self.absolute_front().point.lock().unwrap();
        let top_back = self.absolute_back().point.lock().unwrap();
        geom_front.near(&*top_front) && geom_back.near(&*top_back)
    }

    /// Cuts the edge at `vertex`.
    /// # Failure
    /// Returns `None` if:
    /// - cannot find the parameter `t` such that `edge.get_curve().subs(t) == vertex.get_point()`, or
    /// - the found parameter is not in the parameter range without end points.
    pub fn cut(&self, vertex: &Vertex<P>) -> Option<(Self, Self)>
    where
        P: Clone,
        C: Cut<Point = P> + SearchParameter<D1, Point = P>, {
        let mut curve0 = self.get_curve();
        let t = curve0.search_parameter(vertex.get_point(), None, SEARCH_PARAMETER_TRIALS)?;
        let (t0, t1) = curve0.parameter_range();
        if t < t0 + TOLERANCE || t1 - TOLERANCE < t {
            return None;
        }
        let curve1 = curve0.cut(t);
        let edge0 = Edge {
            vertices: (self.absolute_front().clone(), vertex.clone()),
            orientation: self.orientation,
            curve: Arc::new(Mutex::new(curve0)),
        };
        let edge1 = Edge {
            vertices: (vertex.clone(), self.absolute_back().clone()),
            orientation: self.orientation,
            curve: Arc::new(Mutex::new(curve1)),
        };
        if self.orientation {
            Some((edge0, edge1))
        } else {
            Some((edge1, edge0))
        }
    }

    /// Cuts the edge at `vertex` with parameter `t`.
    /// # Failure
    /// Returns `None` if `!edge.get_curve().subs(t).near(&vertex.get_point())`.
    pub fn cut_with_parameter(&self, vertex: &Vertex<P>, t: f64) -> Option<(Self, Self)>
    where
        P: Clone + Tolerance,
        C: Cut<Point = P>, {
        let mut curve0 = self.get_curve();
        if !curve0.subs(t).near(&vertex.get_point()) {
            return None;
        }
        let (t0, t1) = curve0.parameter_range();
        if t < t0 + TOLERANCE || t1 - TOLERANCE < t {
            return None;
        }
        let curve1 = curve0.cut(t);
        let edge0 = Edge {
            vertices: (self.absolute_front().clone(), vertex.clone()),
            orientation: self.orientation,
            curve: Arc::new(Mutex::new(curve0)),
        };
        let edge1 = Edge {
            vertices: (vertex.clone(), self.absolute_back().clone()),
            orientation: self.orientation,
            curve: Arc::new(Mutex::new(curve1)),
        };
        if self.orientation {
            Some((edge0, edge1))
        } else {
            Some((edge1, edge0))
        }
    }

    /// Concats two edges.
    pub fn concat(&self, rhs: &Self) -> std::result::Result<Self, ConcatError<P>>
    where
        P: Debug,
        C: Concat<C, Point = P, Output = C> + Invertible + ParameterTransform, {
        if self.back() != rhs.front() {
            return Err(ConcatError::DisconnectedVertex(
                self.back().clone(),
                rhs.front().clone(),
            ));
        }
        if self.front() == rhs.back() {
            return Err(ConcatError::SameVertex(self.front().clone()));
        }
        let curve0 = self.oriented_curve();
        let mut curve1 = rhs.oriented_curve();
        let t0 = curve0.parameter_range().1;
        let t1 = curve1.parameter_range().0;
        curve1.parameter_transform(1.0, t0 - t1);
        let curve = curve0.try_concat(&curve1)?;
        Ok(Edge::debug_new(self.front(), rhs.back(), curve))
    }
More examples
Hide additional examples
src/wire.rs (line 557)
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
pub(super) fn edge_entry_map_try_closure<'a, P, C, Q, D, KF, VF>(
    vertex_map: &'a mut EntryMap<VertexID<P>, Option<Vertex<Q>>, KF, VF, &'a Vertex<P>>,
    curve_mapping: &'a mut impl FnMut(&C) -> Option<D>,
) -> impl FnMut(&'a Edge<P, C>) -> Option<Edge<Q, D>> + 'a
where
    KF: FnMut(&'a Vertex<P>) -> VertexID<P>,
    VF: FnMut(&'a Vertex<P>) -> Option<Vertex<Q>>,
{
    move |edge| {
        let vf = edge.absolute_front();
        let vertex0 = vertex_map.entry_or_insert(vf).clone()?;
        let vb = edge.absolute_back();
        let vertex1 = vertex_map.entry_or_insert(vb).clone()?;
        let curve = curve_mapping(&*edge.curve.lock().unwrap())?;
        Some(Edge::debug_new(&vertex0, &vertex1, curve))
    }
}

pub(super) fn edge_entry_map_closure<'a, P, C, Q, D, KF, VF>(
    vertex_map: &'a mut EntryMap<VertexID<P>, Vertex<Q>, KF, VF, &'a Vertex<P>>,
    curve_mapping: &'a mut impl FnMut(&C) -> D,
) -> impl FnMut(&'a Edge<P, C>) -> Edge<Q, D> + 'a
where
    KF: FnMut(&'a Vertex<P>) -> VertexID<P>,
    VF: FnMut(&'a Vertex<P>) -> Vertex<Q>,
{
    move |edge| {
        let vf = edge.absolute_front();
        let vertex0 = vertex_map.entry_or_insert(vf).clone();
        let vb = edge.absolute_back();
        let vertex1 = vertex_map.entry_or_insert(vb).clone();
        let curve = curve_mapping(&*edge.curve.lock().unwrap());
        Edge::debug_new(&vertex0, &vertex1, curve)
    }
}

Returns the orientation of the curve.

Examples
use truck_topology::*;
let v = Vertex::news(&[(), ()]);
let edge0 = Edge::new(&v[0], &v[1], ());
let edge1 = edge0.inverse();
assert!(edge0.orientation());
assert!(!edge1.orientation());
Examples found in repository?
src/edge.rs (line 344)
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
    pub fn try_mapped<Q, D>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Option<Q>,
        mut curve_mapping: impl FnMut(&C) -> Option<D>,
    ) -> Option<Edge<Q, D>> {
        let v0 = self.absolute_front().try_mapped(&mut point_mapping)?;
        let v1 = self.absolute_back().try_mapped(&mut point_mapping)?;
        let curve = curve_mapping(&*self.curve.lock().unwrap())?;
        let mut edge = Edge::debug_new(&v0, &v1, curve);
        if !self.orientation() {
            edge.invert();
        }
        Some(edge)
    }

    /// Returns a new edge whose curve is mapped by `curve_mapping` and
    /// whose end points are mapped by `point_mapping`.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v0 = Vertex::new(0);
    /// let v1 = Vertex::new(1);
    /// let edge0 = Edge::new(&v0, &v1, 2);
    /// let edge1 = edge0.mapped(
    ///     &move |i: &usize| *i as f64 + 0.5,
    ///     &move |j: &usize| *j as f64 + 0.5,
    /// );
    ///
    /// assert_eq!(edge1.front().get_point(), 0.5);
    /// assert_eq!(edge1.back().get_point(), 1.5);
    /// assert_eq!(edge1.get_curve(), 2.5);
    /// ```
    /// # Remarks
    /// Accessing geometry elements directly in the closure will result in a deadlock.
    /// So, this method does not appear to the document.
    #[doc(hidden)]
    #[inline(always)]
    pub fn mapped<Q, D>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Q,
        mut curve_mapping: impl FnMut(&C) -> D,
    ) -> Edge<Q, D> {
        let v0 = self.absolute_front().mapped(&mut point_mapping);
        let v1 = self.absolute_back().mapped(&mut point_mapping);
        let curve = curve_mapping(&*self.curve.lock().unwrap());
        let mut edge = Edge::debug_new(&v0, &v1, curve);
        if edge.orientation() != self.orientation() {
            edge.invert();
        }
        edge
    }
More examples
Hide additional examples
src/wire.rs (line 429)
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
    pub(super) fn sub_mapped<'a, Q, D, KF, KV>(
        &'a self,
        edge_map: &mut EdgeEntryMapForMapping<'a, P, C, Q, D, KF, KV>,
    ) -> Wire<Q, D>
    where
        KF: FnMut(&'a Edge<P, C>) -> EdgeID<C>,
        KV: FnMut(&'a Edge<P, C>) -> Edge<Q, D>,
    {
        self.edge_iter()
            .map(|edge| {
                let new_edge = edge_map.entry_or_insert(edge);
                match edge.orientation() {
                    true => new_edge.clone(),
                    false => new_edge.inverse(),
                }
            })
            .collect()
    }
src/compress.rs (line 124)
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
    fn get_eid(&mut self, edge: &Edge<P, C>) -> CompressedEdgeIndex {
        match self.emap.get(&edge.id()) {
            Some(got) => (got.0, edge.orientation()).into(),
            None => {
                let id = self.emap.len();
                let front_id = self.get_vid(edge.absolute_front());
                let back_id = self.get_vid(edge.absolute_back());
                let curve = edge.get_curve();
                let cedge = CompressedEdge {
                    vertices: (front_id, back_id),
                    curve,
                };
                self.emap.insert(edge.id(), (id, cedge));
                (id, edge.orientation()).into()
            }
        }
    }
src/shell.rs (line 635)
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
    pub fn cut_edge(
        &mut self,
        edge_id: EdgeID<C>,
        vertex: &Vertex<P>,
    ) -> Option<(Edge<P, C>, Edge<P, C>)>
    where
        P: Clone,
        C: Cut<Point = P> + SearchParameter<D1, Point = P>,
    {
        if self.vertex_iter().any(|v| &v == vertex) {
            return None;
        }
        let mut edges = None;
        self.iter_mut()
            .flat_map(|face| face.boundaries.iter_mut())
            .try_for_each(|wire| {
                let find_res = wire
                    .iter()
                    .enumerate()
                    .find(|(_, edge)| edge.id() == edge_id);
                let (idx, edge) = match find_res {
                    Some(got) => got,
                    None => return Some(()),
                };
                if edges.is_none() {
                    edges = Some(edge.absolute_clone().cut(vertex)?);
                }
                let edges = edges.as_ref().unwrap();
                let new_wire = match edge.orientation() {
                    true => Wire::from(vec![edges.0.clone(), edges.1.clone()]),
                    false => Wire::from(vec![edges.1.inverse(), edges.0.inverse()]),
                };
                let flag = wire.swap_edge_into_wire(idx, new_wire);
                debug_assert!(flag);
                Some(())
            });
        edges
    }
    /// Removes `vertex` from `self` by concat two edges on both sides.
    ///
    /// # Returns
    /// Returns the new created edge.
    ///
    /// # Failures
    /// Returns `None` if:
    /// - there are no vertex corresponding to `vertex_id` in the shell,
    /// - the vertex is included more than 2 face boundaries,
    /// - the vertex is included more than 2 edges, or
    /// - concating edges is failed.
    pub fn remove_vertex_by_concat_edges(&mut self, vertex_id: VertexID<P>) -> Option<Edge<P, C>>
    where
        P: Debug,
        C: Concat<C, Point = P, Output = C> + Invertible + ParameterTransform, {
        let mut vec: Vec<(&mut Wire<P, C>, usize)> = self
            .face_iter_mut()
            .flat_map(|face| &mut face.boundaries)
            .filter_map(|wire| {
                let idx = wire
                    .edge_iter()
                    .enumerate()
                    .find(|(_, e)| e.back().id() == vertex_id)?
                    .0;
                Some((wire, idx))
            })
            .collect();
        if vec.len() > 2 || vec.is_empty() {
            None
        } else if vec.len() == 1 {
            let (wire, idx) = vec.pop().unwrap();
            let edge = wire[idx].concat(&wire[(idx + 1) % wire.len()]).ok()?;
            wire.swap_subwire_into_edges(idx, edge.clone());
            Some(edge)
        } else {
            let (wire0, idx0) = vec.pop().unwrap();
            let (wire1, idx1) = vec.pop().unwrap();
            if !wire0[idx0].is_same(&wire1[(idx1 + 1) % wire1.len()])
                || !wire0[(idx0 + 1) % wire0.len()].is_same(&wire1[idx1])
            {
                return None;
            }
            let edge = wire0[idx0].concat(&wire0[(idx0 + 1) % wire0.len()]).ok()?;
            wire1.swap_subwire_into_edges(idx1, edge.inverse());
            wire0.swap_subwire_into_edges(idx0, edge.clone());
            Some(edge)
        }
    }

    /// Creates display struct for debugging the shell.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use truck_topology::shell::ShellCondition;
    /// use ShellDisplayFormat as SDF;
    ///
    /// let v = Vertex::news(&[0, 1, 2, 3]);
    /// let edge = [
    ///     Edge::new(&v[0], &v[1], ()), // 0
    ///     Edge::new(&v[1], &v[2], ()), // 1
    ///     Edge::new(&v[2], &v[0], ()), // 2
    ///     Edge::new(&v[1], &v[3], ()), // 3
    ///     Edge::new(&v[3], &v[2], ()), // 4
    ///     Edge::new(&v[0], &v[3], ()), // 5
    /// ];
    /// let wire = vec![
    ///     Wire::from_iter(vec![&edge[0], &edge[3], &edge[4], &edge[2]]),
    ///     Wire::from_iter(vec![&edge[1], &edge[2], &edge[5], &edge[3].inverse()]),
    /// ];
    /// let shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
    ///
    /// let vertex_format = VertexDisplayFormat::AsPoint;
    /// let edge_format = EdgeDisplayFormat::VerticesTuple { vertex_format };
    /// let wire_format = WireDisplayFormat::EdgesList { edge_format };
    /// let face_format = FaceDisplayFormat::LoopsListTuple { wire_format };
    ///
    /// assert_eq!(
    ///     &format!("{:?}", shell.display(SDF::FacesListTuple {face_format})),
    ///     "Shell([Face([[(0, 1), (1, 3), (3, 2), (2, 0)]]), Face([[(1, 2), (2, 0), (0, 3), (3, 1)]])])",
    /// );
    /// assert_eq!(
    ///     &format!("{:?}", shell.display(SDF::FacesList {face_format})),
    ///     "[Face([[(0, 1), (1, 3), (3, 2), (2, 0)]]), Face([[(1, 2), (2, 0), (0, 3), (3, 1)]])]",
    /// );
    /// ```
    pub fn display(
        &self,
        format: ShellDisplayFormat,
    ) -> DebugDisplay<'_, Self, ShellDisplayFormat> {
        DebugDisplay {
            entity: self,
            format,
        }
    }
}

impl<P, C, S> Clone for Shell<P, C, S> {
    #[inline(always)]
    fn clone(&self) -> Shell<P, C, S> {
        Shell {
            face_list: self.face_list.clone(),
        }
    }
}

impl<P, C, S> From<Shell<P, C, S>> for Vec<Face<P, C, S>> {
    #[inline(always)]
    fn from(shell: Shell<P, C, S>) -> Vec<Face<P, C, S>> { shell.face_list }
}

impl<P, C, S> From<Vec<Face<P, C, S>>> for Shell<P, C, S> {
    #[inline(always)]
    fn from(faces: Vec<Face<P, C, S>>) -> Shell<P, C, S> { Shell { face_list: faces } }
}

impl<P, C, S> FromIterator<Face<P, C, S>> for Shell<P, C, S> {
    #[inline(always)]
    fn from_iter<I: IntoIterator<Item = Face<P, C, S>>>(iter: I) -> Shell<P, C, S> {
        Shell {
            face_list: iter.into_iter().collect(),
        }
    }
}

impl<P, C, S> IntoIterator for Shell<P, C, S> {
    type Item = Face<P, C, S>;
    type IntoIter = std::vec::IntoIter<Face<P, C, S>>;
    #[inline(always)]
    fn into_iter(self) -> Self::IntoIter { self.face_list.into_iter() }
}

impl<'a, P, C, S> IntoIterator for &'a Shell<P, C, S> {
    type Item = &'a Face<P, C, S>;
    type IntoIter = std::slice::Iter<'a, Face<P, C, S>>;
    #[inline(always)]
    fn into_iter(self) -> Self::IntoIter { self.face_list.iter() }
}

impl<P, C, S> std::ops::Deref for Shell<P, C, S> {
    type Target = Vec<Face<P, C, S>>;
    #[inline(always)]
    fn deref(&self) -> &Vec<Face<P, C, S>> { &self.face_list }
}

impl<P, C, S> std::ops::DerefMut for Shell<P, C, S> {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut Vec<Face<P, C, S>> { &mut self.face_list }
}

impl<P, C, S> Default for Shell<P, C, S> {
    #[inline(always)]
    fn default() -> Self {
        Self {
            face_list: Vec::new(),
        }
    }
}

impl<P, C, S> PartialEq for Shell<P, C, S> {
    fn eq(&self, other: &Self) -> bool { self.face_list == other.face_list }
}

impl<P, C, S> Eq for Shell<P, C, S> {}

/// The reference iterator over all faces in shells
pub type FaceIter<'a, P, C, S> = std::slice::Iter<'a, Face<P, C, S>>;
/// The mutable reference iterator over all faces in shells
pub type FaceIterMut<'a, P, C, S> = std::slice::IterMut<'a, Face<P, C, S>>;
/// The into iterator over all faces in shells
pub type FaceIntoIter<P, C, S> = std::vec::IntoIter<Face<P, C, S>>;
/// The reference parallel iterator over all faces in shells
pub type FaceParallelIter<'a, P, C, S> = <Vec<Face<P, C, S>> as IntoParallelRefIterator<'a>>::Iter;
/// The mutable reference parallel iterator over all faces in shells
pub type FaceParallelIterMut<'a, P, C, S> =
    <Vec<Face<P, C, S>> as IntoParallelRefMutIterator<'a>>::Iter;
/// The into parallel iterator over all faces in shells
pub type FaceParallelIntoIter<P, C, S> = <Vec<Face<P, C, S>> as IntoParallelIterator>::Iter;

/// The shell conditions being determined by the half-edge model.
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum ShellCondition {
    /// This shell is not regular.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use truck_topology::shell::ShellCondition;
    /// let v = Vertex::news(&[(); 5]);
    /// let edge = [
    ///    Edge::new(&v[0], &v[1], ()),
    ///    Edge::new(&v[0], &v[2], ()),
    ///    Edge::new(&v[0], &v[3], ()),
    ///    Edge::new(&v[0], &v[4], ()),
    ///    Edge::new(&v[1], &v[2], ()),
    ///    Edge::new(&v[1], &v[3], ()),
    ///    Edge::new(&v[1], &v[4], ()),
    /// ];
    /// let wire = vec![
    ///    Wire::from_iter(vec![&edge[0], &edge[4], &edge[1].inverse()]),
    ///    Wire::from_iter(vec![&edge[0], &edge[5], &edge[2].inverse()]),
    ///    Wire::from_iter(vec![&edge[0], &edge[6], &edge[3].inverse()]),
    /// ];
    /// let shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
    /// // The shell is irregular because three faces share edge[0].
    /// assert_eq!(shell.shell_condition(), ShellCondition::Irregular);
    /// ```
    Irregular,
    /// All edges are shared by at most two faces.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use truck_topology::shell::ShellCondition;
    /// let v = Vertex::news(&[(); 6]);
    /// let edge = [
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[0], &v[2], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[1], &v[3], ()),
    ///     Edge::new(&v[1], &v[4], ()),
    ///     Edge::new(&v[2], &v[4], ()),
    ///     Edge::new(&v[2], &v[5], ()),
    ///     Edge::new(&v[3], &v[4], ()),
    ///     Edge::new(&v[4], &v[5], ()),
    /// ];
    /// let wire = vec![
    ///     Wire::from_iter(vec![&edge[0], &edge[2], &edge[1].inverse()]),
    ///     Wire::from_iter(vec![&edge[3], &edge[7], &edge[4].inverse()]),
    ///     Wire::from_iter(vec![&edge[5], &edge[8], &edge[6].inverse()]),
    ///     Wire::from_iter(vec![&edge[2], &edge[5], &edge[4].inverse()]),
    /// ];
    /// let shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
    /// // This shell is regular, but not oriented.
    /// // It is because the orientations of shell[0] and shell[3] are incompatible on edge[2].
    /// assert_eq!(shell.shell_condition(), ShellCondition::Regular);
    /// ```
    Regular,
    /// The orientations of faces are compatible.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use truck_topology::shell::ShellCondition;
    /// let v = Vertex::news(&[(); 6]);
    /// let edge = [
    ///     Edge::new(&v[0], &v[1] ,()),
    ///     Edge::new(&v[0], &v[2] ,()),
    ///     Edge::new(&v[1], &v[2] ,()),
    ///     Edge::new(&v[1], &v[3] ,()),
    ///     Edge::new(&v[1], &v[4] ,()),
    ///     Edge::new(&v[2], &v[4] ,()),
    ///     Edge::new(&v[2], &v[5] ,()),
    ///     Edge::new(&v[3], &v[4] ,()),
    ///     Edge::new(&v[4], &v[5] ,()),
    /// ];
    /// let wire = vec![
    ///     Wire::from_iter(vec![&edge[0], &edge[2], &edge[1].inverse()]),
    ///     Wire::from_iter(vec![&edge[3], &edge[7], &edge[4].inverse()]),
    ///     Wire::from_iter(vec![&edge[5], &edge[8], &edge[6].inverse()]),
    ///     Wire::from_iter(vec![&edge[2].inverse(), &edge[4], &edge[5].inverse()]),
    /// ];
    /// let shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
    /// // The orientations of all faces in the shell are compatible on the shared edges.
    /// // This shell is not closed because edge[0] is included in only the 0th face.
    /// assert_eq!(shell.shell_condition(), ShellCondition::Oriented);
    /// ```
    Oriented,
    /// All edges are shared by two faces.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use truck_topology::shell::ShellCondition;
    /// let v = Vertex::news(&[(); 8]);
    /// let edge = [
    ///     Edge::new(&v[0], &v[1] ,()),
    ///     Edge::new(&v[1], &v[2] ,()),
    ///     Edge::new(&v[2], &v[3] ,()),
    ///     Edge::new(&v[3], &v[0] ,()),
    ///     Edge::new(&v[0], &v[4] ,()),
    ///     Edge::new(&v[1], &v[5] ,()),
    ///     Edge::new(&v[2], &v[6] ,()),
    ///     Edge::new(&v[3], &v[7] ,()),
    ///     Edge::new(&v[4], &v[5] ,()),
    ///     Edge::new(&v[5], &v[6] ,()),
    ///     Edge::new(&v[6], &v[7] ,()),
    ///     Edge::new(&v[7], &v[4] ,()),
    /// ];
    /// let wire = vec![
    ///     Wire::from_iter(vec![&edge[0], &edge[1], &edge[2], &edge[3]]),
    ///     Wire::from_iter(vec![&edge[0].inverse(), &edge[4], &edge[8], &edge[5].inverse()]),
    ///     Wire::from_iter(vec![&edge[1].inverse(), &edge[5], &edge[9], &edge[6].inverse()]),
    ///     Wire::from_iter(vec![&edge[2].inverse(), &edge[6], &edge[10], &edge[7].inverse()]),
    ///     Wire::from_iter(vec![&edge[3].inverse(), &edge[7], &edge[11], &edge[4].inverse()]),
    ///     Wire::from_iter(vec![&edge[8], &edge[9], &edge[10], &edge[11]]),
    /// ];
    /// let mut shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
    /// shell[5].invert();
    /// assert_eq!(shell.shell_condition(), ShellCondition::Closed);
    /// ```
    Closed,
}

impl std::ops::BitAnd for ShellCondition {
    type Output = Self;
    fn bitand(self, other: Self) -> Self {
        match (self, other) {
            (Self::Irregular, _) => Self::Irregular,
            (_, Self::Irregular) => Self::Irregular,
            (Self::Regular, _) => Self::Regular,
            (_, Self::Regular) => Self::Regular,
            (Self::Oriented, _) => Self::Oriented,
            (_, Self::Oriented) => Self::Oriented,
            (Self::Closed, Self::Closed) => Self::Closed,
        }
    }
}

#[derive(Debug, Clone)]
struct Boundaries<C> {
    checked: HashSet<EdgeID<C>>,
    boundaries: HashMap<EdgeID<C>, bool>,
    condition: ShellCondition,
}

impl<C> Boundaries<C> {
    #[inline(always)]
    fn new() -> Self {
        Self {
            checked: Default::default(),
            boundaries: Default::default(),
            condition: ShellCondition::Oriented,
        }
    }

    #[inline(always)]
    fn insert<P>(&mut self, edge: &Edge<P, C>) {
        self.condition = self.condition
            & match (
                self.checked.insert(edge.id()),
                self.boundaries.insert(edge.id(), edge.orientation()),
            ) {
                (true, None) => ShellCondition::Oriented,
                (false, None) => ShellCondition::Irregular,
                (true, Some(_)) => panic!("unexpected case!"),
                (false, Some(ori)) => {
                    self.boundaries.remove(&edge.id());
                    match edge.orientation() == ori {
                        true => ShellCondition::Regular,
                        false => ShellCondition::Oriented,
                    }
                }
            }
    }

Inverts the direction of edge.

use truck_topology::*;
let v = Vertex::news(&[(), ()]);
let edge = Edge::new(&v[0], &v[1], ());
let mut inv_edge = edge.clone();
inv_edge.invert();

// Two edges are the same edge.
edge.is_same(&inv_edge);

// the front and back are exchanged.
assert_eq!(edge.front(), inv_edge.back());
assert_eq!(edge.back(), inv_edge.front());
Examples found in repository?
src/edge.rs (line 345)
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
    pub fn try_mapped<Q, D>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Option<Q>,
        mut curve_mapping: impl FnMut(&C) -> Option<D>,
    ) -> Option<Edge<Q, D>> {
        let v0 = self.absolute_front().try_mapped(&mut point_mapping)?;
        let v1 = self.absolute_back().try_mapped(&mut point_mapping)?;
        let curve = curve_mapping(&*self.curve.lock().unwrap())?;
        let mut edge = Edge::debug_new(&v0, &v1, curve);
        if !self.orientation() {
            edge.invert();
        }
        Some(edge)
    }

    /// Returns a new edge whose curve is mapped by `curve_mapping` and
    /// whose end points are mapped by `point_mapping`.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v0 = Vertex::new(0);
    /// let v1 = Vertex::new(1);
    /// let edge0 = Edge::new(&v0, &v1, 2);
    /// let edge1 = edge0.mapped(
    ///     &move |i: &usize| *i as f64 + 0.5,
    ///     &move |j: &usize| *j as f64 + 0.5,
    /// );
    ///
    /// assert_eq!(edge1.front().get_point(), 0.5);
    /// assert_eq!(edge1.back().get_point(), 1.5);
    /// assert_eq!(edge1.get_curve(), 2.5);
    /// ```
    /// # Remarks
    /// Accessing geometry elements directly in the closure will result in a deadlock.
    /// So, this method does not appear to the document.
    #[doc(hidden)]
    #[inline(always)]
    pub fn mapped<Q, D>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Q,
        mut curve_mapping: impl FnMut(&C) -> D,
    ) -> Edge<Q, D> {
        let v0 = self.absolute_front().mapped(&mut point_mapping);
        let v1 = self.absolute_back().mapped(&mut point_mapping);
        let curve = curve_mapping(&*self.curve.lock().unwrap());
        let mut edge = Edge::debug_new(&v0, &v1, curve);
        if edge.orientation() != self.orientation() {
            edge.invert();
        }
        edge
    }

Creates the inverse oriented edge.

let v = Vertex::news(&[(), ()]);
let edge = Edge::new(&v[0], &v[1], ());
let inv_edge = edge.inverse();

// Two edges are the same edge.
assert!(edge.is_same(&inv_edge));

// Two edges has the same id.
assert_eq!(edge.id(), inv_edge.id());

// the front and back are exchanged.
assert_eq!(edge.front(), inv_edge.back());
assert_eq!(edge.back(), inv_edge.front());
Examples found in repository?
src/wire.rs (line 190)
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
    pub fn inverse(&self) -> Wire<P, C> {
        let edge_list = self.edge_iter().rev().map(|edge| edge.inverse()).collect();
        Wire { edge_list }
    }

    /// Returns whether all the adjacent pairs of edges have shared vertices or not.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 4]);
    /// let mut wire = Wire::from(vec![
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[2], &v[3], ()),
    /// ]);
    /// assert!(!wire.is_continuous());
    /// wire.insert(1, Edge::new(&v[1], &v[2], ()));
    /// assert!(wire.is_continuous());
    /// ```
    /// ```
    /// use truck_topology::*;
    /// // The empty wire is continuous
    /// assert!(Wire::<(), ()>::new().is_continuous());
    /// ```
    pub fn is_continuous(&self) -> bool {
        let mut iter = self.edge_iter();
        if let Some(edge) = iter.next() {
            let mut prev = edge.back();
            for edge in iter {
                if prev != edge.front() {
                    return false;
                }
                prev = edge.back();
            }
        }
        true
    }

    /// Returns whether the front vertex of the wire is the same as the back one or not.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 4]);
    /// let mut wire = Wire::from(vec![
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[2], &v[3], ()),
    /// ]);
    /// assert!(!wire.is_cyclic());
    /// wire.push_back(Edge::new(&v[3], &v[0], ()));
    /// assert!(wire.is_cyclic());
    /// ```
    /// ```
    /// use truck_topology::*;
    /// // The empty wire is cyclic.
    /// assert!(Wire::<(), ()>::new().is_cyclic());
    /// ```
    #[inline(always)]
    pub fn is_cyclic(&self) -> bool { self.front_vertex() == self.back_vertex() }

    /// Returns whether the wire is closed or not.
    /// Here, "closed" means "continuous" and "cyclic".
    #[inline(always)]
    pub fn is_closed(&self) -> bool { self.is_continuous() && self.is_cyclic() }

    /// Returns whether simple or not.
    /// Here, "simple" means all the vertices in the wire are shared from only two edges at most.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 4]);
    /// let edge0 = Edge::new(&v[0], &v[1], ());
    /// let edge1 = Edge::new(&v[1], &v[2], ());
    /// let edge2 = Edge::new(&v[2], &v[3], ());
    /// let edge3 = Edge::new(&v[3], &v[1], ());
    /// let edge4 = Edge::new(&v[3], &v[0], ());
    ///
    /// let wire0 = Wire::from_iter(vec![&edge0, &edge1, &edge2, &edge3]);
    /// let wire1 = Wire::from(vec![edge0, edge1, edge2, edge4]);
    ///
    /// assert!(!wire0.is_simple());
    /// assert!(wire1.is_simple());
    /// ```
    /// ```
    /// use truck_topology::*;
    /// // The empty wire is simple.
    /// assert!(Wire::<(), ()>::new().is_simple());
    /// ```
    pub fn is_simple(&self) -> bool {
        let mut set = HashSet::default();
        self.vertex_iter()
            .all(move |vertex| set.insert(vertex.id()))
    }

    /// Determines whether all the wires in `wires` has no same vertices.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    ///
    /// let v = Vertex::news(&[(), (), (), (), ()]);
    /// let edge0 = Edge::new(&v[0], &v[1], ());
    /// let edge1 = Edge::new(&v[1], &v[2], ());
    /// let edge2 = Edge::new(&v[2], &v[3], ());
    /// let edge3 = Edge::new(&v[3], &v[4], ());
    ///
    /// let wire0 = Wire::from(vec![edge0, edge1]);
    /// let wire1 = Wire::from(vec![edge2]);
    /// let wire2 = Wire::from(vec![edge3]);
    ///
    /// assert!(Wire::disjoint_wires(&[wire0.clone(), wire2]));
    /// assert!(!Wire::disjoint_wires(&[wire0, wire1]));
    /// ```
    pub fn disjoint_wires(wires: &[Wire<P, C>]) -> bool {
        let mut set = HashSet::default();
        wires.iter().all(move |wire| {
            let mut vec = Vec::new();
            let res = wire.vertex_iter().all(|v| {
                vec.push(v.id());
                !set.contains(&v.id())
            });
            set.extend(vec);
            res
        })
    }

    /// Swap one edge into two edges.
    ///
    /// # Arguments
    /// - `idx`: Index of edge in wire
    /// - `edges`: Inserted edges
    ///
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(), (), (), (), ()]);
    /// let edge0 = Edge::new(&v[0], &v[1], 0);
    /// let edge1 = Edge::new(&v[1], &v[3], 1);
    /// let edge2 = Edge::new(&v[3], &v[4], 2);
    /// let edge3 = Edge::new(&v[1], &v[2], 3);
    /// let edge4 = Edge::new(&v[2], &v[3], 4);
    /// let mut wire0 = Wire::from(vec![
    ///     edge0.clone(), edge1, edge2.clone()
    /// ]);
    /// let wire1 = Wire::from(vec![
    ///     edge0, edge3.clone(), edge4.clone(), edge2
    /// ]);
    /// assert_ne!(wire0, wire1);
    /// wire0.swap_edge_into_wire(1, Wire::from(vec![edge3, edge4]));
    /// assert_eq!(wire0, wire1);
    /// ```
    ///
    /// # Panics
    /// Panic occars if `idx >= self.len()`.
    ///
    /// # Failure
    /// Returns `false` and `self` will not be changed if the end vertices of `self[idx]` and the ones of `wire` is not the same.
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(), (), (), (), ()]);
    /// let edge0 = Edge::new(&v[0], &v[1], 0);
    /// let edge1 = Edge::new(&v[1], &v[3], 1);
    /// let edge2 = Edge::new(&v[3], &v[4], 2);
    /// let edge3 = Edge::new(&v[1], &v[2], 3);
    /// let edge4 = Edge::new(&v[2], &v[1], 4);
    /// let mut wire0 = Wire::from(vec![
    ///     edge0.clone(), edge1, edge2.clone()
    /// ]);
    /// let backup = wire0.clone();
    /// // The end vertices of wire[1] == edge1 is (v[1], v[3]).
    /// // The end points of new wire [edge3, edge4] is (v[1], v[1]).
    /// // Since the back vertices are different, returns false and do nothing.
    /// assert!(!wire0.swap_edge_into_wire(1, Wire::from(vec![edge3, edge4])));
    /// assert_eq!(wire0, backup);
    /// ```
    pub fn swap_edge_into_wire(&mut self, idx: usize, wire: Wire<P, C>) -> bool {
        if wire.is_empty() || self[idx].ends() != wire.ends_vertices().unwrap() {
            return false;
        }
        let mut new_wire: Vec<_> = self.drain(0..idx).collect();
        new_wire.extend(wire);
        self.pop_front();
        new_wire.extend(self.drain(..));
        *self = new_wire.into();
        true
    }
    /// Concat edges
    pub(super) fn swap_subwire_into_edges(&mut self, mut idx: usize, edge: Edge<P, C>) {
        if idx + 1 == self.len() {
            self.rotate_left(1);
            idx -= 1;
        }
        let mut new_wire: Vec<_> = self.drain(0..idx).collect();
        new_wire.push(edge);
        self.pop_front();
        self.pop_front();
        new_wire.extend(self.drain(..));
        *self = new_wire.into();
    }

    pub(super) fn sub_try_mapped<'a, Q, D, KF, KV>(
        &'a self,
        edge_map: &mut EdgeEntryMapForTryMapping<'a, P, C, Q, D, KF, KV>,
    ) -> Option<Wire<Q, D>>
    where
        KF: FnMut(&'a Edge<P, C>) -> EdgeID<C>,
        KV: FnMut(&'a Edge<P, C>) -> Option<Edge<Q, D>>,
    {
        self.edge_iter()
            .map(|edge| Some(edge_map.entry_or_insert(edge).as_ref()?.absolute_clone()))
            .collect()
    }

    /// Returns a new wire whose curves are mapped by `curve_mapping` and
    /// whose points are mapped by `point_mapping`.
    /// # Remarks
    /// Accessing geometry elements directly in the closure will result in a deadlock.
    /// So, this method does not appear to the document.
    #[doc(hidden)]
    pub fn try_mapped<Q, D>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Option<Q>,
        mut curve_mapping: impl FnMut(&C) -> Option<D>,
    ) -> Option<Wire<Q, D>> {
        let mut vertex_map = EntryMap::new(Vertex::id, move |v| v.try_mapped(&mut point_mapping));
        let mut edge_map = EntryMap::new(
            Edge::id,
            edge_entry_map_try_closure(&mut vertex_map, &mut curve_mapping),
        );
        self.sub_try_mapped(&mut edge_map)
    }

    pub(super) fn sub_mapped<'a, Q, D, KF, KV>(
        &'a self,
        edge_map: &mut EdgeEntryMapForMapping<'a, P, C, Q, D, KF, KV>,
    ) -> Wire<Q, D>
    where
        KF: FnMut(&'a Edge<P, C>) -> EdgeID<C>,
        KV: FnMut(&'a Edge<P, C>) -> Edge<Q, D>,
    {
        self.edge_iter()
            .map(|edge| {
                let new_edge = edge_map.entry_or_insert(edge);
                match edge.orientation() {
                    true => new_edge.clone(),
                    false => new_edge.inverse(),
                }
            })
            .collect()
    }
More examples
Hide additional examples
src/compress.rs (line 67)
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
    fn create_face<P, C>(self, edges: &[Edge<P, C>]) -> Result<Face<P, C, S>> {
        let wires: Vec<Wire<P, C>> = self
            .boundaries
            .into_iter()
            .map(|wire| {
                wire.into_iter()
                    .map(
                        |CompressedEdgeIndex { index, orientation }| match orientation {
                            true => edges[index].clone(),
                            false => edges[index].inverse(),
                        },
                    )
                    .collect()
            })
            .collect();
        let mut face = Face::try_new(wires, self.surface)?;
        if !self.orientation {
            face.invert();
        }
        Ok(face)
    }
src/face.rs (line 786)
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
    pub fn cut_by_edge(&self, edge: Edge<P, C>) -> Option<(Self, Self)>
    where S: Clone {
        if self.boundaries.len() != 1 {
            return None;
        }
        let mut face0 = Face {
            boundaries: self.boundaries.clone(),
            orientation: self.orientation,
            surface: Arc::new(Mutex::new(self.get_surface())),
        };
        let wire = &mut face0.boundaries[0];
        let i = wire
            .edge_iter()
            .enumerate()
            .find(|(_, e)| e.front() == edge.back())
            .map(|(i, _)| i)?;
        let j = wire
            .edge_iter()
            .enumerate()
            .find(|(_, e)| e.back() == edge.front())
            .map(|(i, _)| i)?;
        wire.rotate_left(i);
        let j = (j + wire.len() - i) % wire.len();
        let mut new_wire = wire.split_off(j + 1);
        wire.push_back(edge.clone());
        new_wire.push_back(edge.inverse());
        debug_assert!(Face::try_new(self.boundaries.clone(), ()).is_ok());
        debug_assert!(Face::try_new(vec![new_wire.clone()], ()).is_ok());
        let face1 = Face {
            boundaries: vec![new_wire],
            orientation: self.orientation,
            surface: Arc::new(Mutex::new(self.get_surface())),
        };
        Some((face0, face1))
    }

    /// Glue two faces at boundaries.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 8]);
    /// let edge = vec![
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[2], &v[0], ()),
    ///     Edge::new(&v[3], &v[4], ()),
    ///     Edge::new(&v[4], &v[5], ()),
    ///     Edge::new(&v[5], &v[3], ()),
    ///     Edge::new(&v[6], &v[2], ()),
    ///     Edge::new(&v[1], &v[6], ()),
    ///     Edge::new(&v[7], &v[5], ()),
    ///     Edge::new(&v[4], &v[7], ()),
    /// ];
    /// let wire0 = Wire::from(vec![
    ///     edge[0].clone(),
    ///     edge[1].clone(),
    ///     edge[2].clone(),
    /// ]);
    /// let wire1 = Wire::from(vec![
    ///     edge[3].clone(),
    ///     edge[4].clone(),
    ///     edge[5].clone(),
    /// ]);
    /// let wire2 = Wire::from(vec![
    ///     edge[6].clone(),
    ///     edge[1].inverse(),
    ///     edge[7].clone(),
    /// ]);
    /// let wire3 = Wire::from(vec![
    ///     edge[8].clone(),
    ///     edge[4].inverse(),
    ///     edge[9].clone(),
    /// ]);
    /// let face0 = Face::new(vec![wire0, wire1], ());
    /// let face1 = Face::new(vec![wire2, wire3], ());
    /// let face = face0.glue_at_boundaries(&face1).unwrap();
    /// let boundaries = face.boundary_iters();
    /// assert_eq!(boundaries.len(), 2);
    /// assert_eq!(boundaries[0].len(), 4);
    /// assert_eq!(boundaries[1].len(), 4);
    /// ```
    pub fn glue_at_boundaries(&self, other: &Self) -> Option<Self>
    where
        S: Clone + PartialEq,
        Wire<P, C>: Debug, {
        let surface = self.get_surface();
        if surface != other.get_surface() || self.orientation() != other.orientation() {
            return None;
        }
        let mut vemap: HashMap<VertexID<P>, &Edge<P, C>> = self
            .absolute_boundaries()
            .iter()
            .flatten()
            .map(|edge| (edge.front().id(), edge))
            .collect();
        other
            .absolute_boundaries()
            .iter()
            .flatten()
            .try_for_each(|edge| {
                if let Some(edge0) = vemap.get(&edge.back().id()) {
                    if edge.front() == edge0.back() {
                        if edge.is_same(edge0) {
                            vemap.remove(&edge.back().id());
                            return Some(());
                        } else {
                            return None;
                        }
                    }
                }
                vemap.insert(edge.front().id(), edge);
                Some(())
            })?;
        if vemap.is_empty() {
            return None;
        }
        let mut boundaries = Vec::new();
        while !vemap.is_empty() {
            let mut wire = Wire::new();
            let v = *vemap.iter().next().unwrap().0;
            let mut edge = vemap.remove(&v).unwrap();
            wire.push_back(edge.clone());
            while let Some(edge0) = vemap.remove(&edge.back().id()) {
                wire.push_back(edge0.clone());
                edge = edge0;
            }
            boundaries.push(wire);
        }
        debug_assert!(Face::try_new(boundaries.clone(), ()).is_ok());
        Some(Face {
            boundaries,
            orientation: self.orientation(),
            surface: Arc::new(Mutex::new(surface)),
        })
    }

    /// Creates display struct for debugging the face.
    ///
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use FaceDisplayFormat as FDF;
    /// let v = Vertex::news(&[0, 1, 2, 3, 4, 5]);
    /// let edge = vec![
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[2], &v[0], ()),
    ///     Edge::new(&v[3], &v[4], ()),
    ///     Edge::new(&v[4], &v[5], ()),
    ///     Edge::new(&v[5], &v[3], ()),
    /// ];
    /// let wire0 = Wire::from(vec![
    ///     edge[0].clone(),
    ///     edge[1].clone(),
    ///     edge[2].clone(),
    /// ]);
    /// let wire1 = Wire::from(vec![
    ///     edge[3].clone(),
    ///     edge[4].clone(),
    ///     edge[5].clone(),
    /// ]);
    /// let face = Face::new(vec![wire0, wire1], 120);
    ///
    /// let vertex_format = VertexDisplayFormat::AsPoint;
    /// let edge_format = EdgeDisplayFormat::VerticesTuple { vertex_format };
    /// let wire_format = WireDisplayFormat::EdgesList { edge_format };
    ///
    /// assert_eq!(
    ///     format!("{:?}", face.display(FDF::Full { wire_format })),
    ///     format!("Face {{ id: {:?}, boundaries: [[(0, 1), (1, 2), (2, 0)], [(3, 4), (4, 5), (5, 3)]], entity: 120 }}", face.id()),
    /// );
    /// assert_eq!(
    ///     format!("{:?}", face.display(FDF::BoundariesAndID { wire_format })),
    ///     format!("Face {{ id: {:?}, boundaries: [[(0, 1), (1, 2), (2, 0)], [(3, 4), (4, 5), (5, 3)]] }}", face.id()),
    /// );
    /// assert_eq!(
    ///     &format!("{:?}", face.display(FDF::BoundariesAndSurface { wire_format })),
    ///     "Face { boundaries: [[(0, 1), (1, 2), (2, 0)], [(3, 4), (4, 5), (5, 3)]], entity: 120 }",
    /// );
    /// assert_eq!(
    ///     &format!("{:?}", face.display(FDF::LoopsListTuple { wire_format })),
    ///     "Face([[(0, 1), (1, 2), (2, 0)], [(3, 4), (4, 5), (5, 3)]])",
    /// );
    /// assert_eq!(
    ///     &format!("{:?}", face.display(FDF::LoopsList { wire_format })),
    ///     "[[(0, 1), (1, 2), (2, 0)], [(3, 4), (4, 5), (5, 3)]]",
    /// );
    /// assert_eq!(
    ///     &format!("{:?}", face.display(FDF::AsSurface)),
    ///     "120",
    /// );
    /// ```
    #[inline(always)]
    pub fn display(&self, format: FaceDisplayFormat) -> DebugDisplay<'_, Self, FaceDisplayFormat> {
        DebugDisplay {
            entity: self,
            format,
        }
    }
}

impl<P, C, S: Clone + Invertible> Face<P, C, S> {
    /// Returns the cloned surface in face.
    /// If face is inverted, then the returned surface is also inverted.
    #[inline(always)]
    pub fn oriented_surface(&self) -> S {
        match self.orientation {
            true => self.surface.lock().unwrap().clone(),
            false => self.surface.lock().unwrap().inverse(),
        }
    }
}

impl<P, C, S> Face<P, C, S>
where
    P: Tolerance,
    C: BoundedCurve<Point = P>,
    S: IncludeCurve<C>,
{
    /// Returns the consistence of the geometry of end vertices
    /// and the geometry of edge.
    #[inline(always)]
    pub fn is_geometric_consistent(&self) -> bool {
        let surface = &*self.surface.lock().unwrap();
        self.boundary_iters().into_iter().flatten().all(|edge| {
            let edge_consist = edge.is_geometric_consistent();
            let curve = &*edge.curve.lock().unwrap();
            let curve_consist = surface.include(curve);
            edge_consist && curve_consist
        })
    }
}

impl<P, C, S> Clone for Face<P, C, S> {
    #[inline(always)]
    fn clone(&self) -> Face<P, C, S> {
        Face {
            boundaries: self.boundaries.clone(),
            orientation: self.orientation,
            surface: Arc::clone(&self.surface),
        }
    }
}

impl<P, C, S> PartialEq for Face<P, C, S> {
    #[inline(always)]
    fn eq(&self, other: &Self) -> bool {
        std::ptr::eq(Arc::as_ptr(&self.surface), Arc::as_ptr(&other.surface))
            && self.orientation == other.orientation
    }
}

impl<P, C, S> Eq for Face<P, C, S> {}

impl<P, C, S> Hash for Face<P, C, S> {
    #[inline(always)]
    fn hash<H: Hasher>(&self, state: &mut H) {
        std::ptr::hash(Arc::as_ptr(&self.surface), state);
        self.orientation.hash(state);
    }
}

/// An iterator over the edges in the boundaries of a face.
/// # Examples
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 4]);
/// let wire = Wire::from(vec![
///     Edge::new(&v[0], &v[1], ()),
///     Edge::new(&v[1], &v[2], ()),
///     Edge::new(&v[2], &v[3], ()),
///     Edge::new(&v[3], &v[0], ()),
/// ]);
/// let face = Face::new(vec![wire.clone()], ());
///
/// let iter = &mut face.boundary_iters()[0];
/// assert_eq!(iter.next().as_ref(), Some(&wire[0]));
/// assert_eq!(iter.next_back().as_ref(), Some(&wire[3])); // double ended
/// assert_eq!(iter.next().as_ref(), Some(&wire[1]));
/// assert_eq!(iter.next().as_ref(), Some(&wire[2]));
/// assert_eq!(iter.next_back().as_ref(), None);
/// assert_eq!(iter.next().as_ref(), None); // fused
/// ```
#[derive(Clone, Debug)]
pub struct BoundaryIter<'a, P, C> {
    edge_iter: EdgeIter<'a, P, C>,
    orientation: bool,
}

impl<'a, P, C> Iterator for BoundaryIter<'a, P, C> {
    type Item = Edge<P, C>;
    #[inline(always)]
    fn next(&mut self) -> Option<Edge<P, C>> {
        match self.orientation {
            true => self.edge_iter.next().cloned(),
            false => self.edge_iter.next_back().map(|edge| edge.inverse()),
        }
    }

    #[inline(always)]
    fn size_hint(&self) -> (usize, Option<usize>) { (self.len(), Some(self.len())) }

    #[inline(always)]
    fn last(mut self) -> Option<Edge<P, C>> { self.next_back() }
}

impl<'a, P, C> DoubleEndedIterator for BoundaryIter<'a, P, C> {
    #[inline(always)]
    fn next_back(&mut self) -> Option<Edge<P, C>> {
        match self.orientation {
            true => self.edge_iter.next_back().cloned(),
            false => self.edge_iter.next().map(|edge| edge.inverse()),
        }
    }
src/shell.rs (line 637)
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
    pub fn cut_edge(
        &mut self,
        edge_id: EdgeID<C>,
        vertex: &Vertex<P>,
    ) -> Option<(Edge<P, C>, Edge<P, C>)>
    where
        P: Clone,
        C: Cut<Point = P> + SearchParameter<D1, Point = P>,
    {
        if self.vertex_iter().any(|v| &v == vertex) {
            return None;
        }
        let mut edges = None;
        self.iter_mut()
            .flat_map(|face| face.boundaries.iter_mut())
            .try_for_each(|wire| {
                let find_res = wire
                    .iter()
                    .enumerate()
                    .find(|(_, edge)| edge.id() == edge_id);
                let (idx, edge) = match find_res {
                    Some(got) => got,
                    None => return Some(()),
                };
                if edges.is_none() {
                    edges = Some(edge.absolute_clone().cut(vertex)?);
                }
                let edges = edges.as_ref().unwrap();
                let new_wire = match edge.orientation() {
                    true => Wire::from(vec![edges.0.clone(), edges.1.clone()]),
                    false => Wire::from(vec![edges.1.inverse(), edges.0.inverse()]),
                };
                let flag = wire.swap_edge_into_wire(idx, new_wire);
                debug_assert!(flag);
                Some(())
            });
        edges
    }
    /// Removes `vertex` from `self` by concat two edges on both sides.
    ///
    /// # Returns
    /// Returns the new created edge.
    ///
    /// # Failures
    /// Returns `None` if:
    /// - there are no vertex corresponding to `vertex_id` in the shell,
    /// - the vertex is included more than 2 face boundaries,
    /// - the vertex is included more than 2 edges, or
    /// - concating edges is failed.
    pub fn remove_vertex_by_concat_edges(&mut self, vertex_id: VertexID<P>) -> Option<Edge<P, C>>
    where
        P: Debug,
        C: Concat<C, Point = P, Output = C> + Invertible + ParameterTransform, {
        let mut vec: Vec<(&mut Wire<P, C>, usize)> = self
            .face_iter_mut()
            .flat_map(|face| &mut face.boundaries)
            .filter_map(|wire| {
                let idx = wire
                    .edge_iter()
                    .enumerate()
                    .find(|(_, e)| e.back().id() == vertex_id)?
                    .0;
                Some((wire, idx))
            })
            .collect();
        if vec.len() > 2 || vec.is_empty() {
            None
        } else if vec.len() == 1 {
            let (wire, idx) = vec.pop().unwrap();
            let edge = wire[idx].concat(&wire[(idx + 1) % wire.len()]).ok()?;
            wire.swap_subwire_into_edges(idx, edge.clone());
            Some(edge)
        } else {
            let (wire0, idx0) = vec.pop().unwrap();
            let (wire1, idx1) = vec.pop().unwrap();
            if !wire0[idx0].is_same(&wire1[(idx1 + 1) % wire1.len()])
                || !wire0[(idx0 + 1) % wire0.len()].is_same(&wire1[idx1])
            {
                return None;
            }
            let edge = wire0[idx0].concat(&wire0[(idx0 + 1) % wire0.len()]).ok()?;
            wire1.swap_subwire_into_edges(idx1, edge.inverse());
            wire0.swap_subwire_into_edges(idx0, edge.clone());
            Some(edge)
        }
    }

Returns the front vertex

let v = Vertex::news(&[(), ()]);
let edge = Edge::new(&v[0], &v[1], ());
assert_eq!(edge.front(), &v[0]);
Examples found in repository?
src/wire.rs (line 83)
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
    pub fn front_vertex(&self) -> Option<&Vertex<P>> { self.front().map(|edge| edge.front()) }

    /// Returns the back edge. If `self` is empty wire, returns None.  
    /// Practically, an alias of the inherited method `VecDeque::back()`
    #[inline(always)]
    pub fn back_edge(&self) -> Option<&Edge<P, C>> { self.back() }

    /// Returns the back edge. If `self` is empty wire, returns None.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(), (), ()]);
    /// let mut wire = Wire::new();
    /// assert_eq!(wire.back_vertex(), None);
    /// wire.push_back(Edge::new(&v[1], &v[2], ()));
    /// wire.push_front(Edge::new(&v[0], &v[1], ()));
    /// assert_eq!(wire.back_vertex(), Some(&v[2]));
    /// ```
    #[inline(always)]
    pub fn back_vertex(&self) -> Option<&Vertex<P>> { self.back().map(|edge| edge.back()) }

    /// Returns vertices at both ends.
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 3]);
    /// let mut wire = Wire::new();
    /// assert_eq!(wire.back_vertex(), None);
    /// wire.push_back(Edge::new(&v[1], &v[2], ()));
    /// wire.push_front(Edge::new(&v[0], &v[1], ()));
    /// assert_eq!(wire.ends_vertices(), Some((&v[0], &v[2])));
    /// ```
    #[inline(always)]
    pub fn ends_vertices(&self) -> Option<(&Vertex<P>, &Vertex<P>)> {
        match (self.front_vertex(), self.back_vertex()) {
            (Some(got0), Some(got1)) => Some((got0, got1)),
            _ => None,
        }
    }

    /// Moves all the faces of `other` into `self`, leaving `other` empty.
    #[inline(always)]
    pub fn append(&mut self, other: &mut Wire<P, C>) { self.edge_list.append(&mut other.edge_list) }

    /// Splits the `Wire` into two at the given index.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 7]);
    /// let mut wire = Wire::new();
    /// for i in 0..6 {
    ///    wire.push_back(Edge::new(&v[i], &v[i + 1], ()));
    /// }
    /// let original_wire = wire.clone();
    /// let mut wire1 = wire.split_off(4);
    /// assert_eq!(wire.len(), 4);
    /// assert_eq!(wire1.len(), 2);
    /// wire.append(&mut wire1);
    /// assert_eq!(original_wire, wire);
    /// ```
    /// # Panics
    /// Panics if `at > self.len()`
    #[inline(always)]
    pub fn split_off(&mut self, at: usize) -> Wire<P, C> {
        Wire {
            edge_list: self.edge_list.split_off(at),
        }
    }

    /// Inverts the wire.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 4]);
    /// let mut wire = Wire::from(vec![
    ///     Edge::new(&v[3], &v[2], ()),
    ///     Edge::new(&v[2], &v[1], ()),
    ///     Edge::new(&v[1], &v[0], ()),
    /// ]);
    /// wire.invert();
    /// for (i, vert) in wire.vertex_iter().enumerate() {
    ///     assert_eq!(v[i], vert);
    /// }
    /// ```
    #[inline(always)]
    pub fn invert(&mut self) -> &mut Self {
        *self = self.inverse();
        self
    }

    /// Returns the inverse wire.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 4]);
    /// let mut wire = Wire::from(vec![
    ///     Edge::new(&v[3], &v[2], ()),
    ///     Edge::new(&v[2], &v[1], ()),
    ///     Edge::new(&v[1], &v[0], ()),
    /// ]);
    /// let inverse = wire.inverse();
    /// wire.invert();
    /// for (edge0, edge1) in wire.edge_iter().zip(inverse.edge_iter()) {
    ///     assert_eq!(edge0, edge1);
    /// }
    /// ```
    #[inline(always)]
    pub fn inverse(&self) -> Wire<P, C> {
        let edge_list = self.edge_iter().rev().map(|edge| edge.inverse()).collect();
        Wire { edge_list }
    }

    /// Returns whether all the adjacent pairs of edges have shared vertices or not.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 4]);
    /// let mut wire = Wire::from(vec![
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[2], &v[3], ()),
    /// ]);
    /// assert!(!wire.is_continuous());
    /// wire.insert(1, Edge::new(&v[1], &v[2], ()));
    /// assert!(wire.is_continuous());
    /// ```
    /// ```
    /// use truck_topology::*;
    /// // The empty wire is continuous
    /// assert!(Wire::<(), ()>::new().is_continuous());
    /// ```
    pub fn is_continuous(&self) -> bool {
        let mut iter = self.edge_iter();
        if let Some(edge) = iter.next() {
            let mut prev = edge.back();
            for edge in iter {
                if prev != edge.front() {
                    return false;
                }
                prev = edge.back();
            }
        }
        true
    }

    /// Returns whether the front vertex of the wire is the same as the back one or not.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 4]);
    /// let mut wire = Wire::from(vec![
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[2], &v[3], ()),
    /// ]);
    /// assert!(!wire.is_cyclic());
    /// wire.push_back(Edge::new(&v[3], &v[0], ()));
    /// assert!(wire.is_cyclic());
    /// ```
    /// ```
    /// use truck_topology::*;
    /// // The empty wire is cyclic.
    /// assert!(Wire::<(), ()>::new().is_cyclic());
    /// ```
    #[inline(always)]
    pub fn is_cyclic(&self) -> bool { self.front_vertex() == self.back_vertex() }

    /// Returns whether the wire is closed or not.
    /// Here, "closed" means "continuous" and "cyclic".
    #[inline(always)]
    pub fn is_closed(&self) -> bool { self.is_continuous() && self.is_cyclic() }

    /// Returns whether simple or not.
    /// Here, "simple" means all the vertices in the wire are shared from only two edges at most.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 4]);
    /// let edge0 = Edge::new(&v[0], &v[1], ());
    /// let edge1 = Edge::new(&v[1], &v[2], ());
    /// let edge2 = Edge::new(&v[2], &v[3], ());
    /// let edge3 = Edge::new(&v[3], &v[1], ());
    /// let edge4 = Edge::new(&v[3], &v[0], ());
    ///
    /// let wire0 = Wire::from_iter(vec![&edge0, &edge1, &edge2, &edge3]);
    /// let wire1 = Wire::from(vec![edge0, edge1, edge2, edge4]);
    ///
    /// assert!(!wire0.is_simple());
    /// assert!(wire1.is_simple());
    /// ```
    /// ```
    /// use truck_topology::*;
    /// // The empty wire is simple.
    /// assert!(Wire::<(), ()>::new().is_simple());
    /// ```
    pub fn is_simple(&self) -> bool {
        let mut set = HashSet::default();
        self.vertex_iter()
            .all(move |vertex| set.insert(vertex.id()))
    }

    /// Determines whether all the wires in `wires` has no same vertices.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    ///
    /// let v = Vertex::news(&[(), (), (), (), ()]);
    /// let edge0 = Edge::new(&v[0], &v[1], ());
    /// let edge1 = Edge::new(&v[1], &v[2], ());
    /// let edge2 = Edge::new(&v[2], &v[3], ());
    /// let edge3 = Edge::new(&v[3], &v[4], ());
    ///
    /// let wire0 = Wire::from(vec![edge0, edge1]);
    /// let wire1 = Wire::from(vec![edge2]);
    /// let wire2 = Wire::from(vec![edge3]);
    ///
    /// assert!(Wire::disjoint_wires(&[wire0.clone(), wire2]));
    /// assert!(!Wire::disjoint_wires(&[wire0, wire1]));
    /// ```
    pub fn disjoint_wires(wires: &[Wire<P, C>]) -> bool {
        let mut set = HashSet::default();
        wires.iter().all(move |wire| {
            let mut vec = Vec::new();
            let res = wire.vertex_iter().all(|v| {
                vec.push(v.id());
                !set.contains(&v.id())
            });
            set.extend(vec);
            res
        })
    }

    /// Swap one edge into two edges.
    ///
    /// # Arguments
    /// - `idx`: Index of edge in wire
    /// - `edges`: Inserted edges
    ///
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(), (), (), (), ()]);
    /// let edge0 = Edge::new(&v[0], &v[1], 0);
    /// let edge1 = Edge::new(&v[1], &v[3], 1);
    /// let edge2 = Edge::new(&v[3], &v[4], 2);
    /// let edge3 = Edge::new(&v[1], &v[2], 3);
    /// let edge4 = Edge::new(&v[2], &v[3], 4);
    /// let mut wire0 = Wire::from(vec![
    ///     edge0.clone(), edge1, edge2.clone()
    /// ]);
    /// let wire1 = Wire::from(vec![
    ///     edge0, edge3.clone(), edge4.clone(), edge2
    /// ]);
    /// assert_ne!(wire0, wire1);
    /// wire0.swap_edge_into_wire(1, Wire::from(vec![edge3, edge4]));
    /// assert_eq!(wire0, wire1);
    /// ```
    ///
    /// # Panics
    /// Panic occars if `idx >= self.len()`.
    ///
    /// # Failure
    /// Returns `false` and `self` will not be changed if the end vertices of `self[idx]` and the ones of `wire` is not the same.
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(), (), (), (), ()]);
    /// let edge0 = Edge::new(&v[0], &v[1], 0);
    /// let edge1 = Edge::new(&v[1], &v[3], 1);
    /// let edge2 = Edge::new(&v[3], &v[4], 2);
    /// let edge3 = Edge::new(&v[1], &v[2], 3);
    /// let edge4 = Edge::new(&v[2], &v[1], 4);
    /// let mut wire0 = Wire::from(vec![
    ///     edge0.clone(), edge1, edge2.clone()
    /// ]);
    /// let backup = wire0.clone();
    /// // The end vertices of wire[1] == edge1 is (v[1], v[3]).
    /// // The end points of new wire [edge3, edge4] is (v[1], v[1]).
    /// // Since the back vertices are different, returns false and do nothing.
    /// assert!(!wire0.swap_edge_into_wire(1, Wire::from(vec![edge3, edge4])));
    /// assert_eq!(wire0, backup);
    /// ```
    pub fn swap_edge_into_wire(&mut self, idx: usize, wire: Wire<P, C>) -> bool {
        if wire.is_empty() || self[idx].ends() != wire.ends_vertices().unwrap() {
            return false;
        }
        let mut new_wire: Vec<_> = self.drain(0..idx).collect();
        new_wire.extend(wire);
        self.pop_front();
        new_wire.extend(self.drain(..));
        *self = new_wire.into();
        true
    }
    /// Concat edges
    pub(super) fn swap_subwire_into_edges(&mut self, mut idx: usize, edge: Edge<P, C>) {
        if idx + 1 == self.len() {
            self.rotate_left(1);
            idx -= 1;
        }
        let mut new_wire: Vec<_> = self.drain(0..idx).collect();
        new_wire.push(edge);
        self.pop_front();
        self.pop_front();
        new_wire.extend(self.drain(..));
        *self = new_wire.into();
    }

    pub(super) fn sub_try_mapped<'a, Q, D, KF, KV>(
        &'a self,
        edge_map: &mut EdgeEntryMapForTryMapping<'a, P, C, Q, D, KF, KV>,
    ) -> Option<Wire<Q, D>>
    where
        KF: FnMut(&'a Edge<P, C>) -> EdgeID<C>,
        KV: FnMut(&'a Edge<P, C>) -> Option<Edge<Q, D>>,
    {
        self.edge_iter()
            .map(|edge| Some(edge_map.entry_or_insert(edge).as_ref()?.absolute_clone()))
            .collect()
    }

    /// Returns a new wire whose curves are mapped by `curve_mapping` and
    /// whose points are mapped by `point_mapping`.
    /// # Remarks
    /// Accessing geometry elements directly in the closure will result in a deadlock.
    /// So, this method does not appear to the document.
    #[doc(hidden)]
    pub fn try_mapped<Q, D>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Option<Q>,
        mut curve_mapping: impl FnMut(&C) -> Option<D>,
    ) -> Option<Wire<Q, D>> {
        let mut vertex_map = EntryMap::new(Vertex::id, move |v| v.try_mapped(&mut point_mapping));
        let mut edge_map = EntryMap::new(
            Edge::id,
            edge_entry_map_try_closure(&mut vertex_map, &mut curve_mapping),
        );
        self.sub_try_mapped(&mut edge_map)
    }

    pub(super) fn sub_mapped<'a, Q, D, KF, KV>(
        &'a self,
        edge_map: &mut EdgeEntryMapForMapping<'a, P, C, Q, D, KF, KV>,
    ) -> Wire<Q, D>
    where
        KF: FnMut(&'a Edge<P, C>) -> EdgeID<C>,
        KV: FnMut(&'a Edge<P, C>) -> Edge<Q, D>,
    {
        self.edge_iter()
            .map(|edge| {
                let new_edge = edge_map.entry_or_insert(edge);
                match edge.orientation() {
                    true => new_edge.clone(),
                    false => new_edge.inverse(),
                }
            })
            .collect()
    }
    /// Returns a new wire whose curves are mapped by `curve_mapping` and
    /// whose points are mapped by `point_mapping`.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[0, 1, 2, 3, 4]);
    /// let wire0: Wire<usize, usize> = vec![
    ///     Edge::new(&v[0], &v[1], 100),
    ///     Edge::new(&v[2], &v[1], 110).inverse(),
    ///     Edge::new(&v[3], &v[4], 120),
    ///     Edge::new(&v[4], &v[0], 130),
    /// ].into();
    /// let wire1 = wire0.mapped(
    ///     &move |i: &usize| *i as f64 + 0.5,
    ///     &move |j: &usize| *j as f64 + 1000.5,
    /// );
    ///
    /// // Check the points
    /// for (v0, v1) in wire0.vertex_iter().zip(wire1.vertex_iter()) {
    ///     let i = v0.get_point();
    ///     let j = v1.get_point();
    ///     assert_eq!(i as f64 + 0.5, j);
    /// }
    ///
    /// // Check the curves and orientation
    /// for (edge0, edge1) in wire0.edge_iter().zip(wire1.edge_iter()) {
    ///     let i = edge0.get_curve();
    ///     let j = edge1.get_curve();
    ///     assert_eq!(i as f64 + 1000.5, j);
    ///     assert_eq!(edge0.orientation(), edge1.orientation());
    /// }
    ///
    /// // Check the connection
    /// assert_eq!(wire1[0].back(), wire1[1].front());
    /// assert_ne!(wire1[1].back(), wire1[2].front());
    /// assert_eq!(wire1[2].back(), wire1[3].front());
    /// assert_eq!(wire1[3].back(), wire1[0].front());
    /// ```
    /// # Remarks
    /// Accessing geometry elements directly in the closure will result in a deadlock.
    /// So, this method does not appear to the document.
    #[doc(hidden)]
    pub fn mapped<Q, D>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Q,
        mut curve_mapping: impl FnMut(&C) -> D,
    ) -> Wire<Q, D> {
        let mut vertex_map = EntryMap::new(Vertex::id, move |v| v.mapped(&mut point_mapping));
        let mut edge_map = EntryMap::new(
            Edge::id,
            edge_entry_map_closure(&mut vertex_map, &mut curve_mapping),
        );
        self.sub_mapped(&mut edge_map)
    }

    /// Returns the consistence of the geometry of end vertices
    /// and the geometry of edge.
    #[inline(always)]
    pub fn is_geometric_consistent(&self) -> bool
    where
        P: Tolerance,
        C: BoundedCurve<Point = P>, {
        self.iter().all(|edge| edge.is_geometric_consistent())
    }

    /// Creates display struct for debugging the wire.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use WireDisplayFormat as WDF;
    /// let v = Vertex::news(&[0, 1, 2, 3, 4]);
    /// let wire: Wire<usize, usize> = vec![
    ///     Edge::new(&v[0], &v[1], 100),
    ///     Edge::new(&v[2], &v[1], 110).inverse(),
    ///     Edge::new(&v[3], &v[4], 120),
    /// ].into();
    ///
    /// let vertex_format = VertexDisplayFormat::AsPoint;
    /// let edge_format = EdgeDisplayFormat::VerticesTuple { vertex_format };
    ///
    /// assert_eq!(
    ///     &format!("{:?}", wire.display(WDF::EdgesListTuple {edge_format})),
    ///     "Wire([(0, 1), (1, 2), (3, 4)])",
    /// );
    /// assert_eq!(
    ///     &format!("{:?}", wire.display(WDF::EdgesList {edge_format})),
    ///     "[(0, 1), (1, 2), (3, 4)]",
    /// );
    /// assert_eq!(
    ///     &format!("{:?}", wire.display(WDF::VerticesList {vertex_format})),
    ///     "[0, 1, 2, 3, 4]",
    /// );
    /// ```
    #[inline(always)]
    pub fn display(&self, format: WireDisplayFormat) -> DebugDisplay<'_, Self, WireDisplayFormat> {
        DebugDisplay {
            entity: self,
            format,
        }
    }
}

type EdgeEntryMapForTryMapping<'a, P, C, Q, D, KF, KV> =
    EntryMap<EdgeID<C>, Option<Edge<Q, D>>, KF, KV, &'a Edge<P, C>>;
type EdgeEntryMapForMapping<'a, P, C, Q, D, KF, KV> =
    EntryMap<EdgeID<C>, Edge<Q, D>, KF, KV, &'a Edge<P, C>>;

pub(super) fn edge_entry_map_try_closure<'a, P, C, Q, D, KF, VF>(
    vertex_map: &'a mut EntryMap<VertexID<P>, Option<Vertex<Q>>, KF, VF, &'a Vertex<P>>,
    curve_mapping: &'a mut impl FnMut(&C) -> Option<D>,
) -> impl FnMut(&'a Edge<P, C>) -> Option<Edge<Q, D>> + 'a
where
    KF: FnMut(&'a Vertex<P>) -> VertexID<P>,
    VF: FnMut(&'a Vertex<P>) -> Option<Vertex<Q>>,
{
    move |edge| {
        let vf = edge.absolute_front();
        let vertex0 = vertex_map.entry_or_insert(vf).clone()?;
        let vb = edge.absolute_back();
        let vertex1 = vertex_map.entry_or_insert(vb).clone()?;
        let curve = curve_mapping(&*edge.curve.lock().unwrap())?;
        Some(Edge::debug_new(&vertex0, &vertex1, curve))
    }
}

pub(super) fn edge_entry_map_closure<'a, P, C, Q, D, KF, VF>(
    vertex_map: &'a mut EntryMap<VertexID<P>, Vertex<Q>, KF, VF, &'a Vertex<P>>,
    curve_mapping: &'a mut impl FnMut(&C) -> D,
) -> impl FnMut(&'a Edge<P, C>) -> Edge<Q, D> + 'a
where
    KF: FnMut(&'a Vertex<P>) -> VertexID<P>,
    VF: FnMut(&'a Vertex<P>) -> Vertex<Q>,
{
    move |edge| {
        let vf = edge.absolute_front();
        let vertex0 = vertex_map.entry_or_insert(vf).clone();
        let vb = edge.absolute_back();
        let vertex1 = vertex_map.entry_or_insert(vb).clone();
        let curve = curve_mapping(&*edge.curve.lock().unwrap());
        Edge::debug_new(&vertex0, &vertex1, curve)
    }
}

impl<T, P, C> From<T> for Wire<P, C>
where T: Into<VecDeque<Edge<P, C>>>
{
    #[inline(always)]
    fn from(edge_list: T) -> Wire<P, C> {
        Wire {
            edge_list: edge_list.into(),
        }
    }
}

impl<P, C> FromIterator<Edge<P, C>> for Wire<P, C> {
    #[inline(always)]
    fn from_iter<I: IntoIterator<Item = Edge<P, C>>>(iter: I) -> Wire<P, C> {
        Wire::from(VecDeque::from_iter(iter))
    }
}

impl<'a, P, C> FromIterator<&'a Edge<P, C>> for Wire<P, C> {
    #[inline(always)]
    fn from_iter<I: IntoIterator<Item = &'a Edge<P, C>>>(iter: I) -> Wire<P, C> {
        Wire::from(VecDeque::from_iter(iter.into_iter().map(Edge::clone)))
    }
}

impl<P, C> IntoIterator for Wire<P, C> {
    type Item = Edge<P, C>;
    type IntoIter = EdgeIntoIter<P, C>;
    #[inline(always)]
    fn into_iter(self) -> Self::IntoIter { self.edge_list.into_iter() }
}

impl<'a, P, C> IntoIterator for &'a Wire<P, C> {
    type Item = &'a Edge<P, C>;
    type IntoIter = EdgeIter<'a, P, C>;
    #[inline(always)]
    fn into_iter(self) -> Self::IntoIter { self.edge_list.iter() }
}

/// The reference iterator over all edges in a wire.
pub type EdgeIter<'a, P, C> = vec_deque::Iter<'a, Edge<P, C>>;
/// The mutable reference iterator over all edges in a wire.
pub type EdgeIterMut<'a, P, C> = vec_deque::IterMut<'a, Edge<P, C>>;
/// The into iterator over all edges in a wire.
pub type EdgeIntoIter<P, C> = vec_deque::IntoIter<Edge<P, C>>;
/// The reference parallel iterator over all edges in a wire.
pub type EdgeParallelIter<'a, P, C> = <VecDeque<Edge<P, C>> as IntoParallelRefIterator<'a>>::Iter;
/// The mutable reference parallel iterator over all edges in a wire.
pub type EdgeParallelIterMut<'a, P, C> =
    <VecDeque<Edge<P, C>> as IntoParallelRefMutIterator<'a>>::Iter;
/// the parallel iterator over all edges in a wire.
pub type EdgeParallelIntoIter<P, C> = <VecDeque<Edge<P, C>> as IntoParallelIterator>::Iter;

/// The iterator over all the vertices included in a wire.
/// # Details
/// Fundamentally, the iterator runs over all the vertices in a wire.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 6]);
/// let wire = Wire::from(vec![
///     Edge::new(&v[0], &v[1], ()),
///     Edge::new(&v[2], &v[3], ()),
///     Edge::new(&v[4], &v[5], ()),
/// ]);
/// let mut viter = wire.vertex_iter();
/// assert_eq!(viter.next().as_ref(), Some(&v[0]));
/// assert_eq!(viter.next().as_ref(), Some(&v[1]));
/// assert_eq!(viter.next().as_ref(), Some(&v[2]));
/// assert_eq!(viter.next().as_ref(), Some(&v[3]));
/// assert_eq!(viter.next().as_ref(), Some(&v[4]));
/// assert_eq!(viter.next().as_ref(), Some(&v[5]));
/// assert_eq!(viter.next(), None);
/// assert_eq!(viter.next(), None); // VertexIter is a FusedIterator.
/// ```
/// If a pair of adjacent edges share one vertex, the iterator run only one time at the shared vertex.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 6]);
/// let wire = Wire::from(vec![
///     Edge::new(&v[0], &v[1], ()),
///     Edge::new(&v[2], &v[3], ()),
///     Edge::new(&v[3], &v[4], ()),
///     Edge::new(&v[4], &v[5], ()),
/// ]);
/// let mut viter = wire.vertex_iter();
/// assert_eq!(viter.next().as_ref(), Some(&v[0]));
/// assert_eq!(viter.next().as_ref(), Some(&v[1]));
/// assert_eq!(viter.next().as_ref(), Some(&v[2]));
/// assert_eq!(viter.next().as_ref(), Some(&v[3]));
/// assert_eq!(viter.next().as_ref(), Some(&v[4]));
/// assert_eq!(viter.next().as_ref(), Some(&v[5]));
/// assert_eq!(viter.next(), None);
/// ```
/// If the wire is cyclic, the iterator does not arrive at the last vertex.
/// ```
/// # use truck_topology::*;
/// let v = Vertex::news(&[(); 5]);
/// let wire = Wire::from(vec![
///     Edge::new(&v[0], &v[1], ()),
///     Edge::new(&v[1], &v[2], ()),
///     Edge::new(&v[3], &v[4], ()),
///     Edge::new(&v[4], &v[0], ()),
/// ]);
/// let mut viter = wire.vertex_iter();
/// assert_eq!(viter.next().as_ref(), Some(&v[0]));
/// assert_eq!(viter.next().as_ref(), Some(&v[1]));
/// assert_eq!(viter.next().as_ref(), Some(&v[2]));
/// assert_eq!(viter.next().as_ref(), Some(&v[3]));
/// assert_eq!(viter.next().as_ref(), Some(&v[4]));
/// assert_eq!(viter.next(), None);
/// ```
#[derive(Clone, Debug)]
pub struct VertexIter<'a, P, C> {
    edge_iter: Peekable<EdgeIter<'a, P, C>>,
    unconti_next: Option<Vertex<P>>,
    cyclic: bool,
}

impl<'a, P, C> Iterator for VertexIter<'a, P, C> {
    type Item = Vertex<P>;

    fn next(&mut self) -> Option<Vertex<P>> {
        if self.unconti_next.is_some() {
            let res = self.unconti_next.clone();
            self.unconti_next = None;
            res
        } else if let Some(edge) = self.edge_iter.next() {
            if let Some(next) = self.edge_iter.peek() {
                if edge.back() != next.front() {
                    self.unconti_next = Some(edge.back().clone());
                }
            } else if !self.cyclic {
                self.unconti_next = Some(edge.back().clone());
            }
            Some(edge.front().clone())
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let min_size = self.edge_iter.len();
        let max_size = self.edge_iter.len() * 2;
        (min_size, Some(max_size))
    }

    fn last(self) -> Option<Vertex<P>> {
        let closed = self.cyclic;
        self.edge_iter.last().map(|edge| {
            if closed {
                edge.front().clone()
            } else {
                edge.back().clone()
            }
        })
    }
More examples
Hide additional examples
src/face.rs (line 232)
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
    pub fn vertex_iter(&self) -> impl Iterator<Item = Vertex<P>> + '_ {
        self.edge_iter().map(|e| e.front().clone())
    }

    /// Adds a boundary to the face.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(), (), (), (), (), ()]);
    /// let wire0 = Wire::from(vec![
    ///      Edge::new(&v[0], &v[1], ()),
    ///      Edge::new(&v[1], &v[2], ()),
    ///      Edge::new(&v[2], &v[0], ()),
    /// ]);
    /// let wire1 = Wire::from(vec![
    ///      Edge::new(&v[3], &v[4], ()),
    ///      Edge::new(&v[4], &v[5], ()),
    ///      Edge::new(&v[5], &v[3], ()),
    /// ]);
    /// let mut face0 = Face::new(vec![wire0.clone()], ());
    /// face0.try_add_boundary(wire1.clone()).unwrap();
    /// let face1 = Face::new(vec![wire0, wire1], ());
    /// assert_eq!(face0.boundaries(), face1.boundaries());
    /// ```
    /// # Remarks
    /// 1. If the face is inverted, then the added wire is inverted as absolute boundary.
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(), (), (), (), (), ()]);
    /// let wire0 = Wire::from(vec![
    ///      Edge::new(&v[0], &v[1], ()),
    ///      Edge::new(&v[1], &v[2], ()),
    ///      Edge::new(&v[2], &v[0], ()),
    /// ]);
    /// let wire1 = Wire::from(vec![
    ///      Edge::new(&v[3], &v[4], ()),
    ///      Edge::new(&v[5], &v[4], ()).inverse(),
    ///      Edge::new(&v[5], &v[3], ()),
    /// ]);
    /// let mut face = Face::new(vec![wire0], ());
    /// face.invert();
    /// face.try_add_boundary(wire1.clone()).unwrap();
    ///
    /// // The boundary is added in compatible with the face orientation.
    /// assert_eq!(face.boundaries()[1], wire1);
    ///
    /// // The absolute boundary is inverted!
    /// let iter0 = face.absolute_boundaries()[1].edge_iter();
    /// let iter1 = wire1.edge_iter().rev();
    /// for (edge0, edge1) in iter0.zip(iter1) {
    ///     assert_eq!(edge0.id(), edge1.id());
    ///     assert_eq!(edge0.orientation(), !edge1.orientation());
    /// }
    /// ```
    /// 2. This method renew the face id.
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(), (), (), (), (), ()]);
    /// let wire0 = Wire::from(vec![
    ///      Edge::new(&v[0], &v[1], ()),
    ///      Edge::new(&v[1], &v[2], ()),
    ///      Edge::new(&v[2], &v[0], ()),
    /// ]);
    /// let wire1 = Wire::from(vec![
    ///      Edge::new(&v[3], &v[4], ()),
    ///      Edge::new(&v[5], &v[4], ()).inverse(),
    ///      Edge::new(&v[5], &v[3], ()),
    /// ]);
    /// let mut face0 = Face::new(vec![wire0], ());
    /// let face1 = face0.clone();
    /// assert_eq!(face0.id(), face1.id());
    /// face0.try_add_boundary(wire1).unwrap();
    /// assert_ne!(face0.id(), face1.id());
    /// ```
    #[inline(always)]
    pub fn try_add_boundary(&mut self, mut wire: Wire<P, C>) -> Result<()>
    where S: Clone {
        if wire.is_empty() {
            return Err(Error::EmptyWire);
        } else if !wire.is_closed() {
            return Err(Error::NotClosedWire);
        } else if !wire.is_simple() {
            return Err(Error::NotSimpleWire);
        }
        if !self.orientation {
            wire.invert();
        }
        self.boundaries.push(wire);
        self.renew_pointer();
        if !Wire::disjoint_wires(&self.boundaries) {
            self.boundaries.pop();
            return Err(Error::NotDisjointWires);
        }
        Ok(())
    }

    /// Adds a boundary to the face.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(), (), (), (), (), ()]);
    /// let wire0 = Wire::from(vec![
    ///      Edge::new(&v[0], &v[1], ()),
    ///      Edge::new(&v[1], &v[2], ()),
    ///      Edge::new(&v[2], &v[0], ()),
    /// ]);
    /// let wire1 = Wire::from(vec![
    ///      Edge::new(&v[3], &v[4], ()),
    ///      Edge::new(&v[4], &v[5], ()),
    ///      Edge::new(&v[5], &v[3], ()),
    /// ]);
    /// let mut face0 = Face::new(vec![wire0.clone()], ());
    /// face0.add_boundary(wire1.clone());
    /// let face1 = Face::new(vec![wire0, wire1], ());
    /// assert_eq!(face0.boundaries(), face1.boundaries());
    /// ```
    /// # Remarks
    /// 1. If the face is inverted, then the added wire is inverted as absolute boundary.
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(), (), (), (), (), ()]);
    /// let wire0 = Wire::from(vec![
    ///      Edge::new(&v[0], &v[1], ()),
    ///      Edge::new(&v[1], &v[2], ()),
    ///      Edge::new(&v[2], &v[0], ()),
    /// ]);
    /// let wire1 = Wire::from(vec![
    ///      Edge::new(&v[3], &v[4], ()),
    ///      Edge::new(&v[5], &v[4], ()).inverse(),
    ///      Edge::new(&v[5], &v[3], ()),
    /// ]);
    /// let mut face = Face::new(vec![wire0], ());
    /// face.invert();
    /// face.add_boundary(wire1.clone());
    ///
    /// // The boundary is added in compatible with the face orientation.
    /// assert_eq!(face.boundaries()[1], wire1);
    ///
    /// // The absolute boundary is inverted!
    /// let iter0 = face.absolute_boundaries()[1].edge_iter();
    /// let iter1 = wire1.edge_iter().rev();
    /// for (edge0, edge1) in iter0.zip(iter1) {
    ///     assert_eq!(edge0.id(), edge1.id());
    ///     assert_eq!(edge0.orientation(), !edge1.orientation());
    /// }
    /// ```
    /// 2. This method renew the face id.
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(), (), (), (), (), ()]);
    /// let wire0 = Wire::from(vec![
    ///      Edge::new(&v[0], &v[1], ()),
    ///      Edge::new(&v[1], &v[2], ()),
    ///      Edge::new(&v[2], &v[0], ()),
    /// ]);
    /// let wire1 = Wire::from(vec![
    ///      Edge::new(&v[3], &v[4], ()),
    ///      Edge::new(&v[5], &v[4], ()).inverse(),
    ///      Edge::new(&v[5], &v[3], ()),
    /// ]);
    /// let mut face0 = Face::new(vec![wire0], ());
    /// let face1 = face0.clone();
    /// assert_eq!(face0.id(), face1.id());
    /// face0.add_boundary(wire1);
    /// assert_ne!(face0.id(), face1.id());
    /// ```
    #[inline(always)]
    pub fn add_boundary(&mut self, wire: Wire<P, C>)
    where S: Clone {
        self.try_add_boundary(wire).remove_try()
    }

    /// Returns a new face whose surface is mapped by `surface_mapping`,
    /// curves are mapped by `curve_mapping` and points are mapped by `point_mapping`.
    /// # Remarks
    /// Accessing geometry elements directly in the closure will result in a deadlock.
    /// So, this method does not appear to the document.
    #[doc(hidden)]
    pub fn try_mapped<Q, D, T>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Option<Q>,
        mut curve_mapping: impl FnMut(&C) -> Option<D>,
        mut surface_mapping: impl FnMut(&S) -> Option<T>,
    ) -> Option<Face<Q, D, T>> {
        let wires = self
            .absolute_boundaries()
            .iter()
            .map(|wire| wire.try_mapped(&mut point_mapping, &mut curve_mapping))
            .collect::<Option<Vec<_>>>()?;
        let surface = surface_mapping(&*self.surface.lock().unwrap())?;
        let mut face = Face::debug_new(wires, surface);
        if !self.orientation() {
            face.invert();
        }
        Some(face)
    }

    /// Returns a new face whose surface is mapped by `surface_mapping`,
    /// curves are mapped by `curve_mapping` and points are mapped by `point_mapping`.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[0, 1, 2, 3, 4, 5, 6]);
    /// let wire0 = Wire::from(vec![
    ///     Edge::new(&v[0], &v[1], 100),
    ///     Edge::new(&v[1], &v[2], 200),
    ///     Edge::new(&v[2], &v[3], 300),
    ///     Edge::new(&v[3], &v[0], 400),
    /// ]);
    /// let wire1 = Wire::from(vec![
    ///     Edge::new(&v[4], &v[5], 500),
    ///     Edge::new(&v[6], &v[5], 600).inverse(),
    ///     Edge::new(&v[6], &v[4], 700),
    /// ]);
    /// let face0 = Face::new(vec![wire0, wire1], 10000);
    /// let face1 = face0.mapped(
    ///     &move |i: &usize| *i + 10,
    ///     &move |j: &usize| *j + 1000,
    ///     &move |k: &usize| *k + 100000,
    /// );
    /// # for wire in face1.boundaries() {
    /// #    assert!(wire.is_closed());
    /// #    assert!(wire.is_simple());
    /// # }
    ///
    /// assert_eq!(
    ///     face0.get_surface() + 100000,
    ///     face1.get_surface(),
    /// );
    /// let biters0 = face0.boundary_iters();
    /// let biters1 = face1.boundary_iters();
    /// for (biter0, biter1) in biters0.into_iter().zip(biters1) {
    ///     for (edge0, edge1) in biter0.zip(biter1) {
    ///         assert_eq!(
    ///             edge0.front().get_point() + 10,
    ///             edge1.front().get_point(),
    ///         );
    ///         assert_eq!(
    ///             edge0.back().get_point() + 10,
    ///             edge1.back().get_point(),
    ///         );
    ///         assert_eq!(edge0.orientation(), edge1.orientation());
    ///         assert_eq!(
    ///             edge0.get_curve() + 1000,
    ///             edge1.get_curve(),
    ///         );
    ///     }
    /// }
    /// ```
    /// # Remarks
    /// Accessing geometry elements directly in the closure will result in a deadlock.
    /// So, this method does not appear to the document.
    #[doc(hidden)]
    pub fn mapped<Q, D, T>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Q,
        mut curve_mapping: impl FnMut(&C) -> D,
        mut surface_mapping: impl FnMut(&S) -> T,
    ) -> Face<Q, D, T> {
        let wires: Vec<_> = self
            .absolute_boundaries()
            .iter()
            .map(|wire| wire.mapped(&mut point_mapping, &mut curve_mapping))
            .collect();
        let surface = surface_mapping(&*self.surface.lock().unwrap());
        let mut face = Face::debug_new(wires, surface);
        if !self.orientation() {
            face.invert();
        }
        face
    }

    /// Returns the orientation of face.
    ///
    /// The result of this method is the same with `self.boundaries() == self.absolute_boundaries().clone()`.
    /// Moreover, if this method returns false, `self.boundaries() == self.absolute_boundaries().inverse()`.
    #[inline(always)]
    pub fn orientation(&self) -> bool { self.orientation }

    /// Returns the clone of surface of face.
    #[inline(always)]
    pub fn get_surface(&self) -> S
    where S: Clone {
        self.surface.lock().unwrap().clone()
    }

    /// Sets the surface of face.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(), (), ()]);
    /// let wire = Wire::from(vec![
    ///      Edge::new(&v[0], &v[1], ()),
    ///      Edge::new(&v[1], &v[2], ()),
    ///      Edge::new(&v[2], &v[0], ()),
    /// ]);
    /// let face0 = Face::new(vec![wire], 0);
    /// let face1 = face0.clone();
    ///
    /// // Two faces have the same content.
    /// assert_eq!(face0.get_surface(), 0);
    /// assert_eq!(face1.get_surface(), 0);
    ///
    /// // Set surface
    /// face0.set_surface(1);
    ///
    /// // The contents of two vertices are synchronized.
    /// assert_eq!(face0.get_surface(), 1);
    /// assert_eq!(face1.get_surface(), 1);
    /// ```
    #[inline(always)]
    pub fn set_surface(&self, surface: S) { *self.surface.lock().unwrap() = surface; }

    /// Inverts the direction of the face.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use truck_topology::errors::Error;
    /// let v = Vertex::news(&[(), (), ()]);
    /// let wire = Wire::from(vec![
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[2], &v[0], ()),
    /// ]);
    /// let mut face = Face::new(vec![wire], ());
    /// let org_face = face.clone();
    /// let org_bdry = face.boundaries();
    /// face.invert();
    ///
    /// // Two faces are the same face.
    /// face.is_same(&org_face);
    ///
    /// // The boundaries is inverted.
    /// let inversed_edge_iter = org_bdry[0].inverse().edge_into_iter();
    /// let face_edge_iter = &mut face.boundary_iters()[0];
    /// for (edge0, edge1) in inversed_edge_iter.zip(face_edge_iter) {
    ///     assert_eq!(edge0, edge1);
    /// }
    /// ```
    #[inline(always)]
    pub fn invert(&mut self) -> &mut Self {
        self.orientation = !self.orientation;
        self
    }

    /// Returns whether two faces are the same. Returns `true` even if the orientaions are different.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 3]);
    /// let wire = Wire::from(vec![
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[2], &v[0], ()),
    /// ]);
    /// let face0 = Face::new(vec![wire], ());
    /// let face1 = face0.inverse();
    /// assert_ne!(face0, face1);
    /// assert!(face0.is_same(&face1));
    /// ```
    #[inline(always)]
    pub fn is_same(&self, other: &Self) -> bool {
        std::ptr::eq(Arc::as_ptr(&self.surface), Arc::as_ptr(&other.surface))
    }

    /// Returns the id that does not depend on the direction of the face.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 3]);
    /// let wire = Wire::from(vec![
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[2], &v[0], ()),
    /// ]);
    /// let face0 = Face::new(vec![wire.clone()], ());
    /// let face1 = face0.inverse();
    /// let face2 = Face::new(vec![wire], ());
    /// assert_ne!(face0, face1);
    /// assert_ne!(face0, face2);
    /// assert_eq!(face0.id(), face1.id());
    /// assert_ne!(face0.id(), face2.id());
    /// ```
    #[inline(always)]
    pub fn id(&self) -> FaceID<S> { ID::new(Arc::as_ptr(&self.surface)) }

    /// Returns how many same faces.
    ///
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 3]);
    /// let wire = Wire::from(vec![
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[2], &v[0], ()),
    /// ]);
    ///
    /// // Create one face
    /// let face0 = Face::new(vec![wire.clone()], ());
    /// assert_eq!(face0.count(), 1);
    /// // Create another face, independent from face0
    /// let face1 = Face::new(vec![wire.clone()], ());
    /// assert_eq!(face0.count(), 1);
    /// // Clone face0, the result will be 2.
    /// let face2 = face0.clone();
    /// assert_eq!(face0.count(), 2);
    /// assert_eq!(face2.count(), 2);
    /// // drop face2, the result will be 1.
    /// drop(face2);
    /// assert_eq!(face0.count(), 1);
    /// ```
    #[inline(always)]
    pub fn count(&self) -> usize { Arc::strong_count(&self.surface) }

    /// Returns the inverse face.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use truck_topology::errors::Error;
    /// let v = Vertex::news(&[(), (), ()]);
    /// let wire = Wire::from(vec![
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[2], &v[0], ()),
    /// ]);
    /// let mut face = Face::new(vec![wire], ());
    /// let inverted = face.inverse();
    ///
    /// // Two faces are the same face.
    /// assert!(face.is_same(&inverted));
    ///
    /// // Two faces has the same id.
    /// assert_eq!(face.id(), inverted.id());
    ///
    /// // The boundaries is inverted.
    /// let mut inversed_edge_iter = face.boundaries()[0].inverse().edge_into_iter();
    /// let face_edge_iter = &mut inverted.boundary_iters()[0];
    /// for (edge0, edge1) in inversed_edge_iter.zip(face_edge_iter) {
    ///     assert_eq!(edge0, edge1);
    /// }
    /// ```
    #[inline(always)]
    pub fn inverse(&self) -> Face<P, C, S> {
        let mut face = self.clone();
        face.invert();
        face
    }

    /// Returns whether two faces `self` and `other` have a shared edge.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 4]);
    /// let shared_edge = Edge::new(&v[0], &v[1], ());
    /// let another_edge = Edge::new(&v[0], &v[1], ());
    /// let inversed_edge = shared_edge.inverse();
    /// let wire = vec![
    ///     Wire::from_iter(vec![&Edge::new(&v[2], &v[0], ()), &shared_edge, &Edge::new(&v[1], &v[2], ())]),
    ///     Wire::from_iter(vec![&Edge::new(&v[2], &v[0], ()), &another_edge, &Edge::new(&v[1], &v[2], ())]),
    ///     Wire::from_iter(vec![&Edge::new(&v[3], &v[0], ()), &shared_edge, &Edge::new(&v[1], &v[3], ())]),
    ///     Wire::from_iter(vec![&Edge::new(&v[3], &v[1], ()), &inversed_edge, &Edge::new(&v[0], &v[3], ())]),
    /// ];
    /// let face: Vec<_> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
    /// assert!(face[0].border_on(&face[2]));
    /// assert!(!face[1].border_on(&face[2]));
    /// assert!(face[0].border_on(&face[3]));
    /// ```
    pub fn border_on(&self, other: &Face<P, C, S>) -> bool {
        let mut hashmap = HashMap::default();
        let edge_iter = self.boundary_iters().into_iter().flatten();
        edge_iter.for_each(|edge| {
            hashmap.insert(edge.id(), edge);
        });
        let mut edge_iter = other.boundary_iters().into_iter().flatten();
        edge_iter.any(|edge| hashmap.insert(edge.id(), edge).is_some())
    }

    /// Cuts a face with only one boundary by an edge.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(), (), (), ()]);
    /// let wire = Wire::from(vec![
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[2], &v[3], ()),
    ///     Edge::new(&v[3], &v[0], ()),
    /// ]);
    /// let face = Face::new(vec![wire], ());
    /// let (face0, face1) = face.cut_by_edge(Edge::new(&v[1], &v[3], ())).unwrap();
    ///
    /// // The front vertex of face0's boundary becomes the back of cutting edge.
    /// let v0: Vec<Vertex<()>> = face0.boundaries()[0].vertex_iter().collect();
    /// assert_eq!(v0, vec![v[3].clone(), v[0].clone(), v[1].clone()]);
    ///
    /// let v1: Vec<Vertex<()>> = face1.boundaries()[0].vertex_iter().collect();
    /// assert_eq!(v1, vec![v[1].clone(), v[2].clone(), v[3].clone()]);
    /// ```
    /// # Failures
    /// Returns `None` if:
    /// - `self` has several boundaries, or
    /// - `self` does not include vertices of the end vertices of `edge`.
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 6]);
    /// let wire0 = Wire::from(vec![
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[2], &v[0], ()),
    /// ]);
    /// let wire1 = Wire::from(vec![
    ///     Edge::new(&v[3], &v[4], ()),
    ///     Edge::new(&v[4], &v[5], ()),
    ///     Edge::new(&v[5], &v[3], ()),
    /// ]);
    /// let face = Face::new(vec![wire0, wire1], ());
    /// assert!(face.cut_by_edge(Edge::new(&v[1], &v[2], ())).is_none());
    /// ```
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(), (), (), (), ()]);
    /// let wire = Wire::from(vec![
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[2], &v[3], ()),
    ///     Edge::new(&v[3], &v[0], ()),
    /// ]);
    /// let face = Face::new(vec![wire], ());
    /// assert!(face.cut_by_edge(Edge::new(&v[1], &v[4], ())).is_none());
    pub fn cut_by_edge(&self, edge: Edge<P, C>) -> Option<(Self, Self)>
    where S: Clone {
        if self.boundaries.len() != 1 {
            return None;
        }
        let mut face0 = Face {
            boundaries: self.boundaries.clone(),
            orientation: self.orientation,
            surface: Arc::new(Mutex::new(self.get_surface())),
        };
        let wire = &mut face0.boundaries[0];
        let i = wire
            .edge_iter()
            .enumerate()
            .find(|(_, e)| e.front() == edge.back())
            .map(|(i, _)| i)?;
        let j = wire
            .edge_iter()
            .enumerate()
            .find(|(_, e)| e.back() == edge.front())
            .map(|(i, _)| i)?;
        wire.rotate_left(i);
        let j = (j + wire.len() - i) % wire.len();
        let mut new_wire = wire.split_off(j + 1);
        wire.push_back(edge.clone());
        new_wire.push_back(edge.inverse());
        debug_assert!(Face::try_new(self.boundaries.clone(), ()).is_ok());
        debug_assert!(Face::try_new(vec![new_wire.clone()], ()).is_ok());
        let face1 = Face {
            boundaries: vec![new_wire],
            orientation: self.orientation,
            surface: Arc::new(Mutex::new(self.get_surface())),
        };
        Some((face0, face1))
    }

    /// Glue two faces at boundaries.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 8]);
    /// let edge = vec![
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[2], &v[0], ()),
    ///     Edge::new(&v[3], &v[4], ()),
    ///     Edge::new(&v[4], &v[5], ()),
    ///     Edge::new(&v[5], &v[3], ()),
    ///     Edge::new(&v[6], &v[2], ()),
    ///     Edge::new(&v[1], &v[6], ()),
    ///     Edge::new(&v[7], &v[5], ()),
    ///     Edge::new(&v[4], &v[7], ()),
    /// ];
    /// let wire0 = Wire::from(vec![
    ///     edge[0].clone(),
    ///     edge[1].clone(),
    ///     edge[2].clone(),
    /// ]);
    /// let wire1 = Wire::from(vec![
    ///     edge[3].clone(),
    ///     edge[4].clone(),
    ///     edge[5].clone(),
    /// ]);
    /// let wire2 = Wire::from(vec![
    ///     edge[6].clone(),
    ///     edge[1].inverse(),
    ///     edge[7].clone(),
    /// ]);
    /// let wire3 = Wire::from(vec![
    ///     edge[8].clone(),
    ///     edge[4].inverse(),
    ///     edge[9].clone(),
    /// ]);
    /// let face0 = Face::new(vec![wire0, wire1], ());
    /// let face1 = Face::new(vec![wire2, wire3], ());
    /// let face = face0.glue_at_boundaries(&face1).unwrap();
    /// let boundaries = face.boundary_iters();
    /// assert_eq!(boundaries.len(), 2);
    /// assert_eq!(boundaries[0].len(), 4);
    /// assert_eq!(boundaries[1].len(), 4);
    /// ```
    pub fn glue_at_boundaries(&self, other: &Self) -> Option<Self>
    where
        S: Clone + PartialEq,
        Wire<P, C>: Debug, {
        let surface = self.get_surface();
        if surface != other.get_surface() || self.orientation() != other.orientation() {
            return None;
        }
        let mut vemap: HashMap<VertexID<P>, &Edge<P, C>> = self
            .absolute_boundaries()
            .iter()
            .flatten()
            .map(|edge| (edge.front().id(), edge))
            .collect();
        other
            .absolute_boundaries()
            .iter()
            .flatten()
            .try_for_each(|edge| {
                if let Some(edge0) = vemap.get(&edge.back().id()) {
                    if edge.front() == edge0.back() {
                        if edge.is_same(edge0) {
                            vemap.remove(&edge.back().id());
                            return Some(());
                        } else {
                            return None;
                        }
                    }
                }
                vemap.insert(edge.front().id(), edge);
                Some(())
            })?;
        if vemap.is_empty() {
            return None;
        }
        let mut boundaries = Vec::new();
        while !vemap.is_empty() {
            let mut wire = Wire::new();
            let v = *vemap.iter().next().unwrap().0;
            let mut edge = vemap.remove(&v).unwrap();
            wire.push_back(edge.clone());
            while let Some(edge0) = vemap.remove(&edge.back().id()) {
                wire.push_back(edge0.clone());
                edge = edge0;
            }
            boundaries.push(wire);
        }
        debug_assert!(Face::try_new(boundaries.clone(), ()).is_ok());
        Some(Face {
            boundaries,
            orientation: self.orientation(),
            surface: Arc::new(Mutex::new(surface)),
        })
    }
src/shell.rs (line 86)
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
    pub fn vertex_iter(&self) -> impl Iterator<Item = Vertex<P>> + '_ {
        self.edge_iter().map(|edge| edge.front().clone())
    }

    /// Returns a parallel iterator over the vertices.
    #[inline(always)]
    pub fn vertex_par_iter(&self) -> impl ParallelIterator<Item = Vertex<P>> + '_
    where
        P: Send,
        C: Send,
        S: Send, {
        self.edge_par_iter().map(|edge| edge.front().clone())
    }

    /// Moves all the faces of `other` into `self`, leaving `other` empty.
    #[inline(always)]
    pub fn append(&mut self, other: &mut Shell<P, C, S>) {
        self.face_list.append(&mut other.face_list);
    }

    /// Determines the shell conditions: non-regular, regular, oriented, or closed.  
    /// The complexity increases in proportion to the number of edges.
    ///
    /// Examples for each condition can be found on the page of
    /// [`ShellCondition`](./shell/enum.ShellCondition.html).
    pub fn shell_condition(&self) -> ShellCondition {
        self.edge_iter().collect::<Boundaries<C>>().condition()
    }

    /// Returns a vector of all boundaries as wires.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use truck_topology::shell::ShellCondition;
    /// let v = Vertex::news(&[(); 6]);
    /// let edge = [
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[0], &v[2], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[1], &v[3], ()),
    ///     Edge::new(&v[1], &v[4], ()),
    ///     Edge::new(&v[2], &v[4], ()),
    ///     Edge::new(&v[2], &v[5], ()),
    ///     Edge::new(&v[3], &v[4], ()),
    ///     Edge::new(&v[4], &v[5], ()),
    /// ];
    /// let wire = vec![
    ///     Wire::from_iter(vec![&edge[0], &edge[2], &edge[1].inverse()]),
    ///     Wire::from_iter(vec![&edge[3], &edge[7], &edge[4].inverse()]),
    ///     Wire::from_iter(vec![&edge[5], &edge[8], &edge[6].inverse()]),
    ///     Wire::from_iter(vec![&edge[2].inverse(), &edge[4], &edge[5].inverse()]),
    /// ];
    /// let shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
    /// let boundary = shell.extract_boundaries()[0].clone();
    /// assert_eq!(
    ///     boundary,
    ///     Wire::from_iter(vec![&edge[0], &edge[3], &edge[7], &edge[8], &edge[6].inverse(), &edge[1].inverse()]),
    /// );
    /// ```
    /// # Remarks
    /// This method is optimized when the shell is oriented.
    /// Even if the shell is not oriented, all the edges of the boundary are extracted.
    /// However, the connected components of the boundary are split into several wires.
    pub fn extract_boundaries(&self) -> Vec<Wire<P, C>> {
        let boundaries: Boundaries<C> = self.edge_iter().collect();
        let mut vemap: HashMap<_, _> = self
            .edge_iter()
            .filter_map(|edge| {
                boundaries
                    .boundaries
                    .get(&edge.id())
                    .map(|_| (edge.front().id(), edge.clone()))
            })
            .collect();
        let mut res = Vec::new();
        while let Some(edge) = vemap.values().next() {
            if let Some(mut cursor) = vemap.remove(&edge.front().id()) {
                let mut wire = Wire::from(vec![cursor.clone()]);
                loop {
                    cursor = match vemap.remove(&cursor.back().id()) {
                        None => break,
                        Some(got) => {
                            wire.push_back(got.clone());
                            got.clone()
                        }
                    };
                }
                res.push(wire);
            }
        }
        res
    }

    /// Returns the adjacency matrix of vertices in the shell.
    ///
    /// For the returned hashmap `map` and each vertex `v`,
    /// the vector `map[&v]` cosists all vertices which is adjacent to `v`.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use std::collections::HashSet;
    /// let v = Vertex::news(&[(); 4]);
    /// let edge = [
    ///     Edge::new(&v[0], &v[2], ()),
    ///     Edge::new(&v[0], &v[3], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[1], &v[3], ()),
    ///     Edge::new(&v[2], &v[3], ()),
    /// ];
    /// let wire = vec![
    ///     Wire::from_iter(vec![&edge[0], &edge[4], &edge[1].inverse()]),
    ///     Wire::from_iter(vec![&edge[2], &edge[4], &edge[3].inverse()]),
    /// ];
    /// let shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
    /// let adjacency = shell.vertex_adjacency();
    /// let v0_ads_vec = adjacency.get(&v[0].id()).unwrap();
    /// let v0_ads: HashSet<&VertexID<()>> = HashSet::from_iter(v0_ads_vec);
    /// assert_eq!(v0_ads, HashSet::from_iter(vec![&v[2].id(), &v[3].id()]));
    /// ```
    pub fn vertex_adjacency(&self) -> HashMap<VertexID<P>, Vec<VertexID<P>>> {
        let mut adjacency = EntryMap::new(|x| x, |_| Vec::new());
        let mut done_edge: HashSet<EdgeID<C>> = HashSet::default();
        self.edge_iter().for_each(|edge| {
            if done_edge.insert(edge.id()) {
                let v0 = edge.front().id();
                let v1 = edge.back().id();
                adjacency.entry_or_insert(v0).push(v1);
                adjacency.entry_or_insert(v1).push(v0);
            }
        });
        adjacency.into()
    }
src/solid.rs (line 76)
75
76
77
    pub fn vertex_iter(&self) -> impl Iterator<Item = Vertex<P>> + '_ {
        self.edge_iter().map(|edge| edge.front().clone())
    }
src/compress.rs (line 260)
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
fn emap_subroutin<P, Q, C, D>(
    edge0: &Edge<P, C>,
    edge1: &Edge<Q, D>,
    vmap: &mut HashMap<VertexID<P>, VertexID<Q>>,
    emap: &mut HashMap<EdgeID<C>, EdgeID<D>>,
) -> bool {
    match emap.get(&edge0.id()) {
        Some(got) => *got == edge1.id(),
        None => {
            emap.insert(edge0.id(), edge1.id());
            vmap_subroutin(edge0.front(), edge1.front(), vmap)
                && vmap_subroutin(edge0.back(), edge1.back(), vmap)
        }
    }
}
src/edge.rs (line 473)
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
    pub fn concat(&self, rhs: &Self) -> std::result::Result<Self, ConcatError<P>>
    where
        P: Debug,
        C: Concat<C, Point = P, Output = C> + Invertible + ParameterTransform, {
        if self.back() != rhs.front() {
            return Err(ConcatError::DisconnectedVertex(
                self.back().clone(),
                rhs.front().clone(),
            ));
        }
        if self.front() == rhs.back() {
            return Err(ConcatError::SameVertex(self.front().clone()));
        }
        let curve0 = self.oriented_curve();
        let mut curve1 = rhs.oriented_curve();
        let t0 = curve0.parameter_range().1;
        let t1 = curve1.parameter_range().0;
        curve1.parameter_transform(1.0, t0 - t1);
        let curve = curve0.try_concat(&curve1)?;
        Ok(Edge::debug_new(self.front(), rhs.back(), curve))
    }

    /// Create display struct for debugging the edge.
    ///
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use EdgeDisplayFormat as EDF;
    ///
    /// let vertex_format = VertexDisplayFormat::AsPoint;
    /// let edge = Edge::new(&Vertex::new(0), &Vertex::new(1), 2);
    ///
    /// assert_eq!(
    ///     format!("{:?}", edge.display(EDF::Full { vertex_format })),
    ///     format!("Edge {{ id: {:?}, vertices: (0, 1), entity: 2 }}", edge.id()),
    /// );
    /// assert_eq!(
    ///     format!("{:?}", edge.display(EDF::VerticesTupleAndID { vertex_format })),
    ///     format!("Edge {{ id: {:?}, vertices: (0, 1) }}", edge.id()),
    /// );
    /// assert_eq!(
    ///     &format!("{:?}", edge.display(EDF::VerticesTupleAndCurve { vertex_format })),
    ///     "Edge { vertices: (0, 1), entity: 2 }",
    /// );
    /// assert_eq!(
    ///     &format!("{:?}", edge.display(EDF::VerticesTupleStruct { vertex_format })),
    ///     "Edge(0, 1)",
    /// );
    /// assert_eq!(
    ///     &format!("{:?}", edge.display(EDF::VerticesTuple { vertex_format })),
    ///     "(0, 1)",
    /// );
    /// assert_eq!(
    ///     &format!("{:?}", edge.display(EDF::AsCurve)),
    ///     "2",
    /// );
    /// ```
    #[inline(always)]
    pub fn display(&self, format: EdgeDisplayFormat) -> DebugDisplay<'_, Self, EdgeDisplayFormat> {
        DebugDisplay {
            entity: self,
            format,
        }
    }
}

/// Error for concat
#[derive(Clone, Debug, Error)]
pub enum ConcatError<P: Debug> {
    /// Failed to concat edges since the end point of the first curve is different from the start point of the second curve.
    #[error("The end point {0:?} of the first curve is different from the start point {1:?} of the second curve.")]
    DisconnectedVertex(Vertex<P>, Vertex<P>),
    #[error("The end vertices are the same vertex {0:?}.")]
    SameVertex(Vertex<P>),
    /// From geometric error.
    #[error("{0}")]
    FromGeometry(truck_geotrait::ConcatError<P>),
}

impl<P: Debug> From<truck_geotrait::ConcatError<P>> for ConcatError<P> {
    fn from(err: truck_geotrait::ConcatError<P>) -> ConcatError<P> {
        ConcatError::FromGeometry(err)
    }
}

impl<P, C> Clone for Edge<P, C> {
    #[inline(always)]
    fn clone(&self) -> Edge<P, C> {
        Edge {
            vertices: self.vertices.clone(),
            orientation: self.orientation,
            curve: Arc::clone(&self.curve),
        }
    }
}

impl<P, C> PartialEq for Edge<P, C> {
    #[inline(always)]
    fn eq(&self, other: &Self) -> bool {
        std::ptr::eq(Arc::as_ptr(&self.curve), Arc::as_ptr(&other.curve))
            && self.orientation == other.orientation
    }
}

impl<P, C> Eq for Edge<P, C> {}

impl<P, C> Hash for Edge<P, C> {
    #[inline(always)]
    fn hash<H: Hasher>(&self, state: &mut H) {
        std::ptr::hash(Arc::as_ptr(&self.curve), state);
        self.orientation.hash(state);
    }
}

impl<'a, P: Debug, C: Debug> Debug for DebugDisplay<'a, Edge<P, C>, EdgeDisplayFormat> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self.format {
            EdgeDisplayFormat::Full { vertex_format } => f
                .debug_struct("Edge")
                .field("id", &Arc::as_ptr(&self.entity.curve))
                .field(
                    "vertices",
                    &(
                        self.entity.front().display(vertex_format),
                        self.entity.back().display(vertex_format),
                    ),
                )
                .field("entity", &MutexFmt(&self.entity.curve))
                .finish(),
            EdgeDisplayFormat::VerticesTupleAndID { vertex_format } => f
                .debug_struct("Edge")
                .field("id", &self.entity.id())
                .field(
                    "vertices",
                    &(
                        self.entity.front().display(vertex_format),
                        self.entity.back().display(vertex_format),
                    ),
                )
                .finish(),
            EdgeDisplayFormat::VerticesTupleAndCurve { vertex_format } => f
                .debug_struct("Edge")
                .field(
                    "vertices",
                    &(
                        self.entity.front().display(vertex_format),
                        self.entity.back().display(vertex_format),
                    ),
                )
                .field("entity", &MutexFmt(&self.entity.curve))
                .finish(),
            EdgeDisplayFormat::VerticesTupleStruct { vertex_format } => f
                .debug_tuple("Edge")
                .field(&self.entity.front().display(vertex_format))
                .field(&self.entity.back().display(vertex_format))
                .finish(),
            EdgeDisplayFormat::VerticesTuple { vertex_format } => f.write_fmt(format_args!(
                "({:?}, {:?})",
                self.entity.front().display(vertex_format),
                self.entity.back().display(vertex_format),
            )),
            EdgeDisplayFormat::AsCurve => {
                f.write_fmt(format_args!("{:?}", &MutexFmt(&self.entity.curve)))
            }
        }
    }

Returns the back vertex

let v = Vertex::news(&[(), ()]);
let edge = Edge::new(&v[0], &v[1], ());
assert_eq!(edge.back(), &v[1]);
Examples found in repository?
src/wire.rs (line 102)
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
    pub fn back_vertex(&self) -> Option<&Vertex<P>> { self.back().map(|edge| edge.back()) }

    /// Returns vertices at both ends.
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 3]);
    /// let mut wire = Wire::new();
    /// assert_eq!(wire.back_vertex(), None);
    /// wire.push_back(Edge::new(&v[1], &v[2], ()));
    /// wire.push_front(Edge::new(&v[0], &v[1], ()));
    /// assert_eq!(wire.ends_vertices(), Some((&v[0], &v[2])));
    /// ```
    #[inline(always)]
    pub fn ends_vertices(&self) -> Option<(&Vertex<P>, &Vertex<P>)> {
        match (self.front_vertex(), self.back_vertex()) {
            (Some(got0), Some(got1)) => Some((got0, got1)),
            _ => None,
        }
    }

    /// Moves all the faces of `other` into `self`, leaving `other` empty.
    #[inline(always)]
    pub fn append(&mut self, other: &mut Wire<P, C>) { self.edge_list.append(&mut other.edge_list) }

    /// Splits the `Wire` into two at the given index.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 7]);
    /// let mut wire = Wire::new();
    /// for i in 0..6 {
    ///    wire.push_back(Edge::new(&v[i], &v[i + 1], ()));
    /// }
    /// let original_wire = wire.clone();
    /// let mut wire1 = wire.split_off(4);
    /// assert_eq!(wire.len(), 4);
    /// assert_eq!(wire1.len(), 2);
    /// wire.append(&mut wire1);
    /// assert_eq!(original_wire, wire);
    /// ```
    /// # Panics
    /// Panics if `at > self.len()`
    #[inline(always)]
    pub fn split_off(&mut self, at: usize) -> Wire<P, C> {
        Wire {
            edge_list: self.edge_list.split_off(at),
        }
    }

    /// Inverts the wire.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 4]);
    /// let mut wire = Wire::from(vec![
    ///     Edge::new(&v[3], &v[2], ()),
    ///     Edge::new(&v[2], &v[1], ()),
    ///     Edge::new(&v[1], &v[0], ()),
    /// ]);
    /// wire.invert();
    /// for (i, vert) in wire.vertex_iter().enumerate() {
    ///     assert_eq!(v[i], vert);
    /// }
    /// ```
    #[inline(always)]
    pub fn invert(&mut self) -> &mut Self {
        *self = self.inverse();
        self
    }

    /// Returns the inverse wire.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 4]);
    /// let mut wire = Wire::from(vec![
    ///     Edge::new(&v[3], &v[2], ()),
    ///     Edge::new(&v[2], &v[1], ()),
    ///     Edge::new(&v[1], &v[0], ()),
    /// ]);
    /// let inverse = wire.inverse();
    /// wire.invert();
    /// for (edge0, edge1) in wire.edge_iter().zip(inverse.edge_iter()) {
    ///     assert_eq!(edge0, edge1);
    /// }
    /// ```
    #[inline(always)]
    pub fn inverse(&self) -> Wire<P, C> {
        let edge_list = self.edge_iter().rev().map(|edge| edge.inverse()).collect();
        Wire { edge_list }
    }

    /// Returns whether all the adjacent pairs of edges have shared vertices or not.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 4]);
    /// let mut wire = Wire::from(vec![
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[2], &v[3], ()),
    /// ]);
    /// assert!(!wire.is_continuous());
    /// wire.insert(1, Edge::new(&v[1], &v[2], ()));
    /// assert!(wire.is_continuous());
    /// ```
    /// ```
    /// use truck_topology::*;
    /// // The empty wire is continuous
    /// assert!(Wire::<(), ()>::new().is_continuous());
    /// ```
    pub fn is_continuous(&self) -> bool {
        let mut iter = self.edge_iter();
        if let Some(edge) = iter.next() {
            let mut prev = edge.back();
            for edge in iter {
                if prev != edge.front() {
                    return false;
                }
                prev = edge.back();
            }
        }
        true
    }

    /// Returns whether the front vertex of the wire is the same as the back one or not.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 4]);
    /// let mut wire = Wire::from(vec![
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[2], &v[3], ()),
    /// ]);
    /// assert!(!wire.is_cyclic());
    /// wire.push_back(Edge::new(&v[3], &v[0], ()));
    /// assert!(wire.is_cyclic());
    /// ```
    /// ```
    /// use truck_topology::*;
    /// // The empty wire is cyclic.
    /// assert!(Wire::<(), ()>::new().is_cyclic());
    /// ```
    #[inline(always)]
    pub fn is_cyclic(&self) -> bool { self.front_vertex() == self.back_vertex() }

    /// Returns whether the wire is closed or not.
    /// Here, "closed" means "continuous" and "cyclic".
    #[inline(always)]
    pub fn is_closed(&self) -> bool { self.is_continuous() && self.is_cyclic() }

    /// Returns whether simple or not.
    /// Here, "simple" means all the vertices in the wire are shared from only two edges at most.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 4]);
    /// let edge0 = Edge::new(&v[0], &v[1], ());
    /// let edge1 = Edge::new(&v[1], &v[2], ());
    /// let edge2 = Edge::new(&v[2], &v[3], ());
    /// let edge3 = Edge::new(&v[3], &v[1], ());
    /// let edge4 = Edge::new(&v[3], &v[0], ());
    ///
    /// let wire0 = Wire::from_iter(vec![&edge0, &edge1, &edge2, &edge3]);
    /// let wire1 = Wire::from(vec![edge0, edge1, edge2, edge4]);
    ///
    /// assert!(!wire0.is_simple());
    /// assert!(wire1.is_simple());
    /// ```
    /// ```
    /// use truck_topology::*;
    /// // The empty wire is simple.
    /// assert!(Wire::<(), ()>::new().is_simple());
    /// ```
    pub fn is_simple(&self) -> bool {
        let mut set = HashSet::default();
        self.vertex_iter()
            .all(move |vertex| set.insert(vertex.id()))
    }

    /// Determines whether all the wires in `wires` has no same vertices.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    ///
    /// let v = Vertex::news(&[(), (), (), (), ()]);
    /// let edge0 = Edge::new(&v[0], &v[1], ());
    /// let edge1 = Edge::new(&v[1], &v[2], ());
    /// let edge2 = Edge::new(&v[2], &v[3], ());
    /// let edge3 = Edge::new(&v[3], &v[4], ());
    ///
    /// let wire0 = Wire::from(vec![edge0, edge1]);
    /// let wire1 = Wire::from(vec![edge2]);
    /// let wire2 = Wire::from(vec![edge3]);
    ///
    /// assert!(Wire::disjoint_wires(&[wire0.clone(), wire2]));
    /// assert!(!Wire::disjoint_wires(&[wire0, wire1]));
    /// ```
    pub fn disjoint_wires(wires: &[Wire<P, C>]) -> bool {
        let mut set = HashSet::default();
        wires.iter().all(move |wire| {
            let mut vec = Vec::new();
            let res = wire.vertex_iter().all(|v| {
                vec.push(v.id());
                !set.contains(&v.id())
            });
            set.extend(vec);
            res
        })
    }

    /// Swap one edge into two edges.
    ///
    /// # Arguments
    /// - `idx`: Index of edge in wire
    /// - `edges`: Inserted edges
    ///
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(), (), (), (), ()]);
    /// let edge0 = Edge::new(&v[0], &v[1], 0);
    /// let edge1 = Edge::new(&v[1], &v[3], 1);
    /// let edge2 = Edge::new(&v[3], &v[4], 2);
    /// let edge3 = Edge::new(&v[1], &v[2], 3);
    /// let edge4 = Edge::new(&v[2], &v[3], 4);
    /// let mut wire0 = Wire::from(vec![
    ///     edge0.clone(), edge1, edge2.clone()
    /// ]);
    /// let wire1 = Wire::from(vec![
    ///     edge0, edge3.clone(), edge4.clone(), edge2
    /// ]);
    /// assert_ne!(wire0, wire1);
    /// wire0.swap_edge_into_wire(1, Wire::from(vec![edge3, edge4]));
    /// assert_eq!(wire0, wire1);
    /// ```
    ///
    /// # Panics
    /// Panic occars if `idx >= self.len()`.
    ///
    /// # Failure
    /// Returns `false` and `self` will not be changed if the end vertices of `self[idx]` and the ones of `wire` is not the same.
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(), (), (), (), ()]);
    /// let edge0 = Edge::new(&v[0], &v[1], 0);
    /// let edge1 = Edge::new(&v[1], &v[3], 1);
    /// let edge2 = Edge::new(&v[3], &v[4], 2);
    /// let edge3 = Edge::new(&v[1], &v[2], 3);
    /// let edge4 = Edge::new(&v[2], &v[1], 4);
    /// let mut wire0 = Wire::from(vec![
    ///     edge0.clone(), edge1, edge2.clone()
    /// ]);
    /// let backup = wire0.clone();
    /// // The end vertices of wire[1] == edge1 is (v[1], v[3]).
    /// // The end points of new wire [edge3, edge4] is (v[1], v[1]).
    /// // Since the back vertices are different, returns false and do nothing.
    /// assert!(!wire0.swap_edge_into_wire(1, Wire::from(vec![edge3, edge4])));
    /// assert_eq!(wire0, backup);
    /// ```
    pub fn swap_edge_into_wire(&mut self, idx: usize, wire: Wire<P, C>) -> bool {
        if wire.is_empty() || self[idx].ends() != wire.ends_vertices().unwrap() {
            return false;
        }
        let mut new_wire: Vec<_> = self.drain(0..idx).collect();
        new_wire.extend(wire);
        self.pop_front();
        new_wire.extend(self.drain(..));
        *self = new_wire.into();
        true
    }
    /// Concat edges
    pub(super) fn swap_subwire_into_edges(&mut self, mut idx: usize, edge: Edge<P, C>) {
        if idx + 1 == self.len() {
            self.rotate_left(1);
            idx -= 1;
        }
        let mut new_wire: Vec<_> = self.drain(0..idx).collect();
        new_wire.push(edge);
        self.pop_front();
        self.pop_front();
        new_wire.extend(self.drain(..));
        *self = new_wire.into();
    }

    pub(super) fn sub_try_mapped<'a, Q, D, KF, KV>(
        &'a self,
        edge_map: &mut EdgeEntryMapForTryMapping<'a, P, C, Q, D, KF, KV>,
    ) -> Option<Wire<Q, D>>
    where
        KF: FnMut(&'a Edge<P, C>) -> EdgeID<C>,
        KV: FnMut(&'a Edge<P, C>) -> Option<Edge<Q, D>>,
    {
        self.edge_iter()
            .map(|edge| Some(edge_map.entry_or_insert(edge).as_ref()?.absolute_clone()))
            .collect()
    }

    /// Returns a new wire whose curves are mapped by `curve_mapping` and
    /// whose points are mapped by `point_mapping`.
    /// # Remarks
    /// Accessing geometry elements directly in the closure will result in a deadlock.
    /// So, this method does not appear to the document.
    #[doc(hidden)]
    pub fn try_mapped<Q, D>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Option<Q>,
        mut curve_mapping: impl FnMut(&C) -> Option<D>,
    ) -> Option<Wire<Q, D>> {
        let mut vertex_map = EntryMap::new(Vertex::id, move |v| v.try_mapped(&mut point_mapping));
        let mut edge_map = EntryMap::new(
            Edge::id,
            edge_entry_map_try_closure(&mut vertex_map, &mut curve_mapping),
        );
        self.sub_try_mapped(&mut edge_map)
    }

    pub(super) fn sub_mapped<'a, Q, D, KF, KV>(
        &'a self,
        edge_map: &mut EdgeEntryMapForMapping<'a, P, C, Q, D, KF, KV>,
    ) -> Wire<Q, D>
    where
        KF: FnMut(&'a Edge<P, C>) -> EdgeID<C>,
        KV: FnMut(&'a Edge<P, C>) -> Edge<Q, D>,
    {
        self.edge_iter()
            .map(|edge| {
                let new_edge = edge_map.entry_or_insert(edge);
                match edge.orientation() {
                    true => new_edge.clone(),
                    false => new_edge.inverse(),
                }
            })
            .collect()
    }
    /// Returns a new wire whose curves are mapped by `curve_mapping` and
    /// whose points are mapped by `point_mapping`.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[0, 1, 2, 3, 4]);
    /// let wire0: Wire<usize, usize> = vec![
    ///     Edge::new(&v[0], &v[1], 100),
    ///     Edge::new(&v[2], &v[1], 110).inverse(),
    ///     Edge::new(&v[3], &v[4], 120),
    ///     Edge::new(&v[4], &v[0], 130),
    /// ].into();
    /// let wire1 = wire0.mapped(
    ///     &move |i: &usize| *i as f64 + 0.5,
    ///     &move |j: &usize| *j as f64 + 1000.5,
    /// );
    ///
    /// // Check the points
    /// for (v0, v1) in wire0.vertex_iter().zip(wire1.vertex_iter()) {
    ///     let i = v0.get_point();
    ///     let j = v1.get_point();
    ///     assert_eq!(i as f64 + 0.5, j);
    /// }
    ///
    /// // Check the curves and orientation
    /// for (edge0, edge1) in wire0.edge_iter().zip(wire1.edge_iter()) {
    ///     let i = edge0.get_curve();
    ///     let j = edge1.get_curve();
    ///     assert_eq!(i as f64 + 1000.5, j);
    ///     assert_eq!(edge0.orientation(), edge1.orientation());
    /// }
    ///
    /// // Check the connection
    /// assert_eq!(wire1[0].back(), wire1[1].front());
    /// assert_ne!(wire1[1].back(), wire1[2].front());
    /// assert_eq!(wire1[2].back(), wire1[3].front());
    /// assert_eq!(wire1[3].back(), wire1[0].front());
    /// ```
    /// # Remarks
    /// Accessing geometry elements directly in the closure will result in a deadlock.
    /// So, this method does not appear to the document.
    #[doc(hidden)]
    pub fn mapped<Q, D>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Q,
        mut curve_mapping: impl FnMut(&C) -> D,
    ) -> Wire<Q, D> {
        let mut vertex_map = EntryMap::new(Vertex::id, move |v| v.mapped(&mut point_mapping));
        let mut edge_map = EntryMap::new(
            Edge::id,
            edge_entry_map_closure(&mut vertex_map, &mut curve_mapping),
        );
        self.sub_mapped(&mut edge_map)
    }

    /// Returns the consistence of the geometry of end vertices
    /// and the geometry of edge.
    #[inline(always)]
    pub fn is_geometric_consistent(&self) -> bool
    where
        P: Tolerance,
        C: BoundedCurve<Point = P>, {
        self.iter().all(|edge| edge.is_geometric_consistent())
    }

    /// Creates display struct for debugging the wire.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use WireDisplayFormat as WDF;
    /// let v = Vertex::news(&[0, 1, 2, 3, 4]);
    /// let wire: Wire<usize, usize> = vec![
    ///     Edge::new(&v[0], &v[1], 100),
    ///     Edge::new(&v[2], &v[1], 110).inverse(),
    ///     Edge::new(&v[3], &v[4], 120),
    /// ].into();
    ///
    /// let vertex_format = VertexDisplayFormat::AsPoint;
    /// let edge_format = EdgeDisplayFormat::VerticesTuple { vertex_format };
    ///
    /// assert_eq!(
    ///     &format!("{:?}", wire.display(WDF::EdgesListTuple {edge_format})),
    ///     "Wire([(0, 1), (1, 2), (3, 4)])",
    /// );
    /// assert_eq!(
    ///     &format!("{:?}", wire.display(WDF::EdgesList {edge_format})),
    ///     "[(0, 1), (1, 2), (3, 4)]",
    /// );
    /// assert_eq!(
    ///     &format!("{:?}", wire.display(WDF::VerticesList {vertex_format})),
    ///     "[0, 1, 2, 3, 4]",
    /// );
    /// ```
    #[inline(always)]
    pub fn display(&self, format: WireDisplayFormat) -> DebugDisplay<'_, Self, WireDisplayFormat> {
        DebugDisplay {
            entity: self,
            format,
        }
    }
}

type EdgeEntryMapForTryMapping<'a, P, C, Q, D, KF, KV> =
    EntryMap<EdgeID<C>, Option<Edge<Q, D>>, KF, KV, &'a Edge<P, C>>;
type EdgeEntryMapForMapping<'a, P, C, Q, D, KF, KV> =
    EntryMap<EdgeID<C>, Edge<Q, D>, KF, KV, &'a Edge<P, C>>;

pub(super) fn edge_entry_map_try_closure<'a, P, C, Q, D, KF, VF>(
    vertex_map: &'a mut EntryMap<VertexID<P>, Option<Vertex<Q>>, KF, VF, &'a Vertex<P>>,
    curve_mapping: &'a mut impl FnMut(&C) -> Option<D>,
) -> impl FnMut(&'a Edge<P, C>) -> Option<Edge<Q, D>> + 'a
where
    KF: FnMut(&'a Vertex<P>) -> VertexID<P>,
    VF: FnMut(&'a Vertex<P>) -> Option<Vertex<Q>>,
{
    move |edge| {
        let vf = edge.absolute_front();
        let vertex0 = vertex_map.entry_or_insert(vf).clone()?;
        let vb = edge.absolute_back();
        let vertex1 = vertex_map.entry_or_insert(vb).clone()?;
        let curve = curve_mapping(&*edge.curve.lock().unwrap())?;
        Some(Edge::debug_new(&vertex0, &vertex1, curve))
    }
}

pub(super) fn edge_entry_map_closure<'a, P, C, Q, D, KF, VF>(
    vertex_map: &'a mut EntryMap<VertexID<P>, Vertex<Q>, KF, VF, &'a Vertex<P>>,
    curve_mapping: &'a mut impl FnMut(&C) -> D,
) -> impl FnMut(&'a Edge<P, C>) -> Edge<Q, D> + 'a
where
    KF: FnMut(&'a Vertex<P>) -> VertexID<P>,
    VF: FnMut(&'a Vertex<P>) -> Vertex<Q>,
{
    move |edge| {
        let vf = edge.absolute_front();
        let vertex0 = vertex_map.entry_or_insert(vf).clone();
        let vb = edge.absolute_back();
        let vertex1 = vertex_map.entry_or_insert(vb).clone();
        let curve = curve_mapping(&*edge.curve.lock().unwrap());
        Edge::debug_new(&vertex0, &vertex1, curve)
    }
}

impl<T, P, C> From<T> for Wire<P, C>
where T: Into<VecDeque<Edge<P, C>>>
{
    #[inline(always)]
    fn from(edge_list: T) -> Wire<P, C> {
        Wire {
            edge_list: edge_list.into(),
        }
    }
}

impl<P, C> FromIterator<Edge<P, C>> for Wire<P, C> {
    #[inline(always)]
    fn from_iter<I: IntoIterator<Item = Edge<P, C>>>(iter: I) -> Wire<P, C> {
        Wire::from(VecDeque::from_iter(iter))
    }
}

impl<'a, P, C> FromIterator<&'a Edge<P, C>> for Wire<P, C> {
    #[inline(always)]
    fn from_iter<I: IntoIterator<Item = &'a Edge<P, C>>>(iter: I) -> Wire<P, C> {
        Wire::from(VecDeque::from_iter(iter.into_iter().map(Edge::clone)))
    }
}

impl<P, C> IntoIterator for Wire<P, C> {
    type Item = Edge<P, C>;
    type IntoIter = EdgeIntoIter<P, C>;
    #[inline(always)]
    fn into_iter(self) -> Self::IntoIter { self.edge_list.into_iter() }
}

impl<'a, P, C> IntoIterator for &'a Wire<P, C> {
    type Item = &'a Edge<P, C>;
    type IntoIter = EdgeIter<'a, P, C>;
    #[inline(always)]
    fn into_iter(self) -> Self::IntoIter { self.edge_list.iter() }
}

/// The reference iterator over all edges in a wire.
pub type EdgeIter<'a, P, C> = vec_deque::Iter<'a, Edge<P, C>>;
/// The mutable reference iterator over all edges in a wire.
pub type EdgeIterMut<'a, P, C> = vec_deque::IterMut<'a, Edge<P, C>>;
/// The into iterator over all edges in a wire.
pub type EdgeIntoIter<P, C> = vec_deque::IntoIter<Edge<P, C>>;
/// The reference parallel iterator over all edges in a wire.
pub type EdgeParallelIter<'a, P, C> = <VecDeque<Edge<P, C>> as IntoParallelRefIterator<'a>>::Iter;
/// The mutable reference parallel iterator over all edges in a wire.
pub type EdgeParallelIterMut<'a, P, C> =
    <VecDeque<Edge<P, C>> as IntoParallelRefMutIterator<'a>>::Iter;
/// the parallel iterator over all edges in a wire.
pub type EdgeParallelIntoIter<P, C> = <VecDeque<Edge<P, C>> as IntoParallelIterator>::Iter;

/// The iterator over all the vertices included in a wire.
/// # Details
/// Fundamentally, the iterator runs over all the vertices in a wire.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 6]);
/// let wire = Wire::from(vec![
///     Edge::new(&v[0], &v[1], ()),
///     Edge::new(&v[2], &v[3], ()),
///     Edge::new(&v[4], &v[5], ()),
/// ]);
/// let mut viter = wire.vertex_iter();
/// assert_eq!(viter.next().as_ref(), Some(&v[0]));
/// assert_eq!(viter.next().as_ref(), Some(&v[1]));
/// assert_eq!(viter.next().as_ref(), Some(&v[2]));
/// assert_eq!(viter.next().as_ref(), Some(&v[3]));
/// assert_eq!(viter.next().as_ref(), Some(&v[4]));
/// assert_eq!(viter.next().as_ref(), Some(&v[5]));
/// assert_eq!(viter.next(), None);
/// assert_eq!(viter.next(), None); // VertexIter is a FusedIterator.
/// ```
/// If a pair of adjacent edges share one vertex, the iterator run only one time at the shared vertex.
/// ```
/// use truck_topology::*;
/// let v = Vertex::news(&[(); 6]);
/// let wire = Wire::from(vec![
///     Edge::new(&v[0], &v[1], ()),
///     Edge::new(&v[2], &v[3], ()),
///     Edge::new(&v[3], &v[4], ()),
///     Edge::new(&v[4], &v[5], ()),
/// ]);
/// let mut viter = wire.vertex_iter();
/// assert_eq!(viter.next().as_ref(), Some(&v[0]));
/// assert_eq!(viter.next().as_ref(), Some(&v[1]));
/// assert_eq!(viter.next().as_ref(), Some(&v[2]));
/// assert_eq!(viter.next().as_ref(), Some(&v[3]));
/// assert_eq!(viter.next().as_ref(), Some(&v[4]));
/// assert_eq!(viter.next().as_ref(), Some(&v[5]));
/// assert_eq!(viter.next(), None);
/// ```
/// If the wire is cyclic, the iterator does not arrive at the last vertex.
/// ```
/// # use truck_topology::*;
/// let v = Vertex::news(&[(); 5]);
/// let wire = Wire::from(vec![
///     Edge::new(&v[0], &v[1], ()),
///     Edge::new(&v[1], &v[2], ()),
///     Edge::new(&v[3], &v[4], ()),
///     Edge::new(&v[4], &v[0], ()),
/// ]);
/// let mut viter = wire.vertex_iter();
/// assert_eq!(viter.next().as_ref(), Some(&v[0]));
/// assert_eq!(viter.next().as_ref(), Some(&v[1]));
/// assert_eq!(viter.next().as_ref(), Some(&v[2]));
/// assert_eq!(viter.next().as_ref(), Some(&v[3]));
/// assert_eq!(viter.next().as_ref(), Some(&v[4]));
/// assert_eq!(viter.next(), None);
/// ```
#[derive(Clone, Debug)]
pub struct VertexIter<'a, P, C> {
    edge_iter: Peekable<EdgeIter<'a, P, C>>,
    unconti_next: Option<Vertex<P>>,
    cyclic: bool,
}

impl<'a, P, C> Iterator for VertexIter<'a, P, C> {
    type Item = Vertex<P>;

    fn next(&mut self) -> Option<Vertex<P>> {
        if self.unconti_next.is_some() {
            let res = self.unconti_next.clone();
            self.unconti_next = None;
            res
        } else if let Some(edge) = self.edge_iter.next() {
            if let Some(next) = self.edge_iter.peek() {
                if edge.back() != next.front() {
                    self.unconti_next = Some(edge.back().clone());
                }
            } else if !self.cyclic {
                self.unconti_next = Some(edge.back().clone());
            }
            Some(edge.front().clone())
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let min_size = self.edge_iter.len();
        let max_size = self.edge_iter.len() * 2;
        (min_size, Some(max_size))
    }

    fn last(self) -> Option<Vertex<P>> {
        let closed = self.cyclic;
        self.edge_iter.last().map(|edge| {
            if closed {
                edge.front().clone()
            } else {
                edge.back().clone()
            }
        })
    }
More examples
Hide additional examples
src/compress.rs (line 261)
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
fn emap_subroutin<P, Q, C, D>(
    edge0: &Edge<P, C>,
    edge1: &Edge<Q, D>,
    vmap: &mut HashMap<VertexID<P>, VertexID<Q>>,
    emap: &mut HashMap<EdgeID<C>, EdgeID<D>>,
) -> bool {
    match emap.get(&edge0.id()) {
        Some(got) => *got == edge1.id(),
        None => {
            emap.insert(edge0.id(), edge1.id());
            vmap_subroutin(edge0.front(), edge1.front(), vmap)
                && vmap_subroutin(edge0.back(), edge1.back(), vmap)
        }
    }
}
src/edge.rs (line 473)
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
    pub fn concat(&self, rhs: &Self) -> std::result::Result<Self, ConcatError<P>>
    where
        P: Debug,
        C: Concat<C, Point = P, Output = C> + Invertible + ParameterTransform, {
        if self.back() != rhs.front() {
            return Err(ConcatError::DisconnectedVertex(
                self.back().clone(),
                rhs.front().clone(),
            ));
        }
        if self.front() == rhs.back() {
            return Err(ConcatError::SameVertex(self.front().clone()));
        }
        let curve0 = self.oriented_curve();
        let mut curve1 = rhs.oriented_curve();
        let t0 = curve0.parameter_range().1;
        let t1 = curve1.parameter_range().0;
        curve1.parameter_transform(1.0, t0 - t1);
        let curve = curve0.try_concat(&curve1)?;
        Ok(Edge::debug_new(self.front(), rhs.back(), curve))
    }

    /// Create display struct for debugging the edge.
    ///
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use EdgeDisplayFormat as EDF;
    ///
    /// let vertex_format = VertexDisplayFormat::AsPoint;
    /// let edge = Edge::new(&Vertex::new(0), &Vertex::new(1), 2);
    ///
    /// assert_eq!(
    ///     format!("{:?}", edge.display(EDF::Full { vertex_format })),
    ///     format!("Edge {{ id: {:?}, vertices: (0, 1), entity: 2 }}", edge.id()),
    /// );
    /// assert_eq!(
    ///     format!("{:?}", edge.display(EDF::VerticesTupleAndID { vertex_format })),
    ///     format!("Edge {{ id: {:?}, vertices: (0, 1) }}", edge.id()),
    /// );
    /// assert_eq!(
    ///     &format!("{:?}", edge.display(EDF::VerticesTupleAndCurve { vertex_format })),
    ///     "Edge { vertices: (0, 1), entity: 2 }",
    /// );
    /// assert_eq!(
    ///     &format!("{:?}", edge.display(EDF::VerticesTupleStruct { vertex_format })),
    ///     "Edge(0, 1)",
    /// );
    /// assert_eq!(
    ///     &format!("{:?}", edge.display(EDF::VerticesTuple { vertex_format })),
    ///     "(0, 1)",
    /// );
    /// assert_eq!(
    ///     &format!("{:?}", edge.display(EDF::AsCurve)),
    ///     "2",
    /// );
    /// ```
    #[inline(always)]
    pub fn display(&self, format: EdgeDisplayFormat) -> DebugDisplay<'_, Self, EdgeDisplayFormat> {
        DebugDisplay {
            entity: self,
            format,
        }
    }
}

/// Error for concat
#[derive(Clone, Debug, Error)]
pub enum ConcatError<P: Debug> {
    /// Failed to concat edges since the end point of the first curve is different from the start point of the second curve.
    #[error("The end point {0:?} of the first curve is different from the start point {1:?} of the second curve.")]
    DisconnectedVertex(Vertex<P>, Vertex<P>),
    #[error("The end vertices are the same vertex {0:?}.")]
    SameVertex(Vertex<P>),
    /// From geometric error.
    #[error("{0}")]
    FromGeometry(truck_geotrait::ConcatError<P>),
}

impl<P: Debug> From<truck_geotrait::ConcatError<P>> for ConcatError<P> {
    fn from(err: truck_geotrait::ConcatError<P>) -> ConcatError<P> {
        ConcatError::FromGeometry(err)
    }
}

impl<P, C> Clone for Edge<P, C> {
    #[inline(always)]
    fn clone(&self) -> Edge<P, C> {
        Edge {
            vertices: self.vertices.clone(),
            orientation: self.orientation,
            curve: Arc::clone(&self.curve),
        }
    }
}

impl<P, C> PartialEq for Edge<P, C> {
    #[inline(always)]
    fn eq(&self, other: &Self) -> bool {
        std::ptr::eq(Arc::as_ptr(&self.curve), Arc::as_ptr(&other.curve))
            && self.orientation == other.orientation
    }
}

impl<P, C> Eq for Edge<P, C> {}

impl<P, C> Hash for Edge<P, C> {
    #[inline(always)]
    fn hash<H: Hasher>(&self, state: &mut H) {
        std::ptr::hash(Arc::as_ptr(&self.curve), state);
        self.orientation.hash(state);
    }
}

impl<'a, P: Debug, C: Debug> Debug for DebugDisplay<'a, Edge<P, C>, EdgeDisplayFormat> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self.format {
            EdgeDisplayFormat::Full { vertex_format } => f
                .debug_struct("Edge")
                .field("id", &Arc::as_ptr(&self.entity.curve))
                .field(
                    "vertices",
                    &(
                        self.entity.front().display(vertex_format),
                        self.entity.back().display(vertex_format),
                    ),
                )
                .field("entity", &MutexFmt(&self.entity.curve))
                .finish(),
            EdgeDisplayFormat::VerticesTupleAndID { vertex_format } => f
                .debug_struct("Edge")
                .field("id", &self.entity.id())
                .field(
                    "vertices",
                    &(
                        self.entity.front().display(vertex_format),
                        self.entity.back().display(vertex_format),
                    ),
                )
                .finish(),
            EdgeDisplayFormat::VerticesTupleAndCurve { vertex_format } => f
                .debug_struct("Edge")
                .field(
                    "vertices",
                    &(
                        self.entity.front().display(vertex_format),
                        self.entity.back().display(vertex_format),
                    ),
                )
                .field("entity", &MutexFmt(&self.entity.curve))
                .finish(),
            EdgeDisplayFormat::VerticesTupleStruct { vertex_format } => f
                .debug_tuple("Edge")
                .field(&self.entity.front().display(vertex_format))
                .field(&self.entity.back().display(vertex_format))
                .finish(),
            EdgeDisplayFormat::VerticesTuple { vertex_format } => f.write_fmt(format_args!(
                "({:?}, {:?})",
                self.entity.front().display(vertex_format),
                self.entity.back().display(vertex_format),
            )),
            EdgeDisplayFormat::AsCurve => {
                f.write_fmt(format_args!("{:?}", &MutexFmt(&self.entity.curve)))
            }
        }
    }
src/shell.rs (line 164)
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
    pub fn extract_boundaries(&self) -> Vec<Wire<P, C>> {
        let boundaries: Boundaries<C> = self.edge_iter().collect();
        let mut vemap: HashMap<_, _> = self
            .edge_iter()
            .filter_map(|edge| {
                boundaries
                    .boundaries
                    .get(&edge.id())
                    .map(|_| (edge.front().id(), edge.clone()))
            })
            .collect();
        let mut res = Vec::new();
        while let Some(edge) = vemap.values().next() {
            if let Some(mut cursor) = vemap.remove(&edge.front().id()) {
                let mut wire = Wire::from(vec![cursor.clone()]);
                loop {
                    cursor = match vemap.remove(&cursor.back().id()) {
                        None => break,
                        Some(got) => {
                            wire.push_back(got.clone());
                            got.clone()
                        }
                    };
                }
                res.push(wire);
            }
        }
        res
    }

    /// Returns the adjacency matrix of vertices in the shell.
    ///
    /// For the returned hashmap `map` and each vertex `v`,
    /// the vector `map[&v]` cosists all vertices which is adjacent to `v`.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use std::collections::HashSet;
    /// let v = Vertex::news(&[(); 4]);
    /// let edge = [
    ///     Edge::new(&v[0], &v[2], ()),
    ///     Edge::new(&v[0], &v[3], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[1], &v[3], ()),
    ///     Edge::new(&v[2], &v[3], ()),
    /// ];
    /// let wire = vec![
    ///     Wire::from_iter(vec![&edge[0], &edge[4], &edge[1].inverse()]),
    ///     Wire::from_iter(vec![&edge[2], &edge[4], &edge[3].inverse()]),
    /// ];
    /// let shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
    /// let adjacency = shell.vertex_adjacency();
    /// let v0_ads_vec = adjacency.get(&v[0].id()).unwrap();
    /// let v0_ads: HashSet<&VertexID<()>> = HashSet::from_iter(v0_ads_vec);
    /// assert_eq!(v0_ads, HashSet::from_iter(vec![&v[2].id(), &v[3].id()]));
    /// ```
    pub fn vertex_adjacency(&self) -> HashMap<VertexID<P>, Vec<VertexID<P>>> {
        let mut adjacency = EntryMap::new(|x| x, |_| Vec::new());
        let mut done_edge: HashSet<EdgeID<C>> = HashSet::default();
        self.edge_iter().for_each(|edge| {
            if done_edge.insert(edge.id()) {
                let v0 = edge.front().id();
                let v1 = edge.back().id();
                adjacency.entry_or_insert(v0).push(v1);
                adjacency.entry_or_insert(v1).push(v0);
            }
        });
        adjacency.into()
    }

    /// Returns the adjacency matrix of faces in the shell.
    ///
    /// For the returned hashmap `map` and each face `face`,
    /// the vector `map[&face]` consists all faces adjacent to `face`.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use truck_topology::shell::ShellCondition;
    /// let v = Vertex::news(&[(); 6]);
    /// let edge = [
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[0], &v[2], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[1], &v[3], ()),
    ///     Edge::new(&v[1], &v[4], ()),
    ///     Edge::new(&v[2], &v[4], ()),
    ///     Edge::new(&v[2], &v[5], ()),
    ///     Edge::new(&v[3], &v[4], ()),
    ///     Edge::new(&v[4], &v[5], ()),
    /// ];
    /// let wire = vec![
    ///     Wire::from_iter(vec![&edge[0], &edge[2], &edge[1].inverse()]),
    ///     Wire::from_iter(vec![&edge[3], &edge[7], &edge[4].inverse()]),
    ///     Wire::from_iter(vec![&edge[5], &edge[8], &edge[6].inverse()]),
    ///     Wire::from_iter(vec![&edge[2].inverse(), &edge[4], &edge[5].inverse()]),
    /// ];
    /// let shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
    /// let face_adjacency = shell.face_adjacency();
    /// assert_eq!(face_adjacency[&shell[0]].len(), 1);
    /// assert_eq!(face_adjacency[&shell[1]].len(), 1);
    /// assert_eq!(face_adjacency[&shell[2]].len(), 1);
    /// assert_eq!(face_adjacency[&shell[3]].len(), 3);
    /// ```
    pub fn face_adjacency(&self) -> FaceAdjacencyMap<'_, P, C, S> {
        let mut adjacency = EntryMap::new(|x| x, |_| Vec::new());
        let mut edge_face_map = EntryMap::new(|x| x, |_| Vec::new());
        self.face_iter().for_each(|face| {
            face.absolute_boundaries()
                .iter()
                .flatten()
                .for_each(|edge| {
                    let vec = edge_face_map.entry_or_insert(edge.id());
                    adjacency.entry_or_insert(face).extend(vec.iter().copied());
                    vec.iter().for_each(|tmp| {
                        adjacency.entry_or_insert(*tmp).push(face);
                    });
                    vec.push(face);
                });
        });
        adjacency.into()
    }

    /// Returns whether the shell is connected or not.
    /// # Examples
    /// ```
    /// // The empty shell is connected.
    /// use truck_topology::*;
    /// assert!(Shell::<(), (), ()>::new().is_connected());
    /// ```
    /// ```
    /// // An example of a connected shell
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 4]);
    /// let shared_edge = Edge::new(&v[1], &v[2], ());
    /// let wire0 = Wire::from_iter(vec![
    ///     &Edge::new(&v[0], &v[1], ()),
    ///     &shared_edge,
    ///     &Edge::new(&v[2], &v[0], ()),
    /// ]);
    /// let face0 = Face::new(vec![wire0], ());
    /// let wire1 = Wire::from_iter(vec![
    ///     &Edge::new(&v[3], &v[1], ()),
    ///     &shared_edge,
    ///     &Edge::new(&v[2], &v[3], ()),
    /// ]);
    /// let face1 = Face::new(vec![wire1], ());
    /// let shell: Shell<_, _, _> = vec![face0, face1].into();
    /// assert!(shell.is_connected());
    /// ```
    /// ```
    /// // An example of a non-connected shell
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 6]);
    /// let wire0 = Wire::from_iter(vec![
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[2], &v[0], ())
    /// ]);
    /// let face0 = Face::new(vec![wire0], ());
    /// let wire1 = Wire::from_iter(vec![
    ///     &Edge::new(&v[3], &v[4], ()),
    ///     &Edge::new(&v[4], &v[5], ()),
    ///     &Edge::new(&v[5], &v[3], ())
    /// ]);
    /// let face1 = Face::new(vec![wire1], ());
    /// let shell: Shell<_, _, _> = vec![face0, face1].into();
    /// assert!(!shell.is_connected());
    /// ```
    pub fn is_connected(&self) -> bool {
        let mut adjacency = self.vertex_adjacency();
        // Connecting another boundary of the same face with an edge
        for face in self {
            for wire in face.boundaries.windows(2) {
                let v0 = wire[0].front_vertex().unwrap();
                let v1 = wire[1].front_vertex().unwrap();
                adjacency.get_mut(&v0.id()).unwrap().push(v1.id());
                adjacency.get_mut(&v1.id()).unwrap().push(v0.id());
            }
        }
        check_connectivity(&mut adjacency)
    }

    /// Returns a vector consisting of shells of each connected components.
    /// # Examples
    /// ```
    /// use truck_topology::Shell;
    /// // The empty shell has no connected component.
    /// assert!(Shell::<(), (), ()>::new().connected_components().is_empty());
    /// ```
    /// # Remarks
    /// Since this method uses the face adjacency matrix, multiple components
    /// are perhaps generated even if the shell is connected. In that case,
    /// there is a pair of faces such that share vertices but not edges.
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 5]);
    /// let wire0 = Wire::from_iter(vec![
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[2], &v[0], ()),
    /// ]);
    /// let wire1 = Wire::from_iter(vec![
    ///     Edge::new(&v[0], &v[3], ()),
    ///     Edge::new(&v[3], &v[4], ()),
    ///     Edge::new(&v[4], &v[0], ()),
    /// ]);
    /// let shell = Shell::from(vec![
    ///     Face::new(vec![wire0], ()),
    ///     Face::new(vec![wire1], ()),
    /// ]);
    /// assert!(shell.is_connected());
    /// assert_eq!(shell.connected_components().len(), 2);
    /// ```
    pub fn connected_components(&self) -> Vec<Shell<P, C, S>> {
        let mut adjacency = self.face_adjacency();
        let components = create_components(&mut adjacency);
        components
            .into_iter()
            .map(|vec| vec.into_iter().cloned().collect())
            .collect()
    }

    /// Returns the vector of all singular vertices.
    ///
    /// Here, we say that a vertex is singular if, for a sufficiently small neighborhood U of
    /// the vertex, the set U - {the vertex} is not connected.
    ///
    /// A regular, oriented, or closed shell becomes a manifold if and only if the shell has
    /// no singular vertices.
    /// # Examples
    /// ```
    /// // A regular manifold: Mobius bundle
    /// use truck_topology::*;
    /// use truck_topology::shell::ShellCondition;
    ///
    /// let v = Vertex::news(&[(), (), (), ()]);
    /// let edge = [
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[2], &v[0], ()),
    ///     Edge::new(&v[1], &v[3], ()),
    ///     Edge::new(&v[3], &v[2], ()),
    ///     Edge::new(&v[0], &v[3], ()),
    /// ];
    /// let wire = vec![
    ///     Wire::from_iter(vec![&edge[0], &edge[3], &edge[4], &edge[2]]),
    ///     Wire::from_iter(vec![&edge[1], &edge[2], &edge[5], &edge[3].inverse()]),
    /// ];
    /// let shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
    /// assert_eq!(shell.shell_condition(), ShellCondition::Regular);
    /// assert!(shell.singular_vertices().is_empty());
    /// ```
    /// ```
    /// // A closed and connected shell which has a singular vertex.
    /// use truck_topology::*;
    /// use truck_topology::shell::*;
    ///
    /// let v = Vertex::news(&[(); 7]);
    /// let edge = [
    ///     Edge::new(&v[0], &v[1], ()), // 0
    ///     Edge::new(&v[0], &v[2], ()), // 1
    ///     Edge::new(&v[0], &v[3], ()), // 2
    ///     Edge::new(&v[1], &v[2], ()), // 3
    ///     Edge::new(&v[2], &v[3], ()), // 4
    ///     Edge::new(&v[3], &v[1], ()), // 5
    ///     Edge::new(&v[0], &v[4], ()), // 6
    ///     Edge::new(&v[0], &v[5], ()), // 7
    ///     Edge::new(&v[0], &v[6], ()), // 8
    ///     Edge::new(&v[4], &v[5], ()), // 9
    ///     Edge::new(&v[5], &v[6], ()), // 10
    ///     Edge::new(&v[6], &v[4], ()), // 11
    /// ];
    /// let wire = vec![
    ///     Wire::from_iter(vec![&edge[0].inverse(), &edge[1], &edge[3].inverse()]),
    ///     Wire::from_iter(vec![&edge[1].inverse(), &edge[2], &edge[4].inverse()]),
    ///     Wire::from_iter(vec![&edge[2].inverse(), &edge[0], &edge[5].inverse()]),
    ///     Wire::from_iter(vec![&edge[3], &edge[4], &edge[5]]),
    ///     Wire::from_iter(vec![&edge[6].inverse(), &edge[7], &edge[9].inverse()]),
    ///     Wire::from_iter(vec![&edge[7].inverse(), &edge[8], &edge[10].inverse()]),
    ///     Wire::from_iter(vec![&edge[8].inverse(), &edge[6], &edge[11].inverse()]),
    ///     Wire::from_iter(vec![&edge[9], &edge[10], &edge[11]]),
    /// ];
    /// let shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
    /// assert_eq!(shell.shell_condition(), ShellCondition::Closed);
    /// assert!(shell.is_connected());
    /// assert_eq!(shell.singular_vertices(), vec![v[0].clone()]);
    /// ```
    pub fn singular_vertices(&self) -> Vec<Vertex<P>> {
        let mut vert_wise_adjacency =
            EntryMap::new(Vertex::clone, |_| EntryMap::new(Edge::id, |_| Vec::new()));
        self.face_iter()
            .flat_map(Face::absolute_boundaries)
            .for_each(|wire| {
                let first_edge = &wire[0];
                let mut edge_iter = wire.iter().peekable();
                while let Some(edge) = edge_iter.next() {
                    let adjacency = vert_wise_adjacency.entry_or_insert(edge.back());
                    let next_edge = *edge_iter.peek().unwrap_or(&first_edge);
                    adjacency.entry_or_insert(edge).push(next_edge.id());
                    adjacency.entry_or_insert(next_edge).push(edge.id());
                }
            });
        vert_wise_adjacency
            .into_iter()
            .filter_map(|(vertex, adjacency)| {
                Some(vertex).filter(|_| !check_connectivity(&mut adjacency.into()))
            })
            .collect()
    }

    /// Returns a new shell whose surfaces are mapped by `surface_mapping`,
    /// curves are mapped by `curve_mapping` and points are mapped by `point_mapping`.
    /// # Remarks
    /// Accessing geometry elements directly in the closure will result in a deadlock.
    /// So, this method does not appear to the document.
    #[doc(hidden)]
    pub fn try_mapped<Q, D, T>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Option<Q>,
        mut curve_mapping: impl FnMut(&C) -> Option<D>,
        mut surface_mapping: impl FnMut(&S) -> Option<T>,
    ) -> Option<Shell<Q, D, T>> {
        let mut vertex_map = EntryMap::new(Vertex::id, move |v| v.try_mapped(&mut point_mapping));
        let mut edge_map = EntryMap::new(
            Edge::id,
            wire::edge_entry_map_try_closure(&mut vertex_map, &mut curve_mapping),
        );
        self.face_iter()
            .map(|face| {
                let wires = face
                    .absolute_boundaries()
                    .iter()
                    .map(|wire| wire.sub_try_mapped(&mut edge_map))
                    .collect::<Option<Vec<_>>>()?;
                let surface = surface_mapping(&*face.surface.lock().unwrap())?;
                let mut new_face = Face::debug_new(wires, surface);
                if !face.orientation() {
                    new_face.invert();
                }
                Some(new_face)
            })
            .collect()
    }

    /// Returns a new shell whose surfaces are mapped by `surface_mapping`,
    /// curves are mapped by `curve_mapping` and points are mapped by `point_mapping`.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[0, 1, 2, 3, 4, 5, 6]);
    /// let wire0 = Wire::from(vec![
    ///     Edge::new(&v[0], &v[1], 100),
    ///     Edge::new(&v[1], &v[2], 200),
    ///     Edge::new(&v[2], &v[3], 300),
    ///     Edge::new(&v[3], &v[0], 400),
    /// ]);
    /// let wire1 = Wire::from(vec![
    ///     Edge::new(&v[4], &v[5], 500),
    ///     Edge::new(&v[6], &v[5], 600).inverse(),
    ///     Edge::new(&v[6], &v[4], 700),
    /// ]);
    /// let face0 = Face::new(vec![wire0, wire1], 10000);
    /// let face1 = face0.mapped(
    ///     &move |i: &usize| *i + 7,
    ///     &move |j: &usize| *j + 700,
    ///     &move |k: &usize| *k + 10000,
    /// );
    /// let shell0 = Shell::from(vec![face0, face1.inverse()]);
    /// let shell1 = shell0.mapped(
    ///     &move |i: &usize| *i + 50,
    ///     &move |j: &usize| *j + 5000,
    ///     &move |k: &usize| *k + 500000,
    /// );
    /// # for face in shell1.face_iter() {
    /// #    for bdry in face.absolute_boundaries() {
    /// #        assert!(bdry.is_closed());
    /// #        assert!(bdry.is_simple());
    /// #    }
    /// # }
    ///
    /// for (face0, face1) in shell0.face_iter().zip(shell1.face_iter()) {
    ///     assert_eq!(
    ///         face0.get_surface() + 500000,
    ///         face1.get_surface(),
    ///     );
    ///     assert_eq!(face0.orientation(), face1.orientation());
    ///     let biters0 = face0.boundary_iters();
    ///     let biters1 = face1.boundary_iters();
    ///     for (biter0, biter1) in biters0.into_iter().zip(biters1) {
    ///         for (edge0, edge1) in biter0.zip(biter1) {
    ///             assert_eq!(
    ///                 edge0.front().get_point() + 50,
    ///                 edge1.front().get_point(),
    ///             );
    ///             assert_eq!(
    ///                 edge0.back().get_point() + 50,
    ///                 edge1.back().get_point(),
    ///             );
    ///             assert_eq!(
    ///                 edge0.get_curve() + 5000,
    ///                 edge1.get_curve(),
    ///             );
    ///         }
    ///     }
    /// }
    /// ```
    /// # Remarks
    /// Accessing geometry elements directly in the closure will result in a deadlock.
    /// So, this method does not appear to the document.
    #[doc(hidden)]
    pub fn mapped<Q, D, T>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Q,
        mut curve_mapping: impl FnMut(&C) -> D,
        mut surface_mapping: impl FnMut(&S) -> T,
    ) -> Shell<Q, D, T> {
        let mut vertex_map = EntryMap::new(Vertex::id, |v| v.mapped(&mut point_mapping));
        let mut edge_map = EntryMap::new(
            Edge::id,
            wire::edge_entry_map_closure(&mut vertex_map, &mut curve_mapping),
        );
        self.face_iter()
            .map(|face| {
                let wires: Vec<Wire<_, _>> = face
                    .absolute_boundaries()
                    .iter()
                    .map(|wire| wire.sub_mapped(&mut edge_map))
                    .collect();
                let surface = surface_mapping(&*face.surface.lock().unwrap());
                let mut new_face = Face::debug_new(wires, surface);
                if !face.orientation() {
                    new_face.invert();
                }
                new_face
            })
            .collect()
    }

    /// Returns the consistence of the geometry of end vertices
    /// and the geometry of edge.
    #[inline(always)]
    pub fn is_geometric_consistent(&self) -> bool
    where
        P: Tolerance,
        C: BoundedCurve<Point = P>,
        S: IncludeCurve<C>, {
        self.iter().all(|face| face.is_geometric_consistent())
    }

    /// Cuts one edge into two edges at vertex.
    ///
    /// # Returns
    /// Returns the tuple of new edges created by cutting the edge.
    ///
    /// # Failures
    /// Returns `None` and not edit `self` if:
    /// - there is no edge corresponding to `edge_id` in the shell,
    /// - `vertex` is already included in the shell, or
    /// - cutting of edge fails.
    pub fn cut_edge(
        &mut self,
        edge_id: EdgeID<C>,
        vertex: &Vertex<P>,
    ) -> Option<(Edge<P, C>, Edge<P, C>)>
    where
        P: Clone,
        C: Cut<Point = P> + SearchParameter<D1, Point = P>,
    {
        if self.vertex_iter().any(|v| &v == vertex) {
            return None;
        }
        let mut edges = None;
        self.iter_mut()
            .flat_map(|face| face.boundaries.iter_mut())
            .try_for_each(|wire| {
                let find_res = wire
                    .iter()
                    .enumerate()
                    .find(|(_, edge)| edge.id() == edge_id);
                let (idx, edge) = match find_res {
                    Some(got) => got,
                    None => return Some(()),
                };
                if edges.is_none() {
                    edges = Some(edge.absolute_clone().cut(vertex)?);
                }
                let edges = edges.as_ref().unwrap();
                let new_wire = match edge.orientation() {
                    true => Wire::from(vec![edges.0.clone(), edges.1.clone()]),
                    false => Wire::from(vec![edges.1.inverse(), edges.0.inverse()]),
                };
                let flag = wire.swap_edge_into_wire(idx, new_wire);
                debug_assert!(flag);
                Some(())
            });
        edges
    }
    /// Removes `vertex` from `self` by concat two edges on both sides.
    ///
    /// # Returns
    /// Returns the new created edge.
    ///
    /// # Failures
    /// Returns `None` if:
    /// - there are no vertex corresponding to `vertex_id` in the shell,
    /// - the vertex is included more than 2 face boundaries,
    /// - the vertex is included more than 2 edges, or
    /// - concating edges is failed.
    pub fn remove_vertex_by_concat_edges(&mut self, vertex_id: VertexID<P>) -> Option<Edge<P, C>>
    where
        P: Debug,
        C: Concat<C, Point = P, Output = C> + Invertible + ParameterTransform, {
        let mut vec: Vec<(&mut Wire<P, C>, usize)> = self
            .face_iter_mut()
            .flat_map(|face| &mut face.boundaries)
            .filter_map(|wire| {
                let idx = wire
                    .edge_iter()
                    .enumerate()
                    .find(|(_, e)| e.back().id() == vertex_id)?
                    .0;
                Some((wire, idx))
            })
            .collect();
        if vec.len() > 2 || vec.is_empty() {
            None
        } else if vec.len() == 1 {
            let (wire, idx) = vec.pop().unwrap();
            let edge = wire[idx].concat(&wire[(idx + 1) % wire.len()]).ok()?;
            wire.swap_subwire_into_edges(idx, edge.clone());
            Some(edge)
        } else {
            let (wire0, idx0) = vec.pop().unwrap();
            let (wire1, idx1) = vec.pop().unwrap();
            if !wire0[idx0].is_same(&wire1[(idx1 + 1) % wire1.len()])
                || !wire0[(idx0 + 1) % wire0.len()].is_same(&wire1[idx1])
            {
                return None;
            }
            let edge = wire0[idx0].concat(&wire0[(idx0 + 1) % wire0.len()]).ok()?;
            wire1.swap_subwire_into_edges(idx1, edge.inverse());
            wire0.swap_subwire_into_edges(idx0, edge.clone());
            Some(edge)
        }
    }
src/face.rs (line 775)
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
    pub fn cut_by_edge(&self, edge: Edge<P, C>) -> Option<(Self, Self)>
    where S: Clone {
        if self.boundaries.len() != 1 {
            return None;
        }
        let mut face0 = Face {
            boundaries: self.boundaries.clone(),
            orientation: self.orientation,
            surface: Arc::new(Mutex::new(self.get_surface())),
        };
        let wire = &mut face0.boundaries[0];
        let i = wire
            .edge_iter()
            .enumerate()
            .find(|(_, e)| e.front() == edge.back())
            .map(|(i, _)| i)?;
        let j = wire
            .edge_iter()
            .enumerate()
            .find(|(_, e)| e.back() == edge.front())
            .map(|(i, _)| i)?;
        wire.rotate_left(i);
        let j = (j + wire.len() - i) % wire.len();
        let mut new_wire = wire.split_off(j + 1);
        wire.push_back(edge.clone());
        new_wire.push_back(edge.inverse());
        debug_assert!(Face::try_new(self.boundaries.clone(), ()).is_ok());
        debug_assert!(Face::try_new(vec![new_wire.clone()], ()).is_ok());
        let face1 = Face {
            boundaries: vec![new_wire],
            orientation: self.orientation,
            surface: Arc::new(Mutex::new(self.get_surface())),
        };
        Some((face0, face1))
    }

    /// Glue two faces at boundaries.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 8]);
    /// let edge = vec![
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[2], &v[0], ()),
    ///     Edge::new(&v[3], &v[4], ()),
    ///     Edge::new(&v[4], &v[5], ()),
    ///     Edge::new(&v[5], &v[3], ()),
    ///     Edge::new(&v[6], &v[2], ()),
    ///     Edge::new(&v[1], &v[6], ()),
    ///     Edge::new(&v[7], &v[5], ()),
    ///     Edge::new(&v[4], &v[7], ()),
    /// ];
    /// let wire0 = Wire::from(vec![
    ///     edge[0].clone(),
    ///     edge[1].clone(),
    ///     edge[2].clone(),
    /// ]);
    /// let wire1 = Wire::from(vec![
    ///     edge[3].clone(),
    ///     edge[4].clone(),
    ///     edge[5].clone(),
    /// ]);
    /// let wire2 = Wire::from(vec![
    ///     edge[6].clone(),
    ///     edge[1].inverse(),
    ///     edge[7].clone(),
    /// ]);
    /// let wire3 = Wire::from(vec![
    ///     edge[8].clone(),
    ///     edge[4].inverse(),
    ///     edge[9].clone(),
    /// ]);
    /// let face0 = Face::new(vec![wire0, wire1], ());
    /// let face1 = Face::new(vec![wire2, wire3], ());
    /// let face = face0.glue_at_boundaries(&face1).unwrap();
    /// let boundaries = face.boundary_iters();
    /// assert_eq!(boundaries.len(), 2);
    /// assert_eq!(boundaries[0].len(), 4);
    /// assert_eq!(boundaries[1].len(), 4);
    /// ```
    pub fn glue_at_boundaries(&self, other: &Self) -> Option<Self>
    where
        S: Clone + PartialEq,
        Wire<P, C>: Debug, {
        let surface = self.get_surface();
        if surface != other.get_surface() || self.orientation() != other.orientation() {
            return None;
        }
        let mut vemap: HashMap<VertexID<P>, &Edge<P, C>> = self
            .absolute_boundaries()
            .iter()
            .flatten()
            .map(|edge| (edge.front().id(), edge))
            .collect();
        other
            .absolute_boundaries()
            .iter()
            .flatten()
            .try_for_each(|edge| {
                if let Some(edge0) = vemap.get(&edge.back().id()) {
                    if edge.front() == edge0.back() {
                        if edge.is_same(edge0) {
                            vemap.remove(&edge.back().id());
                            return Some(());
                        } else {
                            return None;
                        }
                    }
                }
                vemap.insert(edge.front().id(), edge);
                Some(())
            })?;
        if vemap.is_empty() {
            return None;
        }
        let mut boundaries = Vec::new();
        while !vemap.is_empty() {
            let mut wire = Wire::new();
            let v = *vemap.iter().next().unwrap().0;
            let mut edge = vemap.remove(&v).unwrap();
            wire.push_back(edge.clone());
            while let Some(edge0) = vemap.remove(&edge.back().id()) {
                wire.push_back(edge0.clone());
                edge = edge0;
            }
            boundaries.push(wire);
        }
        debug_assert!(Face::try_new(boundaries.clone(), ()).is_ok());
        Some(Face {
            boundaries,
            orientation: self.orientation(),
            surface: Arc::new(Mutex::new(surface)),
        })
    }

Returns the vertices at both ends.

let v = Vertex::news(&[(), ()]);
let edge = Edge::new(&v[0], &v[1], ());
assert_eq!(edge.ends(), (&v[0], &v[1]));
Examples found in repository?
src/wire.rs (line 362)
361
362
363
364
365
366
367
368
369
370
371
    pub fn swap_edge_into_wire(&mut self, idx: usize, wire: Wire<P, C>) -> bool {
        if wire.is_empty() || self[idx].ends() != wire.ends_vertices().unwrap() {
            return false;
        }
        let mut new_wire: Vec<_> = self.drain(0..idx).collect();
        new_wire.extend(wire);
        self.pop_front();
        new_wire.extend(self.drain(..));
        *self = new_wire.into();
        true
    }

Returns the front vertex which is generated by constructor

let v = Vertex::news(&[(), ()]);
let edge = Edge::new(&v[0], &v[1], ()).inverse();
assert_eq!(edge.front(), &v[1]);
assert_eq!(edge.absolute_front(), &v[0]);
Examples found in repository?
src/edge.rs (line 340)
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
    pub fn try_mapped<Q, D>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Option<Q>,
        mut curve_mapping: impl FnMut(&C) -> Option<D>,
    ) -> Option<Edge<Q, D>> {
        let v0 = self.absolute_front().try_mapped(&mut point_mapping)?;
        let v1 = self.absolute_back().try_mapped(&mut point_mapping)?;
        let curve = curve_mapping(&*self.curve.lock().unwrap())?;
        let mut edge = Edge::debug_new(&v0, &v1, curve);
        if !self.orientation() {
            edge.invert();
        }
        Some(edge)
    }

    /// Returns a new edge whose curve is mapped by `curve_mapping` and
    /// whose end points are mapped by `point_mapping`.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v0 = Vertex::new(0);
    /// let v1 = Vertex::new(1);
    /// let edge0 = Edge::new(&v0, &v1, 2);
    /// let edge1 = edge0.mapped(
    ///     &move |i: &usize| *i as f64 + 0.5,
    ///     &move |j: &usize| *j as f64 + 0.5,
    /// );
    ///
    /// assert_eq!(edge1.front().get_point(), 0.5);
    /// assert_eq!(edge1.back().get_point(), 1.5);
    /// assert_eq!(edge1.get_curve(), 2.5);
    /// ```
    /// # Remarks
    /// Accessing geometry elements directly in the closure will result in a deadlock.
    /// So, this method does not appear to the document.
    #[doc(hidden)]
    #[inline(always)]
    pub fn mapped<Q, D>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Q,
        mut curve_mapping: impl FnMut(&C) -> D,
    ) -> Edge<Q, D> {
        let v0 = self.absolute_front().mapped(&mut point_mapping);
        let v1 = self.absolute_back().mapped(&mut point_mapping);
        let curve = curve_mapping(&*self.curve.lock().unwrap());
        let mut edge = Edge::debug_new(&v0, &v1, curve);
        if edge.orientation() != self.orientation() {
            edge.invert();
        }
        edge
    }

    /// Returns the consistence of the geometry of end vertices
    /// and the geometry of edge.
    #[inline(always)]
    pub fn is_geometric_consistent(&self) -> bool
    where
        P: Tolerance,
        C: BoundedCurve<Point = P>, {
        let curve = self.curve.lock().unwrap();
        let geom_front = curve.front();
        let geom_back = curve.back();
        let top_front = self.absolute_front().point.lock().unwrap();
        let top_back = self.absolute_back().point.lock().unwrap();
        geom_front.near(&*top_front) && geom_back.near(&*top_back)
    }

    /// Cuts the edge at `vertex`.
    /// # Failure
    /// Returns `None` if:
    /// - cannot find the parameter `t` such that `edge.get_curve().subs(t) == vertex.get_point()`, or
    /// - the found parameter is not in the parameter range without end points.
    pub fn cut(&self, vertex: &Vertex<P>) -> Option<(Self, Self)>
    where
        P: Clone,
        C: Cut<Point = P> + SearchParameter<D1, Point = P>, {
        let mut curve0 = self.get_curve();
        let t = curve0.search_parameter(vertex.get_point(), None, SEARCH_PARAMETER_TRIALS)?;
        let (t0, t1) = curve0.parameter_range();
        if t < t0 + TOLERANCE || t1 - TOLERANCE < t {
            return None;
        }
        let curve1 = curve0.cut(t);
        let edge0 = Edge {
            vertices: (self.absolute_front().clone(), vertex.clone()),
            orientation: self.orientation,
            curve: Arc::new(Mutex::new(curve0)),
        };
        let edge1 = Edge {
            vertices: (vertex.clone(), self.absolute_back().clone()),
            orientation: self.orientation,
            curve: Arc::new(Mutex::new(curve1)),
        };
        if self.orientation {
            Some((edge0, edge1))
        } else {
            Some((edge1, edge0))
        }
    }

    /// Cuts the edge at `vertex` with parameter `t`.
    /// # Failure
    /// Returns `None` if `!edge.get_curve().subs(t).near(&vertex.get_point())`.
    pub fn cut_with_parameter(&self, vertex: &Vertex<P>, t: f64) -> Option<(Self, Self)>
    where
        P: Clone + Tolerance,
        C: Cut<Point = P>, {
        let mut curve0 = self.get_curve();
        if !curve0.subs(t).near(&vertex.get_point()) {
            return None;
        }
        let (t0, t1) = curve0.parameter_range();
        if t < t0 + TOLERANCE || t1 - TOLERANCE < t {
            return None;
        }
        let curve1 = curve0.cut(t);
        let edge0 = Edge {
            vertices: (self.absolute_front().clone(), vertex.clone()),
            orientation: self.orientation,
            curve: Arc::new(Mutex::new(curve0)),
        };
        let edge1 = Edge {
            vertices: (vertex.clone(), self.absolute_back().clone()),
            orientation: self.orientation,
            curve: Arc::new(Mutex::new(curve1)),
        };
        if self.orientation {
            Some((edge0, edge1))
        } else {
            Some((edge1, edge0))
        }
    }
More examples
Hide additional examples
src/compress.rs (line 127)
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
    fn get_eid(&mut self, edge: &Edge<P, C>) -> CompressedEdgeIndex {
        match self.emap.get(&edge.id()) {
            Some(got) => (got.0, edge.orientation()).into(),
            None => {
                let id = self.emap.len();
                let front_id = self.get_vid(edge.absolute_front());
                let back_id = self.get_vid(edge.absolute_back());
                let curve = edge.get_curve();
                let cedge = CompressedEdge {
                    vertices: (front_id, back_id),
                    curve,
                };
                self.emap.insert(edge.id(), (id, cedge));
                (id, edge.orientation()).into()
            }
        }
    }
src/wire.rs (line 552)
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
pub(super) fn edge_entry_map_try_closure<'a, P, C, Q, D, KF, VF>(
    vertex_map: &'a mut EntryMap<VertexID<P>, Option<Vertex<Q>>, KF, VF, &'a Vertex<P>>,
    curve_mapping: &'a mut impl FnMut(&C) -> Option<D>,
) -> impl FnMut(&'a Edge<P, C>) -> Option<Edge<Q, D>> + 'a
where
    KF: FnMut(&'a Vertex<P>) -> VertexID<P>,
    VF: FnMut(&'a Vertex<P>) -> Option<Vertex<Q>>,
{
    move |edge| {
        let vf = edge.absolute_front();
        let vertex0 = vertex_map.entry_or_insert(vf).clone()?;
        let vb = edge.absolute_back();
        let vertex1 = vertex_map.entry_or_insert(vb).clone()?;
        let curve = curve_mapping(&*edge.curve.lock().unwrap())?;
        Some(Edge::debug_new(&vertex0, &vertex1, curve))
    }
}

pub(super) fn edge_entry_map_closure<'a, P, C, Q, D, KF, VF>(
    vertex_map: &'a mut EntryMap<VertexID<P>, Vertex<Q>, KF, VF, &'a Vertex<P>>,
    curve_mapping: &'a mut impl FnMut(&C) -> D,
) -> impl FnMut(&'a Edge<P, C>) -> Edge<Q, D> + 'a
where
    KF: FnMut(&'a Vertex<P>) -> VertexID<P>,
    VF: FnMut(&'a Vertex<P>) -> Vertex<Q>,
{
    move |edge| {
        let vf = edge.absolute_front();
        let vertex0 = vertex_map.entry_or_insert(vf).clone();
        let vb = edge.absolute_back();
        let vertex1 = vertex_map.entry_or_insert(vb).clone();
        let curve = curve_mapping(&*edge.curve.lock().unwrap());
        Edge::debug_new(&vertex0, &vertex1, curve)
    }
}

Returns the back vertex which is generated by constructor

let v = Vertex::news(&[(), ()]);
let edge = Edge::new(&v[0], &v[1], ()).inverse();
assert_eq!(edge.back(), &v[0]);
assert_eq!(edge.absolute_back(), &v[1]);
Examples found in repository?
src/edge.rs (line 341)
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
    pub fn try_mapped<Q, D>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Option<Q>,
        mut curve_mapping: impl FnMut(&C) -> Option<D>,
    ) -> Option<Edge<Q, D>> {
        let v0 = self.absolute_front().try_mapped(&mut point_mapping)?;
        let v1 = self.absolute_back().try_mapped(&mut point_mapping)?;
        let curve = curve_mapping(&*self.curve.lock().unwrap())?;
        let mut edge = Edge::debug_new(&v0, &v1, curve);
        if !self.orientation() {
            edge.invert();
        }
        Some(edge)
    }

    /// Returns a new edge whose curve is mapped by `curve_mapping` and
    /// whose end points are mapped by `point_mapping`.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v0 = Vertex::new(0);
    /// let v1 = Vertex::new(1);
    /// let edge0 = Edge::new(&v0, &v1, 2);
    /// let edge1 = edge0.mapped(
    ///     &move |i: &usize| *i as f64 + 0.5,
    ///     &move |j: &usize| *j as f64 + 0.5,
    /// );
    ///
    /// assert_eq!(edge1.front().get_point(), 0.5);
    /// assert_eq!(edge1.back().get_point(), 1.5);
    /// assert_eq!(edge1.get_curve(), 2.5);
    /// ```
    /// # Remarks
    /// Accessing geometry elements directly in the closure will result in a deadlock.
    /// So, this method does not appear to the document.
    #[doc(hidden)]
    #[inline(always)]
    pub fn mapped<Q, D>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Q,
        mut curve_mapping: impl FnMut(&C) -> D,
    ) -> Edge<Q, D> {
        let v0 = self.absolute_front().mapped(&mut point_mapping);
        let v1 = self.absolute_back().mapped(&mut point_mapping);
        let curve = curve_mapping(&*self.curve.lock().unwrap());
        let mut edge = Edge::debug_new(&v0, &v1, curve);
        if edge.orientation() != self.orientation() {
            edge.invert();
        }
        edge
    }

    /// Returns the consistence of the geometry of end vertices
    /// and the geometry of edge.
    #[inline(always)]
    pub fn is_geometric_consistent(&self) -> bool
    where
        P: Tolerance,
        C: BoundedCurve<Point = P>, {
        let curve = self.curve.lock().unwrap();
        let geom_front = curve.front();
        let geom_back = curve.back();
        let top_front = self.absolute_front().point.lock().unwrap();
        let top_back = self.absolute_back().point.lock().unwrap();
        geom_front.near(&*top_front) && geom_back.near(&*top_back)
    }

    /// Cuts the edge at `vertex`.
    /// # Failure
    /// Returns `None` if:
    /// - cannot find the parameter `t` such that `edge.get_curve().subs(t) == vertex.get_point()`, or
    /// - the found parameter is not in the parameter range without end points.
    pub fn cut(&self, vertex: &Vertex<P>) -> Option<(Self, Self)>
    where
        P: Clone,
        C: Cut<Point = P> + SearchParameter<D1, Point = P>, {
        let mut curve0 = self.get_curve();
        let t = curve0.search_parameter(vertex.get_point(), None, SEARCH_PARAMETER_TRIALS)?;
        let (t0, t1) = curve0.parameter_range();
        if t < t0 + TOLERANCE || t1 - TOLERANCE < t {
            return None;
        }
        let curve1 = curve0.cut(t);
        let edge0 = Edge {
            vertices: (self.absolute_front().clone(), vertex.clone()),
            orientation: self.orientation,
            curve: Arc::new(Mutex::new(curve0)),
        };
        let edge1 = Edge {
            vertices: (vertex.clone(), self.absolute_back().clone()),
            orientation: self.orientation,
            curve: Arc::new(Mutex::new(curve1)),
        };
        if self.orientation {
            Some((edge0, edge1))
        } else {
            Some((edge1, edge0))
        }
    }

    /// Cuts the edge at `vertex` with parameter `t`.
    /// # Failure
    /// Returns `None` if `!edge.get_curve().subs(t).near(&vertex.get_point())`.
    pub fn cut_with_parameter(&self, vertex: &Vertex<P>, t: f64) -> Option<(Self, Self)>
    where
        P: Clone + Tolerance,
        C: Cut<Point = P>, {
        let mut curve0 = self.get_curve();
        if !curve0.subs(t).near(&vertex.get_point()) {
            return None;
        }
        let (t0, t1) = curve0.parameter_range();
        if t < t0 + TOLERANCE || t1 - TOLERANCE < t {
            return None;
        }
        let curve1 = curve0.cut(t);
        let edge0 = Edge {
            vertices: (self.absolute_front().clone(), vertex.clone()),
            orientation: self.orientation,
            curve: Arc::new(Mutex::new(curve0)),
        };
        let edge1 = Edge {
            vertices: (vertex.clone(), self.absolute_back().clone()),
            orientation: self.orientation,
            curve: Arc::new(Mutex::new(curve1)),
        };
        if self.orientation {
            Some((edge0, edge1))
        } else {
            Some((edge1, edge0))
        }
    }
More examples
Hide additional examples
src/compress.rs (line 128)
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
    fn get_eid(&mut self, edge: &Edge<P, C>) -> CompressedEdgeIndex {
        match self.emap.get(&edge.id()) {
            Some(got) => (got.0, edge.orientation()).into(),
            None => {
                let id = self.emap.len();
                let front_id = self.get_vid(edge.absolute_front());
                let back_id = self.get_vid(edge.absolute_back());
                let curve = edge.get_curve();
                let cedge = CompressedEdge {
                    vertices: (front_id, back_id),
                    curve,
                };
                self.emap.insert(edge.id(), (id, cedge));
                (id, edge.orientation()).into()
            }
        }
    }
src/wire.rs (line 554)
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
pub(super) fn edge_entry_map_try_closure<'a, P, C, Q, D, KF, VF>(
    vertex_map: &'a mut EntryMap<VertexID<P>, Option<Vertex<Q>>, KF, VF, &'a Vertex<P>>,
    curve_mapping: &'a mut impl FnMut(&C) -> Option<D>,
) -> impl FnMut(&'a Edge<P, C>) -> Option<Edge<Q, D>> + 'a
where
    KF: FnMut(&'a Vertex<P>) -> VertexID<P>,
    VF: FnMut(&'a Vertex<P>) -> Option<Vertex<Q>>,
{
    move |edge| {
        let vf = edge.absolute_front();
        let vertex0 = vertex_map.entry_or_insert(vf).clone()?;
        let vb = edge.absolute_back();
        let vertex1 = vertex_map.entry_or_insert(vb).clone()?;
        let curve = curve_mapping(&*edge.curve.lock().unwrap())?;
        Some(Edge::debug_new(&vertex0, &vertex1, curve))
    }
}

pub(super) fn edge_entry_map_closure<'a, P, C, Q, D, KF, VF>(
    vertex_map: &'a mut EntryMap<VertexID<P>, Vertex<Q>, KF, VF, &'a Vertex<P>>,
    curve_mapping: &'a mut impl FnMut(&C) -> D,
) -> impl FnMut(&'a Edge<P, C>) -> Edge<Q, D> + 'a
where
    KF: FnMut(&'a Vertex<P>) -> VertexID<P>,
    VF: FnMut(&'a Vertex<P>) -> Vertex<Q>,
{
    move |edge| {
        let vf = edge.absolute_front();
        let vertex0 = vertex_map.entry_or_insert(vf).clone();
        let vb = edge.absolute_back();
        let vertex1 = vertex_map.entry_or_insert(vb).clone();
        let curve = curve_mapping(&*edge.curve.lock().unwrap());
        Edge::debug_new(&vertex0, &vertex1, curve)
    }
}

Returns the vertices at both absolute ends.

let v = Vertex::news(&[(), ()]);
let mut edge = Edge::new(&v[0], &v[1], ());
edge.invert();
assert_eq!(edge.ends(), (&v[1], &v[0]));
assert_eq!(edge.absolute_ends(), (&v[0], &v[1]));

Returns a clone of the edge without inversion.

Examples
use truck_topology::{Vertex, Edge};
let v = Vertex::news(&[(), ()]);
let edge0 = Edge::new(&v[0], &v[1], ());
let edge1 = edge0.inverse();
let edge2 = edge1.absolute_clone();
assert_eq!(edge0, edge2);
assert_ne!(edge1, edge2);
assert!(edge1.is_same(&edge2));
Examples found in repository?
src/wire.rs (line 395)
386
387
388
389
390
391
392
393
394
395
396
397
    pub(super) fn sub_try_mapped<'a, Q, D, KF, KV>(
        &'a self,
        edge_map: &mut EdgeEntryMapForTryMapping<'a, P, C, Q, D, KF, KV>,
    ) -> Option<Wire<Q, D>>
    where
        KF: FnMut(&'a Edge<P, C>) -> EdgeID<C>,
        KV: FnMut(&'a Edge<P, C>) -> Option<Edge<Q, D>>,
    {
        self.edge_iter()
            .map(|edge| Some(edge_map.entry_or_insert(edge).as_ref()?.absolute_clone()))
            .collect()
    }
More examples
Hide additional examples
src/shell.rs (line 632)
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
    pub fn cut_edge(
        &mut self,
        edge_id: EdgeID<C>,
        vertex: &Vertex<P>,
    ) -> Option<(Edge<P, C>, Edge<P, C>)>
    where
        P: Clone,
        C: Cut<Point = P> + SearchParameter<D1, Point = P>,
    {
        if self.vertex_iter().any(|v| &v == vertex) {
            return None;
        }
        let mut edges = None;
        self.iter_mut()
            .flat_map(|face| face.boundaries.iter_mut())
            .try_for_each(|wire| {
                let find_res = wire
                    .iter()
                    .enumerate()
                    .find(|(_, edge)| edge.id() == edge_id);
                let (idx, edge) = match find_res {
                    Some(got) => got,
                    None => return Some(()),
                };
                if edges.is_none() {
                    edges = Some(edge.absolute_clone().cut(vertex)?);
                }
                let edges = edges.as_ref().unwrap();
                let new_wire = match edge.orientation() {
                    true => Wire::from(vec![edges.0.clone(), edges.1.clone()]),
                    false => Wire::from(vec![edges.1.inverse(), edges.0.inverse()]),
                };
                let flag = wire.swap_edge_into_wire(idx, new_wire);
                debug_assert!(flag);
                Some(())
            });
        edges
    }

Returns whether two edges are the same. Returns true even if the orientaions are different.

use truck_topology::{Vertex, Edge};
let v = Vertex::news(&[(), ()]);
let edge0 = Edge::new(&v[0], &v[1], ());
let edge1 = Edge::new(&v[0], &v[1], ());
let edge2 = edge0.clone();
let edge3 = edge0.inverse();
assert!(!edge0.is_same(&edge1)); // edges whose ids are different are not the same.
assert!(edge0.is_same(&edge2)); // The cloned edge is the same edge.
assert!(edge0.is_same(&edge3)); // The inversed edge is the "same" edge
Examples found in repository?
src/shell.rs (line 682)
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
    pub fn remove_vertex_by_concat_edges(&mut self, vertex_id: VertexID<P>) -> Option<Edge<P, C>>
    where
        P: Debug,
        C: Concat<C, Point = P, Output = C> + Invertible + ParameterTransform, {
        let mut vec: Vec<(&mut Wire<P, C>, usize)> = self
            .face_iter_mut()
            .flat_map(|face| &mut face.boundaries)
            .filter_map(|wire| {
                let idx = wire
                    .edge_iter()
                    .enumerate()
                    .find(|(_, e)| e.back().id() == vertex_id)?
                    .0;
                Some((wire, idx))
            })
            .collect();
        if vec.len() > 2 || vec.is_empty() {
            None
        } else if vec.len() == 1 {
            let (wire, idx) = vec.pop().unwrap();
            let edge = wire[idx].concat(&wire[(idx + 1) % wire.len()]).ok()?;
            wire.swap_subwire_into_edges(idx, edge.clone());
            Some(edge)
        } else {
            let (wire0, idx0) = vec.pop().unwrap();
            let (wire1, idx1) = vec.pop().unwrap();
            if !wire0[idx0].is_same(&wire1[(idx1 + 1) % wire1.len()])
                || !wire0[(idx0 + 1) % wire0.len()].is_same(&wire1[idx1])
            {
                return None;
            }
            let edge = wire0[idx0].concat(&wire0[(idx0 + 1) % wire0.len()]).ok()?;
            wire1.swap_subwire_into_edges(idx1, edge.inverse());
            wire0.swap_subwire_into_edges(idx0, edge.clone());
            Some(edge)
        }
    }
More examples
Hide additional examples
src/face.rs (line 863)
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
    pub fn glue_at_boundaries(&self, other: &Self) -> Option<Self>
    where
        S: Clone + PartialEq,
        Wire<P, C>: Debug, {
        let surface = self.get_surface();
        if surface != other.get_surface() || self.orientation() != other.orientation() {
            return None;
        }
        let mut vemap: HashMap<VertexID<P>, &Edge<P, C>> = self
            .absolute_boundaries()
            .iter()
            .flatten()
            .map(|edge| (edge.front().id(), edge))
            .collect();
        other
            .absolute_boundaries()
            .iter()
            .flatten()
            .try_for_each(|edge| {
                if let Some(edge0) = vemap.get(&edge.back().id()) {
                    if edge.front() == edge0.back() {
                        if edge.is_same(edge0) {
                            vemap.remove(&edge.back().id());
                            return Some(());
                        } else {
                            return None;
                        }
                    }
                }
                vemap.insert(edge.front().id(), edge);
                Some(())
            })?;
        if vemap.is_empty() {
            return None;
        }
        let mut boundaries = Vec::new();
        while !vemap.is_empty() {
            let mut wire = Wire::new();
            let v = *vemap.iter().next().unwrap().0;
            let mut edge = vemap.remove(&v).unwrap();
            wire.push_back(edge.clone());
            while let Some(edge0) = vemap.remove(&edge.back().id()) {
                wire.push_back(edge0.clone());
                edge = edge0;
            }
            boundaries.push(wire);
        }
        debug_assert!(Face::try_new(boundaries.clone(), ()).is_ok());
        Some(Face {
            boundaries,
            orientation: self.orientation(),
            surface: Arc::new(Mutex::new(surface)),
        })
    }

Returns the clone of the curve.

Remarks

This method returns absolute curve i.e. does not consider the orientation of curve. If you want to get a curve compatible with edge’s orientation, use Edge::oriented_curve.

use truck_topology::*;
let v = Vertex::news(&[0, 1]);
let mut edge = Edge::new(&v[0], &v[1], (0, 1));
edge.invert();

// absolute curve
assert_eq!(edge.get_curve(), (0, 1));
// oriented curve
assert_eq!(edge.oriented_curve(), (1, 0));
Examples found in repository?
src/compress.rs (line 129)
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
    fn get_eid(&mut self, edge: &Edge<P, C>) -> CompressedEdgeIndex {
        match self.emap.get(&edge.id()) {
            Some(got) => (got.0, edge.orientation()).into(),
            None => {
                let id = self.emap.len();
                let front_id = self.get_vid(edge.absolute_front());
                let back_id = self.get_vid(edge.absolute_back());
                let curve = edge.get_curve();
                let cedge = CompressedEdge {
                    vertices: (front_id, back_id),
                    curve,
                };
                self.emap.insert(edge.id(), (id, cedge));
                (id, edge.orientation()).into()
            }
        }
    }
More examples
Hide additional examples
src/edge.rs (line 411)
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
    pub fn cut(&self, vertex: &Vertex<P>) -> Option<(Self, Self)>
    where
        P: Clone,
        C: Cut<Point = P> + SearchParameter<D1, Point = P>, {
        let mut curve0 = self.get_curve();
        let t = curve0.search_parameter(vertex.get_point(), None, SEARCH_PARAMETER_TRIALS)?;
        let (t0, t1) = curve0.parameter_range();
        if t < t0 + TOLERANCE || t1 - TOLERANCE < t {
            return None;
        }
        let curve1 = curve0.cut(t);
        let edge0 = Edge {
            vertices: (self.absolute_front().clone(), vertex.clone()),
            orientation: self.orientation,
            curve: Arc::new(Mutex::new(curve0)),
        };
        let edge1 = Edge {
            vertices: (vertex.clone(), self.absolute_back().clone()),
            orientation: self.orientation,
            curve: Arc::new(Mutex::new(curve1)),
        };
        if self.orientation {
            Some((edge0, edge1))
        } else {
            Some((edge1, edge0))
        }
    }

    /// Cuts the edge at `vertex` with parameter `t`.
    /// # Failure
    /// Returns `None` if `!edge.get_curve().subs(t).near(&vertex.get_point())`.
    pub fn cut_with_parameter(&self, vertex: &Vertex<P>, t: f64) -> Option<(Self, Self)>
    where
        P: Clone + Tolerance,
        C: Cut<Point = P>, {
        let mut curve0 = self.get_curve();
        if !curve0.subs(t).near(&vertex.get_point()) {
            return None;
        }
        let (t0, t1) = curve0.parameter_range();
        if t < t0 + TOLERANCE || t1 - TOLERANCE < t {
            return None;
        }
        let curve1 = curve0.cut(t);
        let edge0 = Edge {
            vertices: (self.absolute_front().clone(), vertex.clone()),
            orientation: self.orientation,
            curve: Arc::new(Mutex::new(curve0)),
        };
        let edge1 = Edge {
            vertices: (vertex.clone(), self.absolute_back().clone()),
            orientation: self.orientation,
            curve: Arc::new(Mutex::new(curve1)),
        };
        if self.orientation {
            Some((edge0, edge1))
        } else {
            Some((edge1, edge0))
        }
    }

Set the curve.

Examples
use truck_topology::*;
let v = Vertex::news(&[(), ()]);
let edge0 = Edge::new(&v[0], &v[1], 0);
let edge1 = edge0.clone();

// Two edges have the same content.
assert_eq!(edge0.get_curve(), 0);
assert_eq!(edge1.get_curve(), 0);

// set the content
edge0.set_curve(1);

// The contents of two edges are synchronized.
assert_eq!(edge0.get_curve(), 1);
assert_eq!(edge1.get_curve(), 1);

Returns the id that does not depend on the direction of the edge.

Examples
use truck_topology::*;
let v = Vertex::news(&[(), ()]);
let edge0 = Edge::new(&v[0], &v[1], ());
let edge1 = edge0.inverse();
assert_ne!(edge0, edge1);
assert_eq!(edge0.id(), edge1.id());
Examples found in repository?
src/edge.rs (line 236)
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
    pub fn is_same(&self, other: &Edge<P, C>) -> bool { self.id() == other.id() }

    /// Returns the clone of the curve.
    /// # Remarks
    /// This method returns absolute curve i.e. does not consider the orientation of curve.
    /// If you want to get a curve compatible with edge's orientation, use `Edge::oriented_curve`.
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[0, 1]);
    /// let mut edge = Edge::new(&v[0], &v[1], (0, 1));
    /// edge.invert();
    ///
    /// // absolute curve
    /// assert_eq!(edge.get_curve(), (0, 1));
    /// // oriented curve
    /// assert_eq!(edge.oriented_curve(), (1, 0));
    /// ```
    #[inline(always)]
    pub fn get_curve(&self) -> C
    where C: Clone {
        self.curve.lock().unwrap().clone()
    }

    /// Set the curve.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(), ()]);
    /// let edge0 = Edge::new(&v[0], &v[1], 0);
    /// let edge1 = edge0.clone();
    ///
    /// // Two edges have the same content.
    /// assert_eq!(edge0.get_curve(), 0);
    /// assert_eq!(edge1.get_curve(), 0);
    ///
    /// // set the content
    /// edge0.set_curve(1);
    ///
    /// // The contents of two edges are synchronized.
    /// assert_eq!(edge0.get_curve(), 1);
    /// assert_eq!(edge1.get_curve(), 1);
    /// ```
    #[inline(always)]
    pub fn set_curve(&self, curve: C) { *self.curve.lock().unwrap() = curve; }

    /// Returns the id that does not depend on the direction of the edge.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(), ()]);
    /// let edge0 = Edge::new(&v[0], &v[1], ());
    /// let edge1 = edge0.inverse();
    /// assert_ne!(edge0, edge1);
    /// assert_eq!(edge0.id(), edge1.id());
    /// ```
    #[inline(always)]
    pub fn id(&self) -> EdgeID<C> { ID::new(Arc::as_ptr(&self.curve)) }

    /// Returns how many same edges.
    ///
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// // Create one edge
    /// let v = Vertex::news(&[(), ()]);
    /// let e0 = Edge::new(&v[0], &v[1], ());
    /// assert_eq!(e0.count(), 1);
    /// // Create another edge, independent from e0
    /// let e1 = Edge::new(&v[0], &v[1], ());
    /// assert_eq!(e0.count(), 1);
    /// // Clone e0, count will be 2
    /// let e2 = e0.clone();
    /// assert_eq!(e0.count(), 2);
    /// assert_eq!(e2.count(), 2);
    /// // drop e2, count will be 1
    /// drop(e2);
    /// assert_eq!(e0.count(), 1);
    /// ```
    #[inline(always)]
    pub fn count(&self) -> usize { Arc::strong_count(&self.curve) }

    /// Returns the cloned curve in edge.
    /// If edge is inverted, then the returned curve is also inverted.
    #[inline(always)]
    pub fn oriented_curve(&self) -> C
    where C: Clone + Invertible {
        match self.orientation {
            true => self.curve.lock().unwrap().clone(),
            false => self.curve.lock().unwrap().inverse(),
        }
    }

    /// Returns a new edge whose curve is mapped by `curve_mapping` and
    /// whose end points are mapped by `point_mapping`.
    /// # Remarks
    /// Accessing geometry elements directly in the closure will result in a deadlock.
    /// So, this method does not appear to the document.
    #[doc(hidden)]
    #[inline(always)]
    pub fn try_mapped<Q, D>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Option<Q>,
        mut curve_mapping: impl FnMut(&C) -> Option<D>,
    ) -> Option<Edge<Q, D>> {
        let v0 = self.absolute_front().try_mapped(&mut point_mapping)?;
        let v1 = self.absolute_back().try_mapped(&mut point_mapping)?;
        let curve = curve_mapping(&*self.curve.lock().unwrap())?;
        let mut edge = Edge::debug_new(&v0, &v1, curve);
        if !self.orientation() {
            edge.invert();
        }
        Some(edge)
    }

    /// Returns a new edge whose curve is mapped by `curve_mapping` and
    /// whose end points are mapped by `point_mapping`.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v0 = Vertex::new(0);
    /// let v1 = Vertex::new(1);
    /// let edge0 = Edge::new(&v0, &v1, 2);
    /// let edge1 = edge0.mapped(
    ///     &move |i: &usize| *i as f64 + 0.5,
    ///     &move |j: &usize| *j as f64 + 0.5,
    /// );
    ///
    /// assert_eq!(edge1.front().get_point(), 0.5);
    /// assert_eq!(edge1.back().get_point(), 1.5);
    /// assert_eq!(edge1.get_curve(), 2.5);
    /// ```
    /// # Remarks
    /// Accessing geometry elements directly in the closure will result in a deadlock.
    /// So, this method does not appear to the document.
    #[doc(hidden)]
    #[inline(always)]
    pub fn mapped<Q, D>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Q,
        mut curve_mapping: impl FnMut(&C) -> D,
    ) -> Edge<Q, D> {
        let v0 = self.absolute_front().mapped(&mut point_mapping);
        let v1 = self.absolute_back().mapped(&mut point_mapping);
        let curve = curve_mapping(&*self.curve.lock().unwrap());
        let mut edge = Edge::debug_new(&v0, &v1, curve);
        if edge.orientation() != self.orientation() {
            edge.invert();
        }
        edge
    }

    /// Returns the consistence of the geometry of end vertices
    /// and the geometry of edge.
    #[inline(always)]
    pub fn is_geometric_consistent(&self) -> bool
    where
        P: Tolerance,
        C: BoundedCurve<Point = P>, {
        let curve = self.curve.lock().unwrap();
        let geom_front = curve.front();
        let geom_back = curve.back();
        let top_front = self.absolute_front().point.lock().unwrap();
        let top_back = self.absolute_back().point.lock().unwrap();
        geom_front.near(&*top_front) && geom_back.near(&*top_back)
    }

    /// Cuts the edge at `vertex`.
    /// # Failure
    /// Returns `None` if:
    /// - cannot find the parameter `t` such that `edge.get_curve().subs(t) == vertex.get_point()`, or
    /// - the found parameter is not in the parameter range without end points.
    pub fn cut(&self, vertex: &Vertex<P>) -> Option<(Self, Self)>
    where
        P: Clone,
        C: Cut<Point = P> + SearchParameter<D1, Point = P>, {
        let mut curve0 = self.get_curve();
        let t = curve0.search_parameter(vertex.get_point(), None, SEARCH_PARAMETER_TRIALS)?;
        let (t0, t1) = curve0.parameter_range();
        if t < t0 + TOLERANCE || t1 - TOLERANCE < t {
            return None;
        }
        let curve1 = curve0.cut(t);
        let edge0 = Edge {
            vertices: (self.absolute_front().clone(), vertex.clone()),
            orientation: self.orientation,
            curve: Arc::new(Mutex::new(curve0)),
        };
        let edge1 = Edge {
            vertices: (vertex.clone(), self.absolute_back().clone()),
            orientation: self.orientation,
            curve: Arc::new(Mutex::new(curve1)),
        };
        if self.orientation {
            Some((edge0, edge1))
        } else {
            Some((edge1, edge0))
        }
    }

    /// Cuts the edge at `vertex` with parameter `t`.
    /// # Failure
    /// Returns `None` if `!edge.get_curve().subs(t).near(&vertex.get_point())`.
    pub fn cut_with_parameter(&self, vertex: &Vertex<P>, t: f64) -> Option<(Self, Self)>
    where
        P: Clone + Tolerance,
        C: Cut<Point = P>, {
        let mut curve0 = self.get_curve();
        if !curve0.subs(t).near(&vertex.get_point()) {
            return None;
        }
        let (t0, t1) = curve0.parameter_range();
        if t < t0 + TOLERANCE || t1 - TOLERANCE < t {
            return None;
        }
        let curve1 = curve0.cut(t);
        let edge0 = Edge {
            vertices: (self.absolute_front().clone(), vertex.clone()),
            orientation: self.orientation,
            curve: Arc::new(Mutex::new(curve0)),
        };
        let edge1 = Edge {
            vertices: (vertex.clone(), self.absolute_back().clone()),
            orientation: self.orientation,
            curve: Arc::new(Mutex::new(curve1)),
        };
        if self.orientation {
            Some((edge0, edge1))
        } else {
            Some((edge1, edge0))
        }
    }

    /// Concats two edges.
    pub fn concat(&self, rhs: &Self) -> std::result::Result<Self, ConcatError<P>>
    where
        P: Debug,
        C: Concat<C, Point = P, Output = C> + Invertible + ParameterTransform, {
        if self.back() != rhs.front() {
            return Err(ConcatError::DisconnectedVertex(
                self.back().clone(),
                rhs.front().clone(),
            ));
        }
        if self.front() == rhs.back() {
            return Err(ConcatError::SameVertex(self.front().clone()));
        }
        let curve0 = self.oriented_curve();
        let mut curve1 = rhs.oriented_curve();
        let t0 = curve0.parameter_range().1;
        let t1 = curve1.parameter_range().0;
        curve1.parameter_transform(1.0, t0 - t1);
        let curve = curve0.try_concat(&curve1)?;
        Ok(Edge::debug_new(self.front(), rhs.back(), curve))
    }

    /// Create display struct for debugging the edge.
    ///
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use EdgeDisplayFormat as EDF;
    ///
    /// let vertex_format = VertexDisplayFormat::AsPoint;
    /// let edge = Edge::new(&Vertex::new(0), &Vertex::new(1), 2);
    ///
    /// assert_eq!(
    ///     format!("{:?}", edge.display(EDF::Full { vertex_format })),
    ///     format!("Edge {{ id: {:?}, vertices: (0, 1), entity: 2 }}", edge.id()),
    /// );
    /// assert_eq!(
    ///     format!("{:?}", edge.display(EDF::VerticesTupleAndID { vertex_format })),
    ///     format!("Edge {{ id: {:?}, vertices: (0, 1) }}", edge.id()),
    /// );
    /// assert_eq!(
    ///     &format!("{:?}", edge.display(EDF::VerticesTupleAndCurve { vertex_format })),
    ///     "Edge { vertices: (0, 1), entity: 2 }",
    /// );
    /// assert_eq!(
    ///     &format!("{:?}", edge.display(EDF::VerticesTupleStruct { vertex_format })),
    ///     "Edge(0, 1)",
    /// );
    /// assert_eq!(
    ///     &format!("{:?}", edge.display(EDF::VerticesTuple { vertex_format })),
    ///     "(0, 1)",
    /// );
    /// assert_eq!(
    ///     &format!("{:?}", edge.display(EDF::AsCurve)),
    ///     "2",
    /// );
    /// ```
    #[inline(always)]
    pub fn display(&self, format: EdgeDisplayFormat) -> DebugDisplay<'_, Self, EdgeDisplayFormat> {
        DebugDisplay {
            entity: self,
            format,
        }
    }
}

/// Error for concat
#[derive(Clone, Debug, Error)]
pub enum ConcatError<P: Debug> {
    /// Failed to concat edges since the end point of the first curve is different from the start point of the second curve.
    #[error("The end point {0:?} of the first curve is different from the start point {1:?} of the second curve.")]
    DisconnectedVertex(Vertex<P>, Vertex<P>),
    #[error("The end vertices are the same vertex {0:?}.")]
    SameVertex(Vertex<P>),
    /// From geometric error.
    #[error("{0}")]
    FromGeometry(truck_geotrait::ConcatError<P>),
}

impl<P: Debug> From<truck_geotrait::ConcatError<P>> for ConcatError<P> {
    fn from(err: truck_geotrait::ConcatError<P>) -> ConcatError<P> {
        ConcatError::FromGeometry(err)
    }
}

impl<P, C> Clone for Edge<P, C> {
    #[inline(always)]
    fn clone(&self) -> Edge<P, C> {
        Edge {
            vertices: self.vertices.clone(),
            orientation: self.orientation,
            curve: Arc::clone(&self.curve),
        }
    }
}

impl<P, C> PartialEq for Edge<P, C> {
    #[inline(always)]
    fn eq(&self, other: &Self) -> bool {
        std::ptr::eq(Arc::as_ptr(&self.curve), Arc::as_ptr(&other.curve))
            && self.orientation == other.orientation
    }
}

impl<P, C> Eq for Edge<P, C> {}

impl<P, C> Hash for Edge<P, C> {
    #[inline(always)]
    fn hash<H: Hasher>(&self, state: &mut H) {
        std::ptr::hash(Arc::as_ptr(&self.curve), state);
        self.orientation.hash(state);
    }
}

impl<'a, P: Debug, C: Debug> Debug for DebugDisplay<'a, Edge<P, C>, EdgeDisplayFormat> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self.format {
            EdgeDisplayFormat::Full { vertex_format } => f
                .debug_struct("Edge")
                .field("id", &Arc::as_ptr(&self.entity.curve))
                .field(
                    "vertices",
                    &(
                        self.entity.front().display(vertex_format),
                        self.entity.back().display(vertex_format),
                    ),
                )
                .field("entity", &MutexFmt(&self.entity.curve))
                .finish(),
            EdgeDisplayFormat::VerticesTupleAndID { vertex_format } => f
                .debug_struct("Edge")
                .field("id", &self.entity.id())
                .field(
                    "vertices",
                    &(
                        self.entity.front().display(vertex_format),
                        self.entity.back().display(vertex_format),
                    ),
                )
                .finish(),
            EdgeDisplayFormat::VerticesTupleAndCurve { vertex_format } => f
                .debug_struct("Edge")
                .field(
                    "vertices",
                    &(
                        self.entity.front().display(vertex_format),
                        self.entity.back().display(vertex_format),
                    ),
                )
                .field("entity", &MutexFmt(&self.entity.curve))
                .finish(),
            EdgeDisplayFormat::VerticesTupleStruct { vertex_format } => f
                .debug_tuple("Edge")
                .field(&self.entity.front().display(vertex_format))
                .field(&self.entity.back().display(vertex_format))
                .finish(),
            EdgeDisplayFormat::VerticesTuple { vertex_format } => f.write_fmt(format_args!(
                "({:?}, {:?})",
                self.entity.front().display(vertex_format),
                self.entity.back().display(vertex_format),
            )),
            EdgeDisplayFormat::AsCurve => {
                f.write_fmt(format_args!("{:?}", &MutexFmt(&self.entity.curve)))
            }
        }
    }
More examples
Hide additional examples
src/face.rs (line 703)
699
700
701
702
703
704
705
706
707
    pub fn border_on(&self, other: &Face<P, C, S>) -> bool {
        let mut hashmap = HashMap::default();
        let edge_iter = self.boundary_iters().into_iter().flatten();
        edge_iter.for_each(|edge| {
            hashmap.insert(edge.id(), edge);
        });
        let mut edge_iter = other.boundary_iters().into_iter().flatten();
        edge_iter.any(|edge| hashmap.insert(edge.id(), edge).is_some())
    }
src/compress.rs (line 123)
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
    fn get_eid(&mut self, edge: &Edge<P, C>) -> CompressedEdgeIndex {
        match self.emap.get(&edge.id()) {
            Some(got) => (got.0, edge.orientation()).into(),
            None => {
                let id = self.emap.len();
                let front_id = self.get_vid(edge.absolute_front());
                let back_id = self.get_vid(edge.absolute_back());
                let curve = edge.get_curve();
                let cedge = CompressedEdge {
                    vertices: (front_id, back_id),
                    curve,
                };
                self.emap.insert(edge.id(), (id, cedge));
                (id, edge.orientation()).into()
            }
        }
    }

    #[inline(always)]
    fn create_boundary(&mut self, boundary: &Wire<P, C>) -> Vec<CompressedEdgeIndex> {
        boundary.iter().map(|edge| self.get_eid(edge)).collect()
    }

    #[inline(always)]
    fn create_cface<S: Clone>(&mut self, face: &Face<P, C, S>) -> CompressedFace<S> {
        CompressedFace {
            boundaries: face
                .boundaries
                .iter()
                .map(|wire| self.create_boundary(wire))
                .collect(),
            orientation: face.orientation(),
            surface: face.get_surface(),
        }
    }

    #[inline(always)]
    fn map2vec<K, T>(map: HashMap<K, (usize, T)>) -> Vec<T> {
        let mut vec: Vec<_> = map.into_iter().map(|entry| entry.1).collect();
        vec.sort_by(|x, y| x.0.cmp(&y.0));
        vec.into_iter().map(|x| x.1).collect()
    }

    #[inline(always)]
    fn vertices_edges(self) -> (Vec<P>, Vec<CompressedEdge<C>>) {
        (Self::map2vec(self.vmap), Self::map2vec(self.emap))
    }
}

impl<P: Clone, C: Clone, S: Clone> Shell<P, C, S> {
    /// Compresses the shell into the serialized compressed shell.
    pub fn compress(&self) -> CompressedShell<P, C, S> {
        let mut director = CompressDirector::new();
        let mut face_closure = |face: &Face<P, C, S>| director.create_cface(face);
        let faces = self.iter().map(&mut face_closure).collect();
        let (vertices, edges) = director.vertices_edges();
        CompressedShell {
            vertices,
            edges,
            faces,
        }
    }

    /// Extracts the serialized compressed shell into the shell.
    pub fn extract(cshell: CompressedShell<P, C, S>) -> Result<Self> {
        let CompressedShell {
            vertices,
            edges,
            faces,
        } = cshell;
        let vertices: Vec<_> = vertices.into_iter().map(Vertex::new).collect();
        let edges = edges
            .into_iter()
            .map(move |edge| edge.create_edge(&vertices))
            .collect::<Result<Vec<_>>>()?;
        faces
            .into_iter()
            .map(move |face| face.create_face(&edges))
            .collect()
    }
}

impl<P: Clone, C: Clone, S: Clone> Solid<P, C, S> {
    /// Compresses the solid into the serialized compressed solid.
    pub fn compress(&self) -> CompressedSolid<P, C, S> {
        CompressedSolid {
            boundaries: self
                .boundaries()
                .iter()
                .map(|shell| shell.compress())
                .collect(),
        }
    }

    /// Extracts the serialized compressed shell into the shell.
    pub fn extract(csolid: CompressedSolid<P, C, S>) -> Result<Self> {
        let shells: Result<Vec<Shell<P, C, S>>> =
            csolid.boundaries.into_iter().map(Shell::extract).collect();
        Solid::try_new(shells?)
    }
}

// -------------------------- test -------------------------- //

#[test]
fn compress_extract() {
    let cube = solid::cube();
    let shell0 = &cube.boundaries()[0];
    let shell1 = Shell::extract(shell0.compress()).unwrap();
    assert!(same_topology(shell0, &shell1));
}

#[allow(dead_code)]
fn vmap_subroutin<P, Q>(
    v0: &Vertex<P>,
    v1: &Vertex<Q>,
    vmap: &mut HashMap<VertexID<P>, VertexID<Q>>,
) -> bool {
    match vmap.get(&v0.id()) {
        Some(got) => *got == v1.id(),
        None => {
            vmap.insert(v0.id(), v1.id());
            true
        }
    }
}

#[allow(dead_code)]
fn emap_subroutin<P, Q, C, D>(
    edge0: &Edge<P, C>,
    edge1: &Edge<Q, D>,
    vmap: &mut HashMap<VertexID<P>, VertexID<Q>>,
    emap: &mut HashMap<EdgeID<C>, EdgeID<D>>,
) -> bool {
    match emap.get(&edge0.id()) {
        Some(got) => *got == edge1.id(),
        None => {
            emap.insert(edge0.id(), edge1.id());
            vmap_subroutin(edge0.front(), edge1.front(), vmap)
                && vmap_subroutin(edge0.back(), edge1.back(), vmap)
        }
    }
}
src/shell.rs (line 155)
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
    pub fn extract_boundaries(&self) -> Vec<Wire<P, C>> {
        let boundaries: Boundaries<C> = self.edge_iter().collect();
        let mut vemap: HashMap<_, _> = self
            .edge_iter()
            .filter_map(|edge| {
                boundaries
                    .boundaries
                    .get(&edge.id())
                    .map(|_| (edge.front().id(), edge.clone()))
            })
            .collect();
        let mut res = Vec::new();
        while let Some(edge) = vemap.values().next() {
            if let Some(mut cursor) = vemap.remove(&edge.front().id()) {
                let mut wire = Wire::from(vec![cursor.clone()]);
                loop {
                    cursor = match vemap.remove(&cursor.back().id()) {
                        None => break,
                        Some(got) => {
                            wire.push_back(got.clone());
                            got.clone()
                        }
                    };
                }
                res.push(wire);
            }
        }
        res
    }

    /// Returns the adjacency matrix of vertices in the shell.
    ///
    /// For the returned hashmap `map` and each vertex `v`,
    /// the vector `map[&v]` cosists all vertices which is adjacent to `v`.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use std::collections::HashSet;
    /// let v = Vertex::news(&[(); 4]);
    /// let edge = [
    ///     Edge::new(&v[0], &v[2], ()),
    ///     Edge::new(&v[0], &v[3], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[1], &v[3], ()),
    ///     Edge::new(&v[2], &v[3], ()),
    /// ];
    /// let wire = vec![
    ///     Wire::from_iter(vec![&edge[0], &edge[4], &edge[1].inverse()]),
    ///     Wire::from_iter(vec![&edge[2], &edge[4], &edge[3].inverse()]),
    /// ];
    /// let shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
    /// let adjacency = shell.vertex_adjacency();
    /// let v0_ads_vec = adjacency.get(&v[0].id()).unwrap();
    /// let v0_ads: HashSet<&VertexID<()>> = HashSet::from_iter(v0_ads_vec);
    /// assert_eq!(v0_ads, HashSet::from_iter(vec![&v[2].id(), &v[3].id()]));
    /// ```
    pub fn vertex_adjacency(&self) -> HashMap<VertexID<P>, Vec<VertexID<P>>> {
        let mut adjacency = EntryMap::new(|x| x, |_| Vec::new());
        let mut done_edge: HashSet<EdgeID<C>> = HashSet::default();
        self.edge_iter().for_each(|edge| {
            if done_edge.insert(edge.id()) {
                let v0 = edge.front().id();
                let v1 = edge.back().id();
                adjacency.entry_or_insert(v0).push(v1);
                adjacency.entry_or_insert(v1).push(v0);
            }
        });
        adjacency.into()
    }

    /// Returns the adjacency matrix of faces in the shell.
    ///
    /// For the returned hashmap `map` and each face `face`,
    /// the vector `map[&face]` consists all faces adjacent to `face`.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use truck_topology::shell::ShellCondition;
    /// let v = Vertex::news(&[(); 6]);
    /// let edge = [
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[0], &v[2], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[1], &v[3], ()),
    ///     Edge::new(&v[1], &v[4], ()),
    ///     Edge::new(&v[2], &v[4], ()),
    ///     Edge::new(&v[2], &v[5], ()),
    ///     Edge::new(&v[3], &v[4], ()),
    ///     Edge::new(&v[4], &v[5], ()),
    /// ];
    /// let wire = vec![
    ///     Wire::from_iter(vec![&edge[0], &edge[2], &edge[1].inverse()]),
    ///     Wire::from_iter(vec![&edge[3], &edge[7], &edge[4].inverse()]),
    ///     Wire::from_iter(vec![&edge[5], &edge[8], &edge[6].inverse()]),
    ///     Wire::from_iter(vec![&edge[2].inverse(), &edge[4], &edge[5].inverse()]),
    /// ];
    /// let shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
    /// let face_adjacency = shell.face_adjacency();
    /// assert_eq!(face_adjacency[&shell[0]].len(), 1);
    /// assert_eq!(face_adjacency[&shell[1]].len(), 1);
    /// assert_eq!(face_adjacency[&shell[2]].len(), 1);
    /// assert_eq!(face_adjacency[&shell[3]].len(), 3);
    /// ```
    pub fn face_adjacency(&self) -> FaceAdjacencyMap<'_, P, C, S> {
        let mut adjacency = EntryMap::new(|x| x, |_| Vec::new());
        let mut edge_face_map = EntryMap::new(|x| x, |_| Vec::new());
        self.face_iter().for_each(|face| {
            face.absolute_boundaries()
                .iter()
                .flatten()
                .for_each(|edge| {
                    let vec = edge_face_map.entry_or_insert(edge.id());
                    adjacency.entry_or_insert(face).extend(vec.iter().copied());
                    vec.iter().for_each(|tmp| {
                        adjacency.entry_or_insert(*tmp).push(face);
                    });
                    vec.push(face);
                });
        });
        adjacency.into()
    }

    /// Returns whether the shell is connected or not.
    /// # Examples
    /// ```
    /// // The empty shell is connected.
    /// use truck_topology::*;
    /// assert!(Shell::<(), (), ()>::new().is_connected());
    /// ```
    /// ```
    /// // An example of a connected shell
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 4]);
    /// let shared_edge = Edge::new(&v[1], &v[2], ());
    /// let wire0 = Wire::from_iter(vec![
    ///     &Edge::new(&v[0], &v[1], ()),
    ///     &shared_edge,
    ///     &Edge::new(&v[2], &v[0], ()),
    /// ]);
    /// let face0 = Face::new(vec![wire0], ());
    /// let wire1 = Wire::from_iter(vec![
    ///     &Edge::new(&v[3], &v[1], ()),
    ///     &shared_edge,
    ///     &Edge::new(&v[2], &v[3], ()),
    /// ]);
    /// let face1 = Face::new(vec![wire1], ());
    /// let shell: Shell<_, _, _> = vec![face0, face1].into();
    /// assert!(shell.is_connected());
    /// ```
    /// ```
    /// // An example of a non-connected shell
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 6]);
    /// let wire0 = Wire::from_iter(vec![
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[2], &v[0], ())
    /// ]);
    /// let face0 = Face::new(vec![wire0], ());
    /// let wire1 = Wire::from_iter(vec![
    ///     &Edge::new(&v[3], &v[4], ()),
    ///     &Edge::new(&v[4], &v[5], ()),
    ///     &Edge::new(&v[5], &v[3], ())
    /// ]);
    /// let face1 = Face::new(vec![wire1], ());
    /// let shell: Shell<_, _, _> = vec![face0, face1].into();
    /// assert!(!shell.is_connected());
    /// ```
    pub fn is_connected(&self) -> bool {
        let mut adjacency = self.vertex_adjacency();
        // Connecting another boundary of the same face with an edge
        for face in self {
            for wire in face.boundaries.windows(2) {
                let v0 = wire[0].front_vertex().unwrap();
                let v1 = wire[1].front_vertex().unwrap();
                adjacency.get_mut(&v0.id()).unwrap().push(v1.id());
                adjacency.get_mut(&v1.id()).unwrap().push(v0.id());
            }
        }
        check_connectivity(&mut adjacency)
    }

    /// Returns a vector consisting of shells of each connected components.
    /// # Examples
    /// ```
    /// use truck_topology::Shell;
    /// // The empty shell has no connected component.
    /// assert!(Shell::<(), (), ()>::new().connected_components().is_empty());
    /// ```
    /// # Remarks
    /// Since this method uses the face adjacency matrix, multiple components
    /// are perhaps generated even if the shell is connected. In that case,
    /// there is a pair of faces such that share vertices but not edges.
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[(); 5]);
    /// let wire0 = Wire::from_iter(vec![
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[2], &v[0], ()),
    /// ]);
    /// let wire1 = Wire::from_iter(vec![
    ///     Edge::new(&v[0], &v[3], ()),
    ///     Edge::new(&v[3], &v[4], ()),
    ///     Edge::new(&v[4], &v[0], ()),
    /// ]);
    /// let shell = Shell::from(vec![
    ///     Face::new(vec![wire0], ()),
    ///     Face::new(vec![wire1], ()),
    /// ]);
    /// assert!(shell.is_connected());
    /// assert_eq!(shell.connected_components().len(), 2);
    /// ```
    pub fn connected_components(&self) -> Vec<Shell<P, C, S>> {
        let mut adjacency = self.face_adjacency();
        let components = create_components(&mut adjacency);
        components
            .into_iter()
            .map(|vec| vec.into_iter().cloned().collect())
            .collect()
    }

    /// Returns the vector of all singular vertices.
    ///
    /// Here, we say that a vertex is singular if, for a sufficiently small neighborhood U of
    /// the vertex, the set U - {the vertex} is not connected.
    ///
    /// A regular, oriented, or closed shell becomes a manifold if and only if the shell has
    /// no singular vertices.
    /// # Examples
    /// ```
    /// // A regular manifold: Mobius bundle
    /// use truck_topology::*;
    /// use truck_topology::shell::ShellCondition;
    ///
    /// let v = Vertex::news(&[(), (), (), ()]);
    /// let edge = [
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[2], &v[0], ()),
    ///     Edge::new(&v[1], &v[3], ()),
    ///     Edge::new(&v[3], &v[2], ()),
    ///     Edge::new(&v[0], &v[3], ()),
    /// ];
    /// let wire = vec![
    ///     Wire::from_iter(vec![&edge[0], &edge[3], &edge[4], &edge[2]]),
    ///     Wire::from_iter(vec![&edge[1], &edge[2], &edge[5], &edge[3].inverse()]),
    /// ];
    /// let shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
    /// assert_eq!(shell.shell_condition(), ShellCondition::Regular);
    /// assert!(shell.singular_vertices().is_empty());
    /// ```
    /// ```
    /// // A closed and connected shell which has a singular vertex.
    /// use truck_topology::*;
    /// use truck_topology::shell::*;
    ///
    /// let v = Vertex::news(&[(); 7]);
    /// let edge = [
    ///     Edge::new(&v[0], &v[1], ()), // 0
    ///     Edge::new(&v[0], &v[2], ()), // 1
    ///     Edge::new(&v[0], &v[3], ()), // 2
    ///     Edge::new(&v[1], &v[2], ()), // 3
    ///     Edge::new(&v[2], &v[3], ()), // 4
    ///     Edge::new(&v[3], &v[1], ()), // 5
    ///     Edge::new(&v[0], &v[4], ()), // 6
    ///     Edge::new(&v[0], &v[5], ()), // 7
    ///     Edge::new(&v[0], &v[6], ()), // 8
    ///     Edge::new(&v[4], &v[5], ()), // 9
    ///     Edge::new(&v[5], &v[6], ()), // 10
    ///     Edge::new(&v[6], &v[4], ()), // 11
    /// ];
    /// let wire = vec![
    ///     Wire::from_iter(vec![&edge[0].inverse(), &edge[1], &edge[3].inverse()]),
    ///     Wire::from_iter(vec![&edge[1].inverse(), &edge[2], &edge[4].inverse()]),
    ///     Wire::from_iter(vec![&edge[2].inverse(), &edge[0], &edge[5].inverse()]),
    ///     Wire::from_iter(vec![&edge[3], &edge[4], &edge[5]]),
    ///     Wire::from_iter(vec![&edge[6].inverse(), &edge[7], &edge[9].inverse()]),
    ///     Wire::from_iter(vec![&edge[7].inverse(), &edge[8], &edge[10].inverse()]),
    ///     Wire::from_iter(vec![&edge[8].inverse(), &edge[6], &edge[11].inverse()]),
    ///     Wire::from_iter(vec![&edge[9], &edge[10], &edge[11]]),
    /// ];
    /// let shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
    /// assert_eq!(shell.shell_condition(), ShellCondition::Closed);
    /// assert!(shell.is_connected());
    /// assert_eq!(shell.singular_vertices(), vec![v[0].clone()]);
    /// ```
    pub fn singular_vertices(&self) -> Vec<Vertex<P>> {
        let mut vert_wise_adjacency =
            EntryMap::new(Vertex::clone, |_| EntryMap::new(Edge::id, |_| Vec::new()));
        self.face_iter()
            .flat_map(Face::absolute_boundaries)
            .for_each(|wire| {
                let first_edge = &wire[0];
                let mut edge_iter = wire.iter().peekable();
                while let Some(edge) = edge_iter.next() {
                    let adjacency = vert_wise_adjacency.entry_or_insert(edge.back());
                    let next_edge = *edge_iter.peek().unwrap_or(&first_edge);
                    adjacency.entry_or_insert(edge).push(next_edge.id());
                    adjacency.entry_or_insert(next_edge).push(edge.id());
                }
            });
        vert_wise_adjacency
            .into_iter()
            .filter_map(|(vertex, adjacency)| {
                Some(vertex).filter(|_| !check_connectivity(&mut adjacency.into()))
            })
            .collect()
    }

    /// Returns a new shell whose surfaces are mapped by `surface_mapping`,
    /// curves are mapped by `curve_mapping` and points are mapped by `point_mapping`.
    /// # Remarks
    /// Accessing geometry elements directly in the closure will result in a deadlock.
    /// So, this method does not appear to the document.
    #[doc(hidden)]
    pub fn try_mapped<Q, D, T>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Option<Q>,
        mut curve_mapping: impl FnMut(&C) -> Option<D>,
        mut surface_mapping: impl FnMut(&S) -> Option<T>,
    ) -> Option<Shell<Q, D, T>> {
        let mut vertex_map = EntryMap::new(Vertex::id, move |v| v.try_mapped(&mut point_mapping));
        let mut edge_map = EntryMap::new(
            Edge::id,
            wire::edge_entry_map_try_closure(&mut vertex_map, &mut curve_mapping),
        );
        self.face_iter()
            .map(|face| {
                let wires = face
                    .absolute_boundaries()
                    .iter()
                    .map(|wire| wire.sub_try_mapped(&mut edge_map))
                    .collect::<Option<Vec<_>>>()?;
                let surface = surface_mapping(&*face.surface.lock().unwrap())?;
                let mut new_face = Face::debug_new(wires, surface);
                if !face.orientation() {
                    new_face.invert();
                }
                Some(new_face)
            })
            .collect()
    }

    /// Returns a new shell whose surfaces are mapped by `surface_mapping`,
    /// curves are mapped by `curve_mapping` and points are mapped by `point_mapping`.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// let v = Vertex::news(&[0, 1, 2, 3, 4, 5, 6]);
    /// let wire0 = Wire::from(vec![
    ///     Edge::new(&v[0], &v[1], 100),
    ///     Edge::new(&v[1], &v[2], 200),
    ///     Edge::new(&v[2], &v[3], 300),
    ///     Edge::new(&v[3], &v[0], 400),
    /// ]);
    /// let wire1 = Wire::from(vec![
    ///     Edge::new(&v[4], &v[5], 500),
    ///     Edge::new(&v[6], &v[5], 600).inverse(),
    ///     Edge::new(&v[6], &v[4], 700),
    /// ]);
    /// let face0 = Face::new(vec![wire0, wire1], 10000);
    /// let face1 = face0.mapped(
    ///     &move |i: &usize| *i + 7,
    ///     &move |j: &usize| *j + 700,
    ///     &move |k: &usize| *k + 10000,
    /// );
    /// let shell0 = Shell::from(vec![face0, face1.inverse()]);
    /// let shell1 = shell0.mapped(
    ///     &move |i: &usize| *i + 50,
    ///     &move |j: &usize| *j + 5000,
    ///     &move |k: &usize| *k + 500000,
    /// );
    /// # for face in shell1.face_iter() {
    /// #    for bdry in face.absolute_boundaries() {
    /// #        assert!(bdry.is_closed());
    /// #        assert!(bdry.is_simple());
    /// #    }
    /// # }
    ///
    /// for (face0, face1) in shell0.face_iter().zip(shell1.face_iter()) {
    ///     assert_eq!(
    ///         face0.get_surface() + 500000,
    ///         face1.get_surface(),
    ///     );
    ///     assert_eq!(face0.orientation(), face1.orientation());
    ///     let biters0 = face0.boundary_iters();
    ///     let biters1 = face1.boundary_iters();
    ///     for (biter0, biter1) in biters0.into_iter().zip(biters1) {
    ///         for (edge0, edge1) in biter0.zip(biter1) {
    ///             assert_eq!(
    ///                 edge0.front().get_point() + 50,
    ///                 edge1.front().get_point(),
    ///             );
    ///             assert_eq!(
    ///                 edge0.back().get_point() + 50,
    ///                 edge1.back().get_point(),
    ///             );
    ///             assert_eq!(
    ///                 edge0.get_curve() + 5000,
    ///                 edge1.get_curve(),
    ///             );
    ///         }
    ///     }
    /// }
    /// ```
    /// # Remarks
    /// Accessing geometry elements directly in the closure will result in a deadlock.
    /// So, this method does not appear to the document.
    #[doc(hidden)]
    pub fn mapped<Q, D, T>(
        &self,
        mut point_mapping: impl FnMut(&P) -> Q,
        mut curve_mapping: impl FnMut(&C) -> D,
        mut surface_mapping: impl FnMut(&S) -> T,
    ) -> Shell<Q, D, T> {
        let mut vertex_map = EntryMap::new(Vertex::id, |v| v.mapped(&mut point_mapping));
        let mut edge_map = EntryMap::new(
            Edge::id,
            wire::edge_entry_map_closure(&mut vertex_map, &mut curve_mapping),
        );
        self.face_iter()
            .map(|face| {
                let wires: Vec<Wire<_, _>> = face
                    .absolute_boundaries()
                    .iter()
                    .map(|wire| wire.sub_mapped(&mut edge_map))
                    .collect();
                let surface = surface_mapping(&*face.surface.lock().unwrap());
                let mut new_face = Face::debug_new(wires, surface);
                if !face.orientation() {
                    new_face.invert();
                }
                new_face
            })
            .collect()
    }

    /// Returns the consistence of the geometry of end vertices
    /// and the geometry of edge.
    #[inline(always)]
    pub fn is_geometric_consistent(&self) -> bool
    where
        P: Tolerance,
        C: BoundedCurve<Point = P>,
        S: IncludeCurve<C>, {
        self.iter().all(|face| face.is_geometric_consistent())
    }

    /// Cuts one edge into two edges at vertex.
    ///
    /// # Returns
    /// Returns the tuple of new edges created by cutting the edge.
    ///
    /// # Failures
    /// Returns `None` and not edit `self` if:
    /// - there is no edge corresponding to `edge_id` in the shell,
    /// - `vertex` is already included in the shell, or
    /// - cutting of edge fails.
    pub fn cut_edge(
        &mut self,
        edge_id: EdgeID<C>,
        vertex: &Vertex<P>,
    ) -> Option<(Edge<P, C>, Edge<P, C>)>
    where
        P: Clone,
        C: Cut<Point = P> + SearchParameter<D1, Point = P>,
    {
        if self.vertex_iter().any(|v| &v == vertex) {
            return None;
        }
        let mut edges = None;
        self.iter_mut()
            .flat_map(|face| face.boundaries.iter_mut())
            .try_for_each(|wire| {
                let find_res = wire
                    .iter()
                    .enumerate()
                    .find(|(_, edge)| edge.id() == edge_id);
                let (idx, edge) = match find_res {
                    Some(got) => got,
                    None => return Some(()),
                };
                if edges.is_none() {
                    edges = Some(edge.absolute_clone().cut(vertex)?);
                }
                let edges = edges.as_ref().unwrap();
                let new_wire = match edge.orientation() {
                    true => Wire::from(vec![edges.0.clone(), edges.1.clone()]),
                    false => Wire::from(vec![edges.1.inverse(), edges.0.inverse()]),
                };
                let flag = wire.swap_edge_into_wire(idx, new_wire);
                debug_assert!(flag);
                Some(())
            });
        edges
    }
    /// Removes `vertex` from `self` by concat two edges on both sides.
    ///
    /// # Returns
    /// Returns the new created edge.
    ///
    /// # Failures
    /// Returns `None` if:
    /// - there are no vertex corresponding to `vertex_id` in the shell,
    /// - the vertex is included more than 2 face boundaries,
    /// - the vertex is included more than 2 edges, or
    /// - concating edges is failed.
    pub fn remove_vertex_by_concat_edges(&mut self, vertex_id: VertexID<P>) -> Option<Edge<P, C>>
    where
        P: Debug,
        C: Concat<C, Point = P, Output = C> + Invertible + ParameterTransform, {
        let mut vec: Vec<(&mut Wire<P, C>, usize)> = self
            .face_iter_mut()
            .flat_map(|face| &mut face.boundaries)
            .filter_map(|wire| {
                let idx = wire
                    .edge_iter()
                    .enumerate()
                    .find(|(_, e)| e.back().id() == vertex_id)?
                    .0;
                Some((wire, idx))
            })
            .collect();
        if vec.len() > 2 || vec.is_empty() {
            None
        } else if vec.len() == 1 {
            let (wire, idx) = vec.pop().unwrap();
            let edge = wire[idx].concat(&wire[(idx + 1) % wire.len()]).ok()?;
            wire.swap_subwire_into_edges(idx, edge.clone());
            Some(edge)
        } else {
            let (wire0, idx0) = vec.pop().unwrap();
            let (wire1, idx1) = vec.pop().unwrap();
            if !wire0[idx0].is_same(&wire1[(idx1 + 1) % wire1.len()])
                || !wire0[(idx0 + 1) % wire0.len()].is_same(&wire1[idx1])
            {
                return None;
            }
            let edge = wire0[idx0].concat(&wire0[(idx0 + 1) % wire0.len()]).ok()?;
            wire1.swap_subwire_into_edges(idx1, edge.inverse());
            wire0.swap_subwire_into_edges(idx0, edge.clone());
            Some(edge)
        }
    }

    /// Creates display struct for debugging the shell.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use truck_topology::shell::ShellCondition;
    /// use ShellDisplayFormat as SDF;
    ///
    /// let v = Vertex::news(&[0, 1, 2, 3]);
    /// let edge = [
    ///     Edge::new(&v[0], &v[1], ()), // 0
    ///     Edge::new(&v[1], &v[2], ()), // 1
    ///     Edge::new(&v[2], &v[0], ()), // 2
    ///     Edge::new(&v[1], &v[3], ()), // 3
    ///     Edge::new(&v[3], &v[2], ()), // 4
    ///     Edge::new(&v[0], &v[3], ()), // 5
    /// ];
    /// let wire = vec![
    ///     Wire::from_iter(vec![&edge[0], &edge[3], &edge[4], &edge[2]]),
    ///     Wire::from_iter(vec![&edge[1], &edge[2], &edge[5], &edge[3].inverse()]),
    /// ];
    /// let shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
    ///
    /// let vertex_format = VertexDisplayFormat::AsPoint;
    /// let edge_format = EdgeDisplayFormat::VerticesTuple { vertex_format };
    /// let wire_format = WireDisplayFormat::EdgesList { edge_format };
    /// let face_format = FaceDisplayFormat::LoopsListTuple { wire_format };
    ///
    /// assert_eq!(
    ///     &format!("{:?}", shell.display(SDF::FacesListTuple {face_format})),
    ///     "Shell([Face([[(0, 1), (1, 3), (3, 2), (2, 0)]]), Face([[(1, 2), (2, 0), (0, 3), (3, 1)]])])",
    /// );
    /// assert_eq!(
    ///     &format!("{:?}", shell.display(SDF::FacesList {face_format})),
    ///     "[Face([[(0, 1), (1, 3), (3, 2), (2, 0)]]), Face([[(1, 2), (2, 0), (0, 3), (3, 1)]])]",
    /// );
    /// ```
    pub fn display(
        &self,
        format: ShellDisplayFormat,
    ) -> DebugDisplay<'_, Self, ShellDisplayFormat> {
        DebugDisplay {
            entity: self,
            format,
        }
    }
}

impl<P, C, S> Clone for Shell<P, C, S> {
    #[inline(always)]
    fn clone(&self) -> Shell<P, C, S> {
        Shell {
            face_list: self.face_list.clone(),
        }
    }
}

impl<P, C, S> From<Shell<P, C, S>> for Vec<Face<P, C, S>> {
    #[inline(always)]
    fn from(shell: Shell<P, C, S>) -> Vec<Face<P, C, S>> { shell.face_list }
}

impl<P, C, S> From<Vec<Face<P, C, S>>> for Shell<P, C, S> {
    #[inline(always)]
    fn from(faces: Vec<Face<P, C, S>>) -> Shell<P, C, S> { Shell { face_list: faces } }
}

impl<P, C, S> FromIterator<Face<P, C, S>> for Shell<P, C, S> {
    #[inline(always)]
    fn from_iter<I: IntoIterator<Item = Face<P, C, S>>>(iter: I) -> Shell<P, C, S> {
        Shell {
            face_list: iter.into_iter().collect(),
        }
    }
}

impl<P, C, S> IntoIterator for Shell<P, C, S> {
    type Item = Face<P, C, S>;
    type IntoIter = std::vec::IntoIter<Face<P, C, S>>;
    #[inline(always)]
    fn into_iter(self) -> Self::IntoIter { self.face_list.into_iter() }
}

impl<'a, P, C, S> IntoIterator for &'a Shell<P, C, S> {
    type Item = &'a Face<P, C, S>;
    type IntoIter = std::slice::Iter<'a, Face<P, C, S>>;
    #[inline(always)]
    fn into_iter(self) -> Self::IntoIter { self.face_list.iter() }
}

impl<P, C, S> std::ops::Deref for Shell<P, C, S> {
    type Target = Vec<Face<P, C, S>>;
    #[inline(always)]
    fn deref(&self) -> &Vec<Face<P, C, S>> { &self.face_list }
}

impl<P, C, S> std::ops::DerefMut for Shell<P, C, S> {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut Vec<Face<P, C, S>> { &mut self.face_list }
}

impl<P, C, S> Default for Shell<P, C, S> {
    #[inline(always)]
    fn default() -> Self {
        Self {
            face_list: Vec::new(),
        }
    }
}

impl<P, C, S> PartialEq for Shell<P, C, S> {
    fn eq(&self, other: &Self) -> bool { self.face_list == other.face_list }
}

impl<P, C, S> Eq for Shell<P, C, S> {}

/// The reference iterator over all faces in shells
pub type FaceIter<'a, P, C, S> = std::slice::Iter<'a, Face<P, C, S>>;
/// The mutable reference iterator over all faces in shells
pub type FaceIterMut<'a, P, C, S> = std::slice::IterMut<'a, Face<P, C, S>>;
/// The into iterator over all faces in shells
pub type FaceIntoIter<P, C, S> = std::vec::IntoIter<Face<P, C, S>>;
/// The reference parallel iterator over all faces in shells
pub type FaceParallelIter<'a, P, C, S> = <Vec<Face<P, C, S>> as IntoParallelRefIterator<'a>>::Iter;
/// The mutable reference parallel iterator over all faces in shells
pub type FaceParallelIterMut<'a, P, C, S> =
    <Vec<Face<P, C, S>> as IntoParallelRefMutIterator<'a>>::Iter;
/// The into parallel iterator over all faces in shells
pub type FaceParallelIntoIter<P, C, S> = <Vec<Face<P, C, S>> as IntoParallelIterator>::Iter;

/// The shell conditions being determined by the half-edge model.
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum ShellCondition {
    /// This shell is not regular.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use truck_topology::shell::ShellCondition;
    /// let v = Vertex::news(&[(); 5]);
    /// let edge = [
    ///    Edge::new(&v[0], &v[1], ()),
    ///    Edge::new(&v[0], &v[2], ()),
    ///    Edge::new(&v[0], &v[3], ()),
    ///    Edge::new(&v[0], &v[4], ()),
    ///    Edge::new(&v[1], &v[2], ()),
    ///    Edge::new(&v[1], &v[3], ()),
    ///    Edge::new(&v[1], &v[4], ()),
    /// ];
    /// let wire = vec![
    ///    Wire::from_iter(vec![&edge[0], &edge[4], &edge[1].inverse()]),
    ///    Wire::from_iter(vec![&edge[0], &edge[5], &edge[2].inverse()]),
    ///    Wire::from_iter(vec![&edge[0], &edge[6], &edge[3].inverse()]),
    /// ];
    /// let shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
    /// // The shell is irregular because three faces share edge[0].
    /// assert_eq!(shell.shell_condition(), ShellCondition::Irregular);
    /// ```
    Irregular,
    /// All edges are shared by at most two faces.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use truck_topology::shell::ShellCondition;
    /// let v = Vertex::news(&[(); 6]);
    /// let edge = [
    ///     Edge::new(&v[0], &v[1], ()),
    ///     Edge::new(&v[0], &v[2], ()),
    ///     Edge::new(&v[1], &v[2], ()),
    ///     Edge::new(&v[1], &v[3], ()),
    ///     Edge::new(&v[1], &v[4], ()),
    ///     Edge::new(&v[2], &v[4], ()),
    ///     Edge::new(&v[2], &v[5], ()),
    ///     Edge::new(&v[3], &v[4], ()),
    ///     Edge::new(&v[4], &v[5], ()),
    /// ];
    /// let wire = vec![
    ///     Wire::from_iter(vec![&edge[0], &edge[2], &edge[1].inverse()]),
    ///     Wire::from_iter(vec![&edge[3], &edge[7], &edge[4].inverse()]),
    ///     Wire::from_iter(vec![&edge[5], &edge[8], &edge[6].inverse()]),
    ///     Wire::from_iter(vec![&edge[2], &edge[5], &edge[4].inverse()]),
    /// ];
    /// let shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
    /// // This shell is regular, but not oriented.
    /// // It is because the orientations of shell[0] and shell[3] are incompatible on edge[2].
    /// assert_eq!(shell.shell_condition(), ShellCondition::Regular);
    /// ```
    Regular,
    /// The orientations of faces are compatible.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use truck_topology::shell::ShellCondition;
    /// let v = Vertex::news(&[(); 6]);
    /// let edge = [
    ///     Edge::new(&v[0], &v[1] ,()),
    ///     Edge::new(&v[0], &v[2] ,()),
    ///     Edge::new(&v[1], &v[2] ,()),
    ///     Edge::new(&v[1], &v[3] ,()),
    ///     Edge::new(&v[1], &v[4] ,()),
    ///     Edge::new(&v[2], &v[4] ,()),
    ///     Edge::new(&v[2], &v[5] ,()),
    ///     Edge::new(&v[3], &v[4] ,()),
    ///     Edge::new(&v[4], &v[5] ,()),
    /// ];
    /// let wire = vec![
    ///     Wire::from_iter(vec![&edge[0], &edge[2], &edge[1].inverse()]),
    ///     Wire::from_iter(vec![&edge[3], &edge[7], &edge[4].inverse()]),
    ///     Wire::from_iter(vec![&edge[5], &edge[8], &edge[6].inverse()]),
    ///     Wire::from_iter(vec![&edge[2].inverse(), &edge[4], &edge[5].inverse()]),
    /// ];
    /// let shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
    /// // The orientations of all faces in the shell are compatible on the shared edges.
    /// // This shell is not closed because edge[0] is included in only the 0th face.
    /// assert_eq!(shell.shell_condition(), ShellCondition::Oriented);
    /// ```
    Oriented,
    /// All edges are shared by two faces.
    /// # Examples
    /// ```
    /// use truck_topology::*;
    /// use truck_topology::shell::ShellCondition;
    /// let v = Vertex::news(&[(); 8]);
    /// let edge = [
    ///     Edge::new(&v[0], &v[1] ,()),
    ///     Edge::new(&v[1], &v[2] ,()),
    ///     Edge::new(&v[2], &v[3] ,()),
    ///     Edge::new(&v[3], &v[0] ,()),
    ///     Edge::new(&v[0], &v[4] ,()),
    ///     Edge::new(&v[1], &v[5] ,()),
    ///     Edge::new(&v[2], &v[6] ,()),
    ///     Edge::new(&v[3], &v[7] ,()),
    ///     Edge::new(&v[4], &v[5] ,()),
    ///     Edge::new(&v[5], &v[6] ,()),
    ///     Edge::new(&v[6], &v[7] ,()),
    ///     Edge::new(&v[7], &v[4] ,()),
    /// ];
    /// let wire = vec![
    ///     Wire::from_iter(vec![&edge[0], &edge[1], &edge[2], &edge[3]]),
    ///     Wire::from_iter(vec![&edge[0].inverse(), &edge[4], &edge[8], &edge[5].inverse()]),
    ///     Wire::from_iter(vec![&edge[1].inverse(), &edge[5], &edge[9], &edge[6].inverse()]),
    ///     Wire::from_iter(vec![&edge[2].inverse(), &edge[6], &edge[10], &edge[7].inverse()]),
    ///     Wire::from_iter(vec![&edge[3].inverse(), &edge[7], &edge[11], &edge[4].inverse()]),
    ///     Wire::from_iter(vec![&edge[8], &edge[9], &edge[10], &edge[11]]),
    /// ];
    /// let mut shell: Shell<_, _, _> = wire.into_iter().map(|w| Face::new(vec![w], ())).collect();
    /// shell[5].invert();
    /// assert_eq!(shell.shell_condition(), ShellCondition::Closed);
    /// ```
    Closed,
}

impl std::ops::BitAnd for ShellCondition {
    type Output = Self;
    fn bitand(self, other: Self) -> Self {
        match (self, other) {
            (Self::Irregular, _) => Self::Irregular,
            (_, Self::Irregular) => Self::Irregular,
            (Self::Regular, _) => Self::Regular,
            (_, Self::Regular) => Self::Regular,
            (Self::Oriented, _) => Self::Oriented,
            (_, Self::Oriented) => Self::Oriented,
            (Self::Closed, Self::Closed) => Self::Closed,
        }
    }
}

#[derive(Debug, Clone)]
struct Boundaries<C> {
    checked: HashSet<EdgeID<C>>,
    boundaries: HashMap<EdgeID<C>, bool>,
    condition: ShellCondition,
}

impl<C> Boundaries<C> {
    #[inline(always)]
    fn new() -> Self {
        Self {
            checked: Default::default(),
            boundaries: Default::default(),
            condition: ShellCondition::Oriented,
        }
    }

    #[inline(always)]
    fn insert<P>(&mut self, edge: &Edge<P, C>) {
        self.condition = self.condition
            & match (
                self.checked.insert(edge.id()),
                self.boundaries.insert(edge.id(), edge.orientation()),
            ) {
                (true, None) => ShellCondition::Oriented,
                (false, None) => ShellCondition::Irregular,
                (true, Some(_)) => panic!("unexpected case!"),
                (false, Some(ori)) => {
                    self.boundaries.remove(&edge.id());
                    match edge.orientation() == ori {
                        true => ShellCondition::Regular,
                        false => ShellCondition::Oriented,
                    }
                }
            }
    }

Returns how many same edges.

Examples
use truck_topology::*;
// Create one edge
let v = Vertex::news(&[(), ()]);
let e0 = Edge::new(&v[0], &v[1], ());
assert_eq!(e0.count(), 1);
// Create another edge, independent from e0
let e1 = Edge::new(&v[0], &v[1], ());
assert_eq!(e0.count(), 1);
// Clone e0, count will be 2
let e2 = e0.clone();
assert_eq!(e0.count(), 2);
assert_eq!(e2.count(), 2);
// drop e2, count will be 1
drop(e2);
assert_eq!(e0.count(), 1);

Returns the cloned curve in edge. If edge is inverted, then the returned curve is also inverted.

Examples found in repository?
src/edge.rs (line 482)
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
    pub fn concat(&self, rhs: &Self) -> std::result::Result<Self, ConcatError<P>>
    where
        P: Debug,
        C: Concat<C, Point = P, Output = C> + Invertible + ParameterTransform, {
        if self.back() != rhs.front() {
            return Err(ConcatError::DisconnectedVertex(
                self.back().clone(),
                rhs.front().clone(),
            ));
        }
        if self.front() == rhs.back() {
            return Err(ConcatError::SameVertex(self.front().clone()));
        }
        let curve0 = self.oriented_curve();
        let mut curve1 = rhs.oriented_curve();
        let t0 = curve0.parameter_range().1;
        let t1 = curve1.parameter_range().0;
        curve1.parameter_transform(1.0, t0 - t1);
        let curve = curve0.try_concat(&curve1)?;
        Ok(Edge::debug_new(self.front(), rhs.back(), curve))
    }

Returns the consistence of the geometry of end vertices and the geometry of edge.

Examples found in repository?
src/wire.rs (line 498)
494
495
496
497
498
499
    pub fn is_geometric_consistent(&self) -> bool
    where
        P: Tolerance,
        C: BoundedCurve<Point = P>, {
        self.iter().all(|edge| edge.is_geometric_consistent())
    }
More examples
Hide additional examples
src/face.rs (line 986)
983
984
985
986
987
988
989
990
991
    pub fn is_geometric_consistent(&self) -> bool {
        let surface = &*self.surface.lock().unwrap();
        self.boundary_iters().into_iter().flatten().all(|edge| {
            let edge_consist = edge.is_geometric_consistent();
            let curve = &*edge.curve.lock().unwrap();
            let curve_consist = surface.include(curve);
            edge_consist && curve_consist
        })
    }

Cuts the edge at vertex.

Failure

Returns None if:

  • cannot find the parameter t such that edge.get_curve().subs(t) == vertex.get_point(), or
  • the found parameter is not in the parameter range without end points.
Examples found in repository?
src/shell.rs (line 632)
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
    pub fn cut_edge(
        &mut self,
        edge_id: EdgeID<C>,
        vertex: &Vertex<P>,
    ) -> Option<(Edge<P, C>, Edge<P, C>)>
    where
        P: Clone,
        C: Cut<Point = P> + SearchParameter<D1, Point = P>,
    {
        if self.vertex_iter().any(|v| &v == vertex) {
            return None;
        }
        let mut edges = None;
        self.iter_mut()
            .flat_map(|face| face.boundaries.iter_mut())
            .try_for_each(|wire| {
                let find_res = wire
                    .iter()
                    .enumerate()
                    .find(|(_, edge)| edge.id() == edge_id);
                let (idx, edge) = match find_res {
                    Some(got) => got,
                    None => return Some(()),
                };
                if edges.is_none() {
                    edges = Some(edge.absolute_clone().cut(vertex)?);
                }
                let edges = edges.as_ref().unwrap();
                let new_wire = match edge.orientation() {
                    true => Wire::from(vec![edges.0.clone(), edges.1.clone()]),
                    false => Wire::from(vec![edges.1.inverse(), edges.0.inverse()]),
                };
                let flag = wire.swap_edge_into_wire(idx, new_wire);
                debug_assert!(flag);
                Some(())
            });
        edges
    }

Cuts the edge at vertex with parameter t.

Failure

Returns None if !edge.get_curve().subs(t).near(&vertex.get_point()).

Concats two edges.

Examples found in repository?
src/shell.rs (line 676)
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
    pub fn remove_vertex_by_concat_edges(&mut self, vertex_id: VertexID<P>) -> Option<Edge<P, C>>
    where
        P: Debug,
        C: Concat<C, Point = P, Output = C> + Invertible + ParameterTransform, {
        let mut vec: Vec<(&mut Wire<P, C>, usize)> = self
            .face_iter_mut()
            .flat_map(|face| &mut face.boundaries)
            .filter_map(|wire| {
                let idx = wire
                    .edge_iter()
                    .enumerate()
                    .find(|(_, e)| e.back().id() == vertex_id)?
                    .0;
                Some((wire, idx))
            })
            .collect();
        if vec.len() > 2 || vec.is_empty() {
            None
        } else if vec.len() == 1 {
            let (wire, idx) = vec.pop().unwrap();
            let edge = wire[idx].concat(&wire[(idx + 1) % wire.len()]).ok()?;
            wire.swap_subwire_into_edges(idx, edge.clone());
            Some(edge)
        } else {
            let (wire0, idx0) = vec.pop().unwrap();
            let (wire1, idx1) = vec.pop().unwrap();
            if !wire0[idx0].is_same(&wire1[(idx1 + 1) % wire1.len()])
                || !wire0[(idx0 + 1) % wire0.len()].is_same(&wire1[idx1])
            {
                return None;
            }
            let edge = wire0[idx0].concat(&wire0[(idx0 + 1) % wire0.len()]).ok()?;
            wire1.swap_subwire_into_edges(idx1, edge.inverse());
            wire0.swap_subwire_into_edges(idx0, edge.clone());
            Some(edge)
        }
    }

Create display struct for debugging the edge.

Examples
use truck_topology::*;
use EdgeDisplayFormat as EDF;

let vertex_format = VertexDisplayFormat::AsPoint;
let edge = Edge::new(&Vertex::new(0), &Vertex::new(1), 2);

assert_eq!(
    format!("{:?}", edge.display(EDF::Full { vertex_format })),
    format!("Edge {{ id: {:?}, vertices: (0, 1), entity: 2 }}", edge.id()),
);
assert_eq!(
    format!("{:?}", edge.display(EDF::VerticesTupleAndID { vertex_format })),
    format!("Edge {{ id: {:?}, vertices: (0, 1) }}", edge.id()),
);
assert_eq!(
    &format!("{:?}", edge.display(EDF::VerticesTupleAndCurve { vertex_format })),
    "Edge { vertices: (0, 1), entity: 2 }",
);
assert_eq!(
    &format!("{:?}", edge.display(EDF::VerticesTupleStruct { vertex_format })),
    "Edge(0, 1)",
);
assert_eq!(
    &format!("{:?}", edge.display(EDF::VerticesTuple { vertex_format })),
    "(0, 1)",
);
assert_eq!(
    &format!("{:?}", edge.display(EDF::AsCurve)),
    "2",
);
Examples found in repository?
src/wire.rs (line 798)
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self.format {
            WireDisplayFormat::EdgesListTuple { edge_format } => f
                .debug_tuple("Wire")
                .field(&Self {
                    entity: self.entity,
                    format: WireDisplayFormat::EdgesList { edge_format },
                })
                .finish(),
            WireDisplayFormat::EdgesList { edge_format } => f
                .debug_list()
                .entries(
                    self.entity
                        .edge_iter()
                        .map(|edge| edge.display(edge_format)),
                )
                .finish(),
            WireDisplayFormat::VerticesList { vertex_format } => {
                let vertices: Vec<_> = self.entity.vertex_iter().collect();
                f.debug_list()
                    .entries(vertices.iter().map(|vertex| vertex.display(vertex_format)))
                    .finish()
            }
        }
    }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Extends a collection with the contents of an iterator. Read more
🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Creates a value from an iterator. Read more
Creates a value from an iterator. Read more
Creates an instance of the collection from the parallel iterator par_iter. Read more
Feeds this value into the given Hasher. Read more
Feeds a slice of this type into the given Hasher. Read more
Extends an instance of the collection with the elements drawn from the parallel iterator par_iter. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The alignment of pointer.
The type for initializers.
Initializes a with the given initializer. Read more
Dereferences the given pointer. Read more
Mutably dereferences the given pointer. Read more
Drops the object pointed to by the given pointer. Read more
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.