📄 sink/src/config.rs
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
//! Application configuration: CLI arguments, environment variables,
//! and TOML config files, all through one clap arg surface.
//!
//! Layering (by `clap_config`, see `from_merged`):
//!
//! 1. CLI arguments (`--rig-left-position "-0.4,0,0"`)
//! 2. environment variables (`KINECT_VIEW_RIG_LEFT_POSITION=-0.4,0,0`)
//! 3. the TOML config file (`--config-file` / `KINECT_VIEW_CONFIG_FILE`,
//!    keys snake_cased: `rig_left_position = [-0.4, 0.0, 0.0]`)
//! 4. built-in defaults (the development rig: a Kinect-like center
//!    camera and two webcams converged on the synthetic subject)
//!
//! Every setting is configurable in all four ways. The arg surface is
//! flat (clap_config has no nested-group support), so rig fields are
//! named `rig_<side>_<field>`.
//!
//! Rotation can be given three ways, with priority
//! `rotation_quat > rotation_deg > look_at`:
//!
//! * `rotation_quat = [x, y, z, w]` — exact COLMAP camera-to-world
//!   quaternion, e.g. from calibration output,
//! * `rotation_deg = [pitch, yaw, roll]` — human-friendly aviation
//!   angles (see [`rig::CameraPose::from_euler_deg`]),
//! * `look_at = [x, y, z]` — converge the camera on a point (the
//!   default: `[0, 0, 2]`, the subject).

use std::path::PathBuf;

use anyhow::{Context, Result, ensure};
use clap::{CommandFactory, Parser};
use clap_config::ClapConfig;
use glam::{Quat, UVec2, Vec3};
use serde::{Deserialize, Serialize};

use rig::{Camera, CameraIntrinsics, CameraPose, Rig};

/// Load the configuration from argv (CLI + environment), merged with
/// the config file named by `--config-file` / `KINECT_VIEW_CONFIG_FILE`,
/// if any.
pub fn load() -> Result<Args> {
    load_from(std::env::args_os())
}

/// Like [`load`], but from an explicit argv (tests).
pub fn load_from<I, T>(argv: I) -> Result<Args>
where
    I: IntoIterator<Item = T>,
    T: Into<std::ffi::OsString> + Clone,
{
    let matches = Args::command().get_matches_from(argv);
    let config_file = matches.get_one::<PathBuf>("config_file").cloned();

    let file_config = match config_file {
        Some(path) if !path.as_os_str().is_empty() => {
            let text = std::fs::read_to_string(&path)
                .with_context(|| format!("reading config file {}", path.display()))?;
            let parsed: ArgsConfig = toml::from_str(&text)
                .with_context(|| format!("parsing config file {}", path.display()))?;
            Some(parsed)
        }
        _ => None,
    };

    Ok(Args::from_merged(matches, file_config))
}

/// The application arguments; also the shape of the config file (see
/// the [module docs](self) for layering).
#[derive(ClapConfig, Parser, Debug, Clone)]
pub struct Args {
    /// Path to a TOML config file. Settings there are overridden by
    /// environment variables and CLI arguments.
    #[clap_config(skip)]
    #[arg(long, env = "KINECT_VIEW_CONFIG_FILE")]
    pub config_file: Option<PathBuf>,

    // -- rig.left: the left webcam -----------------------------------
    /// Left camera identifier (device name/serial on the physical rig).
    #[arg(long, env = "KINECT_VIEW_RIG_LEFT_ID", default_value = "left")]
    pub rig_left_id: String,
    /// Left camera position, metres: `x,y,z`.
    #[arg(
        long,
        env = "KINECT_VIEW_RIG_LEFT_POSITION",
        default_value = "-0.4,0,0"
    )]
    pub rig_left_position: Position3,
    /// Point the left camera at, metres: `x,y,z` (used when no explicit
    /// rotation is set).
    #[arg(long, env = "KINECT_VIEW_RIG_LEFT_LOOK_AT", default_value = "0,0,2")]
    pub rig_left_look_at: Position3,
    /// Left camera rotation as `pitch,yaw,roll` degrees (overrides
    /// look-at).
    #[arg(long, env = "KINECT_VIEW_RIG_LEFT_ROTATION_DEG")]
    pub rig_left_rotation_deg: Option<RotationEulerDeg>,
    /// Left camera rotation as an `x,y,z,w` quaternion (overrides
    /// rotation-deg and look-at).
    #[arg(long, env = "KINECT_VIEW_RIG_LEFT_ROTATION_QUAT")]
    pub rig_left_rotation_quat: Option<RotationQuat>,
    /// Left camera resolution, pixels: `width,height`.
    #[arg(
        long,
        env = "KINECT_VIEW_RIG_LEFT_RESOLUTION",
        default_value = "640,480"
    )]
    pub rig_left_resolution: Resolution2,
    /// Left camera intrinsics, pixels: `fx,fy,cx,cy` (at its resolution).
    #[arg(
        long,
        env = "KINECT_VIEW_RIG_LEFT_INTRINSICS",
        default_value = "554.256,415.692,320,240"
    )]
    pub rig_left_intrinsics: Intrinsics,

    // -- rig.center: the Kinect depth camera --------------------------
    /// Center camera identifier.
    #[arg(long, env = "KINECT_VIEW_RIG_CENTER_ID", default_value = "kinect")]
    pub rig_center_id: String,
    /// Center camera position, metres: `x,y,z`.
    #[arg(long, env = "KINECT_VIEW_RIG_CENTER_POSITION", default_value = "0,0,0")]
    pub rig_center_position: Position3,
    /// Point the center camera at, metres: `x,y,z`.
    #[arg(long, env = "KINECT_VIEW_RIG_CENTER_LOOK_AT", default_value = "0,0,2")]
    pub rig_center_look_at: Position3,
    /// Center camera rotation as `pitch,yaw,roll` degrees.
    #[arg(long, env = "KINECT_VIEW_RIG_CENTER_ROTATION_DEG")]
    pub rig_center_rotation_deg: Option<RotationEulerDeg>,
    /// Center camera rotation as an `x,y,z,w` quaternion.
    #[arg(long, env = "KINECT_VIEW_RIG_CENTER_ROTATION_QUAT")]
    pub rig_center_rotation_quat: Option<RotationQuat>,
    /// Center camera resolution, pixels: `width,height`.
    #[arg(
        long,
        env = "KINECT_VIEW_RIG_CENTER_RESOLUTION",
        default_value = "256,212"
    )]
    pub rig_center_resolution: Resolution2,
    /// Center camera intrinsics, pixels: `fx,fy,cx,cy`.
    #[arg(
        long,
        env = "KINECT_VIEW_RIG_CENTER_INTRINSICS",
        default_value = "182.803,183.597,128,106"
    )]
    pub rig_center_intrinsics: Intrinsics,

    // -- rig.right: the right webcam ---------------------------------
    /// Right camera identifier (device name/serial on the physical rig).
    #[arg(long, env = "KINECT_VIEW_RIG_RIGHT_ID", default_value = "right")]
    pub rig_right_id: String,
    /// Right camera position, metres: `x,y,z`.
    #[arg(
        long,
        env = "KINECT_VIEW_RIG_RIGHT_POSITION",
        default_value = "0.4,0,0"
    )]
    pub rig_right_position: Position3,
    /// Point the right camera at, metres: `x,y,z`.
    #[arg(long, env = "KINECT_VIEW_RIG_RIGHT_LOOK_AT", default_value = "0,0,2")]
    pub rig_right_look_at: Position3,
    /// Right camera rotation as `pitch,yaw,roll` degrees.
    #[arg(long, env = "KINECT_VIEW_RIG_RIGHT_ROTATION_DEG")]
    pub rig_right_rotation_deg: Option<RotationEulerDeg>,
    /// Right camera rotation as an `x,y,z,w` quaternion.
    #[arg(long, env = "KINECT_VIEW_RIG_RIGHT_ROTATION_QUAT")]
    pub rig_right_rotation_quat: Option<RotationQuat>,
    /// Right camera resolution, pixels: `width,height`.
    #[arg(
        long,
        env = "KINECT_VIEW_RIG_RIGHT_RESOLUTION",
        default_value = "640,480"
    )]
    pub rig_right_resolution: Resolution2,
    /// Right camera intrinsics, pixels: `fx,fy,cx,cy`.
    #[arg(
        long,
        env = "KINECT_VIEW_RIG_RIGHT_INTRINSICS",
        default_value = "554.256,415.692,320,240"
    )]
    pub rig_right_intrinsics: Intrinsics,

    // -- scene / source / view ----------------------------------------
    /// Where the synthetic subject sits, metres (the scene is built
    /// around it; the default rig converges on it).
    #[arg(
        long,
        env = "KINECT_VIEW_SCENE_SUBJECT_POSITION",
        default_value = "0,0,2"
    )]
    pub scene_subject_position: Position3,
    /// Playback rate of the frame source, frames per second.
    #[arg(long, env = "KINECT_VIEW_SOURCE_FPS", default_value = "30.0")]
    pub source_fps: f32,
    /// Render background colour, `r,g,b` floats in `[0, 1]`.
    #[arg(long, env = "KINECT_VIEW_BACKGROUND", default_value = "0.10,0.10,0.12")]
    pub background: ColorRgb,
}

impl Args {
    /// Validate the merged settings and build the typed values the app
    /// runs on.
    pub fn resolve(&self) -> Result<ResolvedConfig> {
        let left = camera_from(
            self.rig_left_id.clone(),
            self.rig_left_position,
            self.rig_left_look_at,
            self.rig_left_rotation_deg,
            self.rig_left_rotation_quat,
            self.rig_left_resolution,
            self.rig_left_intrinsics,
        )?;
        let center = camera_from(
            self.rig_center_id.clone(),
            self.rig_center_position,
            self.rig_center_look_at,
            self.rig_center_rotation_deg,
            self.rig_center_rotation_quat,
            self.rig_center_resolution,
            self.rig_center_intrinsics,
        )?;
        let right = camera_from(
            self.rig_right_id.clone(),
            self.rig_right_position,
            self.rig_right_look_at,
            self.rig_right_rotation_deg,
            self.rig_right_rotation_quat,
            self.rig_right_resolution,
            self.rig_right_intrinsics,
        )?;

        let fps = self.source_fps;
        ensure!(fps > 0.0, "source-fps must be positive, got {fps}");

        Ok(ResolvedConfig {
            rig: Rig {
                left,
                center,
                right,
            },
            subject: self.scene_subject_position.0.into(),
            fps,
            background: self.background.0.into(),
        })
    }
}

/// The validated, typed configuration the app runs on.
#[derive(Debug, Clone, PartialEq)]
pub struct ResolvedConfig {
    pub rig: Rig,
    /// The synthetic subject position, metres.
    pub subject: Vec3,
    /// Frame source rate, fps.
    pub fps: f32,
    /// Render background colour.
    pub background: Vec3,
}

/// Build one rig camera from its merged args. Rotation priority:
/// quaternion > euler degrees > look-at.
#[allow(clippy::too_many_arguments)]
fn camera_from(
    id: String,
    position: Position3,
    look_at: Position3,
    rotation_deg: Option<RotationEulerDeg>,
    rotation_quat: Option<RotationQuat>,
    resolution: Resolution2,
    intrinsics: Intrinsics,
) -> Result<Camera> {
    let [w, h] = resolution.0;
    ensure!(
        w > 0 && h > 0,
        "{id}: resolution must be positive, got {w}x{h}"
    );
    let [fx, fy, cx, cy] = intrinsics.0;
    ensure!(
        fx.is_finite() && fx > 0.0 && fy.is_finite() && fy > 0.0,
        "{id}: focal lengths must be positive, got fx={fx}, fy={fy}"
    );

    let pose = if let Some(quat) = rotation_quat {
        let rotation = Quat::from_array(quat.0);
        ensure!(
            rotation.length_squared() > 1e-12,
            "{id}: rotation quaternion must be non-zero"
        );
        CameraPose {
            position: position.0.into(),
            rotation: rotation.normalize(),
        }
    } else if let Some(euler) = rotation_deg {
        CameraPose::from_euler_deg(position.0.into(), euler.0[0], euler.0[1], euler.0[2])
    } else {
        CameraPose::looking_at(position.0.into(), look_at.0.into())
    };

    Ok(Camera {
        id,
        pose,
        intrinsics: CameraIntrinsics { fx, fy, cx, cy },
        resolution: UVec2::new(w, h),
    })
}

// ---------------------------------------------------------------------------
// Value types: comma-separated on the CLI, arrays in TOML.

macro_rules! comma_value_type {
    ($(#[$meta:meta])* $name:ident, [$elem:ty; $n:literal]) => {
        $(#[$meta])*
        #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
        pub struct $name(pub [$elem; $n]);

        impl std::str::FromStr for $name {
            type Err = String;

            fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
                let values: std::result::Result<Vec<$elem>, _> = s
                    .split(',')
                    .map(|part| part.trim().parse::<$elem>())
                    .collect();
                let values = values
                    .map_err(|e| format!("invalid {} value in `{s}`: {e}", stringify!($name)))?;
                if values.len() != $n {
                    return Err(format!(
                        "{} expects {} comma-separated values, got {}",
                        stringify!($name),
                        $n,
                        values.len()
                    ));
                }
                Ok(Self(values.try_into().expect("checked length")))
            }
        }

        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                let parts: Vec<String> = self.0.iter().map(|v| v.to_string()).collect();
                write!(f, "{}", parts.join(","))
            }
        }
    };
}

comma_value_type!(
    /// A 3D position, metres: `x,y,z`.
    Position3,
    [f32; 3]
);
comma_value_type!(
    /// Aviation-style rotation, degrees: `pitch,yaw,roll`.
    RotationEulerDeg,
    [f32; 3]
);
comma_value_type!(
    /// A quaternion, `x,y,z,w`.
    RotationQuat,
    [f32; 4]
);
comma_value_type!(
    /// Pinhole intrinsics, pixels: `fx,fy,cx,cy`.
    Intrinsics,
    [f32; 4]
);
comma_value_type!(
    /// An image resolution, pixels: `width,height`.
    Resolution2,
    [u32; 2]
);
comma_value_type!(
    /// An RGB colour, floats in `[0, 1]`: `r,g,b`.
    ColorRgb,
    [f32; 3]
);

#[cfg(test)]
mod tests {
    use super::*;
    use glam::vec3;
    use replay::synth::dev_rig;
    use std::collections::BTreeMap;
    use std::sync::Mutex;

    /// clap reads the whole environment when building matches, and the
    /// env test mutates it, so all config tests serialize on this lock.
    static TEST_LOCK: Mutex<()> = Mutex::new(());

    fn merged(argv: &[&str], file: Option<&str>) -> Args {
        let matches = Args::command().get_matches_from(argv.iter().copied());
        let file_config = file.map(|text| {
            let parsed: ArgsConfig = toml::from_str(text).expect("test config parses");
            parsed
        });
        Args::from_merged(matches, file_config)
    }

    #[test]
    fn defaults_match_the_dev_rig() {
        let _guard = TEST_LOCK.lock().unwrap();
        let args = merged(&["app"], None).resolve().expect("defaults resolve");
        let dev = dev_rig();

        // Poses are exact: both go through looking_at with the same
        // positions and target.
        assert_eq!(args.rig.left.pose, dev.left.pose);
        assert_eq!(args.rig.center.pose, dev.center.pose);
        assert_eq!(args.rig.right.pose, dev.right.pose);
        assert_eq!(args.rig.left.id, "left");
        assert_eq!(args.rig.center.id, "kinect");
        assert_eq!(args.rig.right.id, "right");
        assert_eq!(args.rig.left.resolution, dev.left.resolution);
        assert_eq!(args.rig.center.resolution, dev.center.resolution);
        assert_eq!(args.rig.right.resolution, dev.right.resolution);
        // Intrinsics are decimal-rounded defaults; the dev rig computes
        // them from focal ratios.
        for (got, want) in [
            (args.rig.left.intrinsics, dev.left.intrinsics),
            (args.rig.center.intrinsics, dev.center.intrinsics),
            (args.rig.right.intrinsics, dev.right.intrinsics),
        ] {
            assert!((got.fx - want.fx).abs() < 1e-2);
            assert!((got.fy - want.fy).abs() < 1e-2);
            assert_eq!((got.cx, got.cy), (want.cx, want.cy));
        }
        assert_eq!(args.subject, vec3(0.0, 0.0, 2.0));
        assert_eq!(args.fps, 30.0);
        assert_eq!(args.background, vec3(0.10, 0.10, 0.12));
    }

    #[test]
    fn file_overrides_defaults() {
        let _guard = TEST_LOCK.lock().unwrap();
        let args = merged(
            &["app"],
            Some("rig_left_position = [1.0, 0.0, 0.0]\nsource_fps = 12.5\n"),
        )
        .resolve()
        .expect("resolves");
        assert_eq!(args.rig.left.pose.position, vec3(1.0, 0.0, 0.0));
        assert_eq!(args.fps, 12.5);
        // Everything else keeps its default.
        assert_eq!(args.rig.right.pose.position, vec3(0.4, 0.0, 0.0));
    }

    #[test]
    fn cli_beats_file_beats_defaults() {
        let _guard = TEST_LOCK.lock().unwrap();
        let args = merged(
            &["app", "--rig-right-position", "1,2,3"],
            Some("rig_right_position = [9.0, 9.0, 9.0]\nrig_left_position = [8.0, 0.0, 0.0]\n"),
        )
        .resolve()
        .expect("resolves");
        // CLI wins over the file…
        assert_eq!(args.rig.right.pose.position, vec3(1.0, 2.0, 3.0));
        // …the file wins over defaults…
        assert_eq!(args.rig.left.pose.position, vec3(8.0, 0.0, 0.0));
        // …and untouched fields keep their defaults.
        assert_eq!(args.rig.center.pose.position, vec3(0.0, 0.0, 0.0));
    }

    #[test]
    fn env_beats_file_and_cli_beats_env() {
        let _guard = TEST_LOCK.lock().unwrap();
        // Environment mutation races between tests and is unsafe in
        // edition 2024, so both layers are exercised in one test, in
        // order, with a variable nothing else touches.
        let var = "KINECT_VIEW_RIG_CENTER_POSITION";
        unsafe { std::env::set_var(var, "5,0,0") };
        let args = merged(&["app"], Some("rig_center_position = [8.0, 8.0, 8.0]\n"))
            .resolve()
            .expect("resolves");
        assert_eq!(args.rig.center.pose.position, vec3(5.0, 0.0, 0.0));

        let args = merged(
            &["app", "--rig-center-position", "7,0,0"],
            Some("rig_center_position = [8.0, 8.0, 8.0]\n"),
        )
        .resolve()
        .expect("resolves");
        assert_eq!(args.rig.center.pose.position, vec3(7.0, 0.0, 0.0));
        unsafe { std::env::remove_var(var) };
    }

    #[test]
    fn rotation_priority_quat_over_euler_over_look_at() {
        let _guard = TEST_LOCK.lock().unwrap();
        let args = merged(
            &["app"],
            Some(concat!(
                "rig_left_rotation_quat = [0.0, 0.0, 0.0, 1.0]\n",
                "rig_left_rotation_deg = [0.0, 90.0, 0.0]\n",
            )),
        )
        .resolve()
        .expect("resolves");
        // Identity quaternion: looking straight down +Z (not at the
        // default look-at target).
        assert!((args.rig.left.pose.rotation * Vec3::Z - Vec3::Z).length() < 1e-6);

        // Without the quaternion, euler wins over look-at.
        let args = merged(&["app"], Some("rig_left_rotation_deg = [0.0, 90.0, 0.0]\n"))
            .resolve()
            .expect("resolves");
        assert!((args.rig.left.pose.rotation * Vec3::Z - Vec3::X).length() < 1e-4);

        // And with neither, look-at applies.
        let args = merged(&["app"], None).resolve().expect("resolves");
        let forward = args.rig.left.pose.rotation * Vec3::Z;
        let to_subject = (vec3(0.0, 0.0, 2.0) - args.rig.left.pose.position).normalize();
        assert!(forward.dot(to_subject) > 0.999);
    }

    #[test]
    fn invalid_values_are_rejected() {
        let _guard = TEST_LOCK.lock().unwrap();
        // Comma parsing.
        assert!("1,2".parse::<Position3>().is_err());
        assert!("a,b,c".parse::<Position3>().is_err());
        assert!("1,2,3".parse::<Position3>().is_ok());
        assert!("640, 480".parse::<Resolution2>().is_ok()); // spaces ok

        // Zero quaternion.
        let err = merged(
            &["app"],
            Some("rig_left_rotation_quat = [0.0, 0.0, 0.0, 0.0]\n"),
        )
        .resolve()
        .expect_err("zero quaternion");
        assert!(err.to_string().contains("non-zero"));

        // Bad resolution.
        let err = merged(&["app", "--rig-left-resolution", "0,480"], None)
            .resolve()
            .expect_err("zero resolution");
        assert!(err.to_string().contains("resolution"));

        // Bad fps.
        let err = merged(&["app", "--source-fps", "0"], None)
            .resolve()
            .expect_err("zero fps");
        assert!(err.to_string().contains("fps"));

        // Missing config file.
        let err = load_from(["app", "--config-file", "/nonexistent/kinect-view.toml"])
            .expect_err("missing file");
        assert!(err.to_string().contains("reading config file"));

        // Malformed config file.
        let err = load_from(["app", "--config-file", "Cargo.toml"])
            .map(|_| ()) // Cargo.toml is TOML, but not this shape.
            .err();
        // Any outcome here is fine as long as it doesn't panic; the
        // error (if any) should mention the config file.
        if let Some(err) = err {
            assert!(err.to_string().contains("config file"));
        }
    }

    #[test]
    fn value_types_round_trip_as_strings_and_toml() {
        let _guard = TEST_LOCK.lock().unwrap();
        let pos: Position3 = "-0.4,0,1".parse().expect("parses");
        assert_eq!(pos.0, [-0.4, 0.0, 1.0]);
        // In a TOML document the value is an array.
        let text = toml::to_string(&BTreeMap::from([("v".to_string(), pos)])).expect("serializes");
        assert!(text.contains("v = [-0.4,"), "unexpected TOML: {text}");
        let back: BTreeMap<String, Position3> = toml::from_str(&text).expect("deserializes");
        assert_eq!(back["v"], pos);
        // And the CLI form round-trips through Display/FromStr.
        let printed = pos.to_string();
        assert_eq!(printed.parse::<Position3>().unwrap(), pos);
    }
}