Skip to main content

lensbench_cli/
main.rs

1//! lensbench のコマンドライン。視野・波長の番号は OpticStudio と同じく 1 始まり。
2//!
3//! 引数の解釈・文字の出力・serve の要求を運ぶ道(TCP・パイプ)を持ち、解析・系の読み方・serve の場は lensbench-engine。
4//! 実行ファイルの入口は `src/bin/lensbench.rs` で、[`main`] を呼ぶだけ(非公開版などは拡張の解析を
5//! [`lensbench_engine::register`] してから呼ぶ)。
6#![allow(clippy::unwrap_used, clippy::panic)] // 入口の exe(計算の中身のクレートは検査の内)
7
8use std::io::Write as _;
9use std::path::PathBuf;
10use std::process::ExitCode;
11
12use clap::{Args, Parser, Subcommand};
13use lensbench_core::{catalog::LensCatalog, coating, glass, System};
14use lensbench_export::{d2, mesh, scene};
15use lensbench_formats::zmx;
16use lensbench_formats::zmx_write;
17use serde_json::{json, Value};
18
19mod analysis_cmd;
20mod error;
21mod help_json;
22mod progress;
23mod text_out;
24mod thermal_cmd;
25pub(crate) use error::AppError;
26use text_out::warn_notes;
27mod coat_cmd;
28use coat_cmd::{coat_compact, coat_design, coat_from_layers, coat_kinks, coat_model, coatings};
29#[cfg(not(target_arch = "wasm32"))]
30use lensbench_cad::{self as cad, coat_remote};
31mod config_sel;
32pub mod ext;
33mod run;
34mod serve;
35mod serve_ipc;
36mod watch;
37mod zmx_merit;
38pub(crate) use config_sel::{overlay_systems, ConfigSel};
39
40use lensbench_design::dls_spec::{Jac, Merit, OptimizeParams, Reference, VarSpec};
41use lensbench_engine::layout::{self, Draw, Pick, RaySel, View};
42use lensbench_engine::load::{coat_interfaces, plugins_json, save_value, AutoCoat, CoatInterfaces};
43use lensbench_engine::{builtin_plugins, provenance};
44
45/// 最適化の設定の既定値(旗の既定はここから。設定の型 1 か所)
46static OPT: std::sync::LazyLock<OptimizeParams> = std::sync::LazyLock::new(OptimizeParams::default);
47/// レイアウトの書き出しの既定値(serve の layout_export と同じ)
48static D2: std::sync::LazyLock<d2::Options2D> = std::sync::LazyLock::new(d2::Options2D::default);
49static D3: std::sync::LazyLock<mesh::Options3D> =
50    std::sync::LazyLock::new(mesh::Options3D::default);
51mod clap_ja;
52mod glass_dirs;
53mod search_cmd;
54
55#[derive(Parser)]
56#[command(name = "lensbench", version = lensbench_core::VERSION, about = "Sequential ray tracing and analysis")]
57struct Cli {
58    /// Number of threads for tracing and analysis (1 runs serially; if omitted, LENSBENCH_THREADS, otherwise RAYON_NUM_THREADS on all cores). Results do not depend on the thread count
59    #[arg(long, global = true)]
60    threads: Option<usize>,
61    #[command(subcommand)]
62    cmd: Cmd,
63}
64
65/// 系を読む解析の共通の引数(拡張のサブコマンドも `#[command(flatten)]` で使う、[`ext`])
66#[derive(Args, Clone)]
67pub struct Common {
68    /// A .zmx file, or a project file (.json) built from blocks
69    pub file: PathBuf,
70    /// Folders to search for glass catalogs (more than one allowed; LENSBENCH_GLASSCAT is also used)
71    #[arg(long = "glass-dir")]
72    pub glass_dir: Vec<PathBuf>,
73    /// Lens catalogs for the catalog lenses ("vendor", "part") of a project file (.zmx files, or folders of .zmx; the folder name is the maker and the file name is the part number; more than one allowed)
74    #[arg(long = "lens-catalog")]
75    pub lens_catalog: Vec<PathBuf>,
76    /// Multi-configuration number (from 1)
77    #[arg(long, default_value_t = 1)]
78    pub cfg: usize,
79    /// State name of a project file (.json) (like a multi-configuration)
80    #[arg(long)]
81    pub state: Option<String>,
82    /// Beam splitter path of a project file (T and R in the order the BSs are passed, e.g. TR; if omitted, the project's path and each BS's arm)
83    #[arg(long = "beam-path")]
84    pub path: Option<String>,
85    /// Output JSON
86    #[arg(long)]
87    pub json: bool,
88    /// File to write the result to (csv, json or npz by extension)
89    #[arg(long)]
90    pub save: Option<PathBuf>,
91    /// Stop with an error when a ZPL macro solve of a .zmx can't be solved (by default the value is the same as OpticStudio's and a warning is shown)
92    #[arg(long = "strict-macros")]
93    pub strict_macros: bool,
94}
95
96impl Common {
97    /// 系の読み方
98    pub fn spec(&self) -> lensbench_engine::SysSpec {
99        lensbench_engine::SysSpec {
100            file: self.file.clone(),
101            glass_dir: self.glass_dir.clone(),
102            lens_catalog: self.lens_catalog.clone(),
103            cfg: self.cfg,
104            state: self.state.clone(),
105            path: self.path.clone(),
106            strict_macros: self.strict_macros,
107            ..Default::default()
108        }
109    }
110}
111
112#[derive(Subcommand)]
113enum Cmd {
114    /// Write the system
115    ///
116    /// A .json extension writes a system file (the complete lensbench format), .zmx writes .zmx. Reads .zmx, projects and system files (with --state and --cfg applied)
117    Convert {
118        #[command(flatten)]
119        c: Common,
120        /// File to write (.json or .zmx)
121        #[arg(long, short)]
122        out: PathBuf,
123    },
124    MakeThermal(thermal_cmd::MakeThermalArgs),
125    /// Write the system to .zmx (an expanded project, etc.)
126    ///
127    /// With --beam-paths, --states or --cfgs, put one configuration per item into a multi-configuration .zmx (per BS path, etc.; surfaces that differ are ignored with IGNR)
128    Zmx {
129        #[command(flatten)]
130        c: Common,
131        #[command(flatten)]
132        sel: ConfigSel,
133        /// .zmx to write
134        #[arg(long, short)]
135        out: PathBuf,
136    },
137    /// Read a multi-configuration .zmx whose configurations are the arms of a cube BS as a project with a BS and beams
138    ///
139    /// Each configuration goes into the cube, out through one arm to a mirror, back along the same surfaces (written out in the .zmx) and out of the cube (the form `zmx --beam-paths` writes, or one with the arms ignored per configuration). The arms become BS branches ending in a mirror that sends the light back, and configuration k becomes beam C<k> (state "Config k")
140    ZmxBeams {
141        #[command(flatten)]
142        c: Common,
143        /// .zmx configurations (from 1, comma-separated, all for every one)
144        #[arg(long, default_value = "all")]
145        cfgs: String,
146        /// Project file to write (.json)
147        #[arg(long, short)]
148        out: PathBuf,
149    },
150    /// Optimize variables with damped least squares (DLS)
151    ///
152    /// The merit function is the RMS spot or RMS wavefront over all fields (field weights) and wavelengths, plus the terms of --term and --terms. --out writes the optimized system to .zmx
153    Optimize {
154        #[command(flatten)]
155        c: Common,
156        /// Variables ("7.t", "lens2.tx", "G1.shift", etc.; a range is "7.t=0.5:3", one-sided "7.t=0.5:" or "7.t=:3"). More than one allowed
157        #[arg(long = "var", required = true)]
158        vars: Vec<String>,
159        /// Default merit function: spot, wavefront or none (only the --term terms)
160        #[arg(long, default_value_t = OPT.merit)]
161        merit: Merit,
162        /// Terms to add (JSON, e.g. '{"type":"paraxial","q":"efl","target":50,"weight":10}'; see the optimization terms in the docs for kinds and keys). More than one allowed
163        #[arg(long = "term")]
164        terms: Vec<String>,
165        /// JSON file of terms to add (an array of terms)
166        #[arg(long = "terms")]
167        terms_file: Option<PathBuf>,
168        /// Use the merit function saved in the .zmx (operators that can be written as terms; the others are skipped with a warning). The default merit function of --merit is not added, and every configuration the merit function uses is optimized together
169        #[arg(long = "zmx-merit")]
170        zmx_merit: bool,
171        /// Reference: centroid or chief (chief ray)
172        #[arg(long = "reference", default_value_t = OPT.reference)]
173        reference: Reference,
174        /// Number of rings of the Gaussian pupil quadrature
175        #[arg(long, default_value_t = OPT.rings)]
176        rings: usize,
177        /// Maximum number of iterations
178        #[arg(long, default_value_t = OPT.iters)]
179        iters: usize,
180        /// Jacobian: auto (analytic for terms with 16 or more analytic columns, central differences for fewer), fd (all central differences) or forward (all forward differences)
181        #[arg(long, default_value_t = OPT.jac)]
182        jac: Jac,
183        #[command(flatten)]
184        dls: search_cmd::DlsArgs,
185        #[command(flatten)]
186        search: Box<search_cmd::SearchArgs>,
187        /// .zmx to write the optimized system to (the first configuration)
188        #[arg(long, short)]
189        out: Option<PathBuf>,
190        #[command(flatten)]
191        sel: ConfigSel,
192    },
193    /// Monte Carlo tolerance simulation
194    ///
195    /// Perturb the system with per-lens tolerance sets (commercial by default; makers' tolerances for catalog lenses) and individual tolerances, re-adjust the compensators, and give the distribution and sensitivity of the merit function (RMS wavefront, spot, MTF, etc.). Settings are JSON (tolerance settings in the docs; the --spec file and --set overrides)
196    Tolerance {
197        #[command(flatten)]
198        c: Common,
199        /// Settings JSON file
200        #[arg(long)]
201        spec: Option<PathBuf>,
202        /// Settings override (a JSON object, e.g. '{"preset":"precision","compensators":["9.t"]}'). More than one allowed
203        #[arg(long = "set")]
204        set: Vec<String>,
205        /// Number of trials (takes precedence over trials in the settings)
206        #[arg(long)]
207        trials: Option<usize>,
208        /// Random seed (takes precedence over seed in the settings)
209        #[arg(long)]
210        seed: Option<u64>,
211        /// File to write the system of the trial with the worst merit (after compensation) to. .json writes a system file (index tolerances included), others .zmx (index and dispersion shifts can't be written to .zmx)
212        #[arg(long, short)]
213        out: Option<PathBuf>,
214        /// CSV file to write the compensators of each trial to (with the merit and the size of the x and y tilt pair [arcmin])
215        #[arg(long = "comp-csv")]
216        comp_csv: Option<PathBuf>,
217        /// JSONL file to write each evaluation (sensitivity and trials) to as it finishes. If the file is from the same calculation, continue from it (only the missing evaluations run; more --trials can be added)
218        #[arg(long)]
219        results: Option<PathBuf>,
220        /// With --results, start over instead of continuing from the file
221        #[arg(long = "no-resume")]
222        no_resume: bool,
223    },
224    /// Zoom trajectory
225    ///
226    /// Solve the group positions (--var) for each state (the project's states or the .zmx configurations). The merit is the image RMS (all fields, all wavelengths) and the --efl and --pmag targets. --steps follows the path between states by continuation
227    Zoom(Box<search_cmd::ZoomArgs>),
228    /// Catalog lens swap search
229    ///
230    /// Run the combinations that replace the --spec slots (lens blocks) with candidates in parallel, optimize the variables (spacings, etc.) for each, and sort them by merit
231    Swap(Box<search_cmd::SwapArgs>),
232    /// Save a lens or block to a user catalog (JSON) (the file is created if missing)
233    CatalogAdd {
234        /// User catalog file
235        catalog: PathBuf,
236        /// Item name
237        #[arg(long)]
238        name: String,
239        /// A .zmx or project file to take the lens from (with --lens), or a project file (with --block)
240        #[arg(long)]
241        from: PathBuf,
242        /// Lens number (from 1, counting only lenses; the .zmx or project split in lens mode)
243        #[arg(long)]
244        lens: Option<usize>,
245        /// Project block ids (two give the range between them in the top-level list; surface table changes in the blocks' surface_edits are baked in)
246        #[arg(long, num_args = 1)]
247        block: Vec<String>,
248        /// Folders to search for glass catalogs (more than one allowed)
249        #[arg(long = "glass-dir")]
250        glass_dir: Vec<PathBuf>,
251        /// Lens catalogs to search for the project's catalog lenses (same as info, etc.)
252        #[arg(long = "lens-catalog")]
253        lens_catalog: Vec<PathBuf>,
254        /// .zmx multi-configuration number
255        #[arg(long, default_value_t = 1)]
256        cfg: usize,
257        /// Description of the item
258        #[arg(long, default_value = "")]
259        description: String,
260        /// Replace an item of the same name
261        #[arg(long)]
262        replace: bool,
263        /// Output JSON
264        #[arg(long)]
265        json: bool,
266    },
267    /// Search catalog items
268    ///
269    /// Filter the items of lens catalogs (ZMF, .zmx, lensbench .json) by kind, maker, words and specs. Specs are the items' `specs` in .json plus those added by `overlay` and `url_template` in a .json of the same maker (efl, diameter and thickness can also be compared with the listed values)
270    CatalogSearch {
271        /// Lens catalogs (files or folders, more than one allowed)
272        #[arg(required = true)]
273        lens_catalog: Vec<PathBuf>,
274        /// Folders to search for glass catalogs (used to find lens focal lengths)
275        #[arg(long = "glass-dir")]
276        glass_dir: Vec<PathBuf>,
277        /// Item kinds (lens, mirror, splitter, polarizer, waveplate, window, filter, prism, other; more than one allowed)
278        #[arg(long, num_args = 1)]
279        kind: Vec<String>,
280        /// Maker (contains; case, spaces and symbols are ignored)
281        #[arg(long, default_value = "")]
282        vendor: String,
283        /// Words in the part number, description, tags or specs (separated by spaces, all must be present)
284        #[arg(long, default_value = "")]
285        text: String,
286        /// Spec conditions (more than one allowed, all must hold): `name` (present), `name=value` (numbers equal, range specs contain, strings contain), `name=a..b`, `name>=value`, `<=`, `>`, `<` (range specs by overlap). E.g. `wavelength_nm=633`, `extinction_ratio>=1000`
287        #[arg(long, num_args = 1)]
288        spec: Vec<String>,
289        /// Only mechanical parts (tubes, mounts, cage plates) that hold an element of diameter [mm]: holding diameter at least the diameter and no more than 0.25 mm larger
290        #[arg(long)]
291        fits: Option<f64>,
292        /// List the specs with fixed names
293        #[arg(long)]
294        list_specs: bool,
295        /// Output JSON
296        #[arg(long)]
297        json: bool,
298    },
299    /// Measure an item's STEP (.step, .stp)
300    ///
301    /// Thickness and diameter; glass and frame (`frame`) for mounted items; mechanical parts without glass (tubes, cage plates, mounts) as a whole frame (`mech`; `frame` with the bore, length, outer diameter, threads, rod spacing and the element held)
302    CatalogStep {
303        /// STEP files to measure (.step, .stp)
304        #[arg(required = true)]
305        files: Vec<PathBuf>,
306        /// Output JSON
307        #[arg(long)]
308        json: bool,
309    },
310    /// Fetch one detailed STEP of an item from its official source (the item's `cad.step`) and put it in the cache
311    ///
312    /// From the second time the cache is used. The fetched STEP is measured like catalog-step and differences from the catalog's simple outline (`mech` length, outer diameter and shape) are shown
313    CadStep {
314        /// User catalog
315        #[arg(long)]
316        catalog: PathBuf,
317        /// Name of the item
318        #[arg(long)]
319        item: String,
320        /// Cache folder (if omitted, the environment variable LENSBENCH_CAD_CACHE, otherwise lensbench/cad in the OS settings location)
321        #[arg(long)]
322        cache: Option<PathBuf>,
323        /// Output JSON
324        #[arg(long)]
325        json: bool,
326    },
327    /// List the items of a user catalog
328    CatalogList {
329        /// User catalog file
330        catalog: PathBuf,
331        /// Output JSON
332        #[arg(long)]
333        json: bool,
334    },
335    /// List the coatings of the surfaces
336    ///
337    /// Interfaces (coating|medium before|medium after) of all configurations and how they are handled. Also shows the interfaces that need a measured table (encrypted coatings, etc.)
338    Coatings(coat_cmd::CoatingsArgs),
339    /// Find the kinks along wavelength (nodes of the dispersion tables of the coating materials) from measured tables (LBCT)
340    ///
341    /// Measure the wavelength grid about 4 times finer than the grid chosen from the coating thickness
342    // 保守の道具は一覧の最後に
343    #[command(display_order = 900)]
344    CoatKinks {
345        /// Measured tables (LBCT format, more than one allowed)
346        tables: Vec<PathBuf>,
347        /// KEYs to check (can be given more than once; by default the transmission from air and the mirror KEYs; on the glass side the residual is large at high β and detection is weak)
348        #[arg(long)]
349        key: Vec<String>,
350        /// Smallest score to take as a kink candidate (how many times the median residual of a smooth fit). Lower finds weaker kinks
351        #[arg(long, default_value_t = 100.0)]
352        min_score: f64,
353        /// Output JSON
354        #[arg(long)]
355        json: bool,
356    },
357    /// Write the layout (section or 3D) and rays
358    ///
359    /// The format is chosen by the --out extension: 2D svg, png or dxf; 3D gltf, glb, obj or stl; step (stp) for CAD
360    Layout {
361        #[command(flatten)]
362        c: Common,
363        #[command(flatten)]
364        l: Box<LayoutArgs>,
365        /// Files to write (more than one allowed)
366        #[arg(long, short, required = true)]
367        out: Vec<PathBuf>,
368        /// 2D projection plane (yz or xz)
369        #[arg(long, default_value = "yz")]
370        plane: d2::Plane,
371        /// PNG width [px]
372        #[arg(long, default_value_t = D2.width)]
373        width: u32,
374        /// Number of divisions around (3D) and of surface lines (2D)
375        #[arg(long, default_value_t = D2.segments)]
376        segments: usize,
377        /// Number of radial divisions (3D)
378        #[arg(long, default_value_t = D3.rings)]
379        rings: usize,
380        /// Radius of the ray tubes [mm] (3D; for STL, 0.1% of the scene size if omitted)
381        #[arg(long)]
382        tube: Option<f64>,
383        /// Draw mechanical parts with the detailed shape of their fetched STEP (3D glTF, OBJ, STL and STEP; parts with no STEP in the cache get the simple outline; fetch STEPs with lensbench cad-step)
384        #[arg(long)]
385        mech_detail: bool,
386    },
387    /// Make an encrypted coating model (LBCM 2) from measured tables (LBCT) taken with a set of model glasses
388    // 保守の道具は一覧の最後に
389    #[command(display_order = 900)]
390    CoatModel(coat_cmd::CoatModelArgs),
391    /// Make a coating model (LBCM) smaller
392    ///
393    /// Write binary (LBCM 3: values packed as integers in steps of 1e-9, 1e-12 for mirrors; LBCM 4 when a model has ORDER or values over 1e8). Read the same as LBCM 2 (text)
394    // 保守の道具は一覧の最後に
395    #[command(display_order = 900)]
396    CoatCompact {
397        /// Original model (LBCM 2, 3 or 4)
398        model: PathBuf,
399        /// Model to write (LBCM 3 or 4)
400        #[arg(long, short)]
401        out: PathBuf,
402        /// Output JSON
403        #[arg(long)]
404        json: bool,
405    },
406    /// Make a coating model (LBCM 4) from the layers of a coating in a coating file, without showing the layers
407    ///
408    /// Computes the characteristic matrices on a grid uniform in 1/λ and β², made finer until the coefficients between the grid points differ by less than --tol. For thick multilayers (tens to hundreds of layers) that the measured models can't hold
409    // 保守の道具は一覧の最後に
410    #[command(display_order = 900)]
411    CoatFromLayers(coat_cmd::CoatFromLayersArgs),
412    /// Fit a multilayer to a spectral curve (reflectance, transmittance) and write an approximate coating (`.lbcs`, the coating file format)
413    ///
414    /// The curves are CSV (columns wl_um or wl_nm, angle_deg, pol (s, p, avg), quantity (R, T), value or value_pct, weight; angle_deg, pol, quantity and weight default to 0, avg, R and 1). Put in a coating file folder, it is used by the coating name
415    CoatDesign {
416        /// Curve CSVs (more than one allowed)
417        targets: Vec<PathBuf>,
418        /// Coating name (the COAT name to write)
419        #[arg(long)]
420        name: String,
421        /// Materials (repeated from the outside, e.g. MGF2,TA2O5): MATE of a coating file, or glasses of a glass catalog
422        #[arg(long, value_delimiter = ',')]
423        materials: Vec<String>,
424        /// Substrate: an index, or a MATE or glass name of a coating file
425        #[arg(long)]
426        substrate: String,
427        /// Coating files to search for materials (COATING.DAT format)
428        #[arg(long = "coating-file")]
429        coating_file: Option<PathBuf>,
430        /// Folders to search for glass catalogs (more than one allowed)
431        #[arg(long = "glass-dir")]
432        glass_dir: Vec<PathBuf>,
433        /// Numbers of layers to try (e.g. 1..12)
434        #[arg(long, default_value = "1..12")]
435        layers: String,
436        /// Number of starting points per number of layers
437        #[arg(long, default_value_t = 20)]
438        starts: usize,
439        /// Maximum layer thickness [µm]
440        #[arg(long = "d-max", default_value_t = 0.6)]
441        d_max: f64,
442        /// Choose the fewest layers within (1 + slack) times the best RMS
443        #[arg(long, default_value_t = 0.1)]
444        slack: f64,
445        /// Approximate coating to write (.lbcs)
446        #[arg(long, short)]
447        out: Option<PathBuf>,
448        /// Output JSON
449        #[arg(long)]
450        json: bool,
451    },
452    /// Keep the system loaded and wait, repeating system changes and analyses over JSON-RPC from outside (127.0.0.1 only by default)
453    ///
454    /// Steps and format: docs/serve.md
455    Serve(serve::ServeArgs),
456    /// Watch the system file and run the analysis and write the result each time it changes
457    ///
458    /// Example: lensbench watch -- spot sys.zmx --json --save out.json
459    Watch(watch::WatchArgs),
460    /// Run a Python script without the GUI (starts an outside Python and passes glasses, coatings, thread count and output folder)
461    ///
462    /// Example: lensbench run --threads 4 --out result sweep.py -- --n 100. The exit code is the script's
463    Run(Box<run::RunArgs>),
464    /// List the bundled plugins (detectors, analyses) and describe their inputs and outputs
465    Plugins {
466        /// Print JSON
467        #[arg(long)]
468        json: bool,
469    },
470    /// Show the GPU that the Huygens PSF and MTF use with device auto (none means they compute on the CPU)
471    Devices {
472        /// Print JSON
473        #[arg(long)]
474        json: bool,
475    },
476    /// Check plugins and analysis parts against reference data
477    ///
478    /// Give a description (*.verify.json) or a folder containing them. Exit code 1 if any check fails
479    Verify {
480        /// Description file or folder (folders are searched all the way down for *.verify.json)
481        #[arg(required = true)]
482        paths: Vec<PathBuf>,
483        /// Skip checks with ci: false (run only locally)
484        #[arg(long)]
485        ci: bool,
486        /// Print JSON
487        #[arg(long)]
488        json: bool,
489    },
490    /// 解析の登録簿の解析([`analysis_cmd`]。clap の定義は [`cli_command`] が設定のスキーマから足す)
491    #[command(skip)]
492    Analysis(Box<analysis_cmd::AnalysisCmd>),
493}
494
495/// レイアウトの光線の選び方
496#[derive(Args)]
497struct LayoutArgs {
498    /// Field numbers (from 1, comma-separated; all fields if omitted)
499    #[arg(long)]
500    fields: Option<String>,
501    /// Wavelength numbers (from 1, comma-separated, all for every one; the primary wavelength if omitted)
502    #[arg(long)]
503    waves: Option<String>,
504    /// Ray pattern (y, x, cross, grid, ring). If omitted, y for 2D, ring for 3D and STEP (the chief ray and the pupil edge)
505    #[arg(long)]
506    fan: Option<scene::Fan>,
507    /// Number of rays (rays per direction for a fan or cross, the side for grid, the rays around for ring, plus the chief ray: n+1). If omitted, 7 for y, 12 for ring
508    #[arg(long)]
509    rays: Option<usize>,
510    /// First surface to draw (if omitted, the object surface when a finite object is near, otherwise surface 1)
511    #[arg(long)]
512    first: Option<usize>,
513    /// Last surface to draw (the image surface if omitted)
514    #[arg(long)]
515    last: Option<usize>,
516    /// Ray colors (field, wave, cfg; cfg is per overlaid configuration). If omitted, cfg when overlaying, otherwise field
517    #[arg(long)]
518    color: Option<d2::ColorBy>,
519    /// 重ね描きする構成
520    #[command(flatten)]
521    sel: ConfigSel,
522    /// Offset per configuration dx,dy,dz [mm] (configuration k is shifted k times; same as the OpticStudio layout offset; overlaid by default)
523    #[arg(long, allow_hyphen_values = true)]
524    offset: Option<String>,
525    /// Unfold along the light path (lay the sections after mirrors and BSs along the extension of the axis before the fold; 2D output only)
526    #[arg(long)]
527    unfold: bool,
528}
529
530impl LayoutArgs {
531    /// 光線の選び方(既定は serve の layout と同じ [`lensbench_engine::layout`])
532    fn ray_sel(&self) -> lensbench_core::Result<RaySel> {
533        let pick = |v: &Option<String>, what: &str| {
534            v.as_deref()
535                .map(|x| x.parse::<Pick>().map_err(|e| format!("{what} {e}")))
536                .transpose()
537        };
538        Ok(RaySel {
539            fields: pick(&self.fields, "field")?,
540            waves: pick(&self.waves, "wavelength")?,
541            fan: self.fan,
542            rays: self.rays,
543            first: self.first,
544            last: self.last,
545            unfold: self.unfold,
546        })
547    }
548}
549
550fn load(c: &Common) -> Result<System, AppError> {
551    Ok(lensbench_engine::load::load_file_noted(&c.spec())?)
552}
553
554/// カンマ区切りの数
555fn parse_list(s: &str, what: &str) -> Result<Vec<f64>, AppError> {
556    let v: Vec<f64> = s
557        .split(',')
558        .filter(|x| !x.trim().is_empty())
559        .map(|x| {
560            x.trim()
561                .parse::<f64>()
562                .map_err(|_| AppError::usage(format!("can't read the number of {what} ({x})")))
563        })
564        .collect::<Result<_, _>>()?;
565    if v.is_empty() {
566        return Err(AppError::usage(format!("{what} is empty")));
567    }
568    Ok(v)
569}
570
571/// 文字で出すときは長い表を省く(PSF・波面の格子など。--json・--save では全体)
572fn brief(v: &Value) -> Value {
573    /// 入れ子の配列も数えた要素の数
574    fn leaves(v: &Value) -> usize {
575        match v {
576            Value::Array(a) => a.iter().map(leaves).sum::<usize>().max(1),
577            _ => 1,
578        }
579    }
580    match v {
581        Value::Object(m) => Value::Object(m.iter().map(|(k, x)| (k.clone(), brief(x))).collect()),
582        Value::Array(a) if leaves(v) > 1000 => {
583            json!(lensbench_core::i18n::tr(&format!(
584                "({} rows, {} elements; use --json or --save for everything)",
585                a.len(),
586                leaves(v)
587            )))
588        }
589        Value::Array(a) => Value::Array(a.iter().map(brief).collect()),
590        _ => v.clone(),
591    }
592}
593
594impl Cmd {
595    /// 系のファイルを読む解析の共通の引数
596    fn common_mut(&mut self) -> Option<&mut Common> {
597        match self {
598            Cmd::Optimize { c, .. }
599            | Cmd::Tolerance { c, .. }
600            | Cmd::Convert { c, .. }
601            | Cmd::Layout { c, .. } => Some(c),
602            Cmd::Analysis(a) => Some(&mut a.c),
603            _ => None,
604        }
605    }
606
607    /// 結果を書き出すファイル(登録簿の解析は自分の形で書くので除く)
608    fn save(&self) -> Option<PathBuf> {
609        match self {
610            Cmd::Optimize { c, .. } | Cmd::Tolerance { c, .. } | Cmd::Layout { c, .. } => {
611                c.save.clone()
612            }
613            Cmd::Zoom(a) => a.save.clone(),
614            Cmd::Swap(a) => a.save.clone(),
615            _ => None,
616        }
617    }
618}
619
620thread_local! {
621    /// 一部が失敗したコマンド(上げ・取り・読みの一部の誤り)の説明。結果は出したうえで終了コード 1 にする
622    static PARTIAL_FAILURE: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
623}
624
625/// 一部が失敗したことを記す([`PARTIAL_FAILURE`]。CLI は結果を出した後に終了コード 1、serve は結果の JSON の errors で)
626fn partial_failure(msg: impl Into<String>) {
627    PARTIAL_FAILURE.with(|x| *x.borrow_mut() = Some(msg.into()));
628}
629
630fn run(cli: Cli) -> Result<(), AppError> {
631    match cli.cmd {
632        Cmd::Serve(a) => Ok(serve::serve(a, cli.threads)?),
633        Cmd::Watch(a) => watch::watch(a),
634        Cmd::Verify { paths, ci, json } => verify(&paths, ci, json),
635        cmd => {
636            let (json_out, out) = execute(cmd)?;
637            print_out(json_out, &out);
638            match PARTIAL_FAILURE.with(|x| x.borrow_mut().take()) {
639                Some(m) => Err(AppError::Failed(m)),
640                None => Ok(()),
641            }
642        }
643    }
644}
645
646/// 照合: 記述を回して表か JSON を出し、通らなければ誤り
647fn verify(paths: &[PathBuf], ci: bool, json_out: bool) -> Result<(), AppError> {
648    let opt = lensbench_verify::Options { ci_only: ci };
649    let reps = lensbench_verify::run_paths(paths, &builtin_plugins(), &opt)?;
650    if json_out {
651        let v: Vec<Value> = reps.iter().map(|r| r.to_json()).collect();
652        println!(
653            "{}",
654            serde_json::to_string_pretty(&json!({ "reports": v })).unwrap()
655        );
656    } else {
657        for r in &reps {
658            r.to_text().lines().for_each(text_out::say);
659        }
660    }
661    let bad = reps.iter().filter(|r| !r.passed()).count();
662    if reps.is_empty() {
663        return Err("no verify description (*.verify.json) found".into());
664    }
665    if bad > 0 {
666        return Err(format!("{bad} of {} checks fail", reps.len()).into());
667    }
668    Ok(())
669}
670
671/// catalog-search の表(メーカー・型番・種類・焦点距離・径・仕様・リンク)
672fn print_catalog_table(v: &Value) {
673    let rows = v["lenses"].as_array().cloned().unwrap_or_default();
674    let f = |x: &Value| {
675        x.as_f64()
676            .map(|x| format!("{x:.4}"))
677            .unwrap_or_else(|| "-".into())
678    };
679    text_out::say(&format!("{} item(s)", rows.len()));
680    for r in &rows {
681        let specs = r["specs"]
682            .as_object()
683            .map(|m| {
684                m.iter()
685                    .map(|(k, v)| match v {
686                        Value::String(t) => format!("{k}={t}"),
687                        o => format!("{k}={o}"),
688                    })
689                    .collect::<Vec<_>>()
690                    .join(" ")
691            })
692            .unwrap_or_default();
693        println!(
694            "{:<14} {:<16} {:<9} efl={:<10} d={:<8} {}{}{}",
695            r["vendor"].as_str().unwrap_or(""),
696            r["part"].as_str().unwrap_or(""),
697            lensbench_catalog::spec::row_category(r),
698            f(&r["efl"]),
699            f(&r["diameter"]),
700            specs,
701            r["url"]
702                .as_str()
703                .map(|u| format!(" {u}"))
704                .unwrap_or_default(),
705            r["error"]
706                .as_str()
707                .map(|e| lensbench_core::i18n::tr(&format!(" error: {e}")))
708                .unwrap_or_default(),
709        );
710    }
711}
712
713/// 結果を標準出力に出す
714fn print_out(json_out: bool, out: &Value) {
715    if out.is_null() {
716        return;
717    }
718    let mut w = std::io::BufWriter::new(std::io::stdout().lock());
719    let r = if json_out {
720        writeln!(w, "{}", serde_json::to_string_pretty(out).unwrap())
721    } else {
722        text_out::print_text(&mut w, &brief(&text_out::tolerance_brief(out)), 0)
723    };
724    // 読み手が先に閉じた(`| head` など)ときは黙って終える
725    let e = r.and_then(|_| w.flush()).err();
726    if let Some(e) = e.filter(|e| e.kind() != std::io::ErrorKind::BrokenPipe) {
727        let m = format!("lensbench: output: {e}");
728        eprintln!("{}", lensbench_core::i18n::tr(&m));
729    }
730}
731
732/// 解析のコマンドを 1 つ実行して結果を返す(--save があれば書き出す)。watch・ext::run_cli もこれを使う
733fn execute(cmd: Cmd) -> Result<(bool, Value), AppError> {
734    let e = AppError::from;
735    let save = cmd.save();
736    provenance::clear();
737    PARTIAL_FAILURE.with(|x| *x.borrow_mut() = None);
738    let (json_out, out): (bool, Value) = match cmd {
739        Cmd::Serve(_) | Cmd::Watch(_) | Cmd::Run(_) => {
740            return Err("serve, watch and run can't be nested".into())
741        }
742        // 記述の中のパス(基準データ・系)を serve の --root で確かめられないので、コマンドラインからだけ
743        Cmd::Verify { .. } => return Err("verify is only available from the command line".into()),
744        Cmd::Plugins { json } => (json, help_json::localize_docs(plugins_json(), json)),
745        Cmd::Devices { json } => (
746            json,
747            serde_json::json!({
748                "gpu_support": lensbench_analysis::huygens::GPU_SUPPORT,
749                "gpu": lensbench_analysis::huygens::gpu_name(),
750            }),
751        ),
752        Cmd::Analysis(a) => {
753            let s = load(&a.c)?;
754            let def = analyses()
755                .get(&a.name)
756                .cloned()
757                .ok_or_else(|| format!("no analysis {}", a.name))?;
758            let (out, to_save) = def
759                .run_save(
760                    &lensbench_analysis::Cx {
761                        system: &s,
762                        source: Some(&lensbench_engine::source::FileSource::new(
763                            &a.c.spec(),
764                            None,
765                        )),
766                    },
767                    &a.params,
768                    a.c.save.as_deref(),
769                )
770                .map_err(e)?;
771            if let (Some(p), Some(v)) = (&a.c.save, &to_save) {
772                save_value(p, v).map_err(AppError::io)?;
773            }
774            // 注意は結果の warnings・notes にも入る。コマンドラインでは標準エラーにも出す(serve は serve_analyze を通る)
775            for k in ["warnings", "notes"] {
776                for w in out[k].as_array().into_iter().flatten() {
777                    if let Some(w) = w.as_str() {
778                        eprintln!("{}", lensbench_core::i18n::warning(w));
779                    }
780                }
781            }
782            (a.c.json, out)
783        }
784        Cmd::Zoom(a) => (a.json, search_cmd::zoom(&a)?),
785        Cmd::Swap(a) => (a.json, search_cmd::swap(&a)?),
786        Cmd::Convert { c, out } => {
787            let s = load(&c)?;
788            let zmx = out
789                .extension()
790                .is_some_and(|x| x.eq_ignore_ascii_case("zmx"));
791            if zmx {
792                warn_notes(zmx_write::save(&out, &s).map_err(e)?);
793            } else {
794                lensbench_project::sysfile::save(&out, &s, &[])?;
795                warn_notes(lensbench_project::sysfile::save_notes(&s));
796            }
797            (
798                c.json,
799                json!({
800                    "written": out.display().to_string(),
801                    "lensbench": lensbench_core::VERSION,
802                    "system_hash": lensbench_project::sysfile::system_hash(&s)?,
803                }),
804            )
805        }
806        Cmd::MakeThermal(a) => (a.c.json, thermal_cmd::make_thermal(&a)?),
807        Cmd::Zmx { c, sel, out } => {
808            let systems = overlay_systems(&c, &sel)?;
809            let v: Vec<System> = systems.iter().map(|x| x.1.clone()).collect();
810            zmx_write::save_configs(&out, &v).map_err(e)?;
811            (
812                c.json,
813                json!({
814                    "file": out.display().to_string(),
815                    "configs": systems.iter().map(|x| x.0.clone()).collect::<Vec<_>>(),
816                }),
817            )
818        }
819        Cmd::ZmxBeams { c, cfgs, out } => {
820            let sel = ConfigSel {
821                cfgs: Some(cfgs),
822                ..Default::default()
823            };
824            let systems = overlay_systems(&c, &sel)?;
825            let v: Vec<System> = systems.iter().map(|x| x.1.clone()).collect();
826            let env = lensbench_project::Env {
827                step_files: None,
828                base: out.parent().map(|x| x.to_path_buf()).unwrap_or_default(),
829                glass_dirs: c.glass_dir.clone(),
830                catalog: None,
831            };
832            let p = lensbench_project::zmx_beams(&v, &c.file.display().to_string(), &env)?;
833            let txt = serde_json::to_string_pretty(&p).unwrap_or_default();
834            std::fs::write(&out, txt + "\n").map_err(AppError::io_at(&out))?;
835            (
836                c.json,
837                json!({
838                    "written": out.display().to_string(),
839                    "beams": p["beams"].as_array().map(|b| b.iter().map(|x| json!({"name": x["name"], "path": x["path"]})).collect::<Vec<_>>()),
840                }),
841            )
842        }
843        Cmd::Layout {
844            c,
845            l,
846            out,
847            plane,
848            width,
849            segments,
850            rings,
851            tube,
852            mech_detail,
853        } => {
854            let systems = overlay_systems(&c, &l.sel)?;
855            let offset = match &l.offset {
856                None => [0.0; 3],
857                Some(v) => {
858                    layout::offset(&parse_list(v, "--offset")?).map_err(AppError::usage_of)?
859                }
860            };
861            let draw = Draw {
862                plane,
863                color: l.color,
864                width: Some(width),
865                segments: Some(segments),
866                rings: Some(rings),
867                tube,
868                mech_detail: mech_detail.then(lensbench_cad::detail::details).flatten(),
869            };
870            let (o2, o3) = draw
871                .options(l.sel.overlay().any())
872                .map_err(AppError::usage_of)?;
873            let rsel = l.ray_sel()?;
874            // 拡張子を先に確かめ、2D 用と 3D 用の場面を要るものだけ作る
875            let fmts = out
876                .iter()
877                .map(|p| {
878                    lensbench_export::LayoutFormat::from_path(p).ok_or_else(|| {
879                        AppError::usage(format!(
880                            "{}: the extension must be svg, png, dxf, gltf, glb, obj, stl, step or stp",
881                            p.display()
882                        ))
883                    })
884                })
885                .collect::<Result<Vec<_>, AppError>>()?;
886            if l.unfold && fmts.iter().any(|f| !f.is_2d()) {
887                return Err(AppError::usage("--unfold is only for 2D (svg, png, dxf)"));
888            }
889            let mut scenes: [Option<scene::Scene>; 2] = [None, None];
890            for f in &fmts {
891                let k = usize::from(!f.is_2d());
892                if scenes[k].is_none() {
893                    let mut parts = Vec::new();
894                    // 重ね描きでは描き始める面をそろえる(物体面から描けない構成があれば全部面 1 から)
895                    let first0 = (l.first.is_none()
896                        && systems.iter().any(|x| scene::auto_first(&x.1) != 0))
897                    .then_some(1);
898                    for (name, sy) in &systems {
899                        let view = match (f.is_2d(), plane) {
900                            (false, _) => View::D3,
901                            (true, d2::Plane::XZ) => View::XZ,
902                            (true, d2::Plane::YZ) => View::YZ,
903                        };
904                        let mut so = rsel.options(sy, view).map_err(e)?;
905                        so.first = so.first.or(first0);
906                        let sc = scene::build(sy, &so).map_err(|x| {
907                            if name.is_empty() {
908                                e(x)
909                            } else {
910                                AppError::Core(x.at(name))
911                            }
912                        })?;
913                        parts.push((name.clone(), sc));
914                    }
915                    scenes[k] = Some(scene::overlay(parts, offset).map_err(e)?);
916                }
917            }
918            let mut written = Vec::new();
919            for (p, f) in out.iter().zip(&fmts) {
920                let sc = scenes[usize::from(!f.is_2d())].as_ref().unwrap();
921                let w = lensbench_export::write_layout(p, sc, &o2, &o3)?;
922                let mut row = json!({ "file": p.display().to_string(), "format": format!("{f:?}").to_lowercase() });
923                // 写した品の STEP の長さを直せなかった実体など
924                if !w.notes.is_empty() {
925                    row["notes"] = json!(w.notes);
926                }
927                written.push(row);
928            }
929            let sc = scenes.iter().flatten().next().unwrap();
930            let (lo, hi) = sc.bounds();
931            (
932                c.json,
933                json!({
934                    "written": written,
935                    "configs": sc.configs,
936                    "solids": sc.solids.iter().map(|x| x.name.clone()).collect::<Vec<_>>(),
937                    "surfaces": sc.plates.iter().map(|x| x.name.clone()).collect::<Vec<_>>(),
938                    "mechanics": sc.mechs.iter().map(|x| x.name.clone()).collect::<Vec<_>>(),
939                    "rays_2d": scenes[0].as_ref().map(|x| x.rays.len()),
940                    "rays_3d": scenes[1].as_ref().map(|x| x.rays.len()),
941                    "bounds_mm": [lo, hi],
942                }),
943            )
944        }
945        Cmd::Optimize {
946            c,
947            vars,
948            merit,
949            terms,
950            terms_file,
951            zmx_merit,
952            reference,
953            rings,
954            iters,
955            jac,
956            dls,
957            search,
958            out,
959            sel,
960        } => {
961            let (mut systems, mut spans) = config_sel::optimize_systems(&c, &sel)?;
962            let s = systems[0].clone();
963            let mut specs: Vec<Value> = Vec::new();
964            let mut merit = merit;
965            let mut zmx_rows = Vec::new();
966            if zmx_merit {
967                let z = zmx_merit::terms(&c, &s, out.is_some())?;
968                specs.extend(z.terms);
969                if !z.systems.is_empty() {
970                    (systems, spans) = (z.systems, Vec::new());
971                }
972                zmx_rows = z.rows;
973                merit = Merit::None;
974            }
975            let n_zmx = specs.len();
976            for t in &terms {
977                specs.push(
978                    serde_json::from_str(t)
979                        .map_err(|x| AppError::usage(format!("--term {t}: {x}")))?,
980                );
981            }
982            if let Some(f) = &terms_file {
983                let txt = lensbench_core::vfs::read_to_string(f).map_err(AppError::io_at(f))?;
984                let v: Value = serde_json::from_str(&txt)
985                    .map_err(|x| AppError::usage(format!("{}: {x}", f.display())))?;
986                match v {
987                    Value::Array(a) => specs.extend(a),
988                    v => specs.push(v),
989                }
990            }
991            // serve の中(--root・--allow-remote)なら zplm の file・macro_dirs の場所を確かめる
992            for v in specs.iter_mut() {
993                lensbench_engine::Files::Any.check_terms(v)?;
994            }
995            let mut op = OptimizeParams {
996                vars: VarSpec::parse_all(&vars).map_err(AppError::usage_of)?,
997                merit,
998                terms: specs,
999                reference,
1000                rings,
1001                iters,
1002                jac,
1003                qr: dls.qr,
1004                gtol: dls.gtol,
1005                active_set: dls.active_set,
1006                stopped_as_vignetted: dls.stopped_as_vignetted,
1007                ..OptimizeParams::default()
1008            };
1009            search.fill(&mut op).map_err(AppError::usage)?;
1010            let (p, n_default) = op.problem_with(systems, &spans).map_err(e)?;
1011            p.check().map_err(e)?;
1012            let run = progress::with(c.json, || op.run_in(&p, &c.glass_dir)).map_err(e)?;
1013            let r = &run.result;
1014            if let Some(path) = &out {
1015                let rows = zmx_merit::rows_to_write(zmx_rows, &op.terms[n_zmx..], &r.systems);
1016                warn_notes(zmx_write::save_with_merit(path, &r.systems[0], &rows).map_err(e)?);
1017            }
1018            let stop = r.stop.as_str();
1019            let vs = search_cmd::vars_json(&op.var_names(&p), &p, &run);
1020            if let Some(n) = &r.note {
1021                eprintln!("{}", lensbench_core::i18n::warning(n));
1022            }
1023            // 足した項の値(最適化の前と後)
1024            let tv0 = p.term_values(&r.x0).map_err(e)?;
1025            let tv = run.problem.term_values(&r.x).map_err(e)?;
1026            let ts: Vec<Value> = op
1027                .terms
1028                .iter()
1029                .enumerate()
1030                .map(|(i, v)| json!({ "term": v, "value0": tv0[n_default + i].value(), "value": tv[n_default + i].value(), "value_kind": tv[n_default + i].kind_name() }))
1031                .collect();
1032            let mut out_v = json!({
1033                "merit": merit.as_str(), "merit0": r.merit0, "merit_final": r.merit, "iterations": r.iterations,
1034                "evals": r.evals, "stop": stop, "note": r.note, "vars": vs, "terms": ts, "history": r.history,
1035            });
1036            search_cmd::add_search_json(&run, &mut out_v);
1037            (c.json, out_v)
1038        }
1039        Cmd::Tolerance {
1040            c,
1041            spec,
1042            set,
1043            trials,
1044            seed,
1045            out,
1046            comp_csv,
1047            results,
1048            no_resume,
1049        } => {
1050            let s = load(&c)?;
1051            let mut v = match &spec {
1052                Some(f) => {
1053                    let txt = lensbench_core::vfs::read_to_string(f).map_err(AppError::io_at(f))?;
1054                    serde_json::from_str::<Value>(&txt)
1055                        .map_err(|x| AppError::usage(format!("{}: {x}", f.display())))?
1056                }
1057                None => json!({}),
1058            };
1059            for t in &set {
1060                let o: Value = serde_json::from_str(t)
1061                    .map_err(|x| AppError::usage(format!("--set {t}: {x}")))?;
1062                let Value::Object(o) = o else {
1063                    return Err(AppError::usage(format!("--set {t} must be an object")));
1064                };
1065                let m = v.as_object_mut().ok_or("settings must be an object")?;
1066                m.extend(o);
1067            }
1068            if let Some(n) = trials {
1069                v["trials"] = json!(n);
1070            }
1071            if let Some(n) = seed {
1072                v["seed"] = json!(n);
1073            }
1074            if let Some(t) = v.get_mut("terms") {
1075                lensbench_engine::Files::Any.check_terms(t)?;
1076            }
1077            let (vendors, reversed) = lensbench_engine::load::tolerance_vendors(&c.spec());
1078            let ms =
1079                lensbench_design::tolerance::spec_from_json_with(&v, vec![s], &vendors, &reversed)?;
1080            let oo = lensbench_design::tolerance::out_opts(&v)?;
1081            let header = match &results {
1082                Some(_) => lensbench_design::tolerance::runs_header(
1083                    &v,
1084                    &ms.problem.configs,
1085                    &vendors,
1086                    &reversed,
1087                )?,
1088                None => String::new(),
1089            };
1090            let ro = lensbench_runs::RunOpts {
1091                out: results.as_deref(),
1092                header,
1093                resume: !no_resume,
1094                ..Default::default()
1095            };
1096            let run = || progress::with(c.json, || lensbench_design::montecarlo::run_to(&ms, &ro));
1097            let r = match oo.threads {
1098                Some(t) => lensbench_core::with_threads(Some(t), run),
1099                None => run(),
1100            }
1101            .map_err(e)?;
1102            if let Some(path) = &out {
1103                let worst = r
1104                    .trials
1105                    .iter()
1106                    .filter_map(|t| t.eval.as_ref().map(|x| (x.merit, t)))
1107                    .max_by(|a, b| a.0.total_cmp(&b.0));
1108                let Some((_, t)) = worst else {
1109                    return Err("--out: no trial could be traced".into());
1110                };
1111                let cs = lensbench_design::montecarlo::perturbed(&ms, &t.deltas).map_err(e)?;
1112                let mut p = ms.problem.clone();
1113                p.configs = cs;
1114                let x = &t.eval.as_ref().unwrap().comp;
1115                let sys = p.systems(x).map_err(e)?;
1116                // .json は系ファイル(屈折率のずれ dn・disp も書ける)、ほかは .zmx
1117                if path
1118                    .extension()
1119                    .is_some_and(|x| x.eq_ignore_ascii_case("json"))
1120                {
1121                    lensbench_project::sysfile::save(path, &sys[0], &[])?;
1122                    warn_notes(lensbench_project::sysfile::save_notes(&sys[0]));
1123                } else {
1124                    warn_notes(
1125                        zmx_write::save(path, &sys[0])
1126                            .map_err(|x| format!("--out: {x} (write a .json system file)"))?,
1127                    );
1128                }
1129            }
1130            let out = lensbench_design::tolerance::result_json(&ms, &r, &oo);
1131            if let Some(path) = &comp_csv {
1132                let csv = lensbench_design::tolerance::compensators_csv(&out)?;
1133                lensbench_core::vfs::write(path, csv).map_err(AppError::io_at(path))?;
1134            }
1135            (c.json, out)
1136        }
1137        Cmd::CatalogAdd {
1138            catalog,
1139            name,
1140            from,
1141            lens,
1142            block,
1143            glass_dir,
1144            lens_catalog,
1145            cfg,
1146            description,
1147            replace,
1148            json,
1149        } => {
1150            let cat = lensbench_project::UserCatalog::load_or_new(&catalog)?;
1151            if cat.items.contains_key(&name) && !replace {
1152                return Err(AppError::usage(format!(
1153                    "item {name} already exists (use --replace)"
1154                )));
1155            }
1156            if block.len() > 2 {
1157                return Err(AppError::usage(
1158                    "--block takes 1 or 2 values (the first and last of the range)",
1159                ));
1160            }
1161            let item = match (lens, block.is_empty()) {
1162                (Some(k), true) => {
1163                    let c = Common {
1164                        file: from.clone(),
1165                        glass_dir: glass_dir.clone(),
1166                        lens_catalog: lens_catalog.clone(),
1167                        cfg,
1168                        state: None,
1169                        path: None,
1170                        json,
1171                        save: None,
1172                        strict_macros: false,
1173                    };
1174                    lensbench_project::lens_item(&load(&c)?, k, &description)?
1175                }
1176                (None, false) => {
1177                    let txt = lensbench_core::vfs::read_to_string(&from)
1178                        .map_err(AppError::io_at(&from))?;
1179                    let p = lensbench_project::Project::from_json(&txt)?;
1180                    let cat = LensCatalog::load_registered(&lens_catalog)?;
1181                    let look = |v: &str, p: &str| cat.zmx(v, p);
1182                    let env = lensbench_project::Env {
1183                        step_files: None,
1184                        base: from.parent().map(|x| x.to_path_buf()).unwrap_or_default(),
1185                        glass_dirs: glass_dir.clone(),
1186                        catalog: Some(&look),
1187                    };
1188                    lensbench_project::blocks_item(&p, &env, &block, &description)?
1189                }
1190                _ => return Err(AppError::usage("give one of --lens and --block")),
1191            };
1192            // 読み直して足す(品を作る間にほかで足した品を消さない)
1193            let cat = lensbench_project::UserCatalog::update(&catalog, |cat| {
1194                if cat.items.contains_key(&name) && !replace {
1195                    return Err(format!("item {name} already exists (use --replace)").into());
1196                }
1197                cat.items.insert(name.clone(), item);
1198                Ok(())
1199            })?;
1200            (
1201                json,
1202                json!({ "catalog": catalog, "added": name, "items": cat.items.keys().collect::<Vec<_>>() }),
1203            )
1204        }
1205        Cmd::CatalogSearch {
1206            lens_catalog,
1207            glass_dir,
1208            kind,
1209            vendor,
1210            text,
1211            spec,
1212            fits,
1213            list_specs,
1214            json,
1215        } => {
1216            use lensbench_catalog::spec::{CatalogQuery, ItemKind, SpecFilter, SPEC_NAMES};
1217            if list_specs {
1218                let v: Vec<Value> = SPEC_NAMES
1219                    .iter()
1220                    .map(|(n, u, d)| json!({ "name": n, "unit": u, "doc": d }))
1221                    .collect();
1222                if !json {
1223                    for (n, u, d) in SPEC_NAMES {
1224                        println!("{n:<18} {u:<7} {d}");
1225                    }
1226                    return Ok((false, Value::Null));
1227                }
1228                return Ok((true, json!({ "specs": v })));
1229            }
1230            let q = CatalogQuery {
1231                kinds: kind
1232                    .iter()
1233                    .map(|k| {
1234                        ItemKind::parse(k)
1235                            .ok_or_else(|| AppError::usage(format!("--kind: unknown kind {k}")))
1236                    })
1237                    .collect::<Result<_, _>>()?,
1238                vendor,
1239                text,
1240                specs: spec
1241                    .iter()
1242                    .map(|s| SpecFilter::parse(s))
1243                    .collect::<Result<_, _>>()?,
1244                fits,
1245            };
1246            let v = lensbench_engine::browse::search(&lens_catalog, &glass_dir, &q)?;
1247            if !json {
1248                print_catalog_table(&v);
1249                return Ok((false, Value::Null));
1250            }
1251            (json, v)
1252        }
1253        Cmd::CatalogStep { files, json } => {
1254            let v: Vec<Value> = files
1255                .iter()
1256                .map(|f| {
1257                    let r = lensbench_core::vfs::read(f)
1258                        .map_err(lensbench_core::Error::io_at(f.display()))
1259                        .and_then(|b| {
1260                            lensbench_catalog::step::read_step(&String::from_utf8_lossy(&b))
1261                        });
1262                    match r {
1263                        Ok(s) => {
1264                            let mut v = serde_json::to_value(&s).unwrap_or(Value::Null);
1265                            v["file"] = json!(f.display().to_string());
1266                            v
1267                        }
1268                        Err(e) => {
1269                            json!({ "file": f.display().to_string(), "error": String::from(e) })
1270                        }
1271                    }
1272                })
1273                .collect();
1274            let bad = v.iter().filter(|x| x.get("error").is_some()).count();
1275            if bad > 0 {
1276                partial_failure(format!("{bad} STEP files could not be read"));
1277            }
1278            if !json {
1279                for x in &v {
1280                    println!("{}", x["file"].as_str().unwrap_or(""));
1281                    match x["error"].as_str() {
1282                        Some(e) => text_out::say(&format!("  error: {e}")),
1283                        None => {
1284                            let (t, d) = (&x["thickness"], &x["diameter"]);
1285                            text_out::say(&match x["frame"].is_null() {
1286                                true => format!("  thickness {t} mm, diameter {d}"),
1287                                false => format!("  thickness {t} mm, diameter {d}, with frame"),
1288                            });
1289                            text_out::say(&format!("  {}", x["note"].as_str().unwrap_or("")));
1290                        }
1291                    }
1292                }
1293                return Ok((false, Value::Null));
1294            }
1295            (true, json!({ "files": v }))
1296        }
1297        Cmd::CadStep {
1298            catalog,
1299            item,
1300            cache,
1301            json,
1302        } => {
1303            #[cfg(target_arch = "wasm32")]
1304            {
1305                let _ = (catalog, item, cache, json);
1306                return Err("cad-step is not available in the web version".into());
1307            }
1308            #[cfg(not(target_arch = "wasm32"))]
1309            {
1310                let cat = lensbench_project::UserCatalog::load(&catalog)?;
1311                let it = cat
1312                    .items
1313                    .get(&item)
1314                    .ok_or_else(|| format!("no item {item} in {}", catalog.display()))?;
1315                let dir = cache.unwrap_or_else(cad::default_cache_dir);
1316                let r = match cad::fetch_item(&dir, &item, it) {
1317                    Ok(r) => r,
1318                    Err(e) if it.url.is_empty() => return Err(e.into()),
1319                    Err(e) => return Err(format!("{e} (product page: {})", it.url).into()),
1320                };
1321                if !json {
1322                    let p = r.path.display();
1323                    text_out::say(&match r.source {
1324                        cad::Source::Cache => format!("{p} (cache)"),
1325                        cad::Source::Store => format!("{p} (from the store)"),
1326                        cad::Source::Vendor => p.to_string(),
1327                        cad::Source::VendorUploaded => format!("{p} (also uploaded to the store)"),
1328                    });
1329                    for n in &r.store_notes {
1330                        text_out::say(&format!("  store: {n}"));
1331                    }
1332                    if let Some(m) = &r.measured {
1333                        text_out::say(&format!("  {}", m.note));
1334                    }
1335                    if r.notes.is_empty() {
1336                        text_out::say("  matches the simple outline");
1337                    }
1338                    for n in &r.notes {
1339                        text_out::say(&format!("  mismatch: {n}"));
1340                    }
1341                    return Ok((false, Value::Null));
1342                }
1343                (true, r.to_json())
1344            }
1345        }
1346        Cmd::CatalogList { catalog, json } => {
1347            let cat = lensbench_project::UserCatalog::load(&catalog)?;
1348            let v: Vec<Value> = cat
1349                .items
1350                .iter()
1351                .map(|(k, it)| json!({ "name": k, "description": it.description, "glass_catalogs": it.glass_catalogs, "blocks": it.blocks().len() }))
1352                .collect();
1353            (json, json!({ "items": v }))
1354        }
1355        Cmd::Coatings(a) => (a.json, coatings(&a)?),
1356        Cmd::CoatKinks {
1357            tables,
1358            key,
1359            min_score,
1360            json,
1361        } => (json, coat_kinks(&tables, &key, min_score)?),
1362        Cmd::CoatModel(a) => (a.json, coat_model(&a)?),
1363        Cmd::CoatCompact { model, out, json } => (json, coat_compact(&model, &out)?),
1364        Cmd::CoatFromLayers(a) => (a.json, coat_from_layers(&a)?),
1365        Cmd::CoatDesign {
1366            targets,
1367            name,
1368            materials,
1369            substrate,
1370            coating_file,
1371            glass_dir,
1372            layers,
1373            starts,
1374            d_max,
1375            slack,
1376            out,
1377            json,
1378        } => (
1379            json,
1380            coat_design(&CoatDesignArgs {
1381                targets: &targets,
1382                name: &name,
1383                materials: &materials,
1384                substrate: &substrate,
1385                coating_file: coating_file.as_deref(),
1386                glass_dir: &glass_dir,
1387                layers: &layers,
1388                starts,
1389                d_max,
1390                slack,
1391                out: out.as_deref(),
1392            })?,
1393        ),
1394    };
1395    if let Some(p) = &save {
1396        save_value(p, &out).map_err(AppError::io)?;
1397    }
1398    Ok((json_out, out))
1399}
1400
1401struct CoatDesignArgs<'a> {
1402    targets: &'a [PathBuf],
1403    name: &'a str,
1404    materials: &'a [String],
1405    substrate: &'a str,
1406    coating_file: Option<&'a std::path::Path>,
1407    glass_dir: &'a [PathBuf],
1408    layers: &'a str,
1409    starts: usize,
1410    d_max: f64,
1411    slack: f64,
1412    out: Option<&'a std::path::Path>,
1413}
1414
1415/// コマンドラインの入口(`lensbench` の実行ファイル)。clap の定義に解析の登録簿のサブコマンド(拡張の `Extensions::analysis` で足した解析も)を足し、
1416/// help(英語が元)を表示の言語に訳したもの
1417fn cli_command() -> clap::Command {
1418    cli_command_with(|_| true)
1419}
1420
1421/// [`cli_command`] で、解析のサブコマンドの引数は `full` が真の名前だけ組む(ほかは名前と 1 行の説明だけ)。
1422/// 引数は設定のスキーマから作るので、起動のたびに全部組むと数 ms かかる(`--version`・`info` などにも)
1423fn cli_command_with(full: impl Fn(&str) -> bool) -> clap::Command {
1424    use clap::CommandFactory;
1425    let mut c = Cli::command().after_long_help(error::exit_code_help());
1426    for a in analyses().iter() {
1427        let m = a.meta();
1428        c = c.subcommand(if full(m.name) {
1429            analysis_cmd::command(a.as_ref())
1430        } else {
1431            clap::Command::new(m.name).about(m.about)
1432        });
1433    }
1434    let c = negative_numbers(c);
1435    // 英語の表示では訳さない(元が英語なので、木を回すだけ無駄になる)
1436    if lensbench_core::i18n::is_ja() {
1437        help_json::localize(c, &lensbench_core::i18n::translate_doc)
1438    } else {
1439        c
1440    }
1441}
1442
1443/// `--dist -5`・`--pmag -0.5` のような負の数を値として受ける(入れ子のサブコマンドも)
1444fn negative_numbers(c: clap::Command) -> clap::Command {
1445    c.allow_negative_numbers(true)
1446        .mut_subcommands(negative_numbers)
1447}
1448
1449/// 解析の登録簿(同梱の解析と、exe の入口で足した拡張の解析)
1450pub(crate) fn analyses() -> std::sync::Arc<lensbench_analysis::Analyses> {
1451    lensbench_engine::analyses()
1452}
1453
1454/// 引数を解釈する(解析の登録簿のサブコマンドも)
1455fn parse_cli<I, T>(argv: I) -> Result<Cli, clap::Error>
1456where
1457    I: IntoIterator<Item = T>,
1458    T: Into<std::ffi::OsString> + Clone,
1459{
1460    use clap::FromArgMatches;
1461    let argv: Vec<std::ffi::OsString> = argv.into_iter().map(Into::into).collect();
1462    // 引数のどこかに名前が出る解析だけ引数まで組む(`spot …`・`help spot`・`--threads 2 spot …`)。
1463    // 名前の出ない解析は呼ばれないので、名前と説明(`--help` の一覧・候補の提案に使う)だけでよい
1464    let named = |n: &str| argv.iter().any(|a| a.as_os_str() == n);
1465    let m = cli_command_with(named).try_get_matches_from(&argv)?;
1466    if let Some((name, sub)) = m.subcommand() {
1467        if let Some(a) = analyses().get(name).cloned() {
1468            let threads = m.try_get_one::<usize>("threads").ok().flatten().copied();
1469            let cmd = analysis_cmd::parse(a.as_ref(), sub).map_err(|x| {
1470                // clap が「error: 」を付けるので、種類の前置きを付けない文(訳す)
1471                let m = lensbench_core::i18n::tr(&String::from(x));
1472                cli_command_with(named).error(clap::error::ErrorKind::ValueValidation, m)
1473            })?;
1474            return Ok(Cli {
1475                threads,
1476                cmd: Cmd::Analysis(Box::new(cmd)),
1477            });
1478        }
1479    }
1480    Cli::from_arg_matches(&m)
1481}
1482
1483/// 拡張を入れてから CLI を動かす(外のクレートの exe の入口)
1484pub fn main_with(ext: lensbench_engine::Extensions) -> ExitCode {
1485    lensbench_lang::register();
1486    if let Err(e) = ext.install() {
1487        eprintln!(
1488            "lensbench: {}",
1489            lensbench_core::i18n::translate(&e.to_string())
1490        );
1491        return ExitCode::FAILURE;
1492    }
1493    main()
1494}
1495
1496pub fn main() -> ExitCode {
1497    error::quiet_broken_pipe();
1498    // 誤りの文・注意・help の訳の表(引数の誤りの訳にも使うので最初に)
1499    lensbench_lang::register();
1500    // 隠し: clap の定義を JSON で(マニュアルの CLI のページの元)
1501    let argv: Vec<std::ffi::OsString> = std::env::args_os().collect();
1502    if help_json::wants(&argv[1.min(argv.len())..]) {
1503        print_out(true, &help_json::help_json(cli_command()));
1504        return ExitCode::SUCCESS;
1505    }
1506    let cli = parse_cli(argv).unwrap_or_else(|e| clap_ja::fail(e));
1507    #[cfg(not(target_arch = "wasm32"))]
1508    coat_remote::install();
1509    // run はスレッド数を自分では使わず、起動する Python に渡す
1510    if let Cmd::Run(a) = &cli.cmd {
1511        return run::finish(a, cli.threads);
1512    }
1513    glass_dirs::init_from_env();
1514    match lensbench_core::with_threads(cli.threads, || run(cli)) {
1515        Ok(()) => ExitCode::SUCCESS,
1516        Err(e) => {
1517            error::report("lensbench", &e);
1518            ExitCode::from(e.exit_code())
1519        }
1520    }
1521}