1use std::path::{Path, PathBuf};
29use std::sync::Arc;
30
31use crate::error::{Error, Result};
32use crate::param::Kind;
33use crate::trace::RayStatus;
34use crate::zpl::{Flow, Host, Program, Value};
35use crate::{RwLockExt, System};
36
37#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
39pub struct Macro {
40 pub name: String,
42 pub source: String,
44 #[serde(skip)]
46 pub path: PathBuf,
47 #[serde(skip)]
49 pub(crate) prog: std::sync::OnceLock<Arc<Program>>,
50}
51
52impl Macro {
53 pub fn from_source(name: &str, src: &str) -> Result<Macro> {
55 let prog = Program::parse(src).map_err(|e| e.at(format!("macro {name}")))?;
56 Ok(Macro {
57 name: name.to_string(),
58 source: src.to_string(),
59 path: PathBuf::new(),
60 prog: Arc::new(prog).into(),
61 })
62 }
63
64 pub fn program(&self) -> Result<Arc<Program>> {
65 if let Some(p) = self.prog.get() {
66 return Ok(p.clone());
67 }
68 let p = Arc::new(
69 Program::parse(&self.source).map_err(|e| e.at(format!("macro {}", self.name)))?,
70 );
71 Ok(self.prog.get_or_init(|| p).clone())
72 }
73}
74
75pub fn macro_dirs(extra: &[PathBuf], zmx_dir: Option<&Path>) -> Vec<PathBuf> {
77 let mut v: Vec<PathBuf> = extra.to_vec();
78 if let Some(d) = zmx_dir {
79 let d = if d.as_os_str().is_empty() {
81 Path::new(".")
82 } else {
83 d
84 };
85 let d = std::path::absolute(d).unwrap_or_else(|_| d.to_path_buf());
86 if let Some(p) = d.parent() {
87 v.push(d.clone());
88 v.push(p.join("Macros"));
89 } else {
90 v.push(d);
91 }
92 }
93 v.extend(DEFAULT_DIRS.read_ok().iter().cloned());
94 v
95}
96
97static DEFAULT_DIRS: std::sync::RwLock<Vec<PathBuf>> = std::sync::RwLock::new(Vec::new());
99
100pub fn set_default_dirs(dirs: Vec<PathBuf>) {
103 *DEFAULT_DIRS.write_ok() = dirs;
104}
105
106pub fn find_macro(name: &str, dirs: &[PathBuf]) -> Result<Macro> {
108 let want = format!("{}.ZPL", name.trim()).to_uppercase();
109 for d in dirs {
110 let Ok(rd) = crate::vfs::read_dir(d) else {
111 continue;
112 };
113 for e in rd {
114 if e.file_name()
115 .map(|n| n.to_string_lossy().to_uppercase())
116 .unwrap_or_default()
117 == want
118 {
119 let path = e;
120 let source = crate::glass::read_text(&path)
121 .map_err(|e| Error::Io(format!("{}: {e}", path.display())))?;
122 let prog = Program::parse(&source).map_err(|e| e.at(path.display()))?;
123 return Ok(Macro {
124 name: name.to_string(),
125 source,
126 path,
127 prog: Arc::new(prog).into(),
128 });
129 }
130 }
131 }
132 Err(Error::Io(format!(
133 "macro {want} not found (looked in {} places)",
134 dirs.len()
135 )))
136}
137
138#[derive(Debug, Clone, Copy, Default)]
140pub struct RayVals {
141 pub xyz: [f64; 3],
143 pub lmn: [f64; 3],
144 pub nor: [f64; 3],
145 pub len: f64,
147 pub opl: f64,
148 pub opth: f64,
149 pub gp: [f64; 3],
151 pub gk: [f64; 3],
152}
153
154pub struct SysHost<'a> {
156 pub sys: &'a System,
157 pub surf: usize,
159 pub ray: Vec<RayVals>,
161 pub raye: f64,
163 pub rayv: f64,
164 pub opdc: f64,
165}
166
167impl<'a> SysHost<'a> {
168 pub fn new(sys: &'a System, surf: usize) -> Self {
169 SysHost {
170 sys,
171 surf,
172 ray: vec![RayVals::default(); sys.surfaces.len()],
173 raye: 0.0,
174 rayv: 0.0,
175 opdc: 0.0,
176 }
177 }
178
179 fn raytrace(&mut self, a: &[Value]) -> Result<Flow> {
183 if !(4..=5).contains(&a.len()) {
184 crate::notimpl!("RAYTRACE has {} arguments (only 4 or 5)", a.len());
185 }
186 let mut x = [0.0; 5];
187 for (i, v) in a.iter().enumerate() {
188 match v {
189 Value::Num(v) => x[i] = *v,
190 _ => crate::invalid!("RAYTRACE arguments must be numbers"),
191 }
192 }
193 if let Some(v) = x[..4].iter().find(|v| !(v.abs() <= 1.0)) {
194 return Ok(Flow::Abort(format!("RAYTRACE coordinate {v} is over 1")));
195 }
196 let s = self.sys;
197 let w = if a.len() == 5 {
198 let w = x[4].trunc();
199 if !(w >= 1.0 && w as usize <= s.wavelengths.len()) {
200 return Ok(Flow::Abort(format!("RAYTRACE wavelength number {}", x[4])));
201 }
202 w as usize - 1
203 } else {
204 s.primary
205 };
206 let field = crate::system::FieldSel::Norm(x[0], x[1]);
207 if (x[2], x[3]) != (0.0, 0.0) {
210 let c = s.try_trace(field, &[0.0], &[0.0], Some(w), None, true)?;
211 self.fill(&c, w);
212 }
213 let t = s.try_trace(field, &[x[2]], &[x[3]], Some(w), None, true)?;
214 self.fill(&t, w);
215 let r = &t.rays[0];
216 if r.status.surf().is_some() {
217 self.ray.iter_mut().for_each(|v| v.opth = 0.0);
219 }
220 self.raye = match r.status {
221 RayStatus::Tir { surf } => -(surf as f64),
222 st => st.code() as f64,
223 };
224 self.rayv = r.vig as f64;
225 self.opdc = if r.status.surf().is_some() {
226 0.0
227 } else {
228 crate::opd::opd(s, field, &[x[2]], &[x[3]], Some(w), true)?.opd[0]
229 };
230 Ok(Flow::Go)
231 }
232
233 fn fill(&mut self, t: &crate::system::Trace, w: usize) {
235 use crate::math::*;
236 let s = self.sys;
237 let fr = s.frames();
238 let (p0, k0) = (t.p0[0], t.k0[0]);
240 let (o, m) = match &fr.surf[0] {
241 Some(f) => (f.o, f.r),
242 None => (fr.obj.o, fr.obj.r),
243 };
244 let q = mtv(&m, sub(p0, o));
245 let kq = mtv(&m, k0);
246 let (q, start) = if fr.surf[0].is_some() {
247 (q, p0)
248 } else {
249 let u = -q[2] / kq[2];
250 (add(q, scale(kq, u)), add(p0, scale(k0, u)))
251 };
252 let opl0 = if fr.surf[0].is_none() {
254 s.index_before(1, w) * dot(q, kq)
255 } else {
256 0.0
257 };
258 let n0 = s.index_before(1, w);
259 let mut off = None;
261 let (mut prev, mut kprev, mut lprev) = (start, k0, 0.0);
262 let mut vals = vec![(
263 0usize,
264 RayVals {
265 xyz: q,
266 lmn: kq,
267 nor: [0.0, 0.0, -1.0],
269 len: 0.0,
270 opl: 0.0,
271 opth: 0.0,
272 gp: start,
273 gk: k0,
274 },
275 )];
276 for e in &t.rec {
277 let Some(f) = &fr.surf[e.surf] else { continue };
278 let en = e.entry(0);
279 if !en.xyz[0].is_finite() {
280 break;
281 }
282 let gk = mv(&f.r, en.lmn);
283 let off = *off.get_or_insert_with(|| n0 * dot(sub(en.p, start), k0) - en.opl);
284 let opl = en.opl + off;
286 vals.push((
287 e.surf,
288 RayVals {
289 xyz: en.xyz,
290 lmn: en.lmn,
291 nor: scale(
292 crate::shape::local_normal(&s.surfaces[e.surf], en.xyz),
293 -1.0,
294 ),
295 len: dot(sub(en.p, prev), kprev),
296 opl: opl - lprev,
297 opth: opl + opl0,
298 gp: en.p,
299 gk,
300 },
301 ));
302 (prev, kprev, lprev) = (en.p, gk, opl);
303 }
304 for (j, v) in vals {
305 self.ray[j] = v;
306 }
307 }
308}
309
310impl SysHost<'_> {
311 fn surf_arg(&self, a: &[Value], name: &str) -> Result<usize> {
312 let k = match a {
313 [Value::Num(x)] => *x,
314 _ => return Err(Error::Invalid(format!("{name} takes one surface number"))),
315 };
316 let k = k.trunc();
317 if k < 0.0 || k as usize >= self.sys.surfaces.len() {
318 return Err(Error::Invalid(format!("{name}({k}): no such surface")));
319 }
320 Ok(k as usize)
321 }
322}
323
324fn num(x: f64) -> Option<Result<Value>> {
325 Some(Ok(Value::Num(x)))
326}
327
328impl Host for SysHost<'_> {
329 fn function(&mut self, name: &str, a: &[Value]) -> Option<Result<Value>> {
330 let s = self.sys;
331 let surf = |h: &Self| h.surf_arg(a, name);
332 let r = match name {
333 "SOSO" => match a {
334 [Value::Num(x)] if *x == 0.0 => num(self.surf as f64),
335 _ => Some(Err(Error::NotImplemented(format!(
336 "SOSO argument {a:?} (only 0)"
337 )))),
338 },
339 "CURV" => Some(surf(self).map(|k| Value::Num(s.surfaces[k].c))),
340 "THIC" => Some(surf(self).map(|k| Value::Num(s.surfaces[k].t))),
341 "CONI" => Some(surf(self).map(|k| Value::Num(s.surfaces[k].k))),
342 "SDIA" => Some(surf(self).map(|k| Value::Num(s.surfaces[k].semi))),
343 "RADI" => Some(match a {
345 [Value::Num(x)] => {
346 let k = x.trunc();
347 let c = if k >= 0.0 {
348 s.surfaces.get(k as usize).map_or(0.0, |d| d.c)
349 } else {
350 0.0
351 };
352 Ok(Value::Num(if c == 0.0 { 0.0 } else { 1.0 / c }))
353 }
354 _ => Err(Error::Invalid(format!("{name} takes one surface number"))),
355 }),
356 "RAYX" | "RAYY" | "RAYZ" | "RAYL" | "RAYM" | "RAYN" | "RANX" | "RANY" | "RANZ"
357 | "RAYT" | "RAYO" | "OPTH" | "RAGX" | "RAGY" | "RAGZ" | "RAGL" | "RAGM" | "RAGN" => {
358 Some(surf(self).map(|k| {
359 let v = &self.ray[k];
360 let i = |c: u8| (c - b'X') as usize;
361 let last = name.as_bytes()[3];
362 Value::Num(match &name[..3] {
363 "RAY" if b"XYZ".contains(&last) => v.xyz[i(last)],
364 "RAY" if b"LMN".contains(&last) => v.lmn[(last - b'L') as usize],
365 "RAN" => v.nor[i(last)],
366 "RAG" if b"XYZ".contains(&last) => v.gp[i(last)],
367 "RAG" => v.gk[(last - b'L') as usize],
368 "RAY" if last == b'T' => v.len,
369 "RAY" => v.opl,
370 _ => v.opth,
371 })
372 }))
373 }
374 "RAYE" if a.is_empty() => num(self.raye),
375 "RAYV" if a.is_empty() => num(self.rayv),
376 "OPDC" if a.is_empty() => num(self.opdc),
377 "INDX" => Some(surf(self).map(|k| Value::Num(s.n(k)[s.primary]))),
378 "PARM" => Some(match a {
379 [Value::Num(n), Value::Num(k)] => {
380 let k = k.trunc();
381 if k < 0.0 || k as usize >= s.surfaces.len() || *n < 0.0 || *n > 255.0 {
382 Err(Error::Invalid(format!(
383 "PARM({n}, {k}): the parameter (0 to 255) or the surface is out of range"
384 )))
385 } else {
386 let d = &s.surfaces[k as usize];
387 let std0 = (d.typ() == crate::surface::SurfType::Standard).then_some(0.0);
389 crate::pickup::surf_parm(d, *n as u8)
390 .or(std0)
391 .map(Value::Num)
392 .ok_or_else(|| Error::NotImplemented(format!("surface {k} PARM {n}")))
393 }
394 }
395 _ => Err(Error::Invalid("PARM takes (number, surface)".into())),
396 }),
397 "NSUR" if a.is_empty() => num((s.surfaces.len() - 1) as f64),
398 "NWAV" if a.is_empty() => num(s.wavelengths.len() as f64),
399 "PWAV" if a.is_empty() => num((s.primary + 1) as f64),
400 "NFLD" if a.is_empty() => num(s.fields.len() as f64),
401 "WAVL" | "FLDX" | "FLDY" => Some(match a {
402 [Value::Num(i)] if *i >= 1.0 => {
403 let i = *i as usize - 1;
404 match name {
405 "WAVL" => s.wavelengths.get(i).copied(),
406 "FLDX" => s.fields.get(i).map(|f| f.x),
407 _ => s.fields.get(i).map(|f| f.y),
408 }
409 .map(Value::Num)
410 .ok_or_else(|| Error::Invalid(format!("no {name}({})", i + 1)))
411 }
412 _ => Err(Error::Invalid(format!("{name} takes one number"))),
413 }),
414 _ => None,
415 };
416 r
417 }
418
419 fn command(&mut self, name: &str, a: &[Value]) -> Option<Result<Flow>> {
420 match name {
421 "RAYTRACE" => Some(self.raytrace(a)),
422 _ => None,
423 }
424 }
425}
426
427#[derive(
429 Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
430)]
431pub struct MacroParm {
432 pub surf: usize,
433 pub id: u16,
435 pub what: Kind,
438}
439
440impl MacroParm {
441 pub fn label(&self) -> String {
443 match self.what {
444 Kind::Parm(i) => format!("parameter {i}"),
445 Kind::Conic => "conic".into(),
446 Kind::Semi => "semi-diameter".into(),
447 Kind::MechSemi => "mechanical semi-diameter".into(),
448 k => k.name(),
449 }
450 }
451}
452
453impl System {
454 pub(crate) fn run_macro(&self, m: &Macro, surf: usize) -> Result<Option<f64>> {
456 Ok(self.run_macro_outcome(m, surf)?.value)
457 }
458
459 pub(crate) fn run_macro_outcome(&self, m: &Macro, surf: usize) -> Result<crate::zpl::Outcome> {
461 m.program()?
462 .solve(&mut SysHost::new(self, surf))
463 .map_err(|e| e.at(format!("surface {surf} macro {}", m.name)))
464 }
465
466 pub(crate) fn solve_macro_parms(&mut self) -> Result<bool> {
468 let mut moved = false;
469 for i in 0..self.macro_parms.len() {
470 let q = self.macro_parms[i];
471 if self.surfaces[q.surf].ignore {
472 continue;
473 }
474 let Some(m) = self.macros.get(q.id as usize) else {
475 crate::invalid!("surface {}: no macro {}", q.surf, q.id);
476 };
477 let Some(mut v) = self.run_macro(m, q.surf)? else {
478 continue;
479 };
480 if matches!(q.what, Kind::Semi | Kind::MechSemi) {
484 v = v.abs();
485 }
486 let what = q.what;
487 let old = crate::pickup::pick_get(&self.surfaces[q.surf], what);
488 if old != Some(v) {
489 if !crate::pickup::pick_set(&mut self.rx_mut().surfaces[q.surf], what, v) {
490 crate::notimpl!(
491 "putting a macro value into surface {} {}",
492 q.surf,
493 q.label()
494 );
495 }
496 if !self.pickups.is_empty() {
497 self.resolve_pickups()?;
498 }
499 self.changed()?;
500 let tol = 1e-14 * (1.0 + v.abs());
501 moved |= old.is_none_or(|o| (o - v).abs() > tol);
502 }
503 }
504 Ok(moved)
505 }
506}
507
508impl System {
509 pub fn macro_warnings(&self) -> Vec<String> {
511 self.macro_notes.clone()
512 }
513}
514
515pub(crate) fn resolve_on_load(s: &mut System) {
518 use crate::solves::SolveKind;
519 let is_macro = |k: &SolveKind| {
520 matches!(
521 k,
522 SolveKind::MacroCurv { .. } | SolveKind::MacroThick { .. }
523 )
524 };
525 if s.solves.iter().any(|q| is_macro(&q.kind)) || !s.macro_parms.is_empty() {
526 let before = s.clone();
527 let mut first = s.solve_thickness();
528 if first.is_err() {
529 let ns = before.solves.len();
532 let np = before.macro_parms.len();
533 let with = |ks: &[bool], kp: &[bool]| {
534 let mut c = before.clone();
535 let r = c.rx_mut();
536 let mut i = 0;
537 r.solves.retain(|q| {
538 i += 1;
539 !is_macro(&q.kind) || ks[i - 1]
540 });
541 let mut i = 0;
542 r.macro_parms.retain(|_| {
543 i += 1;
544 kp[i - 1]
545 });
546 c
547 };
548 let (mut ks, mut kp) = (vec![false; ns], vec![false; np]);
549 if with(&ks, &kp).solve_thickness().is_ok() {
550 let mut notes = Vec::new();
551 for i in 0..ns + np {
552 let (solve, j) = if i < ns { (true, i) } else { (false, i - ns) };
553 if solve {
554 if !is_macro(&before.solves[j].kind) {
555 continue;
556 }
557 ks[j] = true;
558 } else {
559 kp[j] = true;
560 }
561 match with(&ks, &kp).solve_thickness() {
562 Ok(()) => {}
563 Err(e) if solve => {
564 ks[j] = false;
565 let q = &before.solves[j];
566 let (SolveKind::MacroCurv { index: m }
567 | SolveKind::MacroThick { index: m }) = q.kind
568 else {
569 unreachable!()
570 };
571 notes.push(format!(
572 "removed macro solve {} of surface {} and fixed the saved value: can't solve it again ({e})",
573 before.macros[m as usize].name, q.surf
574 ));
575 }
576 Err(e) => {
577 kp[j] = false;
578 let q = &before.macro_parms[j];
579 notes.push(format!(
580 "removed the {what} macro solve {} of surface {} and fixed the saved value: can't solve it again ({e})",
581 before.macros[q.id as usize].name,
582 q.surf,
583 what = q.label()
584 ));
585 }
586 }
587 }
588 *s = with(&ks, &kp);
590 s.rx_mut().macro_notes.extend(notes);
591 first = s.solve_thickness();
592 } else {
593 *s = before.clone();
594 }
595 }
596 if let Err(e) = first {
597 *s = before;
599 let r = s.rx_mut();
600 for q in r.solves.iter().filter(|q| is_macro(&q.kind)) {
601 let name = match q.kind {
602 SolveKind::MacroCurv { index: i } | SolveKind::MacroThick { index: i } => {
603 r.macros[i as usize].name.clone()
604 }
605 _ => unreachable!(),
606 };
607 r.macro_notes.push(format!(
608 "removed macro solve {name} of surface {} and fixed the saved value: can't solve it again ({e})",
609 q.surf
610 ));
611 }
612 r.solves.retain(|q| !is_macro(&q.kind));
613 for q in &r.macro_parms {
614 let name = r.macros[q.id as usize].name.clone();
615 r.macro_notes.push(format!(
616 "removed the {what} macro solve {name} of surface {} and fixed the saved value: can't solve it again ({e})",
617 q.surf,
618 what = q.label()
619 ));
620 }
621 r.macro_parms.clear();
622 }
623 }
624}