1use crate::error::Result;
5use crate::param::Kind;
6use crate::solves::{Solve, SolveKind};
7use crate::system::{Prescription, System};
8use crate::zpl_solve::{Macro, MacroParm};
9
10#[derive(Debug, Clone, Copy, PartialEq)]
12pub enum MacroTarget {
13 Curv,
15 Thick,
17 Col(Kind),
19}
20
21#[derive(Debug)]
24pub struct MacroRequest {
25 pub surf: usize,
26 pub target: MacroTarget,
27 pub name: String,
28 pub found: Result<Macro>,
29}
30
31impl System {
32 pub fn from_import(rx: Prescription, macros: Vec<MacroRequest>) -> Result<System> {
37 let mut s = System::from_rx(rx)?;
38 s.check()?;
39 if !s.pickups.is_empty() {
40 s.resolve_pickups()?;
42 s.changed()?;
43 }
44 for q in macros {
45 attach_macro(&mut s, q);
46 }
47 s.drop_unsolvable_on_load();
49 crate::zpl_solve::resolve_on_load(&mut s);
51 s.solve_thickness()?;
52 s.update_semi();
54 s.rx_mut().units = s.lens_units();
56 Ok(s)
57 }
58}
59
60fn attach_macro(s: &mut System, q: MacroRequest) {
62 let MacroRequest {
63 surf: k,
64 target: t,
65 name,
66 found,
67 } = q;
68 let what = match t {
69 MacroTarget::Curv => "curvature".to_string(),
70 MacroTarget::Thick => "thickness".to_string(),
71 MacroTarget::Col(c) => MacroParm {
72 surf: k,
73 id: 0,
74 what: c,
75 }
76 .label(),
77 };
78 let got = found.and_then(|m| {
79 if let MacroTarget::Col(c) = t {
80 if crate::pickup::pick_get(&s.surfaces[k], c).is_none() {
81 crate::notimpl!("surface type {:?} {what}", s.surfaces[k].typ());
82 }
83 }
84 let o = s.run_macro_outcome(&m, k)?;
85 Ok((m, o))
86 });
87 match got {
88 Ok((m, o)) => {
89 if let Some(e) = &o.error {
91 s.rx_mut().macro_notes.push(match o.value {
92 Some(v) => format!(
93 "the {what} macro solve {name} of surface {k} stopped with an error and used {v} as OpticStudio does: {e}"
94 ),
95 None => format!(
96 "the {what} macro solve {name} of surface {k} stopped with an error and left the value as OpticStudio does: {e}"
97 ),
98 });
99 }
100 let id = match s
101 .macros
102 .iter()
103 .position(|x| x.name == m.name && x.source == m.source)
104 {
105 Some(i) => i,
106 None => {
107 s.rx_mut().macros.push(m);
108 s.macros.len() - 1
109 }
110 } as u16;
111 match t {
112 MacroTarget::Curv | MacroTarget::Thick => s.rx_mut().solves.push(Solve {
113 surf: k,
114 kind: if t == MacroTarget::Curv {
115 SolveKind::MacroCurv { index: id }
116 } else {
117 SolveKind::MacroThick { index: id }
118 },
119 }),
120 MacroTarget::Col(what) => {
121 s.rx_mut().macro_parms.push(MacroParm { surf: k, id, what })
122 }
123 }
124 }
125 Err(e) => s.rx_mut().macro_notes.push(format!(
126 "removed the {what} macro solve {name} of surface {k} and fixed the saved value: {e}"
127 )),
128 }
129}