1use std::collections::HashSet;
33use std::sync::{Arc, OnceLock, RwLock};
34
35use crate::plugin::{Config, ParamSpec, Value};
36use crate::{invalid, Result, RwLockExt};
37
38pub trait ShapeModel: Send + Sync {
40 fn name(&self) -> &str;
42 fn doc(&self) -> String {
44 String::new()
45 }
46 fn params(&self) -> Vec<ParamSpec> {
48 Vec::new()
49 }
50 fn prepare(&self, config: &Config) -> Result<Arc<dyn ShapeInstance>>;
52 fn example_config(&self) -> Option<Config> {
55 self.params()
56 .into_iter()
57 .map(|p| Some((p.name, p.default?)))
58 .collect()
59 }
60 fn example_radius(&self) -> f64 {
62 10.0
63 }
64}
65
66pub trait ShapeInstance: Send + Sync {
68 fn sag(&self, x: f64, y: f64) -> (f64, f64, f64);
70 fn dsag(&self, key: &str, x: f64, y: f64) -> Option<[f64; 3]> {
72 let _ = (key, x, y);
73 None
74 }
75 fn phase(&self, x: f64, y: f64) -> Option<(f64, f64, f64)> {
78 let _ = (x, y);
79 None
80 }
81 fn jones(&self, x: f64, y: f64, wl_um: f64) -> Option<[crate::coating::C64; 4]> {
85 let _ = (x, y, wl_um);
86 None
87 }
88}
89
90#[derive(Clone, serde::Serialize, serde::Deserialize)]
93#[serde(try_from = "UserShapeSpec", into = "UserShapeSpec")]
94pub struct UserShape {
95 pub model: String,
96 pub config: Config,
97 pub flip_z: bool,
99 pub mirror_x: bool,
101 inst: Arc<dyn ShapeInstance>,
102 has_phase: bool,
104}
105
106#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
108pub(crate) struct UserShapeSpec {
109 pub model: String,
111 #[serde(default)]
113 pub config: Config,
114 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
116 pub flip_z: bool,
117 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
119 pub mirror_x: bool,
120}
121
122impl TryFrom<UserShapeSpec> for UserShape {
123 type Error = crate::Error;
124 fn try_from(s: UserShapeSpec) -> Result<Self> {
125 let mut u = UserShape::new(&s.model, s.config)?;
126 u.flip_z = s.flip_z;
127 u.mirror_x = s.mirror_x;
128 Ok(u)
129 }
130}
131
132impl From<UserShape> for UserShapeSpec {
133 fn from(u: UserShape) -> Self {
134 UserShapeSpec {
135 model: u.model,
136 config: u.config,
137 flip_z: u.flip_z,
138 mirror_x: u.mirror_x,
139 }
140 }
141}
142
143impl schemars::JsonSchema for UserShape {
144 fn schema_name() -> std::borrow::Cow<'static, str> {
145 UserShapeSpec::schema_name()
146 }
147 fn json_schema(g: &mut schemars::SchemaGenerator) -> schemars::Schema {
148 UserShapeSpec::json_schema(g)
149 }
150}
151
152impl std::fmt::Debug for UserShape {
153 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154 f.debug_struct("UserShape")
155 .field("model", &self.model)
156 .field("config", &self.config)
157 .field("flip_z", &self.flip_z)
158 .field("mirror_x", &self.mirror_x)
159 .finish()
160 }
161}
162
163impl PartialEq for UserShape {
164 fn eq(&self, o: &Self) -> bool {
165 self.model == o.model
166 && self.config == o.config
167 && self.flip_z == o.flip_z
168 && self.mirror_x == o.mirror_x
169 }
170}
171
172impl UserShape {
173 pub fn new(model: &str, config: Config) -> Result<UserShape> {
175 let m = crate::ext::current().shape_model(model)?;
176 let inst = m.prepare(&config)?;
177 for (k, v) in &config {
178 if matches!(v, Value::Num(_)) {
179 UserKey::intern(k);
180 }
181 }
182 let has_phase = inst.phase(0.0, 0.0).is_some();
183 Ok(UserShape {
184 model: model.to_string(),
185 config,
186 flip_z: false,
187 mirror_x: false,
188 inst,
189 has_phase,
190 })
191 }
192
193 pub fn instance(&self) -> &dyn ShapeInstance {
195 self.inst.as_ref()
196 }
197
198 fn signs(&self) -> (f64, f64) {
199 (
200 if self.flip_z { -1.0 } else { 1.0 },
201 if self.mirror_x { -1.0 } else { 1.0 },
202 )
203 }
204
205 #[inline]
207 pub fn sag(&self, x: f64, y: f64) -> (f64, f64, f64) {
208 let (s, m) = self.signs();
209 let (z, zx, zy) = self.inst.sag(m * x, y);
210 (s * z, s * m * zx, s * zy)
211 }
212
213 pub fn dsag(&self, key: &str, x: f64, y: f64) -> Option<[f64; 3]> {
215 let (s, m) = self.signs();
216 let d = self.inst.dsag(key, m * x, y)?;
217 Some([s * d[0], s * m * d[1], s * d[2]])
218 }
219
220 pub fn has_phase(&self) -> bool {
222 self.has_phase
223 }
224
225 #[inline]
227 pub fn phase(&self, x: f64, y: f64) -> Option<(f64, f64, f64)> {
228 if !self.has_phase {
229 return None;
230 }
231 let (_, m) = self.signs();
232 let (p, px, py) = self.inst.phase(m * x, y)?;
233 Some((p, m * px, py))
234 }
235
236 pub fn has_jones(&self) -> bool {
238 self.inst.jones(0.0, 0.0, 0.55).is_some()
239 }
240
241 pub fn jones(&self, x: f64, y: f64, wl_um: f64) -> Option<[crate::coating::C64; 4]> {
243 let (_, m) = self.signs();
244 let j = self.inst.jones(m * x, y, wl_um)?;
245 Some(if self.mirror_x {
246 [j[0], -j[1], -j[2], j[3]]
247 } else {
248 j
249 })
250 }
251
252 pub fn paraxial_dphi(&self, h: f64) -> f64 {
254 match (self.phase(0.0, h), self.phase(0.0, -h)) {
255 (Some(a), Some(b)) => (a.2 - b.2) / (2.0 * h),
256 _ => 0.0,
257 }
258 }
259
260 pub fn value(&self, key: &str) -> Option<f64> {
262 match self.config.get(key)? {
263 Value::Num(v) => Some(*v),
264 _ => None,
265 }
266 }
267
268 pub fn with_value(&self, key: &str, v: f64) -> Result<UserShape> {
270 let mut config = self.config.clone();
271 config.insert(key.to_string(), Value::Num(v));
272 let mut u = UserShape::new(&self.model, config)?;
273 u.flip_z = self.flip_z;
274 u.mirror_x = self.mirror_x;
275 Ok(u)
276 }
277
278 pub fn paraxial_curv(&self, h: f64) -> f64 {
280 let (_, _, a) = self.sag(0.0, h);
281 let (_, _, b) = self.sag(0.0, -h);
282 (a - b) / (2.0 * h)
283 }
284}
285
286pub(crate) fn declare(m: &dyn ShapeModel) {
289 for p in m.params() {
290 if p.ty == crate::plugin::ParamType::Num && !p.name.is_empty() && !p.name.contains('.') {
291 UserKey::intern(&p.name);
292 }
293 }
294}
295
296pub fn paraxial_step(semi: f64) -> f64 {
298 if semi > 0.0 && semi.is_finite() {
299 1e-6 * semi
300 } else {
301 1e-5
302 }
303}
304
305#[derive(Debug, Clone, Copy)]
338pub struct UserKey(&'static str);
339
340impl PartialEq for UserKey {
341 fn eq(&self, o: &Self) -> bool {
342 std::ptr::eq(self.0, o.0)
344 }
345}
346impl Eq for UserKey {}
347impl std::hash::Hash for UserKey {
348 fn hash<H: std::hash::Hasher>(&self, h: &mut H) {
349 (self.0.as_ptr() as usize).hash(h)
350 }
351}
352impl PartialOrd for UserKey {
353 fn partial_cmp(&self, o: &Self) -> Option<std::cmp::Ordering> {
354 Some(self.cmp(o))
355 }
356}
357impl Ord for UserKey {
358 fn cmp(&self, o: &Self) -> std::cmp::Ordering {
359 self.0.cmp(o.0)
360 }
361}
362
363fn names() -> &'static RwLock<HashSet<&'static str>> {
364 static N: OnceLock<RwLock<HashSet<&'static str>>> = OnceLock::new();
365 N.get_or_init(Default::default)
366}
367
368impl UserKey {
369 pub fn get(name: &str) -> Option<UserKey> {
396 names().read_ok().get(name).map(|&n| UserKey(n))
397 }
398
399 fn intern(name: &str) -> UserKey {
401 if let Some(k) = UserKey::get(name) {
402 return k;
403 }
404 let mut n = names().write_ok();
405 if let Some(&s) = n.get(name) {
406 return UserKey(s);
407 }
408 let s: &'static str = Box::leak(name.to_string().into_boxed_str());
409 n.insert(s);
410 UserKey(s)
411 }
412
413 pub fn name(&self) -> &'static str {
415 self.0
416 }
417}
418
419impl serde::Serialize for UserKey {
420 fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
421 s.serialize_str(self.name())
422 }
423}
424
425impl<'de> serde::Deserialize<'de> for UserKey {
426 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
427 let s = String::deserialize(d)?;
428 UserKey::get(&s).ok_or_else(|| {
429 serde::de::Error::custom(format!("no user-defined shape has the number setting {s}"))
430 })
431 }
432}
433
434impl schemars::JsonSchema for UserKey {
435 fn schema_name() -> std::borrow::Cow<'static, str> {
436 "UserKey".into()
437 }
438 fn json_schema(g: &mut schemars::SchemaGenerator) -> schemars::Schema {
439 String::json_schema(g)
440 }
441}
442
443pub fn check_shape(model: &dyn ShapeModel, config: &Config, radius: f64) -> Result<()> {
449 let name = model.name();
450 if !(radius > 0.0 && radius.is_finite()) {
451 invalid!("check_shape: radius must be positive ({radius})");
452 }
453 let base = model.prepare(config)?;
454 let r = 1.2 * radius;
455 let n = 7;
456 let pts: Vec<(f64, f64)> = (0..n)
457 .flat_map(|i| (0..n).map(move |j| (i, j)))
458 .map(|(i, j)| {
459 let t = |k: usize| -r + 2.0 * r * k as f64 / (n - 1) as f64;
460 (t(i), t(j))
461 })
462 .filter(|&(x, y)| x * x + y * y <= r * r * (1.0 + 1e-12))
464 .collect();
465 let h = 1e-6 * radius;
466 for &(x, y) in &pts {
467 let (z, zx, zy) = base.sag(x, y);
468 if !(z.is_finite() && zx.is_finite() && zy.is_finite()) {
469 invalid!("user-defined shape model {name}: the sag is not finite at ({x}, {y}) (inside 1.2 × radius)");
470 }
471 let nx = (base.sag(x + h, y).0 - base.sag(x - h, y).0) / (2.0 * h);
472 let ny = (base.sag(x, y + h).0 - base.sag(x, y - h).0) / (2.0 * h);
473 let tol = |a: f64| 1e-5 * (1.0 + a.abs());
474 if (nx - zx).abs() > tol(zx) || (ny - zy).abs() > tol(zy) {
475 invalid!("user-defined shape model {name}: the gradient ({zx}, {zy}) at ({x}, {y}) does not match the difference of the sag ({nx}, {ny})");
476 }
477 if base.phase(0.0, 0.0).is_some() {
478 let ph = |x: f64, y: f64| base.phase(x, y).map(|p| p.0).unwrap_or(f64::NAN);
479 let fin = |p: &(f64, f64, f64)| p.0.is_finite() && p.1.is_finite() && p.2.is_finite();
480 let Some((_, px, py)) = base.phase(x, y).filter(fin) else {
481 invalid!("user-defined shape model {name}: the phase is not finite at ({x}, {y}) (inside 1.2 × radius)");
482 };
483 let nx = (ph(x + h, y) - ph(x - h, y)) / (2.0 * h);
484 let ny = (ph(x, y + h) - ph(x, y - h)) / (2.0 * h);
485 let tol = |a: f64| 1e-5 * (1.0 + a.abs());
486 if !((nx - px).abs() <= tol(px) && (ny - py).abs() <= tol(py)) {
487 invalid!("user-defined shape model {name}: the phase gradient ({px}, {py}) at ({x}, {y}) does not match the difference of the phase ({nx}, {ny})");
488 }
489 }
490 }
491 for (key, v) in config {
492 let v0 = match v {
493 Value::Num(v) => *v,
494 _ => continue,
495 };
496 if base.dsag(key, 0.0, 0.0).is_none() {
497 continue;
498 }
499 let dv = 1e-6 * (1.0 + v0.abs());
500 let at = |val: f64| -> Result<Arc<dyn ShapeInstance>> {
501 let mut c = config.clone();
502 c.insert(key.clone(), Value::Num(val));
503 model.prepare(&c)
504 };
505 let (p, m) = (at(v0 + dv)?, at(v0 - dv)?);
506 for &(x, y) in &pts {
507 let Some(d) = base.dsag(key, x, y) else {
508 invalid!("user-defined shape model {name}: dsag of {key} is given at the vertex but not at ({x}, {y})");
509 };
510 let (a, b) = (p.sag(x, y), m.sag(x, y));
511 let num = [
512 (a.0 - b.0) / (2.0 * dv),
513 (a.1 - b.1) / (2.0 * dv),
514 (a.2 - b.2) / (2.0 * dv),
515 ];
516 for i in 0..3 {
517 if (num[i] - d[i]).abs() > 1e-4 * (1.0 + d[i].abs()) {
518 invalid!("user-defined shape model {name}: dsag of {key} at ({x}, {y}) is {d:?} but the difference of the sag gives {num:?}");
519 }
520 }
521 }
522 }
523 Ok(())
524}