Skip to main content

lensbench_project/
expand.rs

1//! 展開の入口(状態・経路)と、面の並びのあとの仕上げ(機構部品の配置・面の操作と編集・群の移動・ピックアップの保持)
2
3use super::*;
4use lensbench_core::error::code;
5use lensbench_core::glass::DIRS_HINT as HINT;
6/// .zmx の取り込みの群の、要素の範囲 (群の番号, 最初, 最後)。最初・最後は面が from〜to に始まる要素(空気でない)
7pub(crate) fn zmx_group_spans(
8    keep: &[Element],
9    groups: &[ZmxGroup],
10) -> lensbench_core::Result<Vec<(usize, usize, usize)>> {
11    let mut out: Vec<(usize, usize, usize)> = Vec::new();
12    for (g, gr) in groups.iter().enumerate() {
13        let label = if gr.id.is_empty() { &gr.name } else { &gr.id };
14        if gr.from > gr.to {
15            return Err(format!(
16                "group {label}: surfaces {} to {} are in reverse order",
17                gr.from, gr.to
18            )
19            .into());
20        }
21        let inside: Vec<usize> = (0..keep.len())
22            .filter(|&i| keep[i].kind != Kind::Air && (gr.from..=gr.to).contains(&keep[i].from))
23            .collect();
24        let (Some(&a), Some(&z)) = (inside.first(), inside.last()) else {
25            return Err(format!(
26                "group {label}: no imported lenses or surfaces in surfaces {} to {}",
27                gr.from, gr.to
28            )
29            .into());
30        };
31        if let Some(o) = out.iter().find(|o| a <= o.2 && o.1 <= z) {
32            return Err(format!("group {label} overlaps group {}", groups[o.0].name).into());
33        }
34        out.push((g, a, z));
35    }
36    Ok(out)
37}
38
39pub(crate) fn curv(r: Option<f64>) -> f64 {
40    match r {
41        Some(r) if r != 0.0 && r.is_finite() => 1.0 / r,
42        _ => 0.0,
43    }
44}
45
46/// 面の開口(JSON)を面の開口に。浮動の開口は半径 semi
47pub(crate) fn surf_ap(ap: Option<SurfAperture>, semi: f64) -> Aperture {
48    match ap {
49        None => Aperture::None,
50        Some(SurfAperture::Circular { min, max, dx, dy }) => {
51            Aperture::Circular { min, max, dx, dy }
52        }
53        Some(SurfAperture::Rect { hx, hy, dx, dy }) => Aperture::Rect { hx, hy, dx, dy },
54        Some(SurfAperture::Ellipse { hx, hy, dx, dy }) => Aperture::Ellipse { hx, hy, dx, dy },
55        Some(SurfAperture::Obscuration { min, max, dx, dy }) => Aperture::Obsc { min, max, dx, dy },
56        Some(SurfAperture::Spider {
57            width,
58            arms,
59            dx,
60            dy,
61        }) => Aperture::Spider {
62            width,
63            arms,
64            dx,
65            dy,
66        },
67        Some(SurfAperture::Floating) => Aperture::Floating { semi },
68    }
69}
70
71pub(crate) fn surf(q: &SurfSpec) -> lensbench_core::Result<Surface> {
72    if let Some(r) = &q.row {
73        let alone = SurfSpec {
74            row: None,
75            ..q.clone()
76        };
77        if serde_json::to_value(&alone).ok() != serde_json::to_value(SurfSpec::default()).ok() {
78            return Err("a surface written as row can't have the other keys".into());
79        }
80        if r.stop || r.object || r.image {
81            return Err(
82                "row of a surface can't have stop, object or image (use set_stop of the block)"
83                    .into(),
84            );
85        }
86        return crate::sysfile_v2::read::surface((**r).clone()).map_err(Into::into);
87    }
88    let mut s = Surface {
89        form: match q.shape {
90            SurfShape::Standard if q.asph.iter().any(|a| *a != 0.0) => Form::EvenAsph {
91                asph: q.asph.clone(),
92            },
93            SurfShape::Standard => Form::Standard,
94            SurfShape::OddAsph => Form::OddAsph {
95                asph: q.asph.clone(),
96            },
97            SurfShape::Toroidal => Form::Toroidal {
98                cx: curv(q.radius_x),
99                asph: q.asph.clone(),
100            },
101            SurfShape::Fresnel => Form::Fresnel {
102                asph: q.asph.clone(),
103            },
104        },
105        c: curv(q.radius),
106        k: q.conic,
107        t: q.t,
108        semi: q.semi.value(),
109        semi_auto: q.semi.is_auto(),
110        coat: q.coat.clone(),
111        comment: q.comment.clone(),
112        ignore: q.ignore,
113        ..Default::default()
114    };
115    s.ap = surf_ap(q.aperture, q.semi.value());
116    let special = q.jones.is_some() as u8
117        + q.coordbrk.is_some() as u8
118        + q.polarizer.is_some() as u8
119        + q.waveplate.is_some() as u8
120        + q.birefringent.is_some() as u8;
121    if special > 1 {
122        return Err(
123            "a surface can't have two or more of jones, polarizer, waveplate, coordbrk and birefringent"
124                .into(),
125        );
126    }
127    if let Some(b) = q.birefringent {
128        s.bire = Some(match b {
129            BireSpec::In { mode, axis } => {
130                if mode > 3 {
131                    return Err(format!("birefringent plate mode {mode} (0 to 3)").into());
132                }
133                if !(axis.iter().all(|v| v.is_finite()) && axis.iter().any(|v| *v != 0.0)) {
134                    return Err(
135                        "the crystal axis of the birefringent plate is 0 or not a number".into(),
136                    );
137                }
138                if q.glass.as_deref().is_none_or(is_air_name) {
139                    return Err("write glass (the ordinary material) on the entrance surface of a birefringent plate".into());
140                }
141                lensbench_core::surface::Bire::In {
142                    mode,
143                    axis,
144                    ne: Vec::new(),
145                }
146            }
147            BireSpec::Out => lensbench_core::surface::Bire::Out,
148        });
149    }
150    if special == 1 && q.birefringent.is_none() {
151        let what = if q.jones.is_some() {
152            "jones"
153        } else if q.polarizer.is_some() {
154            "polarizer"
155        } else if q.waveplate.is_some() {
156            "waveplate"
157        } else {
158            "coordbrk"
159        };
160        if curv(q.radius) != 0.0
161            || q.conic != 0.0
162            || s.typ() == SurfType::EvenAsph
163            || q.shape != SurfShape::Standard
164        {
165            return Err(
166                format!("a {what} surface can't have curvature, conic or asphere terms").into(),
167            );
168        }
169        // Jones 面・偏光子・波長板は玉の中(フィルムの中など)にも置ける。座標ブレークは媒質を持たない
170        if what == "coordbrk" && q.glass.as_deref().is_some_and(|g| !is_air_name(g)) {
171            return Err(format!("no glass after a {what} surface").into());
172        }
173    }
174    if let Some(j) = q.jones {
175        s.form = Form::Jones { jones: j };
176    }
177    let ret = match (&q.polarizer, &q.waveplate) {
178        (Some(p), _) => Some(p.retarder()?),
179        (_, Some(w)) => Some(w.retarder()?),
180        _ => None,
181    };
182    if let Some(r) = ret {
183        // jones は設計波長(偏光子は波長によらない)の値。偏光の追跡は波長ごとに retarder から
184        s.form = Form::Jones {
185            jones: r.jones8(r.wl0),
186        };
187        s.retarder = Some(r);
188    }
189    if let Some([tx, ty]) = q.tilt {
190        if q.coordbrk.is_some() {
191            return Err("a coordinate break surface can't have tilt".into());
192        }
193        if !(tx.is_finite() && ty.is_finite()) {
194            return Err("tilt is not a number".into());
195        }
196        if tx != 0.0 || ty != 0.0 {
197            s.before = Some(lensbench_core::surface::Tilt {
198                d: [0.0, 0.0, tx, ty, 0.0],
199                order: 0,
200            });
201            s.after = After::Reverse;
202        }
203    }
204    if let Some(d) = q.coordbrk {
205        if q.order > 1 {
206            return Err(format!("coordinate break order {} (0 or 1)", q.order).into());
207        }
208        s.form = Form::CoordBrk {
209            cb: d,
210            order: q.order,
211        };
212        s.mat = "-".into();
213        return Ok(s);
214    }
215    if let Some(g) = &q.glass {
216        if let Ok(nd) = g.trim().parse::<f64>() {
217            // 数は屈折率だけの媒質(分散なし)
218            s.mat = Material::Index(nd);
219        } else {
220            s.mat = Material::parse(g);
221        }
222    }
223    Ok(s)
224}
225
226pub(crate) fn pick_lens(s: &System, k: usize) -> lensbench_core::Result<Element> {
227    let els = elements::split(s)?;
228    let lenses: Vec<&Element> = els.iter().filter(|e| e.kind == Kind::Lens).collect();
229    match lenses.get(k.wrapping_sub(1)) {
230        Some(e) => Ok((*e).clone()),
231        None => Err(lensbench_core::Error::Invalid(format!(
232            "no lens {k} ({} lenses)",
233            lenses.len()
234        ))),
235    }
236}
237
238/// 展開の選び方([`expand`])
239#[derive(Clone, Copy, Default)]
240pub struct ExpandOpts<'a> {
241    /// 状態(None なら変更なし)
242    pub state: Option<&'a str>,
243    /// ビームスプリッターの経路(BS を通る順の T・R)。None なら状態・プロジェクトの path
244    pub path: Option<&'a str>,
245    /// カタログの玉を使い回す(同じ環境の展開の間だけで共有する)
246    pub cache: Option<&'a SourceCache>,
247    /// 外側で展開中のファイル・項目(取り込んだプロジェクトを展開するとき、循環を見つける)。ふつうは空
248    pub within: &'a [Loading],
249}
250
251/// 展開中のファイル(正規化したパス)と、ユーザーカタログならその項目
252#[derive(Debug, Clone, PartialEq, Eq)]
253pub struct Loading {
254    pub file: PathBuf,
255    pub item: Option<String>,
256}
257
258impl std::fmt::Display for Loading {
259    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
260        match &self.item {
261            Some(it) => write!(f, "{} item {it}", self.file.display()),
262            None => write!(f, "{}", self.file.display()),
263        }
264    }
265}
266
267/// 展開の結果
268#[derive(Debug, Clone)]
269pub struct Expansion {
270    /// 順次の面の列の系
271    pub system: System,
272    /// 展開で落としたもの(取り込んだ範囲の外を参照するピックアップなど)の注意
273    pub notes: Vec<Note>,
274    /// id のある空気のブロックが入る面(差し替え探索の間隔の変数、[`Gap`])
275    pub gaps: Vec<Gap>,
276    /// 系の面ごとの出どころ(`system.surfaces` と同じ長さ。物体面・像面は既定値)
277    pub map: Vec<SurfOrigin>,
278}
279
280/// 展開した系の面 1 つの出どころ([`Expansion::map`])
281#[derive(Debug, Clone, Default, PartialEq)]
282pub struct SurfOrigin {
283    /// 面を足した id のあるブロック・群(内から外へ。.zmx の取り込みの群も)
284    pub blocks: Vec<String>,
285    /// 鏡の `back` で復路にたどった面
286    pub back: bool,
287    /// 裏返して置いた玉(`reversed`)の面なら、その玉の番号(1 始まり、展開の中で数える)
288    pub flip: Option<usize>,
289    /// 枠付きのユーザーカタログの品の面なら、その品の番号([`Ctx::frames`])
290    pub(crate) frame: Option<usize>,
291    /// .zmx の取り込みの番号と、元の .zmx の面番号(ピックアップを付け替える)
292    pub(crate) zmx: Option<(usize, usize)>,
293    /// 面を足した、面の上書き・操作を持つブロック・群([`Ctx::sites`] の番号)
294    pub(crate) mods: Vec<usize>,
295    /// 面を足したプロジェクトの木のいちばん内のブロックと、その中の何番目の面か([`FaceId`]。物体面・像面は None)。
296    /// 状態・経路の違う展開の間で同じ面を探す([`Expansion::find_face`])
297    pub face: Option<FaceId>,
298    /// 展開中だけ: 面を足した木のブロックのアドレス([`Ctx::leaf`])。展開の終わりに face にして 0 に戻す
299    pub(crate) leaf: usize,
300    /// ブロックの偏心・傾き(置き方)の入口・戻りの座標ブレーク(ブロックの面ではない。surface_edits の coordbrk の
301    /// 番号に数えない)
302    pub(crate) placed: bool,
303}
304
305/// プロジェクトのブロックの木の中の位置(上から順の段)
306#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
307pub struct NodePath(pub Vec<NodeStep>);
308
309/// [`NodePath`] の段
310#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
311pub enum NodeStep {
312    /// 並び(最上位・群の中)の i 番目のブロック
313    Block(usize),
314    /// BS の腕(0 透過 t・1 反射 r・2 d)の i 番目のブロック
315    Arm(u8, usize),
316}
317
318/// 展開した系の面の、プロジェクトの中での名前([`SurfOrigin::face`])。ブロックの木が同じなら、状態・BS の経路が違う
319/// 展開でも同じ面は同じ名前になる
320#[derive(Debug, Clone, PartialEq, Eq, Hash)]
321pub struct FaceId {
322    /// 面を足したいちばん内のブロック(ユーザーカタログの品は品のブロック、BS の腕の中は BS)
323    pub node: NodePath,
324    /// 鏡の `back` で復路にたどった面
325    pub back: bool,
326    /// そのブロックを同じ向きで何回目にたどった範囲か(0 始まり)
327    pub pass: usize,
328    /// 座標ブレーク(偏心・傾き・折り曲げの座標の面)か
329    pub cb: bool,
330    /// 範囲の中の番号(0 始まり、たどった順)。座標ブレークとほかの面は別に数える(偏心の有無が状態で変わっても、
331    /// ほかの面の番号はずれない)
332    pub index: usize,
333}
334
335/// ブロックの木のブロック(アドレス)ごとの位置
336pub(crate) fn node_paths(blocks: &[Block]) -> HashMap<usize, NodePath> {
337    fn walk(
338        v: &[Block],
339        pre: &mut Vec<NodeStep>,
340        arm: Option<u8>,
341        out: &mut HashMap<usize, NodePath>,
342    ) {
343        for (i, b) in v.iter().enumerate() {
344            pre.push(match arm {
345                Some(a) => NodeStep::Arm(a, i),
346                None => NodeStep::Block(i),
347            });
348            out.insert(b as *const Block as usize, NodePath(pre.clone()));
349            match b {
350                Block::Group { blocks, .. } => walk(blocks, pre, None, out),
351                Block::Splitter { spec, .. } => {
352                    for (a, l) in [&spec.t, &spec.r, &spec.d].into_iter().enumerate() {
353                        walk(l, pre, Some(a as u8), out);
354                    }
355                }
356                _ => {}
357            }
358            pre.pop();
359        }
360    }
361    let mut out = HashMap::new();
362    walk(blocks, &mut Vec::new(), None, &mut out);
363    out
364}
365
366/// 展開中に覚えた木のブロックのアドレス([`SurfOrigin::leaf`])を、面の名前 [`FaceId`] にする
367fn name_faces(map: &mut [SurfOrigin], sf: &[Surface], nodes: &HashMap<usize, NodePath>) {
368    // (ブロック, 向き) ごとのたどった範囲の数
369    let mut passes: HashMap<(usize, bool), usize> = HashMap::new();
370    let mut prev: Option<(usize, bool)> = None;
371    // 範囲の中の面・座標ブレークの数
372    let mut k = [0usize; 2];
373    for (j, o) in map.iter_mut().enumerate() {
374        let leaf = std::mem::take(&mut o.leaf);
375        let Some(node) = nodes.get(&leaf) else {
376            prev = None;
377            continue;
378        };
379        let key = (leaf, o.back);
380        let n = passes.entry(key).or_insert(0);
381        if prev != Some(key) {
382            *n += 1;
383            k = [0, 0];
384        }
385        let cb = sf[j].is_coord_break();
386        o.face = Some(FaceId {
387            node: node.clone(),
388            back: o.back,
389            pass: *n - 1,
390            cb,
391            index: k[cb as usize],
392        });
393        k[cb as usize] += 1;
394        prev = Some(key);
395    }
396}
397
398impl Expansion {
399    /// 面の名前が id の面([`SurfOrigin::face`])。無ければ None
400    pub fn find_face(&self, id: &FaceId) -> Option<usize> {
401        self.map.iter().position(|o| o.face.as_ref() == Some(id))
402    }
403}
404
405impl SurfOrigin {
406    /// 面が id のブロック・群のものか
407    pub fn is_in(&self, id: &str) -> bool {
408        self.blocks.iter().any(|b| b == id)
409    }
410}
411
412/// id のあるブロック・群 1 つの系の面の範囲([`Expansion::block_spans`])
413#[derive(Debug, Clone, Default, PartialEq, serde::Serialize)]
414pub struct BlockSpans {
415    pub id: String,
416    /// 往路の範囲(系の面の番号 [最初, 最後]、たどった順)
417    pub forward: Vec<[usize; 2]>,
418    /// 鏡の `back` で復路にたどった範囲
419    #[serde(skip_serializing_if = "Vec::is_empty")]
420    pub back: Vec<[usize; 2]>,
421}
422
423/// id のあるブロック・群(BS・開口・絞り・群も。面を足さない空気は出ない)ごとの系の面の範囲。並びは最初の面の順
424pub fn block_spans(map: &[SurfOrigin]) -> Vec<BlockSpans> {
425    let mut ids: Vec<&str> = Vec::new();
426    for o in map {
427        // 内から外への並びを、外(群)が先に出るように逆にたどる
428        for b in o.blocks.iter().rev() {
429            if !ids.contains(&b.as_str()) {
430                ids.push(b);
431            }
432        }
433    }
434    ids.into_iter()
435        .map(|id| BlockSpans {
436            id: id.to_string(),
437            forward: block_runs(map, id, Some(false)),
438            back: block_runs(map, id, Some(true)),
439        })
440        .collect()
441}
442
443impl Expansion {
444    /// [`block_spans`]
445    pub fn block_spans(&self) -> Vec<BlockSpans> {
446        block_spans(&self.map)
447    }
448}
449
450/// id のブロック・群の面の範囲(系の面の番号 [最初, 最後])。続けて同じ向きにたどった範囲ごとに、たどった順。
451/// back が Some なら往路(false)か復路(true)の範囲だけ
452pub fn block_runs(map: &[SurfOrigin], id: &str, back: Option<bool>) -> Vec<[usize; 2]> {
453    if id.is_empty() {
454        return Vec::new();
455    }
456    runs_where(map, |o| o.is_in(id), back)
457}
458
459/// [`block_runs`] と同じ。面が入るかを f で決める
460pub(crate) fn runs_where(
461    map: &[SurfOrigin],
462    f: impl Fn(&SurfOrigin) -> bool,
463    back: Option<bool>,
464) -> Vec<[usize; 2]> {
465    let mut out: Vec<[usize; 2]> = Vec::new();
466    let mut prev: Option<(usize, bool)> = None;
467    for (j, o) in map.iter().enumerate() {
468        if !f(o) {
469            prev = None;
470            continue;
471        }
472        match (prev, out.last_mut()) {
473            (Some((pj, pb)), Some(r)) if pj + 1 == j && pb == o.back => r[1] = j,
474            _ => out.push([j, j]),
475        }
476        prev = Some((j, o.back));
477    }
478    out.retain(|r| back.is_none_or(|b| map[r[0]].back == b));
479    out
480}
481
482/// id のブロック・群の往路の最初の範囲
483pub(crate) fn fwd_run(map: &[SurfOrigin], id: &str) -> Option<[usize; 2]> {
484    block_runs(map, id, Some(false)).into_iter().next()
485}
486
487/// id のある空気のブロックが入る面: (id, 面番号, 向き)。向きは鏡の後(光が −z へ進む)で −1(面の厚さは −t)。
488/// 往復で 2 回通る空気は 2 つ並ぶ。面の厚さには、同じ面に入る他の空気・群の移動も足されている
489pub type Gap = (String, usize, f64);
490
491/// プロジェクトを順次の面の列の系に展開する。誤りはブロックの中で起きたらその位置を持つ([`ExpandError`]。
492/// `?` で [`lensbench_core::Error`] に直すとブロックの名前が文の前に付く)
493pub fn expand(p: &Project, env: &Env, o: &ExpandOpts) -> Result<Expansion, ExpandError> {
494    let with;
495    let p = match o.state {
496        Some(n) => {
497            with = p.with_state_and_path(n, o.path.is_some())?;
498            &with
499        }
500        None => p,
501    };
502    match expand_inner(
503        p,
504        env,
505        o.path.or(p.path.as_deref()),
506        false,
507        o.cache,
508        o.within,
509    )? {
510        Walk::Done(x) => Ok(*x),
511        _ => Err(lensbench_core::Error::from(
512            "internal error: the BS path is short outside the path search",
513        )
514        .into()),
515    }
516}
517
518/// BS の id を集める(重なりを調べる)
519pub(crate) fn splitter_ids<'x>(v: &'x [Block], out: &mut Vec<&'x str>) {
520    for b in v {
521        match b {
522            Block::Splitter { id, spec, .. } => {
523                out.push(id);
524                for l in [&spec.t, &spec.r, &spec.d] {
525                    splitter_ids(l, out);
526                }
527            }
528            Block::Group { blocks, .. } => splitter_ids(blocks, out),
529            _ => {}
530        }
531    }
532}
533
534/// 展開の行き着いた先
535pub(crate) enum Walk {
536    /// 経路の文字が足りない(経路を探すときだけ)
537    Need,
538    /// 経路を探すとき: ブロックを終わりまでたどれた(系は組まない)
539    Walked,
540    Done(Box<Expansion>),
541}
542
543/// 展開の本体。search(経路を探す)なら、経路の文字が足りなければ [`Walk::Need`]、ブロックを終わりまで
544/// たどれたら系を組まずに [`Walk::Walked`]
545pub(crate) fn expand_inner(
546    p: &Project,
547    env: &Env,
548    path: Option<&str>,
549    search: bool,
550    cache: Option<&SourceCache>,
551    within: &[Loading],
552) -> Result<Walk, ExpandError> {
553    let mut failed = None;
554    expand_body(p, env, path, search, cache, within, &mut failed).map_err(|error| ExpandError {
555        error,
556        block: failed.map(|n| BlockAt::new(&p.blocks, n)),
557    })
558}
559
560fn expand_body(
561    p: &Project,
562    env: &Env,
563    path: Option<&str>,
564    search: bool,
565    cache: Option<&SourceCache>,
566    within: &[Loading],
567    failed: &mut Option<NodePath>,
568) -> lensbench_core::Result<Walk> {
569    {
570        let mut ids = Vec::new();
571        splitter_ids(&p.blocks, &mut ids);
572        for (i, id) in ids.iter().enumerate() {
573            if id.is_empty() {
574                return Err("a BS (splitter) needs an id".into());
575            }
576            if ids[..i].contains(id) {
577                return Err(format!("BS id {id} appears twice or more").into());
578            }
579        }
580    }
581    if p.wavelengths.is_empty() {
582        return Err("no wavelengths".into());
583    }
584    if p.primary == 0 || p.primary > p.wavelengths.len() {
585        return Err(format!(
586            "primary wavelength {} (there are {} wavelengths)",
587            p.primary,
588            p.wavelengths.len()
589        )
590        .into());
591    }
592    let mut dirs = env.glass_dirs.clone();
593    crate::model::zmx_dirs(&p.blocks, &env.base, &mut dirs);
594    let dirs = glass::catalog_dirs(&dirs);
595    let (glasses, missing) = glass::load_catalogs_shared(&p.glass_catalogs, &dirs);
596    if !missing.is_empty() {
597        return Err(lensbench_core::Error::Invalid(format!(
598            "glass catalog not found: {}. Pass catalog folders with --glass-dir (CLI), glass_dirs (serve, Python) or LENSBENCH_GLASSCAT",
599            missing.join(", ")
600        ))
601        .with_code(code::GLASS_NOT_FOUND));
602    }
603    // 面の上書き・操作を持つブロックに番号を付けた写し(無ければそのまま)
604    let keyed;
605    let p = match number_sites(p) {
606        Some(q) => {
607            keyed = q;
608            &keyed
609        }
610        None => p,
611    };
612    let mut sites = Vec::new();
613    face_sites(&p.blocks, &mut sites);
614    let mut c = Ctx {
615        env,
616        cache,
617        base: env.base.clone(),
618        loading: within.to_vec(),
619        outer: within.len(),
620        sf: Vec::new(),
621        map: Vec::new(),
622        noted: Vec::new(),
623        nflip: 0,
624        flip_err: None,
625        zpicks: Vec::new(),
626        lead: 0.0,
627        parity: 1.0,
628        glasses,
629        coats: HashMap::new(),
630        nstop: 0,
631        gaps: Vec::new(),
632        split: SplitState {
633            path: splitter::parse_path(path.unwrap_or(""))?,
634            strict: search,
635            ..Default::default()
636        },
637        turn: TurnState::new(p),
638        media: HashMap::new(),
639        frames: Vec::new(),
640        zenv: Vec::new(),
641        nodes: node_paths(&p.blocks),
642        leaf: Vec::new(),
643        failed: None,
644        notes: Vec::new(),
645    };
646    for (i, b) in p.blocks.iter().enumerate() {
647        if c.split.done {
648            break;
649        }
650        // 検出器(最後のブロック)は面を足さない。像面に置く
651        if matches!(b, Block::Detector(_)) && i + 1 == p.blocks.len() {
652            continue;
653        }
654        match c.block(b, &p.blocks, i) {
655            // 経路の文字が足りない(経路を探すとき。paths が次の文字を試す)
656            Err(_) if c.split.need => return Ok(Walk::Need),
657            Err(e) => {
658                *failed = c.failed.take();
659                return Err(e);
660            }
661            Ok(()) => {}
662        }
663        if let Some(e) = c.flip_err.take() {
664            return Err(e);
665        }
666    }
667    if let Some(t) = c.turn.at.as_ref().filter(|_| c.turn.turned.is_empty()) {
668        return Err(format!(
669            "turn: block {} (pass {}) is not on the path",
670            t.block, t.pass
671        )
672        .into());
673    }
674    if c.split.pos < c.split.path.len() {
675        return Err(format!(
676            "path {}: too many letters (the BS is passed {} times)",
677            path.unwrap_or(""),
678            c.split.pos
679        )
680        .into());
681    }
682    // 絞りを面に置く操作(surface_ops の set_stop)があれば、ブロックの絞りは無くてよい
683    let stop_op = sites.iter().any(|(_, f)| {
684        f.surface_ops
685            .iter()
686            .any(|o| matches!(o, SurfaceOp::SetStop(_)))
687    });
688    if c.nstop > 1 || (c.nstop == 0 && !stop_op) {
689        return Err(format!("{} stops (exactly one is needed)", c.nstop).into());
690    }
691    if search {
692        return Ok(Walk::Walked);
693    }
694    if c.nstop == 0 {
695        // 仮の絞り(set_stop で移す)
696        if let Some(f) = c.sf.first_mut() {
697            f.stop = true;
698        }
699    }
700    let wl: Vec<f64> = p.wavelengths.iter().map(|w| w.um).collect();
701    let wt: Vec<f64> = p.wavelengths.iter().map(|w| w.weight).collect();
702    let mut obj = crate::zmx_links::object_surface(p.object.as_deref())?;
703    obj.t = p.object_distance.unwrap_or(f64::INFINITY);
704    let mut sf = vec![obj];
705    if p.object_distance.is_some() {
706        sf[0].t += c.lead;
707    }
708    if c.sf.len() != c.map.len() {
709        // 面は put か element_from で足す(出どころの表を面と揃える)
710        return Err(format!(
711            "internal error: {} surfaces but {} sources",
712            c.sf.len(),
713            c.map.len()
714        )
715        .into());
716    }
717    sf.append(&mut c.sf);
718    let org: Vec<Option<(usize, usize)>> = c.map.iter().map(|o| o.zmx).collect();
719    // 系の面ごとの出どころ(物体面・像面はブロックの外)
720    let mut map = vec![SurfOrigin::default()];
721    map.append(&mut c.map);
722    map.push(SurfOrigin::default());
723    let zpicks = std::mem::take(&mut c.zpicks);
724    sf.push(match &p.image {
725        None => Surface::default(),
726        Some(r) => {
727            if r.stop
728                || r.object
729                || r.t != 0.0
730                || r.medium.is_some()
731                || r.coordinate_break.is_some()
732            {
733                return Err(
734                    "image: stop, object, t, medium and coordinate_break can't be written".into(),
735                );
736            }
737            let mut r = (**r).clone();
738            r.image = false;
739            crate::sysfile_v2::read::surface(r).map_err(|e| format!("image: {e}"))?
740        }
741    });
742    name_faces(&mut map, &sf, &c.nodes);
743    // 面の後の媒質が決まるか(屈折率は系を作るときに解く。GRIN の面の材料名は分布の名前でガラスではない)
744    let envr = p.environment;
745    // 名前@カタログ のガラス(同じ名前の別のガラスと分けた名前)は、そのカタログから引く
746    let named: Vec<String> = sf
747        .iter()
748        .filter_map(|d| {
749            d.mat
750                .glass()
751                .filter(|g| g.contains('@'))
752                .map(str::to_string)
753        })
754        .filter(|g| !c.glasses.contains_key(g))
755        .collect();
756    if !named.is_empty() {
757        let t = std::sync::Arc::make_mut(&mut c.glasses);
758        glass::resolve_qualified(t, named.iter().map(String::as_str), &dirs);
759    }
760    for (j, d) in sf.iter_mut().enumerate() {
761        let known = (j > 0 && (d.is_mirror() || d.is_coord_break()))
762            || is_air(&d.mat)
763            || d.mat.glass().is_some_and(|g| c.glasses.contains_key(g))
764            || matches!(d.mat, Material::Index(_) | Material::Model { .. })
765            || d.grin().is_some();
766        if !known {
767            return Err(glass_missing(j, &d.mat.name()));
768        }
769        // 複屈折材の板の入口: 異常光の屈折率
770        if let Some(lensbench_core::surface::Bire::In { ne, .. }) = d.bire.as_mut() {
771            let en = lensbench_core::surface::Bire::e_name(&d.mat.name());
772            let g = c.glasses.get(&en).ok_or_else(|| {
773                format!(
774                    "surface {j}: extraordinary glass {en} of birefringent material {} is not in the catalogs",
775                    d.mat
776                )
777            })?;
778            *ne = wl
779                .iter()
780                .map(|&l| g.index(l, envr.temperature_c, envr.pressure_atm, envr.adjust_index))
781                .collect();
782        }
783        // 複屈折材の波長板: 板のガラスを引き、設計波長の行列を作り直す
784        if let Some(r) = d.retarder.as_mut().filter(|r| !r.plates.is_empty()) {
785            r.resolve(&c.glasses)
786                .map_err(|e| format!("surface {j}: {e}"))?;
787            let m = r.jones8(r.wl0);
788            if let Some(j) = d.jones_mut() {
789                *j = m;
790            }
791        }
792        // 屈折面での反射(ビームスプリッター): 反対側の媒質の屈折率
793        if let Some(r) = &mut d.reflect {
794            r.n = if is_air_name(&r.mat) {
795                vec![1.0; wl.len()]
796            } else if let Some(g) = c.glasses.get(r.mat.trim()) {
797                wl.iter()
798                    .map(|&l| g.index(l, envr.temperature_c, envr.pressure_atm, envr.adjust_index))
799                    .collect()
800            } else if matches!(
801                Material::parse(&r.mat),
802                Material::Index(_) | Material::Model { .. }
803            ) {
804                Vec::new() // 光束の turn の反対側の媒質(組んだ後で入れる)
805            } else {
806                return Err(format!("surface {j}: glass {} is not in the catalogs", r.mat).into());
807            };
808        }
809    }
810    // 条件で定める視野の面の名前は展開した後で引く
811    let ft = p.fields.kind.plain().unwrap_or(FieldType::Angle);
812    if p.fields.vignetting.len() > p.fields.points.len() {
813        return Err(format!(
814            "fields: {} vignetting rows for {} fields",
815            p.fields.vignetting.len(),
816            p.fields.points.len()
817        )
818        .into());
819    }
820    let fields: Vec<Field> = p
821        .fields
822        .points
823        .iter()
824        .enumerate()
825        .map(|(i, q)| {
826            let mut f = Field::xy(q[0], q[1]);
827            f.w = p.fields.weights.get(i).copied().unwrap_or(1.0);
828            if let Some(&[vdx, vdy, vcx, vcy, van]) = p.fields.vignetting.get(i) {
829                (f.vdx, f.vdy, f.vcx, f.vcy, f.van) = (vdx, vdy, vcx, vcy, van);
830            }
831            f
832        })
833        .collect();
834    let mut s = System::new(
835        sf,
836        wl,
837        wt,
838        p.primary - 1,
839        fields,
840        ft,
841        p.fields.norm,
842        (p.aperture.kind, p.aperture.value),
843        p.telecentric,
844        p.aiming,
845        c.glasses,
846    )?
847    .into_prescription();
848    s.name = p.name.clone();
849    // プロジェクトのマクロは系のマクロの先頭(ソルブの番号がそのまま。取り込んだ .zmx のマクロはその後ろに足す)
850    s.macros = crate::zmx_links::project_macros(&p.macros)?;
851    // 同梱のカタログ(屈折率だけ)から取ったガラスを知らせる
852    let b = glass::builtin::note_for(&s, &p.glass_catalogs, &dirs);
853    s.import_notes.extend(b);
854    s.import_notes.extend(std::mem::take(&mut c.notes));
855    s.temperature = envr.temperature_c;
856    s.pressure = envr.pressure_atm;
857    s.adjust_index = envr.adjust_index;
858    s.floating_clip = p.floating_clip;
859    s.mech_clip = p.mech_clip;
860    s.apodization = p.apodization;
861    s.ropd = p.ropd;
862    (s.aim_pupil, s.input_pol, s.glass_template) = (p.aim_pupil, p.input_pol, p.glass_template);
863    if let Some(v) = p.vig_interp {
864        s.vig_interp = v;
865    }
866    // 膜: プロジェクトの coatings はカタログの同じ名前より優先
867    s.coat_tables = c.coats;
868    for (k, spec) in &p.coatings {
869        let t = spec.table().map_err(|e| format!("coating {k}: {e}"))?;
870        s.coat_tables.insert(k.clone(), t);
871    }
872    if let Some(u) = &p.afocal {
873        s.afocal = true;
874        s.afocal_unit = AfocalUnit::from_code(u)
875            .ok_or_else(|| format!("afocal unit {u} (ur, mr, rr, as, am or dg)"))?;
876    }
877    if p.fields.kind == FieldKind::Solve {
878        let Some(c) = &p.fields.solve else {
879            return Err("when the fields type is solve, write the condition in solve".into());
880        };
881        let f = |t: &str| {
882            s.find_surface(t)
883                .map_err(|e| format!("field condition: {e}"))
884        };
885        let cond = match c {
886            FieldSolveSpec::Position { surface } => FieldCond::Position { surf: f(surface)? },
887            FieldSolveSpec::DirSum { s1, s2 } => FieldCond::DirSum {
888                s1: f(s1)?,
889                s2: f(s2)?,
890            },
891            FieldSolveSpec::DirDiff { s1, s2 } => FieldCond::DirDiff {
892                s1: f(s1)?,
893                s2: f(s2)?,
894            },
895        };
896        s.field_type = FieldType::Solve(cond);
897    } else if p.fields.solve.is_some() {
898        return Err("fields solve only with type solve".into());
899    }
900    let mut s = s.build_raw()?;
901    fill_turned(&mut s, &c.turn.turned)?;
902    let (picks, medium) = keep_pickups(&mut s, &org, &zpicks)?;
903    let mut warn = Note::all(NoteKind::Pickup, None, picks);
904    warn.extend(Note::all(NoteKind::Medium, None, medium));
905    for (path, t, pr, adj, _) in &c.zenv {
906        let e = &p.environment;
907        // どちらも補正しないなら温度・気圧は屈折率に効かない
908        if !*adj && !e.adjust_index {
909            continue;
910        }
911        // 屈折率の補正は 20 °C・1 atm の外でだけ効く
912        let off_ref = e.temperature_c != 20.0 || e.pressure_atm != 1.0;
913        if (t - e.temperature_c).abs() > 1e-9
914            || (pr - e.pressure_atm).abs() > 1e-9
915            || (off_ref && *adj != e.adjust_index)
916        {
917            warn.push(Note::new(NoteKind::Environment, None, format!(
918                "{path}: the .zmx environment ({t} °C, {pr} atm) differs from the project environment ({} °C, {} atm); indices are computed in the project environment (change it with environment)",
919                e.temperature_c, e.pressure_atm
920            )));
921        }
922    }
923    // 玉・群のパラメータ: 玉モードの玉 lens1 … と、id のあるブロック・群(同じ id の範囲は 1 つの玉・群)
924    let mut rx = s.prescription().clone();
925    rx.units = s.lens_units();
926    // 取り込んだ .zmx の膜ファイル(面の膜の名前はそのファイルで引く)。違うファイルの .zmx が 2 つ以上なら最初のもの
927    crate::zmx_links::carry_notes(&mut rx, &zpicks);
928    crate::zmx_links::coating_file(
929        &mut rx,
930        &c.zenv,
931        p.coating_file.as_deref(),
932        &env.base,
933        &env.glass_dirs,
934        &mut warn,
935    );
936    let mut s = rx.build_raw()?;
937    for id in &c.noted {
938        let id = id.as_str();
939        let spans = block_runs(&map, id, None);
940        match s.define_unit(id, &spans, [0.0; 3]) {
941            // 群の移動はもう厚さに入っているので、その分を玉・群の shift の今の値にする(状態ごとの群の位置を
942            // `id.shift` で比べられるように)
943            Ok(u) => {
944                let shift = group_shift(&p.blocks, id).unwrap_or(0.0);
945                s.edit_raw(|rx| {
946                    rx.units[u].shift = shift;
947                    Ok(())
948                })?
949            }
950            Err(e) => warn.push(Note::new(
951                NoteKind::Unit,
952                Some(id.to_string()),
953                format!("block {id} is not made a lens or group parameter: {e}"),
954            )),
955        }
956    }
957    // 裏返して置いた玉(id の無い玉の lens1 … も): 最初の範囲の面(偏心・傾きの座標ブレークを除く)が、ちょうど
958    // 1 つの裏返した玉の面すべて(前は座標ブレークを含めて範囲を比べたので、偏心した玉は立たなかった)
959    let flipped = |s: &System, r: &[usize; 2]| -> bool {
960        let faces: Vec<usize> = (r[0]..=r[1].min(map.len() - 1))
961            .filter(|&j| !s.surfaces[j].is_coord_break())
962            .collect();
963        let Some(k) = faces.first().and_then(|&j| map[j].flip) else {
964            return false;
965        };
966        faces.iter().all(|&j| map[j].flip == Some(k))
967            && map.iter().filter(|o| o.flip == Some(k)).count() == faces.len()
968    };
969    let marks: Vec<bool> = s
970        .units
971        .iter()
972        .map(|u| u.spans.first().is_some_and(|r| flipped(&s, r)))
973        .collect();
974    s.edit_raw(|rx| {
975        for (u, f) in rx.units.iter_mut().zip(marks) {
976            u.flipped = f;
977        }
978        Ok(())
979    })?;
980    apply_surface_edits(&mut s, &sites, &map)?;
981    let (w, stopped) = apply_surface_ops(&mut s, &sites, &map)?;
982    if c.nstop == 0 && !stopped {
983        // 仮の絞りのまま(set_stop のブロックが無い)にはしない
984        return Err("0 stops (no set_stop block in surface_ops; exactly one is needed)".into());
985    }
986    warn.extend(w);
987    if let Some(r) = &p.glrs {
988        let g = match r {
989            BlockRef::Sys(r) => Some(edit_ops::surf_of(&s, r, "glrs")?),
990            BlockRef::Block(f) => {
991                let j = block_face_of(&s, f, &map).map_err(|x| format!("glrs: {x}"))?;
992                if j.is_none() {
993                    warn.push(Note::new(
994                        NoteKind::Glrs,
995                        Some(f.block.clone()),
996                        format!(
997                            "glrs: block {} not found, so the global reference stays at surface {}",
998                            f.block, s.glrs
999                        ),
1000                    ));
1001                }
1002                j
1003            }
1004        };
1005        if let Some(g) = g {
1006            s.edit_raw(|rx| {
1007                rx.glrs = g;
1008                Ok(())
1009            })?;
1010            // ZPL マクロは大域座標(RAGX など)を読めるので、基準の面を決めてから解き直す
1011            if !s.macros.is_empty() {
1012                s.resolve_links()?;
1013            }
1014        }
1015    }
1016    crate::lens_edge::lens_edge_apertures(&mut s)?;
1017    // 自動の半直径を光線から求める。機構部品の検査・描画・書き出しが使う
1018    s.update_semi();
1019    let mut mw = Vec::new();
1020    let mut mech = place_mechanics(&s, &p.mechanics, env, &map, &mut mw)?;
1021    mech.extend(place_frames(&s, &c.frames, &map, &mut mw));
1022    warn.extend(Note::all(NoteKind::Mechanics, None, mw));
1023    s.edit_raw(|rx| {
1024        rx.mechanics = mech;
1025        Ok(())
1026    })?;
1027    warn.extend(crate::expand_error::in_medium_notes(&s, &map));
1028    s.validate()?;
1029    Ok(Walk::Done(Box::new(Expansion {
1030        system: s,
1031        notes: warn,
1032        gaps: c.gaps,
1033        map,
1034    })))
1035}
1036
1037/// 機構部品を系の面に置く([`Project::mechanics`])。ブロックが無い(状態で外したなど)部品は置かずに注意を出す
1038pub(crate) fn place_mechanics(
1039    s: &System,
1040    ms: &[MechPlacement],
1041    env: &Env<'_>,
1042    map: &[SurfOrigin],
1043    warn: &mut Vec<String>,
1044) -> lensbench_core::Result<Vec<lensbench_core::mech::MechPart>> {
1045    let mut out = Vec::new();
1046    // 置いた部品の寸法(after でねじを見る)
1047    let mut specs: Vec<MechSpec> = Vec::new();
1048    for (k, m) in ms.iter().enumerate() {
1049        let tag = format!("mechanics {}", k + 1);
1050        // 取ってキャッシュにある品の STEP(詳しい形の描画に使う)
1051        let mut step_file = String::new();
1052        let (spec, item_name) = match (&m.mech, &m.catalog, &m.item) {
1053            (Some(x), None, None) => (x.clone(), String::new()),
1054            (None, Some(cat), Some(item)) => {
1055                let path = env.base.join(cat);
1056                let c = UserCatalog::load_shared(&path)?;
1057                let it = c
1058                    .items
1059                    .get(item)
1060                    .ok_or_else(|| format!("{tag}: no item {item} in {}", path.display()))?;
1061                let x = it.mech().cloned().ok_or_else(|| {
1062                    format!("{tag}: item {item} is not a mechanical part (no mech)")
1063                })?;
1064                // URL の無い品も、共有の置き場から取ってあればキャッシュにある(引き方は呼ぶ側が渡す)
1065                if let Some(f) = env.step_files.and_then(|look| look(item, &it.cad.step)) {
1066                    step_file = f.display().to_string();
1067                }
1068                (x, item.clone())
1069            }
1070            _ => {
1071                return Err(format!(
1072                    "{tag}: write a part with mech, or with catalog and item, not both"
1073                )
1074                .into())
1075            }
1076        };
1077        spec.validate().map_err(|e| format!("{tag}: {e}"))?;
1078        // 裏返す(z の大きい端から光が入る)。座に合わせるなら、座は保持する素子の後ろの面に当たる
1079        let spec = if m.reversed {
1080            let t = if m.seat {
1081                m.holds
1082                    .first()
1083                    .and_then(|b| fwd_run(map, b))
1084                    .map_or(0.0, |x| {
1085                        (x[0]..x[1])
1086                            .filter(|&j| j < s.surfaces.len() && !s.surfaces[j].is_coord_break())
1087                            .map(|j| s.surfaces[j].t)
1088                            .sum::<f64>()
1089                    })
1090            } else {
1091                0.0
1092            };
1093            spec.flipped(t)
1094        } else {
1095            spec
1096        };
1097        let name = if !m.name.is_empty() {
1098            m.name.clone()
1099        } else if !item_name.is_empty() {
1100            item_name.clone()
1101        } else {
1102            format!("mech{}", k + 1)
1103        };
1104        // 前の部品の後ろの端につなぐ
1105        if let Some(prev_name) = &m.after {
1106            if m.seat || !m.at.is_unset() {
1107                return Err(format!("{tag}: after can't be used with at or seat").into());
1108            }
1109            if m.tilt != [0.0, 0.0] {
1110                return Err(format!(
1111                    "{tag}: tilt can't be used with after (it takes the previous part's tilt)"
1112                )
1113                .into());
1114            }
1115            let Some((prev, prev_spec)) = out
1116                .iter()
1117                .zip(&specs)
1118                .rev()
1119                .find(|(p, _): &(&lensbench_core::mech::MechPart, _)| &p.name == prev_name)
1120            else {
1121                return Err(format!("{tag}: the after part {prev_name} is not before it").into());
1122            };
1123            let (prev, prev_spec): (&lensbench_core::mech::MechPart, &MechSpec) = (prev, prev_spec);
1124            let overlap = match (&prev_spec.back_thread, &spec.front_thread) {
1125                (Some(a), Some(b)) => {
1126                    if a.thread != b.thread || a.male == b.male {
1127                        let kind = |t: &ThreadEnd| {
1128                            if t.male {
1129                                format!("{} male", t.thread)
1130                            } else {
1131                                format!("{} female", t.thread)
1132                            }
1133                        };
1134                        warn.push(format!(
1135                            "{tag}: the threads of the back end of {prev_name} ({why}) and the front end of {name} ({hint}) don't match",
1136                            why = kind(a),
1137                            hint = kind(b)
1138                        ));
1139                        0.0
1140                    } else if b.male {
1141                        b.length + a.recess
1142                    } else {
1143                        a.length + b.recess
1144                    }
1145                }
1146                _ => 0.0,
1147            };
1148            let mut part0 = spec.part(&name, prev.surface, [0.0; 3], prev.tilt);
1149            let z = prev.z_range()[1] - overlap - part0.z_range()[0];
1150            let r = lensbench_core::math::mm(
1151                &lensbench_core::math::rot(0, prev.tilt[0]),
1152                &lensbench_core::math::rot(1, prev.tilt[1]),
1153            );
1154            let d = lensbench_core::math::mv(&r, [m.offset[0], m.offset[1], m.offset[2] + z]);
1155            part0.offset = [
1156                prev.offset[0] + d[0],
1157                prev.offset[1] + d[1],
1158                prev.offset[2] + d[2],
1159            ];
1160            if !part0.offset.iter().all(|v| v.is_finite()) {
1161                return Err(format!("{tag}: offset is not a number").into());
1162            }
1163            for b in &m.holds {
1164                match fwd_run(map, b) {
1165                    Some(x) => part0
1166                        .holds
1167                        .extend((x[0]..=x[1]).filter(|&j| !s.surfaces[j].is_coord_break())),
1168                    None => warn.push(format!("{tag}: no block {b} for holds")),
1169                }
1170            }
1171            part0.step = step_file;
1172            part0.step_flip = m.reversed;
1173            out.push(part0);
1174            specs.push(spec);
1175            continue;
1176        }
1177        let mut offset = m.offset;
1178        // 座に合わせる: 保持する最初の素子の前面に、部品の座の z を合わせる
1179        let seat_at = if m.seat {
1180            let seat = spec
1181                .holds
1182                .ok_or_else(|| {
1183                    format!("{tag}: seat needs holds (the seat position) in the part size")
1184                })?
1185                .seat_z;
1186            let b = m
1187                .holds
1188                .first()
1189                .ok_or_else(|| format!("{tag}: seat needs holds (the held element)"))?;
1190            offset[2] -= seat;
1191            match block_face(s, b, 0, map).map_err(|e| format!("{tag}: {e}"))? {
1192                Some(j) => Some(j),
1193                None => {
1194                    warn.push(format!("{tag}: no block {b}, not placed"));
1195                    continue;
1196                }
1197            }
1198        } else {
1199            None
1200        };
1201        let surface = match (seat_at, &m.at.block) {
1202            (Some(j), _) => j,
1203            (None, block) => match block {
1204                Some(b) => {
1205                    match block_face(s, b, m.at.surface, map).map_err(|e| format!("{tag}: {e}"))? {
1206                        Some(j) => j,
1207                        None => {
1208                            warn.push(format!("{tag}: no block {b}, not placed"));
1209                            continue;
1210                        }
1211                    }
1212                }
1213                None => {
1214                    if m.at.is_unset() {
1215                        return Err(format!("{tag}: a place (at) or seat is needed").into());
1216                    }
1217                    if m.at.surface == 0 || m.at.surface > s.image() {
1218                        return Err(format!(
1219                            "{tag}: surface {} (1 to {})",
1220                            m.at.surface,
1221                            s.image()
1222                        )
1223                        .into());
1224                    }
1225                    m.at.surface
1226                }
1227            },
1228        };
1229        if !offset.iter().chain(&m.tilt).all(|v| v.is_finite()) {
1230            return Err(format!("{tag}: offset or tilt is not a number").into());
1231        }
1232        let mut part = spec.part(&name, surface, offset, m.tilt);
1233        for b in &m.holds {
1234            match fwd_run(map, b) {
1235                Some(x) => part
1236                    .holds
1237                    .extend((x[0]..=x[1]).filter(|&j| !s.surfaces[j].is_coord_break())),
1238                None => warn.push(format!("{tag}: no block {b} for holds")),
1239            }
1240        }
1241        part.step = step_file;
1242        part.step_flip = m.reversed;
1243        out.push(part);
1244        specs.push(spec);
1245    }
1246    Ok(out)
1247}
1248
1249/// 枠付きのユーザーカタログの品の枠を、ガラスの最初の面に置く(枠の座 `holds.seat_z` をガラスの前面に合わせる)。
1250/// 保持する素子はその品の面(map で品の番号を持つ面)
1251pub(crate) fn place_frames(
1252    s: &System,
1253    frames: &[(String, MechSpec)],
1254    map: &[SurfOrigin],
1255    warn: &mut Vec<String>,
1256) -> Vec<lensbench_core::mech::MechPart> {
1257    let mut out = Vec::new();
1258    for (k, (name, f)) in frames.iter().enumerate() {
1259        let tag = format!("{name} mount");
1260        if let Err(e) = f.validate() {
1261            warn.push(format!("{tag}: {e} (not placed)"));
1262            continue;
1263        }
1264        let faces: Vec<usize> = (0..s.surfaces.len().min(map.len()))
1265            .filter(|&j| map[j].frame == Some(k) && !s.surfaces[j].is_coord_break())
1266            .collect();
1267        let Some(&first) = faces.first() else {
1268            continue;
1269        };
1270        let seat = f.holds.map_or(0.0, |h| h.seat_z);
1271        let mut part = f.part(&tag, first, [0.0, 0.0, -seat], [0.0, 0.0]);
1272        part.holds = faces;
1273        out.push(part);
1274    }
1275    out
1276}
1277
1278/// id の群(ブロックの群・.zmx の取り込みの中の群)の移動
1279pub(crate) fn group_shift(blocks: &[Block], id: &str) -> Option<f64> {
1280    for b in blocks {
1281        match b {
1282            Block::Group {
1283                id: g,
1284                shift,
1285                blocks,
1286                ..
1287            } => {
1288                if g == id {
1289                    return Some(*shift);
1290                }
1291                if let Some(v) = group_shift(blocks, id) {
1292                    return Some(v);
1293                }
1294            }
1295            Block::Zmx { groups, .. } => {
1296                if let Some(g) = groups.iter().find(|g| g.id == id) {
1297                    return Some(g.shift);
1298                }
1299            }
1300            Block::Splitter { spec, .. } => {
1301                for arm in [&spec.t, &spec.r, &spec.d] {
1302                    if let Some(v) = group_shift(arm, id) {
1303                        return Some(v);
1304                    }
1305                }
1306            }
1307            _ => {}
1308        }
1309    }
1310    None
1311}
1312
1313/// zmx ブロックで取り込んだ面のピックアップと厚さのソルブを、展開した系の面番号に付け替えて残す。
1314/// 元か先が取り込んだ範囲の外にあるもの、展開で値の関係が崩れたもの(群の移動で厚さが変わったなど)は
1315/// 値で固定し、説明を返す。org[i] は展開した系の面 i + 1 の出どころ。物体空間の媒質の注意([`crate::zmx_links::carry_object`])
1316/// も別に返す
1317pub(crate) fn keep_pickups(
1318    s: &mut System,
1319    org: &[Option<(usize, usize)>],
1320    zpicks: &[ZmxLinks],
1321) -> lensbench_core::Result<(Vec<String>, Vec<String>)> {
1322    let mut at: HashMap<(usize, usize), usize> = HashMap::new();
1323    for (i, o) in org.iter().enumerate() {
1324        if let Some(k) = o {
1325            // 同じ取り込みで同じ面が 2 回出ることはない
1326            at.insert(*k, i + 1);
1327        }
1328    }
1329    let medium = crate::zmx_links::carry_object(s, zpicks, &mut at)?;
1330    let mut warn = Vec::new();
1331    for (inst, z) in zpicks.iter().enumerate() {
1332        let (path, picks) = (&z.path, &z.pickups);
1333        for q in picks {
1334            let (Some(&dst), src) = (at.get(&(inst, q.dst)), at.get(&(inst, q.src))) else {
1335                continue; // 先が取り込んでいない面
1336            };
1337            let Some(&src) = src else {
1338                warn.push(format!(
1339                    "{path}: surface {} {:?} is a pickup from surface {} outside the range (fixed to the value)",
1340                    q.dst, q.what, q.src
1341                ));
1342                continue;
1343            };
1344            // 鏡のあと(向きが逆、sign = −1)で取り込むと、曲率・厚さの符号が変わる。先 dst' = σd·dst、元 src' = σs·src
1345            // (σ は量の符号が変われば sign、変わらなければ 1)なら、dst = a·src + b は dst' = (σd·σs·a)·src' + σd·b。
1346            // 向きから決めた組を先に試し、合わなければ(面タイプのパラメータの意味は型で違う)ほかの符号の組を試す
1347            use lensbench_core::param::Kind as Pk;
1348            let flips = |k: Pk| matches!(k, Pk::Curv | Pk::Thick | Pk::Radius);
1349            let sd = if flips(q.what) { z.sign } else { 1.0 };
1350            let ss = if flips(q.from.unwrap_or(q.what)) {
1351                z.sign
1352            } else {
1353                1.0
1354            };
1355            let mut cands = vec![Pickup {
1356                dst,
1357                src,
1358                scale: sd * ss * q.scale,
1359                offset: sd * q.offset,
1360                ..*q
1361            }];
1362            for (a, b) in [(1.0, 1.0), (1.0, -1.0), (-1.0, 1.0), (-1.0, -1.0)] {
1363                let c = Pickup {
1364                    dst,
1365                    src,
1366                    scale: a * q.scale,
1367                    offset: b * q.offset,
1368                    ..*q
1369                };
1370                if !cands.contains(&c) {
1371                    cands.push(c);
1372                }
1373            }
1374            match cands.iter().position(|c| c.holds(s)) {
1375                Some(0) => s.edit_raw(|rx| {
1376                    rx.pickups.push(cands[0]);
1377                    Ok(())
1378                })?,
1379                Some(k) => {
1380                    // 向きから決めた組と違う符号で値が合った(元の値が 0 だと符号を区別できない)
1381                    s.edit_raw(|rx| {
1382                        rx.pickups.push(cands[k]);
1383                        Ok(())
1384                    })?;
1385                    warn.push(format!(
1386                        "{path}: the sign of the scale and offset of surface {} {:?} (from surface {}) was chosen by matching values (scale {}, offset {}); check it is as intended",
1387                        q.dst, q.what, q.src, cands[k].scale, cands[k].offset
1388                    ));
1389                }
1390                None => warn.push(format!(
1391                    "{path}: the value relation of surface {} {:?} (from surface {}) changed in the expansion (fixed to the value)",
1392                    q.dst, q.what, q.src
1393                )),
1394            }
1395        }
1396    }
1397    if !s.pickups.is_empty() {
1398        s.resolve_links()?;
1399    }
1400    let moff = crate::zmx_links::carry_macros(s, zpicks, &at)?;
1401    // ソルブ(厚さ・曲率): 関わる面(厚さは次の面、玉のパワーは前の面、基準の面)が同じ並びで取り込まれていれば
1402    // 残し、展開した系で解き直す(雛形の像面の手前の面の厚さのソルブは、展開した系でも像面の手前にあれば残す)
1403    for (inst, z) in zpicks.iter().enumerate() {
1404        for q in &z.solves {
1405            let Some(&k) = at.get(&(inst, q.surf)) else {
1406                continue;
1407            };
1408            // 雛形の面 j が、展開した系で面 k からの同じずれにあるか
1409            let same = |j: usize| -> bool {
1410                at.get(&(inst, j))
1411                    .is_some_and(|&n| n as i64 - k as i64 == j as i64 - q.surf as i64)
1412            };
1413            use lensbench_core::solves::SolveKind as Sk;
1414            let mut ok = true;
1415            // 位置ソルブは高さを見ないので次の面は要らない(基準の面との間が並んでいればよい)
1416            if !q.kind.is_curv() && !matches!(q.kind, Sk::Position { .. }) {
1417                ok &= same(q.surf + 1) || (q.surf + 1 == z.image && k + 1 == s.image());
1418            }
1419            if matches!(q.kind, Sk::ElementPower { .. }) {
1420                ok &= q.surf >= 1 && same(q.surf - 1);
1421            }
1422            let mut kind = q.kind;
1423            crate::zmx_links::shift_macro(&mut kind, moff[inst]);
1424            if let Some(o) = q.kind.other_surface() {
1425                ok &= same(o);
1426                // 基準の面との距離で決まるものは、間の面(基準の面が後ろでも)も並んで取り込まれていること
1427                if matches!(
1428                    q.kind,
1429                    Sk::Position { .. }
1430                        | Sk::CenterOfCurvature { .. }
1431                        | Sk::ConcentricSurface { .. }
1432                        | Sk::ConcentricRadius { .. }
1433                ) {
1434                    ok &= (o.min(q.surf)..=o.max(q.surf)).all(same);
1435                }
1436                if let Some(&n) = at.get(&(inst, o)) {
1437                    kind = kind.with_other_surface(n);
1438                }
1439            }
1440            if ok {
1441                s.edit_raw(|rx| {
1442                    rx.solves.push(Solve { surf: k, kind });
1443                    Ok(())
1444                })?;
1445            } else {
1446                warn.push(format!(
1447                    "{}: the solve of surface {} ({:?}) involves surfaces outside the range or far away (fixed to the value)",
1448                    z.path, q.surf, q.kind
1449                ));
1450            }
1451        }
1452    }
1453    if !s.solves.is_empty() || !s.macro_parms.is_empty() {
1454        let val = |s: &System, q: &Solve| {
1455            let d = &s.surfaces[q.surf];
1456            if q.kind.is_curv() {
1457                d.c
1458            } else {
1459                d.t
1460            }
1461        };
1462        let before: Vec<f64> = s.solves.iter().map(|q| val(s, q)).collect();
1463        s.resolve_links()?;
1464        for (q, b) in s.solves.iter().zip(before) {
1465            let a = val(s, q);
1466            if (a - b).abs() > 1e-9 * (1.0 + b.abs()) {
1467                let what = if q.kind.is_curv() {
1468                    "curvature"
1469                } else {
1470                    "thickness"
1471                };
1472                warn.push(format!(
1473                    "solved the {what} of surface {} again with the solve ({}, value {}): {b} → {a}",
1474                    q.surf,
1475                    lensbench_core::solves::solve_kind_info(q.kind).0,
1476                    q.kind.value()
1477                ));
1478            }
1479        }
1480    }
1481    Ok((warn, medium))
1482}
1483
1484/// 面 j のガラス mat がカタログに無い誤り(符号 [`code::GLASS_NOT_FOUND`])
1485fn glass_missing(j: usize, mat: &str) -> lensbench_core::Error {
1486    lensbench_core::Error::Invalid(format!(
1487        "surface {j}: glass {mat} is not in the catalogs{HINT}"
1488    ))
1489    .with_code(code::GLASS_NOT_FOUND)
1490}