1use std::fmt::Write as _;
6use std::path::Path;
7
8use lensbench_core::coord_return::ReturnMode;
9use lensbench_core::error::{Error, Result};
10use lensbench_core::notimpl;
11use lensbench_core::param::Kind;
12use lensbench_core::solves::{Solve, SolveKind};
13use lensbench_core::surface::{After, Aperture, Bire, Material, SurfType, Tilt};
14use lensbench_core::system::{Aiming, ApertureKind, FieldNorm, FieldType, System};
15
16mod configs;
17use configs::{config_notes, config_op, config_pick_unwritable, config_row_numbers};
18
19fn f(v: f64) -> String {
21 if v.is_infinite() {
22 "INFINITY".into()
23 } else {
24 let s = format!("{v:?}");
25 s.strip_suffix(".0").map(|x| x.to_string()).unwrap_or(s)
26 }
27}
28
29fn col(q: &lensbench_core::pickup::Pickup) -> i64 {
31 q.from.and_then(|k| k.column()).unwrap_or(0)
32}
33
34fn tilt_line(out: &mut String, which: u8, mode: usize, t: &Tilt) {
35 let _ = writeln!(
36 out,
37 " SCBD {which} {} {mode} {} {} {} {} {}",
38 t.order,
39 f(t.d[0]),
40 f(t.d[1]),
41 f(t.d[2]),
42 f(t.d[3]),
43 f(t.d[4])
44 );
45}
46
47pub fn write(s: &System) -> Result<String> {
50 write_as(s, DEFAULT_COAT_FILE)
51}
52
53pub(crate) const DEFAULT_COAT_FILE: &str = "lensbench_coat.dat";
56
57fn write_header(s: &System, coat_file: &str) -> Result<String> {
61 let mut o = String::new();
62 let w = |o: &mut String, l: String| {
63 o.push_str(&l);
64 o.push('\n');
65 };
66 w(&mut o, "VERS 260327 42 20120530 20120530".into());
67 w(&mut o, "MODE SEQ".into());
68 w(&mut o, format!("NAME {}", s.name));
69 w(
70 &mut o,
71 format!("UNIT MM X W X CM {} CPMM LU", s.afocal_unit.code()),
72 );
73 match s.aperture.0 {
74 ApertureKind::Epd => w(&mut o, format!("ENPD {}", f(s.aperture.1))),
75 ApertureKind::FNum => w(&mut o, format!("FNUM {} 0", f(s.aperture.1))),
76 ApertureKind::Pwfn => w(&mut o, format!("FNUM {} 1", f(s.aperture.1))),
77 ApertureKind::Na => w(&mut o, format!("OBNA {} 0", f(s.aperture.1))),
78 ApertureKind::Cone => w(&mut o, format!("OBNA {} 1", f(s.aperture.1))),
79 ApertureKind::Float => w(&mut o, "FLOA".into()),
80 }
81 w(
82 &mut o,
83 format!(
84 "ENVD {} {} {}",
85 f(s.temperature),
86 f(s.pressure),
87 if s.adjust_index { 1 } else { 0 }
88 ),
89 );
90 let mut cats: Vec<String> = Vec::new();
92 for d in &s.surfaces {
93 if let Some(g) = d.mat.glass().and_then(|m| s.glasses.get(m)) {
94 if !g.catalog.is_empty() && !cats.contains(&g.catalog) {
95 cats.push(g.catalog.clone());
96 }
97 }
98 }
99 w(&mut o, format!("GCAT {}", cats.join(" ")));
100 let aim = match s.aiming {
101 Aiming::Off => 0,
102 Aiming::Paraxial => 1,
103 Aiming::Real => 2,
104 };
105 let ap = &s.aim_pupil;
107 w(
108 &mut o,
109 format!(
110 "RAIM 0 {aim} 1 1 0 0 0 0 0 {}",
111 ap.auto_shift.unwrap_or(true) as u8
112 ),
113 );
114 let ip = &s.input_pol;
116 if !ip.is_default() {
117 w(
118 &mut o,
119 format!(
120 "POLS {} {} {} {} {} 1 0",
121 ip.unpolarized as u8,
122 f(ip.jx),
123 f(ip.jy),
124 f(ip.phase_x),
125 f(ip.phase_y)
126 ),
127 );
128 }
129 let gt = &s.glass_template;
131 if !gt.is_default() {
132 let b = |x: bool| if x { "1" } else { "0" };
133 let mut l = format!("GSTD {}", b(gt.enabled));
134 for x in gt.max {
135 l += &format!(" {}", f(x));
136 }
137 l += &format!(" {}", b(gt.exclude_incomplete));
138 for x in gt.status {
139 l += &format!(" {}", b(x));
140 }
141 for x in gt.check {
142 l += &format!(" {}", b(x));
143 }
144 w(&mut o, l);
145 }
146 if !ap.is_default() {
147 w(
148 &mut o,
149 format!(
150 "PUSH {} {} {} {} {} {}",
151 f(ap.shift[2]),
152 f(ap.shift[1]),
153 f(ap.shift[0]),
154 ap.scale_by_field as u8,
155 f(ap.compress[0]),
156 f(ap.compress[1])
157 ),
158 );
159 }
160 let ft = match s.field_type {
161 FieldType::Angle => 0,
162 FieldType::ObjH => 1,
163 FieldType::ParH => 2,
164 FieldType::RealH => 3,
165 FieldType::Solve(c) => {
166 notimpl!("a field set by a condition ({c:?}) can't be written to .zmx (OpticStudio has none)")
167 }
168 };
169 let nf = s.fields.len();
170 w(
171 &mut o,
172 format!(
173 "FTYP {ft} {} {nf} {} {} 0 {} {nf}",
176 if s.telecentric { 1 } else { 0 },
177 s.wavelengths.len(),
178 if s.field_norm == FieldNorm::Rect {
179 1
180 } else {
181 0
182 },
183 if s.afocal { 1 } else { 0 }
184 ),
185 );
186 w(&mut o, format!("ROPD {}", s.ropd));
187 match s.apodization {
190 lensbench_core::pupil::Apodization::Uniform => {}
191 lensbench_core::pupil::Apodization::Gaussian(g) => w(&mut o, format!("GFAC {} 1", f(g))),
192 lensbench_core::pupil::Apodization::CosineCubed => w(&mut o, "GFAC 0 2".to_string()),
193 }
194 let row = |key: &str, g: &dyn Fn(&lensbench_core::system::Field) -> f64| -> String {
195 let v: Vec<String> = s.fields.iter().map(|x| f(g(x))).collect();
196 format!("{key} {}", v.join(" "))
197 };
198 w(&mut o, row("XFLN", &|x| x.x));
199 w(&mut o, row("YFLN", &|x| x.y));
200 w(&mut o, row("FWGN", &|x| x.w));
201 w(&mut o, row("VDXN", &|x| x.vdx));
202 w(&mut o, row("VDYN", &|x| x.vdy));
203 w(&mut o, row("VCXN", &|x| x.vcx));
204 w(&mut o, row("VCYN", &|x| x.vcy));
205 w(&mut o, row("VANN", &|x| x.van));
206 for (i, (l, q)) in s.wavelengths.iter().zip(&s.weights).enumerate() {
207 w(&mut o, format!("WAVM {} {} {}", i + 1, f(*l), f(*q)));
208 }
209 w(&mut o, format!("PWAV {}", s.primary + 1));
210 w(&mut o, format!("GLRS {} 0", s.glrs));
211 let grd = s
213 .surfaces
214 .iter()
215 .find_map(|d| match d.grin().map(|g| &g.kind) {
216 Some(lensbench_core::grin::GrinKind::Gradium { prof, .. })
217 if !prof.file.eq_ignore_ascii_case("PROFILE.GRD") =>
218 {
219 Some(prof.file.clone())
220 }
221 _ => None,
222 });
223 let coat = if uses_coat_tables(s) {
225 Some(coat_file.to_string())
226 } else {
227 s.coating_file
228 .as_ref()
229 .and_then(|p| p.file_name())
230 .map(|c| c.to_string_lossy().to_string())
231 };
232 match (coat, grd) {
233 (Some(c), None) => {
234 w(&mut o, format!("COFN QF \"{c}\""));
235 w(&mut o, format!("COFN {c}"));
236 }
237 (c, Some(g)) => {
238 let c = c.unwrap_or_else(|| "COATING.DAT".into());
239 w(
240 &mut o,
241 format!("COFN QF \"{c}\" \"SCATTER_PROFILE.DAT\" \"ABG_DATA.DAT\" \"{g}\""),
242 );
243 w(
244 &mut o,
245 format!("COFN {c} SCATTER_PROFILE.DAT ABG_DATA.DAT {g}"),
246 );
247 }
248 (None, None) => {}
249 }
250 Ok(o)
251}
252
253pub(crate) fn write_as(s: &System, coat_file: &str) -> Result<String> {
254 if s.mech_clip && !s.mechanics.is_empty() {
255 return write_as(&lensbench_core::mech::as_apertures(s)?.0, coat_file);
257 }
258 if s.units.iter().any(|u| u.moved()) {
259 let mut f = s.flatten_units()?.into_prescription();
262 f.configs = None;
263 return write_as(&f.build_raw()?, coat_file);
264 }
265 let mut o = write_header(s, coat_file)?;
266 let w = |o: &mut String, l: String| {
267 o.push_str(&l);
268 o.push('\n');
269 };
270 for (k, d) in s.surfaces.iter().enumerate() {
271 if d.dn != 0.0 || d.disp != 0.0 {
272 notimpl!(
273 "surface {k}: an index offset (dn {}, disp {}) can't be written to .zmx",
274 d.dn,
275 d.disp
276 );
277 }
278 if d.dnd != 0.0 || d.dvd != 0.0 {
279 notimpl!(
280 "surface {k}: a glass nd or vd offset (nd {}, vd {}) can't be written to .zmx",
281 d.dnd,
282 d.dvd
283 );
284 }
285 if d.typ() == SurfType::User && !d.ignore {
286 notimpl!("surface {k}: a user-defined surface can't be written to .zmx (OpticStudio has none)");
287 }
288 if d.typ() == SurfType::UserShape && !d.ignore {
289 notimpl!(
290 "surface {k}: a user-defined shape can't be written to .zmx (OpticStudio has none)"
291 );
292 }
293 w(&mut o, format!("SURF {k}"));
294 let typ = match d.typ() {
295 SurfType::Standard => "STANDARD",
296 SurfType::EvenAsph => "EVENASPH",
297 SurfType::CoordBrk => "COORDBRK",
298 SurfType::Jones => "JONESMAT",
299 SurfType::Paraxial => "PARAXIAL",
300 SurfType::Toroidal => "TOROIDAL",
301 SurfType::ZernikeStd => "SZERNSAG",
302 SurfType::ZernikeFringe => "FZERNSAG",
303 SurfType::GridSag => "GRID_SAG",
304 SurfType::Fresnel => "FRESNELS",
305 SurfType::CylFresnel => "CFRESNEL",
306 SurfType::Binary2 => "BINARY_2",
307 SurfType::Gradium => "GRINSUR8",
308 SurfType::Gradient9 => "GRINSUR9",
309 SurfType::OddAsph => "ODDASPHE",
310 SurfType::TiltSurf => "TILTSURF",
311 SurfType::Irregular => "IRREGULA",
312 SurfType::User | SurfType::UserShape => "STANDARD",
314 };
315 let bire = match (&d.bire, d.typ()) {
317 (Some(b), SurfType::Standard) => Some(b),
318 (Some(_), t) => {
319 notimpl!("surface {k}: the birefringent plate surface is {t:?} (standard only)")
320 }
321 (None, _) => None,
322 };
323 match bire {
324 Some(Bire::In { .. }) => w(&mut o, " TYPE BIRE__IN \"\"".into()),
325 Some(Bire::Out) => w(&mut o, " TYPE BIRE_OUT".into()),
326 None => w(&mut o, format!(" TYPE {typ}")),
327 }
328 if !d.comment.is_empty() {
329 w(&mut o, format!(" COMM {}", d.comment));
330 }
331 if d.stop {
332 w(&mut o, " STOP".into());
333 }
334 if d.ignore {
335 w(&mut o, " HIDE 0 0 0 0 0 1 0 0 0 0 0 0 0".into());
337 }
338 match s
339 .pickups
340 .iter()
341 .find(|q| q.dst == k && q.what == Kind::Curv)
342 {
343 Some(q) => w(
344 &mut o,
345 format!(
346 " CURV {} 4 {} {} {} \"\"",
347 f(d.c),
348 q.src,
349 f(q.scale),
350 col(q)
351 ),
352 ),
353 None => match s.solves.iter().find(|q| q.surf == k && q.kind.is_curv()) {
354 Some(Solve {
356 kind: SolveKind::MacroCurv { index: i },
357 ..
358 }) => {
359 let name = s
360 .macros
361 .get(*i as usize)
362 .map(|m| m.name.as_str())
363 .unwrap_or("");
364 w(&mut o, format!(" CURV {} 12 0 0 0 \"{name}\"", f(d.c)))
365 }
366 Some(q) => {
368 let (code, v) = match q.kind {
369 SolveKind::MarginalAngle { .. } => (2, q.kind.value()),
370 SolveKind::ChiefAngle { .. } => (3, q.kind.value()),
371 SolveKind::MarginalNormal => (5, 0.0),
372 SolveKind::ChiefNormal => (6, 0.0),
373 SolveKind::Aplanatic => (7, 0.0),
374 SolveKind::ElementPower { .. } => (8, q.kind.value()),
375 SolveKind::ConcentricSurface { other: j } => (9, j as f64),
376 SolveKind::ConcentricRadius { other: j } => (10, j as f64),
377 SolveKind::FNumber { .. } => (11, q.kind.value()),
378 _ => unreachable!(),
379 };
380 w(
381 &mut o,
382 format!(" CURV {} {code} {} 0 0 \"\"", f(d.c), f(v)),
383 )
384 }
385 None => w(&mut o, format!(" CURV {}", f(d.c))),
386 },
387 }
388 if d.k != 0.0 {
389 w(&mut o, format!(" CONI {}", f(d.k)));
390 }
391 match bire {
392 Some(Bire::In { mode, axis, .. }) => {
393 let mut v = vec![0.0, *mode as f64, axis[0], axis[1], axis[2], 1.0];
395 v.resize(13, 0.0);
396 for (i, a) in v.iter().enumerate() {
397 w(&mut o, format!(" PARM {i} {}", f(*a)));
398 }
399 w(&mut o, " XDAT 1 0 0 0 1 0 0 \"\"".into());
400 }
401 Some(Bire::Out) => {
402 for i in 1..=12 {
403 w(&mut o, format!(" PARM {i} 0"));
404 }
405 }
406 None => {}
407 }
408 match d.typ() {
409 SurfType::EvenAsph
410 | SurfType::Fresnel
411 | SurfType::OddAsph
412 | SurfType::TiltSurf
413 | SurfType::Irregular => {
414 for (i, a) in d.asph().iter().enumerate() {
415 w(&mut o, format!(" PARM {} {}", i + 1, f(*a)));
416 }
417 }
418 SurfType::Binary2 => {
419 let Some(b) = &d.bin2() else {
421 notimpl!("surface {k}: no Binary 2 phase");
422 };
423 w(&mut o, format!(" PARM 0 {}", f(b.order)));
424 for (i, a) in d.asph().iter().enumerate() {
425 w(&mut o, format!(" PARM {} {}", i + 1, f(*a)));
426 }
427 w(&mut o, format!(" XDAT 1 {} 0 0 1 0 0 \"\"", b.coef.len()));
428 w(&mut o, format!(" XDAT 2 {} 0 0 1 0 0 \"\"", f(b.norm)));
429 for (i, a) in b.coef.iter().enumerate() {
430 w(&mut o, format!(" XDAT {} {} 0 0 1 0 0 \"\"", i + 3, f(*a)));
431 }
432 }
433 SurfType::CylFresnel => {
434 let Some(cf) = &d.cylf() else {
436 notimpl!("surface {k}: no Cylinder Fresnel surface");
437 };
438 for (i, a) in d.asph().iter().enumerate() {
439 w(&mut o, format!(" PARM {} {}", i + 1, f(*a)));
440 }
441 w(&mut o, format!(" XDAT 1 {} 0 0 1 0 0 \"\"", cf.coef.len()));
442 w(&mut o, format!(" XDAT 2 {} 0 0 1 0 0 \"\"", f(cf.c)));
443 w(&mut o, format!(" XDAT 3 {} 0 0 1 0 0 \"\"", f(cf.k)));
444 for (i, a) in cf.coef.iter().enumerate() {
445 w(&mut o, format!(" XDAT {} {} 0 0 1 0 0 \"\"", i + 4, f(*a)));
446 }
447 }
448 SurfType::Gradium | SurfType::Gradient9 => {
449 let Some(g) = &d.grin() else {
452 notimpl!("surface {k}: no GRIN profile");
453 };
454 match &g.kind {
455 lensbench_core::grin::GrinKind::Gradium {
456 prof, dz, dec, cap, ..
457 } => {
458 if prof.flipped {
459 let name = &prof.name;
460 notimpl!("surface {k}: the Gradium profile {name} is flipped (after a mirror or in a reversed lens) and differs from the profile file, so it can't be written to .zmx");
461 }
462 w(&mut o, format!(" PARM 0 {}", f(prof.zmax)));
463 w(&mut o, format!(" PARM 1 {}", f(g.dt)));
464 w(&mut o, format!(" PARM 2 {}", f(*dz)));
465 w(
466 &mut o,
467 format!(" PARM 3 {}", f(g.ref_index().unwrap_or(0.0))),
468 );
469 for (i, a) in dec.iter().enumerate() {
470 w(&mut o, format!(" PARM {} {}", i + 4, f(*a)));
471 }
472 w(&mut o, format!(" PARM 8 {cap}"));
473 }
474 lensbench_core::grin::GrinKind::Grad9 { tan, .. } => {
475 w(&mut o, format!(" PARM 1 {}", f(g.dt)));
476 w(&mut o, format!(" PARM 2 {}", f(tan[0])));
477 w(&mut o, format!(" PARM 3 {}", f(tan[1])));
478 }
479 }
480 }
481 SurfType::CoordBrk => {
483 for i in 1..=5 {
484 w(
485 &mut o,
486 format!(" PARM {i} {}", f(d.parm(i).unwrap_or(0.0))),
487 );
488 }
489 w(&mut o, format!(" PARM 6 {}", d.cb_order()));
490 }
491 SurfType::Jones => {
492 for i in 1..=8 {
493 w(
494 &mut o,
495 format!(" PARM {i} {}", f(d.parm(i).unwrap_or(0.0))),
496 );
497 }
498 }
499 SurfType::Paraxial => {
500 w(&mut o, format!(" PARM 1 {}", f(d.parm(1).unwrap_or(0.0))));
501 w(&mut o, format!(" PARM 2 {}", d.opd_mode()));
502 }
503 SurfType::User | SurfType::UserShape => {}
504 SurfType::Toroidal => {
505 w(&mut o, format!(" PARM 1 {}", f(d.parm(1).unwrap_or(0.0))));
506 for (i, a) in d.asph().iter().enumerate() {
507 w(&mut o, format!(" PARM {} {}", i + 2, f(*a)));
508 }
509 w(&mut o, " XDAT 1 0 0 0 1 0 0 \"\"".into());
511 w(&mut o, " XDAT 2 100 0 0 1 0 0 \"\"".into());
512 }
513 SurfType::ZernikeStd | SurfType::ZernikeFringe | SurfType::GridSag => {
514 let z = d.zern();
517 let p0 = match (&d.grid(), z) {
518 (Some(g), _) => {
519 if g.linear {
520 1.0
521 } else {
522 0.0
523 }
524 }
525 (None, Some(z)) => {
526 if z.extrapolate {
527 1.0
528 } else {
529 0.0
530 }
531 }
532 (None, None) => 1.0,
533 };
534 if d.typ() == SurfType::GridSag && z.is_some_and(|z| !z.extrapolate) {
535 notimpl!("surface {k}: the Grid Sag Zernike terms can only be extrapolated");
536 }
537 if d.asph().len() > 8 {
538 notimpl!("surface {k}: terms of r^18 or higher");
539 }
540 w(&mut o, format!(" PARM 0 {}", f(p0)));
541 for i in 0..8 {
542 w(
543 &mut o,
544 format!(
545 " PARM {} {}",
546 i + 1,
547 f(d.asph().get(i).copied().unwrap_or(0.0))
548 ),
549 );
550 }
551 w(&mut o, format!(" PARM 9 {}", f(z.map_or(0.0, |z| z.dx))));
552 w(&mut o, format!(" PARM 10 {}", f(z.map_or(0.0, |z| z.dy))));
553 let (nt, norm) = z.map_or((0, 100.0), |z| (z.coef.len(), z.norm));
554 w(&mut o, format!(" XDAT 1 {nt} 0 0 1 0 0 \"\""));
555 w(&mut o, format!(" XDAT 2 {} 0 0 1 0 0 \"\"", f(norm)));
556 if let Some(z) = z {
557 for (i, a) in z.coef.iter().enumerate() {
558 w(&mut o, format!(" XDAT {} {} 0 0 1 0 0 \"\"", i + 3, f(*a)));
559 }
560 }
561 if d.typ() == SurfType::GridSag {
562 let Some(g) = &d.grid() else {
563 notimpl!("surface {k}: no Grid Sag grid");
564 };
565 w(&mut o, format!(" FIMP {}", d.grid_file()));
566 w(
567 &mut o,
568 format!(
569 " GDAT {} {} {} {} {} {} 0 0 0 1",
570 g.nx,
571 g.ny,
572 f(g.dx),
573 f(g.dy),
574 f(g.xdec),
575 f(g.ydec)
576 ),
577 );
578 let mut i = 0;
580 for row in (0..g.ny).rev() {
581 for ix in 0..g.nx {
582 let kk = row * g.nx + ix;
583 let v = g.z[kk];
584 w(
585 &mut o,
586 format!(
587 " GARR {i} {} {} {} {} {}",
588 f(v[0]),
589 f(v[1]),
590 f(v[2]),
591 f(v[3]),
592 u8::from(g.nodata[kk])
593 ),
594 );
595 i += 1;
596 }
597 }
598 }
599 }
600 SurfType::Standard => {}
601 }
602 for q in s.pickups.iter().filter(|q| q.dst == k) {
603 match q.what {
604 Kind::Thick => w(
605 &mut o,
606 format!(" PZUP {} {} {} {}", q.src, f(q.scale), f(q.offset), col(q)),
607 ),
608 Kind::Conic => w(
610 &mut o,
611 format!(" PKUP {} {} {}", q.src, f(q.scale), col(q)),
612 ),
613 Kind::Parm(i) => w(
614 &mut o,
615 format!(
616 " PPAR {i} {} {} {} {}",
617 q.src,
618 f(q.scale),
619 f(q.offset),
620 col(q)
621 ),
622 ),
623 Kind::Curv
625 | Kind::Dn
626 | Kind::Disp
627 | Kind::Semi
628 | Kind::After(_)
629 | Kind::Radius
630 | Kind::Before(_)
631 | Kind::Coating => {}
632 _ => {}
634 }
635 }
636 for q in s.macro_parms.iter().filter(|q| q.surf == k) {
639 let name = macro_name(s, q.id);
640 match q.what {
641 Kind::Parm(i) => w(&mut o, format!(" PZPL {i} \"{name}\"")),
642 Kind::Conic => w(&mut o, format!(" KZPL \"{name}\"")),
643 _ => {}
644 }
645 }
646 if d.tce != 0.0 {
647 w(&mut o, format!(" TCED {} 0 0", f(d.tce)));
648 }
649 w(&mut o, format!(" DISZ {}", f(d.t)));
650 for q in s.solves.iter().filter(|q| q.surf == k && !q.kind.is_curv()) {
652 let h = f(q.kind.value());
653 let line = match q.kind {
654 SolveKind::MarginalHeight { .. } => format!(" MAZH {h} 0"),
655 SolveKind::MarginalHeightZone { zone: z, .. } => format!(" MAZH {h} {}", f(z)),
656 SolveKind::ChiefHeight { .. } => format!(" CHZH {h} 0"),
657 SolveKind::PupilPosition => " TPUP 0 0".into(),
658 SolveKind::Edge { radius: r, .. } => format!(" EDGE {h} {}", f(r)),
659 SolveKind::Opd { zone: z, .. } => format!(" OPDZ {h} {}", f(z)),
660 SolveKind::Position { other: j, .. } => format!(" TOLE {j} {h}"),
661 SolveKind::Compensator { other: j, .. } => format!(" TCOM {j} {h}"),
662 SolveKind::CenterOfCurvature { other: j } => format!(" TCOC {j} 0"),
663 SolveKind::MacroThick { index: i } => {
665 let name = s
666 .macros
667 .get(i as usize)
668 .map(|m| m.name.as_str())
669 .unwrap_or("");
670 format!(" TZPL \"{name}\"")
671 }
672 _ => unreachable!(),
673 };
674 w(&mut o, line);
675 }
676 let mat_pick = s.pickups.iter().find(|q| q.dst == k && q.what == Kind::Dn);
677 if d.is_mirror() {
678 w(&mut o, " GLAS MIRROR 0 0 1.5 40 0 0 0 0 0 0".into());
679 } else if let (Some(q), false) = (mat_pick, d.typ() == SurfType::CoordBrk) {
680 let name = match d.mat.glass() {
682 Some(m) if s.glasses.contains_key(m) => glass_name(m),
683 _ => "___BLANK",
684 };
685 w(
686 &mut o,
687 format!(" GLAS {name} 2 {} 1.5 40 0 0 0 0 0 0", q.src),
688 );
689 } else if d.typ() != SurfType::CoordBrk {
690 match &d.mat {
691 Material::Air | Material::Mirror | Material::Inherit => {}
692 Material::Glass(m) if s.glasses.contains_key(m) || d.grin().is_some() => {
693 let m = glass_name(m);
695 w(&mut o, format!(" GLAS {m} 0 0 1.5 40 0 0 0 0 0 0"));
696 }
697 Material::Glass(m) => {
698 notimpl!("surface {k}: writing glass {m} that is not in the catalogs");
699 }
700 Material::Model { nd, vd, dpgf } => w(
702 &mut o,
703 format!(
704 " GLAS ___BLANK 1 0 {} {} {} 0 0 0 0",
705 f(*nd),
706 f(*vd),
707 f(*dpgf)
708 ),
709 ),
710 Material::Index(nd) => w(
712 &mut o,
713 format!(" GLAS ___BLANK 1 0 {} 0 0 0 0 0 0 0", f(*nd)),
714 ),
715 }
716 }
717 if !d.coat.is_empty() {
718 w(&mut o, format!(" COAT {}", d.coat));
719 }
720 match s
721 .pickups
722 .iter()
723 .find(|q| q.dst == k && q.what == Kind::Semi)
724 {
725 Some(q) => w(
727 &mut o,
728 format!(
729 " DIAM {} 2 {} {} {} \"\"",
730 f(d.semi),
731 q.src,
732 col(q),
733 f(q.scale)
734 ),
735 ),
736 None => match s
737 .macro_parms
738 .iter()
739 .find(|q| q.surf == k && q.what == Kind::Semi)
740 {
741 Some(q) => w(
743 &mut o,
744 format!(" DIAM {} 4 0 0 1 \"{}\"", f(d.semi), macro_name(s, q.id)),
745 ),
746 None => w(
750 &mut o,
751 format!(
752 " DIAM {} {} 0 0 1 \"\"",
753 f(d.semi),
754 if d.semi_auto
755 || d.typ() == SurfType::CoordBrk
756 || (d.semi == 0.0 && d.ap == Aperture::None)
757 {
758 0
759 } else {
760 1
761 }
762 ),
763 ),
764 },
765 }
766 if d.chip_zone != 0.0 {
769 w(&mut o, format!(" OEMA {} 0 0 0 1 \"\"", f(d.chip_zone)));
770 }
771 match (
772 s.pickups
773 .iter()
774 .find(|q| q.dst == k && q.what == Kind::MechSemi),
775 d.mech_semi,
776 ) {
777 (Some(q), _) if q.offset != 0.0 => notimpl!(
779 "surface {k}: the mechanical semi-diameter pickup has an offset ({}), which can't be written to .zmx",
780 q.offset
781 ),
782 (Some(q), m) => w(
783 &mut o,
784 format!(
785 " MEMA {} 2 {} 0 {} \"\"",
786 f(m.unwrap_or(0.0)),
787 q.src,
788 f(q.scale)
789 ),
790 ),
791 (None, Some(m)) => match s
792 .macro_parms
793 .iter()
794 .find(|q| q.surf == k && q.what == Kind::MechSemi)
795 {
796 Some(q) => w(
798 &mut o,
799 format!(" MEMA {} 3 0 0 1 \"{}\"", f(m), macro_name(s, q.id)),
800 ),
801 None => w(&mut o, format!(" MEMA {} 1 0 0 1 \"\"", f(m))),
802 },
803 (None, None) => w(&mut o, format!(" MEMA {} 0 0 0 1 \"\"", f(s.lens_radius(k)))),
806 }
807 match d.ap {
808 Aperture::None => {}
809 Aperture::Circular { min, max, dx, dy } => {
810 w(&mut o, format!(" CLAP {} {} 0", f(min), f(max)));
811 w(&mut o, format!(" OBDC {} {}", f(dx), f(dy)));
812 }
813 Aperture::Rect { hx, hy, dx, dy } => {
814 w(&mut o, format!(" SQAP {} {} 0", f(hx), f(hy)));
815 w(&mut o, format!(" OBDC {} {}", f(dx), f(dy)));
816 }
817 Aperture::Ellipse { hx, hy, dx, dy } => {
818 w(&mut o, format!(" ELAP {} {} 0", f(hx), f(hy)));
819 w(&mut o, format!(" OBDC {} {}", f(dx), f(dy)));
820 }
821 Aperture::Floating { semi } => {
822 w(&mut o, format!(" FLAP 0 {} 0", f(semi)));
823 }
824 Aperture::Obsc { min, max, dx, dy } => {
825 w(&mut o, format!(" OBSC {} {} 0", f(min), f(max)));
826 w(&mut o, format!(" OBDC {} {}", f(dx), f(dy)));
827 }
828 Aperture::Spider {
829 width,
830 arms,
831 dx,
832 dy,
833 } => {
834 w(&mut o, format!(" SPID {} {arms} 0", f(width)));
835 w(&mut o, format!(" OBDC {} {}", f(dx), f(dy)));
836 }
837 }
838 if let Some(t) = &d.before {
839 tilt_line(&mut o, 1, 0, t);
840 }
841 let after_pick = s
842 .pickups
843 .iter()
844 .find(|q| q.dst == k && matches!(q.what, Kind::After(_)));
845 match (&d.after, &d.before) {
846 (a, _) if after_pick.is_some() => {
848 let q = after_pick.expect("checked by the match guard");
849 let mode = 2 * (k - q.src) + if q.scale < 0.0 { 2 } else { 1 };
850 let t = match a {
851 After::Tilt(t) => *t,
852 _ => Tilt {
853 d: [0.0; 5],
854 order: 0,
855 },
856 };
857 tilt_line(&mut o, 2, mode, &t);
858 }
859 (After::None, _) => {}
860 (After::Reverse, Some(b)) => {
861 let r = Tilt {
862 d: b.d.map(|v| -v),
863 order: 1 - b.order.min(1),
864 };
865 tilt_line(&mut o, 2, 2, &r);
866 }
867 (After::Reverse, None) => {}
868 (After::Tilt(t), _) => tilt_line(&mut o, 2, 0, t),
869 }
870 if let Some(c) = d
872 .coord_return
873 .filter(|c| c.mode != ReturnMode::Off && d.is_coord_break())
874 {
875 w(&mut o, format!(" SCBD 3 {} {}", c.mode.os_code(), c.surf));
876 }
877 }
878 if let Some(c) = &s.configs {
880 w(&mut o, format!("MNUM {} {}", c.n, c.active));
881 let row_no = config_row_numbers(s, c);
883 let mut row = 0;
884 for r in &c.rows {
885 row += 1;
886 if r.is_material() {
887 for k in 1..=c.n {
888 let name = r.name_at(k).map_err(|e| e.to_string())?;
889 let p1 = r.param.index();
890 w(
891 &mut o,
892 format!("GLSS {p1} {k} \"{name}\" 0 0 0 1 1 0 0 \"\" 0"),
893 );
894 }
895 continue;
896 }
897 if r.is_coating() {
898 for k in 1..=c.n {
899 let name = r.name_at(k).map_err(|e| e.to_string())?;
900 let p1 = r.param.index();
901 w(
902 &mut o,
903 format!("COTN {p1} {k} \"{name}\" 0 0 0 1 1 0 0.0 \"\" 0"),
904 );
905 }
906 continue;
907 }
908 let Some((op, p1, parm, conv)) = config_op(s, r.param) else {
909 row -= 1;
910 continue;
911 };
912 let p = parm.unwrap_or(0);
913 for (k, &v) in r.values.iter().enumerate() {
914 let v = conv(v);
915 let src_row = |q: &lensbench_core::configs::ConfigPick| match q.row {
918 None => Some(row),
919 Some(p) => row_no
920 .iter()
921 .find(|(x, _)| *x == p)
922 .map(|(_, n)| *n)
923 .filter(|&n| n < row && q.from <= q.k),
924 };
925 let (t, from, src, sc, off) = match r.pick(k + 1) {
926 Some(q) if !config_pick_unwritable(r) && src_row(q).is_some() => (
927 q.from + 1,
928 q.from,
929 src_row(q).unwrap_or(row),
930 q.scale,
931 conv(q.offset),
932 ),
933 _ => (0, 1, 1, 1.0, 0.0),
934 };
935 w(
936 &mut o,
937 format!(
938 "{op} {p1} {} {} {t} {p} 0 {from} {src} {} {} 0 \"\" 0",
939 k + 1,
940 f(v),
941 f(sc),
942 f(off)
943 ),
944 );
945 }
946 }
947 }
948 Ok(o.replace('\n', "\r\n"))
949}
950
951pub fn save(path: &Path, s: &System) -> Result<Vec<String>> {
956 let name = coat_file_for(path);
957 let txt = write_as(s, &name)?;
958 save_coating(path, &name, s)?;
959 save_utf16(path, &txt)?;
960 Ok(write_notes(s))
961}
962
963pub fn save_with_merit(
966 path: &Path,
967 s: &System,
968 rows: &[crate::zmx::merit::MeritRow],
969) -> Result<Vec<String>> {
970 let name = coat_file_for(path);
971 let mut txt = write_as(s, &name)?;
972 let mut notes = write_notes(s);
973 if !rows.is_empty() {
974 if s.units.iter().any(|u| u.moved()) || (s.mech_clip && !s.mechanics.is_empty()) {
975 notes.push(
976 "the merit function was not written to the .zmx (moving lenses or groups or the apertures of mechanical parts renumber the surfaces)"
977 .into(),
978 );
979 } else {
980 let has_mce = txt.starts_with("MNUM ") || txt.contains("\r\nMNUM ");
982 let later = rows
983 .iter()
984 .position(|r| r.op == "CONF" && r.int(0).is_ok_and(|c| c > 1));
985 let cut = later.filter(|_| !has_mce);
986 if later.is_some() && has_mce {
987 notes.push(
988 "the .zmx is written from configuration 1; the multi-configuration table keeps the values read"
989 .into(),
990 );
991 }
992 if cut.is_some() {
993 notes.push(
994 "the merit function rows of configurations 2 and later were not written (the .zmx has no multi-configuration table)"
995 .into(),
996 );
997 }
998 txt = insert_merit(&txt, &rows[..cut.unwrap_or(rows.len())]);
999 }
1000 }
1001 save_coating(path, &name, s)?;
1002 save_utf16(path, &txt)?;
1003 Ok(notes)
1004}
1005
1006fn insert_merit(txt: &str, rows: &[crate::zmx::merit::MeritRow]) -> String {
1008 let mut block = String::new();
1009 for r in rows {
1010 block.push_str(&r.text());
1011 block.push_str("\r\n");
1012 }
1013 let at = if txt.starts_with("MNUM ") {
1014 Some(0)
1015 } else {
1016 txt.find("\r\nMNUM ").map(|i| i + 2)
1017 };
1018 match at {
1019 Some(i) => format!("{}{block}{}", &txt[..i], &txt[i..]),
1020 None => format!("{txt}{block}"),
1021 }
1022}
1023
1024pub fn write_notes(s: &System) -> Vec<String> {
1026 let mut out = Vec::new();
1027 if s.units.iter().any(|u| u.moved()) {
1028 out.push(
1029 "lens and group moves were written as coordinate breaks (the surface numbers change)"
1030 .to_string(),
1031 );
1032 }
1033 for q in &s.pickups {
1034 let what = match q.what {
1035 Kind::Before(_) => "tilt and decenter before the surface",
1036 Kind::Coating => "coating",
1037 Kind::Radius => "radius of curvature",
1038 _ => continue,
1039 };
1040 out.push(format!(
1041 "the {what} pickup of surface {} (from surface {}) can't be written to .zmx, so only the value was written",
1042 q.dst, q.src
1043 ));
1044 }
1045 if !s.mechanics.is_empty() && s.mech_clip {
1046 out.push(
1047 "the bores of the mechanical parts were written as circular apertures on dummy surfaces at their ends (the surface numbers change)"
1048 .to_string(),
1049 );
1050 if let Ok((_, n)) = lensbench_core::mech::as_apertures(s) {
1051 out.extend(n);
1052 }
1053 } else if !s.mechanics.is_empty() {
1054 out.push(format!(
1055 "{} mechanical parts can't be written to .zmx (they don't clip rays: mech_clip is false)",
1056 s.mechanics.len()
1057 ));
1058 }
1059 if !s.floating_clip {
1060 out.push(
1061 "the setting that floating apertures don't clip (floating_clip: false) can't be written to .zmx (they clip when read back)"
1062 .to_string(),
1063 );
1064 }
1065 let user: std::collections::BTreeSet<String> = s
1067 .surfaces
1068 .iter()
1069 .map(|d| d.mat.name())
1070 .filter(|n| {
1071 s.glasses
1072 .get(n.trim())
1073 .is_some_and(|g| g.formula == lensbench_core::usermaterial::USER_FORMULA)
1074 })
1075 .collect();
1076 if !user.is_empty() {
1077 out.push(format!(
1078 "user-defined materials ({}) were written by name only; OpticStudio has no catalog for them",
1079 user.into_iter().collect::<Vec<_>>().join(", ")
1080 ));
1081 }
1082 out.extend(config_notes(s));
1083 if !out.is_empty() {
1084 out.push("write a system file (.json) to keep everything".to_string());
1085 }
1086 out
1087}
1088
1089fn save_utf16(path: &Path, txt: &str) -> Result<()> {
1090 let mut b = vec![0xffu8, 0xfe];
1091 for u in txt.encode_utf16() {
1092 b.extend_from_slice(&u.to_le_bytes());
1093 }
1094 lensbench_core::vfs::write(path, b).map_err(|e| Error::Io(format!("{}: {e}", path.display())))
1095}
1096
1097fn coat_file_for(path: &Path) -> String {
1099 let stem = path
1100 .file_stem()
1101 .map(|x| x.to_string_lossy().to_string())
1102 .unwrap_or_else(|| "lensbench".into());
1103 format!("{stem}_coat.dat")
1104}
1105
1106fn save_coating(path: &Path, name: &str, s: &System) -> Result<()> {
1107 if let Some(txt) = coating_dat(s)? {
1108 let p = path.with_file_name(name);
1109 lensbench_core::vfs::write(&p, txt.as_bytes())
1110 .map_err(|e| Error::Io(format!("{}: {e}", p.display())))?;
1111 }
1112 Ok(())
1113}
1114
1115fn uses_coat_tables(s: &System) -> bool {
1117 s.surfaces
1118 .iter()
1119 .any(|d| !d.coat.is_empty() && s.coat_tables.contains_key(&d.coat))
1120}
1121
1122pub fn coating_dat(s: &System) -> Result<Option<String>> {
1126 if !uses_coat_tables(s) {
1127 return Ok(None);
1128 }
1129 let mut o = String::new();
1130 if let Some(p) = &s.coating_file {
1131 let t = lensbench_core::glass::read_text(p)
1132 .map_err(|e| Error::Io(format!("{}: {e}", p.display())))?;
1133 o.push_str(t.trim_end());
1134 o.push_str("\r\n\r\n");
1135 }
1136 o.push_str("! lensbench: 系に書いた膜の表(プロジェクト・カタログの coatings)\r\n");
1137 let mut names: Vec<&String> = s.coat_tables.keys().collect();
1138 names.sort();
1139 for k in names {
1140 if k.is_empty() || k.chars().any(|c| c.is_whitespace() || !c.is_ascii()) {
1141 notimpl!("coating name {k:?}: a name with spaces or non-ASCII characters can't go in a coating file");
1142 }
1143 let _ = write!(o, "TABLE {k}\r\n");
1144 for (a, rows) in same_wavelengths(&s.coat_tables[k]) {
1145 let _ = write!(o, "ANGL {}\r\n", f(a));
1146 for r in rows {
1147 let v: Vec<String> = r.iter().map(|x| f(*x)).collect();
1148 let _ = write!(o, "WAVE {}\r\n", v.join(" "));
1149 }
1150 }
1151 }
1152 Ok(Some(o))
1153}
1154
1155fn same_wavelengths(t: &lensbench_core::coating::Table) -> Vec<(f64, Vec<[f64; 9]>)> {
1160 let mut wl: Vec<f64> = t.iter().flat_map(|(_, r)| r.iter().map(|x| x[0])).collect();
1161 wl.sort_by(f64::total_cmp);
1162 wl.dedup();
1163 t.iter()
1164 .map(|(a, rows)| {
1165 if rows.len() == wl.len() && rows.iter().zip(&wl).all(|(r, w)| r[0] == *w) {
1166 return (*a, rows.clone());
1167 }
1168 let xs: Vec<f64> = rows.iter().map(|r| r[0]).collect();
1169 let cols: Vec<Vec<f64>> = (1..9)
1170 .map(|k| rows.iter().map(|r| r[k]).collect())
1171 .collect();
1172 let out = wl
1173 .iter()
1174 .map(|&w| {
1175 let mut r = [w; 9];
1176 for k in 1..9 {
1177 r[k] = lensbench_core::coating::interp(w, &xs, &cols[k - 1]);
1178 }
1179 r
1180 })
1181 .collect();
1182 (*a, out)
1183 })
1184 .collect()
1185}
1186
1187pub fn write_configs(systems: &[System]) -> Result<String> {
1194 Ok(write_configs_as(systems, DEFAULT_COAT_FILE)?.0)
1195}
1196
1197fn write_configs_as(systems: &[System], coat_file: &str) -> Result<(String, System)> {
1199 if systems.is_empty() {
1200 lensbench_core::invalid!("no system to write");
1201 }
1202 if systems.len() == 1 {
1203 return Ok((write_as(&systems[0], coat_file)?, systems[0].clone()));
1204 }
1205 let mut ss: Vec<System> = Vec::with_capacity(systems.len());
1206 for (i, s) in systems.iter().enumerate() {
1207 if s.configs.is_some() {
1208 notimpl!(
1209 "configuration {}: systems with a multi-configuration table can't be merged",
1210 i + 1
1211 );
1212 }
1213 if let lensbench_core::system::FieldType::Solve(_) = s.field_type {
1214 notimpl!("a field set by a condition can't be written to .zmx");
1215 }
1216 let t = if s.units.iter().any(|u| u.moved()) {
1217 s.flatten_units()?
1218 } else {
1219 s.clone()
1220 };
1221 let mut t = t.into_prescription();
1222 t.units.clear();
1223 t.pickups.clear();
1224 t.solves.clear();
1225 ss.push(t.build_raw()?);
1226 }
1227 let head = |s: &System| -> Result<Vec<String>> {
1229 let mut t = s.prescription().clone();
1230 t.name = String::new();
1231 Ok(write_header(&t.build_raw()?, coat_file)?
1232 .lines()
1233 .filter(|l| !l.starts_with("GCAT") && !l.starts_with("NAME"))
1234 .map(|l| l.to_string())
1235 .collect())
1236 };
1237 let h0 = head(&ss[0])?;
1238 for (i, s) in ss.iter().enumerate().skip(1) {
1239 let h = head(s)?;
1240 if h != h0 {
1241 let d = h
1242 .iter()
1243 .zip(&h0)
1244 .find(|(a, b)| a != b)
1245 .map(|(a, _)| a.clone())
1246 .unwrap_or_else(|| "the number of lines".into());
1247 notimpl!(
1248 "configuration {} system values differ from configuration 1 ({d})",
1249 i + 1
1250 );
1251 }
1252 }
1253 let key_t = |d: &lensbench_core::surface::Surface| {
1255 let mut d = d.clone();
1256 d.t = 0.0;
1257 if d.semi_auto {
1259 d.semi = 0.0;
1260 if let Aperture::Floating { semi } = &mut d.ap {
1261 *semi = 0.0;
1262 }
1263 }
1264 d
1265 };
1266 let min_img = ss
1267 .iter()
1268 .map(|s| s.image())
1269 .min()
1270 .expect("a system has at least one configuration");
1271 let mut np = 0;
1272 while np < min_img
1273 && ss
1274 .iter()
1275 .all(|s| key_t(&s.surfaces[np]) == key_t(&ss[0].surfaces[np]))
1276 {
1277 np += 1;
1278 }
1279 let thick: Vec<(usize, Vec<f64>)> = (0..np)
1280 .filter_map(|j| {
1281 let v: Vec<f64> = ss.iter().map(|s| s.surfaces[j].t).collect();
1282 v.iter().any(|&t| t != v[0]).then_some((j, v))
1283 })
1284 .collect();
1285 if np == 0 {
1286 notimpl!("the object surface differs between configurations");
1287 }
1288 let glrs = ss[0].glrs;
1289 if ss.iter().any(|s| s.glrs != glrs) || glrs >= np {
1290 notimpl!("the global coordinate reference surface is on a per-configuration surface");
1291 }
1292 let img_key = |s: &System| {
1294 let mut d = s.surfaces[s.image()].clone();
1295 d.semi = 0.0;
1296 d
1297 };
1298 if ss.iter().any(|s| img_key(s) != img_key(&ss[0])) {
1299 notimpl!("the image surface (other than its radius) differs between configurations");
1300 }
1301 let mut surfs: Vec<lensbench_core::surface::Surface> = ss[0].surfaces[..np].to_vec();
1302 let mut tails: Vec<Vec<usize>> = Vec::new();
1304 let mut stops: Vec<usize> = Vec::new();
1305 let mut ign0: Vec<bool> = Vec::new();
1306 for (i, s) in ss.iter().enumerate() {
1307 let mut v = Vec::new();
1308 let st = s.stop();
1309 let mut stop_m = if st < np { st } else { 0 };
1310 for j in np..s.image() {
1311 let mut d = s.surfaces[j].clone();
1312 if j == st {
1313 stop_m = surfs.len();
1314 }
1315 d.stop = false;
1316 ign0.push(d.ignore);
1317 if i > 0 {
1318 d.ignore = true;
1319 }
1320 v.push(surfs.len());
1321 surfs.push(d);
1322 }
1323 tails.push(v);
1324 stops.push(stop_m);
1325 }
1326 for d in surfs.iter_mut() {
1327 d.stop = false;
1328 }
1329 surfs[stops[0]].stop = stops[0] > 0;
1330 let mut im = ss[0].surfaces[ss[0].image()].clone();
1331 im.stop = false;
1332 surfs.push(im);
1333 let nimg = surfs.len() - 1;
1334 let mut m = ss[0].prescription().clone();
1335 m.surfaces = surfs;
1336 for s in &ss[1..] {
1337 if !std::sync::Arc::ptr_eq(&m.glasses, &s.glasses) {
1338 let mg = std::sync::Arc::make_mut(&mut m.glasses);
1339 for (k, g) in s.glasses.iter() {
1340 mg.entry(k.clone()).or_insert_with(|| g.clone());
1341 }
1342 }
1343 for (k, t) in &s.coat_tables {
1344 if m.coat_tables.get(k).is_some_and(|u| u != t) {
1345 notimpl!("coating table {k} differs between configurations");
1346 }
1347 m.coat_tables.entry(k.clone()).or_insert_with(|| t.clone());
1348 }
1349 }
1350 let m = m.build_raw()?;
1351 let mut o = write_as(&m, coat_file)?;
1352 let n = ss.len();
1355 let row = |o: &mut String, op: &str, p1: usize, vals: &[f64]| {
1356 for (c, v) in vals.iter().enumerate() {
1357 o.push_str(&format!(
1358 "{op} {p1} {} {} 0 0 0 1 1 1 0 0 \"\" 0\r\n",
1359 c + 1,
1360 f(*v)
1361 ));
1362 }
1363 };
1364 o.push_str(&format!("MNUM {n} 1\r\n"));
1365 for (j, v) in &thick {
1366 row(&mut o, "THIC", *j, v);
1367 }
1368 let mut t0 = 0;
1369 for (i, v) in tails.iter().enumerate() {
1370 for &j in v {
1371 let own = ign0[t0];
1372 t0 += 1;
1373 let vals: Vec<f64> = (0..n)
1374 .map(|c| {
1375 if c == i {
1376 f64::from(u8::from(own))
1377 } else {
1378 1.0
1379 }
1380 })
1381 .collect();
1382 row(&mut o, "IGNR", j, &vals);
1383 }
1384 }
1385 if stops.iter().any(|&k| k != stops[0]) {
1386 let vals: Vec<f64> = stops.iter().map(|&k| k as f64).collect();
1387 row(&mut o, "STPS", 0, &vals);
1388 }
1389 let semis: Vec<f64> = ss.iter().map(|s| s.surfaces[s.image()].semi).collect();
1390 if semis.iter().any(|&v| v != semis[0]) {
1391 row(&mut o, "SDIA", nimg, &semis);
1392 }
1393 Ok((o, m))
1394}
1395
1396pub fn save_configs(path: &Path, systems: &[System]) -> Result<()> {
1398 let name = coat_file_for(path);
1399 let (txt, m) = write_configs_as(systems, &name)?;
1400 save_coating(path, &name, &m)?;
1401 save_utf16(path, &txt)
1402}
1403
1404fn macro_name(s: &System, id: u16) -> &str {
1406 s.macros
1407 .get(id as usize)
1408 .map(|m| m.name.as_str())
1409 .unwrap_or("")
1410}
1411
1412fn glass_name(m: &str) -> &str {
1414 lensbench_core::glass::base_name(m)
1415}
1416
1417#[cfg(test)]
1418mod merit_tests {
1419 use super::insert_merit;
1420 use crate::zmx::merit::MeritRow;
1421
1422 #[test]
1423 fn merit_before_mnum() {
1424 let rows = [
1425 MeritRow::blank("a\nb"),
1426 MeritRow::new("EFFL", [0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 50.0, 0.5),
1427 ];
1428 let block = "BLNK a b\r\nEFFL 0 1 0 0 0 0 50 0.5 0 0\r\n";
1429 let t = "SURF 0\r\n DISZ 0\r\nMNUM 2 1\r\nTHIC 1 1 5 0 0 0 1 1 1 0 0 \"\" 0\r\n";
1430 let got = insert_merit(t, &rows);
1431 assert_eq!(
1432 got,
1433 format!(
1434 "SURF 0\r\n DISZ 0\r\n{block}MNUM 2 1\r\nTHIC 1 1 5 0 0 0 1 1 1 0 0 \"\" 0\r\n"
1435 )
1436 );
1437 assert_eq!(
1438 insert_merit("SURF 0\r\n", &rows),
1439 format!("SURF 0\r\n{block}")
1440 );
1441 }
1442
1443 #[test]
1445 fn merit_without_mce_drops_later_configs() {
1446 let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
1447 let s = crate::zmx::load_with(
1448 &root.join("tests/refs/A0/system.zmx"),
1449 &crate::zmx::LoadOptions {
1450 cfg: 1,
1451 catalog_dirs: vec![root.join("tests/glass")],
1452 ..Default::default()
1453 },
1454 )
1455 .unwrap();
1456 let z = [0.0; 8];
1457 let rows = [
1458 MeritRow::new("EFFL", [0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 50.0, 1.0),
1459 MeritRow::new("CONF", [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 0.0, 0.0),
1460 MeritRow::new("TOTR", z, 80.0, 1.0),
1461 ];
1462 let dir = std::env::temp_dir().join(format!("lb_merit_mce_{}", std::process::id()));
1463 std::fs::create_dir_all(&dir).unwrap();
1464 let path = dir.join("out.zmx");
1465 let notes = super::save_with_merit(&path, &s, &rows).unwrap();
1466 assert!(
1467 notes
1468 .iter()
1469 .any(|n| n.contains("configurations 2 and later")),
1470 "{notes:?}"
1471 );
1472 let mf = crate::zmx::merit::merit_function(&path).unwrap();
1473 let ops: Vec<&str> = mf.rows.iter().map(|r| r.op.as_str()).collect();
1474 assert_eq!(ops, ["EFFL"]);
1475 std::fs::remove_dir_all(&dir).ok();
1476 }
1477}