ringgrid 0.5.6

Pure-Rust detector for coded ring calibration targets
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
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
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
//! Runtime target layout specification.
//!
//! Target JSON follows a parametric schema (`ringgrid.target.v4`): marker
//! locations are generated at runtime from `(rows, long_row_cols, pitch_mm)`.
//! Per-marker coordinate lists are intentionally not part of the runtime schema.

use std::collections::HashMap;
#[cfg(feature = "std")]
use std::path::Path;

const TARGET_SCHEMA_V4: &str = "ringgrid.target.v4";

const DEFAULT_NAME: &str = "ringgrid_200mm_hex";
const DEFAULT_PITCH_MM: f32 = 8.0;
const DEFAULT_ROWS: usize = 15;
const DEFAULT_LONG_ROW_COLS: usize = 14;
const DEFAULT_OUTER_RADIUS_MM: f32 = 4.8;
const DEFAULT_INNER_RADIUS_MM: f32 = 3.2;
const DEFAULT_RING_WIDTH_MM: f32 = 1.152;

/// Validation failures for a board layout specification.
#[derive(Debug, Clone)]
pub enum BoardLayoutValidationError {
    /// Validation failed: unsupported target schema version.
    UnsupportedSchema {
        /// Schema string found in the file.
        found: String,
        /// Schema string the loader expected.
        expected: &'static str,
    },
    /// Validation failed: target name is empty.
    EmptyName,
    /// Validation failed: pitch is non-positive or non-finite.
    InvalidPitch {
        /// The invalid pitch value.
        pitch_mm: f32,
    },
    /// Validation failed: row count is zero.
    InvalidRows {
        /// The invalid row count.
        rows: usize,
    },
    /// Validation failed: long-row column count is zero.
    InvalidLongRowCols {
        /// The invalid column count.
        long_row_cols: usize,
    },
    /// Validation failed: long-row columns must exceed short-row columns derived from row count.
    InvalidLongRowColsForRows {
        /// Total number of rows.
        rows: usize,
        /// Column count for the longest row.
        long_row_cols: usize,
    },
    /// Validation failed: outer radius is non-positive or non-finite.
    InvalidOuterRadius {
        /// The invalid outer radius value.
        marker_outer_radius_mm: f32,
    },
    /// Validation failed: inner radius is non-positive or non-finite.
    InvalidInnerRadius {
        /// The invalid inner radius value.
        marker_inner_radius_mm: f32,
    },
    /// Validation failed: ring width is non-positive or non-finite.
    InvalidRingWidth {
        /// The invalid ring width value.
        marker_ring_width_mm: f32,
    },
    /// Validation failed: inner radius must be strictly less than outer radius.
    InnerRadiusNotSmallerThanOuter {
        /// The inner radius value.
        marker_inner_radius_mm: f32,
        /// The outer radius value.
        marker_outer_radius_mm: f32,
    },
    /// Validation failed: code band gap between inner and outer rings is non-positive.
    NonPositiveCodeBandGap {
        /// Outer edge of the inner ring in mm.
        inner_ring_outer_edge_mm: f32,
        /// Inner edge of the outer ring in mm.
        outer_ring_inner_edge_mm: f32,
    },
    /// Validation failed: outer diameter exceeds minimum center-to-center spacing.
    OuterDiameterExceedsMinCenterSpacing {
        /// Outer diameter in mm.
        marker_outer_diameter_mm: f32,
        /// Minimum center spacing in mm.
        min_center_spacing_mm: f32,
    },
    /// Validation failed: marker draw diameter exceeds minimum center-to-center spacing.
    MarkerDrawDiameterExceedsMinCenterSpacing {
        /// Marker draw diameter in mm.
        marker_draw_diameter_mm: f32,
        /// Minimum center spacing in mm.
        min_center_spacing_mm: f32,
    },
    /// Validation failed: a row has zero columns after applying hex-lattice offset.
    DerivedZeroColumns {
        /// Index of the problematic row.
        row_index: usize,
        /// Total number of rows.
        rows: usize,
        /// Column count for the longest row.
        long_row_cols: usize,
    },
    /// Validation failed: `id_assignment` length does not match marker count.
    IdAssignmentLength {
        /// Expected length (marker count).
        expected: usize,
        /// Actual length.
        got: usize,
    },
    /// Validation failed: `id_assignment` contains duplicate IDs.
    IdAssignmentDuplicate {
        /// The duplicated codebook ID.
        id: usize,
        /// Position index where the duplicate was found.
        position: usize,
    },
}

impl std::fmt::Display for BoardLayoutValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::UnsupportedSchema { found, expected } => write!(
                f,
                "unsupported target schema '{}' (expected '{}')",
                found, expected
            ),
            Self::EmptyName => f.write_str("target name must not be empty"),
            Self::InvalidPitch { pitch_mm } => {
                write!(f, "pitch_mm must be finite and > 0 (got {pitch_mm})")
            }
            Self::InvalidRows { rows } => write!(f, "rows must be >= 1 (got {rows})"),
            Self::InvalidLongRowCols { long_row_cols } => {
                write!(f, "long_row_cols must be >= 1 (got {long_row_cols})")
            }
            Self::InvalidLongRowColsForRows {
                rows,
                long_row_cols,
            } => write!(
                f,
                "long_row_cols must be >= 2 when rows > 1 (got rows={}, long_row_cols={})",
                rows, long_row_cols
            ),
            Self::InvalidOuterRadius {
                marker_outer_radius_mm,
            } => write!(
                f,
                "marker_outer_radius_mm must be finite and > 0 (got {marker_outer_radius_mm})"
            ),
            Self::InvalidInnerRadius {
                marker_inner_radius_mm,
            } => write!(
                f,
                "marker_inner_radius_mm must be finite and > 0 (got {marker_inner_radius_mm})"
            ),
            Self::InvalidRingWidth {
                marker_ring_width_mm,
            } => write!(
                f,
                "marker_ring_width_mm must be finite and > 0 (got {marker_ring_width_mm})"
            ),
            Self::InnerRadiusNotSmallerThanOuter {
                marker_inner_radius_mm,
                marker_outer_radius_mm,
            } => write!(
                f,
                "marker_inner_radius_mm must be < marker_outer_radius_mm (inner={}, outer={})",
                marker_inner_radius_mm, marker_outer_radius_mm
            ),
            Self::NonPositiveCodeBandGap {
                inner_ring_outer_edge_mm,
                outer_ring_inner_edge_mm,
            } => write!(
                f,
                "marker geometry leaves no code band between rings (inner ring outer edge={inner_ring_outer_edge_mm:.4}mm, outer ring inner edge={outer_ring_inner_edge_mm:.4}mm)"
            ),
            Self::OuterDiameterExceedsMinCenterSpacing {
                marker_outer_diameter_mm,
                min_center_spacing_mm,
            } => write!(
                f,
                "marker outer diameter ({marker_outer_diameter_mm:.4}mm) must be smaller than minimum center spacing ({min_center_spacing_mm:.4}mm)"
            ),
            Self::MarkerDrawDiameterExceedsMinCenterSpacing {
                marker_draw_diameter_mm,
                min_center_spacing_mm,
            } => write!(
                f,
                "printed marker diameter including ring stroke ({marker_draw_diameter_mm:.4}mm) must be smaller than minimum center spacing ({min_center_spacing_mm:.4}mm)"
            ),
            Self::DerivedZeroColumns {
                row_index,
                rows,
                long_row_cols,
            } => write!(
                f,
                "derived row has zero columns at row {} (rows={}, long_row_cols={})",
                row_index, rows, long_row_cols
            ),
            Self::IdAssignmentLength { expected, got } => write!(
                f,
                "id_assignment length ({got}) does not match marker count ({expected})"
            ),
            Self::IdAssignmentDuplicate { id, position } => write!(
                f,
                "id_assignment contains duplicate ID {id} at position {position}"
            ),
        }
    }
}

impl std::error::Error for BoardLayoutValidationError {}

/// Load-time failures for board layout JSON.
#[derive(Debug)]
pub enum BoardLayoutLoadError {
    /// File I/O error while reading the layout JSON.
    #[cfg(feature = "std")]
    Io(std::io::Error),
    /// JSON deserialization failed.
    JsonParse(serde_json::Error),
    /// Deserialized values failed validation.
    Validation(BoardLayoutValidationError),
}

impl std::fmt::Display for BoardLayoutLoadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            #[cfg(feature = "std")]
            Self::Io(err) => write!(f, "failed to read target JSON: {err}"),
            Self::JsonParse(err) => write!(f, "failed to parse target JSON: {err}"),
            Self::Validation(err) => write!(f, "invalid target spec: {err}"),
        }
    }
}

impl std::error::Error for BoardLayoutLoadError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            #[cfg(feature = "std")]
            Self::Io(err) => Some(err),
            Self::JsonParse(err) => Some(err),
            Self::Validation(err) => Some(err),
        }
    }
}

#[cfg(feature = "std")]
impl From<std::io::Error> for BoardLayoutLoadError {
    fn from(value: std::io::Error) -> Self {
        Self::Io(value)
    }
}

impl From<serde_json::Error> for BoardLayoutLoadError {
    fn from(value: serde_json::Error) -> Self {
        Self::JsonParse(value)
    }
}

impl From<BoardLayoutValidationError> for BoardLayoutLoadError {
    fn from(value: BoardLayoutValidationError) -> Self {
        Self::Validation(value)
    }
}
/// A single marker's position on the calibration board.
///
/// Each marker has a unique `id` (codebook index in the active profile), a
/// physical position `xy_mm` on the board, and optional hex-lattice axial
/// coordinates `(q, r)`.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct BoardMarker {
    /// Unique marker ID (codebook index in the active profile).
    pub id: usize,
    /// Position on the board in millimeters `[x, y]`.
    pub xy_mm: [f32; 2],
    /// Hex-lattice axial coordinate q (column offset).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub q: Option<i16>,
    /// Hex-lattice axial coordinate r (row).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub r: Option<i16>,
}

/// Runtime board layout used by the detector.
///
/// Describes the physical hex-lattice arrangement of ring markers: their
/// positions in millimeters, ring radii, ring width, and lattice parameters.
/// Load from a JSON file conforming to `ringgrid.target.v4` schema, or use the
/// built-in default via [`BoardLayout::default()`].
///
/// # Example
///
/// ```no_run
/// use ringgrid::BoardLayout;
/// use std::path::Path;
///
/// let board = BoardLayout::from_json_file(Path::new("target.json")).unwrap();
/// println!("{} markers, pitch={} mm", board.n_markers(), board.pitch_mm);
/// ```
#[derive(Debug, Clone)]
pub struct BoardLayout {
    /// Human-readable name of the target layout.
    pub name: String,
    /// Center-to-center spacing between adjacent markers in millimeters.
    pub pitch_mm: f32,
    /// Number of marker rows on the board.
    pub rows: usize,
    /// Number of columns in the longest (even-indexed) row.
    pub long_row_cols: usize,
    /// Outer ring radius in millimeters.
    pub marker_outer_radius_mm: f32,
    /// Inner ring radius in millimeters.
    pub marker_inner_radius_mm: f32,
    /// Width of each ring band in millimeters.
    pub marker_ring_width_mm: f32,
    markers: Vec<BoardMarker>,

    /// Fast lookup: marker ID -> index into `markers`.
    id_to_idx: HashMap<usize, usize>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct BoardLayoutSpecV4 {
    schema: String,
    name: String,
    pitch_mm: f32,
    rows: usize,
    long_row_cols: usize,
    marker_outer_radius_mm: f32,
    marker_inner_radius_mm: f32,
    marker_ring_width_mm: f32,
    /// Optional optimized ID assignment. When present, `id_assignment[i]` is the
    /// codebook ID for the i-th marker (in generation order). When absent, IDs
    /// are assigned sequentially (0, 1, 2, ...).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    id_assignment: Option<Vec<usize>>,
}

impl BoardLayout {
    /// Construct a board layout from direct geometry arguments.
    ///
    /// Uses a deterministic geometry-derived name so the layout can round-trip
    /// through the canonical `ringgrid.target.v4` JSON schema without requiring
    /// the caller to supply a name up front.
    pub fn new(
        pitch_mm: f32,
        rows: usize,
        long_row_cols: usize,
        marker_outer_radius_mm: f32,
        marker_inner_radius_mm: f32,
        marker_ring_width_mm: f32,
    ) -> Result<Self, BoardLayoutValidationError> {
        Self::with_name(
            generated_name(
                pitch_mm,
                rows,
                long_row_cols,
                marker_outer_radius_mm,
                marker_inner_radius_mm,
                marker_ring_width_mm,
            ),
            pitch_mm,
            rows,
            long_row_cols,
            marker_outer_radius_mm,
            marker_inner_radius_mm,
            marker_ring_width_mm,
        )
    }

    /// Construct a named board layout from direct geometry arguments.
    pub fn with_name<S: Into<String>>(
        name: S,
        pitch_mm: f32,
        rows: usize,
        long_row_cols: usize,
        marker_outer_radius_mm: f32,
        marker_inner_radius_mm: f32,
        marker_ring_width_mm: f32,
    ) -> Result<Self, BoardLayoutValidationError> {
        Self::from_layout_spec(BoardLayoutSpecV4 {
            schema: TARGET_SCHEMA_V4.to_string(),
            name: name.into(),
            pitch_mm,
            rows,
            long_row_cols,
            marker_outer_radius_mm,
            marker_inner_radius_mm,
            marker_ring_width_mm,
            id_assignment: None,
        })
    }

    /// Look up board coordinates (x, y) in mm for a given marker ID.
    pub fn xy_mm(&self, id: usize) -> Option<[f32; 2]> {
        self.id_to_idx.get(&id).map(|&idx| self.markers[idx].xy_mm)
    }

    /// Look up a marker by ID.
    pub fn marker(&self, id: usize) -> Option<&BoardMarker> {
        self.id_to_idx.get(&id).map(|&idx| &self.markers[idx])
    }

    /// Borrow all markers as a read-only slice.
    pub fn markers(&self) -> &[BoardMarker] {
        &self.markers
    }

    /// Look up a marker by storage index.
    pub fn marker_by_index(&self, index: usize) -> Option<&BoardMarker> {
        self.markers.get(index)
    }

    /// Total number of markers on the board.
    pub fn n_markers(&self) -> usize {
        self.markers.len()
    }

    /// Marker outer radius in board units (mm).
    pub fn marker_outer_radius_mm(&self) -> f32 {
        self.marker_outer_radius_mm
    }

    /// Minimum center-to-center spacing between adjacent markers (mm).
    pub(crate) fn min_center_spacing_mm(&self) -> f32 {
        hex_row_spacing_mm(self.pitch_mm)
    }

    /// Marker inner radius in board units (mm).
    pub fn marker_inner_radius_mm(&self) -> f32 {
        self.marker_inner_radius_mm
    }

    /// Marker ring width in board units (mm).
    pub fn marker_ring_width_mm(&self) -> f32 {
        self.marker_ring_width_mm
    }

    /// Iterator over all marker IDs present on the board.
    pub fn marker_ids(&self) -> impl Iterator<Item = usize> + '_ {
        self.markers.iter().map(|m| m.id)
    }

    /// Maximum marker ID present on the board.
    pub fn max_marker_id(&self) -> usize {
        self.markers.iter().map(|m| m.id).max().unwrap_or(0)
    }

    /// Axis-aligned marker bounds in board mm.
    ///
    /// Returns `(min_xy, max_xy)` over marker centers.
    pub fn marker_bounds_mm(&self) -> Option<([f32; 2], [f32; 2])> {
        let first = self.markers.first()?;
        let mut min_x = first.xy_mm[0];
        let mut max_x = first.xy_mm[0];
        let mut min_y = first.xy_mm[1];
        let mut max_y = first.xy_mm[1];

        for m in &self.markers[1..] {
            min_x = min_x.min(m.xy_mm[0]);
            max_x = max_x.max(m.xy_mm[0]);
            min_y = min_y.min(m.xy_mm[1]);
            max_y = max_y.max(m.xy_mm[1]);
        }

        Some(([min_x, min_y], [max_x, max_y]))
    }

    /// Axis-aligned marker span in board mm (`[width, height]`).
    pub fn marker_span_mm(&self) -> Option<[f32; 2]> {
        self.marker_bounds_mm()
            .map(|(min_xy, max_xy)| [max_xy[0] - min_xy[0], max_xy[1] - min_xy[1]])
    }

    /// Load a board layout from a JSON file.
    #[cfg(feature = "std")]
    pub fn from_json_file(path: &Path) -> Result<Self, BoardLayoutLoadError> {
        let data = std::fs::read_to_string(path)?;
        Self::from_json_str(&data)
    }

    /// Load a board layout from a JSON string.
    pub fn from_json_str(data: &str) -> Result<Self, BoardLayoutLoadError> {
        let spec: BoardLayoutSpecV4 = serde_json::from_str(data)?;
        Self::from_layout_spec(spec).map_err(Into::into)
    }

    /// Serialize the layout as canonical `ringgrid.target.v4` JSON.
    pub fn to_json_string(&self) -> String {
        serde_json::to_string_pretty(&self.to_layout_spec())
            .expect("board layout JSON serialization must succeed")
    }

    /// Write the canonical `ringgrid.target.v4` JSON representation to disk.
    #[cfg(feature = "std")]
    pub fn write_json_file(&self, path: &Path) -> Result<(), std::io::Error> {
        if let Some(parent) = path.parent()
            && !parent.as_os_str().is_empty()
        {
            std::fs::create_dir_all(parent)?;
        }

        std::fs::write(path, format!("{}\n", self.to_json_string()))
    }

    fn from_layout_spec(spec: BoardLayoutSpecV4) -> Result<Self, BoardLayoutValidationError> {
        if spec.schema != TARGET_SCHEMA_V4 {
            return Err(BoardLayoutValidationError::UnsupportedSchema {
                found: spec.schema,
                expected: TARGET_SCHEMA_V4,
            });
        }

        validate_layout_spec(&spec)?;
        let mut markers = generate_markers(spec.rows, spec.long_row_cols, spec.pitch_mm)?;

        if let Some(ref assignment) = spec.id_assignment {
            if assignment.len() != markers.len() {
                return Err(BoardLayoutValidationError::IdAssignmentLength {
                    expected: markers.len(),
                    got: assignment.len(),
                });
            }
            let mut seen = std::collections::HashSet::new();
            for (i, &id) in assignment.iter().enumerate() {
                if !seen.insert(id) {
                    return Err(BoardLayoutValidationError::IdAssignmentDuplicate {
                        id,
                        position: i,
                    });
                }
                markers[i].id = id;
            }
        }

        let id_to_idx = markers.iter().enumerate().map(|(i, m)| (m.id, i)).collect();

        Ok(Self {
            name: spec.name,
            pitch_mm: spec.pitch_mm,
            rows: spec.rows,
            long_row_cols: spec.long_row_cols,
            marker_outer_radius_mm: spec.marker_outer_radius_mm,
            marker_inner_radius_mm: spec.marker_inner_radius_mm,
            marker_ring_width_mm: spec.marker_ring_width_mm,
            markers,
            id_to_idx,
        })
    }

    fn to_layout_spec(&self) -> BoardLayoutSpecV4 {
        let is_sequential = self.markers.iter().enumerate().all(|(i, m)| m.id == i);
        let id_assignment = if is_sequential {
            None
        } else {
            Some(self.markers.iter().map(|m| m.id).collect())
        };
        BoardLayoutSpecV4 {
            schema: TARGET_SCHEMA_V4.to_string(),
            name: self.name.clone(),
            pitch_mm: self.pitch_mm,
            rows: self.rows,
            long_row_cols: self.long_row_cols,
            marker_outer_radius_mm: self.marker_outer_radius_mm,
            marker_inner_radius_mm: self.marker_inner_radius_mm,
            marker_ring_width_mm: self.marker_ring_width_mm,
            id_assignment,
        }
    }
}

impl Default for BoardLayout {
    fn default() -> Self {
        let spec = BoardLayoutSpecV4 {
            schema: TARGET_SCHEMA_V4.to_string(),
            name: DEFAULT_NAME.to_string(),
            pitch_mm: DEFAULT_PITCH_MM,
            rows: DEFAULT_ROWS,
            long_row_cols: DEFAULT_LONG_ROW_COLS,
            marker_outer_radius_mm: DEFAULT_OUTER_RADIUS_MM,
            marker_inner_radius_mm: DEFAULT_INNER_RADIUS_MM,
            marker_ring_width_mm: DEFAULT_RING_WIDTH_MM,
            id_assignment: None,
        };

        Self::from_layout_spec(spec).expect("default board spec must be valid")
    }
}

fn validate_layout_spec(spec: &BoardLayoutSpecV4) -> Result<(), BoardLayoutValidationError> {
    if spec.name.trim().is_empty() {
        return Err(BoardLayoutValidationError::EmptyName);
    }

    if !spec.pitch_mm.is_finite() || spec.pitch_mm <= 0.0 {
        return Err(BoardLayoutValidationError::InvalidPitch {
            pitch_mm: spec.pitch_mm,
        });
    }

    if spec.rows == 0 {
        return Err(BoardLayoutValidationError::InvalidRows { rows: spec.rows });
    }

    if spec.long_row_cols == 0 {
        return Err(BoardLayoutValidationError::InvalidLongRowCols {
            long_row_cols: spec.long_row_cols,
        });
    }

    if spec.rows > 1 && spec.long_row_cols < 2 {
        return Err(BoardLayoutValidationError::InvalidLongRowColsForRows {
            rows: spec.rows,
            long_row_cols: spec.long_row_cols,
        });
    }

    if !spec.marker_outer_radius_mm.is_finite() || spec.marker_outer_radius_mm <= 0.0 {
        return Err(BoardLayoutValidationError::InvalidOuterRadius {
            marker_outer_radius_mm: spec.marker_outer_radius_mm,
        });
    }

    if !spec.marker_inner_radius_mm.is_finite() || spec.marker_inner_radius_mm <= 0.0 {
        return Err(BoardLayoutValidationError::InvalidInnerRadius {
            marker_inner_radius_mm: spec.marker_inner_radius_mm,
        });
    }

    if !spec.marker_ring_width_mm.is_finite() || spec.marker_ring_width_mm <= 0.0 {
        return Err(BoardLayoutValidationError::InvalidRingWidth {
            marker_ring_width_mm: spec.marker_ring_width_mm,
        });
    }

    if spec.marker_inner_radius_mm >= spec.marker_outer_radius_mm {
        return Err(BoardLayoutValidationError::InnerRadiusNotSmallerThanOuter {
            marker_inner_radius_mm: spec.marker_inner_radius_mm,
            marker_outer_radius_mm: spec.marker_outer_radius_mm,
        });
    }

    let ring_half_thickness_mm = marker_ring_half_thickness_mm(spec.marker_ring_width_mm);
    let inner_ring_outer_edge_mm = spec.marker_inner_radius_mm + ring_half_thickness_mm;
    let outer_ring_inner_edge_mm = spec.marker_outer_radius_mm - ring_half_thickness_mm;
    if inner_ring_outer_edge_mm >= outer_ring_inner_edge_mm {
        return Err(BoardLayoutValidationError::NonPositiveCodeBandGap {
            inner_ring_outer_edge_mm,
            outer_ring_inner_edge_mm,
        });
    }

    let min_center_spacing = hex_row_spacing_mm(spec.pitch_mm);
    if spec.marker_outer_radius_mm * 2.0 >= min_center_spacing {
        return Err(
            BoardLayoutValidationError::OuterDiameterExceedsMinCenterSpacing {
                marker_outer_diameter_mm: spec.marker_outer_radius_mm * 2.0,
                min_center_spacing_mm: min_center_spacing,
            },
        );
    }
    let marker_draw_diameter_mm =
        2.0 * marker_outer_draw_radius_mm(spec.marker_outer_radius_mm, spec.marker_ring_width_mm);
    if marker_draw_diameter_mm >= min_center_spacing {
        return Err(
            BoardLayoutValidationError::MarkerDrawDiameterExceedsMinCenterSpacing {
                marker_draw_diameter_mm,
                min_center_spacing_mm: min_center_spacing,
            },
        );
    }

    Ok(())
}

fn generate_markers(
    rows: usize,
    long_row_cols: usize,
    pitch_mm: f32,
) -> Result<Vec<BoardMarker>, BoardLayoutValidationError> {
    let short_row_cols = long_row_cols.saturating_sub(1);
    let mut markers = Vec::new();
    let row_mid = (rows as i32) / 2;

    for row_idx in 0..rows {
        let r = row_idx as i32 - row_mid;
        let n_cols = if rows == 1 || ((r + long_row_cols as i32 - 1) & 1) == 0 {
            long_row_cols
        } else {
            short_row_cols
        };

        if n_cols == 0 {
            return Err(BoardLayoutValidationError::DerivedZeroColumns {
                row_index: row_idx,
                rows,
                long_row_cols,
            });
        }

        let q_start = -((r + n_cols as i32 - 1) / 2);
        for col_idx in 0..n_cols {
            let q = q_start + col_idx as i32;
            let xy = hex_axial_to_xy_mm(q, r, pitch_mm);
            markers.push(BoardMarker {
                id: markers.len(),
                xy_mm: xy,
                q: i16::try_from(q).ok(),
                r: i16::try_from(r).ok(),
            });
        }
    }

    normalize_marker_origin(&mut markers);
    Ok(markers)
}

fn hex_axial_to_xy_mm(q: i32, r: i32, pitch_mm: f32) -> [f32; 2] {
    let qf = q as f64;
    let rf = r as f64;
    let pitch = pitch_mm as f64;
    let x = pitch * (f64::sqrt(3.0) * qf + 0.5 * f64::sqrt(3.0) * rf);
    let y = pitch * (1.5 * rf);
    [x as f32, y as f32]
}

fn normalize_marker_origin(markers: &mut [BoardMarker]) {
    let Some(anchor) = markers.first().map(|m| m.xy_mm) else {
        return;
    };
    for marker in markers {
        marker.xy_mm[0] -= anchor[0];
        marker.xy_mm[1] -= anchor[1];
    }
}

fn hex_row_spacing_mm(pitch_mm: f32) -> f32 {
    // Hex nearest-neighbor distance in this axial layout.
    pitch_mm * f32::sqrt(3.0)
}

pub(crate) fn marker_ring_half_thickness_mm(marker_ring_width_mm: f32) -> f32 {
    0.5 * marker_ring_width_mm
}

pub(crate) fn marker_outer_draw_radius_mm(outer_radius_mm: f32, marker_ring_width_mm: f32) -> f32 {
    outer_radius_mm + marker_ring_half_thickness_mm(marker_ring_width_mm)
}

pub(crate) fn marker_code_band_bounds_mm(
    outer_radius_mm: f32,
    inner_radius_mm: f32,
    marker_ring_width_mm: f32,
) -> (f32, f32) {
    let ring_half_thickness_mm = marker_ring_half_thickness_mm(marker_ring_width_mm);
    (
        inner_radius_mm + ring_half_thickness_mm,
        outer_radius_mm - ring_half_thickness_mm,
    )
}

fn generated_name(
    pitch_mm: f32,
    rows: usize,
    long_row_cols: usize,
    marker_outer_radius_mm: f32,
    marker_inner_radius_mm: f32,
    marker_ring_width_mm: f32,
) -> String {
    format!(
        "ringgrid_hex_r{rows}_c{long_row_cols}_p{pitch_mm:.3}_o{marker_outer_radius_mm:.3}_i{marker_inner_radius_mm:.3}_w{marker_ring_width_mm:.3}"
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::{SystemTime, UNIX_EPOCH};

    #[cfg(feature = "std")]
    fn temp_json_path(prefix: &str) -> std::path::PathBuf {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system time")
            .as_nanos();
        std::env::temp_dir().join(format!(
            "ringgrid_{prefix}_{}_{}.json",
            std::process::id(),
            nanos
        ))
    }

    #[test]
    fn default_board_has_expected_shape() {
        let board = BoardLayout::default();
        assert_eq!(board.rows, 15);
        assert_eq!(board.long_row_cols, 14);
        assert_eq!(board.n_markers(), 203);
        assert_eq!(board.xy_mm(0), Some([0.0, 0.0]));
        assert_eq!(board.xy_mm(20), Some([90.06664, 12.0]));
    }

    #[test]
    fn default_board_lookup_stays_consistent() {
        let board = BoardLayout::default();
        for id in 0..board.n_markers() {
            let xy = board.xy_mm(id).expect("valid id");
            let marker = board.marker_by_index(id).expect("marker index");
            assert_eq!(xy, marker.xy_mm);
        }
        assert_eq!(board.xy_mm(999), None);
    }

    #[test]
    fn default_board_min_center_spacing_matches_hex_pitch() {
        let board = BoardLayout::default();
        let expected = board.pitch_mm * f32::sqrt(3.0);
        assert!((board.min_center_spacing_mm() - expected).abs() < 1.0e-6);
    }

    #[test]
    fn default_board_anchor_is_top_left_marker() {
        let board = BoardLayout::default();
        assert_eq!(board.xy_mm(0), Some([0.0, 0.0]));
        let anchor = board.marker_by_index(0).expect("marker 0").xy_mm;
        let min_y = board
            .markers()
            .iter()
            .map(|m| m.xy_mm[1])
            .fold(f32::INFINITY, f32::min);
        let min_x_at_min_y = board
            .markers()
            .iter()
            .filter(|m| (m.xy_mm[1] - min_y).abs() < 1e-6)
            .map(|m| m.xy_mm[0])
            .fold(f32::INFINITY, f32::min);
        assert!((anchor[1] - min_y).abs() < 1e-6);
        assert!((anchor[0] - min_x_at_min_y).abs() < 1e-6);
    }

    #[test]
    fn from_json_requires_v4_schema() {
        let raw = r#"{
            "schema":"ringgrid.target.v2",
            "name":"x",
            "pitch_mm":8.0,
            "rows":1,
            "long_row_cols":1,
            "marker_outer_radius_mm":4.8,
            "marker_inner_radius_mm":3.2,
            "marker_ring_width_mm":1.152
        }"#;
        let spec: BoardLayoutSpecV4 = serde_json::from_str(raw).expect("valid json");
        let err = BoardLayout::from_layout_spec(spec).expect_err("expected error");
        assert!(matches!(
            err,
            BoardLayoutValidationError::UnsupportedSchema { .. }
        ));
    }

    #[test]
    fn from_json_rejects_marker_list_field() {
        let raw = r#"{
            "schema":"ringgrid.target.v4",
            "name":"x",
            "pitch_mm":8.0,
            "rows":1,
            "long_row_cols":1,
            "marker_outer_radius_mm":4.8,
            "marker_inner_radius_mm":3.2,
            "marker_ring_width_mm":1.152,
            "markers":[{"id":0,"xy_mm":[0.0,0.0]}]
        }"#;
        let parsed: Result<BoardLayoutSpecV4, _> = serde_json::from_str(raw);
        assert!(parsed.is_err());
    }

    #[test]
    fn from_json_rejects_legacy_fields() {
        let raw = r#"{
            "schema":"ringgrid.target.v4",
            "name":"x",
            "pitch_mm":8.0,
            "rows":3,
            "long_row_cols":4,
            "origin_mm":[0.0,0.0],
            "board_size_mm":[200.0,200.0],
            "marker_code_band_outer_radius_mm":4.64,
            "marker_code_band_inner_radius_mm":3.36,
            "marker_outer_radius_mm":4.8,
            "marker_inner_radius_mm":3.2,
            "marker_ring_width_mm":1.152
        }"#;
        let parsed: Result<BoardLayoutSpecV4, _> = serde_json::from_str(raw);
        assert!(parsed.is_err());
    }

    #[test]
    fn marker_span_is_positive() {
        let board = BoardLayout::default();
        let span = board.marker_span_mm().expect("span");
        assert!(span[0] > 0.0);
        assert!(span[1] > 0.0);
    }

    #[cfg(feature = "std")]
    #[test]
    fn from_json_file_maps_io_error_to_typed_variant() {
        let missing = temp_json_path("missing_board");
        let err = BoardLayout::from_json_file(&missing).expect_err("expected io error");
        assert!(matches!(err, BoardLayoutLoadError::Io(_)));
    }

    #[cfg(feature = "std")]
    #[test]
    fn from_json_file_maps_parse_error_to_typed_variant() {
        let path = temp_json_path("bad_json");
        std::fs::write(&path, "{ this is not valid json").expect("write temp json");

        let err = BoardLayout::from_json_file(&path).expect_err("expected parse error");
        assert!(matches!(err, BoardLayoutLoadError::JsonParse(_)));

        let _ = std::fs::remove_file(path);
    }

    #[cfg(feature = "std")]
    #[test]
    fn from_json_file_maps_validation_error_to_typed_variant() {
        let path = temp_json_path("bad_schema");
        let raw = r#"{
            "schema":"ringgrid.target.v2",
            "name":"x",
            "pitch_mm":8.0,
            "rows":1,
            "long_row_cols":1,
            "marker_outer_radius_mm":4.8,
            "marker_inner_radius_mm":3.2,
            "marker_ring_width_mm":1.152
        }"#;
        std::fs::write(&path, raw).expect("write temp json");

        let err = BoardLayout::from_json_file(&path).expect_err("expected validation error");
        assert!(matches!(
            err,
            BoardLayoutLoadError::Validation(BoardLayoutValidationError::UnsupportedSchema { .. })
        ));

        let _ = std::fs::remove_file(path);
    }

    #[test]
    fn from_json_str_loads_valid_spec() {
        let raw = r#"{
            "schema":"ringgrid.target.v4",
            "name":"x",
            "pitch_mm":8.0,
            "rows":3,
            "long_row_cols":4,
            "marker_outer_radius_mm":4.8,
            "marker_inner_radius_mm":3.2,
            "marker_ring_width_mm":1.152
        }"#;

        let board = BoardLayout::from_json_str(raw).expect("valid board json");
        assert_eq!(board.name, "x");
        assert_eq!(board.rows, 3);
        assert_eq!(board.long_row_cols, 4);
        assert!(board.n_markers() > 0);
    }

    #[test]
    fn direct_constructor_matches_round_trip_json() {
        let board = BoardLayout::with_name("fixture_compact_hex", 8.0, 3, 4, 4.8, 3.2, 1.152)
            .expect("valid direct geometry");

        let json = board.to_json_string();
        let reloaded = BoardLayout::from_json_str(&json).expect("round-trip json");

        assert_eq!(reloaded.name, "fixture_compact_hex");
        assert_eq!(reloaded.rows, 3);
        assert_eq!(reloaded.long_row_cols, 4);
        assert_eq!(reloaded.marker_outer_radius_mm, 4.8);
        assert_eq!(reloaded.marker_inner_radius_mm, 3.2);
        assert!((reloaded.marker_ring_width_mm - 1.152).abs() < 1e-6);
        assert_eq!(reloaded.markers().len(), board.markers().len());
        assert_eq!(reloaded.xy_mm(0), Some([0.0, 0.0]));
    }

    #[test]
    fn direct_constructor_uses_deterministic_default_name() {
        let board = BoardLayout::new(8.0, 3, 4, 4.8, 3.2, 1.152).expect("valid direct geometry");
        assert_eq!(board.name, "ringgrid_hex_r3_c4_p8.000_o4.800_i3.200_w1.152");
    }

    #[cfg(feature = "std")]
    #[test]
    fn write_json_file_creates_parent_dirs_and_round_trips() {
        let path = temp_json_path("round_trip");
        let nested = path.with_file_name("nested").join("board.json");
        let board = BoardLayout::with_name("fixture_compact_hex", 8.0, 3, 4, 4.8, 3.2, 1.152)
            .expect("valid direct geometry");

        board
            .write_json_file(&nested)
            .expect("write nested board json");
        let loaded = BoardLayout::from_json_file(&nested).expect("load nested board json");

        assert_eq!(loaded.name, board.name);
        assert_eq!(loaded.markers().len(), board.markers().len());

        let _ = std::fs::remove_file(&nested);
        let _ = std::fs::remove_dir(nested.parent().expect("nested parent"));
    }

    #[test]
    fn direct_constructor_reuses_layout_validation() {
        assert!(matches!(
            BoardLayout::new(8.0, 0, 4, 4.8, 3.2, 1.152),
            Err(BoardLayoutValidationError::InvalidRows { rows: 0 })
        ));
        assert!(matches!(
            BoardLayout::new(8.0, 3, 1, 4.8, 3.2, 1.152),
            Err(BoardLayoutValidationError::InvalidLongRowColsForRows {
                rows: 3,
                long_row_cols: 1,
            })
        ));
        assert!(matches!(
            BoardLayout::new(8.0, 3, 4, 4.8, 4.8, 1.152),
            Err(BoardLayoutValidationError::InnerRadiusNotSmallerThanOuter {
                marker_inner_radius_mm: 4.8,
                marker_outer_radius_mm: 4.8,
            })
        ));
        assert!(matches!(
            BoardLayout::new(8.0, 3, 4, 4.8, 4.1, 1.152),
            Err(BoardLayoutValidationError::NonPositiveCodeBandGap { .. })
        ));
        assert!(matches!(
            BoardLayout::new(f32::NAN, 3, 4, 4.8, 3.2, 1.152),
            Err(BoardLayoutValidationError::InvalidPitch { .. })
        ));
        assert!(matches!(
            BoardLayout::new(5.0, 3, 4, 4.0, 2.0, 1.152),
            Err(BoardLayoutValidationError::MarkerDrawDiameterExceedsMinCenterSpacing { .. })
        ));
        assert!(matches!(
            BoardLayout::new(8.0, 3, 4, 4.8, 3.2, 0.0),
            Err(BoardLayoutValidationError::InvalidRingWidth { .. })
        ));
    }

    // ── id_assignment tests ───────────────────────────────────────

    #[cfg(feature = "std")]
    fn repo_root() -> std::path::PathBuf {
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")
    }

    #[cfg(feature = "std")]
    #[test]
    fn id_assignment_loads_and_remaps() {
        let path = repo_root().join("tools/board/board_spec_optimized.json");
        let board = BoardLayout::from_json_file(&path).unwrap();
        assert_eq!(board.n_markers(), 203);

        // Read raw JSON to get the assignment array
        let raw: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        let assignment: Vec<usize> = raw["id_assignment"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_u64().unwrap() as usize)
            .collect();

        // Each marker's ID should match the assignment
        for (i, &expected_id) in assignment.iter().enumerate() {
            let marker = board.marker_by_index(i).unwrap();
            assert_eq!(
                marker.id, expected_id,
                "marker at index {i}: expected ID {expected_id}, got {}",
                marker.id
            );
        }
    }

    #[cfg(feature = "std")]
    #[test]
    fn id_assignment_roundtrip() {
        let path = repo_root().join("tools/board/board_spec_optimized.json");
        let board = BoardLayout::from_json_file(&path).unwrap();

        // Serialize and deserialize
        let json = board.to_json_string();
        let board2 = BoardLayout::from_json_str(&json).unwrap();

        assert_eq!(board.n_markers(), board2.n_markers());
        for i in 0..board.n_markers() {
            let m1 = board.marker_by_index(i).unwrap();
            let m2 = board2.marker_by_index(i).unwrap();
            assert_eq!(m1.id, m2.id, "ID mismatch at index {i}");
            assert!(
                (m1.xy_mm[0] - m2.xy_mm[0]).abs() < 1e-4
                    && (m1.xy_mm[1] - m2.xy_mm[1]).abs() < 1e-4,
                "position mismatch at index {i}"
            );
        }
    }

    #[test]
    fn id_assignment_rejects_wrong_length() {
        // Build a small valid board JSON, then add wrong-length id_assignment
        let board = BoardLayout::default();
        let json = board.to_json_string();
        let mut val: serde_json::Value = serde_json::from_str(&json).unwrap();
        val["id_assignment"] = serde_json::json!([0, 1, 2]); // only 3, need 203
        let bad_json = serde_json::to_string(&val).unwrap();
        let err = BoardLayout::from_json_str(&bad_json).unwrap_err();
        assert!(
            err.to_string().contains("id_assignment length"),
            "expected IdAssignmentLength error, got: {err}"
        );
    }

    #[test]
    fn id_assignment_rejects_duplicates() {
        let board = BoardLayout::default();
        let json = board.to_json_string();
        let mut val: serde_json::Value = serde_json::from_str(&json).unwrap();
        // Create assignment with correct length but duplicate ID at positions 0 and 1
        let n = board.n_markers();
        let mut ids: Vec<usize> = (0..n).collect();
        ids[1] = ids[0]; // duplicate
        val["id_assignment"] = serde_json::json!(ids);
        let bad_json = serde_json::to_string(&val).unwrap();
        let err = BoardLayout::from_json_str(&bad_json).unwrap_err();
        assert!(
            err.to_string().contains("duplicate ID"),
            "expected IdAssignmentDuplicate error, got: {err}"
        );
    }

    #[test]
    fn sequential_board_omits_id_assignment() {
        let board = BoardLayout::default();
        let json = board.to_json_string();
        let val: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert!(
            val.get("id_assignment").is_none(),
            "sequential board should not include id_assignment in JSON"
        );
    }
}