Skip to main content

lensbench_project/
writeback.rs

1//! 展開した系にした面の編集(serve の `edit`・GUI の面の表)を、面を足したブロックの面の上書き・操作
2//! ([`FaceMods`])としてプロジェクトに書き戻す。面は展開の面の名前([`FaceId`])でブロックへ戻す
3
4use crate::edit_spec::{BlockFace, BlockRef, EditOp, Ref};
5use crate::{Block, FaceId, FaceMods, NodePath, NodeStep, Project, SurfaceEdit, SurfaceOp};
6use lensbench_core::System;
7use serde_json::{Map, Value};
8
9/// 編集した系とその面の名前([`crate::SurfOrigin::face`]、系の面と同じ並び)
10#[derive(Clone, Copy)]
11pub struct Edited<'a> {
12    pub system: &'a System,
13    pub faces: &'a [Option<FaceId>],
14    /// 編集する前の系(プロジェクトを展開したまま。面の並びは system と同じ)。置くソルブ・ピックアップがブロックの
15    /// 元(.zmx など)から出ていたかをこれで見る(編集した系では、編集で置いたものも出ている)
16    pub before: &'a System,
17}
18
19/// 木の位置のブロック
20fn node_mut<'p>(blocks: &'p mut [Block], path: &NodePath) -> Option<&'p mut Block> {
21    let (first, rest) = path.0.split_first()?;
22    let b = match *first {
23        NodeStep::Block(i) => blocks.get_mut(i)?,
24        NodeStep::Arm(..) => return None,
25    };
26    let mut cur = b;
27    for st in rest {
28        cur = match (cur, *st) {
29            (Block::Group { blocks, .. }, NodeStep::Block(i)) => blocks.get_mut(i)?,
30            (Block::Splitter { spec, .. }, NodeStep::Arm(a, i)) => match a {
31                0 => spec.t.get_mut(i)?,
32                1 => spec.r.get_mut(i)?,
33                2 => spec.d.get_mut(i)?,
34                _ => return None,
35            },
36            _ => return None,
37        };
38    }
39    Some(cur)
40}
41
42fn node<'p>(blocks: &'p [Block], path: &NodePath) -> Option<&'p Block> {
43    let (first, rest) = path.0.split_first()?;
44    let mut cur = match *first {
45        NodeStep::Block(i) => blocks.get(i)?,
46        NodeStep::Arm(..) => return None,
47    };
48    for st in rest {
49        cur = match (cur, *st) {
50            (Block::Group { blocks, .. }, NodeStep::Block(i)) => blocks.get(i)?,
51            (Block::Splitter { spec, .. }, NodeStep::Arm(a, i)) => match a {
52                0 => spec.t.get(i)?,
53                1 => spec.r.get(i)?,
54                2 => spec.d.get(i)?,
55                _ => return None,
56            },
57            _ => return None,
58        };
59    }
60    Some(cur)
61}
62
63/// 展開した系の面 j を書き戻せるブロックの面(座標ブレークでない面)と、ブロックの面の番号。往路の 2 回目以降
64/// (`pass > 0`)は往路の 1 回目と同じ番号、鏡の `back`・光束の `turn` で戻る復路の面は往路の番号(復路はその範囲の
65/// 面を往路の逆の順に通るので、範囲の面の数を m として m − 1 − 範囲の中の番号。[`crate::edit_spec::BlockFace`] の
66/// `back` と同じ数え方)
67fn face_of(x: Edited, r: &Ref) -> Result<(FaceId, usize), String> {
68    let j = match r {
69        Ref::Index(j) => *j,
70        Ref::Name(n) => x.system.find_surface(n).map_err(|e| e.to_string())?,
71    };
72    let f = x
73        .faces
74        .get(j)
75        .cloned()
76        .flatten()
77        .ok_or_else(|| format!("surface {j} is not a surface of a block"))?;
78    if f.cb {
79        return Err(format!(
80            "surface {j} is a coordinate break of a block (use the block decenter and tilt)"
81        ));
82    }
83    if f.back {
84        // 復路は範囲の面を往路の逆の順にたどる
85        let m = x
86            .faces
87            .iter()
88            .flatten()
89            .filter(|g| g.node == f.node && !g.cb && g.back && g.pass == f.pass)
90            .count();
91        let i = m.checked_sub(f.index + 1).ok_or_else(|| {
92            format!("surface {j} on the return pass has no surface on the forward pass")
93        })?;
94        return Ok((f, i));
95    }
96    let i = f.index;
97    Ok((f, i))
98}
99
100/// 面の値の欄のうち、面の後ろの媒質と間隔の欄(復路では 1 つ前の面のもの)
101fn gap_field(k: &str) -> bool {
102    matches!(k, "t" | "material" | "dn" | "disp")
103}
104
105/// 面の id のあるブロックの id(無ければ誤り。復路の面・ほかの面を指すのに要る)
106fn block_id_of<'p>(p: &'p Project, f: &FaceId, r: &Ref) -> Result<&'p str, String> {
107    let id = node(&p.blocks, &f.node).map(crate::block_id).unwrap_or("");
108    if id.is_empty() {
109        return Err(format!(
110            "surface {} is in a block without an id (give the block an id to refer to it)",
111            match r {
112                Ref::Index(j) => j.to_string(),
113                Ref::Name(n) => n.clone(),
114            }
115        ));
116    }
117    Ok(id)
118}
119
120/// 面のブロックが往復する(復路の面がある)
121fn round_trip(x: Edited, f: &FaceId) -> bool {
122    x.faces.iter().flatten().any(|g| g.node == f.node && g.back)
123}
124
125/// ほかの面を指す面(ピックアップの元・ソルブの参照の面): id のあるブロックの面(復路の面も)
126fn other_ref(p: &Project, x: Edited, r: &Ref) -> Result<BlockRef, String> {
127    let (f, i) = face_of(x, r)?;
128    let id = block_id_of(p, &f, r)?;
129    Ok(BlockRef::Block(BlockFace {
130        block: id.to_string(),
131        surface: i,
132        coordbrk: false,
133        back: f.back,
134        pass: f.pass,
135    }))
136}
137
138/// 木の位置のブロックの面の上書き・操作
139fn faces<'p>(p: &'p mut Project, n: &NodePath) -> Result<&'p mut FaceMods, String> {
140    node_mut(&mut p.blocks, n)
141        .ok_or("the block is not in the project")?
142        .faces_mut()
143        .ok_or_else(|| "this kind of block can't hold surface edits".into())
144}
145
146/// 書き戻す 1 つ: 面の上書きか操作。ソルブ・ピックアップを置く操作は、系にその面のソルブ・ピックアップが
147/// 出ていたか(ブロックの元のものを置き換えるか、[`crate::surface_ops`])も持つ
148enum Mod {
149    Edit(SurfaceEdit),
150    Op(SurfaceOp, bool),
151}
152
153/// 面の番号(名前の面は系で引く)
154fn sys_index(x: Edited, r: &Ref) -> Option<usize> {
155    match r {
156        Ref::Index(j) => Some(*j),
157        Ref::Name(n) => x.system.find_surface(n).ok(),
158    }
159}
160
161/// ブロックの面の上書きに 1 つ足す。同じ面の同じ欄の前の上書きは外す(空になった上書きも)
162fn put_edit(edits: &mut Vec<SurfaceEdit>, e: SurfaceEdit) {
163    for q in edits
164        .iter_mut()
165        .filter(|q| q.surface == e.surface && q.coordbrk == e.coordbrk)
166    {
167        q.fields.retain(|k, _| !e.fields.contains_key(k));
168    }
169    edits.retain(|q| !q.fields.is_empty());
170    edits.push(e);
171}
172
173/// ブロックの面の操作に 1 つ足す。ソルブ・ピックアップは同じ面・量のものを 1 つにまとめ、元のものを置き換える・
174/// 外すときは外す操作も置く([`crate::surface_ops`])
175fn put_op(ops: &mut Vec<SurfaceOp>, o: SurfaceOp, shown: bool) {
176    use crate::surface_ops as so;
177    match o {
178        SurfaceOp::AddSolve(o) => so::put_solve(ops, o, shown),
179        SurfaceOp::AddPickup(o) => so::put_pickup(ops, o, shown),
180        SurfaceOp::RemoveSolve {
181            surface: at @ (BlockRef::Sys(Ref::Index(_)) | BlockRef::Block(_)),
182            what,
183        } => so::drop_solve_at(ops, at, what),
184        SurfaceOp::RemovePickup {
185            dst: at @ (BlockRef::Sys(Ref::Index(_)) | BlockRef::Block(_)),
186            what,
187        } => so::drop_pickup_at(ops, at, what),
188        o => ops.push(o),
189    }
190}
191
192/// 操作 1 つを、書き戻す先のブロックと上書き・操作に(復路の面の値は、面の値と前の面の後ろの媒質・間隔の 2 つになる)
193fn to_mod(p: &Project, x: Edited, op: &EditOp) -> Result<Vec<(NodePath, Mod)>, String> {
194    use EditOp as E;
195    // ブロックの面 i の上書き 1 つ。ブロックの最後の面の厚さには後ろの空気のブロックが入っている(状態で変わる間隔も)。
196    // 上書きすると全部の状態で固定されるので、空気のブロックで変える。往復するブロックの最後の面の後の媒質(材料など)も
197    // 同じ(展開で通らない)
198    let one = |f: &FaceId,
199               i: usize,
200               fields: Map<String, Value>|
201     -> Result<(NodePath, Mod), String> {
202        let last = !x
203            .faces
204            .iter()
205            .flatten()
206            .any(|g| g.node == f.node && !g.cb && !g.back && g.pass == 0 && g.index > i);
207        if last && fields.contains_key("t") {
208            return Err(
209                "the thickness after the last surface of a block includes the following air (change the air block)"
210                    .into(),
211            );
212        }
213        if last && round_trip(x, f) && fields.keys().any(|k| gap_field(k)) {
214            return Err(
215                "the medium after the last surface of a round-trip block is the following air (change the air block)"
216                    .into(),
217            );
218        }
219        Ok((
220            f.node.clone(),
221            Mod::Edit(SurfaceEdit {
222                surface: i,
223                coordbrk: false,
224                fields,
225            }),
226        ))
227    };
228    let edit = |r: &Ref, fields: Map<String, Value>| -> Result<Vec<(NodePath, Mod)>, String> {
229        let (f, i) = face_of(x, r)?;
230        // 往路の 2 回目以降は 1 回目と同じ面・同じ値
231        if !f.back {
232            return Ok(vec![one(&f, i, fields)?]);
233        }
234        // 復路の面は往路の面と同じ座標(曲率・コーニック・非球面・開口などは同じ値)。面の後ろの媒質と間隔は往路の
235        // 1 つ前の面のもの(間隔は符号が逆)
236        let (gap, own): (Map<String, Value>, Map<String, Value>) =
237            fields.into_iter().partition(|(k, _)| gap_field(k));
238        let mut out = Vec::new();
239        if !own.is_empty() {
240            out.push(one(&f, i, own)?);
241        }
242        if !gap.is_empty() {
243            let Some(prev) = i.checked_sub(1) else {
244                return Err(
245                    "the medium and the spacing after this surface on the return pass are those before the block (change the block or air in front)"
246                        .into(),
247                );
248            };
249            let mut g = Map::new();
250            for (k, v) in gap {
251                let v = if k == "t" {
252                    let t = v
253                        .as_f64()
254                        .ok_or("the thickness on the return pass must be a number")?;
255                    Value::from(-t)
256                } else {
257                    v
258                };
259                g.insert(k, v);
260            }
261            out.push(one(&f, prev, g)?);
262        }
263        Ok(out)
264    };
265    // 当てる面(surface・dst)はブロックの面の番号。any なら復路・往路の 2 回目以降の面にもソルブ・ピックアップを置ける
266    // (ブロックの面 `{"block": id, "surface": 往路の番号, "back": true, "pass": 回}` で指す)
267    let at = |r: &Ref, any: bool| -> Result<(NodePath, BlockRef), String> {
268        let (f, i) = face_of(x, r)?;
269        if f.back || f.pass > 0 {
270            if !any {
271                let j = match r {
272                    Ref::Index(j) => j.to_string(),
273                    Ref::Name(n) => n.clone(),
274                };
275                return Err(format!(
276                    "surface {j} is on a later pass of a block (choose the surface on its first forward pass)"
277                ));
278            }
279            let id = block_id_of(p, &f, r)?.to_string();
280            let b = BlockFace {
281                block: id,
282                surface: i,
283                coordbrk: false,
284                back: f.back,
285                pass: f.pass,
286            };
287            return Ok((f.node, BlockRef::Block(b)));
288        }
289        Ok((f.node, BlockRef::Sys(Ref::Index(i))))
290    };
291    let own = |r: &Ref| at(r, false);
292    let any = |r: &Ref| at(r, true);
293    Ok(vec![match op {
294        E::SetSurface { surface, fields } => return edit(surface, fields.clone()),
295        E::SetSurfaceData { surface, data } => return edit(surface, data.clone()),
296        E::SetMaterial { surface, material } => {
297            let mut m = Map::new();
298            m.insert("material".into(), Value::String(material.clone()));
299            return edit(surface, m);
300        }
301        E::SetStop(o) => {
302            let (n, r) = own(&o.surface)?;
303            (
304                n,
305                Mod::Op(
306                    SurfaceOp::SetStop(crate::edit_spec::StopOp { surface: r }),
307                    false,
308                ),
309            )
310        }
311        E::AddSolve(o) => {
312            let (n, r) = any(&o.surface)?;
313            let other = o.other.as_ref().map(|q| other_ref(p, x, q)).transpose()?;
314            let j = sys_index(x, &o.surface);
315            let shown = x
316                .before
317                .solves
318                .iter()
319                .any(|q| Some(q.surf) == j && q.kind.is_curv() == o.is_curv());
320            (
321                n,
322                Mod::Op(
323                    SurfaceOp::AddSolve(crate::edit_spec::SolveOp {
324                        surface: r,
325                        kind: o.kind.clone(),
326                        value: o.value,
327                        other,
328                        param: o.param,
329                        macro_ref: o.macro_ref.clone(),
330                    }),
331                    shown,
332                ),
333            )
334        }
335        E::AddPickup(o) => {
336            let (n, r) = any(&o.dst)?;
337            let src = other_ref(p, x, &o.src)?;
338            let j = sys_index(x, &o.dst);
339            let w = lensbench_core::pickup::pick_kind_parse(&o.what).ok();
340            let shown = x
341                .before
342                .pickups
343                .iter()
344                .any(|q| Some(q.dst) == j && Some(q.what) == w);
345            (
346                n,
347                Mod::Op(
348                    SurfaceOp::AddPickup(crate::edit_spec::PickupOp {
349                        dst: r,
350                        src,
351                        what: o.what.clone(),
352                        scale: o.scale,
353                        offset: o.offset,
354                        from: o.from.clone(),
355                    }),
356                    shown,
357                ),
358            )
359        }
360        E::RemoveSolve { surface, what } => {
361            let (n, r) = any(surface)?;
362            (
363                n,
364                Mod::Op(
365                    SurfaceOp::RemoveSolve {
366                        surface: r,
367                        what: *what,
368                    },
369                    false,
370                ),
371            )
372        }
373        E::RemovePickup { dst, what } => {
374            let (n, r) = any(dst)?;
375            (
376                n,
377                Mod::Op(
378                    SurfaceOp::RemovePickup {
379                        dst: r,
380                        what: what.clone(),
381                    },
382                    false,
383                ),
384            )
385        }
386        E::SetParam { param, .. } => {
387            return Err(format!(
388                "parameter {param} can't be written back to blocks (only surface parameters)"
389            ))
390        }
391        _ => return Err("only surface edits can be written back to blocks".into()),
392    }])
393}
394
395/// id のあるブロックの面の上書き・操作(木の全部のブロック、群の中・BS の口の先も)。書き戻しの前後で比べて、
396/// 変わったブロックだけを返すのに使う(GUI の組合せの要素へ当てる)
397pub fn face_mods(p: &Project) -> Vec<(&str, &FaceMods)> {
398    fn walk<'p>(bs: &'p [Block], out: &mut Vec<(&'p str, &'p FaceMods)>) {
399        for b in bs {
400            let id = crate::block_id(b);
401            if let (false, Some(f)) = (id.is_empty(), b.faces()) {
402                out.push((id, f));
403            }
404            match b {
405                Block::Group { blocks, .. } => walk(blocks, out),
406                Block::Splitter { spec, .. } => {
407                    for arm in [&spec.t, &spec.r, &spec.d] {
408                        walk(arm, out);
409                    }
410                }
411                _ => {}
412            }
413        }
414    }
415    let mut out = Vec::new();
416    walk(&p.blocks, &mut out);
417    out
418}
419
420/// パラメータの値を変える操作を、面の値・面のデータの上書きにする。厚さ・半径・曲率・コーニックは面の値、ほかの
421/// 値(非球面係数・Zernike・偏心など)は、ここまでの操作をすべて順に当てた系の写し run に当てて、変わった面の
422/// データの項目(同じ項目を先に変えた値も入った今の値)にする。ほかの操作はそのまま返し、run にも当てる。
423/// 値の変わらないパラメータは None(書くものが無い)
424fn param_op(run: &mut Option<System>, x: Edited, op: &EditOp) -> Result<Option<EditOp>, String> {
425    let cur = run.get_or_insert_with(|| x.before.clone());
426    let EditOp::SetParam { param, value } = op else {
427        // 当てられない操作(書き戻せないものなど)は写しに当てずに進む。書けるかは後で to_mod が見る
428        let mut next = cur.clone();
429        if crate::edit_ops::apply(&mut next, std::slice::from_ref(op)).is_ok() {
430            *cur = next;
431        }
432        return Ok(Some(op.clone()));
433    };
434    let no =
435        || format!("parameter {param} can't be written back to blocks (only surface parameters)");
436    let (s, k) = param.trim().rsplit_once('.').ok_or_else(no)?;
437    let s = s.strip_prefix("surf:").unwrap_or(s);
438    let j: usize = s.trim().parse().map_err(|_| no())?;
439    use lensbench_core::param::{Kind, Param};
440    let kind = Kind::parse(k).map_err(|e| e.to_string())?;
441    let key = match kind {
442        Kind::Curv => Some("c"),
443        Kind::Radius => Some("r"),
444        Kind::Conic => Some("k"),
445        Kind::Thick => Some("t"),
446        _ => None,
447    };
448    // 今と同じ値なら書くものは無い(注意も出さない)
449    if cur.get_param(Param::new(j, kind)).ok() == Some(value.0) {
450        return Ok(None);
451    }
452    let mut fields = Map::new();
453    let next = cur
454        .with_params(&[(Param::new(j, kind), value.0)])
455        .map_err(|e| e.to_string())?;
456    if let Some(key) = key {
457        fields.insert(key.into(), Value::from(value.0));
458        *cur = next;
459        return Ok(Some(EditOp::SetSurface {
460            surface: Ref::Index(j),
461            fields,
462        }));
463    }
464    let a = crate::edit_ops::surface_data(cur, j).map_err(|e| e.to_string())?;
465    let b = crate::edit_ops::surface_data(&next, j).map_err(|e| e.to_string())?;
466    for (k, v) in b["data"].as_object().into_iter().flatten() {
467        if !matches!(k.as_str(), "semi" | "semi_auto") && a["data"].get(k) != Some(v) {
468            fields.insert(k.clone(), v.clone());
469        }
470    }
471    *cur = next;
472    if fields.is_empty() {
473        return Err(no());
474    }
475    Ok(Some(EditOp::SetSurfaceData {
476        surface: Ref::Index(j),
477        data: fields,
478    }))
479}
480
481/// 展開した系 x(プロジェクト p の展開。状態・経路は問わない、ブロックの木が同じこと)にした編集 ops を、面を足した
482/// ブロックの [`FaceMods`] に足す。書き戻せない操作(面を入れる・消す、座標ブレーク、面の上書きを持てないブロックの面、
483/// 系の設定など)は書かずに、説明を返す。復路・往路の 2 回目以降の面の値はブロックの面へ書く(ブロックのどの回にも
484/// 当たる。復路の面の後ろの媒質・間隔は往路の 1 つ前の面のもの)。面を入れる・消す操作の後の操作は面の番号が
485/// ずれるので書かない。check は足した後のプロジェクトを確かめる(展開できるか)。通らない上書きは外して説明を返す
486/// ので、書き戻したプロジェクトは check を通る
487pub fn write_back(
488    p: &mut Project,
489    x: Edited,
490    ops: &[EditOp],
491    check: &dyn Fn(&Project) -> Result<(), String>,
492) -> Vec<String> {
493    let mut notes = Vec::new();
494    let mut run = None;
495    for (k, op) in ops.iter().enumerate() {
496        if matches!(
497            op,
498            EditOp::InsertSurface { .. } | EditOp::DeleteSurface { .. }
499        ) {
500            notes.push(format!(
501                "edit {}: {} and the later edits are not written back (surfaces of blocks can't be inserted or deleted here)",
502                k + 1,
503                op.name()
504            ));
505            break;
506        }
507        let op2 = match param_op(&mut run, x, op) {
508            Ok(Some(o)) => o,
509            Ok(None) => continue,
510            Err(e) => {
511                notes.push(format!(
512                    "edit {}: {} is not written back ({e})",
513                    k + 1,
514                    op.name()
515                ));
516                continue;
517            }
518        };
519        let r = to_mod(p, x, &op2).and_then(|mods| {
520            // 面の値を変えるブロックを何回通るか(往路の範囲の数と復路があるか)。値はどの回にも当たる
521            let mut rt = (false, false);
522            let mut saved: Vec<(NodePath, FaceMods)> = Vec::new();
523            for (n, m) in mods {
524                if matches!(m, Mod::Edit(_)) {
525                    let g = x.faces.iter().flatten().filter(|g| g.node == n);
526                    rt.0 |= g.clone().any(|g| g.back);
527                    rt.1 |= g.clone().any(|g| !g.back && g.pass > 0);
528                }
529                let f = faces(p, &n)?;
530                if !saved.iter().any(|(s, _)| *s == n) {
531                    saved.push((n.clone(), f.clone()));
532                }
533                match m {
534                    Mod::Edit(e) => put_edit(&mut f.surface_edits, e),
535                    Mod::Op(o, shown) => put_op(&mut f.surface_ops, o, shown),
536                }
537            }
538            if let Err(e) = check(p) {
539                for (n, before) in saved.into_iter().rev() {
540                    *faces(p, &n)? = before;
541                }
542                return Err(format!("the project would not expand: {e}"));
543            }
544            Ok(rt)
545        });
546        match r {
547            Ok((true, _)) => notes.push(format!(
548                "edit {}: {} also changes the return path of the round-trip block",
549                k + 1,
550                op.name()
551            )),
552            Ok((false, true)) => notes.push(format!(
553                "edit {}: {} also changes the other passes through the block",
554                k + 1,
555                op.name()
556            )),
557            Ok((false, false)) => {}
558            Err(e) => notes.push(format!(
559                "edit {}: {} is not written back ({e})",
560                k + 1,
561                op.name()
562            )),
563        }
564    }
565    notes
566}