Skip to main content

lensbench_core/
material.rs

1//! 面の後ろの媒質(材料)。.zmx・系ファイルの名前の書き方(空・"AIR"・"MIRROR"・"-"・`nd,vd[,ΔPgF]`・ガラスの名前)は
2//! 読むときに [`Material::parse`] でこの型にし、名前に戻すのは [`Material::name`](serde も同じ文字列)。
3
4use std::fmt;
5
6/// 面の後ろの媒質
7#[derive(Debug, Clone, PartialEq, Default)]
8pub enum Material {
9    /// 空気(屈折率 1)
10    #[default]
11    Air,
12    /// 名前で引く媒質(カタログのガラス・GRIN の分布の名前・複屈折材の常光の材料)
13    Glass(String),
14    /// モデルガラス(Abbe 数 vd ≠ 0。ΔPgF は無ければ 0)
15    Model { nd: f64, vd: f64, dpgf: f64 },
16    /// どの波長でも同じ屈折率の媒質(分散のないモデルガラス、屈折率だけ決めた媒質)
17    Index(f64),
18    /// 鏡(後ろの媒質は前の媒質のまま)
19    Mirror,
20    /// 媒質を持たない面(座標ブレーク。後ろの媒質は前の媒質のまま)
21    Inherit,
22}
23
24impl Material {
25    /// 名前から。空・"AIR" は空気、"MIRROR" は鏡、"-" は媒質なし、`nd,vd[,ΔPgF]` はモデルガラス(vd = 0 は屈折率だけ)、
26    /// ほかはガラスの名前(前後の空白は除く。大文字小文字はガラスの名前では区別する)
27    pub fn parse(s: &str) -> Material {
28        let m = s.trim();
29        if m.is_empty() || m.eq_ignore_ascii_case("AIR") {
30            return Material::Air;
31        }
32        if m.eq_ignore_ascii_case("MIRROR") {
33            return Material::Mirror;
34        }
35        if m == "-" {
36            return Material::Inherit;
37        }
38        if let Some((nd, vd, dpgf)) = model_numbers(m) {
39            return if vd == 0.0 {
40                Material::Index(nd)
41            } else {
42                Material::Model { nd, vd, dpgf }
43            };
44        }
45        Material::Glass(m.to_string())
46    }
47
48    /// 名前([`Material::parse`] で同じ値に戻る。空気は空、屈折率だけの媒質は "nd,0")
49    pub fn name(&self) -> String {
50        match self {
51            Material::Air => String::new(),
52            Material::Glass(g) => g.clone(),
53            Material::Model { nd, vd, dpgf } if *dpgf == 0.0 => format!("{nd},{vd}"),
54            Material::Model { nd, vd, dpgf } => format!("{nd},{vd},{dpgf}"),
55            Material::Index(nd) => format!("{nd},0"),
56            Material::Mirror => "MIRROR".into(),
57            Material::Inherit => "-".into(),
58        }
59    }
60
61    /// 膜の境界の鍵・表示に使う媒質の名前(空気は "AIR"、屈折率だけの媒質は小数 2 桁に丸めた "1.52,0.0")
62    pub fn label(&self) -> String {
63        match self {
64            Material::Air => "AIR".into(),
65            Material::Index(nd) => format!("{nd:.2},0.0"),
66            m => m.name(),
67        }
68    }
69
70    pub fn is_air(&self) -> bool {
71        matches!(self, Material::Air)
72    }
73
74    pub fn is_mirror(&self) -> bool {
75        matches!(self, Material::Mirror)
76    }
77
78    /// 屈折率を持つ媒質(空気・ガラス・モデルガラス・屈折率だけ)。鏡と媒質なしは持たない
79    pub fn is_medium(&self) -> bool {
80        !matches!(self, Material::Mirror | Material::Inherit)
81    }
82
83    /// ガラスの名前(名前で引く媒質だけ)
84    pub fn glass(&self) -> Option<&str> {
85        match self {
86            Material::Glass(g) => Some(g),
87            _ => None,
88        }
89    }
90}
91
92impl fmt::Display for Material {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        f.write_str(&self.name())
95    }
96}
97
98/// 名前と比べる(名前を [`Material::parse`] で読んだ値と同じか。"AIR" と空は同じ)
99impl PartialEq<str> for Material {
100    fn eq(&self, other: &str) -> bool {
101        *self == Material::parse(other)
102    }
103}
104
105impl PartialEq<&str> for Material {
106    fn eq(&self, other: &&str) -> bool {
107        *self == Material::parse(other)
108    }
109}
110
111impl From<&str> for Material {
112    fn from(s: &str) -> Material {
113        Material::parse(s)
114    }
115}
116
117impl From<String> for Material {
118    fn from(s: String) -> Material {
119        Material::parse(&s)
120    }
121}
122
123/// モデルガラスの名前 "nd,vd[,dpgf]" の (nd, vd, dpgf)
124fn model_numbers(mat: &str) -> Option<(f64, f64, f64)> {
125    let v: Vec<f64> = mat
126        .split(',')
127        .map(|x| x.trim().parse::<f64>())
128        .collect::<std::result::Result<_, _>>()
129        .ok()?;
130    ((2..=3).contains(&v.len()) && v.iter().all(|x| x.is_finite()) && v[0] > 0.0)
131        .then(|| (v[0], v[1], v.get(2).copied().unwrap_or(0.0)))
132}
133
134impl serde::Serialize for Material {
135    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
136        s.serialize_str(&self.name())
137    }
138}
139
140impl<'de> serde::Deserialize<'de> for Material {
141    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Material, D::Error> {
142        let s = <String as serde::Deserialize>::deserialize(d)?;
143        Ok(Material::parse(&s))
144    }
145}
146
147impl schemars::JsonSchema for Material {
148    fn schema_name() -> std::borrow::Cow<'static, str> {
149        "Material".into()
150    }
151
152    fn json_schema(g: &mut schemars::SchemaGenerator) -> schemars::Schema {
153        <String as schemars::JsonSchema>::json_schema(g)
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    #[test]
162    fn names_round_trip() {
163        for s in [
164            "",
165            "MIRROR",
166            "-",
167            "N-BK7",
168            "1.5168,64.17",
169            "1.6,30,0.01",
170            "1.523456789,0",
171        ] {
172            let m = Material::parse(s);
173            assert_eq!(Material::parse(&m.name()), m, "{s}");
174        }
175        assert_eq!(Material::parse("AIR"), Material::Air);
176        assert_eq!(Material::parse("1.52,0.0"), Material::Index(1.52));
177        assert_eq!(Material::Index(1.5234).label(), "1.52,0.0");
178    }
179}