1df5050443489a8025914c48c5dae2ee80ef3deb
[blender-staging.git] / intern / cycles / kernel / kernel_volume.h
1 /*
2  * Copyright 2011-2013 Blender Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 CCL_NAMESPACE_BEGIN
18
19 /* Events for probalistic scattering */
20
21 typedef enum VolumeIntegrateResult {
22         VOLUME_PATH_SCATTERED = 0,
23         VOLUME_PATH_ATTENUATED = 1,
24         VOLUME_PATH_MISSED = 2
25 } VolumeIntegrateResult;
26
27 /* Volume shader properties
28  *
29  * extinction coefficient = absorption coefficient + scattering coefficient
30  * sigma_t = sigma_a + sigma_s */
31
32 typedef struct VolumeShaderCoefficients {
33         float3 sigma_t;
34         float3 sigma_s;
35         float3 emission;
36 } VolumeShaderCoefficients;
37
38 #ifdef __VOLUME__
39
40 /* evaluate shader to get extinction coefficient at P */
41 ccl_device_inline bool volume_shader_extinction_sample(KernelGlobals *kg,
42                                                        ShaderData *sd,
43                                                        ccl_addr_space PathState *state,
44                                                        float3 P,
45                                                        float3 *extinction)
46 {
47         sd->P = P;
48         shader_eval_volume(kg, sd, state, state->volume_stack, PATH_RAY_SHADOW);
49
50         if(sd->flag & SD_EXTINCTION) {
51                 *extinction = sd->closure_transparent_extinction;
52                 return true;
53         }
54         else {
55                 return false;
56         }
57 }
58
59 /* evaluate shader to get absorption, scattering and emission at P */
60 ccl_device_inline bool volume_shader_sample(KernelGlobals *kg,
61                                             ShaderData *sd,
62                                             ccl_addr_space PathState *state,
63                                             float3 P,
64                                             VolumeShaderCoefficients *coeff)
65 {
66         sd->P = P;
67         shader_eval_volume(kg, sd, state, state->volume_stack, state->flag);
68
69         if(!(sd->flag & (SD_EXTINCTION|SD_SCATTER|SD_EMISSION)))
70                 return false;
71
72         coeff->sigma_s = make_float3(0.0f, 0.0f, 0.0f);
73         coeff->sigma_t = (sd->flag & SD_EXTINCTION)? sd->closure_transparent_extinction:
74                                                      make_float3(0.0f, 0.0f, 0.0f);
75         coeff->emission = (sd->flag & SD_EMISSION)? sd->closure_emission_background:
76                                                     make_float3(0.0f, 0.0f, 0.0f);
77
78         if(sd->flag & SD_SCATTER) {
79                 for(int i = 0; i < sd->num_closure; i++) {
80                         const ShaderClosure *sc = &sd->closure[i];
81
82                         if(CLOSURE_IS_VOLUME(sc->type))
83                                 coeff->sigma_s += sc->weight;
84                 }
85         }
86
87         return true;
88 }
89
90 #endif  /* __VOLUME__ */
91
92 ccl_device float3 volume_color_transmittance(float3 sigma, float t)
93 {
94         return exp3(-sigma * t);
95 }
96
97 ccl_device float kernel_volume_channel_get(float3 value, int channel)
98 {
99         return (channel == 0)? value.x: ((channel == 1)? value.y: value.z);
100 }
101
102 #ifdef __VOLUME__
103
104 ccl_device bool volume_stack_is_heterogeneous(KernelGlobals *kg, ccl_addr_space VolumeStack *stack)
105 {
106         for(int i = 0; stack[i].shader != SHADER_NONE; i++) {
107                 int shader_flag = kernel_tex_fetch(__shaders, (stack[i].shader & SHADER_MASK)).flags;
108
109                 if(shader_flag & SD_HETEROGENEOUS_VOLUME) {
110                         return true;
111                 }
112                 else if(shader_flag & SD_NEED_ATTRIBUTES) {
113                         /* We want to render world or objects without any volume grids
114                          * as homogenous, but can only verify this at runtime since other
115                          * heterogenous volume objects may be using the same shader. */
116                         int object = stack[i].object;
117                         if(object != OBJECT_NONE) {
118                                 int object_flag = kernel_tex_fetch(__object_flag, object);
119                                 if(object_flag & SD_OBJECT_HAS_VOLUME_ATTRIBUTES) {
120                                         return true;
121                                 }
122                         }
123                 }
124         }
125
126         return false;
127 }
128
129 ccl_device int volume_stack_sampling_method(KernelGlobals *kg, VolumeStack *stack)
130 {
131         if(kernel_data.integrator.num_all_lights == 0)
132                 return 0;
133
134         int method = -1;
135
136         for(int i = 0; stack[i].shader != SHADER_NONE; i++) {
137                 int shader_flag = kernel_tex_fetch(__shaders, (stack[i].shader & SHADER_MASK)).flags;
138
139                 if(shader_flag & SD_VOLUME_MIS) {
140                         return SD_VOLUME_MIS;
141                 }
142                 else if(shader_flag & SD_VOLUME_EQUIANGULAR) {
143                         if(method == 0)
144                                 return SD_VOLUME_MIS;
145
146                         method = SD_VOLUME_EQUIANGULAR;
147                 }
148                 else {
149                         if(method == SD_VOLUME_EQUIANGULAR)
150                                 return SD_VOLUME_MIS;
151
152                         method = 0;
153                 }
154         }
155
156         return method;
157 }
158
159 ccl_device_inline void kernel_volume_step_init(KernelGlobals *kg,
160                                                ccl_addr_space PathState *state,
161                                                float t,
162                                                float *step_size,
163                                                float *step_offset)
164 {
165         const int max_steps = kernel_data.integrator.volume_max_steps;
166         float step = min(kernel_data.integrator.volume_step_size, t);
167
168         /* compute exact steps in advance for malloc */
169         if(t > max_steps * step) {
170                 step = t / (float)max_steps;
171         }
172
173         *step_size = step;
174         *step_offset = path_state_rng_1D_hash(kg, state, 0x1e31d8a4) * step;
175 }
176
177 /* Volume Shadows
178  *
179  * These functions are used to attenuate shadow rays to lights. Both absorption
180  * and scattering will block light, represented by the extinction coefficient. */
181
182 /* homogeneous volume: assume shader evaluation at the starts gives
183  * the extinction coefficient for the entire line segment */
184 ccl_device void kernel_volume_shadow_homogeneous(KernelGlobals *kg,
185                                                  ccl_addr_space PathState *state,
186                                                  Ray *ray,
187                                                  ShaderData *sd,
188                                                  float3 *throughput)
189 {
190         float3 sigma_t;
191
192         if(volume_shader_extinction_sample(kg, sd, state, ray->P, &sigma_t))
193                 *throughput *= volume_color_transmittance(sigma_t, ray->t);
194 }
195
196 /* heterogeneous volume: integrate stepping through the volume until we
197  * reach the end, get absorbed entirely, or run out of iterations */
198 ccl_device void kernel_volume_shadow_heterogeneous(KernelGlobals *kg,
199                                                    ccl_addr_space PathState *state,
200                                                    Ray *ray,
201                                                    ShaderData *sd,
202                                                    float3 *throughput)
203 {
204         float3 tp = *throughput;
205         const float tp_eps = 1e-6f; /* todo: this is likely not the right value */
206
207         /* prepare for stepping */
208         int max_steps = kernel_data.integrator.volume_max_steps;
209         float step_offset, step_size;
210         kernel_volume_step_init(kg, state, ray->t, &step_size, &step_offset);
211
212         /* compute extinction at the start */
213         float t = 0.0f;
214
215         float3 sum = make_float3(0.0f, 0.0f, 0.0f);
216
217         for(int i = 0; i < max_steps; i++) {
218                 /* advance to new position */
219                 float new_t = min(ray->t, (i+1) * step_size);
220
221                 /* use random position inside this segment to sample shader, adjust
222                  * for last step that is shorter than other steps. */
223                 if(new_t == ray->t) {
224                         step_offset *= (new_t - t) / step_size;
225                 }
226
227                 float3 new_P = ray->P + ray->D * (t + step_offset);
228                 float3 sigma_t;
229
230                 /* compute attenuation over segment */
231                 if(volume_shader_extinction_sample(kg, sd, state, new_P, &sigma_t)) {
232                         /* Compute expf() only for every Nth step, to save some calculations
233                          * because exp(a)*exp(b) = exp(a+b), also do a quick tp_eps check then. */
234
235                         sum += (-sigma_t * (new_t - t));
236                         if((i & 0x07) == 0) { /* ToDo: Other interval? */
237                                 tp = *throughput * exp3(sum);
238
239                                 /* stop if nearly all light is blocked */
240                                 if(tp.x < tp_eps && tp.y < tp_eps && tp.z < tp_eps)
241                                         break;
242                         }
243                 }
244
245                 /* stop if at the end of the volume */
246                 t = new_t;
247                 if(t == ray->t) {
248                         /* Update throughput in case we haven't done it above */
249                         tp = *throughput * exp3(sum);
250                         break;
251                 }
252         }
253
254         *throughput = tp;
255 }
256
257 /* get the volume attenuation over line segment defined by ray, with the
258  * assumption that there are no surfaces blocking light between the endpoints */
259 ccl_device_noinline void kernel_volume_shadow(KernelGlobals *kg,
260                                               ShaderData *shadow_sd,
261                                               ccl_addr_space PathState *state,
262                                               Ray *ray,
263                                               float3 *throughput)
264 {
265         shader_setup_from_volume(kg, shadow_sd, ray);
266
267         if(volume_stack_is_heterogeneous(kg, state->volume_stack))
268                 kernel_volume_shadow_heterogeneous(kg, state, ray, shadow_sd, throughput);
269         else
270                 kernel_volume_shadow_homogeneous(kg, state, ray, shadow_sd, throughput);
271 }
272
273 #endif  /* __VOLUME__ */
274
275 /* Equi-angular sampling as in:
276  * "Importance Sampling Techniques for Path Tracing in Participating Media" */
277
278 ccl_device float kernel_volume_equiangular_sample(Ray *ray, float3 light_P, float xi, float *pdf)
279 {
280         float t = ray->t;
281
282         float delta = dot((light_P - ray->P) , ray->D);
283         float D = safe_sqrtf(len_squared(light_P - ray->P) - delta * delta);
284         if(UNLIKELY(D == 0.0f)) {
285                 *pdf = 0.0f;
286                 return 0.0f;
287         }
288         float theta_a = -atan2f(delta, D);
289         float theta_b = atan2f(t - delta, D);
290         float t_ = D * tanf((xi * theta_b) + (1 - xi) * theta_a);
291         if(UNLIKELY(theta_b == theta_a)) {
292                 *pdf = 0.0f;
293                 return 0.0f;
294         }
295         *pdf = D / ((theta_b - theta_a) * (D * D + t_ * t_));
296
297         return min(t, delta + t_); /* min is only for float precision errors */
298 }
299
300 ccl_device float kernel_volume_equiangular_pdf(Ray *ray, float3 light_P, float sample_t)
301 {
302         float delta = dot((light_P - ray->P) , ray->D);
303         float D = safe_sqrtf(len_squared(light_P - ray->P) - delta * delta);
304         if(UNLIKELY(D == 0.0f)) {
305                 return 0.0f;
306         }
307
308         float t = ray->t;
309         float t_ = sample_t - delta;
310
311         float theta_a = -atan2f(delta, D);
312         float theta_b = atan2f(t - delta, D);
313         if(UNLIKELY(theta_b == theta_a)) {
314                 return 0.0f;
315         }
316
317         float pdf = D / ((theta_b - theta_a) * (D * D + t_ * t_));
318
319         return pdf;
320 }
321
322 /* Distance sampling */
323
324 ccl_device float kernel_volume_distance_sample(float max_t, float3 sigma_t, int channel, float xi, float3 *transmittance, float3 *pdf)
325 {
326         /* xi is [0, 1[ so log(0) should never happen, division by zero is
327          * avoided because sample_sigma_t > 0 when SD_SCATTER is set */
328         float sample_sigma_t = kernel_volume_channel_get(sigma_t, channel);
329         float3 full_transmittance = volume_color_transmittance(sigma_t, max_t);
330         float sample_transmittance = kernel_volume_channel_get(full_transmittance, channel);
331
332         float sample_t = min(max_t, -logf(1.0f - xi*(1.0f - sample_transmittance))/sample_sigma_t);
333
334         *transmittance = volume_color_transmittance(sigma_t, sample_t);
335         *pdf = safe_divide_color(sigma_t * *transmittance, make_float3(1.0f, 1.0f, 1.0f) - full_transmittance);
336
337         /* todo: optimization: when taken together with hit/miss decision,
338          * the full_transmittance cancels out drops out and xi does not
339          * need to be remapped */
340
341         return sample_t;
342 }
343
344 ccl_device float3 kernel_volume_distance_pdf(float max_t, float3 sigma_t, float sample_t)
345 {
346         float3 full_transmittance = volume_color_transmittance(sigma_t, max_t);
347         float3 transmittance = volume_color_transmittance(sigma_t, sample_t);
348
349         return safe_divide_color(sigma_t * transmittance, make_float3(1.0f, 1.0f, 1.0f) - full_transmittance);
350 }
351
352 /* Emission */
353
354 ccl_device float3 kernel_volume_emission_integrate(VolumeShaderCoefficients *coeff, int closure_flag, float3 transmittance, float t)
355 {
356         /* integral E * exp(-sigma_t * t) from 0 to t = E * (1 - exp(-sigma_t * t))/sigma_t
357          * this goes to E * t as sigma_t goes to zero
358          *
359          * todo: we should use an epsilon to avoid precision issues near zero sigma_t */
360         float3 emission = coeff->emission;
361
362         if(closure_flag & SD_EXTINCTION) {
363                 float3 sigma_t = coeff->sigma_t;
364
365                 emission.x *= (sigma_t.x > 0.0f)? (1.0f - transmittance.x)/sigma_t.x: t;
366                 emission.y *= (sigma_t.y > 0.0f)? (1.0f - transmittance.y)/sigma_t.y: t;
367                 emission.z *= (sigma_t.z > 0.0f)? (1.0f - transmittance.z)/sigma_t.z: t;
368         }
369         else
370                 emission *= t;
371
372         return emission;
373 }
374
375 /* Volume Path */
376
377 ccl_device int kernel_volume_sample_channel(float3 albedo, float3 throughput, float rand, float3 *pdf)
378 {
379         /* Sample color channel proportional to throughput and single scattering
380          * albedo, to significantly reduce noise with many bounce, following:
381          *
382          * "Practical and Controllable Subsurface Scattering for Production Path
383          *  Tracing". Matt Jen-Yuan Chiang, Peter Kutz, Brent Burley. SIGGRAPH 2016. */
384         float3 weights = fabs(throughput * albedo);
385         float sum_weights = weights.x + weights.y + weights.z;
386         float3 weights_pdf;
387
388         if(sum_weights > 0.0f) {
389                 weights_pdf = weights/sum_weights;
390         }
391         else {
392                 weights_pdf = make_float3(1.0f/3.0f, 1.0f/3.0f, 1.0f/3.0f);
393         }
394
395         *pdf = weights_pdf;
396
397         /* OpenCL does not support -> on float3, so don't use pdf->x. */
398         if(rand < weights_pdf.x) {
399                 return 0;
400         }
401         else if(rand < weights_pdf.x + weights_pdf.y) {
402                 return 1;
403         }
404         else {
405                 return 2;
406         }
407 }
408
409 #ifdef __VOLUME__
410
411 /* homogeneous volume: assume shader evaluation at the start gives
412  * the volume shading coefficient for the entire line segment */
413 ccl_device VolumeIntegrateResult kernel_volume_integrate_homogeneous(
414     KernelGlobals *kg,
415     ccl_addr_space PathState *state,
416     Ray *ray,
417     ShaderData *sd,
418     PathRadiance *L,
419     ccl_addr_space float3 *throughput,
420     bool probalistic_scatter)
421 {
422         VolumeShaderCoefficients coeff;
423
424         if(!volume_shader_sample(kg, sd, state, ray->P, &coeff))
425                 return VOLUME_PATH_MISSED;
426
427         int closure_flag = sd->flag;
428         float t = ray->t;
429         float3 new_tp;
430
431 #ifdef __VOLUME_SCATTER__
432         /* randomly scatter, and if we do t is shortened */
433         if(closure_flag & SD_SCATTER) {
434                 /* Sample channel, use MIS with balance heuristic. */
435                 float rphase = path_state_rng_1D(kg, state, PRNG_PHASE_CHANNEL);
436                 float3 albedo = safe_divide_color(coeff.sigma_s, coeff.sigma_t);
437                 float3 channel_pdf;
438                 int channel = kernel_volume_sample_channel(albedo, *throughput, rphase, &channel_pdf);
439
440                 /* decide if we will hit or miss */
441                 bool scatter = true;
442                 float xi = path_state_rng_1D(kg, state, PRNG_SCATTER_DISTANCE);
443
444                 if(probalistic_scatter) {
445                         float sample_sigma_t = kernel_volume_channel_get(coeff.sigma_t, channel);
446                         float sample_transmittance = expf(-sample_sigma_t * t);
447
448                         if(1.0f - xi >= sample_transmittance) {
449                                 scatter = true;
450
451                                 /* rescale random number so we can reuse it */
452                                 xi = 1.0f - (1.0f - xi - sample_transmittance)/(1.0f - sample_transmittance);
453
454                         }
455                         else
456                                 scatter = false;
457                 }
458
459                 if(scatter) {
460                         /* scattering */
461                         float3 pdf;
462                         float3 transmittance;
463                         float sample_t;
464
465                         /* distance sampling */
466                         sample_t = kernel_volume_distance_sample(ray->t, coeff.sigma_t, channel, xi, &transmittance, &pdf);
467
468                         /* modify pdf for hit/miss decision */
469                         if(probalistic_scatter)
470                                 pdf *= make_float3(1.0f, 1.0f, 1.0f) - volume_color_transmittance(coeff.sigma_t, t);
471
472                         new_tp = *throughput * coeff.sigma_s * transmittance / dot(channel_pdf, pdf);
473                         t = sample_t;
474                 }
475                 else {
476                         /* no scattering */
477                         float3 transmittance = volume_color_transmittance(coeff.sigma_t, t);
478                         float pdf = dot(channel_pdf, transmittance);
479                         new_tp = *throughput * transmittance / pdf;
480                 }
481         }
482         else
483 #endif
484         if(closure_flag & SD_EXTINCTION) {
485                 /* absorption only, no sampling needed */
486                 float3 transmittance = volume_color_transmittance(coeff.sigma_t, t);
487                 new_tp = *throughput * transmittance;
488         }
489
490         /* integrate emission attenuated by extinction */
491         if(L && (closure_flag & SD_EMISSION)) {
492                 float3 transmittance = volume_color_transmittance(coeff.sigma_t, ray->t);
493                 float3 emission = kernel_volume_emission_integrate(&coeff, closure_flag, transmittance, ray->t);
494                 path_radiance_accum_emission(L, state, *throughput, emission);
495         }
496
497         /* modify throughput */
498         if(closure_flag & SD_EXTINCTION) {
499                 *throughput = new_tp;
500
501                 /* prepare to scatter to new direction */
502                 if(t < ray->t) {
503                         /* adjust throughput and move to new location */
504                         sd->P = ray->P + t*ray->D;
505
506                         return VOLUME_PATH_SCATTERED;
507                 }
508         }
509
510         return VOLUME_PATH_ATTENUATED;
511 }
512
513 /* heterogeneous volume distance sampling: integrate stepping through the
514  * volume until we reach the end, get absorbed entirely, or run out of
515  * iterations. this does probabilistically scatter or get transmitted through
516  * for path tracing where we don't want to branch. */
517 ccl_device VolumeIntegrateResult kernel_volume_integrate_heterogeneous_distance(
518     KernelGlobals *kg,
519     ccl_addr_space PathState *state,
520     Ray *ray,
521     ShaderData *sd,
522     PathRadiance *L,
523     ccl_addr_space float3 *throughput)
524 {
525         float3 tp = *throughput;
526         const float tp_eps = 1e-6f; /* todo: this is likely not the right value */
527
528         /* prepare for stepping */
529         int max_steps = kernel_data.integrator.volume_max_steps;
530         float step_offset, step_size;
531         kernel_volume_step_init(kg, state, ray->t, &step_size, &step_offset);
532
533         /* compute coefficients at the start */
534         float t = 0.0f;
535         float3 accum_transmittance = make_float3(1.0f, 1.0f, 1.0f);
536
537         /* pick random color channel, we use the Veach one-sample
538          * model with balance heuristic for the channels */
539         float xi = path_state_rng_1D(kg, state, PRNG_SCATTER_DISTANCE);
540         float rphase = path_state_rng_1D(kg, state, PRNG_PHASE_CHANNEL);
541         bool has_scatter = false;
542
543         for(int i = 0; i < max_steps; i++) {
544                 /* advance to new position */
545                 float new_t = min(ray->t, (i+1) * step_size);
546                 float dt = new_t - t;
547
548                 /* use random position inside this segment to sample shader,
549                 * for last shorter step we remap it to fit within the segment. */
550                 if(new_t == ray->t) {
551                         step_offset *= (new_t - t) / step_size;
552                 }
553
554                 float3 new_P = ray->P + ray->D * (t + step_offset);
555                 VolumeShaderCoefficients coeff;
556
557                 /* compute segment */
558                 if(volume_shader_sample(kg, sd, state, new_P, &coeff)) {
559                         int closure_flag = sd->flag;
560                         float3 new_tp;
561                         float3 transmittance;
562                         bool scatter = false;
563
564                         /* distance sampling */
565 #ifdef __VOLUME_SCATTER__
566                         if((closure_flag & SD_SCATTER) || (has_scatter && (closure_flag & SD_EXTINCTION))) {
567                                 has_scatter = true;
568
569                                 /* Sample channel, use MIS with balance heuristic. */
570                                 float3 albedo = safe_divide_color(coeff.sigma_s, coeff.sigma_t);
571                                 float3 channel_pdf;
572                                 int channel = kernel_volume_sample_channel(albedo, tp, rphase, &channel_pdf);
573
574                                 /* compute transmittance over full step */
575                                 transmittance = volume_color_transmittance(coeff.sigma_t, dt);
576
577                                 /* decide if we will scatter or continue */
578                                 float sample_transmittance = kernel_volume_channel_get(transmittance, channel);
579
580                                 if(1.0f - xi >= sample_transmittance) {
581                                         /* compute sampling distance */
582                                         float sample_sigma_t = kernel_volume_channel_get(coeff.sigma_t, channel);
583                                         float new_dt = -logf(1.0f - xi)/sample_sigma_t;
584                                         new_t = t + new_dt;
585
586                                         /* transmittance and pdf */
587                                         float3 new_transmittance = volume_color_transmittance(coeff.sigma_t, new_dt);
588                                         float3 pdf = coeff.sigma_t * new_transmittance;
589
590                                         /* throughput */
591                                         new_tp = tp * coeff.sigma_s * new_transmittance / dot(channel_pdf, pdf);
592                                         scatter = true;
593                                 }
594                                 else {
595                                         /* throughput */
596                                         float pdf = dot(channel_pdf, transmittance);
597                                         new_tp = tp * transmittance / pdf;
598
599                                         /* remap xi so we can reuse it and keep thing stratified */
600                                         xi = 1.0f - (1.0f - xi)/sample_transmittance;
601                                 }
602                         }
603                         else
604 #endif
605                         if(closure_flag & SD_EXTINCTION) {
606                                 /* absorption only, no sampling needed */
607                                 transmittance = volume_color_transmittance(coeff.sigma_t, dt);
608                                 new_tp = tp * transmittance;
609                         }
610
611                         /* integrate emission attenuated by absorption */
612                         if(L && (closure_flag & SD_EMISSION)) {
613                                 float3 emission = kernel_volume_emission_integrate(&coeff, closure_flag, transmittance, dt);
614                                 path_radiance_accum_emission(L, state, tp, emission);
615                         }
616
617                         /* modify throughput */
618                         if(closure_flag & SD_EXTINCTION) {
619                                 tp = new_tp;
620
621                                 /* stop if nearly all light blocked */
622                                 if(tp.x < tp_eps && tp.y < tp_eps && tp.z < tp_eps) {
623                                         tp = make_float3(0.0f, 0.0f, 0.0f);
624                                         break;
625                                 }
626                         }
627
628                         /* prepare to scatter to new direction */
629                         if(scatter) {
630                                 /* adjust throughput and move to new location */
631                                 sd->P = ray->P + new_t*ray->D;
632                                 *throughput = tp;
633
634                                 return VOLUME_PATH_SCATTERED;
635                         }
636                         else {
637                                 /* accumulate transmittance */
638                                 accum_transmittance *= transmittance;
639                         }
640                 }
641
642                 /* stop if at the end of the volume */
643                 t = new_t;
644                 if(t == ray->t)
645                         break;
646         }
647
648         *throughput = tp;
649
650         return VOLUME_PATH_ATTENUATED;
651 }
652
653 /* get the volume attenuation and emission over line segment defined by
654  * ray, with the assumption that there are no surfaces blocking light
655  * between the endpoints. distance sampling is used to decide if we will
656  * scatter or not. */
657 ccl_device_noinline VolumeIntegrateResult kernel_volume_integrate(
658     KernelGlobals *kg,
659     ccl_addr_space PathState *state,
660     ShaderData *sd,
661     Ray *ray,
662     PathRadiance *L,
663     ccl_addr_space float3 *throughput,
664     bool heterogeneous)
665 {
666         shader_setup_from_volume(kg, sd, ray);
667
668         if(heterogeneous)
669                 return kernel_volume_integrate_heterogeneous_distance(kg, state, ray, sd, L, throughput);
670         else
671                 return kernel_volume_integrate_homogeneous(kg, state, ray, sd, L, throughput, true);
672 }
673
674 #ifndef __SPLIT_KERNEL__
675 /* Decoupled Volume Sampling
676  *
677  * VolumeSegment is list of coefficients and transmittance stored at all steps
678  * through a volume. This can then later be used for decoupled sampling as in:
679  * "Importance Sampling Techniques for Path Tracing in Participating Media"
680  *
681  * On the GPU this is only supported (but currently not enabled)
682  * for homogeneous volumes (1 step), due to
683  * no support for malloc/free and too much stack usage with a fix size array. */
684
685 typedef struct VolumeStep {
686         float3 sigma_s;                         /* scatter coefficient */
687         float3 sigma_t;                         /* extinction coefficient */
688         float3 accum_transmittance;     /* accumulated transmittance including this step */
689         float3 cdf_distance;            /* cumulative density function for distance sampling */
690         float t;                                        /* distance at end of this step */
691         float shade_t;                          /* jittered distance where shading was done in step */
692         int closure_flag;                       /* shader evaluation closure flags */
693 } VolumeStep;
694
695 typedef struct VolumeSegment {
696         VolumeStep stack_step;      /* stack storage for homogeneous step, to avoid malloc */
697         VolumeStep *steps;                      /* recorded steps */
698         int numsteps;                           /* number of steps */
699         int closure_flag;                       /* accumulated closure flags from all steps */
700
701         float3 accum_emission;          /* accumulated emission at end of segment */
702         float3 accum_transmittance;     /* accumulated transmittance at end of segment */
703         float3 accum_albedo;        /* accumulated average albedo over segment */
704
705         int sampling_method;            /* volume sampling method */
706 } VolumeSegment;
707
708 /* record volume steps to the end of the volume.
709  *
710  * it would be nice if we could only record up to the point that we need to scatter,
711  * but the entire segment is needed to do always scattering, rather than probabilistically
712  * hitting or missing the volume. if we don't know the transmittance at the end of the
713  * volume we can't generate stratified distance samples up to that transmittance */
714 #ifdef __VOLUME_DECOUPLED__
715 ccl_device void kernel_volume_decoupled_record(KernelGlobals *kg, PathState *state,
716         Ray *ray, ShaderData *sd, VolumeSegment *segment, bool heterogeneous)
717 {
718         const float tp_eps = 1e-6f; /* todo: this is likely not the right value */
719
720         /* prepare for volume stepping */
721         int max_steps;
722         float step_size, step_offset;
723
724         if(heterogeneous) {
725                 max_steps = kernel_data.integrator.volume_max_steps;
726                 kernel_volume_step_init(kg, state, ray->t, &step_size, &step_offset);
727
728 #ifdef __KERNEL_CPU__
729                 /* NOTE: For the branched path tracing it's possible to have direct
730                  * and indirect light integration both having volume segments allocated.
731                  * We detect this using index in the pre-allocated memory. Currently we
732                  * only support two segments allocated at a time, if more needed some
733                  * modifications to the KernelGlobals will be needed.
734                  *
735                  * This gives us restrictions that decoupled record should only happen
736                  * in the stack manner, meaning if there's subsequent call of decoupled
737                  * record it'll need to free memory before it's caller frees memory.
738                  */
739                 const int index = kg->decoupled_volume_steps_index;
740                 assert(index < sizeof(kg->decoupled_volume_steps) /
741                                sizeof(*kg->decoupled_volume_steps));
742                 if(kg->decoupled_volume_steps[index] == NULL) {
743                         kg->decoupled_volume_steps[index] =
744                                 (VolumeStep*)malloc(sizeof(VolumeStep)*max_steps);
745                 }
746                 segment->steps = kg->decoupled_volume_steps[index];
747                 ++kg->decoupled_volume_steps_index;
748 #else
749                 segment->steps = (VolumeStep*)malloc(sizeof(VolumeStep)*max_steps);
750 #endif
751         }
752         else {
753                 max_steps = 1;
754                 step_size = ray->t;
755                 step_offset = 0.0f;
756                 segment->steps = &segment->stack_step;
757         }
758
759         /* init accumulation variables */
760         float3 accum_emission = make_float3(0.0f, 0.0f, 0.0f);
761         float3 accum_transmittance = make_float3(1.0f, 1.0f, 1.0f);
762         float3 accum_albedo = make_float3(0.0f, 0.0f, 0.0f);
763         float3 cdf_distance = make_float3(0.0f, 0.0f, 0.0f);
764         float t = 0.0f;
765
766         segment->numsteps = 0;
767         segment->closure_flag = 0;
768         bool is_last_step_empty = false;
769
770         VolumeStep *step = segment->steps;
771
772         for(int i = 0; i < max_steps; i++, step++) {
773                 /* advance to new position */
774                 float new_t = min(ray->t, (i+1) * step_size);
775                 float dt = new_t - t;
776
777                 /* use random position inside this segment to sample shader,
778                 * for last shorter step we remap it to fit within the segment. */
779                 if(new_t == ray->t) {
780                         step_offset *= (new_t - t) / step_size;
781                 }
782
783                 float3 new_P = ray->P + ray->D * (t + step_offset);
784                 VolumeShaderCoefficients coeff;
785
786                 /* compute segment */
787                 if(volume_shader_sample(kg, sd, state, new_P, &coeff)) {
788                         int closure_flag = sd->flag;
789                         float3 sigma_t = coeff.sigma_t;
790
791                         /* compute average albedo for channel sampling */
792                         if(closure_flag & SD_SCATTER) {
793                                 accum_albedo += dt * safe_divide_color(coeff.sigma_s, sigma_t);
794                         }
795
796                         /* compute accumulated transmittance */
797                         float3 transmittance = volume_color_transmittance(sigma_t, dt);
798
799                         /* compute emission attenuated by absorption */
800                         if(closure_flag & SD_EMISSION) {
801                                 float3 emission = kernel_volume_emission_integrate(&coeff, closure_flag, transmittance, dt);
802                                 accum_emission += accum_transmittance * emission;
803                         }
804
805                         accum_transmittance *= transmittance;
806
807                         /* compute pdf for distance sampling */
808                         float3 pdf_distance = dt * accum_transmittance * coeff.sigma_s;
809                         cdf_distance = cdf_distance + pdf_distance;
810
811                         /* write step data */
812                         step->sigma_t = sigma_t;
813                         step->sigma_s = coeff.sigma_s;
814                         step->closure_flag = closure_flag;
815
816                         segment->closure_flag |= closure_flag;
817
818                         is_last_step_empty = false;
819                         segment->numsteps++;
820                 }
821                 else {
822                         if(is_last_step_empty) {
823                                 /* consecutive empty step, merge */
824                                 step--;
825                         }
826                         else {
827                                 /* store empty step */
828                                 step->sigma_t = make_float3(0.0f, 0.0f, 0.0f);
829                                 step->sigma_s = make_float3(0.0f, 0.0f, 0.0f);
830                                 step->closure_flag = 0;
831
832                                 segment->numsteps++;
833                                 is_last_step_empty = true;
834                         }
835                 }
836
837                 step->accum_transmittance = accum_transmittance;
838                 step->cdf_distance = cdf_distance;
839                 step->t = new_t;
840                 step->shade_t = t + step_offset;
841
842                 /* stop if at the end of the volume */
843                 t = new_t;
844                 if(t == ray->t)
845                         break;
846
847                 /* stop if nearly all light blocked */
848                 if(accum_transmittance.x < tp_eps && accum_transmittance.y < tp_eps && accum_transmittance.z < tp_eps)
849                         break;
850         }
851
852         /* store total emission and transmittance */
853         segment->accum_emission = accum_emission;
854         segment->accum_transmittance = accum_transmittance;
855         segment->accum_albedo = accum_albedo;
856
857         /* normalize cumulative density function for distance sampling */
858         VolumeStep *last_step = segment->steps + segment->numsteps - 1;
859
860         if(!is_zero(last_step->cdf_distance)) {
861                 VolumeStep *step = &segment->steps[0];
862                 int numsteps = segment->numsteps;
863                 float3 inv_cdf_distance_sum = safe_invert_color(last_step->cdf_distance);
864
865                 for(int i = 0; i < numsteps; i++, step++)
866                         step->cdf_distance *= inv_cdf_distance_sum;
867         }
868 }
869
870 ccl_device void kernel_volume_decoupled_free(KernelGlobals *kg, VolumeSegment *segment)
871 {
872         if(segment->steps != &segment->stack_step) {
873 #ifdef __KERNEL_CPU__
874                 /* NOTE: We only allow free last allocated segment.
875                  * No random order of alloc/free is supported.
876                  */
877                 assert(kg->decoupled_volume_steps_index > 0);
878                 assert(segment->steps == kg->decoupled_volume_steps[kg->decoupled_volume_steps_index - 1]);
879                 --kg->decoupled_volume_steps_index;
880 #else
881                 free(segment->steps);
882 #endif
883         }
884 }
885 #endif  /* __VOLUME_DECOUPLED__ */
886
887 /* scattering for homogeneous and heterogeneous volumes, using decoupled ray
888  * marching.
889  *
890  * function is expected to return VOLUME_PATH_SCATTERED when probalistic_scatter is false */
891 ccl_device VolumeIntegrateResult kernel_volume_decoupled_scatter(
892         KernelGlobals *kg, PathState *state, Ray *ray, ShaderData *sd,
893         float3 *throughput, float rphase, float rscatter,
894         const VolumeSegment *segment, const float3 *light_P, bool probalistic_scatter)
895 {
896         kernel_assert(segment->closure_flag & SD_SCATTER);
897
898         /* Sample color channel, use MIS with balance heuristic. */
899         float3 channel_pdf;
900         int channel = kernel_volume_sample_channel(segment->accum_albedo,
901                                                    *throughput,
902                                                    rphase,
903                                                    &channel_pdf);
904
905         float xi = rscatter;
906
907         /* probabilistic scattering decision based on transmittance */
908         if(probalistic_scatter) {
909                 float sample_transmittance = kernel_volume_channel_get(segment->accum_transmittance, channel);
910
911                 if(1.0f - xi >= sample_transmittance) {
912                         /* rescale random number so we can reuse it */
913                         xi = 1.0f - (1.0f - xi - sample_transmittance)/(1.0f - sample_transmittance);
914                 }
915                 else {
916                         *throughput /= sample_transmittance;
917                         return VOLUME_PATH_MISSED;
918                 }
919         }
920
921         VolumeStep *step;
922         float3 transmittance;
923         float pdf, sample_t;
924         float mis_weight = 1.0f;
925         bool distance_sample = true;
926         bool use_mis = false;
927
928         if(segment->sampling_method && light_P) {
929                 if(segment->sampling_method == SD_VOLUME_MIS) {
930                         /* multiple importance sample: randomly pick between
931                          * equiangular and distance sampling strategy */
932                         if(xi < 0.5f) {
933                                 xi *= 2.0f;
934                         }
935                         else {
936                                 xi = (xi - 0.5f)*2.0f;
937                                 distance_sample = false;
938                         }
939
940                         use_mis = true;
941                 }
942                 else {
943                         /* only equiangular sampling */
944                         distance_sample = false;
945                 }
946         }
947
948         /* distance sampling */
949         if(distance_sample) {
950                 /* find step in cdf */
951                 step = segment->steps;
952
953                 float prev_t = 0.0f;
954                 float3 step_pdf_distance = make_float3(1.0f, 1.0f, 1.0f);
955
956                 if(segment->numsteps > 1) {
957                         float prev_cdf = 0.0f;
958                         float step_cdf = 1.0f;
959                         float3 prev_cdf_distance = make_float3(0.0f, 0.0f, 0.0f);
960
961                         for(int i = 0; ; i++, step++) {
962                                 /* todo: optimize using binary search */
963                                 step_cdf = kernel_volume_channel_get(step->cdf_distance, channel);
964
965                                 if(xi < step_cdf || i == segment->numsteps-1)
966                                         break;
967
968                                 prev_cdf = step_cdf;
969                                 prev_t = step->t;
970                                 prev_cdf_distance = step->cdf_distance;
971                         }
972
973                         /* remap xi so we can reuse it */
974                         xi = (xi - prev_cdf)/(step_cdf - prev_cdf);
975
976                         /* pdf for picking step */
977                         step_pdf_distance = step->cdf_distance - prev_cdf_distance;
978                 }
979
980                 /* determine range in which we will sample */
981                 float step_t = step->t - prev_t;
982
983                 /* sample distance and compute transmittance */
984                 float3 distance_pdf;
985                 sample_t = prev_t + kernel_volume_distance_sample(step_t, step->sigma_t, channel, xi, &transmittance, &distance_pdf);
986
987                 /* modify pdf for hit/miss decision */
988                 if(probalistic_scatter)
989                         distance_pdf *= make_float3(1.0f, 1.0f, 1.0f) - segment->accum_transmittance;
990
991                 pdf = dot(channel_pdf, distance_pdf * step_pdf_distance);
992
993                 /* multiple importance sampling */
994                 if(use_mis) {
995                         float equi_pdf = kernel_volume_equiangular_pdf(ray, *light_P, sample_t);
996                         mis_weight = 2.0f*power_heuristic(pdf, equi_pdf);
997                 }
998         }
999         /* equi-angular sampling */
1000         else {
1001                 /* sample distance */
1002                 sample_t = kernel_volume_equiangular_sample(ray, *light_P, xi, &pdf);
1003
1004                 /* find step in which sampled distance is located */
1005                 step = segment->steps;
1006
1007                 float prev_t = 0.0f;
1008                 float3 step_pdf_distance = make_float3(1.0f, 1.0f, 1.0f);
1009
1010                 if(segment->numsteps > 1) {
1011                         float3 prev_cdf_distance = make_float3(0.0f, 0.0f, 0.0f);
1012
1013                         int numsteps = segment->numsteps;
1014                         int high = numsteps - 1;
1015                         int low = 0;
1016                         int mid;
1017
1018                         while(low < high) {
1019                                 mid = (low + high) >> 1;
1020
1021                                 if(sample_t < step[mid].t)
1022                                         high = mid;
1023                                 else if(sample_t >= step[mid + 1].t)
1024                                         low = mid + 1;
1025                                 else {
1026                                         /* found our interval in step[mid] .. step[mid+1] */
1027                                         prev_t = step[mid].t;
1028                                         prev_cdf_distance = step[mid].cdf_distance;
1029                                         step += mid+1;
1030                                         break;
1031                                 }
1032                         }
1033
1034                         if(low >= numsteps - 1) {
1035                                 prev_t = step[numsteps - 1].t;
1036                                 prev_cdf_distance = step[numsteps-1].cdf_distance;
1037                                 step += numsteps - 1;
1038                         }
1039
1040                         /* pdf for picking step with distance sampling */
1041                         step_pdf_distance = step->cdf_distance - prev_cdf_distance;
1042                 }
1043
1044                 /* determine range in which we will sample */
1045                 float step_t = step->t - prev_t;
1046                 float step_sample_t = sample_t - prev_t;
1047
1048                 /* compute transmittance */
1049                 transmittance = volume_color_transmittance(step->sigma_t, step_sample_t);
1050
1051                 /* multiple importance sampling */
1052                 if(use_mis) {
1053                         float3 distance_pdf3 = kernel_volume_distance_pdf(step_t, step->sigma_t, step_sample_t);
1054                         float distance_pdf = dot(channel_pdf, distance_pdf3 * step_pdf_distance);
1055                         mis_weight = 2.0f*power_heuristic(pdf, distance_pdf);
1056                 }
1057         }
1058         if(sample_t < 0.0f || pdf == 0.0f) {
1059                 return VOLUME_PATH_MISSED;
1060         }
1061
1062         /* compute transmittance up to this step */
1063         if(step != segment->steps)
1064                 transmittance *= (step-1)->accum_transmittance;
1065
1066         /* modify throughput */
1067         *throughput *= step->sigma_s * transmittance * (mis_weight / pdf);
1068
1069         /* evaluate shader to create closures at shading point */
1070         if(segment->numsteps > 1) {
1071                 sd->P = ray->P + step->shade_t*ray->D;
1072
1073                 VolumeShaderCoefficients coeff;
1074                 volume_shader_sample(kg, sd, state, sd->P, &coeff);
1075         }
1076
1077         /* move to new position */
1078         sd->P = ray->P + sample_t*ray->D;
1079
1080         return VOLUME_PATH_SCATTERED;
1081 }
1082 #endif  /* __SPLIT_KERNEL */
1083
1084 /* decide if we need to use decoupled or not */
1085 ccl_device bool kernel_volume_use_decoupled(KernelGlobals *kg, bool heterogeneous, bool direct, int sampling_method)
1086 {
1087         /* decoupled ray marching for heterogeneous volumes not supported on the GPU,
1088          * which also means equiangular and multiple importance sampling is not
1089          * support for that case */
1090         if(!kernel_data.integrator.volume_decoupled)
1091                 return false;
1092
1093 #ifdef __KERNEL_GPU__
1094         if(heterogeneous)
1095                 return false;
1096 #endif
1097
1098         /* equiangular and multiple importance sampling only implemented for decoupled */
1099         if(sampling_method != 0)
1100                 return true;
1101
1102         /* for all light sampling use decoupled, reusing shader evaluations is
1103          * typically faster in that case */
1104         if(direct)
1105                 return kernel_data.integrator.sample_all_lights_direct;
1106         else
1107                 return kernel_data.integrator.sample_all_lights_indirect;
1108 }
1109
1110 /* Volume Stack
1111  *
1112  * This is an array of object/shared ID's that the current segment of the path
1113  * is inside of. */
1114
1115 ccl_device void kernel_volume_stack_init(KernelGlobals *kg,
1116                                          ShaderData *stack_sd,
1117                                          ccl_addr_space const PathState *state,
1118                                          ccl_addr_space const Ray *ray,
1119                                          ccl_addr_space VolumeStack *stack)
1120 {
1121         /* NULL ray happens in the baker, does it need proper initialization of
1122          * camera in volume?
1123          */
1124         if(!kernel_data.cam.is_inside_volume || ray == NULL) {
1125                 /* Camera is guaranteed to be in the air, only take background volume
1126                  * into account in this case.
1127                  */
1128                 if(kernel_data.background.volume_shader != SHADER_NONE) {
1129                         stack[0].shader = kernel_data.background.volume_shader;
1130                         stack[0].object = PRIM_NONE;
1131                         stack[1].shader = SHADER_NONE;
1132                 }
1133                 else {
1134                         stack[0].shader = SHADER_NONE;
1135                 }
1136                 return;
1137         }
1138
1139         kernel_assert(state->flag & PATH_RAY_CAMERA);
1140
1141         Ray volume_ray = *ray;
1142         volume_ray.t = FLT_MAX;
1143
1144         const uint visibility = (state->flag & PATH_RAY_ALL_VISIBILITY);
1145         int stack_index = 0, enclosed_index = 0;
1146
1147 #ifdef __VOLUME_RECORD_ALL__
1148         Intersection hits[2*VOLUME_STACK_SIZE + 1];
1149         uint num_hits = scene_intersect_volume_all(kg,
1150                                                    &volume_ray,
1151                                                    hits,
1152                                                    2*VOLUME_STACK_SIZE,
1153                                                    visibility);
1154         if(num_hits > 0) {
1155                 int enclosed_volumes[VOLUME_STACK_SIZE];
1156                 Intersection *isect = hits;
1157
1158                 qsort(hits, num_hits, sizeof(Intersection), intersections_compare);
1159
1160                 for(uint hit = 0; hit < num_hits; ++hit, ++isect) {
1161                         shader_setup_from_ray(kg, stack_sd, isect, &volume_ray);
1162                         if(stack_sd->flag & SD_BACKFACING) {
1163                                 bool need_add = true;
1164                                 for(int i = 0; i < enclosed_index && need_add; ++i) {
1165                                         /* If ray exited the volume and never entered to that volume
1166                                          * it means that camera is inside such a volume.
1167                                          */
1168                                         if(enclosed_volumes[i] == stack_sd->object) {
1169                                                 need_add = false;
1170                                         }
1171                                 }
1172                                 for(int i = 0; i < stack_index && need_add; ++i) {
1173                                         /* Don't add intersections twice. */
1174                                         if(stack[i].object == stack_sd->object) {
1175                                                 need_add = false;
1176                                                 break;
1177                                         }
1178                                 }
1179                                 if(need_add && stack_index < VOLUME_STACK_SIZE - 1) {
1180                                         stack[stack_index].object = stack_sd->object;
1181                                         stack[stack_index].shader = stack_sd->shader;
1182                                         ++stack_index;
1183                                 }
1184                         }
1185                         else {
1186                                 /* If ray from camera enters the volume, this volume shouldn't
1187                                  * be added to the stack on exit.
1188                                  */
1189                                 enclosed_volumes[enclosed_index++] = stack_sd->object;
1190                         }
1191                 }
1192         }
1193 #else
1194         int enclosed_volumes[VOLUME_STACK_SIZE];
1195         int step = 0;
1196
1197         while(stack_index < VOLUME_STACK_SIZE - 1 &&
1198               enclosed_index < VOLUME_STACK_SIZE - 1 &&
1199               step < 2 * VOLUME_STACK_SIZE)
1200         {
1201                 Intersection isect;
1202                 if(!scene_intersect_volume(kg, &volume_ray, &isect, visibility)) {
1203                         break;
1204                 }
1205
1206                 shader_setup_from_ray(kg, stack_sd, &isect, &volume_ray);
1207                 if(stack_sd->flag & SD_BACKFACING) {
1208                         /* If ray exited the volume and never entered to that volume
1209                          * it means that camera is inside such a volume.
1210                          */
1211                         bool need_add = true;
1212                         for(int i = 0; i < enclosed_index && need_add; ++i) {
1213                                 /* If ray exited the volume and never entered to that volume
1214                                  * it means that camera is inside such a volume.
1215                                  */
1216                                 if(enclosed_volumes[i] == stack_sd->object) {
1217                                         need_add = false;
1218                                 }
1219                         }
1220                         for(int i = 0; i < stack_index && need_add; ++i) {
1221                                 /* Don't add intersections twice. */
1222                                 if(stack[i].object == stack_sd->object) {
1223                                         need_add = false;
1224                                         break;
1225                                 }
1226                         }
1227                         if(need_add) {
1228                                 stack[stack_index].object = stack_sd->object;
1229                                 stack[stack_index].shader = stack_sd->shader;
1230                                 ++stack_index;
1231                         }
1232                 }
1233                 else {
1234                         /* If ray from camera enters the volume, this volume shouldn't
1235                          * be added to the stack on exit.
1236                          */
1237                         enclosed_volumes[enclosed_index++] = stack_sd->object;
1238                 }
1239
1240                 /* Move ray forward. */
1241                 volume_ray.P = ray_offset(stack_sd->P, -stack_sd->Ng);
1242                 ++step;
1243         }
1244 #endif
1245         /* stack_index of 0 means quick checks outside of the kernel gave false
1246          * positive, nothing to worry about, just we've wasted quite a few of
1247          * ticks just to come into conclusion that camera is in the air.
1248          *
1249          * In this case we're doing the same above -- check whether background has
1250          * volume.
1251          */
1252         if(stack_index == 0 && kernel_data.background.volume_shader == SHADER_NONE) {
1253                 stack[0].shader = kernel_data.background.volume_shader;
1254                 stack[0].object = PRIM_NONE;
1255                 stack[1].shader = SHADER_NONE;
1256         }
1257         else {
1258                 stack[stack_index].shader = SHADER_NONE;
1259         }
1260 }
1261
1262 ccl_device void kernel_volume_stack_enter_exit(KernelGlobals *kg, ShaderData *sd, ccl_addr_space VolumeStack *stack)
1263 {
1264         /* todo: we should have some way for objects to indicate if they want the
1265          * world shader to work inside them. excluding it by default is problematic
1266          * because non-volume objects can't be assumed to be closed manifolds */
1267
1268         if(!(sd->flag & SD_HAS_VOLUME))
1269                 return;
1270
1271         if(sd->flag & SD_BACKFACING) {
1272                 /* exit volume object: remove from stack */
1273                 for(int i = 0; stack[i].shader != SHADER_NONE; i++) {
1274                         if(stack[i].object == sd->object) {
1275                                 /* shift back next stack entries */
1276                                 do {
1277                                         stack[i] = stack[i+1];
1278                                         i++;
1279                                 }
1280                                 while(stack[i].shader != SHADER_NONE);
1281
1282                                 return;
1283                         }
1284                 }
1285         }
1286         else {
1287                 /* enter volume object: add to stack */
1288                 int i;
1289
1290                 for(i = 0; stack[i].shader != SHADER_NONE; i++) {
1291                         /* already in the stack? then we have nothing to do */
1292                         if(stack[i].object == sd->object)
1293                                 return;
1294                 }
1295
1296                 /* if we exceed the stack limit, ignore */
1297                 if(i >= VOLUME_STACK_SIZE-1)
1298                         return;
1299
1300                 /* add to the end of the stack */
1301                 stack[i].shader = sd->shader;
1302                 stack[i].object = sd->object;
1303                 stack[i+1].shader = SHADER_NONE;
1304         }
1305 }
1306
1307 #ifdef __SUBSURFACE__
1308 ccl_device void kernel_volume_stack_update_for_subsurface(KernelGlobals *kg,
1309                                                           ShaderData *stack_sd,
1310                                                           Ray *ray,
1311                                                           ccl_addr_space VolumeStack *stack)
1312 {
1313         kernel_assert(kernel_data.integrator.use_volumes);
1314
1315         Ray volume_ray = *ray;
1316
1317 #  ifdef __VOLUME_RECORD_ALL__
1318         Intersection hits[2*VOLUME_STACK_SIZE + 1];
1319         uint num_hits = scene_intersect_volume_all(kg,
1320                                                    &volume_ray,
1321                                                    hits,
1322                                                    2*VOLUME_STACK_SIZE,
1323                                                    PATH_RAY_ALL_VISIBILITY);
1324         if(num_hits > 0) {
1325                 Intersection *isect = hits;
1326
1327                 qsort(hits, num_hits, sizeof(Intersection), intersections_compare);
1328
1329                 for(uint hit = 0; hit < num_hits; ++hit, ++isect) {
1330                         shader_setup_from_ray(kg, stack_sd, isect, &volume_ray);
1331                         kernel_volume_stack_enter_exit(kg, stack_sd, stack);
1332                 }
1333         }
1334 #  else
1335         Intersection isect;
1336         int step = 0;
1337         float3 Pend = ray->P + ray->D*ray->t;
1338         while(step < 2 * VOLUME_STACK_SIZE &&
1339               scene_intersect_volume(kg,
1340                                      &volume_ray,
1341                                      &isect,
1342                                      PATH_RAY_ALL_VISIBILITY))
1343         {
1344                 shader_setup_from_ray(kg, stack_sd, &isect, &volume_ray);
1345                 kernel_volume_stack_enter_exit(kg, stack_sd, stack);
1346
1347                 /* Move ray forward. */
1348                 volume_ray.P = ray_offset(stack_sd->P, -stack_sd->Ng);
1349                 if(volume_ray.t != FLT_MAX) {
1350                         volume_ray.D = normalize_len(Pend - volume_ray.P, &volume_ray.t);
1351                 }
1352                 ++step;
1353         }
1354 #  endif
1355 }
1356 #endif
1357
1358 /* Clean stack after the last bounce.
1359  *
1360  * It is expected that all volumes are closed manifolds, so at the time when ray
1361  * hits nothing (for example, it is a last bounce which goes to environment) the
1362  * only expected volume in the stack is the world's one. All the rest volume
1363  * entries should have been exited already.
1364  *
1365  * This isn't always true because of ray intersection precision issues, which
1366  * could lead us to an infinite non-world volume in the stack, causing render
1367  * artifacts.
1368  *
1369  * Use this function after the last bounce to get rid of all volumes apart from
1370  * the world's one after the last bounce to avoid render artifacts.
1371  */
1372 ccl_device_inline void kernel_volume_clean_stack(KernelGlobals *kg,
1373                                                  ccl_addr_space VolumeStack *volume_stack)
1374 {
1375         if(kernel_data.background.volume_shader != SHADER_NONE) {
1376                 /* Keep the world's volume in stack. */
1377                 volume_stack[1].shader = SHADER_NONE;
1378         }
1379         else {
1380                 volume_stack[0].shader = SHADER_NONE;
1381         }
1382 }
1383
1384 #endif  /* __VOLUME__ */
1385
1386 CCL_NAMESPACE_END