indicatrix-cli 0.7.0

Headless command-line tool for Indicatrix faceting designs: info, solve, metrics, validate, optimize, retarget, sweep and export from scripts, with no window. Reads .indicatrix, .asc, .gem and .gcs; uses the same solver, retarget gate and optimizer as the desktop editor.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! `render` and `tilt-video`: render a job file written by the desktop app's render queue.
//!
//! The job is rendered by the very same executor the app runs
//! (`indicatrix_cut::gui::render_jobs::headless::run_job`), so a picture made from a script
//! is the one the app would have made, and a remote worker is used through the app's own
//! client. These two commands are the exception to "a command never prints or writes": they
//! write the picture or the frames themselves, and stream their progress to the writer they
//! are given (standard error for [`crate::run`], a buffer for [`crate::run_command_line`]).
//!
//! # Output
//!
//! Standard output is one line: the path written (the PNG; the MP4 or GIF; or the frame
//! folder when no video could be made). The rest goes through the progress writer:
//!
//! | Where | What |
//! |---|---|
//! | terminal | one line rewritten in place, and a line feed at the end |
//! | not a terminal | a still: one line each time the percentage crosses a multiple of 10; a video: one line per finished frame |
//! | always | `note: ...` lines, each distinct note once |
//!
//! `--quiet` turns the progress lines off, never the notes.

use crate::{
    args::{JobCommandKind, RenderJobArgs},
    outcome::{CliError, CommandResult, EXIT_DESIGN, EXIT_IO, EXIT_RENDER, Outcome},
};
use indicatrix_cut::gui::render_jobs::headless::{
    HeadlessOptions, RemoteEndpoint, gpu_compiled_in, run_job,
};
use indicatrix_render_jobs::{
    FailureKind, JobKind, JobOutcome, JobProgress, JobSink, LocalEngines, RenderJobFile, codec,
    run::format_progress_line,
};
use std::{
    io::Write,
    path::{Path, PathBuf},
    sync::atomic::AtomicBool,
};

/// Streams progress lines and notes to a writer, in the layout `render` and `tilt-video` use.
struct StreamSink<'a> {
    out: &'a mut dyn Write,
    word: &'static str,
    terminal: bool,
    quiet: bool,
    /// The width of the line a terminal is showing now, 0 when no line is open.
    open_len: usize,
    /// The tens of percent a plain still has already reported.
    last_decile: u32,
    /// The latest estimate, which a plain video line repeats.
    last_eta: Option<f64>,
    notes: Vec<String>,
}

impl<'a> StreamSink<'a> {
    fn new(out: &'a mut dyn Write, word: &'static str, terminal: bool, quiet: bool) -> Self {
        Self {
            out,
            word,
            terminal,
            quiet,
            open_len: 0,
            last_decile: 0,
            last_eta: None,
            notes: Vec::new(),
        }
    }

    /// Ends the line a terminal is rewriting, so the next text starts on a fresh one.
    fn end_line(&mut self) {
        if self.open_len > 0 {
            let _ = writeln!(self.out);
            self.open_len = 0;
        }
    }

    /// Prints `note: {note}` on its own line, unless this note was printed already.
    fn note(&mut self, note: &str) {
        if self.notes.iter().any(|seen| seen == note) {
            return;
        }
        self.end_line();
        let _ = writeln!(self.out, "note: {note}");
        self.notes.push(note.to_string());
    }

    /// Ends the open line and flushes.
    fn finish(&mut self) {
        self.end_line();
        let _ = self.out.flush();
    }
}

impl JobSink for StreamSink<'_> {
    fn progress(&mut self, progress: &JobProgress) {
        if let Some(note) = &progress.note {
            self.note(note);
        }
        self.last_eta = progress.eta_secs;
        if self.quiet {
            return;
        }
        if self.terminal {
            let line = format_progress_line(self.word, progress, true);
            let width = self.open_len;
            let _ = write!(self.out, "\r{line:<width$}");
            let _ = self.out.flush();
            self.open_len = line.chars().count();
        } else if progress.frames_total <= 1 {
            let decile = ((progress.fraction.clamp(0.0, 1.0) * 100.0).round() as u32) / 10;
            if decile > self.last_decile {
                self.last_decile = decile;
                let _ = writeln!(
                    self.out,
                    "{}",
                    format_progress_line(self.word, progress, false)
                );
            }
        }
    }

    fn frame_finished(&mut self, frames_done: u32, frames_total: u32) {
        if self.quiet || self.terminal || frames_total <= 1 {
            return;
        }
        let progress = JobProgress {
            frames_done,
            frames_total,
            fraction: frames_done as f32 / frames_total as f32,
            eta_secs: self.last_eta,
            note: None,
        };
        let _ = writeln!(
            self.out,
            "{}",
            format_progress_line(self.word, &progress, false)
        );
    }
}

/// Refuses a job file of the other kind, naming the command that runs it.
fn check_kind(kind: JobCommandKind, job: &RenderJobFile) -> Result<(), CliError> {
    match (kind, &job.kind) {
        (JobCommandKind::Render, JobKind::TiltVideo(_)) => Err(CliError::usage(
            "This job file holds a tilt video; run it with: indicatrix-cli tilt-video FILE",
        )),
        (JobCommandKind::TiltVideo, JobKind::Still(_)) => Err(CliError::usage(
            "This job file holds a still picture; run it with: indicatrix-cli render FILE",
        )),
        _ => Ok(()),
    }
}

/// The folder of the job file: relative paths in the job resolve against it.
fn job_folder(job: &Path) -> PathBuf {
    job.parent()
        .filter(|folder| !folder.as_os_str().is_empty())
        .map_or_else(|| PathBuf::from("."), Path::to_path_buf)
}

/// The exit code a failed run ends the process with.
const fn failure_code(kind: FailureKind) -> i32 {
    match kind {
        FailureKind::Input => EXIT_DESIGN,
        FailureKind::Output => EXIT_IO,
        FailureKind::Render => EXIT_RENDER,
    }
}

/// Renders the job file `args.job`, streaming progress to `progress`.
///
/// `terminal` says `progress` is a terminal, which rewrites one line instead of printing a
/// line per step.
///
/// # Errors
///
/// - [`CliError::io`] when the job file cannot be read;
/// - [`CliError::design`] when it is not a usable job file;
/// - [`CliError::usage`] when it holds the other kind of job;
/// - a [`EXIT_RENDER`] error when the render was stopped, and the exit code of the failure
///   (`EXIT_DESIGN`, `EXIT_IO` or `EXIT_RENDER`) when it failed.
pub fn run(args: &RenderJobArgs, progress: &mut dyn Write, terminal: bool) -> CommandResult {
    let text = std::fs::read_to_string(&args.job)
        .map_err(|e| CliError::io(format!("cannot read {}: {e}", args.job.display())))?;
    let job = codec::from_text(&text).map_err(|e| CliError::design(e.to_string()))?;
    check_kind(args.kind, &job)?;

    let remote = match (&args.remote, &args.cert_dir) {
        (Some(address), Some(cert_dir)) => Some(RemoteEndpoint {
            address: address.clone(),
            cert_dir: cert_dir.clone(),
        }),
        _ => None,
    };
    let options = HeadlessOptions {
        local: args.local,
        remote,
        compute: args.compute,
        transfer: args.transfer,
        contribute_local: args.contribute_local.then_some(true),
        output: args.out.clone(),
        restart_frames: args.restart,
    };
    // Ctrl+C is not trapped: a video's frames are written atomically, so the next run
    // continues from them.
    let cancel = AtomicBool::new(false);
    let mut sink = StreamSink::new(progress, args.kind.word(), terminal, args.quiet);
    if args.local != LocalEngines::Cpu && !gpu_compiled_in() {
        sink.note("this build has no GPU support; rendering on the CPU.");
    }
    let ended = run_job(&job, &job_folder(&args.job), &options, &cancel, &mut sink);
    sink.finish();

    match ended {
        JobOutcome::Done { result, note } => {
            let mut outcome = Outcome::text(format!("{}\n", result.display()));
            if let Some(note) = note {
                outcome = outcome.with_note(&format!("note: {note}"));
            }
            Ok(outcome.with_note(&format!("wrote {}", result.display())))
        }
        JobOutcome::Stopped { .. } => Err(CliError {
            code: EXIT_RENDER,
            message: "the render was stopped".to_string(),
        }),
        JobOutcome::Failed { kind, message, .. } => Err(CliError {
            code: failure_code(kind),
            message,
        }),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        outcome::{EXIT_OK, EXIT_USAGE},
        run_command_line, testing,
    };
    use indicatrix::{
        geometry::cuts::StandardGemCuts,
        optics::{materials::GemMaterial, raytracer::LightingPreset},
    };
    use indicatrix_net::{SceneState, scene::SceneEnvironment};
    use indicatrix_render_jobs::{
        ComputeChoice, JobColorSpace, StillJob, TiltVideoJob, TransferChoice,
        job::{DesignInfo, JOB_FORMAT_VERSION, JobCompute, OverlaySelection},
    };

    /// The smallest scene a job accepts: a round brilliant, 16 by 16, four bounces.
    fn tiny_scene() -> SceneState {
        SceneState {
            width: 16,
            height: 16,
            yaw: 0.4,
            pitch: 0.3,
            distance: 3.0,
            light_yaw: 0.85,
            light_pitch: 0.95,
            exposure: 1.0,
            max_bounces: 4,
            lighting_preset: LightingPreset::Daylight,
            material: GemMaterial::diamond(),
            planes: StandardGemCuts::standard_round_brilliant(),
            girdle_frosted: false,
            backdrop: 0.0,
            environment: SceneEnvironment::Studio,
            surface_glare: 1.0,
            tools: Vec::new(),
            fluorescence: indicatrix::optics::fluorescence::Fluorescence::default(),
            head_shadow_deg: 16.0,
        }
    }

    fn job_with(output: &Path, kind: JobKind) -> RenderJobFile {
        RenderJobFile {
            format: JOB_FORMAT_VERSION,
            token: "9f2c4a7d1e0b48c3a65d2f71c8e4b903".to_string(),
            label: "Test job".to_string(),
            created_at: 1_791_302_580,
            design: DesignInfo::default(),
            scene: tiny_scene(),
            hdr: None,
            compute: JobCompute {
                target: ComputeChoice::Local,
                transfer: TransferChoice::FullData,
                contribute_local: false,
            },
            output: output.to_string_lossy().into_owned(),
            kind,
        }
    }

    fn still_kind() -> JobKind {
        JobKind::Still(StillJob {
            samples_per_pixel: 2,
            color_space: JobColorSpace::Srgb,
            preset_label: String::new(),
        })
    }

    fn video_kind() -> JobKind {
        JobKind::TiltVideo(TiltVideoJob {
            axis_index: 0,
            start_deg: 0.0,
            end_deg: 1.0,
            step_deg: 1.0,
            total_frames: 2,
            fps: 2,
            samples_per_pixel: 1,
            color_space: JobColorSpace::Srgb,
            overlay: OverlaySelection::default(),
            curves: None,
            keep_frames: true,
            video_name: "tiny tilt".to_string(),
        })
    }

    /// A fresh, empty folder for one test.
    fn folder(name: &str) -> PathBuf {
        let folder = testing::temp_path(name);
        let _ = std::fs::remove_dir_all(&folder);
        std::fs::create_dir_all(&folder).expect("the test folder can be made");
        folder
    }

    fn write_job(folder: &Path, job: &RenderJobFile) -> String {
        let path = folder.join("tiny.job.json");
        std::fs::write(&path, codec::to_text(job).expect("the job encodes"))
            .expect("the job file can be written");
        path.to_string_lossy().into_owned()
    }

    fn run_words(parts: &[&str]) -> crate::Outcome {
        let args: Vec<String> = parts.iter().map(|part| (*part).to_string()).collect();
        run_command_line(&args)
    }

    #[test]
    fn a_still_job_renders_a_png_and_prints_its_path() {
        let folder = folder("render-job-still");
        let png = folder.join("out.png");
        let job = write_job(&folder, &job_with(&png, still_kind()));
        let outcome = run_words(&["render", &job, "--local", "cpu"]);
        assert_eq!(outcome.exit, EXIT_OK, "{}", outcome.stderr);
        assert!(png.is_file(), "the picture is on disk");
        assert_eq!(outcome.stdout, format!("{}\n", png.display()));
        assert!(
            outcome.stderr.contains(&format!("wrote {}", png.display())),
            "{}",
            outcome.stderr
        );
    }

    #[test]
    fn quiet_leaves_out_the_progress_lines() {
        let folder = folder("render-job-quiet");
        let png = folder.join("out.png");
        let job = write_job(&folder, &job_with(&png, still_kind()));
        let outcome = run_words(&["render", &job, "--local", "cpu", "--quiet"]);
        assert_eq!(outcome.exit, EXIT_OK, "{}", outcome.stderr);
        assert!(!outcome.stderr.contains("render:"), "{}", outcome.stderr);
        assert!(png.is_file());
    }

    #[test]
    fn a_still_file_under_tilt_video_is_a_command_line_mistake() {
        let folder = folder("render-job-wrong-kind");
        let job = write_job(&folder, &job_with(&folder.join("out.png"), still_kind()));
        let outcome = run_words(&["tilt-video", &job, "--local", "cpu"]);
        assert_eq!(outcome.exit, EXIT_USAGE, "{}", outcome.stderr);
        assert!(
            outcome.stderr.contains("indicatrix-cli render FILE"),
            "{}",
            outcome.stderr
        );

        let video = write_job(&folder, &job_with(&folder.join("frames"), video_kind()));
        let outcome = run_words(&["render", &video, "--local", "cpu"]);
        assert_eq!(outcome.exit, EXIT_USAGE, "{}", outcome.stderr);
        assert!(
            outcome.stderr.contains("indicatrix-cli tilt-video FILE"),
            "{}",
            outcome.stderr
        );
    }

    #[test]
    fn a_missing_job_file_is_exit_3() {
        let missing = testing::temp_path("render-job-no-such-folder").join("none.job.json");
        let outcome = run_words(&["render", &missing.to_string_lossy(), "--local", "cpu"]);
        assert_eq!(outcome.exit, EXIT_IO, "{}", outcome.stderr);
        assert!(
            outcome.stderr.starts_with("error: cannot read"),
            "{}",
            outcome.stderr
        );
    }

    #[test]
    fn a_job_file_of_a_newer_format_is_exit_2() {
        let folder = folder("render-job-newer");
        let job = job_with(&folder.join("out.png"), still_kind());
        let mut value: serde_json::Value =
            serde_json::from_str(&codec::to_text(&job).expect("the job encodes"))
                .expect("the text is JSON");
        value["format"] = serde_json::json!(99);
        let path = folder.join("newer.job.json");
        std::fs::write(&path, value.to_string()).expect("the job file can be written");
        let outcome = run_words(&["render", &path.to_string_lossy(), "--local", "cpu"]);
        assert_eq!(outcome.exit, EXIT_DESIGN, "{}", outcome.stderr);
        assert!(!folder.join("out.png").exists());
    }

    #[test]
    fn a_tilt_video_resumes_from_its_frames_and_restart_renders_them_again() {
        let folder = folder("render-job-video");
        let frames = folder.join("frames");
        let job = write_job(&folder, &job_with(&frames, video_kind()));

        let first = run_words(&["tilt-video", &job, "--local", "cpu"]);
        assert_eq!(first.exit, EXIT_OK, "{}", first.stderr);
        let video = first.stdout.trim().to_string();
        let extension = Path::new(&video)
            .extension()
            .map(std::ffi::OsStr::to_ascii_lowercase);
        assert!(
            extension.is_some_and(|extension| extension == "mp4" || extension == "gif"),
            "{}",
            first.stdout
        );
        assert!(
            first.stderr.contains("frame 1 of 2 done"),
            "{}",
            first.stderr
        );
        assert!(
            first.stderr.contains("frame 2 of 2 done"),
            "{}",
            first.stderr
        );

        std::fs::remove_file(&video).expect("the video was written");
        let second = run_words(&["tilt-video", &job, "--local", "cpu"]);
        assert_eq!(second.exit, EXIT_OK, "{}", second.stderr);
        assert!(
            !second.stderr.contains("frame 1 of 2 done"),
            "frame 1 is reused: {}",
            second.stderr
        );
        assert!(Path::new(&video).is_file(), "the video is made again");

        let third = run_words(&["tilt-video", &job, "--local", "cpu", "--restart"]);
        assert_eq!(third.exit, EXIT_OK, "{}", third.stderr);
        assert!(
            third.stderr.contains("frame 1 of 2 done"),
            "{}",
            third.stderr
        );
        assert!(
            third.stderr.contains("frame 2 of 2 done"),
            "{}",
            third.stderr
        );
    }

    #[test]
    fn the_sink_prints_plain_lines_per_ten_percent_and_each_note_once() {
        let mut buffer: Vec<u8> = Vec::new();
        {
            let mut sink = StreamSink::new(&mut buffer, "render", false, false);
            let at = |fraction: f32, note: Option<&str>| JobProgress {
                frames_done: 0,
                frames_total: 1,
                fraction,
                eta_secs: None,
                note: note.map(str::to_string),
            };
            sink.progress(&at(0.04, None));
            sink.progress(&at(0.12, Some("slow")));
            sink.progress(&at(0.15, Some("slow")));
            sink.progress(&at(0.4, None));
            sink.finish();
        }
        let text = String::from_utf8(buffer).expect("text");
        assert_eq!(text, "note: slow\nrender: 12%\nrender: 40%\n");
    }

    #[test]
    fn a_terminal_sink_rewrites_one_line_and_ends_it() {
        let mut buffer: Vec<u8> = Vec::new();
        {
            let mut sink = StreamSink::new(&mut buffer, "render", true, false);
            let at = |fraction: f32| JobProgress {
                frames_done: 0,
                frames_total: 1,
                fraction,
                eta_secs: None,
                note: None,
            };
            sink.progress(&at(0.5));
            sink.progress(&at(1.0));
            sink.finish();
        }
        let text = String::from_utf8(buffer).expect("text");
        assert_eq!(text, "\rrender  50%\rrender  100%\n");
    }
}