d6d283c42c5a4ab05d79fda6337d3c34a16c99b0
[blender.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
387         if(sum_weights > 0.0f) {
388                 *pdf = weights/sum_weights;
389         }
390         else {
391                 *pdf = make_float3(1.0f/3.0f, 1.0f/3.0f, 1.0f/3.0f);
392         }
393
394         if(rand < pdf->x) {
395                 return 0;
396         }
397         else if(rand < pdf->x + pdf->y) {
398                 return 1;
399         }
400         else {
401                 return 2;
402         }
403 }
404
405 #ifdef __VOLUME__
406
407 /* homogeneous volume: assume shader evaluation at the start gives
408  * the volume shading coefficient for the entire line segment */
409 ccl_device VolumeIntegrateResult kernel_volume_integrate_homogeneous(
410     KernelGlobals *kg,
411     ccl_addr_space PathState *state,
412     Ray *ray,
413     ShaderData *sd,
414     PathRadiance *L,
415     ccl_addr_space float3 *throughput,
416     bool probalistic_scatter)
417 {
418         VolumeShaderCoefficients coeff;
419
420         if(!volume_shader_sample(kg, sd, state, ray->P, &coeff))
421                 return VOLUME_PATH_MISSED;
422
423         int closure_flag = sd->flag;
424         float t = ray->t;
425         float3 new_tp;
426
427 #ifdef __VOLUME_SCATTER__
428         /* randomly scatter, and if we do t is shortened */
429         if(closure_flag & SD_SCATTER) {
430                 /* Sample channel, use MIS with balance heuristic. */
431                 float rphase = path_state_rng_1D(kg, state, PRNG_PHASE_CHANNEL);
432                 float3 albedo = safe_divide_color(coeff.sigma_s, coeff.sigma_t);
433                 float3 channel_pdf;
434                 int channel = kernel_volume_sample_channel(albedo, *throughput, rphase, &channel_pdf);
435
436                 /* decide if we will hit or miss */
437                 bool scatter = true;
438                 float xi = path_state_rng_1D(kg, state, PRNG_SCATTER_DISTANCE);
439
440                 if(probalistic_scatter) {
441                         float sample_sigma_t = kernel_volume_channel_get(coeff.sigma_t, channel);
442                         float sample_transmittance = expf(-sample_sigma_t * t);
443
444                         if(1.0f - xi >= sample_transmittance) {
445                                 scatter = true;
446
447                                 /* rescale random number so we can reuse it */
448                                 xi = 1.0f - (1.0f - xi - sample_transmittance)/(1.0f - sample_transmittance);
449
450                         }
451                         else
452                                 scatter = false;
453                 }
454
455                 if(scatter) {
456                         /* scattering */
457                         float3 pdf;
458                         float3 transmittance;
459                         float sample_t;
460
461                         /* distance sampling */
462                         sample_t = kernel_volume_distance_sample(ray->t, coeff.sigma_t, channel, xi, &transmittance, &pdf);
463
464                         /* modify pdf for hit/miss decision */
465                         if(probalistic_scatter)
466                                 pdf *= make_float3(1.0f, 1.0f, 1.0f) - volume_color_transmittance(coeff.sigma_t, t);
467
468                         new_tp = *throughput * coeff.sigma_s * transmittance / dot(channel_pdf, pdf);
469                         t = sample_t;
470                 }
471                 else {
472                         /* no scattering */
473                         float3 transmittance = volume_color_transmittance(coeff.sigma_t, t);
474                         float pdf = dot(channel_pdf, transmittance);
475                         new_tp = *throughput * transmittance / pdf;
476                 }
477         }
478         else
479 #endif
480         if(closure_flag & SD_EXTINCTION) {
481                 /* absorption only, no sampling needed */
482                 float3 transmittance = volume_color_transmittance(coeff.sigma_t, t);
483                 new_tp = *throughput * transmittance;
484         }
485
486         /* integrate emission attenuated by extinction */
487         if(L && (closure_flag & SD_EMISSION)) {
488                 float3 transmittance = volume_color_transmittance(coeff.sigma_t, ray->t);
489                 float3 emission = kernel_volume_emission_integrate(&coeff, closure_flag, transmittance, ray->t);
490                 path_radiance_accum_emission(L, state, *throughput, emission);
491         }
492
493         /* modify throughput */
494         if(closure_flag & SD_EXTINCTION) {
495                 *throughput = new_tp;
496
497                 /* prepare to scatter to new direction */
498                 if(t < ray->t) {
499                         /* adjust throughput and move to new location */
500                         sd->P = ray->P + t*ray->D;
501
502                         return VOLUME_PATH_SCATTERED;
503                 }
504         }
505
506         return VOLUME_PATH_ATTENUATED;
507 }
508
509 /* heterogeneous volume distance sampling: integrate stepping through the
510  * volume until we reach the end, get absorbed entirely, or run out of
511  * iterations. this does probabilistically scatter or get transmitted through
512  * for path tracing where we don't want to branch. */
513 ccl_device VolumeIntegrateResult kernel_volume_integrate_heterogeneous_distance(
514     KernelGlobals *kg,
515     ccl_addr_space PathState *state,
516     Ray *ray,
517     ShaderData *sd,
518     PathRadiance *L,
519     ccl_addr_space float3 *throughput)
520 {
521         float3 tp = *throughput;
522         const float tp_eps = 1e-6f; /* todo: this is likely not the right value */
523
524         /* prepare for stepping */
525         int max_steps = kernel_data.integrator.volume_max_steps;
526         float step_offset, step_size;
527         kernel_volume_step_init(kg, state, ray->t, &step_size, &step_offset);
528
529         /* compute coefficients at the start */
530         float t = 0.0f;
531         float3 accum_transmittance = make_float3(1.0f, 1.0f, 1.0f);
532
533         /* pick random color channel, we use the Veach one-sample
534          * model with balance heuristic for the channels */
535         float xi = path_state_rng_1D(kg, state, PRNG_SCATTER_DISTANCE);
536         float rphase = path_state_rng_1D(kg, state, PRNG_PHASE_CHANNEL);
537         bool has_scatter = false;
538
539         for(int i = 0; i < max_steps; i++) {
540                 /* advance to new position */
541                 float new_t = min(ray->t, (i+1) * step_size);
542                 float dt = new_t - t;
543
544                 /* use random position inside this segment to sample shader,
545                 * for last shorter step we remap it to fit within the segment. */
546                 if(new_t == ray->t) {
547                         step_offset *= (new_t - t) / step_size;
548                 }
549
550                 float3 new_P = ray->P + ray->D * (t + step_offset);
551                 VolumeShaderCoefficients coeff;
552
553                 /* compute segment */
554                 if(volume_shader_sample(kg, sd, state, new_P, &coeff)) {
555                         int closure_flag = sd->flag;
556                         float3 new_tp;
557                         float3 transmittance;
558                         bool scatter = false;
559
560                         /* distance sampling */
561 #ifdef __VOLUME_SCATTER__
562                         if((closure_flag & SD_SCATTER) || (has_scatter && (closure_flag & SD_EXTINCTION))) {
563                                 has_scatter = true;
564
565                                 /* Sample channel, use MIS with balance heuristic. */
566                                 float3 albedo = safe_divide_color(coeff.sigma_s, coeff.sigma_t);
567                                 float3 channel_pdf;
568                                 int channel = kernel_volume_sample_channel(albedo, tp, rphase, &channel_pdf);
569
570                                 /* compute transmittance over full step */
571                                 transmittance = volume_color_transmittance(coeff.sigma_t, dt);
572
573                                 /* decide if we will scatter or continue */
574                                 float sample_transmittance = kernel_volume_channel_get(transmittance, channel);
575
576                                 if(1.0f - xi >= sample_transmittance) {
577                                         /* compute sampling distance */
578                                         float sample_sigma_t = kernel_volume_channel_get(coeff.sigma_t, channel);
579                                         float new_dt = -logf(1.0f - xi)/sample_sigma_t;
580                                         new_t = t + new_dt;
581
582                                         /* transmittance and pdf */
583                                         float3 new_transmittance = volume_color_transmittance(coeff.sigma_t, new_dt);
584                                         float3 pdf = coeff.sigma_t * new_transmittance;
585
586                                         /* throughput */
587                                         new_tp = tp * coeff.sigma_s * new_transmittance / dot(channel_pdf, pdf);
588                                         scatter = true;
589                                 }
590                                 else {
591                                         /* throughput */
592                                         float pdf = dot(channel_pdf, transmittance);
593                                         new_tp = tp * transmittance / pdf;
594
595                                         /* remap xi so we can reuse it and keep thing stratified */
596                                         xi = 1.0f - (1.0f - xi)/sample_transmittance;
597                                 }
598                         }
599                         else
600 #endif
601                         if(closure_flag & SD_EXTINCTION) {
602                                 /* absorption only, no sampling needed */
603                                 transmittance = volume_color_transmittance(coeff.sigma_t, dt);
604                                 new_tp = tp * transmittance;
605                         }
606
607                         /* integrate emission attenuated by absorption */
608                         if(L && (closure_flag & SD_EMISSION)) {
609                                 float3 emission = kernel_volume_emission_integrate(&coeff, closure_flag, transmittance, dt);
610                                 path_radiance_accum_emission(L, state, tp, emission);
611                         }
612
613                         /* modify throughput */
614                         if(closure_flag & SD_EXTINCTION) {
615                                 tp = new_tp;
616
617                                 /* stop if nearly all light blocked */
618                                 if(tp.x < tp_eps && tp.y < tp_eps && tp.z < tp_eps) {
619                                         tp = make_float3(0.0f, 0.0f, 0.0f);
620                                         break;
621                                 }
622                         }
623
624                         /* prepare to scatter to new direction */
625                         if(scatter) {
626                                 /* adjust throughput and move to new location */
627                                 sd->P = ray->P + new_t*ray->D;
628                                 *throughput = tp;
629
630                                 return VOLUME_PATH_SCATTERED;
631                         }
632                         else {
633                                 /* accumulate transmittance */
634                                 accum_transmittance *= transmittance;
635                         }
636                 }
637
638                 /* stop if at the end of the volume */
639                 t = new_t;
640                 if(t == ray->t)
641                         break;
642         }
643
644         *throughput = tp;
645
646         return VOLUME_PATH_ATTENUATED;
647 }
648
649 /* get the volume attenuation and emission over line segment defined by
650  * ray, with the assumption that there are no surfaces blocking light
651  * between the endpoints. distance sampling is used to decide if we will
652  * scatter or not. */
653 ccl_device_noinline VolumeIntegrateResult kernel_volume_integrate(
654     KernelGlobals *kg,
655     ccl_addr_space PathState *state,
656     ShaderData *sd,
657     Ray *ray,
658     PathRadiance *L,
659     ccl_addr_space float3 *throughput,
660     bool heterogeneous)
661 {
662         shader_setup_from_volume(kg, sd, ray);
663
664         if(heterogeneous)
665                 return kernel_volume_integrate_heterogeneous_distance(kg, state, ray, sd, L, throughput);
666         else
667                 return kernel_volume_integrate_homogeneous(kg, state, ray, sd, L, throughput, true);
668 }
669
670 #ifndef __SPLIT_KERNEL__
671 /* Decoupled Volume Sampling
672  *
673  * VolumeSegment is list of coefficients and transmittance stored at all steps
674  * through a volume. This can then later be used for decoupled sampling as in:
675  * "Importance Sampling Techniques for Path Tracing in Participating Media"
676  *
677  * On the GPU this is only supported (but currently not enabled)
678  * for homogeneous volumes (1 step), due to
679  * no support for malloc/free and too much stack usage with a fix size array. */
680
681 typedef struct VolumeStep {
682         float3 sigma_s;                         /* scatter coefficient */
683         float3 sigma_t;                         /* extinction coefficient */
684         float3 accum_transmittance;     /* accumulated transmittance including this step */
685         float3 cdf_distance;            /* cumulative density function for distance sampling */
686         float t;                                        /* distance at end of this step */
687         float shade_t;                          /* jittered distance where shading was done in step */
688         int closure_flag;                       /* shader evaluation closure flags */
689 } VolumeStep;
690
691 typedef struct VolumeSegment {
692         VolumeStep stack_step;      /* stack storage for homogeneous step, to avoid malloc */
693         VolumeStep *steps;                      /* recorded steps */
694         int numsteps;                           /* number of steps */
695         int closure_flag;                       /* accumulated closure flags from all steps */
696
697         float3 accum_emission;          /* accumulated emission at end of segment */
698         float3 accum_transmittance;     /* accumulated transmittance at end of segment */
699         float3 accum_albedo;        /* accumulated average albedo over segment */
700
701         int sampling_method;            /* volume sampling method */
702 } VolumeSegment;
703
704 /* record volume steps to the end of the volume.
705  *
706  * it would be nice if we could only record up to the point that we need to scatter,
707  * but the entire segment is needed to do always scattering, rather than probabilistically
708  * hitting or missing the volume. if we don't know the transmittance at the end of the
709  * volume we can't generate stratified distance samples up to that transmittance */
710 #ifdef __VOLUME_DECOUPLED__
711 ccl_device void kernel_volume_decoupled_record(KernelGlobals *kg, PathState *state,
712         Ray *ray, ShaderData *sd, VolumeSegment *segment, bool heterogeneous)
713 {
714         const float tp_eps = 1e-6f; /* todo: this is likely not the right value */
715
716         /* prepare for volume stepping */
717         int max_steps;
718         float step_size, step_offset;
719
720         if(heterogeneous) {
721                 max_steps = kernel_data.integrator.volume_max_steps;
722                 kernel_volume_step_init(kg, state, ray->t, &step_size, &step_offset);
723
724 #ifdef __KERNEL_CPU__
725                 /* NOTE: For the branched path tracing it's possible to have direct
726                  * and indirect light integration both having volume segments allocated.
727                  * We detect this using index in the pre-allocated memory. Currently we
728                  * only support two segments allocated at a time, if more needed some
729                  * modifications to the KernelGlobals will be needed.
730                  *
731                  * This gives us restrictions that decoupled record should only happen
732                  * in the stack manner, meaning if there's subsequent call of decoupled
733                  * record it'll need to free memory before it's caller frees memory.
734                  */
735                 const int index = kg->decoupled_volume_steps_index;
736                 assert(index < sizeof(kg->decoupled_volume_steps) /
737                                sizeof(*kg->decoupled_volume_steps));
738                 if(kg->decoupled_volume_steps[index] == NULL) {
739                         kg->decoupled_volume_steps[index] =
740                                 (VolumeStep*)malloc(sizeof(VolumeStep)*max_steps);
741                 }
742                 segment->steps = kg->decoupled_volume_steps[index];
743                 ++kg->decoupled_volume_steps_index;
744 #else
745                 segment->steps = (VolumeStep*)malloc(sizeof(VolumeStep)*max_steps);
746 #endif
747         }
748         else {
749                 max_steps = 1;
750                 step_size = ray->t;
751                 step_offset = 0.0f;
752                 segment->steps = &segment->stack_step;
753         }
754
755         /* init accumulation variables */
756         float3 accum_emission = make_float3(0.0f, 0.0f, 0.0f);
757         float3 accum_transmittance = make_float3(1.0f, 1.0f, 1.0f);
758         float3 accum_albedo = make_float3(0.0f, 0.0f, 0.0f);
759         float3 cdf_distance = make_float3(0.0f, 0.0f, 0.0f);
760         float t = 0.0f;
761
762         segment->numsteps = 0;
763         segment->closure_flag = 0;
764         bool is_last_step_empty = false;
765
766         VolumeStep *step = segment->steps;
767
768         for(int i = 0; i < max_steps; i++, step++) {
769                 /* advance to new position */
770                 float new_t = min(ray->t, (i+1) * step_size);
771                 float dt = new_t - t;
772
773                 /* use random position inside this segment to sample shader,
774                 * for last shorter step we remap it to fit within the segment. */
775                 if(new_t == ray->t) {
776                         step_offset *= (new_t - t) / step_size;
777                 }
778
779                 float3 new_P = ray->P + ray->D * (t + step_offset);
780                 VolumeShaderCoefficients coeff;
781
782                 /* compute segment */
783                 if(volume_shader_sample(kg, sd, state, new_P, &coeff)) {
784                         int closure_flag = sd->flag;
785                         float3 sigma_t = coeff.sigma_t;
786
787                         /* compute average albedo for channel sampling */
788                         if(closure_flag & SD_SCATTER) {
789                                 accum_albedo += dt * safe_divide_color(coeff.sigma_s, sigma_t);
790                         }
791
792                         /* compute accumulated transmittance */
793                         float3 transmittance = volume_color_transmittance(sigma_t, dt);
794
795                         /* compute emission attenuated by absorption */
796                         if(closure_flag & SD_EMISSION) {
797                                 float3 emission = kernel_volume_emission_integrate(&coeff, closure_flag, transmittance, dt);
798                                 accum_emission += accum_transmittance * emission;
799                         }
800
801                         accum_transmittance *= transmittance;
802
803                         /* compute pdf for distance sampling */
804                         float3 pdf_distance = dt * accum_transmittance * coeff.sigma_s;
805                         cdf_distance = cdf_distance + pdf_distance;
806
807                         /* write step data */
808                         step->sigma_t = sigma_t;
809                         step->sigma_s = coeff.sigma_s;
810                         step->closure_flag = closure_flag;
811
812                         segment->closure_flag |= closure_flag;
813
814                         is_last_step_empty = false;
815                         segment->numsteps++;
816                 }
817                 else {
818                         if(is_last_step_empty) {
819                                 /* consecutive empty step, merge */
820                                 step--;
821                         }
822                         else {
823                                 /* store empty step */
824                                 step->sigma_t = make_float3(0.0f, 0.0f, 0.0f);
825                                 step->sigma_s = make_float3(0.0f, 0.0f, 0.0f);
826                                 step->closure_flag = 0;
827
828                                 segment->numsteps++;
829                                 is_last_step_empty = true;
830                         }
831                 }
832
833                 step->accum_transmittance = accum_transmittance;
834                 step->cdf_distance = cdf_distance;
835                 step->t = new_t;
836                 step->shade_t = t + step_offset;
837
838                 /* stop if at the end of the volume */
839                 t = new_t;
840                 if(t == ray->t)
841                         break;
842
843                 /* stop if nearly all light blocked */
844                 if(accum_transmittance.x < tp_eps && accum_transmittance.y < tp_eps && accum_transmittance.z < tp_eps)
845                         break;
846         }
847
848         /* store total emission and transmittance */
849         segment->accum_emission = accum_emission;
850         segment->accum_transmittance = accum_transmittance;
851         segment->accum_albedo = accum_albedo;
852
853         /* normalize cumulative density function for distance sampling */
854         VolumeStep *last_step = segment->steps + segment->numsteps - 1;
855
856         if(!is_zero(last_step->cdf_distance)) {
857                 VolumeStep *step = &segment->steps[0];
858                 int numsteps = segment->numsteps;
859                 float3 inv_cdf_distance_sum = safe_invert_color(last_step->cdf_distance);
860
861                 for(int i = 0; i < numsteps; i++, step++)
862                         step->cdf_distance *= inv_cdf_distance_sum;
863         }
864 }
865
866 ccl_device void kernel_volume_decoupled_free(KernelGlobals *kg, VolumeSegment *segment)
867 {
868         if(segment->steps != &segment->stack_step) {
869 #ifdef __KERNEL_CPU__
870                 /* NOTE: We only allow free last allocated segment.
871                  * No random order of alloc/free is supported.
872                  */
873                 assert(kg->decoupled_volume_steps_index > 0);
874                 assert(segment->steps == kg->decoupled_volume_steps[kg->decoupled_volume_steps_index - 1]);
875                 --kg->decoupled_volume_steps_index;
876 #else
877                 free(segment->steps);
878 #endif
879         }
880 }
881 #endif  /* __VOLUME_DECOUPLED__ */
882
883 /* scattering for homogeneous and heterogeneous volumes, using decoupled ray
884  * marching.
885  *
886  * function is expected to return VOLUME_PATH_SCATTERED when probalistic_scatter is false */
887 ccl_device VolumeIntegrateResult kernel_volume_decoupled_scatter(
888         KernelGlobals *kg, PathState *state, Ray *ray, ShaderData *sd,
889         float3 *throughput, float rphase, float rscatter,
890         const VolumeSegment *segment, const float3 *light_P, bool probalistic_scatter)
891 {
892         kernel_assert(segment->closure_flag & SD_SCATTER);
893
894         /* Sample color channel, use MIS with balance heuristic. */
895         float3 channel_pdf;
896         int channel = kernel_volume_sample_channel(segment->accum_albedo,
897                                                    *throughput,
898                                                    rphase,
899                                                    &channel_pdf);
900
901         float xi = rscatter;
902
903         /* probabilistic scattering decision based on transmittance */
904         if(probalistic_scatter) {
905                 float sample_transmittance = kernel_volume_channel_get(segment->accum_transmittance, channel);
906
907                 if(1.0f - xi >= sample_transmittance) {
908                         /* rescale random number so we can reuse it */
909                         xi = 1.0f - (1.0f - xi - sample_transmittance)/(1.0f - sample_transmittance);
910                 }
911                 else {
912                         *throughput /= sample_transmittance;
913                         return VOLUME_PATH_MISSED;
914                 }
915         }
916
917         VolumeStep *step;
918         float3 transmittance;
919         float pdf, sample_t;
920         float mis_weight = 1.0f;
921         bool distance_sample = true;
922         bool use_mis = false;
923
924         if(segment->sampling_method && light_P) {
925                 if(segment->sampling_method == SD_VOLUME_MIS) {
926                         /* multiple importance sample: randomly pick between
927                          * equiangular and distance sampling strategy */
928                         if(xi < 0.5f) {
929                                 xi *= 2.0f;
930                         }
931                         else {
932                                 xi = (xi - 0.5f)*2.0f;
933                                 distance_sample = false;
934                         }
935
936                         use_mis = true;
937                 }
938                 else {
939                         /* only equiangular sampling */
940                         distance_sample = false;
941                 }
942         }
943
944         /* distance sampling */
945         if(distance_sample) {
946                 /* find step in cdf */
947                 step = segment->steps;
948
949                 float prev_t = 0.0f;
950                 float3 step_pdf_distance = make_float3(1.0f, 1.0f, 1.0f);
951
952                 if(segment->numsteps > 1) {
953                         float prev_cdf = 0.0f;
954                         float step_cdf = 1.0f;
955                         float3 prev_cdf_distance = make_float3(0.0f, 0.0f, 0.0f);
956
957                         for(int i = 0; ; i++, step++) {
958                                 /* todo: optimize using binary search */
959                                 step_cdf = kernel_volume_channel_get(step->cdf_distance, channel);
960
961                                 if(xi < step_cdf || i == segment->numsteps-1)
962                                         break;
963
964                                 prev_cdf = step_cdf;
965                                 prev_t = step->t;
966                                 prev_cdf_distance = step->cdf_distance;
967                         }
968
969                         /* remap xi so we can reuse it */
970                         xi = (xi - prev_cdf)/(step_cdf - prev_cdf);
971
972                         /* pdf for picking step */
973                         step_pdf_distance = step->cdf_distance - prev_cdf_distance;
974                 }
975
976                 /* determine range in which we will sample */
977                 float step_t = step->t - prev_t;
978
979                 /* sample distance and compute transmittance */
980                 float3 distance_pdf;
981                 sample_t = prev_t + kernel_volume_distance_sample(step_t, step->sigma_t, channel, xi, &transmittance, &distance_pdf);
982
983                 /* modify pdf for hit/miss decision */
984                 if(probalistic_scatter)
985                         distance_pdf *= make_float3(1.0f, 1.0f, 1.0f) - segment->accum_transmittance;
986
987                 pdf = dot(channel_pdf, distance_pdf * step_pdf_distance);
988
989                 /* multiple importance sampling */
990                 if(use_mis) {
991                         float equi_pdf = kernel_volume_equiangular_pdf(ray, *light_P, sample_t);
992                         mis_weight = 2.0f*power_heuristic(pdf, equi_pdf);
993                 }
994         }
995         /* equi-angular sampling */
996         else {
997                 /* sample distance */
998                 sample_t = kernel_volume_equiangular_sample(ray, *light_P, xi, &pdf);
999
1000                 /* find step in which sampled distance is located */
1001                 step = segment->steps;
1002
1003                 float prev_t = 0.0f;
1004                 float3 step_pdf_distance = make_float3(1.0f, 1.0f, 1.0f);
1005
1006                 if(segment->numsteps > 1) {
1007                         float3 prev_cdf_distance = make_float3(0.0f, 0.0f, 0.0f);
1008
1009                         int numsteps = segment->numsteps;
1010                         int high = numsteps - 1;
1011                         int low = 0;
1012                         int mid;
1013
1014                         while(low < high) {
1015                                 mid = (low + high) >> 1;
1016
1017                                 if(sample_t < step[mid].t)
1018                                         high = mid;
1019                                 else if(sample_t >= step[mid + 1].t)
1020                                         low = mid + 1;
1021                                 else {
1022                                         /* found our interval in step[mid] .. step[mid+1] */
1023                                         prev_t = step[mid].t;
1024                                         prev_cdf_distance = step[mid].cdf_distance;
1025                                         step += mid+1;
1026                                         break;
1027                                 }
1028                         }
1029
1030                         if(low >= numsteps - 1) {
1031                                 prev_t = step[numsteps - 1].t;
1032                                 prev_cdf_distance = step[numsteps-1].cdf_distance;
1033                                 step += numsteps - 1;
1034                         }
1035
1036                         /* pdf for picking step with distance sampling */
1037                         step_pdf_distance = step->cdf_distance - prev_cdf_distance;
1038                 }
1039
1040                 /* determine range in which we will sample */
1041                 float step_t = step->t - prev_t;
1042                 float step_sample_t = sample_t - prev_t;
1043
1044                 /* compute transmittance */
1045                 transmittance = volume_color_transmittance(step->sigma_t, step_sample_t);
1046
1047                 /* multiple importance sampling */
1048                 if(use_mis) {
1049                         float3 distance_pdf3 = kernel_volume_distance_pdf(step_t, step->sigma_t, step_sample_t);
1050                         float distance_pdf = dot(channel_pdf, distance_pdf3 * step_pdf_distance);
1051                         mis_weight = 2.0f*power_heuristic(pdf, distance_pdf);
1052                 }
1053         }
1054         if(sample_t < 0.0f || pdf == 0.0f) {
1055                 return VOLUME_PATH_MISSED;
1056         }
1057
1058         /* compute transmittance up to this step */
1059         if(step != segment->steps)
1060                 transmittance *= (step-1)->accum_transmittance;
1061
1062         /* modify throughput */
1063         *throughput *= step->sigma_s * transmittance * (mis_weight / pdf);
1064
1065         /* evaluate shader to create closures at shading point */
1066         if(segment->numsteps > 1) {
1067                 sd->P = ray->P + step->shade_t*ray->D;
1068
1069                 VolumeShaderCoefficients coeff;
1070                 volume_shader_sample(kg, sd, state, sd->P, &coeff);
1071         }
1072
1073         /* move to new position */
1074         sd->P = ray->P + sample_t*ray->D;
1075
1076         return VOLUME_PATH_SCATTERED;
1077 }
1078 #endif  /* __SPLIT_KERNEL */
1079
1080 /* decide if we need to use decoupled or not */
1081 ccl_device bool kernel_volume_use_decoupled(KernelGlobals *kg, bool heterogeneous, bool direct, int sampling_method)
1082 {
1083         /* decoupled ray marching for heterogeneous volumes not supported on the GPU,
1084          * which also means equiangular and multiple importance sampling is not
1085          * support for that case */
1086         if(!kernel_data.integrator.volume_decoupled)
1087                 return false;
1088
1089 #ifdef __KERNEL_GPU__
1090         if(heterogeneous)
1091                 return false;
1092 #endif
1093
1094         /* equiangular and multiple importance sampling only implemented for decoupled */
1095         if(sampling_method != 0)
1096                 return true;
1097
1098         /* for all light sampling use decoupled, reusing shader evaluations is
1099          * typically faster in that case */
1100         if(direct)
1101                 return kernel_data.integrator.sample_all_lights_direct;
1102         else
1103                 return kernel_data.integrator.sample_all_lights_indirect;
1104 }
1105
1106 /* Volume Stack
1107  *
1108  * This is an array of object/shared ID's that the current segment of the path
1109  * is inside of. */
1110
1111 ccl_device void kernel_volume_stack_init(KernelGlobals *kg,
1112                                          ShaderData *stack_sd,
1113                                          ccl_addr_space const PathState *state,
1114                                          ccl_addr_space const Ray *ray,
1115                                          ccl_addr_space VolumeStack *stack)
1116 {
1117         /* NULL ray happens in the baker, does it need proper initialization of
1118          * camera in volume?
1119          */
1120         if(!kernel_data.cam.is_inside_volume || ray == NULL) {
1121                 /* Camera is guaranteed to be in the air, only take background volume
1122                  * into account in this case.
1123                  */
1124                 if(kernel_data.background.volume_shader != SHADER_NONE) {
1125                         stack[0].shader = kernel_data.background.volume_shader;
1126                         stack[0].object = PRIM_NONE;
1127                         stack[1].shader = SHADER_NONE;
1128                 }
1129                 else {
1130                         stack[0].shader = SHADER_NONE;
1131                 }
1132                 return;
1133         }
1134
1135         kernel_assert(state->flag & PATH_RAY_CAMERA);
1136
1137         Ray volume_ray = *ray;
1138         volume_ray.t = FLT_MAX;
1139
1140         const uint visibility = (state->flag & PATH_RAY_ALL_VISIBILITY);
1141         int stack_index = 0, enclosed_index = 0;
1142
1143 #ifdef __VOLUME_RECORD_ALL__
1144         Intersection hits[2*VOLUME_STACK_SIZE + 1];
1145         uint num_hits = scene_intersect_volume_all(kg,
1146                                                    &volume_ray,
1147                                                    hits,
1148                                                    2*VOLUME_STACK_SIZE,
1149                                                    visibility);
1150         if(num_hits > 0) {
1151                 int enclosed_volumes[VOLUME_STACK_SIZE];
1152                 Intersection *isect = hits;
1153
1154                 qsort(hits, num_hits, sizeof(Intersection), intersections_compare);
1155
1156                 for(uint hit = 0; hit < num_hits; ++hit, ++isect) {
1157                         shader_setup_from_ray(kg, stack_sd, isect, &volume_ray);
1158                         if(stack_sd->flag & SD_BACKFACING) {
1159                                 bool need_add = true;
1160                                 for(int i = 0; i < enclosed_index && need_add; ++i) {
1161                                         /* If ray exited the volume and never entered to that volume
1162                                          * it means that camera is inside such a volume.
1163                                          */
1164                                         if(enclosed_volumes[i] == stack_sd->object) {
1165                                                 need_add = false;
1166                                         }
1167                                 }
1168                                 for(int i = 0; i < stack_index && need_add; ++i) {
1169                                         /* Don't add intersections twice. */
1170                                         if(stack[i].object == stack_sd->object) {
1171                                                 need_add = false;
1172                                                 break;
1173                                         }
1174                                 }
1175                                 if(need_add && stack_index < VOLUME_STACK_SIZE - 1) {
1176                                         stack[stack_index].object = stack_sd->object;
1177                                         stack[stack_index].shader = stack_sd->shader;
1178                                         ++stack_index;
1179                                 }
1180                         }
1181                         else {
1182                                 /* If ray from camera enters the volume, this volume shouldn't
1183                                  * be added to the stack on exit.
1184                                  */
1185                                 enclosed_volumes[enclosed_index++] = stack_sd->object;
1186                         }
1187                 }
1188         }
1189 #else
1190         int enclosed_volumes[VOLUME_STACK_SIZE];
1191         int step = 0;
1192
1193         while(stack_index < VOLUME_STACK_SIZE - 1 &&
1194               enclosed_index < VOLUME_STACK_SIZE - 1 &&
1195               step < 2 * VOLUME_STACK_SIZE)
1196         {
1197                 Intersection isect;
1198                 if(!scene_intersect_volume(kg, &volume_ray, &isect, visibility)) {
1199                         break;
1200                 }
1201
1202                 shader_setup_from_ray(kg, stack_sd, &isect, &volume_ray);
1203                 if(stack_sd->flag & SD_BACKFACING) {
1204                         /* If ray exited the volume and never entered to that volume
1205                          * it means that camera is inside such a volume.
1206                          */
1207                         bool need_add = true;
1208                         for(int i = 0; i < enclosed_index && need_add; ++i) {
1209                                 /* If ray exited the volume and never entered to that volume
1210                                  * it means that camera is inside such a volume.
1211                                  */
1212                                 if(enclosed_volumes[i] == stack_sd->object) {
1213                                         need_add = false;
1214                                 }
1215                         }
1216                         for(int i = 0; i < stack_index && need_add; ++i) {
1217                                 /* Don't add intersections twice. */
1218                                 if(stack[i].object == stack_sd->object) {
1219                                         need_add = false;
1220                                         break;
1221                                 }
1222                         }
1223                         if(need_add) {
1224                                 stack[stack_index].object = stack_sd->object;
1225                                 stack[stack_index].shader = stack_sd->shader;
1226                                 ++stack_index;
1227                         }
1228                 }
1229                 else {
1230                         /* If ray from camera enters the volume, this volume shouldn't
1231                          * be added to the stack on exit.
1232                          */
1233                         enclosed_volumes[enclosed_index++] = stack_sd->object;
1234                 }
1235
1236                 /* Move ray forward. */
1237                 volume_ray.P = ray_offset(stack_sd->P, -stack_sd->Ng);
1238                 ++step;
1239         }
1240 #endif
1241         /* stack_index of 0 means quick checks outside of the kernel gave false
1242          * positive, nothing to worry about, just we've wasted quite a few of
1243          * ticks just to come into conclusion that camera is in the air.
1244          *
1245          * In this case we're doing the same above -- check whether background has
1246          * volume.
1247          */
1248         if(stack_index == 0 && kernel_data.background.volume_shader == SHADER_NONE) {
1249                 stack[0].shader = kernel_data.background.volume_shader;
1250                 stack[0].object = PRIM_NONE;
1251                 stack[1].shader = SHADER_NONE;
1252         }
1253         else {
1254                 stack[stack_index].shader = SHADER_NONE;
1255         }
1256 }
1257
1258 ccl_device void kernel_volume_stack_enter_exit(KernelGlobals *kg, ShaderData *sd, ccl_addr_space VolumeStack *stack)
1259 {
1260         /* todo: we should have some way for objects to indicate if they want the
1261          * world shader to work inside them. excluding it by default is problematic
1262          * because non-volume objects can't be assumed to be closed manifolds */
1263
1264         if(!(sd->flag & SD_HAS_VOLUME))
1265                 return;
1266
1267         if(sd->flag & SD_BACKFACING) {
1268                 /* exit volume object: remove from stack */
1269                 for(int i = 0; stack[i].shader != SHADER_NONE; i++) {
1270                         if(stack[i].object == sd->object) {
1271                                 /* shift back next stack entries */
1272                                 do {
1273                                         stack[i] = stack[i+1];
1274                                         i++;
1275                                 }
1276                                 while(stack[i].shader != SHADER_NONE);
1277
1278                                 return;
1279                         }
1280                 }
1281         }
1282         else {
1283                 /* enter volume object: add to stack */
1284                 int i;
1285
1286                 for(i = 0; stack[i].shader != SHADER_NONE; i++) {
1287                         /* already in the stack? then we have nothing to do */
1288                         if(stack[i].object == sd->object)
1289                                 return;
1290                 }
1291
1292                 /* if we exceed the stack limit, ignore */
1293                 if(i >= VOLUME_STACK_SIZE-1)
1294                         return;
1295
1296                 /* add to the end of the stack */
1297                 stack[i].shader = sd->shader;
1298                 stack[i].object = sd->object;
1299                 stack[i+1].shader = SHADER_NONE;
1300         }
1301 }
1302
1303 #ifdef __SUBSURFACE__
1304 ccl_device void kernel_volume_stack_update_for_subsurface(KernelGlobals *kg,
1305                                                           ShaderData *stack_sd,
1306                                                           Ray *ray,
1307                                                           ccl_addr_space VolumeStack *stack)
1308 {
1309         kernel_assert(kernel_data.integrator.use_volumes);
1310
1311         Ray volume_ray = *ray;
1312
1313 #  ifdef __VOLUME_RECORD_ALL__
1314         Intersection hits[2*VOLUME_STACK_SIZE + 1];
1315         uint num_hits = scene_intersect_volume_all(kg,
1316                                                    &volume_ray,
1317                                                    hits,
1318                                                    2*VOLUME_STACK_SIZE,
1319                                                    PATH_RAY_ALL_VISIBILITY);
1320         if(num_hits > 0) {
1321                 Intersection *isect = hits;
1322
1323                 qsort(hits, num_hits, sizeof(Intersection), intersections_compare);
1324
1325                 for(uint hit = 0; hit < num_hits; ++hit, ++isect) {
1326                         shader_setup_from_ray(kg, stack_sd, isect, &volume_ray);
1327                         kernel_volume_stack_enter_exit(kg, stack_sd, stack);
1328                 }
1329         }
1330 #  else
1331         Intersection isect;
1332         int step = 0;
1333         float3 Pend = ray->P + ray->D*ray->t;
1334         while(step < 2 * VOLUME_STACK_SIZE &&
1335               scene_intersect_volume(kg,
1336                                      &volume_ray,
1337                                      &isect,
1338                                      PATH_RAY_ALL_VISIBILITY))
1339         {
1340                 shader_setup_from_ray(kg, stack_sd, &isect, &volume_ray);
1341                 kernel_volume_stack_enter_exit(kg, stack_sd, stack);
1342
1343                 /* Move ray forward. */
1344                 volume_ray.P = ray_offset(stack_sd->P, -stack_sd->Ng);
1345                 if(volume_ray.t != FLT_MAX) {
1346                         volume_ray.D = normalize_len(Pend - volume_ray.P, &volume_ray.t);
1347                 }
1348                 ++step;
1349         }
1350 #  endif
1351 }
1352 #endif
1353
1354 /* Clean stack after the last bounce.
1355  *
1356  * It is expected that all volumes are closed manifolds, so at the time when ray
1357  * hits nothing (for example, it is a last bounce which goes to environment) the
1358  * only expected volume in the stack is the world's one. All the rest volume
1359  * entries should have been exited already.
1360  *
1361  * This isn't always true because of ray intersection precision issues, which
1362  * could lead us to an infinite non-world volume in the stack, causing render
1363  * artifacts.
1364  *
1365  * Use this function after the last bounce to get rid of all volumes apart from
1366  * the world's one after the last bounce to avoid render artifacts.
1367  */
1368 ccl_device_inline void kernel_volume_clean_stack(KernelGlobals *kg,
1369                                                  ccl_addr_space VolumeStack *volume_stack)
1370 {
1371         if(kernel_data.background.volume_shader != SHADER_NONE) {
1372                 /* Keep the world's volume in stack. */
1373                 volume_stack[1].shader = SHADER_NONE;
1374         }
1375         else {
1376                 volume_stack[0].shader = SHADER_NONE;
1377         }
1378 }
1379
1380 #endif  /* __VOLUME__ */
1381
1382 CCL_NAMESPACE_END