1use super::*;
4
5fn mce_line(line: &str) -> Option<(String, i64, i64, String, Vec<String>)> {
6 let b = line.as_bytes();
8 if b.len() < 4
9 || !b[..4]
10 .iter()
11 .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit())
12 {
13 return None;
14 }
15 let rest = &line[4..];
16 if !rest.starts_with(char::is_whitespace) {
17 return None;
18 }
19 let t: Vec<&str> = rest.split_whitespace().collect();
20 if t.len() < 3 {
21 return None;
22 }
23 let p1: i64 = t[0].parse().ok()?;
24 if !t[1].chars().all(|c| c.is_ascii_digit()) {
25 return None;
26 }
27 let cfg: i64 = t[1].parse().ok()?;
28 Some((
29 line[..4].to_string(),
30 p1,
31 cfg,
32 t[2].to_string(),
33 t[3..].iter().map(|s| s.to_string()).collect(),
34 ))
35}
36
37fn config_pickup_columns(rest: &mut [String]) -> Option<String> {
42 let num = |i: usize| rest.get(i).and_then(|x| x.parse::<i64>().ok());
43 let (t, from) = (num(0)?, num(3));
44 if t < 2 || from == Some(t - 1) {
45 return None;
46 }
47 rest[0] = "0".into();
48 Some(format!(
49 "the solve of kind {t} (a thermal pickup or another one) was read as its value"
50 ))
51}
52
53pub fn parse_text(txt: &str) -> Result<Raw> {
54 let mut raw = Raw::default();
55 let mut cur: Option<usize> = None;
56 let mut in_mce = false;
57 let mut last_cfg = i64::MAX;
59 let mut in_merit = false;
61 let legacy = !txt.lines().any(|l| l.starts_with(" "));
64 for (no, line) in txt.lines().enumerate() {
65 let t: Vec<&str> = line.split_whitespace().collect();
66 if t.is_empty() {
67 continue;
68 }
69 let key = if legacy && cur.is_some() && t[0] == "stop" {
70 "STOP"
71 } else {
72 t[0]
73 };
74 let rest = || t[1..].iter().map(|s| s.to_string()).collect::<Vec<_>>();
75 if key == "SURF" {
76 raw.surfs.push(RawSurf {
77 n: t.get(1).and_then(|v| v.parse().ok()).unwrap_or(0),
78 ..Default::default()
79 });
80 cur = Some(raw.surfs.len() - 1);
81 continue;
82 }
83 if key == "MNUM" {
84 in_mce = true;
85 in_merit = false;
86 cur = None;
87 raw.sysl.entry(key.into()).or_default().push(rest());
88 continue;
89 }
90 if key == "TOL" {
91 in_merit = false;
92 }
93 if in_merit {
94 raw.merit
95 .push(merit::MeritRow::parse(raw.merit.len() + 1, no + 1, line));
96 continue;
97 }
98 if in_mce {
99 if key == "BLNK" {
101 let cfg = mce_line(line).map_or(i64::MAX, |m| m.2);
102 if cfg == i64::MAX || cfg <= last_cfg {
103 raw.mce_rows.push((key.to_string(), 0, 0));
104 }
105 last_cfg = cfg;
106 continue;
107 }
108 let Some(mut m) = mce_line(line) else {
109 invalid!("can't read the zmx multi-configuration line: {line}");
110 };
111 if m.0 == "FVAN" {
114 m.0 = "FTAN".into();
115 }
116 if let Some(n) = m.0.strip_prefix("PAR").and_then(|n| n.parse::<u8>().ok()) {
118 if (1..=8).contains(&n) {
119 m.0 = "PRAM".into();
120 m.4.resize(m.4.len().max(2), "0".into());
121 m.4[1] = n.to_string();
122 }
123 }
124 if m.2 <= last_cfg {
125 let parm = if m.0 == "PRAM" || m.0.starts_with("PSP") {
126 m.4.get(1).and_then(|x| x.parse::<i64>().ok()).unwrap_or(-1)
127 } else {
128 0
129 };
130 raw.mce_rows.push((m.0.clone(), m.1, parm));
131 }
132 last_cfg = m.2;
133 if let Some(why) = config_pickup_columns(&mut m.4) {
134 raw.notes.push(format!(
135 "multi-configuration row {} configuration {}: {why}",
136 raw.mce_rows.len(),
137 m.2
138 ));
139 }
140 if m.0 == "IGNM" {
141 let end =
143 m.4.get(1)
144 .and_then(|x| x.parse::<i64>().ok())
145 .unwrap_or(m.1)
146 .min(m.1.saturating_add(100_000));
147 for k in m.1..=end {
148 raw.mce
149 .push(("IGNR".into(), k, m.2, m.3.clone(), m.4.clone()));
150 }
151 continue;
152 }
153 raw.mce.push(m);
154 continue;
155 }
156 let Some(ci) = cur.filter(|_| legacy || line.starts_with(" ")) else {
157 if cur.is_some() && key != "TOL" {
158 in_merit = true;
159 cur = None;
160 raw.merit
161 .push(merit::MeritRow::parse(raw.merit.len() + 1, no + 1, line));
162 continue;
163 }
164 raw.sysl.entry(key.into()).or_default().push(rest());
165 cur = None;
166 continue;
167 };
168 let s = &mut raw.surfs[ci];
169 let num = |i: usize| -> Result<f64> { fv(t.get(i).copied().unwrap_or("0")) };
170 let nums = || -> Result<Vec<f64>> { t[1..].iter().map(|v| fv(v)).collect() };
171 match key {
172 "COMM" => s.comment = line.trim().get(5..).unwrap_or("").to_string(),
173 "PARM" => {
174 s.parm.insert(num(1)? as i64, num(2)?);
175 }
176 "PPAR" if num(2)? < 0.0 => {}
181 "PPAR" => {
182 let i = num(1)? as i64;
183 let from = pick_col(s.n, "PPAR", num(5)?, Kind::Parm(i.clamp(0, 255) as u8))?;
184 s.ppar
185 .insert(i, (surf_no(num(2)?)?, num(3)?, num(4)?, from));
186 }
187 "PZUP" => {
188 let from = pick_col(s.n, "PZUP", num(4)?, Kind::Thick)?;
189 s.pzup = Some((surf_no(num(1)?)?, num(2)?, num(3)?, from));
190 }
191 "MAZH" => {
193 let z = num(2)?;
194 let k = if z == 0.0 {
195 SolveKind::MarginalHeight { height: 0.0 }
196 } else {
197 SolveKind::MarginalHeightZone {
198 height: 0.0,
199 zone: z,
200 }
201 };
202 s.tsolve = Some((k, num(1)?));
203 }
204 "CHZH" => s.tsolve = Some((SolveKind::ChiefHeight { height: 0.0 }, num(1)?)),
205 "TPUP" => s.tsolve = Some((SolveKind::PupilPosition, 0.0)),
206 "EDGE" => {
207 s.tsolve = Some((
208 SolveKind::Edge {
209 thickness: 0.0,
210 radius: num(2)?,
211 },
212 num(1)?,
213 ))
214 }
215 "TOLE" => {
216 s.tsolve = Some((
217 SolveKind::Position {
218 other: surf_no(num(1)?)?,
219 length: 0.0,
220 },
221 num(2)?,
222 ))
223 }
224 "TCOM" => {
225 s.tsolve = Some((
226 SolveKind::Compensator {
227 other: surf_no(num(1)?)?,
228 sum: 0.0,
229 },
230 num(2)?,
231 ))
232 }
233 "TCOC" => {
234 s.tsolve = Some((
235 SolveKind::CenterOfCurvature {
236 other: surf_no(num(1)?)?,
237 },
238 0.0,
239 ))
240 }
241 "OPDZ" => {
242 s.tsolve = Some((
243 SolveKind::Opd {
244 opd: 0.0,
245 zone: num(2)?,
246 },
247 num(1)?,
248 ))
249 }
250 "PKUP" => {
251 let from = pick_col(s.n, "PKUP", num(3)?, Kind::Conic)?;
252 s.pkup = Some((surf_no(num(1)?)?, num(2)?, 0.0, from));
253 }
254 "XDAT" => {
255 s.xdat.insert(num(1)? as i64, num(2)?);
256 }
257 "GDAT" => s.gdat = Some(nums()?),
258 "GARR" => {
259 let v = nums()?;
260 if v.len() < 5 {
261 invalid!("surface {}: too few GARR values", s.n);
262 }
263 let g = |i: usize| v.get(i).copied().unwrap_or(0.0);
264 s.garr.push((
265 count_in(v[0], "GARR number", 0, MAX_GRID)?,
266 [g(1), g(2), g(3), g(4), g(5)],
267 ));
268 }
269 "FIMP" => s.fimp = Some(line.trim().get(5..).unwrap_or("").trim().to_string()),
270 "TYPE" => s.typ = Some(t.get(1).unwrap_or(&"").to_string()),
271 "COAT" => s.coat = Some(t.get(1).unwrap_or(&"").to_string()),
272 "GLAS" => {
275 s.glas = Some(t.get(1).unwrap_or(&"").to_string());
276 if t.get(2) == Some(&"4") && (num(10)? != 0.0 || num(11)? != 0.0) {
278 let (surf, dnd, dvd) = (s.n, num(10)?, num(11)?);
279 notimpl!("zmx surface {surf}: material Offset solve (Δnd {dnd}, Δvd {dvd})");
280 }
281 if t.get(2) == Some(&"2") {
282 s.glas_pickup = Some(surf_no(num(3)?)?);
283 } else if t.get(1) == Some(&"___BLANK") {
284 s.model_glass = Some((num(4)?, num(5)?, num(6)?));
285 }
286 }
287 "CURV" => {
290 s.curv = Some(num(1)?);
291 let p1 = num(3)?;
292 s.csolve = match t.get(2).copied().unwrap_or("0") {
293 "0" | "1" => None,
294 "4" => {
295 let from = pick_col(s.n, "CURV", num(5)?, Kind::Curv)?;
296 s.curv_pickup = Some((surf_no(p1)?, num(4)?, from));
297 None
298 }
299 "2" => Some((SolveKind::MarginalAngle { angle: 0.0 }, p1)),
301 "3" => Some((SolveKind::ChiefAngle { angle: 0.0 }, p1)),
302 "5" => Some((SolveKind::MarginalNormal, 0.0)),
303 "6" => Some((SolveKind::ChiefNormal, 0.0)),
304 "7" => Some((SolveKind::Aplanatic, 0.0)),
305 "8" => Some((SolveKind::ElementPower { power: 0.0 }, p1)),
306 "9" => Some((
307 SolveKind::ConcentricSurface {
308 other: surf_no(p1)?,
309 },
310 0.0,
311 )),
312 "10" => Some((
313 SolveKind::ConcentricRadius {
314 other: surf_no(p1)?,
315 },
316 0.0,
317 )),
318 "11" => Some((SolveKind::FNumber { fnum: 0.0 }, p1)),
319 "12" => {
321 s.cmacro = Some(macro_name(s.n, line)?);
322 None
323 }
324 c => notimpl!("zmx surface {}: curvature solve {c}", s.n),
325 };
326 }
327 "CONI" => s.coni = Some(num(1)?),
328 "TZPL" => s.tmacro = Some(macro_name(s.n, line)?),
330 "KZPL" => s.kmacro = Some(macro_name(s.n, line)?),
331 "PZPL" => {
332 let n = num(1)?;
333 if !(0.0..=255.0).contains(&n) || n.fract() != 0.0 {
334 invalid!("zmx surface {}: PZPL parameter number {n}", s.n);
335 }
336 s.pmacros.push((n as u8, macro_name(s.n, line)?));
337 }
338 "DISZ" => s.disz = Some(num(1)?),
339 "TCED" => s.tced = Some(num(1)?),
340 "DIAM" => {
343 s.diam = Some(num(1)?);
344 s.diam_mode = t.get(2).and_then(|v| v.parse().ok());
345 s.diam_fixed = t.get(2) == Some(&"1");
346 if t.get(2) == Some(&"4") {
347 s.smacro = Some(macro_name(s.n, line)?);
348 }
349 if t.get(2) == Some(&"2") {
350 let from = pick_col(s.n, "DIAM", num(4)?, Kind::Semi)?;
351 s.diam_pickup = Some((surf_no(num(3)?)?, num(5)?, from));
352 }
353 }
354 "CLAP" => s.clap = Some(nums()?),
355 "SQAP" => s.sqap = Some(nums()?),
356 "ELAP" => s.elap = Some(nums()?),
357 "FLAP" => s.flap = Some(nums()?),
358 "OBSC" => s.obsc = Some(nums()?),
359 "SPID" => {
362 let v = nums()?;
363 let (w, n) = (
364 v.first().copied().unwrap_or(0.0),
365 v.get(1).copied().unwrap_or(0.0),
366 );
367 if !(w >= 0.0) || !(n >= 0.0 && n.fract() == 0.0 && n <= u32::MAX as f64) {
368 invalid!("zmx surface {}: spider arm width {w}, {n} arms", s.n);
369 }
370 s.spid = Some(v);
371 }
372 "OBDC" => s.obdc = Some(nums()?),
373 "SCBD" => s.scbd.push(rest()),
374 "STOP" => s.stop = true,
375 "HIDE" => s.ignore = t.get(6).is_some_and(|v| *v != "0"),
378 "MEMA" => match t.get(2).copied().unwrap_or("0") {
382 "0" => {}
383 "1" => s.mema = Some(num(1)?),
384 "3" => {
385 s.mema = Some(num(1)?);
386 s.mmacro = Some(macro_name(s.n, line)?);
387 }
388 "2" if num(4)? == 0.0 => {
389 s.mema = Some(num(1)?);
390 s.mema_pickup = Some((surf_no(num(3)?)?, num(5)?));
391 }
392 "2" => {
393 let (n, col) = (s.n, num(4)?);
394 raw.notes.push(format!(
395 "zmx surface {n}: the mechanical semi-diameter picks up column {col}, which is not supported; it was read as automatic"
396 ));
397 }
398 m => {
399 let n = s.n;
400 raw.notes.push(format!(
401 "zmx surface {n}: mechanical semi-diameter solve {m} is not supported; it was read as automatic"
402 ));
403 }
404 },
405 "OEMA" => s.oema = num(1)?,
406 k if HARMLESS.contains(&k) => {}
407 k if legacy => raw.notes.push(format!(
408 "zmx surface {}: line {k} was skipped (an old .zmx without indentation)",
409 s.n
410 )),
411 "NSOH" => notimpl!(
413 "zmx surface {}: non-sequential objects (NSOH) are not supported (a non-sequential or mixed-mode system)",
414 s.n
415 ),
416 k => notimpl!("zmx surface {}: line {} is not supported", s.n, k),
417 }
418 }
419 raw.check_counts()?;
420 Ok(raw)
421}
422
423fn macro_name(n: i64, line: &str) -> Result<String> {
425 match (line.find('"'), line.rfind('"')) {
426 (Some(a), Some(b)) if b > a + 1 => Ok(line[a + 1..b].to_string()),
427 _ => invalid!("zmx surface {n}: no macro solve name"),
428 }
429}
430
431fn surf_no(v: f64) -> Result<usize> {
433 if v < 0.0 || v.fract() != 0.0 {
434 invalid!("surface number {v}");
435 }
436 Ok(v as usize)
437}
438
439fn pick_col(n: i64, key: &str, col: f64, dst: Kind) -> Result<Option<Kind>> {
441 match Kind::from_column(col as i64, dst).filter(|_| col.fract() == 0.0) {
442 Some(f) => Ok(f),
443 None => notimpl!("zmx surface {n}: pickup column {col} of {key}"),
444 }
445}