-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
128 lines (123 loc) · 3.4 KB
/
main.rs
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
use clap::{Arg, Command};
use indicatif::ProgressBar;
use rrt::book2chap2::*;
use rrt::rng::*;
use rrt::threadpool::*;
use rrt::tracescene;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::{thread, time};
fn main() {
let arg_matches = Command::new("rrt")
.version("0.1.0")
.author("Jean-Francois Roy <[email protected]>")
.about("Ray Tracing In One Weekend")
.arg(
Arg::new("resolution")
.long("resolution")
.short('r')
.num_args(1)
.default_value("1200x800")
.help("output resolution in pixels"),
)
.arg(
Arg::new("samples")
.long("samples")
.short('s')
.num_args(1)
.default_value("10")
.help("samples per pixel"),
)
.arg(
Arg::new("seed")
.long("seed")
.short('e')
.num_args(1)
.default_value("0")
.help("rng seed"),
)
.arg(
Arg::new("random")
.long("random")
.short('m')
.help("use a random rng seed"),
)
.get_matches();
let (w, h) = match parse_resolution(arg_matches.get_one::<String>("resolution")) {
Some(v) => v,
None => {
eprintln!("invalid resolution");
return;
}
};
let spp = match arg_matches.get_one::<usize>("samples") {
Some(v) => *v,
None => {
eprintln!("invalid sample count");
return;
}
};
let mut rng: RttRng = if arg_matches.contains_id("random") {
RttRng::from_entropy()
} else {
match arg_matches.get_one::<u64>("seed") {
Some(v) => RttRng::seed_from_u64(*v),
None => {
eprintln!("invalid rng seed");
return;
}
}
};
eprintln!(
"Rendering {} x {} image using {} samples per pixel.",
w, h, spp
);
let pxcount = Arc::new(AtomicUsize::new(0));
let ui_pxcount = Arc::clone(&pxcount);
let ui_thread = thread::Builder::new()
.name("ui".to_string())
.spawn(move || {
let t = w * h;
let pb = ProgressBar::new((t) as u64);
loop {
let x = ui_pxcount.load(Ordering::Relaxed);
pb.set_position(x as u64);
thread::sleep(time::Duration::from_secs(1));
if x >= t {
break;
}
}
})
.unwrap();
let (scene, camera) = book2_chap2_scene(w, h, &mut rng);
let pool = init_pool_with_rng(rng);
let pixels = tracescene(w, h, spp, &scene, &camera, &pool, &pxcount);
ui_thread.join().unwrap();
image::save_buffer(
"o.ppm",
&pixels[..],
w as u32,
h as u32,
image::ColorType::Rgb8,
)
.unwrap()
}
fn parse_resolution(s: Option<&String>) -> Option<(usize, usize)> {
let v: Vec<&str> = s?.split('x').collect();
if v.len() != 2 {
return None;
}
let w = match v[0].parse::<usize>() {
Ok(n) => n,
Err(_) => {
return None;
}
};
let h = match v[1].parse::<usize>() {
Ok(n) => n,
Err(_) => {
return None;
}
};
Some((w, h))
}