calib-targets-print 0.13.0

Printable calibration target generation for chessboard, ChArUco, PuzzleBoard, and marker boards
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
//! Printable target document model.
//!
//! Sub-modules split by concern:
//! - `error`: [`PrintableTargetError`]
//! - `page`: [`PageSize`], [`PageOrientation`], [`PageSpec`], [`RenderOptions`]
//! - `chessboard`: [`ChessboardTargetSpec`]
//! - `charuco`: [`CharucoTargetSpec`]
//! - `marker`: [`MarkerCircleSpec`], [`MarkerBoardTargetSpec`]
//! - `puzzleboard`: [`PuzzleBoardTargetSpec`]

mod charuco;
mod chessboard;
mod error;
mod marker;
mod page;
mod puzzleboard;

pub use charuco::CharucoTargetSpec;
pub use chessboard::ChessboardTargetSpec;
pub use error::PrintableTargetError;
pub use marker::{MarkerBoardTargetSpec, MarkerCircleSpec};
pub use page::{PageOrientation, PageSize, PageSpec, RenderOptions};
pub use puzzleboard::PuzzleBoardTargetSpec;

pub(crate) use charuco::validate_charuco_spec;
pub(crate) use chessboard::validate_inner_corner_grid;
pub(crate) use marker::validate_marker_board_spec;
pub(crate) use puzzleboard::validate_puzzleboard_spec;

use error::SCHEMA_VERSION_V1;

use calib_targets_core::Coord;
use calib_targets_marker::MarkerBoardSpec;
use calib_targets_puzzleboard::MASTER_COLS;
use serde::{Deserialize, Serialize};
use std::{
    fs,
    path::{Path, PathBuf},
};

fn default_schema_version() -> u32 {
    SCHEMA_VERSION_V1
}

fn default_page_spec() -> PageSpec {
    PageSpec::default()
}

fn default_render_options() -> RenderOptions {
    RenderOptions::default()
}

/// Union of all printable target geometries.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum TargetSpec {
    /// A plain chessboard target.
    Chessboard(ChessboardTargetSpec),
    /// A ChArUco board target.
    Charuco(CharucoTargetSpec),
    /// A checkerboard marker board target.
    MarkerBoard(MarkerBoardTargetSpec),
    /// A PuzzleBoard self-identifying target.
    PuzzleBoard(PuzzleBoardTargetSpec),
}

impl TargetSpec {
    /// Short name for the target kind, suitable for filenames and JSON.
    pub fn kind_name(&self) -> &'static str {
        match self {
            Self::Chessboard(_) => "chessboard",
            Self::Charuco(_) => "charuco",
            Self::MarkerBoard(_) => "marker_board",
            Self::PuzzleBoard(_) => "puzzleboard",
        }
    }

    /// Returns `(width_mm, height_mm)` of the rendered board area.
    pub fn board_size_mm(&self) -> Result<(f64, f64), PrintableTargetError> {
        match self {
            Self::Chessboard(spec) => {
                validate_inner_corner_grid(spec.inner_rows, spec.inner_cols, spec.square_size_mm)?;
                Ok((
                    (spec.inner_cols as f64 + 1.0) * spec.square_size_mm,
                    (spec.inner_rows as f64 + 1.0) * spec.square_size_mm,
                ))
            }
            Self::Charuco(spec) => {
                validate_charuco_spec(spec)?;
                Ok((
                    spec.cols as f64 * spec.square_size_mm,
                    spec.rows as f64 * spec.square_size_mm,
                ))
            }
            Self::MarkerBoard(spec) => {
                validate_marker_board_spec(spec)?;
                Ok((
                    (spec.inner_cols as f64 + 1.0) * spec.square_size_mm,
                    (spec.inner_rows as f64 + 1.0) * spec.square_size_mm,
                ))
            }
            Self::PuzzleBoard(spec) => {
                validate_puzzleboard_spec(spec)?;
                Ok((
                    spec.cols as f64 * spec.square_size_mm,
                    spec.rows as f64 * spec.square_size_mm,
                ))
            }
        }
    }

    /// Compute board-space coordinates for every output point.
    pub fn resolved_points(&self) -> Result<Vec<ResolvedTargetPoint>, PrintableTargetError> {
        match self {
            Self::Chessboard(spec) => {
                validate_inner_corner_grid(spec.inner_rows, spec.inner_cols, spec.square_size_mm)?;
                let mut points =
                    Vec::with_capacity(spec.inner_rows as usize * spec.inner_cols as usize);
                for j in 0..spec.inner_rows {
                    for i in 0..spec.inner_cols {
                        points.push(ResolvedTargetPoint {
                            position_mm: [
                                (i as f64 + 1.0) * spec.square_size_mm,
                                (j as f64 + 1.0) * spec.square_size_mm,
                            ],
                            grid: Some(Coord::new(i as i32, j as i32)),
                            id: None,
                        });
                    }
                }
                Ok(points)
            }
            Self::Charuco(spec) => {
                validate_charuco_spec(spec)?;
                let mut points = Vec::with_capacity(
                    (spec.rows.saturating_sub(1) * spec.cols.saturating_sub(1)) as usize,
                );
                let inner_rows = spec.rows - 1;
                let inner_cols = spec.cols - 1;
                for j in 0..inner_rows {
                    for i in 0..inner_cols {
                        let id = j * inner_cols + i;
                        points.push(ResolvedTargetPoint {
                            position_mm: [
                                (i as f64 + 1.0) * spec.square_size_mm,
                                (j as f64 + 1.0) * spec.square_size_mm,
                            ],
                            grid: Some(Coord::new(i as i32, j as i32)),
                            id: Some(id),
                        });
                    }
                }
                Ok(points)
            }
            Self::MarkerBoard(spec) => {
                validate_marker_board_spec(spec)?;
                let mut points =
                    Vec::with_capacity(spec.inner_rows as usize * spec.inner_cols as usize);
                for j in 0..spec.inner_rows {
                    for i in 0..spec.inner_cols {
                        points.push(ResolvedTargetPoint {
                            position_mm: [
                                (i as f64 + 1.0) * spec.square_size_mm,
                                (j as f64 + 1.0) * spec.square_size_mm,
                            ],
                            grid: Some(Coord::new(i as i32, j as i32)),
                            id: None,
                        });
                    }
                }
                Ok(points)
            }
            Self::PuzzleBoard(spec) => {
                validate_puzzleboard_spec(spec)?;
                let inner_rows = spec.rows.saturating_sub(1);
                let inner_cols = spec.cols.saturating_sub(1);
                let mut points = Vec::with_capacity((inner_rows * inner_cols) as usize);
                // Each corner's id is `I * MASTER_COLS + J` where (I, J) are
                // master-absolute coords. (I, J) = local (i, j) + origin.
                for j in 0..inner_rows {
                    for i in 0..inner_cols {
                        let master_i = spec.origin_col + i + 1; // inner corner → (origin_col + 1 + i)
                        let master_j = spec.origin_row + j + 1;
                        let id = master_j * MASTER_COLS + master_i;
                        points.push(ResolvedTargetPoint {
                            position_mm: [
                                (i as f64 + 1.0) * spec.square_size_mm,
                                (j as f64 + 1.0) * spec.square_size_mm,
                            ],
                            grid: Some(Coord::new(master_i as i32, master_j as i32)),
                            id: Some(id),
                        });
                    }
                }
                Ok(points)
            }
        }
    }
}

/// Top-level printable target document (the JSON file on disk).
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PrintableTargetDocument {
    /// JSON schema version of this document.
    #[serde(default = "default_schema_version")]
    pub schema_version: u32,
    /// The target geometry to render.
    pub target: TargetSpec,
    /// Page size and orientation the target is placed on.
    #[serde(default = "default_page_spec")]
    pub page: PageSpec,
    /// Rendering options (margins, labels, etc.).
    #[serde(default = "default_render_options")]
    pub render: RenderOptions,
}

impl PrintableTargetDocument {
    /// Create a new document with default page and render settings.
    pub fn new(target: TargetSpec) -> Self {
        Self {
            schema_version: default_schema_version(),
            target,
            page: PageSpec::default(),
            render: RenderOptions::default(),
        }
    }

    /// Override the page size / orientation / margin.
    #[must_use]
    pub fn with_page(mut self, page: PageSpec) -> Self {
        self.page = page;
        self
    }

    /// Override the rasterization / annotation options.
    #[must_use]
    pub fn with_render(mut self, render: RenderOptions) -> Self {
        self.render = render;
        self
    }

    /// Build a printable document from a ChArUco board spec whose `cell_size`
    /// is already expressed in millimeters.
    pub fn from_charuco_board_spec_mm(board: &calib_targets_charuco::CharucoBoardSpec) -> Self {
        Self::new(TargetSpec::Charuco(CharucoTargetSpec::from_board_spec_mm(
            board,
        )))
    }

    /// Build a printable document from a marker-board layout whose `cell_size`
    /// is already expressed in millimeters.
    pub fn try_from_marker_board_layout_mm(
        layout: &MarkerBoardSpec,
    ) -> Result<Self, PrintableTargetError> {
        Ok(Self::new(TargetSpec::MarkerBoard(
            MarkerBoardTargetSpec::try_from_layout_mm(layout)?,
        )))
    }

    /// Load and validate a document from a JSON file.
    pub fn load_json(path: impl AsRef<Path>) -> Result<Self, PrintableTargetError> {
        let raw = fs::read_to_string(path)?;
        let doc: Self = serde_json::from_str(&raw)?;
        doc.validate()?;
        Ok(doc)
    }

    /// Validate and write to a JSON file.
    pub fn write_json(&self, path: impl AsRef<Path>) -> Result<(), PrintableTargetError> {
        self.validate()?;
        fs::write(path, self.to_json_pretty()?)?;
        Ok(())
    }

    /// Serialize to pretty-printed JSON.
    pub fn to_json_pretty(&self) -> Result<String, PrintableTargetError> {
        self.validate()?;
        Ok(serde_json::to_string_pretty(self)?)
    }

    /// Validate schema version, page dimensions, and target geometry.
    pub fn validate(&self) -> Result<(), PrintableTargetError> {
        if self.schema_version != SCHEMA_VERSION_V1 {
            return Err(PrintableTargetError::UnsupportedSchemaVersion(
                self.schema_version,
            ));
        }
        let _ = self.page.printable_dimensions_mm()?;
        if self.render.png_dpi == 0 {
            return Err(PrintableTargetError::InvalidPngDpi);
        }
        let (board_width_mm, board_height_mm) = self.target.board_size_mm()?;
        let (printable_width_mm, printable_height_mm) = self.page.printable_dimensions_mm()?;
        if board_width_mm > printable_width_mm || board_height_mm > printable_height_mm {
            return Err(PrintableTargetError::BoardDoesNotFit {
                board_width_mm,
                board_height_mm,
                printable_width_mm,
                printable_height_mm,
            });
        }
        let _ = self.target.resolved_points()?;
        Ok(())
    }

    /// Compute the full page + board layout for rendering.
    pub fn resolve_layout(&self) -> Result<ResolvedTargetLayout, PrintableTargetError> {
        self.validate()?;
        let (page_width_mm, page_height_mm) = self.page.dimensions_mm()?;
        let (board_width_mm, board_height_mm) = self.target.board_size_mm()?;
        let printable_width_mm = page_width_mm - 2.0 * self.page.margin_mm;
        let printable_height_mm = page_height_mm - 2.0 * self.page.margin_mm;
        let board_origin_mm = [
            self.page.margin_mm + 0.5 * (printable_width_mm - board_width_mm),
            self.page.margin_mm + 0.5 * (printable_height_mm - board_height_mm),
        ];
        Ok(ResolvedTargetLayout {
            page_width_mm,
            page_height_mm,
            board_origin_mm,
            board_width_mm,
            board_height_mm,
            points: self.target.resolved_points()?,
        })
    }
}

/// A single output point in board-space coordinates.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResolvedTargetPoint {
    /// Point position `[x, y]` in board-space millimeters.
    pub position_mm: [f64; 2],
    /// Integer `(i, j)` grid label of the point, when it has one.
    #[serde(default)]
    pub grid: Option<Coord>,
    /// Logical ID of the point (e.g. ChArUco corner ID), when it has one.
    #[serde(default)]
    pub id: Option<u32>,
}

/// Full resolved layout for a single printable target document.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ResolvedTargetLayout {
    /// Page width in millimeters.
    pub page_width_mm: f64,
    /// Page height in millimeters.
    pub page_height_mm: f64,
    /// Board top-left origin `[x, y]` on the page, in millimeters.
    pub board_origin_mm: [f64; 2],
    /// Board width in millimeters.
    pub board_width_mm: f64,
    /// Board height in millimeters.
    pub board_height_mm: f64,
    /// Every resolved board point in board-space coordinates.
    pub points: Vec<ResolvedTargetPoint>,
}

/// Output file paths derived from a single stem.
///
/// Returned by [`StemPaths::from_stem`] (and the legacy [`stem_paths`]
/// shim). `#[non_exhaustive]` so that adding new bundled formats — DXF
/// today, potentially PDF or Gerber tomorrow — is not a breaking
/// change for cross-crate consumers, who must construct instances
/// through the named constructor.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StemPaths {
    /// `<stem>.json` — printable target description.
    pub json: PathBuf,
    /// `<stem>.svg` — vector rendering.
    pub svg: PathBuf,
    /// `<stem>.png` — raster rendering.
    pub png: PathBuf,
    /// `<stem>.dxf` — chrome-on-glass photolithography handoff (pattern only).
    pub dxf: PathBuf,
}

impl StemPaths {
    /// Compute the four output paths from a single filename stem by
    /// appending the format-specific extensions.
    pub fn from_stem(output_stem: impl AsRef<Path>) -> Self {
        let stem = output_stem.as_ref();
        Self {
            json: stem.with_extension("json"),
            svg: stem.with_extension("svg"),
            png: stem.with_extension("png"),
            dxf: stem.with_extension("dxf"),
        }
    }
}

/// Free-function alias for [`StemPaths::from_stem`].
///
/// Returns the four output paths derived from a single stem
/// (`<stem>.json`, `.svg`, `.png`, `.dxf`) as a [`StemPaths`] struct.
///
/// **0.9.0 breaking change:** prior versions of this function
/// returned a `(PathBuf, PathBuf, PathBuf)` tuple covering only the
/// JSON / SVG / PNG outputs. With the addition of DXF as a fourth
/// printable-target output, the return type is now the
/// `#[non_exhaustive]` [`StemPaths`] struct so future formats can be
/// added without further breaking changes. Callers that destructured
/// the tuple should switch to named-field access on the returned
/// struct (`let paths = stem_paths(...); paths.json` / `.svg` /
/// `.png` / `.dxf`).
pub fn stem_paths(output_stem: impl AsRef<Path>) -> StemPaths {
    StemPaths::from_stem(output_stem)
}

#[cfg(test)]
mod tests {
    use super::*;
    use calib_targets_aruco::builtins;
    use calib_targets_charuco::MarkerLayout;
    use calib_targets_marker::CirclePolarity;
    use calib_targets_marker::{CellCoords, MarkerCircleSpec as DetectorMarkerCircleSpec};

    fn sample_chessboard() -> PrintableTargetDocument {
        PrintableTargetDocument::new(TargetSpec::Chessboard(ChessboardTargetSpec {
            inner_rows: 6,
            inner_cols: 8,
            square_size_mm: 20.0,
        }))
    }

    fn sample_charuco() -> PrintableTargetDocument {
        PrintableTargetDocument::new(TargetSpec::Charuco(CharucoTargetSpec {
            rows: 5,
            cols: 7,
            square_size_mm: 15.0,
            marker_size_rel: 0.75,
            dictionary: builtins::builtin_dictionary("DICT_4X4_50").expect("dict"),
            marker_layout: MarkerLayout::OpenCvCharuco,
            border_bits: 1,
        }))
    }

    fn sample_marker_board() -> PrintableTargetDocument {
        PrintableTargetDocument::new(TargetSpec::MarkerBoard(MarkerBoardTargetSpec {
            inner_rows: 6,
            inner_cols: 8,
            square_size_mm: 20.0,
            circles: MarkerBoardTargetSpec::default_circles(6, 8),
            circle_diameter_rel: 0.5,
        }))
    }

    #[test]
    fn resolves_chessboard_points() {
        let doc = sample_chessboard();
        let layout = doc.resolve_layout().expect("layout");
        assert_eq!(layout.points.len(), 48);
        assert_eq!(layout.points[0].position_mm, [20.0, 20.0]);
        assert_eq!(layout.board_width_mm, 180.0);
        assert_eq!(layout.board_height_mm, 140.0);
    }

    #[test]
    fn resolves_charuco_points() {
        let doc = sample_charuco();
        let layout = doc.resolve_layout().expect("layout");
        assert_eq!(layout.points.len(), 24);
        assert_eq!(layout.points[0].id, Some(0));
        assert_eq!(layout.points[0].grid, Some(Coord::new(0, 0)));
    }

    #[test]
    fn rejects_board_that_does_not_fit_page() {
        let mut doc = sample_chessboard();
        doc.page.size = PageSize::Custom {
            width_mm: 50.0,
            height_mm: 50.0,
        };
        let err = doc.validate().expect_err("fit check");
        assert!(matches!(err, PrintableTargetError::BoardDoesNotFit { .. }));
    }

    #[test]
    fn rejects_duplicate_marker_circles() {
        let mut doc = sample_marker_board();
        if let TargetSpec::MarkerBoard(spec) = &mut doc.target {
            spec.circles = [
                MarkerCircleSpec {
                    i: 1,
                    j: 1,
                    polarity: CirclePolarity::White,
                },
                MarkerCircleSpec {
                    i: 1,
                    j: 1,
                    polarity: CirclePolarity::Black,
                },
                MarkerCircleSpec {
                    i: 2,
                    j: 2,
                    polarity: CirclePolarity::White,
                },
            ];
        }
        let err = doc.validate().expect_err("duplicate circles");
        assert!(matches!(err, PrintableTargetError::DuplicateCircleCells));
    }

    #[test]
    fn json_roundtrip_is_stable() {
        let doc = sample_charuco();
        let json = doc.to_json_pretty().expect("json");
        let parsed: PrintableTargetDocument = serde_json::from_str(&json).expect("parse");
        assert_eq!(parsed, doc);
    }

    #[test]
    fn builds_charuco_spec_from_board_spec_mm() {
        use calib_targets_charuco::CharucoBoardSpec;
        let board = CharucoBoardSpec::new(
            5,
            7,
            20.0,
            0.75,
            builtins::builtin_dictionary("DICT_4X4_50").expect("dict"),
        )
        .with_marker_layout(MarkerLayout::OpenCvCharuco);
        let spec = CharucoTargetSpec::from_board_spec_mm(&board);
        assert_eq!(spec.rows, board.rows);
        assert_eq!(spec.cols, board.cols);
        assert_eq!(spec.square_size_mm, 20.0);
        assert_eq!(spec.marker_size_rel, 0.75);
        assert_eq!(spec.dictionary.name(), board.dictionary.name());
        assert_eq!(spec.marker_layout, board.marker_layout);
        assert_eq!(spec.border_bits, 1);
    }

    #[test]
    fn builds_charuco_document_from_board_spec_mm() {
        use calib_targets_charuco::CharucoBoardSpec;
        let board = CharucoBoardSpec::new(
            5,
            7,
            20.0,
            0.75,
            builtins::builtin_dictionary("DICT_4X4_50").expect("dict"),
        )
        .with_marker_layout(MarkerLayout::OpenCvCharuco);
        let doc = PrintableTargetDocument::from_charuco_board_spec_mm(&board);
        assert!(matches!(
            &doc.target,
            TargetSpec::Charuco(spec)
                if spec.rows == 5
                    && spec.cols == 7
                    && spec.square_size_mm == 20.0
                    && spec.marker_size_rel == 0.75
                    && spec.border_bits == 1
        ));
        doc.validate().expect("valid printable charuco");
    }

    #[test]
    fn builds_marker_board_spec_from_layout_mm() {
        let layout = MarkerBoardSpec::new(
            6,
            8,
            [
                DetectorMarkerCircleSpec::new(CellCoords { i: 3, j: 2 }, CirclePolarity::White),
                DetectorMarkerCircleSpec::new(CellCoords { i: 4, j: 2 }, CirclePolarity::Black),
                DetectorMarkerCircleSpec::new(CellCoords { i: 4, j: 3 }, CirclePolarity::White),
            ],
        )
        .with_cell_size(20.0);
        let spec = MarkerBoardTargetSpec::try_from_layout_mm(&layout).expect("marker board spec");
        assert_eq!(spec.inner_rows, 6);
        assert_eq!(spec.inner_cols, 8);
        assert_eq!(spec.square_size_mm, 20.0);
        assert_eq!(
            spec.circles,
            [
                MarkerCircleSpec {
                    i: 3,
                    j: 2,
                    polarity: CirclePolarity::White,
                },
                MarkerCircleSpec {
                    i: 4,
                    j: 2,
                    polarity: CirclePolarity::Black,
                },
                MarkerCircleSpec {
                    i: 4,
                    j: 3,
                    polarity: CirclePolarity::White,
                },
            ]
        );
        assert_eq!(spec.circle_diameter_rel, 0.5);
    }

    #[test]
    fn builds_marker_board_document_from_layout_mm() {
        let layout = MarkerBoardSpec::new(
            6,
            8,
            [
                DetectorMarkerCircleSpec::new(CellCoords { i: 3, j: 2 }, CirclePolarity::White),
                DetectorMarkerCircleSpec::new(CellCoords { i: 4, j: 2 }, CirclePolarity::Black),
                DetectorMarkerCircleSpec::new(CellCoords { i: 4, j: 3 }, CirclePolarity::White),
            ],
        )
        .with_cell_size(20.0);
        let doc = PrintableTargetDocument::try_from_marker_board_layout_mm(&layout)
            .expect("marker board doc");
        assert!(matches!(
            &doc.target,
            TargetSpec::MarkerBoard(spec)
                if spec.inner_rows == 6
                    && spec.inner_cols == 8
                    && spec.square_size_mm == 20.0
                    && spec.circle_diameter_rel == 0.5
        ));
        doc.validate().expect("valid printable marker board");
    }

    #[test]
    fn rejects_marker_board_layout_without_cell_size() {
        let layout = MarkerBoardSpec::new(6, 8, MarkerBoardSpec::default().circles);
        let err =
            MarkerBoardTargetSpec::try_from_layout_mm(&layout).expect_err("missing cell size");
        assert!(matches!(
            err,
            PrintableTargetError::MissingMarkerBoardCellSize
        ));
    }

    #[test]
    fn rejects_negative_detector_circle_coords() {
        let layout = MarkerBoardSpec::new(
            6,
            8,
            [
                DetectorMarkerCircleSpec::new(CellCoords { i: -1, j: 2 }, CirclePolarity::White),
                DetectorMarkerCircleSpec::new(CellCoords { i: 4, j: 2 }, CirclePolarity::Black),
                DetectorMarkerCircleSpec::new(CellCoords { i: 4, j: 3 }, CirclePolarity::White),
            ],
        )
        .with_cell_size(20.0);
        let err =
            MarkerBoardTargetSpec::try_from_layout_mm(&layout).expect_err("negative detector cell");
        assert!(matches!(err, PrintableTargetError::InvalidCircleCell));
    }
}