Attempt to fix #35041 and #34725: cycles crash with OSL and both a 3D viewport
[blender.git] / intern / cycles / kernel / osl / osl_shader.cpp
1 /*
2  * Copyright 2011, Blender Foundation.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  */
18
19 #include "kernel_compat_cpu.h"
20 #include "kernel_types.h"
21 #include "kernel_globals.h"
22 #include "kernel_object.h"
23
24 #include "osl_bssrdf.h"
25 #include "osl_closures.h"
26 #include "osl_globals.h"
27 #include "osl_services.h"
28 #include "osl_shader.h"
29
30 #include "util_foreach.h"
31
32 #include "attribute.h"
33
34 #include <OSL/oslexec.h>
35
36 CCL_NAMESPACE_BEGIN
37
38 /* Threads */
39
40 void OSLShader::thread_init(KernelGlobals *kg, KernelGlobals *kernel_globals, OSLGlobals *osl_globals)
41 {
42         /* no osl used? */
43         if(!osl_globals->use) {
44                 kg->osl = NULL;
45                 return;
46         }
47
48         /* per thread kernel data init*/
49         kg->osl = osl_globals;
50         kg->osl->services->thread_init(kernel_globals);
51
52         OSL::ShadingSystem *ss = kg->osl->ss;
53         OSLThreadData *tdata = new OSLThreadData();
54
55         memset(&tdata->globals, 0, sizeof(OSL::ShaderGlobals));
56         tdata->globals.tracedata = &tdata->tracedata;
57         tdata->globals.flipHandedness = false;
58         tdata->thread_info = ss->create_thread_info();
59
60         for(int i = 0; i < SHADER_CONTEXT_NUM; i++)
61                 tdata->context[i] = ss->get_context(tdata->thread_info);
62
63         kg->osl_ss = (OSLShadingSystem*)ss;
64         kg->osl_tdata = tdata;
65 }
66
67 void OSLShader::thread_free(KernelGlobals *kg)
68 {
69         if(!kg->osl)
70                 return;
71
72         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)kg->osl_ss;
73         OSLThreadData *tdata = kg->osl_tdata;
74
75         for(int i = 0; i < SHADER_CONTEXT_NUM; i++)
76                 ss->release_context(tdata->context[i]);
77
78         ss->destroy_thread_info(tdata->thread_info);
79
80         delete tdata;
81
82         kg->osl = NULL;
83         kg->osl_ss = NULL;
84         kg->osl_tdata = NULL;
85 }
86
87 /* Globals */
88
89 static void shaderdata_to_shaderglobals(KernelGlobals *kg, ShaderData *sd,
90                                         int path_flag, OSLThreadData *tdata)
91 {
92         OSL::ShaderGlobals *globals = &tdata->globals;
93
94         /* copy from shader data to shader globals */
95         globals->P = TO_VEC3(sd->P);
96         globals->dPdx = TO_VEC3(sd->dP.dx);
97         globals->dPdy = TO_VEC3(sd->dP.dy);
98         globals->I = TO_VEC3(sd->I);
99         globals->dIdx = TO_VEC3(sd->dI.dx);
100         globals->dIdy = TO_VEC3(sd->dI.dy);
101         globals->N = TO_VEC3(sd->N);
102         globals->Ng = TO_VEC3(sd->Ng);
103         globals->u = sd->u;
104         globals->dudx = sd->du.dx;
105         globals->dudy = sd->du.dy;
106         globals->v = sd->v;
107         globals->dvdx = sd->dv.dx;
108         globals->dvdy = sd->dv.dy;
109         globals->dPdu = TO_VEC3(sd->dPdu);
110         globals->dPdv = TO_VEC3(sd->dPdv);
111         globals->surfacearea = (sd->object == ~0) ? 1.0f : object_surface_area(kg, sd->object);
112         globals->time = sd->time;
113
114         /* booleans */
115         globals->raytype = path_flag;
116         globals->backfacing = (sd->flag & SD_BACKFACING);
117
118         /* shader data to be used in services callbacks */
119         globals->renderstate = sd; 
120
121         /* hacky, we leave it to services to fetch actual object matrix */
122         globals->shader2common = sd;
123         globals->object2common = sd;
124
125         /* must be set to NULL before execute */
126         globals->Ci = NULL;
127
128         /* clear trace data */
129         tdata->tracedata.init = false;
130
131         /* used by renderservices */
132         sd->osl_globals = kg;
133 }
134
135 /* Surface */
136
137 static void flatten_surface_closure_tree(ShaderData *sd, bool no_glossy,
138                                          const OSL::ClosureColor *closure, float3 weight = make_float3(1.0f, 1.0f, 1.0f))
139 {
140         /* OSL gives us a closure tree, we flatten it into arrays per
141          * closure type, for evaluation, sampling, etc later on. */
142
143         if (closure->type == OSL::ClosureColor::COMPONENT) {
144                 OSL::ClosureComponent *comp = (OSL::ClosureComponent *)closure;
145                 OSL::ClosurePrimitive *prim = (OSL::ClosurePrimitive *)comp->data();
146
147                 if (prim) {
148                         ShaderClosure sc;
149                         sc.weight = weight;
150
151                         switch (prim->category()) {
152                                 case OSL::ClosurePrimitive::BSDF: {
153                                         CBSDFClosure *bsdf = (CBSDFClosure *)prim;
154                                         int scattering = bsdf->scattering();
155
156                                         /* no caustics option */
157                                         if (no_glossy && scattering == LABEL_GLOSSY)
158                                                 return;
159
160                                         /* sample weight */
161                                         float sample_weight = fabsf(average(weight));
162
163                                         sc.sample_weight = sample_weight;
164
165                                         sc.type = bsdf->sc.type;
166                                         sc.N = bsdf->sc.N;
167                                         sc.T = bsdf->sc.T;
168                                         sc.data0 = bsdf->sc.data0;
169                                         sc.data1 = bsdf->sc.data1;
170                                         sc.prim = bsdf->sc.prim;
171
172                                         /* add */
173                                         if(sc.sample_weight > 1e-5f && sd->num_closure < MAX_CLOSURE) {
174                                                 sd->closure[sd->num_closure++] = sc;
175                                                 sd->flag |= bsdf->shaderdata_flag();
176                                         }
177                                         break;
178                                 }
179                                 case OSL::ClosurePrimitive::Emissive: {
180                                         /* sample weight */
181                                         float sample_weight = fabsf(average(weight));
182
183                                         sc.sample_weight = sample_weight;
184                                         sc.type = CLOSURE_EMISSION_ID;
185                                         sc.prim = NULL;
186
187                                         /* flag */
188                                         if(sd->num_closure < MAX_CLOSURE) {
189                                                 sd->closure[sd->num_closure++] = sc;
190                                                 sd->flag |= SD_EMISSION;
191                                         }
192                                         break;
193                                 }
194                                 case AmbientOcclusion: {
195                                         /* sample weight */
196                                         float sample_weight = fabsf(average(weight));
197
198                                         sc.sample_weight = sample_weight;
199                                         sc.type = CLOSURE_AMBIENT_OCCLUSION_ID;
200                                         sc.prim = NULL;
201
202                                         if(sd->num_closure < MAX_CLOSURE) {
203                                                 sd->closure[sd->num_closure++] = sc;
204                                                 sd->flag |= SD_AO;
205                                         }
206                                         break;
207                                 }
208                                 case OSL::ClosurePrimitive::Holdout: {
209                                         sc.sample_weight = 0.0f;
210                                         sc.type = CLOSURE_HOLDOUT_ID;
211                                         sc.prim = NULL;
212
213                                         if(sd->num_closure < MAX_CLOSURE) {
214                                                 sd->closure[sd->num_closure++] = sc;
215                                                 sd->flag |= SD_HOLDOUT;
216                                         }
217                                         break;
218                                 }
219                                 case OSL::ClosurePrimitive::BSSRDF: {
220                                         CBSSRDFClosure *bssrdf = (CBSSRDFClosure *)prim;
221                                         float sample_weight = fabsf(average(weight));
222
223                                         if(sample_weight > 1e-5f && sd->num_closure+2 < MAX_CLOSURE) {
224                                                 sc.sample_weight = sample_weight;
225
226                                                 sc.type = bssrdf->sc.type;
227                                                 sc.N = bssrdf->sc.N;
228                                                 sc.data1 = bssrdf->sc.data1;
229                                                 sc.prim = NULL;
230
231                                                 /* create one closure for each color channel */
232                                                 if(fabsf(weight.x) > 0.0f) {
233                                                         sc.weight = make_float3(weight.x, 0.0f, 0.0f);
234                                                         sc.data0 = bssrdf->radius.x;
235                                                         sd->closure[sd->num_closure++] = sc;
236                                                         sd->flag |= bssrdf->shaderdata_flag();
237                                                 }
238
239                                                 if(fabsf(weight.y) > 0.0f) {
240                                                         sc.weight = make_float3(0.0f, weight.y, 0.0f);
241                                                         sc.data0 = bssrdf->radius.y;
242                                                         sd->closure[sd->num_closure++] = sc;
243                                                         sd->flag |= bssrdf->shaderdata_flag();
244                                                 }
245
246                                                 if(fabsf(weight.z) > 0.0f) {
247                                                         sc.weight = make_float3(0.0f, 0.0f, weight.z);
248                                                         sc.data0 = bssrdf->radius.z;
249                                                         sd->closure[sd->num_closure++] = sc;
250                                                         sd->flag |= bssrdf->shaderdata_flag();
251                                                 }
252                                         }
253                                         break;
254                                 }
255                                 case OSL::ClosurePrimitive::Debug:
256                                         break; /* not implemented */
257                                 case OSL::ClosurePrimitive::Background:
258                                 case OSL::ClosurePrimitive::Volume:
259                                         break; /* not relevant */
260                         }
261                 }
262         }
263         else if (closure->type == OSL::ClosureColor::MUL) {
264                 OSL::ClosureMul *mul = (OSL::ClosureMul *)closure;
265                 flatten_surface_closure_tree(sd, no_glossy, mul->closure, TO_FLOAT3(mul->weight) * weight);
266         }
267         else if (closure->type == OSL::ClosureColor::ADD) {
268                 OSL::ClosureAdd *add = (OSL::ClosureAdd *)closure;
269                 flatten_surface_closure_tree(sd, no_glossy, add->closureA, weight);
270                 flatten_surface_closure_tree(sd, no_glossy, add->closureB, weight);
271         }
272 }
273
274 void OSLShader::eval_surface(KernelGlobals *kg, ShaderData *sd, float randb, int path_flag, ShaderContext ctx)
275 {
276         /* setup shader globals from shader data */
277         OSLThreadData *tdata = kg->osl_tdata;
278         shaderdata_to_shaderglobals(kg, sd, path_flag, tdata);
279
280         /* execute shader for this point */
281         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)kg->osl_ss;
282         OSL::ShaderGlobals *globals = &tdata->globals;
283         OSL::ShadingContext *octx = tdata->context[(int)ctx];
284         int shader = sd->shader & SHADER_MASK;
285
286         if (kg->osl->surface_state[shader])
287                 ss->execute(*octx, *(kg->osl->surface_state[shader]), *globals);
288
289         /* flatten closure tree */
290         sd->num_closure = 0;
291         sd->randb_closure = randb;
292
293         if (globals->Ci) {
294                 bool no_glossy = (path_flag & PATH_RAY_DIFFUSE) && kernel_data.integrator.no_caustics;
295                 flatten_surface_closure_tree(sd, no_glossy, globals->Ci);
296         }
297 }
298
299 /* Background */
300
301 static float3 flatten_background_closure_tree(const OSL::ClosureColor *closure)
302 {
303         /* OSL gives us a closure tree, if we are shading for background there
304          * is only one supported closure type at the moment, which has no evaluation
305          * functions, so we just sum the weights */
306
307         if (closure->type == OSL::ClosureColor::COMPONENT) {
308                 OSL::ClosureComponent *comp = (OSL::ClosureComponent *)closure;
309                 OSL::ClosurePrimitive *prim = (OSL::ClosurePrimitive *)comp->data();
310
311                 if (prim && prim->category() == OSL::ClosurePrimitive::Background)
312                         return make_float3(1.0f, 1.0f, 1.0f);
313         }
314         else if (closure->type == OSL::ClosureColor::MUL) {
315                 OSL::ClosureMul *mul = (OSL::ClosureMul *)closure;
316
317                 return TO_FLOAT3(mul->weight) * flatten_background_closure_tree(mul->closure);
318         }
319         else if (closure->type == OSL::ClosureColor::ADD) {
320                 OSL::ClosureAdd *add = (OSL::ClosureAdd *)closure;
321
322                 return flatten_background_closure_tree(add->closureA) +
323                        flatten_background_closure_tree(add->closureB);
324         }
325
326         return make_float3(0.0f, 0.0f, 0.0f);
327 }
328
329 float3 OSLShader::eval_background(KernelGlobals *kg, ShaderData *sd, int path_flag, ShaderContext ctx)
330 {
331         /* setup shader globals from shader data */
332         OSLThreadData *tdata = kg->osl_tdata;
333         shaderdata_to_shaderglobals(kg, sd, path_flag, tdata);
334
335         /* execute shader for this point */
336         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)kg->osl_ss;
337         OSL::ShaderGlobals *globals = &tdata->globals;
338         OSL::ShadingContext *octx = tdata->context[(int)ctx];
339
340         if (kg->osl->background_state)
341                 ss->execute(*octx, *(kg->osl->background_state), *globals);
342
343         /* return background color immediately */
344         if (globals->Ci)
345                 return flatten_background_closure_tree(globals->Ci);
346
347         return make_float3(0.0f, 0.0f, 0.0f);
348 }
349
350 /* Volume */
351
352 static void flatten_volume_closure_tree(ShaderData *sd,
353                                         const OSL::ClosureColor *closure, float3 weight = make_float3(1.0f, 1.0f, 1.0f))
354 {
355         /* OSL gives us a closure tree, we flatten it into arrays per
356          * closure type, for evaluation, sampling, etc later on. */
357
358         if (closure->type == OSL::ClosureColor::COMPONENT) {
359                 OSL::ClosureComponent *comp = (OSL::ClosureComponent *)closure;
360                 OSL::ClosurePrimitive *prim = (OSL::ClosurePrimitive *)comp->data();
361
362                 if (prim) {
363                         ShaderClosure sc;
364                         sc.weight = weight;
365
366                         switch (prim->category()) {
367                                 case OSL::ClosurePrimitive::Volume: {
368                                         /* sample weight */
369                                         float sample_weight = fabsf(average(weight));
370
371                                         sc.sample_weight = sample_weight;
372                                         sc.type = CLOSURE_VOLUME_ID;
373                                         sc.prim = NULL;
374
375                                         /* add */
376                                         if(sc.sample_weight > 1e-5f && sd->num_closure < MAX_CLOSURE)
377                                                 sd->closure[sd->num_closure++] = sc;
378                                         break;
379                                 }
380                                 case OSL::ClosurePrimitive::Holdout:
381                                 case OSL::ClosurePrimitive::Debug:
382                                         break; /* not implemented */
383                                 case OSL::ClosurePrimitive::Background:
384                                 case OSL::ClosurePrimitive::BSDF:
385                                 case OSL::ClosurePrimitive::Emissive:
386                                 case OSL::ClosurePrimitive::BSSRDF:
387                                         break; /* not relevant */
388                         }
389                 }
390         }
391         else if (closure->type == OSL::ClosureColor::MUL) {
392                 OSL::ClosureMul *mul = (OSL::ClosureMul *)closure;
393                 flatten_volume_closure_tree(sd, mul->closure, TO_FLOAT3(mul->weight) * weight);
394         }
395         else if (closure->type == OSL::ClosureColor::ADD) {
396                 OSL::ClosureAdd *add = (OSL::ClosureAdd *)closure;
397                 flatten_volume_closure_tree(sd, add->closureA, weight);
398                 flatten_volume_closure_tree(sd, add->closureB, weight);
399         }
400 }
401
402 void OSLShader::eval_volume(KernelGlobals *kg, ShaderData *sd, float randb, int path_flag, ShaderContext ctx)
403 {
404         /* setup shader globals from shader data */
405         OSLThreadData *tdata = kg->osl_tdata;
406         shaderdata_to_shaderglobals(kg, sd, path_flag, tdata);
407
408         /* execute shader */
409         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)kg->osl_ss;
410         OSL::ShaderGlobals *globals = &tdata->globals;
411         OSL::ShadingContext *octx = tdata->context[(int)ctx];
412         int shader = sd->shader & SHADER_MASK;
413
414         if (kg->osl->volume_state[shader])
415                 ss->execute(*octx, *(kg->osl->volume_state[shader]), *globals);
416
417         if (globals->Ci)
418                 flatten_volume_closure_tree(sd, globals->Ci);
419 }
420
421 /* Displacement */
422
423 void OSLShader::eval_displacement(KernelGlobals *kg, ShaderData *sd, ShaderContext ctx)
424 {
425         /* setup shader globals from shader data */
426         OSLThreadData *tdata = kg->osl_tdata;
427         shaderdata_to_shaderglobals(kg, sd, 0, tdata);
428
429         /* execute shader */
430         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)kg->osl_ss;
431         OSL::ShaderGlobals *globals = &tdata->globals;
432         OSL::ShadingContext *octx = tdata->context[(int)ctx];
433         int shader = sd->shader & SHADER_MASK;
434
435         if (kg->osl->displacement_state[shader])
436                 ss->execute(*octx, *(kg->osl->displacement_state[shader]), *globals);
437
438         /* get back position */
439         sd->P = TO_FLOAT3(globals->P);
440 }
441
442 /* BSDF Closure */
443
444 int OSLShader::bsdf_sample(const ShaderData *sd, const ShaderClosure *sc, float randu, float randv, float3& eval, float3& omega_in, differential3& domega_in, float& pdf)
445 {
446         CBSDFClosure *sample_bsdf = (CBSDFClosure *)sc->prim;
447
448         pdf = 0.0f;
449
450         return sample_bsdf->sample(sd->Ng,
451                                    sd->I, sd->dI.dx, sd->dI.dy,
452                                    randu, randv,
453                                    omega_in, domega_in.dx, domega_in.dy,
454                                    pdf, eval);
455 }
456
457 float3 OSLShader::bsdf_eval(const ShaderData *sd, const ShaderClosure *sc, const float3& omega_in, float& pdf)
458 {
459         CBSDFClosure *bsdf = (CBSDFClosure *)sc->prim;
460         float3 bsdf_eval;
461
462         if (dot(sd->Ng, omega_in) >= 0.0f)
463                 bsdf_eval = bsdf->eval_reflect(sd->I, omega_in, pdf);
464         else
465                 bsdf_eval = bsdf->eval_transmit(sd->I, omega_in, pdf);
466         
467         return bsdf_eval;
468 }
469
470 void OSLShader::bsdf_blur(ShaderClosure *sc, float roughness)
471 {
472         CBSDFClosure *bsdf = (CBSDFClosure *)sc->prim;
473         bsdf->blur(roughness);
474 }
475
476 /* Emissive Closure */
477
478 float3 OSLShader::emissive_eval(const ShaderData *sd, const ShaderClosure *sc)
479 {
480         OSL::EmissiveClosure *emissive = (OSL::EmissiveClosure *)sc->prim;
481         OSL::Color3 emissive_eval = emissive->eval(TO_VEC3(sd->Ng), TO_VEC3(sd->I));
482
483         return TO_FLOAT3(emissive_eval);
484 }
485
486 /* Volume Closure */
487
488 float3 OSLShader::volume_eval_phase(const ShaderClosure *sc, const float3 omega_in, const float3 omega_out)
489 {
490         OSL::VolumeClosure *volume = (OSL::VolumeClosure *)sc->prim;
491         OSL::Color3 volume_eval = volume->eval_phase(TO_VEC3(omega_in), TO_VEC3(omega_out));
492         return TO_FLOAT3(volume_eval) * sc->weight;
493 }
494
495 /* Attributes */
496
497 int OSLShader::find_attribute(KernelGlobals *kg, const ShaderData *sd, uint id, AttributeElement *elem)
498 {
499         /* for OSL, a hash map is used to lookup the attribute by name. */
500         int object = sd->object*ATTR_PRIM_TYPES;
501 #ifdef __HAIR__
502         if(sd->segment != ~0) object += ATTR_PRIM_CURVE;
503 #endif
504
505         OSLGlobals::AttributeMap &attr_map = kg->osl->attribute_map[object];
506         ustring stdname(std::string("geom:") + std::string(Attribute::standard_name((AttributeStandard)id)));
507         OSLGlobals::AttributeMap::const_iterator it = attr_map.find(stdname);
508
509         if (it != attr_map.end()) {
510                 const OSLGlobals::Attribute &osl_attr = it->second;
511                 *elem = osl_attr.elem;
512                 /* return result */
513                 return (osl_attr.elem == ATTR_ELEMENT_NONE) ? (int)ATTR_STD_NOT_FOUND : osl_attr.offset;
514         }
515         else
516                 return (int)ATTR_STD_NOT_FOUND;
517 }
518
519 CCL_NAMESPACE_END
520