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
// std
use std::borrow::Borrow;
use std::cell::Cell;
use std::sync::Arc;
// pbrt
// use crate::core::bssrdf::Bssrdf;
use crate::core::camera::Camera;
use crate::core::geometry::{vec3_abs_dot_nrmf, vec3_dot_nrmf};
use crate::core::geometry::{Bounds2i, Point2f, Ray, Vector3f};
use crate::core::integrator::uniform_sample_one_light;
use crate::core::interaction::{Interaction, MediumInteraction, SurfaceInteraction};
use crate::core::lightdistrib::create_light_sample_distribution;
use crate::core::lightdistrib::LightDistribution;
use crate::core::material::TransportMode;
use crate::core::pbrt::{Float, Spectrum};
use crate::core::reflection::BxdfType;
use crate::core::sampler::Sampler;
use crate::core::sampling::Distribution1D;
use crate::core::scene::Scene;

// see volpath.h

/// Accounts for scattering and attenuation from participating media
/// as well as scattering from surfaces - uses the render loop of a
/// [SamplerIntegrator](../../core/integrator/enum.SamplerIntegrator.html)
pub struct VolPathIntegrator {
    // inherited from SamplerIntegrator (see integrator.h)
    pub camera: Arc<Camera>,
    pub sampler: Box<Sampler>,
    pub pixel_bounds: Bounds2i,
    // see volpath.h
    pub max_depth: u32,
    pub rr_threshold: Float,           // 1.0
    pub light_sample_strategy: String, // "spatial"
    pub light_distribution: Option<Arc<LightDistribution>>,
}

impl VolPathIntegrator {
    pub fn new(
        max_depth: u32,
        camera: Arc<Camera>,
        sampler: Box<Sampler>,
        pixel_bounds: Bounds2i,
        rr_threshold: Float,
        light_sample_strategy: String,
    ) -> Self {
        VolPathIntegrator {
            camera,
            sampler,
            pixel_bounds,
            max_depth,
            rr_threshold,
            light_sample_strategy,
            light_distribution: None,
        }
    }
    pub fn preprocess(&mut self, scene: &Scene) {
        self.light_distribution =
            create_light_sample_distribution(self.light_sample_strategy.clone(), scene);
    }
    pub fn li(
        &self,
        r: &mut Ray,
        scene: &Scene,
        sampler: &mut Sampler,
        // arena: &mut Arena,
        _depth: i32,
    ) -> Spectrum {
        // TODO: ProfilePhase p(Prof::SamplerIntegratorLi);
        let mut l: Spectrum = Spectrum::default();
        let mut beta: Spectrum = Spectrum::new(1.0 as Float);
        let mut ray: Ray = Ray {
            o: r.o,
            d: r.d,
            t_max: Cell::new(r.t_max.get()),
            time: r.time,
            differential: r.differential,
            medium: r.medium.clone(),
        };
        let mut specular_bounce: bool = false;
        let mut bounces: u32 = 0_u32;
        // Added after book publication: etaScale tracks the
        // accumulated effect of radiance scaling due to rays passing
        // through refractive boundaries (see the derivation on p. 527
        // of the third edition). We track this value in order to
        // remove it from beta when we apply Russian roulette; this is
        // worthwhile, since it lets us sometimes avoid terminating
        // refracted rays that are about to be refracted back out of a
        // medium and thus have their beta value increased.
        let mut eta_scale: Float = 1.0;
        loop {
            let mut mi_opt: Option<MediumInteraction> = None;
            // intersect _ray_ with scene and store intersection in _isect_
            let mut isect: SurfaceInteraction = SurfaceInteraction::default();
            if scene.intersect(&mut ray, &mut isect) {
                // sample the participating medium, if present
                if let Some(ref medium) = ray.medium {
                    let (spectrum, option) = medium.sample(&ray, sampler);
                    beta *= spectrum;
                    if let Some(mi) = option {
                        mi_opt = Some(mi);
                    }
                }
                if beta.is_black() {
                    break;
                }
                // handle an interaction with a medium or a surface
                if let Some(mi) = mi_opt {
                    // terminate path if ray escaped or _maxDepth_ was reached
                    if bounces >= self.max_depth {
                        break;
                    }
                    let mi_p = mi.common.p;
                    // if mi.is_valid() {...}
                    if let Some(phase) = mi.clone().phase {
                        // TODO: ++volumeInteractions;
                        // handle scattering at point in medium for volumetric path tracer
                        if let Some(ref light_distribution) = self.light_distribution {
                            let distrib: Arc<Distribution1D> = light_distribution.lookup(&mi_p);
                            l += beta
                                * uniform_sample_one_light(
                                    &mi as &dyn Interaction,
                                    scene,
                                    sampler,
                                    true,
                                    Some(&distrib),
                                );
                            let mut wi: Vector3f = Vector3f::default();
                            phase.sample_p(&(-ray.d), &mut wi, sampler.get_2d());
                            ray = mi.spawn_ray(&wi);
                            specular_bounce = false;
                        }
                    }
                } else {
                    // TODO: ++surfaceInteractions;
                    // possibly add emitted light at intersection
                    if bounces == 0 || specular_bounce {
                        // add emitted light at path vertex
                        l += beta * isect.le(&-ray.d);
                    }
                    // terminate path if _maxDepth_ was reached
                    if bounces >= self.max_depth {
                        break;
                    }
                    // compute scattering functions and skip over medium boundaries
                    let mode: TransportMode = TransportMode::Radiance;
                    isect.compute_scattering_functions(&ray, true, mode);
                    if let Some(ref _bsdf) = isect.bsdf {
                        // we are fine (for below)
                    } else {
                        ray = isect.spawn_ray(&ray.d);
                        // bounces--;
                        continue;
                    }
                    if let Some(ref light_distribution) = self.light_distribution {
                        let light_distrib: Arc<Distribution1D> =
                            light_distribution.lookup(&isect.common.p);
                        // Sample illumination from lights to find
                        // attenuated path contribution.
                        let it: &SurfaceInteraction = isect.borrow();
                        l += beta
                            * uniform_sample_one_light(
                                it,
                                scene,
                                sampler,
                                true,
                                Some(&light_distrib),
                            );
                        if let Some(ref bsdf) = isect.bsdf {
                            // Sample BSDF to get new path direction
                            let wo: Vector3f = -ray.d;
                            let mut wi: Vector3f = Vector3f::default();
                            let mut pdf: Float = 0.0 as Float;
                            let bsdf_flags: u8 = BxdfType::BsdfAll as u8;
                            let mut sampled_type: u8 = u8::max_value(); // != 0
                            let f: Spectrum = bsdf.sample_f(
                                &wo,
                                &mut wi,
                                &sampler.get_2d(),
                                &mut pdf,
                                bsdf_flags,
                                &mut sampled_type,
                            );
                            if f.is_black() || pdf == 0.0 as Float {
                                break;
                            }
                            beta *= (f * vec3_abs_dot_nrmf(&wi, &isect.shading.n)) / pdf;
                            assert!(
                                !(beta.y().is_infinite()),
                                "[{:#?}, {:?}] = ({:#?} * dot({:#?}, {:#?})) / {:?}",
                                sampler.get_current_pixel(),
                                sampler.get_current_sample_number(),
                                f,
                                wi,
                                isect.shading.n,
                                pdf
                            );
                            specular_bounce = (sampled_type & BxdfType::BsdfSpecular as u8) != 0_u8;
                            if ((sampled_type & BxdfType::BsdfSpecular as u8) != 0_u8)
                                && ((sampled_type & BxdfType::BsdfTransmission as u8) != 0_u8)
                            {
                                let eta: Float = bsdf.eta;
                                // Update the term that tracks radiance
                                // scaling for refraction depending on
                                // whether the ray is entering or leaving
                                // the medium.
                                if vec3_dot_nrmf(&wo, &isect.common.n) > 0.0 as Float {
                                    eta_scale *= eta * eta;
                                } else {
                                    eta_scale *= 1.0 as Float / (eta * eta);
                                }
                            }
                            ray = isect.spawn_ray(&wi);
                            // account for attenuated subsurface scattering, if applicable
                            if let Some(ref bssrdf) = isect.bssrdf {
                                if (sampled_type & BxdfType::BsdfTransmission as u8) != 0_u8 {
                                    // importance sample the BSSRDF
                                    let s2: Point2f = sampler.get_2d();
                                    let s1: Float = sampler.get_1d();
                                    let (s, pi_opt) = bssrdf.sample_s(
                                        // the next three (extra) parameters are used for SeparableBssrdfAdapter
                                        bssrdf.clone(),
                                        bssrdf.mode,
                                        bssrdf.eta,
                                        // done
                                        scene,
                                        s1,
                                        s2,
                                        &mut pdf,
                                    );
                                    if s.is_black() || pdf == 0.0 as Float {
                                        break;
                                    }
                                    assert!(!(beta.y().is_infinite()));
                                    beta *= s / pdf;
                                    if let Some(pi) = pi_opt {
                                        // account for the direct subsurface scattering component
                                        let distrib: Arc<Distribution1D> =
                                            light_distribution.lookup(&pi.common.p);
                                        l += beta
                                            * uniform_sample_one_light(
                                                &pi,
                                                scene,
                                                sampler,
                                                true,
                                                Some(&distrib),
                                            );
                                        // account for the indirect subsurface scattering component
                                        let mut wi: Vector3f = Vector3f::default();
                                        let mut pdf: Float = 0.0 as Float;
                                        let bsdf_flags: u8 = BxdfType::BsdfAll as u8;
                                        let mut sampled_type: u8 = u8::max_value(); // != 0
                                        if let Some(ref bsdf) = pi.bsdf {
                                            let f: Spectrum = bsdf.sample_f(
                                                &pi.common.wo,
                                                &mut wi,
                                                &sampler.get_2d(),
                                                &mut pdf,
                                                bsdf_flags,
                                                &mut sampled_type,
                                            );
                                            if f.is_black() || pdf == 0.0 as Float {
                                                break;
                                            }
                                            beta *= f * vec3_abs_dot_nrmf(&wi, &pi.shading.n) / pdf;
                                            assert!(!(beta.y().is_infinite()));
                                            specular_bounce = (sampled_type
                                                & BxdfType::BsdfSpecular as u8)
                                                != 0_u8;
                                            ray = pi.spawn_ray(&wi);
                                        } else {
                                            panic!("no pi.bsdf found");
                                        }
                                    } else {
                                        panic!("bssrdf.sample_s() did return (s, None)");
                                    }
                                }
                            }
                        } else {
                            println!("TODO: if let Some(ref bsdf) = isect.bsdf failed");
                        }
                    }
                }
                // Possibly terminate the path with Russian roulette.
                // Factor out radiance scaling due to refraction in rr_beta.
                let rr_beta: Spectrum = beta * eta_scale;
                if rr_beta.max_component_value() < self.rr_threshold && bounces > 3 {
                    let q: Float =
                        (0.05 as Float).max(1.0 as Float - rr_beta.max_component_value());
                    if sampler.get_1d() < q {
                        break;
                    }
                    beta /= 1.0 as Float - q;
                    assert!(!(beta.y().is_infinite()));
                }
            } else {
                // sample the participating medium, if present
                if let Some(ref medium) = ray.medium {
                    let (spectrum, option) = medium.sample(&ray, sampler);
                    beta *= spectrum;
                    if let Some(mi) = option {
                        mi_opt = Some(mi);
                    }
                }
                if beta.is_black() {
                    break;
                }
                // handle an interaction with a medium
                if let Some(mi) = mi_opt {
                    // terminate path if ray escaped or _maxDepth_ was reached
                    if bounces >= self.max_depth {
                        break;
                    }
                    let mi_p = mi.common.p;
                    // if mi.is_valid() {...}
                    if let Some(phase) = mi.clone().phase {
                        // TODO: ++volumeInteractions;
                        // handle scattering at point in medium for volumetric path tracer
                        if let Some(ref light_distribution) = self.light_distribution {
                            let distrib: Arc<Distribution1D> = light_distribution.lookup(&mi_p);
                            l += beta
                                * uniform_sample_one_light(
                                    &mi as &dyn Interaction,
                                    scene,
                                    sampler,
                                    true,
                                    Some(&distrib),
                                );
                            let mut wi: Vector3f = Vector3f::default();
                            phase.sample_p(&(-ray.d), &mut wi, sampler.get_2d());
                            ray = mi.spawn_ray(&wi);
                            specular_bounce = false;
                        }
                    }
                }
                // add emitted light from the environment
                if bounces == 0 || specular_bounce {
                    for light in &scene.infinite_lights {
                        l += beta * light.le(&mut ray);
                    }
                }
                // terminate path if ray escaped
                break;
            }
            bounces += 1_u32;
        }
        l
    }
    pub fn get_camera(&self) -> Arc<Camera> {
        self.camera.clone()
    }
    pub fn get_sampler(&self) -> &Sampler {
        &self.sampler
    }
    pub fn get_pixel_bounds(&self) -> Bounds2i {
        self.pixel_bounds
    }
}