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
use std::f32;
use enum_set::EnumSet;
use linalg::{self, Vector};
use film::Colorf;
use bxdf::{self, BxDF, BxDFType};
use bxdf::fresnel::Fresnel;
use bxdf::microfacet::{MicrofacetDistribution};
#[derive(Copy, Clone)]
pub struct TorranceSparrow<'a> {
reflectance: Colorf,
fresnel: &'a Fresnel,
microfacet: &'a MicrofacetDistribution,
}
impl<'a> TorranceSparrow<'a> {
pub fn new(c: &Colorf, fresnel: &'a Fresnel, microfacet: &'a MicrofacetDistribution)
-> TorranceSparrow<'a> {
TorranceSparrow { reflectance: *c, fresnel: fresnel, microfacet: microfacet }
}
}
impl<'a> BxDF for TorranceSparrow<'a> {
fn bxdf_type(&self) -> EnumSet<BxDFType> {
let mut e = EnumSet::new();
e.insert(BxDFType::Glossy);
e.insert(BxDFType::Reflection);
e
}
fn eval(&self, w_o: &Vector, w_i: &Vector) -> Colorf {
let cos_to = f32::abs(bxdf::cos_theta(w_o));
let cos_ti = f32::abs(bxdf::cos_theta(w_i));
if cos_to == 0.0 || cos_ti == 0.0 {
return Colorf::new(0.0, 0.0, 0.0)
}
let mut w_h = *w_i + *w_o;
if w_h == Vector::broadcast(0.0) {
return Colorf::new(0.0, 0.0, 0.0)
}
w_h = w_h.normalized();
let d = self.microfacet.normal_distribution(&w_h);
let f = self.fresnel.fresnel(linalg::dot(w_i, &w_h));
let g = self.microfacet.shadowing_masking(w_i, w_o, &w_h);
(self.reflectance * f * d * g / (4.0 * cos_ti * cos_to))
}
fn sample(&self, w_o: &Vector, samples: &(f32, f32)) -> (Colorf, Vector, f32) {
if w_o.z == 0.0 {
return (Colorf::black(), Vector::broadcast(0.0), 0.0)
}
let mut w_h = self.microfacet.sample(w_o, samples);
if !bxdf::same_hemisphere(w_o, &w_h) {
w_h = -w_h;
}
let w_i = linalg::reflect(w_o, &w_h);
if !bxdf::same_hemisphere(w_o, &w_i) {
(Colorf::black(), Vector::broadcast(0.0), 0.0)
} else {
(self.eval(w_o, &w_i), w_i, self.pdf(w_o, &w_i))
}
}
fn pdf(&self, w_o: &Vector, w_i: &Vector) -> f32 {
if !bxdf::same_hemisphere(w_o, w_i) {
0.0
} else {
let w_h = (*w_o + *w_i).normalized();
let jacobian = 1.0 / (4.0 * f32::abs(linalg::dot(w_o, &w_h)));
self.microfacet.pdf(&w_h) * jacobian
}
}
}