Skip to main content

lensbench_project/
edit_spec.rs

1//! 系の編集の操作の JSON の型。`op` で操作を選び、操作ごとに使えるキーだけを受ける(知らないキーは誤り)。
2//! serve の `edit` の `ops`([`EditOp`])と、ブロックの `surface_ops`([`SurfaceOp`]、面をブロックの面でも指せる
3//! 絞り・ソルブ・ピックアップだけ)。当て方は [`crate::edit_ops`]。`docs/schema/edit-ops.schema.json` はこの型から作る。
4//!
5//! 面の値・面のデータ・系の設定・機構部品の書き換え(`fields`・`data`・`part`)は、系ファイルの同じ名前の項目と同じ形の
6//! `{名前: 値}` で、名前と値の確かめは当てるとき([`lensbench_core::edit::SURF_FIELDS`]・[`crate::edit_ops::SYSTEM_KEYS`])。
7
8use lensbench_core::mech::MechPart;
9use schemars::{json_schema, JsonSchema, Schema, SchemaGenerator};
10use serde::{Deserialize, Deserializer, Serialize, Serializer};
11use serde_json::{Map, Value};
12use std::borrow::Cow;
13
14/// 数。JSON に書けない無限遠などは `{"$f": "inf"}`(`"-inf"`・`"nan"`、系ファイルと同じ)
15#[derive(Debug, Clone, Copy, PartialEq)]
16pub struct Num(pub f64);
17
18impl Serialize for Num {
19    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
20        let x = self.0;
21        if x.is_finite() {
22            s.serialize_f64(x)
23        } else {
24            let t = if x.is_nan() {
25                "nan"
26            } else if x > 0.0 {
27                "inf"
28            } else {
29                "-inf"
30            };
31            let mut m = Map::new();
32            m.insert("$f".into(), Value::from(t));
33            m.serialize(s)
34        }
35    }
36}
37
38impl<'de> Deserialize<'de> for Num {
39    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
40        #[derive(Deserialize)]
41        #[serde(untagged)]
42        enum Raw {
43            N(f64),
44            F {
45                #[serde(rename = "$f")]
46                f: String,
47            },
48        }
49        match Raw::deserialize(d)
50            .map_err(|_| serde::de::Error::custom("a number or {\"$f\": \"inf\"} is needed"))?
51        {
52            Raw::N(x) => Ok(Num(x)),
53            Raw::F { f } => match f.as_str() {
54                "inf" => Ok(Num(f64::INFINITY)),
55                "-inf" => Ok(Num(f64::NEG_INFINITY)),
56                "nan" => Ok(Num(f64::NAN)),
57                t => Err(serde::de::Error::custom(format!(
58                    "{{\"$f\": \"{t}\"}} (inf, -inf, nan)"
59                ))),
60            },
61        }
62    }
63}
64
65impl JsonSchema for Num {
66    fn schema_name() -> Cow<'static, str> {
67        "Num".into()
68    }
69    fn json_schema(_: &mut SchemaGenerator) -> Schema {
70        json_schema!({
71            "description": "数。JSON に書けない数は {\"$f\": \"inf\"}(-inf・nan も)",
72            "anyOf": [
73                {"type": "number"},
74                {
75                    "type": "object",
76                    "properties": {"$f": {"enum": ["inf", "-inf", "nan"]}},
77                    "required": ["$f"],
78                    "additionalProperties": false
79                }
80            ]
81        })
82    }
83}
84
85/// 番号か名前。面は OpticStudio の面番号か面のコメント、玉・群と機構部品は 0 始まりの番号か名前
86#[derive(Serialize, JsonSchema, Debug, Clone, PartialEq, Eq)]
87#[serde(untagged)]
88pub enum Ref {
89    /// 番号
90    Index(usize),
91    /// 名前
92    Name(String),
93}
94
95/// プロジェクトのブロックの面
96#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq, Eq)]
97#[serde(deny_unknown_fields)]
98pub struct BlockFace {
99    /// ブロックの id
100    pub block: String,
101    /// ブロックの面の番号(0 始まり、座標ブレークを除く。往復するブロックは往路の面)
102    pub surface: usize,
103    /// 座標ブレークの面を指す(surface はブロックの座標ブレークだけを数えた番号)
104    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
105    pub coordbrk: bool,
106    /// 鏡の `back` で戻る復路の面を指す(surface は往路と同じ番号で、復路では逆の順に通る)
107    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
108    pub back: bool,
109    /// 同じ向きに何回目に通る面か(0 始まり。往復を重ねてブロックを 2 回以上通るとき)
110    #[serde(default, skip_serializing_if = "is_zero")]
111    pub pass: usize,
112}
113
114fn is_zero(n: &usize) -> bool {
115    *n == 0
116}
117
118/// ブロックの `surface_ops` の面: ブロックの面 `{"block": id, "surface": i}` か、展開した系の面の番号か名前
119#[derive(Serialize, JsonSchema, Debug, Clone, PartialEq, Eq)]
120#[serde(untagged)]
121pub enum BlockRef {
122    /// ブロックの面
123    Block(BlockFace),
124    /// 展開した系の面
125    Sys(Ref),
126}
127
128fn ref_of<E: serde::de::Error>(v: Value, surface: bool) -> Result<Ref, E> {
129    let msg = match (&v, surface) {
130        (Value::Number(n), true) => format!("surface number {n} (an integer 0 or more)"),
131        (Value::Number(n), false) => format!("item number {n} (an integer 0 or more)"),
132        (v, true) => format!("surface number or name needed ({v})"),
133        (v, false) => format!("item number or name needed ({v})"),
134    };
135    match v {
136        Value::Number(n) => n
137            .as_u64()
138            .map(|i| Ref::Index(i as usize))
139            .ok_or_else(|| E::custom(msg)),
140        Value::String(t) => Ok(Ref::Name(t)),
141        _ => Err(E::custom(msg)),
142    }
143}
144
145impl<'de> Deserialize<'de> for Ref {
146    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
147        ref_of(Value::deserialize(d)?, false)
148    }
149}
150
151impl<'de> Deserialize<'de> for BlockRef {
152    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
153        match Value::deserialize(d)? {
154            v @ Value::Object(_) => BlockFace::deserialize(v).map(BlockRef::Block).map_err(|e| {
155                serde::de::Error::custom(format!("block surface (block, surface): {e}"))
156            }),
157            v => ref_of(v, true).map(BlockRef::Sys).map_err(|e: D::Error| {
158                serde::de::Error::custom(format!(
159                    "{e} (a block surface is written with block and surface)"
160                ))
161            }),
162        }
163    }
164}
165
166/// 面を絞りにする
167#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)]
168#[serde(deny_unknown_fields)]
169pub struct StopOp<S> {
170    pub surface: S,
171}
172
173/// 円錐係数・半直径・機械半径・面タイプのパラメータを ZPL マクロで解く(同じ面・同じ量のものは置き換える。OpticStudio の
174/// KZPL・DIAM の Macro Solve・PZPL)
175#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)]
176#[serde(deny_unknown_fields, bound(deserialize = "S: Deserialize<'de>"))]
177pub struct MacroSolveOp<S> {
178    pub surface: S,
179    /// マクロの名前か番号(系のマクロ、プロジェクトでは `macros`。番号は 0 始まり)
180    #[serde(rename = "macro")]
181    pub macro_ref: Ref,
182    /// 解く量: `k`(円錐係数)・`semi`(半直径)・`mech`(機械半径)・`p1` …(面タイプのパラメータ)
183    pub what: String,
184}
185
186impl<S> MacroSolveOp<S> {
187    /// 面を f で読み替える(None は当てない)
188    pub fn map<T, E>(
189        self,
190        mut f: impl FnMut(S) -> Result<Option<T>, E>,
191    ) -> Result<Option<MacroSolveOp<T>>, E> {
192        Ok(f(self.surface)?.map(|surface| MacroSolveOp {
193            surface,
194            macro_ref: self.macro_ref,
195            what: self.what,
196        }))
197    }
198}
199
200/// 厚さか曲率のソルブを置く(同じ面・同じ量のソルブは置き換える)
201#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)]
202#[serde(deny_unknown_fields, bound(deserialize = "S: Deserialize<'de>"))]
203pub struct SolveOp<S> {
204    pub surface: S,
205    /// 種類(既定 marginal_height、[`lensbench_core::solves::SOLVE_KINDS`])
206    #[serde(default, skip_serializing_if = "Option::is_none")]
207    pub kind: Option<String>,
208    /// 目標の値(既定 0)
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub value: Option<Num>,
211    /// 別の面を参照する種類の面
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub other: Option<S>,
214    /// 帯・縁の高さ(既定 0)。種類 `macro_curv`・`macro_thick` ではマクロの番号(`macro` で名前でも指せる)
215    #[serde(default, skip_serializing_if = "Option::is_none")]
216    pub param: Option<Num>,
217    /// 種類 `macro_curv`・`macro_thick` のマクロの名前か番号(系のマクロ、プロジェクトでは `macros`)。書けば `param` より優先
218    #[serde(rename = "macro", default, skip_serializing_if = "Option::is_none")]
219    pub macro_ref: Option<Ref>,
220}
221
222/// ピックアップを置く: dst の量 = src の量 × scale + offset
223#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)]
224#[serde(deny_unknown_fields)]
225pub struct PickupOp<S> {
226    /// 値を写される面
227    pub dst: S,
228    /// 元の面
229    pub src: S,
230    /// 量(c r t k p1〜 dn disp semi before0〜4 after0〜4)
231    pub what: String,
232    /// 倍率(既定 1)
233    #[serde(default, skip_serializing_if = "Option::is_none")]
234    pub scale: Option<Num>,
235    /// 足す値(既定 0)
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub offset: Option<Num>,
238    /// 元の量(省くと what)
239    #[serde(default, skip_serializing_if = "Option::is_none")]
240    pub from: Option<String>,
241}
242
243impl<S> StopOp<S> {
244    /// 面を f で読み替える(None は当てない)
245    pub fn map<T, E>(
246        self,
247        mut f: impl FnMut(S) -> Result<Option<T>, E>,
248    ) -> Result<Option<StopOp<T>>, E> {
249        Ok(f(self.surface)?.map(|surface| StopOp { surface }))
250    }
251}
252
253impl<S> SolveOp<S> {
254    /// 面を f で読み替える(どれかが None なら当てない)
255    pub fn map<T, E>(
256        self,
257        mut f: impl FnMut(S) -> Result<Option<T>, E>,
258    ) -> Result<Option<SolveOp<T>>, E> {
259        let Some(surface) = f(self.surface)? else {
260            return Ok(None);
261        };
262        let other = match self.other {
263            Some(o) => match f(o)? {
264                Some(o) => Some(o),
265                None => return Ok(None),
266            },
267            None => None,
268        };
269        Ok(Some(SolveOp {
270            surface,
271            kind: self.kind,
272            value: self.value,
273            other,
274            param: self.param,
275            macro_ref: self.macro_ref,
276        }))
277    }
278
279    /// 曲率のソルブか(種類の名前が読めなければ false)
280    pub fn is_curv(&self) -> bool {
281        lensbench_core::solves::solve_kind_parse(
282            self.kind.as_deref().unwrap_or("marginal_height"),
283            0.0,
284            0.0,
285            Some(0),
286        )
287        .is_ok_and(|k| k.is_curv())
288    }
289}
290
291impl<S> PickupOp<S> {
292    /// 面を f で読み替える(どれかが None なら当てない)
293    pub fn map<T, E>(
294        self,
295        mut f: impl FnMut(S) -> Result<Option<T>, E>,
296    ) -> Result<Option<PickupOp<T>>, E> {
297        let (Some(dst), Some(src)) = (f(self.dst)?, f(self.src)?) else {
298            return Ok(None);
299        };
300        Ok(Some(PickupOp {
301            dst,
302            src,
303            what: self.what,
304            scale: self.scale,
305            offset: self.offset,
306            from: self.from,
307        }))
308    }
309}
310
311/// ソルブを外す量
312#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, Copy, PartialEq, Eq, Default)]
313#[serde(rename_all = "lowercase")]
314pub enum SolveWhat {
315    /// 厚さ(既定)
316    #[default]
317    T,
318    /// 曲率
319    C,
320}
321
322/// 系の編集の操作(serve の `edit` の `ops` の要素)。`op` で選ぶ
323#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)]
324#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
325pub enum EditOp {
326    /// 面 at の前に面を入れる(surface は面の値の名前と値、[`lensbench_core::edit::SURF_FIELDS`])
327    InsertSurface {
328        at: usize,
329        #[serde(default, skip_serializing_if = "Map::is_empty")]
330        surface: Map<String, Value>,
331    },
332    /// 面を消す
333    DeleteSurface { surface: Ref },
334    /// 面の値を変える(名前と値、[`lensbench_core::edit::SURF_FIELDS`]。aperture は {"type": "circular", "max": 3, …} か null)
335    SetSurface {
336        surface: Ref,
337        fields: Map<String, Value>,
338    },
339    /// 面タイプを変える
340    SetSurfaceType {
341        surface: Ref,
342        #[serde(rename = "type")]
343        typ: String,
344    },
345    /// 材料を変える
346    SetMaterial { surface: Ref, material: String },
347    /// 面を絞りにする
348    SetStop(StopOp<Ref>),
349    /// ピックアップを置く
350    AddPickup(PickupOp<Ref>),
351    /// ピックアップを外す
352    RemovePickup { dst: Ref, what: String },
353    /// ソルブを置く
354    AddSolve(SolveOp<Ref>),
355    /// 円錐係数・半直径・機械半径・面タイプのパラメータのマクロのソルブを置く
356    AddMacroSolve(MacroSolveOp<Ref>),
357    /// ソルブを外す
358    RemoveSolve {
359        surface: Ref,
360        #[serde(default)]
361        what: SolveWhat,
362    },
363    /// 面のデータを全部の項目で変える(serve の `surface_data` の data と同じ形、書いた項目だけ)。屈折率 n・絞り stop・
364    /// 鏡 mirror は変えない(材料・set_stop で)。面タイプの形のデータ zern・grid・bin2・cylf・grin、前後の傾き偏心
365    /// before・after もここで
366    SetSurfaceData {
367        surface: Ref,
368        data: Map<String, Value>,
369    },
370    /// パラメータの値を変える(名前は set と同じ)
371    SetParam { param: String, value: Num },
372    /// 系の設定の項目を変える([`crate::edit_ops::SYSTEM_KEYS`] の書いた分だけ。形は serve の `system_data` と同じ)
373    SetSystemData { data: Map<String, Value> },
374    /// 玉・群を作る(spans は面の範囲 [[最初, 最後], …]、pivot は既定 [0, 0, 0])
375    DefineUnit {
376        name: String,
377        spans: Vec<[usize; 2]>,
378        #[serde(default, skip_serializing_if = "Option::is_none")]
379        pivot: Option<[Num; 3]>,
380    },
381    /// 玉・群を変える(書いた分だけ。範囲を変えるのは動き・移動が 0 のときだけ)
382    SetUnit {
383        unit: Ref,
384        #[serde(default, skip_serializing_if = "Option::is_none")]
385        name: Option<String>,
386        #[serde(default, skip_serializing_if = "Option::is_none")]
387        spans: Option<Vec<[usize; 2]>>,
388        #[serde(default, skip_serializing_if = "Option::is_none")]
389        pivot: Option<[Num; 3]>,
390    },
391    /// 玉・群を外す(動き・移動が 0 のときだけ)
392    RemoveUnit { unit: Ref },
393    /// 機構部品を置く(系ファイルの mechanics の要素と同じ形)
394    AddMech { part: MechPart },
395    /// 機構部品を変える(part は書いた項目だけ)
396    SetMech { mech: Ref, part: Map<String, Value> },
397    /// 機構部品を外す
398    RemoveMech { mech: Ref },
399    /// 多重構成の数
400    SetConfigCount { n: usize },
401    /// 多重構成の表の行(パラメータの構成ごとの値)
402    SetConfigRow { param: String, values: Vec<Num> },
403    /// 多重構成の表の材料の行(param は `N.material`、構成ごとの材料の名前)
404    SetConfigMaterials { param: String, names: Vec<String> },
405    /// 多重構成の表の膜の行(param は `N.coating`、構成ごとの膜の名前。空は膜なし)
406    SetConfigCoatings { param: String, names: Vec<String> },
407    /// 多重構成の表に行を足す(どの構成も今の値)
408    AddConfigRow { param: String },
409    /// 多重構成の表の行を外す
410    RemoveConfigRow { param: String },
411    /// 構成 k(1 始まり)を系に入れる
412    SetConfig { k: usize },
413    /// 構成を at(1 始まり)に入れる。from の構成の値で(既定は今の構成、pickup なら 1)、pickup なら from を写す
414    InsertConfig {
415        at: usize,
416        #[serde(default, skip_serializing_if = "Option::is_none")]
417        from: Option<usize>,
418        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
419        pickup: bool,
420    },
421    /// 構成 k を外す
422    RemoveConfig { k: usize },
423    /// 表の行 param の構成 k を構成 from から写す(× scale + offset)。row があれば表の別の行 row(同じ量の種類の行)の
424    /// 構成 from から写す(OpticStudio の構成のピックアップの元の行。OpticStudio が拾わない下の行・後の構成からのものは .zmx に値だけ書く)
425    SetConfigPickup {
426        param: String,
427        k: usize,
428        from: usize,
429        #[serde(default, skip_serializing_if = "Option::is_none")]
430        row: Option<String>,
431        #[serde(default, skip_serializing_if = "Option::is_none")]
432        scale: Option<Num>,
433        #[serde(default, skip_serializing_if = "Option::is_none")]
434        offset: Option<Num>,
435    },
436    /// 表の行 param の構成 k の写しをやめる
437    RemoveConfigPickup { param: String, k: usize },
438    /// 熱の構成を作る(OpticStudio の Make Thermal、[`lensbench_core::thermal`])。今の構成を構成 1 にし、temps の温度
439    /// [°C] ごとに構成を足す。pressures は足す構成の気圧 [atm](省くと今の気圧)
440    MakeThermal {
441        temps: Vec<Num>,
442        #[serde(default, skip_serializing_if = "Vec::is_empty")]
443        pressures: Vec<Num>,
444    },
445}
446
447impl EditOp {
448    /// 多重構成の表の操作か(そうでなければ、変えた値を表の今の構成の列にも写す)
449    pub fn is_config(&self) -> bool {
450        use EditOp::*;
451        matches!(
452            self,
453            SetConfigCount { .. }
454                | SetConfigRow { .. }
455                | SetConfigMaterials { .. }
456                | SetConfigCoatings { .. }
457                | AddConfigRow { .. }
458                | RemoveConfigRow { .. }
459                | SetConfig { .. }
460                | InsertConfig { .. }
461                | RemoveConfig { .. }
462                | SetConfigPickup { .. }
463                | RemoveConfigPickup { .. }
464                | MakeThermal { .. }
465        )
466    }
467
468    /// 操作の名前(`op`)
469    pub fn name(&self) -> String {
470        serde_json::to_value(self)
471            .ok()
472            .and_then(|v| v["op"].as_str().map(str::to_string))
473            .unwrap_or_default()
474    }
475}
476
477/// ブロックの `surface_ops` の操作([`crate::FaceMods`]): serve の `edit` の `set_stop`・`add_solve`・`add_pickup`・`remove_solve`・
478/// `remove_pickup` と同じ形で、面(`surface`・`dst`・`src`・`other`)はブロックの面 `{"block": id, "surface": i}` でも指せる
479/// (当てる面 `surface`・`dst` の番号はそのブロックの面)。
480/// `remove_*` はブロックの元(.zmx など)にあるソルブ・ピックアップを外す(無ければ当てずに注意)
481#[derive(Serialize, Deserialize, JsonSchema, Debug, Clone, PartialEq)]
482#[serde(tag = "op", rename_all = "snake_case")]
483pub enum SurfaceOp {
484    /// 面を絞りにする
485    SetStop(StopOp<BlockRef>),
486    /// ソルブを置く
487    AddSolve(SolveOp<BlockRef>),
488    /// 円錐係数・半直径・機械半径・面タイプのパラメータのマクロのソルブを置く
489    AddMacroSolve(MacroSolveOp<BlockRef>),
490    /// ピックアップを置く
491    AddPickup(PickupOp<BlockRef>),
492    /// ソルブを外す
493    RemoveSolve {
494        surface: BlockRef,
495        #[serde(default)]
496        what: SolveWhat,
497    },
498    /// ピックアップを外す
499    RemovePickup { dst: BlockRef, what: String },
500}
501
502impl SurfaceOp {
503    /// 面を f で系の面に読み替えて編集の操作にする(f が None を返した面があれば当てない)
504    pub fn to_edit<E>(
505        &self,
506        mut f: impl FnMut(BlockRef) -> Result<Option<Ref>, E>,
507    ) -> Result<Option<EditOp>, E> {
508        Ok(match self.clone() {
509            SurfaceOp::SetStop(o) => o.map(f)?.map(EditOp::SetStop),
510            SurfaceOp::AddSolve(o) => o.map(f)?.map(EditOp::AddSolve),
511            SurfaceOp::AddMacroSolve(o) => o.map(f)?.map(EditOp::AddMacroSolve),
512            SurfaceOp::AddPickup(o) => o.map(f)?.map(EditOp::AddPickup),
513            SurfaceOp::RemoveSolve { surface, what } => {
514                f(surface)?.map(|surface| EditOp::RemoveSolve { surface, what })
515            }
516            SurfaceOp::RemovePickup { dst, what } => {
517                f(dst)?.map(|dst| EditOp::RemovePickup { dst, what })
518            }
519        })
520    }
521
522    /// 操作を当てる面(`surface`・`dst`。`src`・`other` は含めない)
523    pub fn target_mut(&mut self) -> &mut BlockRef {
524        match self {
525            SurfaceOp::SetStop(x) => &mut x.surface,
526            SurfaceOp::AddSolve(x) => &mut x.surface,
527            SurfaceOp::AddMacroSolve(x) => &mut x.surface,
528            SurfaceOp::AddPickup(x) => &mut x.dst,
529            SurfaceOp::RemoveSolve { surface, .. } => surface,
530            SurfaceOp::RemovePickup { dst, .. } => dst,
531        }
532    }
533
534    /// 番号で書いた面の `set_stop` の面の番号
535    pub fn stop_index(&self) -> Option<usize> {
536        match self {
537            SurfaceOp::SetStop(StopOp {
538                surface: BlockRef::Sys(Ref::Index(i)),
539            }) => Some(*i),
540            _ => None,
541        }
542    }
543
544    /// 操作の名前(`op`)
545    pub fn name(&self) -> &'static str {
546        match self {
547            SurfaceOp::SetStop(_) => "set_stop",
548            SurfaceOp::AddSolve(_) => "add_solve",
549            SurfaceOp::AddMacroSolve(_) => "add_macro_solve",
550            SurfaceOp::AddPickup(_) => "add_pickup",
551            SurfaceOp::RemoveSolve { .. } => "remove_solve",
552            SurfaceOp::RemovePickup { .. } => "remove_pickup",
553        }
554    }
555}