delaunay 0.7.8

D-dimensional Delaunay triangulations and convex hulls in Rust, with exact predicates, multi-level validation, and bistellar flips
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
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
//! Geometric orientation orchestration for generic [`Triangulation`](crate::Triangulation).
//!
//! This module owns triangulation-level orientation work: collecting lifted simplex
//! points from the TDS, validating geometric orientation, canonicalizing simplex
//! slot order, and normalizing coherent orientation after construction or edits.
//! Predicate implementations remain in the geometry layer.

use crate::core::algorithms::incremental_insertion::InsertionError;
use crate::core::collections::{MAX_PRACTICAL_DIMENSION_SIZE, SimplexKeyBuffer, SmallBuffer};
use crate::core::simplex::Simplex;
use crate::core::tds::{GeometricError, SimplexKey, TdsError, VertexKey};
use crate::core::triangulation::Triangulation;
use crate::core::validation::TriangulationValidationError;
use crate::geometry::kernel::Kernel;
use crate::geometry::point::Point;
use crate::geometry::predicates::Orientation;
use crate::geometry::robust_predicates::robust_orientation;
use crate::geometry::traits::coordinate::Coordinate;
use crate::topology::traits::global_topology_model::GlobalTopologyModel;

impl<K, U, V, const D: usize> Triangulation<K, U, V, D>
where
    K: Kernel<D>,
{
    /// Collect simplex points for orientation evaluation.
    ///
    /// For periodic simplices, this delegates per-vertex lattice-offset lifting to the active
    /// [`GlobalTopology`](crate::topology::traits::topological_space::GlobalTopology) behavior model.
    fn collect_simplex_points_for_orientation(
        &self,
        simplex_key: SimplexKey,
        simplex: &Simplex<K::Scalar, U, V, D>,
        purpose: &str,
    ) -> Result<SmallBuffer<Point<K::Scalar, D>, MAX_PRACTICAL_DIMENSION_SIZE>, TdsError> {
        let topology_model = self.global_topology.model();
        let periodic_offsets = simplex.periodic_vertex_offsets();
        if let Some(offsets) = periodic_offsets {
            if offsets.len() != simplex.number_of_vertices() {
                return Err(TdsError::DimensionMismatch {
                    expected: simplex.number_of_vertices(),
                    actual: offsets.len(),
                    context: format!(
                        "simplex {:?} (key {simplex_key:?}) periodic offset count vs vertex count during {purpose}",
                        simplex.uuid(),
                    ),
                });
            }
            if !topology_model.supports_periodic_orientation_offsets() {
                return Err(TdsError::InconsistentDataStructure {
                    message: format!(
                        "Simplex {:?} (key {simplex_key:?}) has periodic offsets (count {}) during {purpose}, but triangulation global topology is {:?} (kind {:?}, allows_boundary: {}, periodic_domain: {:?}); expected periodic-orientation-offset-capable topology",
                        simplex.uuid(),
                        offsets.len(),
                        self.global_topology,
                        topology_model.kind(),
                        topology_model.allows_boundary(),
                        topology_model.periodic_domain(),
                    ),
                });
            }
        }

        let mut points: SmallBuffer<Point<K::Scalar, D>, MAX_PRACTICAL_DIMENSION_SIZE> =
            SmallBuffer::with_capacity(simplex.number_of_vertices());

        for (vertex_idx, &vertex_key) in simplex.vertices().iter().enumerate() {
            let vertex = self.tds.vertex(vertex_key).ok_or_else(|| {
                TdsError::VertexNotFound {
                    vertex_key,
                    context: format!(
                        "referenced by simplex {:?} (key {simplex_key:?}) at position {vertex_idx} during {purpose}",
                        simplex.uuid(),
                    ),
                }
            })?;
            let periodic_offset = periodic_offsets.map(|offsets| offsets[vertex_idx]);
            let lifted_coords = topology_model
                .lift_for_orientation(*vertex.point().coords(), periodic_offset)
                .map_err(|error| TdsError::InconsistentDataStructure {
                    message: format!(
                        "Failed to lift coordinates for vertex key {vertex_key:?} at slot {vertex_idx} in simplex {:?} (key {simplex_key:?}) during {purpose}: {error}",
                        simplex.uuid(),
                    ),
                })?;

            points.push(Point::new(lifted_coords));
        }

        Ok(points)
    }

    /// Evaluate a simplex's geometric orientation for a validation/canonicalization context.
    ///
    /// This helper uses [`robust_orientation`] directly, without `SoS`, so true
    /// degeneracy remains distinguishable from positive or negative orientation.
    pub(crate) fn evaluate_simplex_orientation_for_context(
        &self,
        simplex_key: SimplexKey,
        simplex: &Simplex<K::Scalar, U, V, D>,
        purpose: &str,
        predicate_failure_prefix: &str,
    ) -> Result<i32, TdsError> {
        let points = self.collect_simplex_points_for_orientation(simplex_key, simplex, purpose)?;

        match robust_orientation(&points) {
            Ok(Orientation::POSITIVE) => Ok(1),
            Ok(Orientation::NEGATIVE) => Ok(-1),
            Ok(Orientation::DEGENERATE) => Ok(0),
            Err(error) => Err(TdsError::InconsistentDataStructure {
                message: format!(
                    "{predicate_failure_prefix} {:?} (key {simplex_key:?}): {error}",
                    simplex.uuid(),
                ),
            }),
        }
    }

    /// Validates geometric orientation sign for each stored simplex using exact arithmetic.
    ///
    /// Simplices are stored in canonical positive orientation order by construction and mutation
    /// paths; a negative sign indicates geometric/combinatorial mismatch.
    pub(crate) fn validate_geometric_simplex_orientation(&self) -> Result<(), TdsError> {
        for (simplex_key, simplex) in self.tds.simplices() {
            let orientation = self.evaluate_simplex_orientation_for_context(
                simplex_key,
                simplex,
                "geometric orientation validation",
                "Geometric orientation predicate failed for simplex",
            )?;
            if orientation < 0 {
                let vertex_keys: SmallBuffer<VertexKey, MAX_PRACTICAL_DIMENSION_SIZE> =
                    simplex.vertices().iter().copied().collect();
                let neighbor_keys: SmallBuffer<Option<SimplexKey>, MAX_PRACTICAL_DIMENSION_SIZE> =
                    simplex
                        .neighbor_keys()
                        .map(Iterator::collect)
                        .unwrap_or_default();
                tracing::debug!(
                    simplex_uuid = %simplex.uuid(),
                    ?simplex_key,
                    ?vertex_keys,
                    ?neighbor_keys,
                    orientation,
                    "negative geometric orientation detected during validation",
                );

                return Err(TdsError::Geometric(GeometricError::NegativeOrientation {
                    message: format!(
                        "Simplex {:?} (key {simplex_key:?}, vertices {vertex_keys:?}) has negative geometric orientation; expected positive canonical orientation",
                        simplex.uuid(),
                    ),
                }));
            }
        }

        Ok(())
    }

    /// Validates geometric orientation for a local set of simplices.
    pub(crate) fn validate_geometric_simplex_orientation_for_simplices(
        &self,
        simplices: &[SimplexKey],
    ) -> Result<(), TdsError> {
        for &simplex_key in simplices {
            let simplex =
                self.tds
                    .simplex(simplex_key)
                    .ok_or_else(|| TdsError::SimplexNotFound {
                        simplex_key,
                        context: "local geometric orientation validation scope".to_string(),
                    })?;
            let orientation = self.evaluate_simplex_orientation_for_context(
                simplex_key,
                simplex,
                "local geometric orientation validation",
                "Geometric orientation predicate failed for local simplex",
            )?;
            if orientation < 0 {
                let vertex_keys: SmallBuffer<VertexKey, MAX_PRACTICAL_DIMENSION_SIZE> =
                    simplex.vertices().iter().copied().collect();
                tracing::debug!(
                    simplex_uuid = %simplex.uuid(),
                    ?simplex_key,
                    ?vertex_keys,
                    orientation,
                    "negative geometric orientation detected during local validation",
                );

                return Err(TdsError::Geometric(GeometricError::NegativeOrientation {
                    message: format!(
                        "Simplex {:?} (key {simplex_key:?}, vertices {vertex_keys:?}) has negative geometric orientation; expected positive canonical orientation",
                        simplex.uuid(),
                    ),
                }));
            }
        }

        Ok(())
    }

    /// Validates local orientation invariants for simplices changed by insertion.
    pub(crate) fn validate_local_orientation_for_simplices(
        &self,
        simplices: &[SimplexKey],
    ) -> Result<(), InsertionError> {
        self.tds
            .validate_coherent_orientation_for_simplices(simplices)?;
        self.validate_geometric_simplex_orientation_for_simplices(simplices)?;
        Ok(())
    }

    /// Flip all negatively oriented simplices to positive orientation.
    fn promote_simplices_to_positive_orientation(&mut self) -> Result<bool, InsertionError> {
        let mut negative_simplices = SimplexKeyBuffer::new();

        for (simplex_key, simplex) in self.tds.simplices() {
            let orientation = self.evaluate_simplex_orientation_for_context(
                simplex_key,
                simplex,
                "positive-orientation promotion",
                "Geometric orientation predicate failed while promoting positive orientation for simplex",
            )?;
            if orientation == 0 {
                continue;
            }
            if orientation < 0 {
                negative_simplices.push(simplex_key);
            }
        }

        if negative_simplices.is_empty() {
            return Ok(false);
        }

        for simplex_key in negative_simplices {
            let simplex =
                self.tds
                    .simplex_mut(simplex_key)
                    .ok_or_else(|| TdsError::SimplexNotFound {
                        simplex_key,
                        context: "applying positive-orientation promotion".to_string(),
                    })?;
            if simplex.number_of_vertices() >= 2 {
                simplex.swap_vertex_slots(0, 1);
            }
        }

        self.tds.mark_topology_modified();
        Ok(true)
    }

    /// Check whether any simplex still requires positive-orientation promotion.
    fn simplices_require_positive_orientation_promotion(&self) -> Result<bool, InsertionError> {
        for (simplex_key, simplex) in self.tds.simplices() {
            let orientation = self.evaluate_simplex_orientation_for_context(
                simplex_key,
                simplex,
                "positive-orientation convergence check",
                "Geometric orientation predicate failed while checking positive-orientation convergence for simplex",
            )?;
            if orientation == 0 {
                continue;
            }
            if orientation < 0 {
                return Ok(true);
            }
        }

        Ok(false)
    }

    /// For connected non-periodic triangulations, canonicalize the coherent global sign.
    fn canonicalize_global_orientation_sign(&mut self) -> Result<(), InsertionError> {
        let representative_sign = {
            let mut sign = None;
            for (simplex_key, simplex) in self.tds.simplices() {
                let orientation = self.evaluate_simplex_orientation_for_context(
                    simplex_key,
                    simplex,
                    "global orientation-sign canonicalization",
                    "Geometric orientation predicate failed while canonicalizing global orientation sign for simplex",
                )?;
                if orientation != 0 {
                    sign = Some(orientation);
                    break;
                }
            }
            sign
        };

        if representative_sign != Some(-1) {
            return Ok(());
        }

        let simplex_keys: SimplexKeyBuffer = self.tds.simplex_keys().collect();
        let mut flipped_any = false;
        for simplex_key in simplex_keys {
            let Some(simplex) = self.tds.simplex_mut(simplex_key) else {
                continue;
            };
            if simplex.number_of_vertices() >= 2 {
                simplex.swap_vertex_slots(0, 1);
                flipped_any = true;
            }
        }

        if flipped_any {
            self.tds.mark_topology_modified();
        }

        Ok(())
    }

    /// Normalize coherent orientation and promote geometric orientation to the positive sign.
    pub(crate) fn normalize_and_promote_positive_orientation(
        &mut self,
    ) -> Result<(), InsertionError> {
        self.tds.normalize_coherent_orientation()?;
        self.canonicalize_global_orientation_sign()?;

        for _ in 0..3 {
            if !self.promote_simplices_to_positive_orientation()? {
                break;
            }
            self.tds.normalize_coherent_orientation()?;
        }

        if self.simplices_require_positive_orientation_promotion()? {
            let mut residual_count = 0_usize;
            let mut sample_keys: [Option<SimplexKey>; 5] = [None; 5];
            for (simplex_key, simplex) in self.tds.simplices() {
                let orientation = self.evaluate_simplex_orientation_for_context(
                    simplex_key,
                    simplex,
                    "residual negative-orientation sampling",
                    "Geometric orientation predicate failed while sampling residual negatives for simplex",
                )?;
                if orientation < 0 {
                    if residual_count < sample_keys.len() {
                        sample_keys[residual_count] = Some(simplex_key);
                    }
                    residual_count += 1;
                }
            }
            let sampled: Vec<SimplexKey> = sample_keys.into_iter().flatten().collect();
            return Err(InsertionError::TopologyValidationFailed {
                message: "Positive-orientation promotion failed to converge".to_string(),
                source: TriangulationValidationError::OrientationPromotionNonConvergence {
                    residual_count,
                    sampled,
                },
            });
        }
        self.canonicalize_global_orientation_sign()?;
        Ok(())
    }

    /// Canonicalize a set of newly created simplices to positive geometric orientation.
    #[expect(
        clippy::too_many_lines,
        reason = "debug-only orientation diagnostics with dedup add conditional branches"
    )]
    pub(crate) fn canonicalize_positive_orientation_for_simplices(
        &mut self,
        simplices: &SimplexKeyBuffer,
    ) -> Result<(), InsertionError> {
        #[cfg(debug_assertions)]
        let debug_orientation = std::env::var_os("DELAUNAY_DEBUG_ORIENTATION").is_some();
        #[cfg(debug_assertions)]
        let mut orientation_warn_count = 0_usize;

        for &simplex_key in simplices {
            let orientation = {
                let simplex =
                    self.tds
                        .simplex(simplex_key)
                        .ok_or_else(|| TdsError::SimplexNotFound {
                            simplex_key,
                            context: "canonicalizing insertion orientation".to_string(),
                        })?;
                self.evaluate_simplex_orientation_for_context(
                    simplex_key,
                    simplex,
                    "insertion orientation canonicalization",
                    "Geometric orientation predicate failed while canonicalizing simplex",
                )?
            };

            if orientation == 0 {
                continue;
            }

            if orientation < 0 {
                #[cfg(debug_assertions)]
                let pre_swap_vertices = if debug_orientation {
                    self.tds.simplex(simplex_key).map(|c| c.vertices().to_vec())
                } else {
                    None
                };

                let simplex =
                    self.tds
                        .simplex_mut(simplex_key)
                        .ok_or_else(|| TdsError::SimplexNotFound {
                            simplex_key,
                            context: "applying insertion orientation canonicalization".to_string(),
                        })?;
                if simplex.number_of_vertices() < 2 {
                    return Err(TdsError::DimensionMismatch {
                        expected: 2,
                        actual: simplex.number_of_vertices(),
                        context: format!(
                            "simplex {simplex_key:?} needs >= 2 vertices for orientation canonicalization"
                        ),
                    }
                    .into());
                }
                simplex.swap_vertex_slots(0, 1);

                #[cfg(debug_assertions)]
                if debug_orientation {
                    orientation_warn_count += 1;
                    if orientation_warn_count <= 3 {
                        let post_orientation = self.tds.simplex(simplex_key).map(|c| {
                            self.evaluate_simplex_orientation_for_context(
                                simplex_key,
                                c,
                                "orientation swap verification",
                                "orientation predicate failed during swap verification",
                            )
                        });
                        match post_orientation {
                            Some(Ok(post_o)) => {
                                tracing::warn!(
                                    simplex_key = ?simplex_key,
                                    pre_swap_vertices = ?pre_swap_vertices,
                                    pre_swap_orientation = orientation,
                                    post_swap_orientation = post_o,
                                    swap_fixed = post_o > 0,
                                    "canonicalize_positive_orientation: negative-orientation simplex swapped"
                                );
                            }
                            Some(Err(ref e)) => {
                                tracing::warn!(
                                    simplex_key = ?simplex_key,
                                    pre_swap_vertices = ?pre_swap_vertices,
                                    pre_swap_orientation = orientation,
                                    error = %e,
                                    "canonicalize_positive_orientation: post-swap verification failed"
                                );
                            }
                            None => {
                                tracing::warn!(
                                    simplex_key = ?simplex_key,
                                    pre_swap_vertices = ?pre_swap_vertices,
                                    pre_swap_orientation = orientation,
                                    "canonicalize_positive_orientation: simplex not found after swap"
                                );
                            }
                        }
                    }
                }
            }
        }

        #[cfg(debug_assertions)]
        if orientation_warn_count > 3 && debug_orientation {
            let suppressed = orientation_warn_count - 3;
            tracing::warn!(
                total_negative = orientation_warn_count,
                suppressed,
                "canonicalize_positive_orientation: suppressed {suppressed} additional negative-orientation warnings (see first 3 above)"
            );
        }

        Ok(())
    }

    /// Verifies that no simplex is geometrically degenerate.
    ///
    /// This is a sign-agnostic check: it flags simplices whose exact orientation
    /// determinant is zero regardless of the sign.
    pub(crate) fn validate_geometric_nondegeneracy(&self) -> Result<(), TdsError> {
        for (simplex_key, simplex) in self.tds.simplices() {
            let orientation = self.evaluate_simplex_orientation_for_context(
                simplex_key,
                simplex,
                "geometric nondegeneracy check",
                "Orientation predicate failed for simplex",
            )?;
            if orientation == 0 {
                return Err(TdsError::Geometric(GeometricError::DegenerateOrientation {
                    message: format!(
                        "Simplex {:?} (key {simplex_key:?}) is geometrically degenerate \
                         (zero-volume simplex from collinear/coplanar vertices)",
                        simplex.uuid(),
                    ),
                }));
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::tds::InvariantError;
    use crate::geometry::kernel::FastKernel;
    use crate::topology::traits::topological_space::{GlobalTopology, ToroidalConstructionMode};
    use crate::vertex;

    /// Regression test: a negatively oriented but topologically valid simplex
    /// passes topology-only validation while failing full validation.
    #[test]
    fn negative_oriented_simplex_topology_only() {
        let vertices = vec![
            vertex!([0.0, 0.0]),
            vertex!([1.0, 0.0]),
            vertex!([0.0, 1.0]),
        ];
        let tds =
            Triangulation::<FastKernel<f64>, (), (), 2>::build_initial_simplex(&vertices).unwrap();
        let mut tri =
            Triangulation::<FastKernel<f64>, (), (), 2>::new_with_tds(FastKernel::new(), tds);

        assert!(tri.is_valid().is_ok());
        assert!(tri.is_valid_topology_only().is_ok());

        let simplex_key = tri.tds.simplex_keys().next().unwrap();
        tri.tds
            .simplex_mut(simplex_key)
            .unwrap()
            .swap_vertex_slots(0, 1);

        assert!(tri.is_valid_topology_only().is_ok());
        assert!(tri.is_valid().is_err());
    }

    #[test]
    fn local_geometric_orientation_validation_errors_on_missing_scope_simplex() {
        let vertices = vec![
            vertex!([0.0, 0.0, 0.0]),
            vertex!([1.0, 0.0, 0.0]),
            vertex!([0.0, 1.0, 0.0]),
            vertex!([0.0, 0.0, 1.0]),
        ];
        let tds =
            Triangulation::<FastKernel<f64>, (), (), 3>::build_initial_simplex(&vertices).unwrap();
        let mut tri =
            Triangulation::<FastKernel<f64>, (), (), 3>::new_with_tds(FastKernel::new(), tds);
        let simplex_key = tri.tds.simplex_keys().next().unwrap();
        assert_eq!(tri.tds.remove_simplices_by_keys(&[simplex_key]), 1);

        match tri.validate_geometric_simplex_orientation_for_simplices(&[simplex_key]) {
            Err(TdsError::SimplexNotFound {
                simplex_key: missing_key,
                ..
            }) => assert_eq!(missing_key, simplex_key),
            other => panic!("Expected SimplexNotFound, got {other:?}"),
        }
    }

    #[test]
    fn is_valid_rejects_negative_geometric_simplex_orientation() {
        let vertices = vec![
            vertex!([0.0, 0.0]),
            vertex!([1.0, 0.0]),
            vertex!([0.0, 1.0]),
        ];
        let mut tds =
            Triangulation::<FastKernel<f64>, (), (), 2>::build_initial_simplex(&vertices).unwrap();

        let simplex_key = tds.simplex_keys().next().unwrap();
        tds.simplex_mut(simplex_key)
            .unwrap()
            .swap_vertex_slots(0, 1);

        let tri = Triangulation::<FastKernel<f64>, (), (), 2>::new_with_tds(FastKernel::new(), tds);
        let err = tri.is_valid().unwrap_err();
        assert!(matches!(
            err,
            InvariantError::Tds(TdsError::Geometric(GeometricError::NegativeOrientation { message }))
                if message.contains("negative geometric orientation")
        ));
    }

    #[test]
    fn validate_geometric_simplex_orientation_returns_enriched_error_on_negative() {
        let vertices = vec![
            vertex!([0.0, 0.0]),
            vertex!([1.0, 0.0]),
            vertex!([0.0, 1.0]),
        ];
        let mut tds =
            Triangulation::<FastKernel<f64>, (), (), 2>::build_initial_simplex(&vertices).unwrap();

        let simplex_key = tds.simplex_keys().next().unwrap();
        tds.simplex_mut(simplex_key)
            .unwrap()
            .swap_vertex_slots(0, 1);

        let tri = Triangulation::<FastKernel<f64>, (), (), 2>::new_with_tds(FastKernel::new(), tds);
        let err = tri.validate_geometric_simplex_orientation().unwrap_err();
        assert!(
            matches!(
                &err,
                TdsError::Geometric(GeometricError::NegativeOrientation { message })
                    if message.contains("negative geometric orientation")
                       && message.contains("vertices")
            ),
            "Error should contain vertex keys: {err}"
        );
    }

    #[test]
    fn simplices_require_positive_orientation_promotion_detects_negative_without_mutating() {
        let vertices = vec![
            vertex!([0.0, 0.0]),
            vertex!([1.0, 0.0]),
            vertex!([0.0, 1.0]),
        ];
        let mut tds =
            Triangulation::<FastKernel<f64>, (), (), 2>::build_initial_simplex(&vertices).unwrap();
        let simplex_key = tds.simplex_keys().next().unwrap();
        tds.simplex_mut(simplex_key)
            .unwrap()
            .swap_vertex_slots(0, 1);

        let tri = Triangulation::<FastKernel<f64>, (), (), 2>::new_with_tds(FastKernel::new(), tds);
        let before: Vec<_> = tri.tds.simplex(simplex_key).unwrap().vertices().to_vec();

        assert!(
            tri.simplices_require_positive_orientation_promotion()
                .unwrap()
        );

        let after: Vec<_> = tri.tds.simplex(simplex_key).unwrap().vertices().to_vec();
        assert_eq!(before, after);
    }

    #[test]
    fn simplices_require_positive_orientation_promotion_false_for_positive_without_mutating() {
        let vertices = vec![
            vertex!([0.0, 0.0]),
            vertex!([1.0, 0.0]),
            vertex!([0.0, 1.0]),
        ];
        let tds =
            Triangulation::<FastKernel<f64>, (), (), 2>::build_initial_simplex(&vertices).unwrap();
        let simplex_key = tds.simplex_keys().next().unwrap();

        let tri = Triangulation::<FastKernel<f64>, (), (), 2>::new_with_tds(FastKernel::new(), tds);
        let before: Vec<_> = tri.tds.simplex(simplex_key).unwrap().vertices().to_vec();

        assert!(
            !tri.simplices_require_positive_orientation_promotion()
                .unwrap()
        );

        let after: Vec<_> = tri.tds.simplex(simplex_key).unwrap().vertices().to_vec();
        assert_eq!(before, after);
    }

    #[test]
    fn periodic_geometric_orientation_validation_uses_lifted_coordinates() {
        let vertices = vec![
            vertex!([0.0, 0.0]),
            vertex!([0.8, 0.0]),
            vertex!([0.0, 0.8]),
        ];
        let mut tds =
            Triangulation::<FastKernel<f64>, (), (), 2>::build_initial_simplex(&vertices).unwrap();
        let simplex_key = tds.simplex_keys().next().unwrap();
        tds.simplex_mut(simplex_key)
            .unwrap()
            .set_periodic_vertex_offsets(vec![[0, 0], [0, 0], [1, 0]])
            .unwrap();

        let mut tri =
            Triangulation::<FastKernel<f64>, (), (), 2>::new_with_tds(FastKernel::new(), tds);
        tri.set_global_topology(GlobalTopology::Toroidal {
            domain: [1.0, 1.0],
            mode: ToroidalConstructionMode::PeriodicImagePoint,
        });

        assert!(tri.validate_geometric_simplex_orientation().is_ok());

        tri.tds
            .simplex_mut(simplex_key)
            .unwrap()
            .swap_vertex_slots(0, 1);
        let err = tri.validate_geometric_simplex_orientation().unwrap_err();
        assert!(matches!(
            err,
            TdsError::Geometric(GeometricError::NegativeOrientation { message })
                if message.contains("negative geometric orientation")
        ));
    }

    #[test]
    fn periodic_geometric_orientation_validation_requires_toroidal_metadata() {
        let vertices = vec![
            vertex!([0.0, 0.0]),
            vertex!([0.8, 0.0]),
            vertex!([0.0, 0.8]),
        ];
        let mut tds =
            Triangulation::<FastKernel<f64>, (), (), 2>::build_initial_simplex(&vertices).unwrap();
        let simplex_key = tds.simplex_keys().next().unwrap();
        tds.simplex_mut(simplex_key)
            .unwrap()
            .set_periodic_vertex_offsets(vec![[0, 0], [0, 0], [1, 0]])
            .unwrap();

        let tri = Triangulation::<FastKernel<f64>, (), (), 2>::new_with_tds(FastKernel::new(), tds);
        let err = tri.validate_geometric_simplex_orientation().unwrap_err();
        assert!(matches!(
            err,
            TdsError::InconsistentDataStructure { message }
                if message.contains("has periodic offsets")
                    && message.contains("expected periodic-orientation-offset-capable topology")
        ));
    }

    #[test]
    fn periodic_geometric_orientation_validation_rejects_offset_count_mismatch() {
        let vertices = vec![
            vertex!([0.0, 0.0]),
            vertex!([0.8, 0.0]),
            vertex!([0.0, 0.8]),
        ];
        let mut tds =
            Triangulation::<FastKernel<f64>, (), (), 2>::build_initial_simplex(&vertices).unwrap();
        let simplex_key = tds.simplex_keys().next().unwrap();
        tds.simplex_mut(simplex_key)
            .unwrap()
            .periodic_vertex_offsets = Some(vec![[0, 0], [1, 0]].into());

        let tri = Triangulation::<FastKernel<f64>, (), (), 2>::new_with_tds(FastKernel::new(), tds);
        let err = tri.validate_geometric_simplex_orientation().unwrap_err();
        assert!(matches!(
            err,
            TdsError::DimensionMismatch {
                expected: 3,
                actual: 2,
                ..
            }
        ));
    }

    #[test]
    fn periodic_geometric_orientation_validation_maps_lift_errors() {
        let vertices = vec![
            vertex!([0.0, 0.0]),
            vertex!([0.8, 0.0]),
            vertex!([0.0, 0.8]),
        ];
        let mut tds =
            Triangulation::<FastKernel<f64>, (), (), 2>::build_initial_simplex(&vertices).unwrap();
        let simplex_key = tds.simplex_keys().next().unwrap();
        tds.simplex_mut(simplex_key)
            .unwrap()
            .set_periodic_vertex_offsets(vec![[0, 0], [0, 0], [1, 0]])
            .unwrap();

        let mut tri =
            Triangulation::<FastKernel<f64>, (), (), 2>::new_with_tds(FastKernel::new(), tds);
        tri.set_global_topology(GlobalTopology::Toroidal {
            domain: [0.0, 1.0],
            mode: ToroidalConstructionMode::PeriodicImagePoint,
        });

        let err = tri.validate_geometric_simplex_orientation().unwrap_err();
        assert!(matches!(
            err,
            TdsError::InconsistentDataStructure { message }
                if message.contains("Failed to lift coordinates")
                    && message.contains("Invalid toroidal period")
        ));
    }
}