1use super::*;
4use lensbench_core::error::{code, Error};
5use lensbench_core::system::{GlassTemplate, InputPolarization};
6
7#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
8pub struct Wave {
9 pub um: f64,
10 #[serde(default = "wave_weight")]
11 pub weight: f64,
12}
13
14#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
15pub struct ApertureSpec {
16 #[serde(rename = "type")]
17 pub kind: ApertureKind,
18 #[serde(default)]
19 pub value: f64,
20}
21
22pub use lensbench_core::system::FieldKind;
24
25#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
27#[serde(tag = "cond", rename_all = "snake_case")]
28pub enum FieldSolveSpec {
29 Position { surface: String },
31 DirSum { s1: String, s2: String },
33 DirDiff { s1: String, s2: String },
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
38pub struct FieldsSpec {
39 #[serde(rename = "type", default)]
40 pub kind: FieldKind,
41 pub points: Vec<[f64; 2]>,
43 #[serde(default)]
44 pub weights: Vec<f64>,
45 #[serde(default, skip_serializing_if = "Option::is_none")]
47 pub solve: Option<FieldSolveSpec>,
48 #[serde(default, skip_serializing_if = "is_radial")]
50 pub norm: FieldNorm,
51 #[serde(default, skip_serializing_if = "Vec::is_empty")]
53 pub vignetting: Vec<[f64; 5]>,
54}
55
56fn is_radial(n: &FieldNorm) -> bool {
57 *n == FieldNorm::Radial
58}
59
60impl Default for FieldsSpec {
61 fn default() -> Self {
62 FieldsSpec {
63 kind: FieldKind::Angle,
64 points: vec![[0.0, 0.0]],
65 weights: Vec::new(),
66 solve: None,
67 norm: FieldNorm::Radial,
68 vignetting: Vec::new(),
69 }
70 }
71}
72
73#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default, JsonSchema)]
74#[serde(rename_all = "snake_case")]
75pub enum OffMode {
76 #[default]
78 Collapse,
79 Air,
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
85pub struct Place {
86 #[serde(default = "yes")]
87 pub on: bool,
88 #[serde(default)]
89 pub off: OffMode,
90 #[serde(default)]
92 pub decenter: [f64; 2],
93 #[serde(default)]
95 pub tilt: [f64; 3],
96}
97
98impl Default for Place {
99 fn default() -> Self {
100 Place {
101 on: true,
102 off: OffMode::Collapse,
103 decenter: [0.0; 2],
104 tilt: [0.0; 3],
105 }
106 }
107}
108
109impl Place {
110 pub(crate) fn moved(&self) -> bool {
111 self.decenter
112 .iter()
113 .chain(self.tilt.iter())
114 .any(|v| *v != 0.0)
115 }
116}
117
118#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
120pub struct SurfSpec {
121 #[serde(default)]
123 pub radius: Option<f64>,
124 #[serde(default)]
125 pub conic: f64,
126 #[serde(default)]
128 pub asph: Vec<f64>,
129 #[serde(default)]
131 pub t: f64,
132 #[serde(default)]
134 pub glass: Option<String>,
135 #[serde(default)]
137 pub semi: Semi,
138 #[serde(default)]
139 pub coat: String,
140 #[serde(default)]
141 pub comment: String,
142 #[serde(default, skip_serializing_if = "Option::is_none")]
144 pub jones: Option<[f64; 8]>,
145 #[serde(default, skip_serializing_if = "Option::is_none")]
147 pub polarizer: Option<PolarizerSpec>,
148 #[serde(default, skip_serializing_if = "Option::is_none")]
150 pub waveplate: Option<WaveplateSpec>,
151 #[serde(default, skip_serializing_if = "Option::is_none")]
153 pub tilt: Option<[f64; 2]>,
154 #[serde(default, skip_serializing_if = "Option::is_none")]
156 pub coordbrk: Option<[f64; 5]>,
157 #[serde(default, skip_serializing_if = "is_zero_u8")]
159 pub order: u8,
160 #[serde(default, skip_serializing_if = "Option::is_none")]
162 pub aperture: Option<SurfAperture>,
163 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
165 pub ignore: bool,
166 #[serde(default, skip_serializing_if = "Option::is_none")]
168 pub birefringent: Option<BireSpec>,
169 #[serde(default, skip_serializing_if = "SurfShape::is_standard")]
174 pub shape: SurfShape,
175 #[serde(default, skip_serializing_if = "Option::is_none")]
177 pub radius_x: Option<f64>,
178 #[serde(default, skip_serializing_if = "Option::is_none")]
182 pub row: Option<Box<crate::sysfile_v2::Row>>,
183}
184
185#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
187#[serde(rename_all = "snake_case")]
188pub enum SurfShape {
189 #[default]
191 Standard,
192 OddAsph,
194 Toroidal,
196 Fresnel,
198}
199
200impl SurfShape {
201 pub(crate) fn is_standard(&self) -> bool {
202 *self == SurfShape::Standard
203 }
204}
205
206#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
208#[serde(rename_all = "snake_case")]
209pub enum BireSpec {
210 In {
211 #[serde(default = "two_u8")]
213 mode: u8,
214 axis: [f64; 3],
216 },
217 Out,
218}
219
220pub(crate) fn two_u8() -> u8 {
221 2
222}
223
224#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
226#[serde(untagged)]
227pub enum Semi {
228 Value(f64),
229 Auto(AutoWord),
230}
231
232#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
234#[serde(rename_all = "lowercase")]
235pub enum AutoWord {
236 Auto,
237}
238
239impl Default for Semi {
240 fn default() -> Self {
241 Semi::Value(0.0)
242 }
243}
244
245impl From<f64> for Semi {
246 fn from(v: f64) -> Self {
247 Semi::Value(v)
248 }
249}
250
251impl Semi {
252 pub const AUTO: Semi = Semi::Auto(AutoWord::Auto);
253
254 pub fn value(self) -> f64 {
256 match self {
257 Semi::Value(v) => v,
258 Semi::Auto(_) => 0.0,
259 }
260 }
261
262 pub fn is_auto(self) -> bool {
263 matches!(self, Semi::Auto(_))
264 }
265
266 pub fn of(d: &Surface) -> Semi {
268 if d.semi_auto {
269 Semi::AUTO
270 } else {
271 Semi::Value(d.semi)
272 }
273 }
274}
275
276pub(crate) fn is_zero_u8(v: &u8) -> bool {
277 *v == 0
278}
279
280pub(crate) fn inf_f64() -> f64 {
281 f64::INFINITY
282}
283
284pub(crate) fn is_inf(x: &f64) -> bool {
285 x.is_infinite()
286}
287
288#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
290pub struct PolarizerSpec {
291 #[serde(default)]
293 pub axis_deg: f64,
294 #[serde(default = "inf_f64", skip_serializing_if = "is_inf")]
296 pub extinction_ratio: f64,
297 #[serde(default = "one_f64")]
299 pub transmittance: f64,
300}
301
302#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
306pub struct WaveplateSpec {
307 #[serde(default)]
309 pub retardance: f64,
310 pub wavelength_um: f64,
312 #[serde(default)]
314 pub axis_deg: f64,
315 #[serde(default)]
317 pub order: u32,
318 #[serde(default = "one_f64")]
320 pub transmittance: f64,
321 #[serde(default, skip_serializing_if = "Option::is_none")]
323 pub material: Option<String>,
324 #[serde(default, skip_serializing_if = "Option::is_none")]
326 pub thickness_mm: Option<f64>,
327 #[serde(default, skip_serializing_if = "Vec::is_empty")]
329 pub plates: Vec<PlateSpec>,
330}
331
332#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
334pub struct PlateSpec {
335 pub material: String,
337 pub thickness_mm: f64,
339 #[serde(default)]
341 pub axis_deg: f64,
342}
343
344impl PolarizerSpec {
345 pub fn retarder(&self) -> lensbench_core::Result<lensbench_core::surface::Retarder> {
346 if !(self.transmittance >= 0.0 && self.transmittance <= 1.0) {
347 return Err(format!("polarizer transmittance {} (0 to 1)", self.transmittance).into());
348 }
349 if self.extinction_ratio.is_nan() || self.extinction_ratio < 1.0 {
350 return Err(format!(
351 "polarizer extinction ratio {} (1 or more)",
352 self.extinction_ratio
353 )
354 .into());
355 }
356 Ok(lensbench_core::surface::Retarder {
357 axis_deg: self.axis_deg,
358 tx: self.transmittance.sqrt(),
359 ty: (self.transmittance / self.extinction_ratio).sqrt(),
360 retardance: 0.0,
361 order: 0,
362 wl0: 1.0,
363 plates: Vec::new(),
364 })
365 }
366}
367
368impl WaveplateSpec {
369 pub fn retarder(&self) -> lensbench_core::Result<lensbench_core::surface::Retarder> {
370 if !(self.wavelength_um > 0.0 && self.wavelength_um.is_finite()) {
371 return Err(format!("waveplate design wavelength {} µm", self.wavelength_um).into());
372 }
373 if !(self.transmittance >= 0.0 && self.transmittance <= 1.0) {
374 return Err(format!("waveplate transmittance {} (0 to 1)", self.transmittance).into());
375 }
376 if !self.retardance.is_finite() {
377 return Err("the waveplate retardance is not a number".into());
378 }
379 use lensbench_core::surface::Plate;
380 let plate = |m: &str, d: f64, a: f64| Plate {
381 material: m.trim().to_string(),
382 thickness: d,
383 axis_deg: a,
384 o: None,
385 e: None,
386 };
387 let plates = match (&self.material, self.plates.is_empty()) {
388 (Some(_), false) => {
389 return Err("a waveplate can't have both material and plates".into())
390 }
391 (Some(m), true) => {
392 let d = self.thickness_mm.unwrap_or(0.0);
393 if self.thickness_mm.is_some() && !(d > 0.0 && d.is_finite()) {
394 return Err(format!("waveplate thickness {d} mm").into());
395 }
396 let total = self.order as f64 + self.retardance;
397 if self.thickness_mm.is_none() && !(total > 0.0 && total.is_finite()) {
398 return Err("a waveplate without a thickness needs a positive retardance order + retardance".into());
399 }
400 vec![plate(m, d, 0.0)]
401 }
402 (None, false) => {
403 if self.thickness_mm.is_some() {
404 return Err("a waveplate with plates takes a thickness for each plate".into());
405 }
406 let mut v = Vec::new();
407 for p in &self.plates {
408 if !(p.thickness_mm > 0.0 && p.thickness_mm.is_finite()) {
409 return Err(format!(
410 "waveplate plate {} thickness {} mm",
411 p.material, p.thickness_mm
412 )
413 .into());
414 }
415 if !p.axis_deg.is_finite() {
416 return Err("the waveplate plate axis is not a number".into());
417 }
418 v.push(plate(&p.material, p.thickness_mm, p.axis_deg));
419 }
420 v
421 }
422 (None, true) => {
423 if self.thickness_mm.is_some() {
424 return Err("write the waveplate thickness together with material".into());
425 }
426 Vec::new()
427 }
428 };
429 if plates.iter().any(|p| p.material.is_empty()) {
430 return Err("empty birefringent material name of the waveplate".into());
431 }
432 let t = self.transmittance.sqrt();
433 Ok(lensbench_core::surface::Retarder {
434 axis_deg: self.axis_deg,
435 tx: t,
436 ty: t,
437 retardance: self.retardance,
438 order: self.order,
439 wl0: self.wavelength_um,
440 plates,
441 })
442 }
443}
444
445#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
447#[serde(tag = "type", rename_all = "snake_case")]
448pub enum SurfAperture {
449 Circular {
451 #[serde(default)]
452 min: f64,
453 max: f64,
454 #[serde(default)]
455 dx: f64,
456 #[serde(default)]
457 dy: f64,
458 },
459 Rect {
461 hx: f64,
462 hy: f64,
463 #[serde(default)]
464 dx: f64,
465 #[serde(default)]
466 dy: f64,
467 },
468 Ellipse {
470 hx: f64,
471 hy: f64,
472 #[serde(default)]
473 dx: f64,
474 #[serde(default)]
475 dy: f64,
476 },
477 Obscuration {
479 #[serde(default)]
480 min: f64,
481 max: f64,
482 #[serde(default)]
483 dx: f64,
484 #[serde(default)]
485 dy: f64,
486 },
487 Spider {
489 width: f64,
490 arms: u32,
491 #[serde(default)]
492 dx: f64,
493 #[serde(default)]
494 dy: f64,
495 },
496 Floating,
498}
499
500#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
502#[serde(untagged)]
503pub enum LensSource {
504 Zmx {
506 zmx: String,
507 #[serde(default = "one")]
508 lens: usize,
509 #[serde(default = "one")]
511 config: usize,
512 },
513 Catalog { vendor: String, part: String },
515 Surfaces { surfaces: Vec<SurfSpec> },
517}
518
519#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
520#[serde(remote = "Self", tag = "type", rename_all = "snake_case")]
521pub enum Block {
522 Lens {
523 #[serde(default)]
524 id: String,
525 source: LensSource,
526 #[serde(default)]
527 reversed: bool,
528 #[serde(default)]
530 stop: bool,
531 #[serde(flatten)]
532 place: Place,
533 #[serde(flatten)]
534 faces: FaceMods,
535 },
536 Air {
537 #[serde(default)]
538 id: String,
539 t: f64,
540 #[serde(default, skip_serializing_if = "Option::is_none")]
542 medium: Option<String>,
543 },
544 Stop {
546 #[serde(default)]
547 id: String,
548 #[serde(default)]
549 semi: f64,
550 #[serde(flatten)]
551 faces: FaceMods,
552 },
553 Mirror {
554 #[serde(default)]
555 id: String,
556 #[serde(default)]
558 radius: Option<f64>,
559 #[serde(default)]
560 conic: f64,
561 #[serde(default)]
564 tilt: [f64; 2],
565 #[serde(default)]
566 semi: f64,
567 #[serde(default, skip_serializing_if = "Option::is_none")]
569 aperture: Option<SurfAperture>,
570 #[serde(default)]
571 coat: String,
572 #[serde(default = "yes")]
573 on: bool,
574 #[serde(default)]
576 back: bool,
577 #[serde(default, skip_serializing_if = "Option::is_none")]
581 row: Option<Box<crate::sysfile_v2::Row>>,
582 #[serde(flatten)]
583 faces: FaceMods,
584 },
585 Surfaces {
587 #[serde(default)]
588 id: String,
589 surfaces: Vec<SurfSpec>,
590 #[serde(flatten)]
591 place: Place,
592 #[serde(flatten)]
593 faces: FaceMods,
594 },
595 Zmx {
598 #[serde(default)]
599 id: String,
600 path: String,
601 #[serde(default)]
602 from: Option<usize>,
603 #[serde(default)]
604 to: Option<usize>,
605 #[serde(default = "one")]
607 config: usize,
608 #[serde(default = "yes")]
610 stop: bool,
611 #[serde(default, skip_serializing_if = "Option::is_none")]
613 state: Option<String>,
614 #[serde(default, skip_serializing_if = "Option::is_none")]
616 beam_path: Option<String>,
617 #[serde(default)]
619 groups: Vec<ZmxGroup>,
620 #[serde(flatten)]
621 place: Place,
622 #[serde(flatten)]
623 faces: FaceMods,
624 },
625 User {
627 #[serde(default)]
628 id: String,
629 catalog: String,
631 item: String,
632 #[serde(flatten)]
633 place: Place,
634 #[serde(flatten)]
635 faces: FaceMods,
636 },
637 Splitter {
639 #[serde(default)]
640 id: String,
641 #[serde(flatten)]
642 spec: SplitterSpec,
643 #[serde(flatten)]
644 place: Place,
645 },
646 Group {
647 #[serde(default)]
648 id: String,
649 #[serde(default)]
650 name: String,
651 #[serde(default)]
652 role: Option<Role>,
653 #[serde(default)]
655 shift: f64,
656 blocks: Vec<Block>,
657 #[serde(flatten)]
658 place: Place,
659 #[serde(flatten)]
660 faces: FaceMods,
661 },
662 #[serde(skip)]
665 Detector(DetectorBlock),
666}
667
668pub const BUILTIN_BLOCKS: [&str; 9] = [
670 "lens", "air", "stop", "mirror", "surfaces", "zmx", "user", "splitter", "group",
671];
672
673#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
675pub struct DetectorBlock {
676 #[serde(rename = "type")]
678 pub kind: String,
679 #[serde(default)]
680 pub id: String,
681 #[serde(flatten)]
683 pub params: Map<String, Value>,
684}
685
686impl DetectorBlock {
687 pub fn check(&self) -> lensbench_core::Result<()> {
689 let k = detectors::get(&self.kind).ok_or_else(|| {
690 format!(
691 "unknown block type {:?} ({} or a registered detector: {})",
692 self.kind,
693 BUILTIN_BLOCKS.join(", "),
694 detectors::list()
695 .iter()
696 .map(|k| k.name)
697 .collect::<Vec<_>>()
698 .join(", ")
699 )
700 })?;
701 Ok((k.check)(&self.params).map_err(|e| format!("{} {}: {e}", self.kind, self.id))?)
702 }
703}
704
705impl<'de> Deserialize<'de> for Block {
706 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
707 use serde::de::Error;
708 let v = Value::deserialize(d)?;
709 match v.get("type").and_then(Value::as_str) {
710 Some(t) if !BUILTIN_BLOCKS.contains(&t) => serde_json::from_value(v)
711 .map(Block::Detector)
712 .map_err(D::Error::custom),
713 _ => Block::deserialize(v).map_err(D::Error::custom),
714 }
715 }
716}
717
718impl Serialize for Block {
719 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
720 match self {
721 Block::Detector(d) => d.serialize(s),
722 b => Block::serialize(b, s),
723 }
724 }
725}
726
727pub(crate) fn check_detectors(blocks: &[Block]) -> lensbench_core::Result<()> {
729 for b in blocks {
730 match b {
731 Block::Detector(d) => d.check()?,
732 Block::Group { blocks, .. } => check_detectors(blocks)?,
733 _ => {}
734 }
735 }
736 Ok(())
737}
738
739impl Project {
740 pub fn detector(&self) -> Option<&DetectorBlock> {
742 match self.blocks.last() {
743 Some(Block::Detector(d)) => Some(d),
744 _ => None,
745 }
746 }
747}
748
749#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
751#[serde(rename_all = "snake_case")]
752pub enum Role {
753 Zoom,
754 Focus,
755 Fixed,
756}
757
758#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
760pub struct ZmxGroup {
761 #[serde(default)]
762 pub id: String,
763 #[serde(default)]
764 pub name: String,
765 #[serde(default)]
766 pub role: Option<Role>,
767 pub from: usize,
768 pub to: usize,
769 #[serde(default)]
771 pub shift: f64,
772 #[serde(flatten)]
773 pub place: Place,
774 #[serde(flatten)]
775 pub faces: FaceMods,
776}
777
778#[derive(Debug, Clone, Serialize, Deserialize, Default, JsonSchema)]
780pub struct State {
781 pub name: String,
782 #[serde(default)]
784 pub set: BTreeMap<String, Map<String, Value>>,
785 #[serde(default)]
787 pub project: Map<String, Value>,
788}
789
790pub const PROJECT_FORMAT: &str = "lensbench-project";
792pub const PROJECT_FORMAT_VERSION: u32 = 1;
794
795#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
796pub struct Project {
797 #[serde(default, skip_serializing_if = "Option::is_none")]
799 pub format: Option<String>,
800 #[serde(default, skip_serializing_if = "Option::is_none")]
802 pub format_version: Option<u32>,
803 #[serde(default)]
804 pub name: String,
805 #[serde(default = "default_catalogs")]
806 pub glass_catalogs: Vec<String>,
807 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
809 pub coatings: BTreeMap<String, filter::CoatSpec>,
810 #[serde(default, skip_serializing_if = "Option::is_none")]
813 pub coating_file: Option<String>,
814 #[serde(default, skip_serializing_if = "Vec::is_empty")]
817 pub macros: Vec<lensbench_core::zpl_solve::Macro>,
818 pub wavelengths: Vec<Wave>,
819 #[serde(default = "one")]
821 pub primary: usize,
822 pub aperture: ApertureSpec,
823 #[serde(default)]
824 pub fields: FieldsSpec,
825 #[serde(default)]
827 pub object_distance: Option<f64>,
828 #[serde(default)]
829 pub aiming: Aiming,
830 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
832 pub telecentric: bool,
833 #[serde(default, skip_serializing_if = "Option::is_none")]
835 pub afocal: Option<String>,
836 #[serde(default = "yes", skip_serializing_if = "is_yes")]
838 pub floating_clip: bool,
839 #[serde(default = "yes", skip_serializing_if = "is_yes")]
842 pub mech_clip: bool,
843 #[serde(default, skip_serializing_if = "is_uniform")]
845 pub apodization: lensbench_core::pupil::Apodization,
846 #[serde(default = "two_i64", skip_serializing_if = "is_two_i64")]
848 pub ropd: i64,
849 #[serde(
851 default,
852 skip_serializing_if = "lensbench_core::system::AimPupil::is_default"
853 )]
854 pub aim_pupil: lensbench_core::system::AimPupil,
855 #[serde(default, skip_serializing_if = "InputPolarization::is_default")]
857 pub input_pol: InputPolarization,
858 #[serde(default, skip_serializing_if = "GlassTemplate::is_default")]
860 pub glass_template: GlassTemplate,
861 #[serde(default, skip_serializing_if = "Option::is_none")]
863 pub vig_interp: Option<lensbench_core::system::VigInterp>,
864 pub blocks: Vec<Block>,
865 #[serde(default)]
866 pub states: Vec<State>,
867 #[serde(default, skip_serializing_if = "Option::is_none")]
869 pub path: Option<String>,
870 #[serde(default, skip_serializing_if = "Vec::is_empty")]
872 pub beams: Vec<Beam>,
873 #[serde(skip)]
875 #[schemars(skip)]
876 pub turn: Option<crate::edit_spec::BlockFace>,
877 #[serde(default, skip_serializing_if = "Vec::is_empty")]
879 pub mechanics: Vec<MechPlacement>,
880 #[serde(default, skip_serializing_if = "Option::is_none")]
883 pub glrs: Option<BlockRef>,
884 #[serde(default, skip_serializing_if = "Environment::is_default")]
886 pub environment: Environment,
887 #[serde(default, skip_serializing_if = "Option::is_none")]
890 pub image: Option<Box<crate::sysfile_v2::Row>>,
891 #[serde(default, skip_serializing_if = "Option::is_none")]
894 pub object: Option<Box<crate::sysfile_v2::Row>>,
895 #[serde(default, skip_serializing_if = "Option::is_none")]
897 pub gui: Option<Value>,
898}
899
900#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
902pub struct Environment {
903 #[serde(default = "env_t")]
905 pub temperature_c: f64,
906 #[serde(default = "env_p")]
908 pub pressure_atm: f64,
909 #[serde(default)]
911 pub adjust_index: bool,
912}
913
914pub(crate) fn env_t() -> f64 {
915 20.0
916}
917pub(crate) fn env_p() -> f64 {
918 1.0
919}
920
921impl Default for Environment {
922 fn default() -> Self {
923 Environment {
924 temperature_c: env_t(),
925 pressure_atm: env_p(),
926 adjust_index: false,
927 }
928 }
929}
930
931impl Environment {
932 pub(crate) fn is_default(&self) -> bool {
933 *self == Environment::default()
934 }
935}
936
937#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
940pub struct FaceMods {
941 #[serde(default, skip_serializing_if = "Vec::is_empty")]
943 pub surface_edits: Vec<SurfaceEdit>,
944 #[serde(default, skip_serializing_if = "Vec::is_empty")]
949 pub surface_ops: Vec<SurfaceOp>,
950 #[serde(skip)]
953 #[schemars(skip)]
954 pub(crate) site: usize,
955}
956
957impl PartialEq for FaceMods {
958 fn eq(&self, o: &Self) -> bool {
959 self.surface_edits == o.surface_edits && self.surface_ops == o.surface_ops
960 }
961}
962
963impl FaceMods {
964 pub fn is_empty(&self) -> bool {
965 self.surface_edits.is_empty() && self.surface_ops.is_empty()
966 }
967}
968
969impl Block {
970 pub fn faces(&self) -> Option<&FaceMods> {
972 match self {
973 Block::Lens { faces, .. }
974 | Block::Stop { faces, .. }
975 | Block::Mirror { faces, .. }
976 | Block::Surfaces { faces, .. }
977 | Block::Zmx { faces, .. }
978 | Block::User { faces, .. }
979 | Block::Group { faces, .. } => Some(faces),
980 _ => None,
981 }
982 }
983 pub fn faces_mut(&mut self) -> Option<&mut FaceMods> {
984 match self {
985 Block::Lens { faces, .. }
986 | Block::Stop { faces, .. }
987 | Block::Mirror { faces, .. }
988 | Block::Surfaces { faces, .. }
989 | Block::Zmx { faces, .. }
990 | Block::User { faces, .. }
991 | Block::Group { faces, .. } => Some(faces),
992 _ => None,
993 }
994 }
995}
996
997#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
1001#[serde(deny_unknown_fields)]
1002pub struct SurfaceEdit {
1003 pub surface: usize,
1004 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1007 pub coordbrk: bool,
1008 pub fields: Map<String, Value>,
1009}
1010
1011impl Project {
1012 pub fn load(path: &std::path::Path) -> lensbench_core::Result<Project> {
1014 let txt = lensbench_core::vfs::read_to_string(path)
1015 .map_err(lensbench_core::Error::io_at(path.display()))?;
1016 Project::from_json(&txt).map_err(|e| format!("{}: {e}", path.display()).into())
1017 }
1018
1019 pub fn from_json(txt: &str) -> lensbench_core::Result<Project> {
1020 let v: Value = serde_json::from_str(txt).map_err(|e| format!("project file: {e}"))?;
1021 let p: Project =
1022 serde_json::from_value(v.clone()).map_err(|e| format!("project file: {e}"))?;
1023 let unknown: Vec<String> = unknown_keys::<Project>(&v, &p)
1025 .into_iter()
1026 .filter(|k| k != "$schema")
1027 .collect();
1028 if !unknown.is_empty() {
1029 return Err(format!(
1030 "project file: unknown key {} (check the spelling)",
1031 unknown.join(", ")
1032 )
1033 .into());
1034 }
1035 if let Some(f) = p.format.as_deref().filter(|f| *f != PROJECT_FORMAT) {
1036 return Err(
1037 format!("project file: format {f} (a project file is {PROJECT_FORMAT})").into(),
1038 );
1039 }
1040 if let Some(n) = p.format_version.filter(|&n| n > PROJECT_FORMAT_VERSION) {
1041 return Err(format!(
1042 "project file: format version {n} is newer than this lensbench reads ({PROJECT_FORMAT_VERSION}); update lensbench"
1043 )
1044 .into());
1045 }
1046 check_detectors(&p.blocks)?;
1047 p.check_beams()?;
1048 Ok(p)
1049 }
1050
1051 pub fn to_json(&self) -> String {
1053 let mut p = self.clone();
1054 p.format = Some(PROJECT_FORMAT.into());
1055 p.format_version = Some(PROJECT_FORMAT_VERSION);
1056 let txt = serde_json::to_string_pretty(&p).expect("JSON of plain data");
1057 crate::schema::stamp_text(&txt, "project")
1058 }
1059
1060 pub fn state_names(&self) -> Vec<&str> {
1061 self.states.iter().map(|s| s.name.as_str()).collect()
1062 }
1063
1064 pub fn with_state(&self, name: &str) -> lensbench_core::Result<Project> {
1067 if let Some(b) = self.beam(name) {
1068 let mut p = match &b.state {
1069 Some(st) => self
1070 .state_only(st)
1071 .map_err(|e| format!("beam {name}: {e}"))?,
1072 None => self.clone(),
1073 };
1074 if b.path.is_some() {
1075 p.path = b.path.clone();
1076 }
1077 p.turn = b.turn.clone();
1078 return Ok(p);
1079 }
1080 self.state_only(name)
1081 }
1082
1083 fn state_only(&self, name: &str) -> lensbench_core::Result<Project> {
1085 let st: Vec<&State> = self.states.iter().filter(|s| s.name == name).collect();
1086 let st = match st.as_slice() {
1087 [s] => *s,
1088 [] if self.states.is_empty() && !self.beams.is_empty() => {
1089 return Err(Error::Invalid(format!(
1090 "no state or beam {name} (beams: {})",
1091 self.beam_names().join(", ")
1092 ))
1093 .with_code(code::STATE_NOT_FOUND))
1094 }
1095 [] if !self.beams.is_empty() => {
1096 return Err(Error::Invalid(format!(
1097 "no state or beam {name} (states: {}; beams: {})",
1098 self.state_names().join(", "),
1099 self.beam_names().join(", ")
1100 ))
1101 .with_code(code::STATE_NOT_FOUND))
1102 }
1103 [] if self.states.is_empty() => {
1104 return Err(
1105 Error::Invalid(format!("no state {name} (the project has no states)"))
1106 .with_code(code::STATE_NOT_FOUND),
1107 )
1108 }
1109 [] => {
1110 return Err(Error::Invalid(format!(
1111 "no state {name} ({})",
1112 self.state_names().join(", ")
1113 ))
1114 .with_code(code::STATE_NOT_FOUND))
1115 }
1116 _ => return Err(format!("two or more states named {name}").into()),
1117 };
1118 let mut p = self.clone();
1122 if !st.project.is_empty() {
1123 let blocks = std::mem::take(&mut p.blocks);
1124 let states = std::mem::take(&mut p.states);
1125 let beams = std::mem::take(&mut p.beams);
1126 patch(
1127 &mut p,
1128 &st.project,
1129 &["blocks", "states", "beams"],
1130 name,
1131 |k| format!("state {name}: system value {k} can't be changed"),
1132 )?;
1133 p.blocks = blocks;
1134 p.states = states;
1135 p.beams = beams;
1136 }
1137 for (id, fields) in &st.set {
1138 let n = count_id(&p.blocks, id);
1139 if n == 0 {
1140 return Err(Error::Invalid(format!("state {name}: no block {id}"))
1141 .with_code(code::BLOCK_NOT_FOUND));
1142 }
1143 if n > 1 {
1144 return Err(format!("state {name}: two or more blocks with id {id}").into());
1145 }
1146 let fixed = ["type", "id", "blocks", "groups"];
1147 let msg = |k: &str| format!("state {name}: {k} of block {id} can't be changed");
1148 let r = match find_node_mut(&mut p.blocks, id).expect("counted above") {
1149 NodeMut::Block(b) => patch(b, fields, &fixed, name, msg),
1150 NodeMut::ZmxGroup(g) => patch(g, fields, &fixed, name, msg),
1151 };
1152 r?;
1153 }
1154 Ok(p)
1155 }
1156}
1157
1158fn patch<T: Serialize + serde::de::DeserializeOwned>(
1161 x: &mut T,
1162 fields: &Map<String, Value>,
1163 fixed: &[&str],
1164 name: &str,
1165 msg: impl Fn(&str) -> String,
1166) -> lensbench_core::Result<()> {
1167 let mut v = serde_json::to_value(&*x).map_err(|e| Error::Invalid(e.to_string()))?;
1168 let obj = v.as_object_mut().expect("block and project are objects");
1169 for (k, val) in fields {
1170 if fixed.contains(&k.as_str()) {
1171 return Err(msg(k).into());
1172 }
1173 obj.insert(k.clone(), val.clone());
1174 }
1175 let y: T = serde_json::from_value(v.clone()).map_err(|e| format!("state {name}: {e}"))?;
1176 let unknown = unknown_keys(&v, &y);
1178 if let Some(k) = fields.keys().find(|k| {
1179 unknown
1180 .iter()
1181 .any(|u| u == *k || u.starts_with(&format!("{k}/")))
1182 }) {
1183 if unknown.iter().any(|u| u == k) {
1184 return Err(msg(k).into());
1185 }
1186 let u: Vec<&str> = unknown.iter().map(String::as_str).collect();
1187 return Err(format!("state {name}: unknown key {}", u.join(", ")).into());
1188 }
1189 *x = y;
1190 Ok(())
1191}
1192
1193enum NodeMut<'x> {
1195 Block(&'x mut Block),
1196 ZmxGroup(&'x mut ZmxGroup),
1197}
1198
1199pub(crate) fn zmx_dirs(blocks: &[Block], base: &Path, out: &mut Vec<PathBuf>) {
1201 for b in blocks {
1202 if let Block::Zmx { path, .. } = b {
1203 if let Some(d) = base.join(path).parent() {
1204 if !out.iter().any(|x| x == d) {
1205 out.push(d.to_path_buf());
1206 }
1207 }
1208 }
1209 for k in kids(b) {
1210 zmx_dirs(k, base, out);
1211 }
1212 }
1213}
1214
1215fn kids(b: &Block) -> Vec<&Vec<Block>> {
1217 match b {
1218 Block::Group { blocks, .. } => vec![blocks],
1219 Block::Splitter { spec, .. } => vec![&spec.t, &spec.r, &spec.d],
1220 _ => Vec::new(),
1221 }
1222}
1223
1224fn count_id(blocks: &[Block], id: &str) -> usize {
1226 if id.is_empty() {
1227 return 0;
1228 }
1229 let mut n = 0;
1230 for b in blocks {
1231 n += usize::from(crate::blocks::block_id(b) == id);
1232 if let Block::Zmx { groups, .. } = b {
1233 n += groups.iter().filter(|g| g.id == id).count();
1234 }
1235 n += kids(b).into_iter().map(|k| count_id(k, id)).sum::<usize>();
1236 }
1237 n
1238}
1239
1240fn find_node_mut<'x>(blocks: &'x mut [Block], id: &str) -> Option<NodeMut<'x>> {
1242 if id.is_empty() {
1243 return None;
1244 }
1245 for b in blocks {
1246 if crate::blocks::block_id(b) == id {
1247 return Some(NodeMut::Block(b));
1248 }
1249 match b {
1250 Block::Zmx { groups, .. } => {
1251 if let Some(g) = groups.iter_mut().find(|g| g.id == id) {
1252 return Some(NodeMut::ZmxGroup(g));
1253 }
1254 }
1255 Block::Group { blocks, .. } => {
1256 if let Some(x) = find_node_mut(blocks, id) {
1257 return Some(x);
1258 }
1259 }
1260 Block::Splitter { spec, .. } => {
1261 for k in [&mut spec.t, &mut spec.r, &mut spec.d] {
1262 if let Some(x) = find_node_mut(k, id) {
1263 return Some(x);
1264 }
1265 }
1266 }
1267 _ => {}
1268 }
1269 }
1270 None
1271}
1272
1273pub fn block_pointers(blocks: &Value, id: &str) -> Vec<String> {
1276 let mut out = Vec::new();
1277 if !id.is_empty() {
1278 find_id(blocks, "/blocks", id, &mut out);
1279 }
1280 out
1281}
1282
1283pub fn find_block_mut<'x>(blocks: &'x mut [Block], id: &str) -> Option<&'x mut Block> {
1285 if id.is_empty() {
1286 return None;
1287 }
1288 for b in blocks {
1289 if crate::blocks::block_id(b) == id {
1290 return Some(b);
1291 }
1292 let kids: Vec<&mut Vec<Block>> = match b {
1293 Block::Group { blocks, .. } => vec![blocks],
1294 Block::Splitter { spec, .. } => vec![&mut spec.t, &mut spec.r, &mut spec.d],
1295 _ => Vec::new(),
1296 };
1297 for k in kids {
1298 if let Some(x) = find_block_mut(k, id) {
1299 return Some(x);
1300 }
1301 }
1302 }
1303 None
1304}
1305
1306pub(crate) fn find_id(v: &Value, path: &str, id: &str, out: &mut Vec<String>) {
1308 let Some(a) = v.as_array() else { return };
1309 for (i, x) in a.iter().enumerate() {
1310 let p = format!("{path}/{i}");
1311 if x.get("id").and_then(Value::as_str) == Some(id) {
1312 out.push(p.clone());
1313 }
1314 for key in ["blocks", "groups", "t", "r", "d"] {
1315 if let Some(y) = x.get(key) {
1316 find_id(y, &format!("{p}/{key}"), id, out);
1317 }
1318 }
1319 }
1320}
1321
1322pub fn unknown_keys<T: serde::de::DeserializeOwned + Serialize>(
1327 input: &Value,
1328 parsed: &T,
1329) -> Vec<String> {
1330 fn walk(i: &Value, o: &Value, path: &mut Vec<String>, miss: &mut Vec<Vec<String>>) {
1331 match (i, o) {
1332 (Value::Object(a), Value::Object(b)) => {
1333 for (k, x) in a {
1334 path.push(k.clone());
1335 match b.get(k) {
1336 Some(y) => walk(x, y, path, miss),
1337 None => miss.push(path.clone()),
1338 }
1339 path.pop();
1340 }
1341 }
1342 (Value::Array(a), Value::Array(b)) => {
1343 for (n, (x, y)) in a.iter().zip(b).enumerate() {
1344 path.push(n.to_string());
1345 walk(x, y, path, miss);
1346 path.pop();
1347 }
1348 }
1349 _ => {}
1350 }
1351 }
1352 let Ok(out) = serde_json::to_value(parsed) else {
1353 return Vec::new();
1354 };
1355 let mut miss = Vec::new();
1356 walk(input, &out, &mut Vec::new(), &mut miss);
1357 let ignored = |p: &[String], junk: Value| {
1360 let mut probe = input.clone();
1361 let mut at = &mut probe;
1362 for k in p {
1363 at = match at {
1364 Value::Object(m) => m.get_mut(k).expect("walk で見たキー"),
1365 Value::Array(a) => &mut a[k.parse::<usize>().expect("添字")],
1366 _ => unreachable!(),
1367 };
1368 }
1369 *at = junk;
1370 serde_json::from_value::<T>(probe)
1371 .ok()
1372 .and_then(|t| serde_json::to_value(t).ok())
1373 .is_some_and(|v| v == out)
1374 };
1375 fn at<'a>(v: &'a Value, p: &[String]) -> Option<&'a Value> {
1376 p.iter().try_fold(v, |v, k| match v {
1377 Value::Object(m) => m.get(k),
1378 Value::Array(a) => a.get(k.parse::<usize>().ok()?),
1379 _ => None,
1380 })
1381 }
1382 fn check(
1384 p: Vec<String>,
1385 input: &Value,
1386 ignored: &dyn Fn(&[String], Value) -> bool,
1387 found: &mut Vec<Vec<String>>,
1388 ) {
1389 if ignored(&p, serde_json::json!({ "\u{1}lensbench_probe": [true] }))
1390 && ignored(&p, Value::from("\u{1}lensbench_probe"))
1391 {
1392 found.push(p);
1393 } else if let Some(Value::Object(m)) = at(input, &p) {
1394 for k in m.keys() {
1395 let mut c = p.clone();
1396 c.push(k.clone());
1397 check(c, input, ignored, found);
1398 }
1399 }
1400 }
1401 let mut found = Vec::new();
1402 for p in miss {
1403 check(p, input, &ignored, &mut found);
1404 }
1405 found.into_iter().map(|p| p.join("/")).collect()
1406}
1407
1408fn is_uniform(a: &lensbench_core::pupil::Apodization) -> bool {
1409 *a == lensbench_core::pupil::Apodization::Uniform
1410}
1411
1412fn two_i64() -> i64 {
1413 2
1414}
1415
1416fn is_two_i64(v: &i64) -> bool {
1417 *v == 2
1418}