lensbench_core/
material.rs1use std::fmt;
5
6#[derive(Debug, Clone, PartialEq, Default)]
8pub enum Material {
9 #[default]
11 Air,
12 Glass(String),
14 Model { nd: f64, vd: f64, dpgf: f64 },
16 Index(f64),
18 Mirror,
20 Inherit,
22}
23
24impl Material {
25 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 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 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 pub fn is_medium(&self) -> bool {
80 !matches!(self, Material::Mirror | Material::Inherit)
81 }
82
83 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
98impl 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
123fn 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}