Fix T63415: no Cycles displacement update when updating OSL code
[blender.git] / intern / cycles / render / nodes.cpp
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 #include "render/film.h"
18 #include "render/image.h"
19 #include "render/integrator.h"
20 #include "render/light.h"
21 #include "render/nodes.h"
22 #include "render/scene.h"
23 #include "render/svm.h"
24 #include "kernel/svm/svm_color_util.h"
25 #include "kernel/svm/svm_ramp_util.h"
26 #include "kernel/svm/svm_math_util.h"
27 #include "render/osl.h"
28 #include "render/constant_fold.h"
29
30 #include "util/util_sky_model.h"
31 #include "util/util_foreach.h"
32 #include "util/util_logging.h"
33 #include "util/util_transform.h"
34
35 CCL_NAMESPACE_BEGIN
36
37 /* Texture Mapping */
38
39 #define TEXTURE_MAPPING_DEFINE(TextureNode) \
40   SOCKET_POINT(tex_mapping.translation, "Translation", make_float3(0.0f, 0.0f, 0.0f)); \
41   SOCKET_VECTOR(tex_mapping.rotation, "Rotation", make_float3(0.0f, 0.0f, 0.0f)); \
42   SOCKET_VECTOR(tex_mapping.scale, "Scale", make_float3(1.0f, 1.0f, 1.0f)); \
43 \
44   SOCKET_VECTOR(tex_mapping.min, "Min", make_float3(-FLT_MAX, -FLT_MAX, -FLT_MAX)); \
45   SOCKET_VECTOR(tex_mapping.max, "Max", make_float3(FLT_MAX, FLT_MAX, FLT_MAX)); \
46   SOCKET_BOOLEAN(tex_mapping.use_minmax, "Use Min Max", false); \
47 \
48   static NodeEnum mapping_axis_enum; \
49   mapping_axis_enum.insert("none", TextureMapping::NONE); \
50   mapping_axis_enum.insert("x", TextureMapping::X); \
51   mapping_axis_enum.insert("y", TextureMapping::Y); \
52   mapping_axis_enum.insert("z", TextureMapping::Z); \
53   SOCKET_ENUM(tex_mapping.x_mapping, "x_mapping", mapping_axis_enum, TextureMapping::X); \
54   SOCKET_ENUM(tex_mapping.y_mapping, "y_mapping", mapping_axis_enum, TextureMapping::Y); \
55   SOCKET_ENUM(tex_mapping.z_mapping, "z_mapping", mapping_axis_enum, TextureMapping::Z); \
56 \
57   static NodeEnum mapping_type_enum; \
58   mapping_type_enum.insert("point", TextureMapping::POINT); \
59   mapping_type_enum.insert("texture", TextureMapping::TEXTURE); \
60   mapping_type_enum.insert("vector", TextureMapping::VECTOR); \
61   mapping_type_enum.insert("normal", TextureMapping::NORMAL); \
62   SOCKET_ENUM(tex_mapping.type, "Type", mapping_type_enum, TextureMapping::TEXTURE); \
63 \
64   static NodeEnum mapping_projection_enum; \
65   mapping_projection_enum.insert("flat", TextureMapping::FLAT); \
66   mapping_projection_enum.insert("cube", TextureMapping::CUBE); \
67   mapping_projection_enum.insert("tube", TextureMapping::TUBE); \
68   mapping_projection_enum.insert("sphere", TextureMapping::SPHERE); \
69   SOCKET_ENUM(tex_mapping.projection, "Projection", mapping_projection_enum, TextureMapping::FLAT);
70
71 TextureMapping::TextureMapping()
72 {
73 }
74
75 Transform TextureMapping::compute_transform()
76 {
77   Transform mmat = transform_scale(make_float3(0.0f, 0.0f, 0.0f));
78
79   if (x_mapping != NONE)
80     mmat[0][x_mapping - 1] = 1.0f;
81   if (y_mapping != NONE)
82     mmat[1][y_mapping - 1] = 1.0f;
83   if (z_mapping != NONE)
84     mmat[2][z_mapping - 1] = 1.0f;
85
86   float3 scale_clamped = scale;
87
88   if (type == TEXTURE || type == NORMAL) {
89     /* keep matrix invertible */
90     if (fabsf(scale.x) < 1e-5f)
91       scale_clamped.x = signf(scale.x) * 1e-5f;
92     if (fabsf(scale.y) < 1e-5f)
93       scale_clamped.y = signf(scale.y) * 1e-5f;
94     if (fabsf(scale.z) < 1e-5f)
95       scale_clamped.z = signf(scale.z) * 1e-5f;
96   }
97
98   Transform smat = transform_scale(scale_clamped);
99   Transform rmat = transform_euler(rotation);
100   Transform tmat = transform_translate(translation);
101
102   Transform mat;
103
104   switch (type) {
105     case TEXTURE:
106       /* inverse transform on texture coordinate gives
107        * forward transform on texture */
108       mat = tmat * rmat * smat;
109       mat = transform_inverse(mat);
110       break;
111     case POINT:
112       /* full transform */
113       mat = tmat * rmat * smat;
114       break;
115     case VECTOR:
116       /* no translation for vectors */
117       mat = rmat * smat;
118       break;
119     case NORMAL:
120       /* no translation for normals, and inverse transpose */
121       mat = rmat * smat;
122       mat = transform_transposed_inverse(mat);
123       break;
124   }
125
126   /* projection last */
127   mat = mat * mmat;
128
129   return mat;
130 }
131
132 bool TextureMapping::skip()
133 {
134   if (translation != make_float3(0.0f, 0.0f, 0.0f))
135     return false;
136   if (rotation != make_float3(0.0f, 0.0f, 0.0f))
137     return false;
138   if (scale != make_float3(1.0f, 1.0f, 1.0f))
139     return false;
140
141   if (x_mapping != X || y_mapping != Y || z_mapping != Z)
142     return false;
143   if (use_minmax)
144     return false;
145
146   return true;
147 }
148
149 void TextureMapping::compile(SVMCompiler &compiler, int offset_in, int offset_out)
150 {
151   compiler.add_node(NODE_MAPPING, offset_in, offset_out);
152
153   Transform tfm = compute_transform();
154   compiler.add_node(tfm.x);
155   compiler.add_node(tfm.y);
156   compiler.add_node(tfm.z);
157
158   if (use_minmax) {
159     compiler.add_node(NODE_MIN_MAX, offset_out, offset_out);
160     compiler.add_node(float3_to_float4(min));
161     compiler.add_node(float3_to_float4(max));
162   }
163
164   if (type == NORMAL) {
165     compiler.add_node(NODE_VECTOR_MATH, NODE_VECTOR_MATH_NORMALIZE, offset_out, offset_out);
166     compiler.add_node(NODE_VECTOR_MATH, SVM_STACK_INVALID, offset_out);
167   }
168 }
169
170 /* Convenience function for texture nodes, allocating stack space to output
171  * a modified vector and returning its offset */
172 int TextureMapping::compile_begin(SVMCompiler &compiler, ShaderInput *vector_in)
173 {
174   if (!skip()) {
175     int offset_in = compiler.stack_assign(vector_in);
176     int offset_out = compiler.stack_find_offset(SocketType::VECTOR);
177
178     compile(compiler, offset_in, offset_out);
179
180     return offset_out;
181   }
182
183   return compiler.stack_assign(vector_in);
184 }
185
186 void TextureMapping::compile_end(SVMCompiler &compiler, ShaderInput *vector_in, int vector_offset)
187 {
188   if (!skip()) {
189     compiler.stack_clear_offset(vector_in->type(), vector_offset);
190   }
191 }
192
193 void TextureMapping::compile(OSLCompiler &compiler)
194 {
195   if (!skip()) {
196     compiler.parameter("mapping", compute_transform());
197     compiler.parameter("use_mapping", 1);
198   }
199 }
200
201 /* Image Texture */
202
203 NODE_DEFINE(ImageTextureNode)
204 {
205   NodeType *type = NodeType::add("image_texture", create, NodeType::SHADER);
206
207   TEXTURE_MAPPING_DEFINE(ImageTextureNode);
208
209   SOCKET_STRING(filename, "Filename", ustring());
210
211   static NodeEnum color_space_enum;
212   color_space_enum.insert("none", NODE_COLOR_SPACE_NONE);
213   color_space_enum.insert("color", NODE_COLOR_SPACE_COLOR);
214   SOCKET_ENUM(color_space, "Color Space", color_space_enum, NODE_COLOR_SPACE_COLOR);
215
216   SOCKET_BOOLEAN(use_alpha, "Use Alpha", true);
217
218   static NodeEnum interpolation_enum;
219   interpolation_enum.insert("closest", INTERPOLATION_CLOSEST);
220   interpolation_enum.insert("linear", INTERPOLATION_LINEAR);
221   interpolation_enum.insert("cubic", INTERPOLATION_CUBIC);
222   interpolation_enum.insert("smart", INTERPOLATION_SMART);
223   SOCKET_ENUM(interpolation, "Interpolation", interpolation_enum, INTERPOLATION_LINEAR);
224
225   static NodeEnum extension_enum;
226   extension_enum.insert("periodic", EXTENSION_REPEAT);
227   extension_enum.insert("clamp", EXTENSION_EXTEND);
228   extension_enum.insert("black", EXTENSION_CLIP);
229   SOCKET_ENUM(extension, "Extension", extension_enum, EXTENSION_REPEAT);
230
231   static NodeEnum projection_enum;
232   projection_enum.insert("flat", NODE_IMAGE_PROJ_FLAT);
233   projection_enum.insert("box", NODE_IMAGE_PROJ_BOX);
234   projection_enum.insert("sphere", NODE_IMAGE_PROJ_SPHERE);
235   projection_enum.insert("tube", NODE_IMAGE_PROJ_TUBE);
236   SOCKET_ENUM(projection, "Projection", projection_enum, NODE_IMAGE_PROJ_FLAT);
237
238   SOCKET_FLOAT(projection_blend, "Projection Blend", 0.0f);
239
240   SOCKET_IN_POINT(vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_UV);
241
242   SOCKET_OUT_COLOR(color, "Color");
243   SOCKET_OUT_FLOAT(alpha, "Alpha");
244
245   return type;
246 }
247
248 ImageTextureNode::ImageTextureNode() : ImageSlotTextureNode(node_type)
249 {
250   image_manager = NULL;
251   slot = -1;
252   is_float = -1;
253   is_linear = false;
254   builtin_data = NULL;
255   animated = false;
256 }
257
258 ImageTextureNode::~ImageTextureNode()
259 {
260   if (image_manager) {
261     image_manager->remove_image(
262         filename.string(), builtin_data, interpolation, extension, use_alpha);
263   }
264 }
265
266 ShaderNode *ImageTextureNode::clone() const
267 {
268   ImageTextureNode *node = new ImageTextureNode(*this);
269   node->image_manager = NULL;
270   node->slot = -1;
271   node->is_float = -1;
272   node->is_linear = false;
273   return node;
274 }
275
276 void ImageTextureNode::attributes(Shader *shader, AttributeRequestSet *attributes)
277 {
278 #ifdef WITH_PTEX
279   /* todo: avoid loading other texture coordinates when using ptex,
280    * and hide texture coordinate socket in the UI */
281   if (shader->has_surface && string_endswith(filename, ".ptx")) {
282     /* ptex */
283     attributes->add(ATTR_STD_PTEX_FACE_ID);
284     attributes->add(ATTR_STD_PTEX_UV);
285   }
286 #endif
287
288   ShaderNode::attributes(shader, attributes);
289 }
290
291 void ImageTextureNode::compile(SVMCompiler &compiler)
292 {
293   ShaderInput *vector_in = input("Vector");
294   ShaderOutput *color_out = output("Color");
295   ShaderOutput *alpha_out = output("Alpha");
296
297   image_manager = compiler.image_manager;
298   if (is_float == -1) {
299     ImageMetaData metadata;
300     slot = image_manager->add_image(filename.string(),
301                                     builtin_data,
302                                     animated,
303                                     0,
304                                     interpolation,
305                                     extension,
306                                     use_alpha,
307                                     metadata);
308     is_float = metadata.is_float;
309     is_linear = metadata.is_linear;
310   }
311
312   if (slot != -1) {
313     int srgb = (is_linear || color_space != NODE_COLOR_SPACE_COLOR) ? 0 : 1;
314     int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
315
316     if (projection != NODE_IMAGE_PROJ_BOX) {
317       compiler.add_node(NODE_TEX_IMAGE,
318                         slot,
319                         compiler.encode_uchar4(vector_offset,
320                                                compiler.stack_assign_if_linked(color_out),
321                                                compiler.stack_assign_if_linked(alpha_out),
322                                                srgb),
323                         projection);
324     }
325     else {
326       compiler.add_node(NODE_TEX_IMAGE_BOX,
327                         slot,
328                         compiler.encode_uchar4(vector_offset,
329                                                compiler.stack_assign_if_linked(color_out),
330                                                compiler.stack_assign_if_linked(alpha_out),
331                                                srgb),
332                         __float_as_int(projection_blend));
333     }
334
335     tex_mapping.compile_end(compiler, vector_in, vector_offset);
336   }
337   else {
338     /* image not found */
339     if (!color_out->links.empty()) {
340       compiler.add_node(NODE_VALUE_V, compiler.stack_assign(color_out));
341       compiler.add_node(
342           NODE_VALUE_V,
343           make_float3(TEX_IMAGE_MISSING_R, TEX_IMAGE_MISSING_G, TEX_IMAGE_MISSING_B));
344     }
345     if (!alpha_out->links.empty())
346       compiler.add_node(
347           NODE_VALUE_F, __float_as_int(TEX_IMAGE_MISSING_A), compiler.stack_assign(alpha_out));
348   }
349 }
350
351 void ImageTextureNode::compile(OSLCompiler &compiler)
352 {
353   ShaderOutput *alpha_out = output("Alpha");
354
355   tex_mapping.compile(compiler);
356
357   image_manager = compiler.image_manager;
358   if (is_float == -1) {
359     ImageMetaData metadata;
360     if (builtin_data == NULL) {
361       image_manager->get_image_metadata(filename.string(), NULL, metadata);
362     }
363     else {
364       slot = image_manager->add_image(filename.string(),
365                                       builtin_data,
366                                       animated,
367                                       0,
368                                       interpolation,
369                                       extension,
370                                       use_alpha,
371                                       metadata);
372     }
373     is_float = metadata.is_float;
374     is_linear = metadata.is_linear;
375   }
376
377   if (slot == -1) {
378     compiler.parameter(this, "filename");
379   }
380   else {
381     /* TODO(sergey): It's not so simple to pass custom attribute
382      * to the texture() function in order to make builtin images
383      * support more clear. So we use special file name which is
384      * "@i<slot_number>" and check whether file name matches this
385      * mask in the OSLRenderServices::texture().
386      */
387     compiler.parameter("filename", string_printf("@i%d", slot).c_str());
388   }
389   if (is_linear || color_space != NODE_COLOR_SPACE_COLOR)
390     compiler.parameter("color_space", "linear");
391   else
392     compiler.parameter("color_space", "sRGB");
393   compiler.parameter(this, "projection");
394   compiler.parameter(this, "projection_blend");
395   compiler.parameter("is_float", is_float);
396   compiler.parameter("use_alpha", !alpha_out->links.empty());
397   compiler.parameter(this, "interpolation");
398   compiler.parameter(this, "extension");
399
400   compiler.add(this, "node_image_texture");
401 }
402
403 /* Environment Texture */
404
405 NODE_DEFINE(EnvironmentTextureNode)
406 {
407   NodeType *type = NodeType::add("environment_texture", create, NodeType::SHADER);
408
409   TEXTURE_MAPPING_DEFINE(EnvironmentTextureNode);
410
411   SOCKET_STRING(filename, "Filename", ustring());
412
413   static NodeEnum color_space_enum;
414   color_space_enum.insert("none", NODE_COLOR_SPACE_NONE);
415   color_space_enum.insert("color", NODE_COLOR_SPACE_COLOR);
416   SOCKET_ENUM(color_space, "Color Space", color_space_enum, NODE_COLOR_SPACE_COLOR);
417
418   SOCKET_BOOLEAN(use_alpha, "Use Alpha", true);
419
420   static NodeEnum interpolation_enum;
421   interpolation_enum.insert("closest", INTERPOLATION_CLOSEST);
422   interpolation_enum.insert("linear", INTERPOLATION_LINEAR);
423   interpolation_enum.insert("cubic", INTERPOLATION_CUBIC);
424   interpolation_enum.insert("smart", INTERPOLATION_SMART);
425   SOCKET_ENUM(interpolation, "Interpolation", interpolation_enum, INTERPOLATION_LINEAR);
426
427   static NodeEnum projection_enum;
428   projection_enum.insert("equirectangular", NODE_ENVIRONMENT_EQUIRECTANGULAR);
429   projection_enum.insert("mirror_ball", NODE_ENVIRONMENT_MIRROR_BALL);
430   SOCKET_ENUM(projection, "Projection", projection_enum, NODE_ENVIRONMENT_EQUIRECTANGULAR);
431
432   SOCKET_IN_POINT(vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_POSITION);
433
434   SOCKET_OUT_COLOR(color, "Color");
435   SOCKET_OUT_FLOAT(alpha, "Alpha");
436
437   return type;
438 }
439
440 EnvironmentTextureNode::EnvironmentTextureNode() : ImageSlotTextureNode(node_type)
441 {
442   image_manager = NULL;
443   slot = -1;
444   is_float = -1;
445   is_linear = false;
446   builtin_data = NULL;
447   animated = false;
448 }
449
450 EnvironmentTextureNode::~EnvironmentTextureNode()
451 {
452   if (image_manager) {
453     image_manager->remove_image(
454         filename.string(), builtin_data, interpolation, EXTENSION_REPEAT, use_alpha);
455   }
456 }
457
458 ShaderNode *EnvironmentTextureNode::clone() const
459 {
460   EnvironmentTextureNode *node = new EnvironmentTextureNode(*this);
461   node->image_manager = NULL;
462   node->slot = -1;
463   node->is_float = -1;
464   node->is_linear = false;
465   return node;
466 }
467
468 void EnvironmentTextureNode::attributes(Shader *shader, AttributeRequestSet *attributes)
469 {
470 #ifdef WITH_PTEX
471   if (shader->has_surface && string_endswith(filename, ".ptx")) {
472     /* ptex */
473     attributes->add(ATTR_STD_PTEX_FACE_ID);
474     attributes->add(ATTR_STD_PTEX_UV);
475   }
476 #endif
477
478   ShaderNode::attributes(shader, attributes);
479 }
480
481 void EnvironmentTextureNode::compile(SVMCompiler &compiler)
482 {
483   ShaderInput *vector_in = input("Vector");
484   ShaderOutput *color_out = output("Color");
485   ShaderOutput *alpha_out = output("Alpha");
486
487   image_manager = compiler.image_manager;
488   if (slot == -1) {
489     ImageMetaData metadata;
490     slot = image_manager->add_image(filename.string(),
491                                     builtin_data,
492                                     animated,
493                                     0,
494                                     interpolation,
495                                     EXTENSION_REPEAT,
496                                     use_alpha,
497                                     metadata);
498     is_float = metadata.is_float;
499     is_linear = metadata.is_linear;
500   }
501
502   if (slot != -1) {
503     int srgb = (is_linear || color_space != NODE_COLOR_SPACE_COLOR) ? 0 : 1;
504     int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
505
506     compiler.add_node(NODE_TEX_ENVIRONMENT,
507                       slot,
508                       compiler.encode_uchar4(vector_offset,
509                                              compiler.stack_assign_if_linked(color_out),
510                                              compiler.stack_assign_if_linked(alpha_out),
511                                              srgb),
512                       projection);
513
514     tex_mapping.compile_end(compiler, vector_in, vector_offset);
515   }
516   else {
517     /* image not found */
518     if (!color_out->links.empty()) {
519       compiler.add_node(NODE_VALUE_V, compiler.stack_assign(color_out));
520       compiler.add_node(
521           NODE_VALUE_V,
522           make_float3(TEX_IMAGE_MISSING_R, TEX_IMAGE_MISSING_G, TEX_IMAGE_MISSING_B));
523     }
524     if (!alpha_out->links.empty())
525       compiler.add_node(
526           NODE_VALUE_F, __float_as_int(TEX_IMAGE_MISSING_A), compiler.stack_assign(alpha_out));
527   }
528 }
529
530 void EnvironmentTextureNode::compile(OSLCompiler &compiler)
531 {
532   ShaderOutput *alpha_out = output("Alpha");
533
534   tex_mapping.compile(compiler);
535
536   /* See comments in ImageTextureNode::compile about support
537    * of builtin images.
538    */
539   image_manager = compiler.image_manager;
540   if (is_float == -1) {
541     ImageMetaData metadata;
542     if (builtin_data == NULL) {
543       image_manager->get_image_metadata(filename.string(), NULL, metadata);
544     }
545     else {
546       slot = image_manager->add_image(filename.string(),
547                                       builtin_data,
548                                       animated,
549                                       0,
550                                       interpolation,
551                                       EXTENSION_REPEAT,
552                                       use_alpha,
553                                       metadata);
554     }
555     is_float = metadata.is_float;
556     is_linear = metadata.is_linear;
557   }
558
559   if (slot == -1) {
560     compiler.parameter(this, "filename");
561   }
562   else {
563     compiler.parameter("filename", string_printf("@i%d", slot).c_str());
564   }
565   compiler.parameter(this, "projection");
566   if (is_linear || color_space != NODE_COLOR_SPACE_COLOR)
567     compiler.parameter("color_space", "linear");
568   else
569     compiler.parameter("color_space", "sRGB");
570
571   compiler.parameter(this, "interpolation");
572   compiler.parameter("is_float", is_float);
573   compiler.parameter("use_alpha", !alpha_out->links.empty());
574   compiler.add(this, "node_environment_texture");
575 }
576
577 /* Sky Texture */
578
579 static float2 sky_spherical_coordinates(float3 dir)
580 {
581   return make_float2(acosf(dir.z), atan2f(dir.x, dir.y));
582 }
583
584 typedef struct SunSky {
585   /* sun direction in spherical and cartesian */
586   float theta, phi;
587
588   /* Parameter */
589   float radiance_x, radiance_y, radiance_z;
590   float config_x[9], config_y[9], config_z[9];
591 } SunSky;
592
593 /* Preetham model */
594 static float sky_perez_function(float lam[6], float theta, float gamma)
595 {
596   return (1.0f + lam[0] * expf(lam[1] / cosf(theta))) *
597          (1.0f + lam[2] * expf(lam[3] * gamma) + lam[4] * cosf(gamma) * cosf(gamma));
598 }
599
600 static void sky_texture_precompute_old(SunSky *sunsky, float3 dir, float turbidity)
601 {
602   /*
603    * We re-use the SunSky struct of the new model, to avoid extra variables
604    * zenith_Y/x/y is now radiance_x/y/z
605    * perez_Y/x/y is now config_x/y/z
606    */
607
608   float2 spherical = sky_spherical_coordinates(dir);
609   float theta = spherical.x;
610   float phi = spherical.y;
611
612   sunsky->theta = theta;
613   sunsky->phi = phi;
614
615   float theta2 = theta * theta;
616   float theta3 = theta2 * theta;
617   float T = turbidity;
618   float T2 = T * T;
619
620   float chi = (4.0f / 9.0f - T / 120.0f) * (M_PI_F - 2.0f * theta);
621   sunsky->radiance_x = (4.0453f * T - 4.9710f) * tanf(chi) - 0.2155f * T + 2.4192f;
622   sunsky->radiance_x *= 0.06f;
623
624   sunsky->radiance_y = (0.00166f * theta3 - 0.00375f * theta2 + 0.00209f * theta) * T2 +
625                        (-0.02903f * theta3 + 0.06377f * theta2 - 0.03202f * theta + 0.00394f) * T +
626                        (0.11693f * theta3 - 0.21196f * theta2 + 0.06052f * theta + 0.25886f);
627
628   sunsky->radiance_z = (0.00275f * theta3 - 0.00610f * theta2 + 0.00317f * theta) * T2 +
629                        (-0.04214f * theta3 + 0.08970f * theta2 - 0.04153f * theta + 0.00516f) * T +
630                        (0.15346f * theta3 - 0.26756f * theta2 + 0.06670f * theta + 0.26688f);
631
632   sunsky->config_x[0] = (0.1787f * T - 1.4630f);
633   sunsky->config_x[1] = (-0.3554f * T + 0.4275f);
634   sunsky->config_x[2] = (-0.0227f * T + 5.3251f);
635   sunsky->config_x[3] = (0.1206f * T - 2.5771f);
636   sunsky->config_x[4] = (-0.0670f * T + 0.3703f);
637
638   sunsky->config_y[0] = (-0.0193f * T - 0.2592f);
639   sunsky->config_y[1] = (-0.0665f * T + 0.0008f);
640   sunsky->config_y[2] = (-0.0004f * T + 0.2125f);
641   sunsky->config_y[3] = (-0.0641f * T - 0.8989f);
642   sunsky->config_y[4] = (-0.0033f * T + 0.0452f);
643
644   sunsky->config_z[0] = (-0.0167f * T - 0.2608f);
645   sunsky->config_z[1] = (-0.0950f * T + 0.0092f);
646   sunsky->config_z[2] = (-0.0079f * T + 0.2102f);
647   sunsky->config_z[3] = (-0.0441f * T - 1.6537f);
648   sunsky->config_z[4] = (-0.0109f * T + 0.0529f);
649
650   /* unused for old sky model */
651   for (int i = 5; i < 9; i++) {
652     sunsky->config_x[i] = 0.0f;
653     sunsky->config_y[i] = 0.0f;
654     sunsky->config_z[i] = 0.0f;
655   }
656
657   sunsky->radiance_x /= sky_perez_function(sunsky->config_x, 0, theta);
658   sunsky->radiance_y /= sky_perez_function(sunsky->config_y, 0, theta);
659   sunsky->radiance_z /= sky_perez_function(sunsky->config_z, 0, theta);
660 }
661
662 /* Hosek / Wilkie */
663 static void sky_texture_precompute_new(SunSky *sunsky,
664                                        float3 dir,
665                                        float turbidity,
666                                        float ground_albedo)
667 {
668   /* Calculate Sun Direction and save coordinates */
669   float2 spherical = sky_spherical_coordinates(dir);
670   float theta = spherical.x;
671   float phi = spherical.y;
672
673   /* Clamp Turbidity */
674   turbidity = clamp(turbidity, 0.0f, 10.0f);
675
676   /* Clamp to Horizon */
677   theta = clamp(theta, 0.0f, M_PI_2_F);
678
679   sunsky->theta = theta;
680   sunsky->phi = phi;
681
682   float solarElevation = M_PI_2_F - theta;
683
684   /* Initialize Sky Model */
685   ArHosekSkyModelState *sky_state;
686   sky_state = arhosek_xyz_skymodelstate_alloc_init(
687       (double)turbidity, (double)ground_albedo, (double)solarElevation);
688
689   /* Copy values from sky_state to SunSky */
690   for (int i = 0; i < 9; ++i) {
691     sunsky->config_x[i] = (float)sky_state->configs[0][i];
692     sunsky->config_y[i] = (float)sky_state->configs[1][i];
693     sunsky->config_z[i] = (float)sky_state->configs[2][i];
694   }
695   sunsky->radiance_x = (float)sky_state->radiances[0];
696   sunsky->radiance_y = (float)sky_state->radiances[1];
697   sunsky->radiance_z = (float)sky_state->radiances[2];
698
699   /* Free sky_state */
700   arhosekskymodelstate_free(sky_state);
701 }
702
703 NODE_DEFINE(SkyTextureNode)
704 {
705   NodeType *type = NodeType::add("sky_texture", create, NodeType::SHADER);
706
707   TEXTURE_MAPPING_DEFINE(SkyTextureNode);
708
709   static NodeEnum type_enum;
710   type_enum.insert("preetham", NODE_SKY_OLD);
711   type_enum.insert("hosek_wilkie", NODE_SKY_NEW);
712   SOCKET_ENUM(type, "Type", type_enum, NODE_SKY_NEW);
713
714   SOCKET_VECTOR(sun_direction, "Sun Direction", make_float3(0.0f, 0.0f, 1.0f));
715   SOCKET_FLOAT(turbidity, "Turbidity", 2.2f);
716   SOCKET_FLOAT(ground_albedo, "Ground Albedo", 0.3f);
717
718   SOCKET_IN_POINT(
719       vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_GENERATED);
720
721   SOCKET_OUT_COLOR(color, "Color");
722
723   return type;
724 }
725
726 SkyTextureNode::SkyTextureNode() : TextureNode(node_type)
727 {
728 }
729
730 void SkyTextureNode::compile(SVMCompiler &compiler)
731 {
732   ShaderInput *vector_in = input("Vector");
733   ShaderOutput *color_out = output("Color");
734
735   SunSky sunsky;
736   if (type == NODE_SKY_OLD)
737     sky_texture_precompute_old(&sunsky, sun_direction, turbidity);
738   else if (type == NODE_SKY_NEW)
739     sky_texture_precompute_new(&sunsky, sun_direction, turbidity, ground_albedo);
740   else
741     assert(false);
742
743   int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
744
745   compiler.stack_assign(color_out);
746   compiler.add_node(NODE_TEX_SKY, vector_offset, compiler.stack_assign(color_out), type);
747   compiler.add_node(__float_as_uint(sunsky.phi),
748                     __float_as_uint(sunsky.theta),
749                     __float_as_uint(sunsky.radiance_x),
750                     __float_as_uint(sunsky.radiance_y));
751   compiler.add_node(__float_as_uint(sunsky.radiance_z),
752                     __float_as_uint(sunsky.config_x[0]),
753                     __float_as_uint(sunsky.config_x[1]),
754                     __float_as_uint(sunsky.config_x[2]));
755   compiler.add_node(__float_as_uint(sunsky.config_x[3]),
756                     __float_as_uint(sunsky.config_x[4]),
757                     __float_as_uint(sunsky.config_x[5]),
758                     __float_as_uint(sunsky.config_x[6]));
759   compiler.add_node(__float_as_uint(sunsky.config_x[7]),
760                     __float_as_uint(sunsky.config_x[8]),
761                     __float_as_uint(sunsky.config_y[0]),
762                     __float_as_uint(sunsky.config_y[1]));
763   compiler.add_node(__float_as_uint(sunsky.config_y[2]),
764                     __float_as_uint(sunsky.config_y[3]),
765                     __float_as_uint(sunsky.config_y[4]),
766                     __float_as_uint(sunsky.config_y[5]));
767   compiler.add_node(__float_as_uint(sunsky.config_y[6]),
768                     __float_as_uint(sunsky.config_y[7]),
769                     __float_as_uint(sunsky.config_y[8]),
770                     __float_as_uint(sunsky.config_z[0]));
771   compiler.add_node(__float_as_uint(sunsky.config_z[1]),
772                     __float_as_uint(sunsky.config_z[2]),
773                     __float_as_uint(sunsky.config_z[3]),
774                     __float_as_uint(sunsky.config_z[4]));
775   compiler.add_node(__float_as_uint(sunsky.config_z[5]),
776                     __float_as_uint(sunsky.config_z[6]),
777                     __float_as_uint(sunsky.config_z[7]),
778                     __float_as_uint(sunsky.config_z[8]));
779
780   tex_mapping.compile_end(compiler, vector_in, vector_offset);
781 }
782
783 void SkyTextureNode::compile(OSLCompiler &compiler)
784 {
785   tex_mapping.compile(compiler);
786
787   SunSky sunsky;
788   if (type == NODE_SKY_OLD)
789     sky_texture_precompute_old(&sunsky, sun_direction, turbidity);
790   else if (type == NODE_SKY_NEW)
791     sky_texture_precompute_new(&sunsky, sun_direction, turbidity, ground_albedo);
792   else
793     assert(false);
794
795   compiler.parameter(this, "type");
796   compiler.parameter("theta", sunsky.theta);
797   compiler.parameter("phi", sunsky.phi);
798   compiler.parameter_color("radiance",
799                            make_float3(sunsky.radiance_x, sunsky.radiance_y, sunsky.radiance_z));
800   compiler.parameter_array("config_x", sunsky.config_x, 9);
801   compiler.parameter_array("config_y", sunsky.config_y, 9);
802   compiler.parameter_array("config_z", sunsky.config_z, 9);
803   compiler.add(this, "node_sky_texture");
804 }
805
806 /* Gradient Texture */
807
808 NODE_DEFINE(GradientTextureNode)
809 {
810   NodeType *type = NodeType::add("gradient_texture", create, NodeType::SHADER);
811
812   TEXTURE_MAPPING_DEFINE(GradientTextureNode);
813
814   static NodeEnum type_enum;
815   type_enum.insert("linear", NODE_BLEND_LINEAR);
816   type_enum.insert("quadratic", NODE_BLEND_QUADRATIC);
817   type_enum.insert("easing", NODE_BLEND_EASING);
818   type_enum.insert("diagonal", NODE_BLEND_DIAGONAL);
819   type_enum.insert("radial", NODE_BLEND_RADIAL);
820   type_enum.insert("quadratic_sphere", NODE_BLEND_QUADRATIC_SPHERE);
821   type_enum.insert("spherical", NODE_BLEND_SPHERICAL);
822   SOCKET_ENUM(type, "Type", type_enum, NODE_BLEND_LINEAR);
823
824   SOCKET_IN_POINT(
825       vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_GENERATED);
826
827   SOCKET_OUT_COLOR(color, "Color");
828   SOCKET_OUT_FLOAT(fac, "Fac");
829
830   return type;
831 }
832
833 GradientTextureNode::GradientTextureNode() : TextureNode(node_type)
834 {
835 }
836
837 void GradientTextureNode::compile(SVMCompiler &compiler)
838 {
839   ShaderInput *vector_in = input("Vector");
840   ShaderOutput *color_out = output("Color");
841   ShaderOutput *fac_out = output("Fac");
842
843   int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
844
845   compiler.add_node(NODE_TEX_GRADIENT,
846                     compiler.encode_uchar4(type,
847                                            vector_offset,
848                                            compiler.stack_assign_if_linked(fac_out),
849                                            compiler.stack_assign_if_linked(color_out)));
850
851   tex_mapping.compile_end(compiler, vector_in, vector_offset);
852 }
853
854 void GradientTextureNode::compile(OSLCompiler &compiler)
855 {
856   tex_mapping.compile(compiler);
857
858   compiler.parameter(this, "type");
859   compiler.add(this, "node_gradient_texture");
860 }
861
862 /* Noise Texture */
863
864 NODE_DEFINE(NoiseTextureNode)
865 {
866   NodeType *type = NodeType::add("noise_texture", create, NodeType::SHADER);
867
868   TEXTURE_MAPPING_DEFINE(NoiseTextureNode);
869
870   SOCKET_IN_FLOAT(scale, "Scale", 1.0f);
871   SOCKET_IN_FLOAT(detail, "Detail", 2.0f);
872   SOCKET_IN_FLOAT(distortion, "Distortion", 0.0f);
873   SOCKET_IN_POINT(
874       vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_GENERATED);
875
876   SOCKET_OUT_COLOR(color, "Color");
877   SOCKET_OUT_FLOAT(fac, "Fac");
878
879   return type;
880 }
881
882 NoiseTextureNode::NoiseTextureNode() : TextureNode(node_type)
883 {
884 }
885
886 void NoiseTextureNode::compile(SVMCompiler &compiler)
887 {
888   ShaderInput *distortion_in = input("Distortion");
889   ShaderInput *detail_in = input("Detail");
890   ShaderInput *scale_in = input("Scale");
891   ShaderInput *vector_in = input("Vector");
892   ShaderOutput *color_out = output("Color");
893   ShaderOutput *fac_out = output("Fac");
894
895   int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
896
897   compiler.add_node(NODE_TEX_NOISE,
898                     compiler.encode_uchar4(vector_offset,
899                                            compiler.stack_assign_if_linked(scale_in),
900                                            compiler.stack_assign_if_linked(detail_in),
901                                            compiler.stack_assign_if_linked(distortion_in)),
902                     compiler.encode_uchar4(compiler.stack_assign_if_linked(color_out),
903                                            compiler.stack_assign_if_linked(fac_out)));
904   compiler.add_node(__float_as_int(scale), __float_as_int(detail), __float_as_int(distortion));
905
906   tex_mapping.compile_end(compiler, vector_in, vector_offset);
907 }
908
909 void NoiseTextureNode::compile(OSLCompiler &compiler)
910 {
911   tex_mapping.compile(compiler);
912
913   compiler.add(this, "node_noise_texture");
914 }
915
916 /* Voronoi Texture */
917
918 NODE_DEFINE(VoronoiTextureNode)
919 {
920   NodeType *type = NodeType::add("voronoi_texture", create, NodeType::SHADER);
921
922   TEXTURE_MAPPING_DEFINE(VoronoiTextureNode);
923
924   static NodeEnum coloring_enum;
925   coloring_enum.insert("intensity", NODE_VORONOI_INTENSITY);
926   coloring_enum.insert("cells", NODE_VORONOI_CELLS);
927   SOCKET_ENUM(coloring, "Coloring", coloring_enum, NODE_VORONOI_INTENSITY);
928
929   static NodeEnum metric;
930   metric.insert("distance", NODE_VORONOI_DISTANCE);
931   metric.insert("manhattan", NODE_VORONOI_MANHATTAN);
932   metric.insert("chebychev", NODE_VORONOI_CHEBYCHEV);
933   metric.insert("minkowski", NODE_VORONOI_MINKOWSKI);
934   SOCKET_ENUM(metric, "Distance Metric", metric, NODE_VORONOI_INTENSITY);
935
936   static NodeEnum feature_enum;
937   feature_enum.insert("F1", NODE_VORONOI_F1);
938   feature_enum.insert("F2", NODE_VORONOI_F2);
939   feature_enum.insert("F3", NODE_VORONOI_F3);
940   feature_enum.insert("F4", NODE_VORONOI_F4);
941   feature_enum.insert("F2F1", NODE_VORONOI_F2F1);
942   SOCKET_ENUM(feature, "Feature", feature_enum, NODE_VORONOI_INTENSITY);
943
944   SOCKET_IN_FLOAT(scale, "Scale", 1.0f);
945   SOCKET_IN_FLOAT(exponent, "Exponent", 0.5f);
946   SOCKET_IN_POINT(
947       vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_GENERATED);
948
949   SOCKET_OUT_COLOR(color, "Color");
950   SOCKET_OUT_FLOAT(fac, "Fac");
951
952   return type;
953 }
954
955 VoronoiTextureNode::VoronoiTextureNode() : TextureNode(node_type)
956 {
957 }
958
959 void VoronoiTextureNode::compile(SVMCompiler &compiler)
960 {
961   ShaderInput *scale_in = input("Scale");
962   ShaderInput *vector_in = input("Vector");
963   ShaderInput *exponent_in = input("Exponent");
964   ShaderOutput *color_out = output("Color");
965   ShaderOutput *fac_out = output("Fac");
966
967   if (vector_in->link)
968     compiler.stack_assign(vector_in);
969   if (scale_in->link)
970     compiler.stack_assign(scale_in);
971   if (exponent_in->link)
972     compiler.stack_assign(exponent_in);
973
974   int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
975
976   compiler.add_node(NODE_TEX_VORONOI,
977                     compiler.encode_uchar4(vector_offset, coloring, metric, feature),
978                     compiler.encode_uchar4(compiler.stack_assign_if_linked(scale_in),
979                                            compiler.stack_assign_if_linked(exponent_in),
980                                            compiler.stack_assign(fac_out),
981                                            compiler.stack_assign(color_out)));
982   compiler.add_node(__float_as_int(scale), __float_as_int(exponent));
983
984   tex_mapping.compile_end(compiler, vector_in, vector_offset);
985 }
986
987 void VoronoiTextureNode::compile(OSLCompiler &compiler)
988 {
989   tex_mapping.compile(compiler);
990
991   compiler.parameter(this, "coloring");
992   compiler.parameter(this, "metric");
993   compiler.parameter(this, "feature");
994   compiler.add(this, "node_voronoi_texture");
995 }
996
997 /* IES Light */
998
999 NODE_DEFINE(IESLightNode)
1000 {
1001   NodeType *type = NodeType::add("ies_light", create, NodeType::SHADER);
1002
1003   TEXTURE_MAPPING_DEFINE(IESLightNode);
1004
1005   SOCKET_STRING(ies, "IES", ustring());
1006   SOCKET_STRING(filename, "File Name", ustring());
1007
1008   SOCKET_IN_FLOAT(strength, "Strength", 1.0f);
1009   SOCKET_IN_POINT(
1010       vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_NORMAL);
1011
1012   SOCKET_OUT_FLOAT(fac, "Fac");
1013
1014   return type;
1015 }
1016
1017 IESLightNode::IESLightNode() : TextureNode(node_type)
1018 {
1019   light_manager = NULL;
1020   slot = -1;
1021 }
1022
1023 ShaderNode *IESLightNode::clone() const
1024 {
1025   IESLightNode *node = new IESLightNode(*this);
1026
1027   node->light_manager = NULL;
1028   node->slot = -1;
1029
1030   return node;
1031 }
1032
1033 IESLightNode::~IESLightNode()
1034 {
1035   if (light_manager) {
1036     light_manager->remove_ies(slot);
1037   }
1038 }
1039
1040 void IESLightNode::get_slot()
1041 {
1042   assert(light_manager);
1043
1044   if (slot == -1) {
1045     if (ies.empty()) {
1046       slot = light_manager->add_ies_from_file(filename);
1047     }
1048     else {
1049       slot = light_manager->add_ies(ies);
1050     }
1051   }
1052 }
1053
1054 void IESLightNode::compile(SVMCompiler &compiler)
1055 {
1056   light_manager = compiler.light_manager;
1057   get_slot();
1058
1059   ShaderInput *strength_in = input("Strength");
1060   ShaderInput *vector_in = input("Vector");
1061   ShaderOutput *fac_out = output("Fac");
1062
1063   int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
1064
1065   compiler.add_node(NODE_IES,
1066                     compiler.encode_uchar4(compiler.stack_assign_if_linked(strength_in),
1067                                            vector_offset,
1068                                            compiler.stack_assign(fac_out),
1069                                            0),
1070                     slot,
1071                     __float_as_int(strength));
1072
1073   tex_mapping.compile_end(compiler, vector_in, vector_offset);
1074 }
1075
1076 void IESLightNode::compile(OSLCompiler &compiler)
1077 {
1078   light_manager = compiler.light_manager;
1079   get_slot();
1080
1081   tex_mapping.compile(compiler);
1082
1083   compiler.parameter("slot", slot);
1084   compiler.add(this, "node_ies_light");
1085 }
1086
1087 /* Musgrave Texture */
1088
1089 NODE_DEFINE(MusgraveTextureNode)
1090 {
1091   NodeType *type = NodeType::add("musgrave_texture", create, NodeType::SHADER);
1092
1093   TEXTURE_MAPPING_DEFINE(MusgraveTextureNode);
1094
1095   static NodeEnum type_enum;
1096   type_enum.insert("multifractal", NODE_MUSGRAVE_MULTIFRACTAL);
1097   type_enum.insert("fBM", NODE_MUSGRAVE_FBM);
1098   type_enum.insert("hybrid_multifractal", NODE_MUSGRAVE_HYBRID_MULTIFRACTAL);
1099   type_enum.insert("ridged_multifractal", NODE_MUSGRAVE_RIDGED_MULTIFRACTAL);
1100   type_enum.insert("hetero_terrain", NODE_MUSGRAVE_HETERO_TERRAIN);
1101   SOCKET_ENUM(type, "Type", type_enum, NODE_MUSGRAVE_FBM);
1102
1103   SOCKET_IN_FLOAT(scale, "Scale", 1.0f);
1104   SOCKET_IN_FLOAT(detail, "Detail", 2.0f);
1105   SOCKET_IN_FLOAT(dimension, "Dimension", 2.0f);
1106   SOCKET_IN_FLOAT(lacunarity, "Lacunarity", 1.0f);
1107   SOCKET_IN_FLOAT(offset, "Offset", 0.0f);
1108   SOCKET_IN_FLOAT(gain, "Gain", 1.0f);
1109   SOCKET_IN_POINT(
1110       vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_GENERATED);
1111
1112   SOCKET_OUT_COLOR(color, "Color");
1113   SOCKET_OUT_FLOAT(fac, "Fac");
1114
1115   return type;
1116 }
1117
1118 MusgraveTextureNode::MusgraveTextureNode() : TextureNode(node_type)
1119 {
1120 }
1121
1122 void MusgraveTextureNode::compile(SVMCompiler &compiler)
1123 {
1124   ShaderInput *vector_in = input("Vector");
1125   ShaderInput *scale_in = input("Scale");
1126   ShaderInput *dimension_in = input("Dimension");
1127   ShaderInput *lacunarity_in = input("Lacunarity");
1128   ShaderInput *detail_in = input("Detail");
1129   ShaderInput *offset_in = input("Offset");
1130   ShaderInput *gain_in = input("Gain");
1131   ShaderOutput *fac_out = output("Fac");
1132   ShaderOutput *color_out = output("Color");
1133
1134   int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
1135
1136   compiler.add_node(NODE_TEX_MUSGRAVE,
1137                     compiler.encode_uchar4(type,
1138                                            vector_offset,
1139                                            compiler.stack_assign_if_linked(color_out),
1140                                            compiler.stack_assign_if_linked(fac_out)),
1141                     compiler.encode_uchar4(compiler.stack_assign_if_linked(dimension_in),
1142                                            compiler.stack_assign_if_linked(lacunarity_in),
1143                                            compiler.stack_assign_if_linked(detail_in),
1144                                            compiler.stack_assign_if_linked(offset_in)),
1145                     compiler.encode_uchar4(compiler.stack_assign_if_linked(gain_in),
1146                                            compiler.stack_assign_if_linked(scale_in)));
1147   compiler.add_node(__float_as_int(dimension),
1148                     __float_as_int(lacunarity),
1149                     __float_as_int(detail),
1150                     __float_as_int(offset));
1151   compiler.add_node(__float_as_int(gain), __float_as_int(scale));
1152
1153   tex_mapping.compile_end(compiler, vector_in, vector_offset);
1154 }
1155
1156 void MusgraveTextureNode::compile(OSLCompiler &compiler)
1157 {
1158   tex_mapping.compile(compiler);
1159
1160   compiler.parameter(this, "type");
1161   compiler.add(this, "node_musgrave_texture");
1162 }
1163
1164 /* Wave Texture */
1165
1166 NODE_DEFINE(WaveTextureNode)
1167 {
1168   NodeType *type = NodeType::add("wave_texture", create, NodeType::SHADER);
1169
1170   TEXTURE_MAPPING_DEFINE(WaveTextureNode);
1171
1172   static NodeEnum type_enum;
1173   type_enum.insert("bands", NODE_WAVE_BANDS);
1174   type_enum.insert("rings", NODE_WAVE_RINGS);
1175   SOCKET_ENUM(type, "Type", type_enum, NODE_WAVE_BANDS);
1176
1177   static NodeEnum profile_enum;
1178   profile_enum.insert("sine", NODE_WAVE_PROFILE_SIN);
1179   profile_enum.insert("saw", NODE_WAVE_PROFILE_SAW);
1180   SOCKET_ENUM(profile, "Profile", profile_enum, NODE_WAVE_PROFILE_SIN);
1181
1182   SOCKET_IN_FLOAT(scale, "Scale", 1.0f);
1183   SOCKET_IN_FLOAT(distortion, "Distortion", 0.0f);
1184   SOCKET_IN_FLOAT(detail, "Detail", 2.0f);
1185   SOCKET_IN_FLOAT(detail_scale, "Detail Scale", 0.0f);
1186   SOCKET_IN_POINT(
1187       vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_GENERATED);
1188
1189   SOCKET_OUT_COLOR(color, "Color");
1190   SOCKET_OUT_FLOAT(fac, "Fac");
1191
1192   return type;
1193 }
1194
1195 WaveTextureNode::WaveTextureNode() : TextureNode(node_type)
1196 {
1197 }
1198
1199 void WaveTextureNode::compile(SVMCompiler &compiler)
1200 {
1201   ShaderInput *scale_in = input("Scale");
1202   ShaderInput *distortion_in = input("Distortion");
1203   ShaderInput *dscale_in = input("Detail Scale");
1204   ShaderInput *detail_in = input("Detail");
1205   ShaderInput *vector_in = input("Vector");
1206   ShaderOutput *fac_out = output("Fac");
1207   ShaderOutput *color_out = output("Color");
1208
1209   int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
1210
1211   compiler.add_node(NODE_TEX_WAVE,
1212                     compiler.encode_uchar4(type,
1213                                            compiler.stack_assign_if_linked(color_out),
1214                                            compiler.stack_assign_if_linked(fac_out),
1215                                            compiler.stack_assign_if_linked(dscale_in)),
1216                     compiler.encode_uchar4(vector_offset,
1217                                            compiler.stack_assign_if_linked(scale_in),
1218                                            compiler.stack_assign_if_linked(detail_in),
1219                                            compiler.stack_assign_if_linked(distortion_in)),
1220                     profile);
1221
1222   compiler.add_node(__float_as_int(scale),
1223                     __float_as_int(detail),
1224                     __float_as_int(distortion),
1225                     __float_as_int(detail_scale));
1226
1227   tex_mapping.compile_end(compiler, vector_in, vector_offset);
1228 }
1229
1230 void WaveTextureNode::compile(OSLCompiler &compiler)
1231 {
1232   tex_mapping.compile(compiler);
1233
1234   compiler.parameter(this, "type");
1235   compiler.parameter(this, "profile");
1236
1237   compiler.add(this, "node_wave_texture");
1238 }
1239
1240 /* Magic Texture */
1241
1242 NODE_DEFINE(MagicTextureNode)
1243 {
1244   NodeType *type = NodeType::add("magic_texture", create, NodeType::SHADER);
1245
1246   TEXTURE_MAPPING_DEFINE(MagicTextureNode);
1247
1248   SOCKET_INT(depth, "Depth", 2);
1249
1250   SOCKET_IN_POINT(
1251       vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_GENERATED);
1252   SOCKET_IN_FLOAT(scale, "Scale", 5.0f);
1253   SOCKET_IN_FLOAT(distortion, "Distortion", 1.0f);
1254
1255   SOCKET_OUT_COLOR(color, "Color");
1256   SOCKET_OUT_FLOAT(fac, "Fac");
1257
1258   return type;
1259 }
1260
1261 MagicTextureNode::MagicTextureNode() : TextureNode(node_type)
1262 {
1263 }
1264
1265 void MagicTextureNode::compile(SVMCompiler &compiler)
1266 {
1267   ShaderInput *vector_in = input("Vector");
1268   ShaderInput *scale_in = input("Scale");
1269   ShaderInput *distortion_in = input("Distortion");
1270   ShaderOutput *color_out = output("Color");
1271   ShaderOutput *fac_out = output("Fac");
1272
1273   int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
1274
1275   compiler.add_node(NODE_TEX_MAGIC,
1276                     compiler.encode_uchar4(depth,
1277                                            compiler.stack_assign_if_linked(color_out),
1278                                            compiler.stack_assign_if_linked(fac_out)),
1279                     compiler.encode_uchar4(vector_offset,
1280                                            compiler.stack_assign_if_linked(scale_in),
1281                                            compiler.stack_assign_if_linked(distortion_in)));
1282   compiler.add_node(__float_as_int(scale), __float_as_int(distortion));
1283
1284   tex_mapping.compile_end(compiler, vector_in, vector_offset);
1285 }
1286
1287 void MagicTextureNode::compile(OSLCompiler &compiler)
1288 {
1289   tex_mapping.compile(compiler);
1290
1291   compiler.parameter(this, "depth");
1292   compiler.add(this, "node_magic_texture");
1293 }
1294
1295 /* Checker Texture */
1296
1297 NODE_DEFINE(CheckerTextureNode)
1298 {
1299   NodeType *type = NodeType::add("checker_texture", create, NodeType::SHADER);
1300
1301   TEXTURE_MAPPING_DEFINE(CheckerTextureNode);
1302
1303   SOCKET_IN_POINT(
1304       vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_GENERATED);
1305   SOCKET_IN_COLOR(color1, "Color1", make_float3(0.0f, 0.0f, 0.0f));
1306   SOCKET_IN_COLOR(color2, "Color2", make_float3(0.0f, 0.0f, 0.0f));
1307   SOCKET_IN_FLOAT(scale, "Scale", 1.0f);
1308
1309   SOCKET_OUT_COLOR(color, "Color");
1310   SOCKET_OUT_FLOAT(fac, "Fac");
1311
1312   return type;
1313 }
1314
1315 CheckerTextureNode::CheckerTextureNode() : TextureNode(node_type)
1316 {
1317 }
1318
1319 void CheckerTextureNode::compile(SVMCompiler &compiler)
1320 {
1321   ShaderInput *vector_in = input("Vector");
1322   ShaderInput *color1_in = input("Color1");
1323   ShaderInput *color2_in = input("Color2");
1324   ShaderInput *scale_in = input("Scale");
1325
1326   ShaderOutput *color_out = output("Color");
1327   ShaderOutput *fac_out = output("Fac");
1328
1329   int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
1330
1331   compiler.add_node(NODE_TEX_CHECKER,
1332                     compiler.encode_uchar4(vector_offset,
1333                                            compiler.stack_assign(color1_in),
1334                                            compiler.stack_assign(color2_in),
1335                                            compiler.stack_assign_if_linked(scale_in)),
1336                     compiler.encode_uchar4(compiler.stack_assign_if_linked(color_out),
1337                                            compiler.stack_assign_if_linked(fac_out)),
1338                     __float_as_int(scale));
1339
1340   tex_mapping.compile_end(compiler, vector_in, vector_offset);
1341 }
1342
1343 void CheckerTextureNode::compile(OSLCompiler &compiler)
1344 {
1345   tex_mapping.compile(compiler);
1346
1347   compiler.add(this, "node_checker_texture");
1348 }
1349
1350 /* Brick Texture */
1351
1352 NODE_DEFINE(BrickTextureNode)
1353 {
1354   NodeType *type = NodeType::add("brick_texture", create, NodeType::SHADER);
1355
1356   TEXTURE_MAPPING_DEFINE(BrickTextureNode);
1357
1358   SOCKET_FLOAT(offset, "Offset", 0.5f);
1359   SOCKET_INT(offset_frequency, "Offset Frequency", 2);
1360   SOCKET_FLOAT(squash, "Squash", 1.0f);
1361   SOCKET_INT(squash_frequency, "Squash Frequency", 2);
1362
1363   SOCKET_IN_POINT(
1364       vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TEXTURE_GENERATED);
1365
1366   SOCKET_IN_COLOR(color1, "Color1", make_float3(0.0f, 0.0f, 0.0f));
1367   SOCKET_IN_COLOR(color2, "Color2", make_float3(0.0f, 0.0f, 0.0f));
1368   SOCKET_IN_COLOR(mortar, "Mortar", make_float3(0.0f, 0.0f, 0.0f));
1369   SOCKET_IN_FLOAT(scale, "Scale", 5.0f);
1370   SOCKET_IN_FLOAT(mortar_size, "Mortar Size", 0.02f);
1371   SOCKET_IN_FLOAT(mortar_smooth, "Mortar Smooth", 0.0f);
1372   SOCKET_IN_FLOAT(bias, "Bias", 0.0f);
1373   SOCKET_IN_FLOAT(brick_width, "Brick Width", 0.5f);
1374   SOCKET_IN_FLOAT(row_height, "Row Height", 0.25f);
1375
1376   SOCKET_OUT_COLOR(color, "Color");
1377   SOCKET_OUT_FLOAT(fac, "Fac");
1378
1379   return type;
1380 }
1381
1382 BrickTextureNode::BrickTextureNode() : TextureNode(node_type)
1383 {
1384 }
1385
1386 void BrickTextureNode::compile(SVMCompiler &compiler)
1387 {
1388   ShaderInput *vector_in = input("Vector");
1389   ShaderInput *color1_in = input("Color1");
1390   ShaderInput *color2_in = input("Color2");
1391   ShaderInput *mortar_in = input("Mortar");
1392   ShaderInput *scale_in = input("Scale");
1393   ShaderInput *mortar_size_in = input("Mortar Size");
1394   ShaderInput *mortar_smooth_in = input("Mortar Smooth");
1395   ShaderInput *bias_in = input("Bias");
1396   ShaderInput *brick_width_in = input("Brick Width");
1397   ShaderInput *row_height_in = input("Row Height");
1398
1399   ShaderOutput *color_out = output("Color");
1400   ShaderOutput *fac_out = output("Fac");
1401
1402   int vector_offset = tex_mapping.compile_begin(compiler, vector_in);
1403
1404   compiler.add_node(NODE_TEX_BRICK,
1405                     compiler.encode_uchar4(vector_offset,
1406                                            compiler.stack_assign(color1_in),
1407                                            compiler.stack_assign(color2_in),
1408                                            compiler.stack_assign(mortar_in)),
1409                     compiler.encode_uchar4(compiler.stack_assign_if_linked(scale_in),
1410                                            compiler.stack_assign_if_linked(mortar_size_in),
1411                                            compiler.stack_assign_if_linked(bias_in),
1412                                            compiler.stack_assign_if_linked(brick_width_in)),
1413                     compiler.encode_uchar4(compiler.stack_assign_if_linked(row_height_in),
1414                                            compiler.stack_assign_if_linked(color_out),
1415                                            compiler.stack_assign_if_linked(fac_out),
1416                                            compiler.stack_assign_if_linked(mortar_smooth_in)));
1417
1418   compiler.add_node(compiler.encode_uchar4(offset_frequency, squash_frequency),
1419                     __float_as_int(scale),
1420                     __float_as_int(mortar_size),
1421                     __float_as_int(bias));
1422
1423   compiler.add_node(__float_as_int(brick_width),
1424                     __float_as_int(row_height),
1425                     __float_as_int(offset),
1426                     __float_as_int(squash));
1427
1428   compiler.add_node(
1429       __float_as_int(mortar_smooth), SVM_STACK_INVALID, SVM_STACK_INVALID, SVM_STACK_INVALID);
1430
1431   tex_mapping.compile_end(compiler, vector_in, vector_offset);
1432 }
1433
1434 void BrickTextureNode::compile(OSLCompiler &compiler)
1435 {
1436   tex_mapping.compile(compiler);
1437
1438   compiler.parameter(this, "offset");
1439   compiler.parameter(this, "offset_frequency");
1440   compiler.parameter(this, "squash");
1441   compiler.parameter(this, "squash_frequency");
1442   compiler.add(this, "node_brick_texture");
1443 }
1444
1445 /* Point Density Texture */
1446
1447 NODE_DEFINE(PointDensityTextureNode)
1448 {
1449   NodeType *type = NodeType::add("point_density_texture", create, NodeType::SHADER);
1450
1451   SOCKET_STRING(filename, "Filename", ustring());
1452
1453   static NodeEnum space_enum;
1454   space_enum.insert("object", NODE_TEX_VOXEL_SPACE_OBJECT);
1455   space_enum.insert("world", NODE_TEX_VOXEL_SPACE_WORLD);
1456   SOCKET_ENUM(space, "Space", space_enum, NODE_TEX_VOXEL_SPACE_OBJECT);
1457
1458   static NodeEnum interpolation_enum;
1459   interpolation_enum.insert("closest", INTERPOLATION_CLOSEST);
1460   interpolation_enum.insert("linear", INTERPOLATION_LINEAR);
1461   interpolation_enum.insert("cubic", INTERPOLATION_CUBIC);
1462   interpolation_enum.insert("smart", INTERPOLATION_SMART);
1463   SOCKET_ENUM(interpolation, "Interpolation", interpolation_enum, INTERPOLATION_LINEAR);
1464
1465   SOCKET_TRANSFORM(tfm, "Transform", transform_identity());
1466
1467   SOCKET_IN_POINT(vector, "Vector", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_POSITION);
1468
1469   SOCKET_OUT_FLOAT(density, "Density");
1470   SOCKET_OUT_COLOR(color, "Color");
1471
1472   return type;
1473 }
1474
1475 PointDensityTextureNode::PointDensityTextureNode() : ShaderNode(node_type)
1476 {
1477   image_manager = NULL;
1478   slot = -1;
1479   builtin_data = NULL;
1480 }
1481
1482 PointDensityTextureNode::~PointDensityTextureNode()
1483 {
1484   if (image_manager) {
1485     image_manager->remove_image(
1486         filename.string(), builtin_data, interpolation, EXTENSION_CLIP, true);
1487   }
1488 }
1489
1490 ShaderNode *PointDensityTextureNode::clone() const
1491 {
1492   PointDensityTextureNode *node = new PointDensityTextureNode(*this);
1493   node->image_manager = NULL;
1494   node->slot = -1;
1495   return node;
1496 }
1497
1498 void PointDensityTextureNode::attributes(Shader *shader, AttributeRequestSet *attributes)
1499 {
1500   if (shader->has_volume)
1501     attributes->add(ATTR_STD_GENERATED_TRANSFORM);
1502
1503   ShaderNode::attributes(shader, attributes);
1504 }
1505
1506 void PointDensityTextureNode::add_image()
1507 {
1508   if (slot == -1) {
1509     ImageMetaData metadata;
1510     slot = image_manager->add_image(
1511         filename.string(), builtin_data, false, 0, interpolation, EXTENSION_CLIP, true, metadata);
1512   }
1513 }
1514
1515 void PointDensityTextureNode::compile(SVMCompiler &compiler)
1516 {
1517   ShaderInput *vector_in = input("Vector");
1518   ShaderOutput *density_out = output("Density");
1519   ShaderOutput *color_out = output("Color");
1520
1521   const bool use_density = !density_out->links.empty();
1522   const bool use_color = !color_out->links.empty();
1523
1524   image_manager = compiler.image_manager;
1525
1526   if (use_density || use_color) {
1527     add_image();
1528
1529     if (slot != -1) {
1530       compiler.stack_assign(vector_in);
1531       compiler.add_node(NODE_TEX_VOXEL,
1532                         slot,
1533                         compiler.encode_uchar4(compiler.stack_assign(vector_in),
1534                                                compiler.stack_assign_if_linked(density_out),
1535                                                compiler.stack_assign_if_linked(color_out),
1536                                                space));
1537       if (space == NODE_TEX_VOXEL_SPACE_WORLD) {
1538         compiler.add_node(tfm.x);
1539         compiler.add_node(tfm.y);
1540         compiler.add_node(tfm.z);
1541       }
1542     }
1543     else {
1544       if (use_density) {
1545         compiler.add_node(NODE_VALUE_F, __float_as_int(0.0f), compiler.stack_assign(density_out));
1546       }
1547       if (use_color) {
1548         compiler.add_node(NODE_VALUE_V, compiler.stack_assign(color_out));
1549         compiler.add_node(
1550             NODE_VALUE_V,
1551             make_float3(TEX_IMAGE_MISSING_R, TEX_IMAGE_MISSING_G, TEX_IMAGE_MISSING_B));
1552       }
1553     }
1554   }
1555 }
1556
1557 void PointDensityTextureNode::compile(OSLCompiler &compiler)
1558 {
1559   ShaderOutput *density_out = output("Density");
1560   ShaderOutput *color_out = output("Color");
1561
1562   const bool use_density = !density_out->links.empty();
1563   const bool use_color = !color_out->links.empty();
1564
1565   image_manager = compiler.image_manager;
1566
1567   if (use_density || use_color) {
1568     add_image();
1569
1570     if (slot != -1) {
1571       compiler.parameter("filename", string_printf("@i%d", slot).c_str());
1572     }
1573     if (space == NODE_TEX_VOXEL_SPACE_WORLD) {
1574       compiler.parameter("mapping", tfm);
1575       compiler.parameter("use_mapping", 1);
1576     }
1577     compiler.parameter(this, "interpolation");
1578     compiler.add(this, "node_voxel_texture");
1579   }
1580 }
1581
1582 /* Normal */
1583
1584 NODE_DEFINE(NormalNode)
1585 {
1586   NodeType *type = NodeType::add("normal", create, NodeType::SHADER);
1587
1588   SOCKET_VECTOR(direction, "direction", make_float3(0.0f, 0.0f, 0.0f));
1589
1590   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f));
1591
1592   SOCKET_OUT_NORMAL(normal, "Normal");
1593   SOCKET_OUT_FLOAT(dot, "Dot");
1594
1595   return type;
1596 }
1597
1598 NormalNode::NormalNode() : ShaderNode(node_type)
1599 {
1600 }
1601
1602 void NormalNode::compile(SVMCompiler &compiler)
1603 {
1604   ShaderInput *normal_in = input("Normal");
1605   ShaderOutput *normal_out = output("Normal");
1606   ShaderOutput *dot_out = output("Dot");
1607
1608   compiler.add_node(NODE_NORMAL,
1609                     compiler.stack_assign(normal_in),
1610                     compiler.stack_assign(normal_out),
1611                     compiler.stack_assign(dot_out));
1612   compiler.add_node(
1613       __float_as_int(direction.x), __float_as_int(direction.y), __float_as_int(direction.z));
1614 }
1615
1616 void NormalNode::compile(OSLCompiler &compiler)
1617 {
1618   compiler.parameter(this, "direction");
1619   compiler.add(this, "node_normal");
1620 }
1621
1622 /* Mapping */
1623
1624 NODE_DEFINE(MappingNode)
1625 {
1626   NodeType *type = NodeType::add("mapping", create, NodeType::SHADER);
1627
1628   TEXTURE_MAPPING_DEFINE(MappingNode);
1629
1630   SOCKET_IN_POINT(vector, "Vector", make_float3(0.0f, 0.0f, 0.0f));
1631   SOCKET_OUT_POINT(vector, "Vector");
1632
1633   return type;
1634 }
1635
1636 MappingNode::MappingNode() : ShaderNode(node_type)
1637 {
1638 }
1639
1640 void MappingNode::compile(SVMCompiler &compiler)
1641 {
1642   ShaderInput *vector_in = input("Vector");
1643   ShaderOutput *vector_out = output("Vector");
1644
1645   tex_mapping.compile(
1646       compiler, compiler.stack_assign(vector_in), compiler.stack_assign(vector_out));
1647 }
1648
1649 void MappingNode::compile(OSLCompiler &compiler)
1650 {
1651   compiler.parameter("Matrix", tex_mapping.compute_transform());
1652   compiler.parameter_point("mapping_min", tex_mapping.min);
1653   compiler.parameter_point("mapping_max", tex_mapping.max);
1654   compiler.parameter("use_minmax", tex_mapping.use_minmax);
1655
1656   compiler.add(this, "node_mapping");
1657 }
1658
1659 /* RGBToBW */
1660
1661 NODE_DEFINE(RGBToBWNode)
1662 {
1663   NodeType *type = NodeType::add("rgb_to_bw", create, NodeType::SHADER);
1664
1665   SOCKET_IN_COLOR(color, "Color", make_float3(0.0f, 0.0f, 0.0f));
1666   SOCKET_OUT_FLOAT(val, "Val");
1667
1668   return type;
1669 }
1670
1671 RGBToBWNode::RGBToBWNode() : ShaderNode(node_type)
1672 {
1673 }
1674
1675 void RGBToBWNode::constant_fold(const ConstantFolder &folder)
1676 {
1677   if (folder.all_inputs_constant()) {
1678     float val = folder.scene->shader_manager->linear_rgb_to_gray(color);
1679     folder.make_constant(val);
1680   }
1681 }
1682
1683 void RGBToBWNode::compile(SVMCompiler &compiler)
1684 {
1685   compiler.add_node(NODE_CONVERT,
1686                     NODE_CONVERT_CF,
1687                     compiler.stack_assign(inputs[0]),
1688                     compiler.stack_assign(outputs[0]));
1689 }
1690
1691 void RGBToBWNode::compile(OSLCompiler &compiler)
1692 {
1693   compiler.add(this, "node_rgb_to_bw");
1694 }
1695
1696 /* Convert */
1697
1698 const NodeType *ConvertNode::node_types[ConvertNode::MAX_TYPE][ConvertNode::MAX_TYPE];
1699 bool ConvertNode::initialized = ConvertNode::register_types();
1700
1701 Node *ConvertNode::create(const NodeType *type)
1702 {
1703   return new ConvertNode(type->inputs[0].type, type->outputs[0].type);
1704 }
1705
1706 bool ConvertNode::register_types()
1707 {
1708   const int num_types = 8;
1709   SocketType::Type types[num_types] = {SocketType::FLOAT,
1710                                        SocketType::INT,
1711                                        SocketType::COLOR,
1712                                        SocketType::VECTOR,
1713                                        SocketType::POINT,
1714                                        SocketType::NORMAL,
1715                                        SocketType::STRING,
1716                                        SocketType::CLOSURE};
1717
1718   for (size_t i = 0; i < num_types; i++) {
1719     SocketType::Type from = types[i];
1720     ustring from_name(SocketType::type_name(from));
1721     ustring from_value_name("value_" + from_name.string());
1722
1723     for (size_t j = 0; j < num_types; j++) {
1724       SocketType::Type to = types[j];
1725       ustring to_name(SocketType::type_name(to));
1726       ustring to_value_name("value_" + to_name.string());
1727
1728       string node_name = "convert_" + from_name.string() + "_to_" + to_name.string();
1729       NodeType *type = NodeType::add(node_name.c_str(), create, NodeType::SHADER);
1730
1731       type->register_input(from_value_name,
1732                            from_value_name,
1733                            from,
1734                            SOCKET_OFFSETOF(ConvertNode, value_float),
1735                            SocketType::zero_default_value(),
1736                            NULL,
1737                            NULL,
1738                            SocketType::LINKABLE);
1739       type->register_output(to_value_name, to_value_name, to);
1740
1741       assert(from < MAX_TYPE);
1742       assert(to < MAX_TYPE);
1743
1744       node_types[from][to] = type;
1745     }
1746   }
1747
1748   return true;
1749 }
1750
1751 ConvertNode::ConvertNode(SocketType::Type from_, SocketType::Type to_, bool autoconvert)
1752     : ShaderNode(node_types[from_][to_])
1753 {
1754   from = from_;
1755   to = to_;
1756
1757   if (from == to)
1758     special_type = SHADER_SPECIAL_TYPE_PROXY;
1759   else if (autoconvert)
1760     special_type = SHADER_SPECIAL_TYPE_AUTOCONVERT;
1761 }
1762
1763 void ConvertNode::constant_fold(const ConstantFolder &folder)
1764 {
1765   /* proxy nodes should have been removed at this point */
1766   assert(special_type != SHADER_SPECIAL_TYPE_PROXY);
1767
1768   /* TODO(DingTo): conversion from/to int is not supported yet, don't fold in that case */
1769
1770   if (folder.all_inputs_constant()) {
1771     if (from == SocketType::FLOAT) {
1772       if (SocketType::is_float3(to)) {
1773         folder.make_constant(make_float3(value_float, value_float, value_float));
1774       }
1775     }
1776     else if (SocketType::is_float3(from)) {
1777       if (to == SocketType::FLOAT) {
1778         if (from == SocketType::COLOR) {
1779           /* color to float */
1780           float val = folder.scene->shader_manager->linear_rgb_to_gray(value_color);
1781           folder.make_constant(val);
1782         }
1783         else {
1784           /* vector/point/normal to float */
1785           folder.make_constant(average(value_vector));
1786         }
1787       }
1788       else if (SocketType::is_float3(to)) {
1789         folder.make_constant(value_color);
1790       }
1791     }
1792   }
1793   else {
1794     ShaderInput *in = inputs[0];
1795     ShaderNode *prev = in->link->parent;
1796
1797     /* no-op conversion of A to B to A */
1798     if (prev->type == node_types[to][from]) {
1799       ShaderInput *prev_in = prev->inputs[0];
1800
1801       if (SocketType::is_float3(from) && (to == SocketType::FLOAT || SocketType::is_float3(to)) &&
1802           prev_in->link) {
1803         folder.bypass(prev_in->link);
1804       }
1805     }
1806   }
1807 }
1808
1809 void ConvertNode::compile(SVMCompiler &compiler)
1810 {
1811   /* proxy nodes should have been removed at this point */
1812   assert(special_type != SHADER_SPECIAL_TYPE_PROXY);
1813
1814   ShaderInput *in = inputs[0];
1815   ShaderOutput *out = outputs[0];
1816
1817   if (from == SocketType::FLOAT) {
1818     if (to == SocketType::INT)
1819       /* float to int */
1820       compiler.add_node(
1821           NODE_CONVERT, NODE_CONVERT_FI, compiler.stack_assign(in), compiler.stack_assign(out));
1822     else
1823       /* float to float3 */
1824       compiler.add_node(
1825           NODE_CONVERT, NODE_CONVERT_FV, compiler.stack_assign(in), compiler.stack_assign(out));
1826   }
1827   else if (from == SocketType::INT) {
1828     if (to == SocketType::FLOAT)
1829       /* int to float */
1830       compiler.add_node(
1831           NODE_CONVERT, NODE_CONVERT_IF, compiler.stack_assign(in), compiler.stack_assign(out));
1832     else
1833       /* int to vector/point/normal */
1834       compiler.add_node(
1835           NODE_CONVERT, NODE_CONVERT_IV, compiler.stack_assign(in), compiler.stack_assign(out));
1836   }
1837   else if (to == SocketType::FLOAT) {
1838     if (from == SocketType::COLOR)
1839       /* color to float */
1840       compiler.add_node(
1841           NODE_CONVERT, NODE_CONVERT_CF, compiler.stack_assign(in), compiler.stack_assign(out));
1842     else
1843       /* vector/point/normal to float */
1844       compiler.add_node(
1845           NODE_CONVERT, NODE_CONVERT_VF, compiler.stack_assign(in), compiler.stack_assign(out));
1846   }
1847   else if (to == SocketType::INT) {
1848     if (from == SocketType::COLOR)
1849       /* color to int */
1850       compiler.add_node(
1851           NODE_CONVERT, NODE_CONVERT_CI, compiler.stack_assign(in), compiler.stack_assign(out));
1852     else
1853       /* vector/point/normal to int */
1854       compiler.add_node(
1855           NODE_CONVERT, NODE_CONVERT_VI, compiler.stack_assign(in), compiler.stack_assign(out));
1856   }
1857   else {
1858     /* float3 to float3 */
1859     if (in->link) {
1860       /* no op in SVM */
1861       compiler.stack_link(in, out);
1862     }
1863     else {
1864       /* set 0,0,0 value */
1865       compiler.add_node(NODE_VALUE_V, compiler.stack_assign(out));
1866       compiler.add_node(NODE_VALUE_V, value_color);
1867     }
1868   }
1869 }
1870
1871 void ConvertNode::compile(OSLCompiler &compiler)
1872 {
1873   /* proxy nodes should have been removed at this point */
1874   assert(special_type != SHADER_SPECIAL_TYPE_PROXY);
1875
1876   if (from == SocketType::FLOAT)
1877     compiler.add(this, "node_convert_from_float");
1878   else if (from == SocketType::INT)
1879     compiler.add(this, "node_convert_from_int");
1880   else if (from == SocketType::COLOR)
1881     compiler.add(this, "node_convert_from_color");
1882   else if (from == SocketType::VECTOR)
1883     compiler.add(this, "node_convert_from_vector");
1884   else if (from == SocketType::POINT)
1885     compiler.add(this, "node_convert_from_point");
1886   else if (from == SocketType::NORMAL)
1887     compiler.add(this, "node_convert_from_normal");
1888   else
1889     assert(0);
1890 }
1891
1892 /* Base type for all closure-type nodes */
1893
1894 BsdfBaseNode::BsdfBaseNode(const NodeType *node_type) : ShaderNode(node_type)
1895 {
1896   special_type = SHADER_SPECIAL_TYPE_CLOSURE;
1897 }
1898
1899 bool BsdfBaseNode::has_bump()
1900 {
1901   /* detect if anything is plugged into the normal input besides the default */
1902   ShaderInput *normal_in = input("Normal");
1903   return (normal_in && normal_in->link &&
1904           normal_in->link->parent->special_type != SHADER_SPECIAL_TYPE_GEOMETRY);
1905 }
1906
1907 /* BSDF Closure */
1908
1909 BsdfNode::BsdfNode(const NodeType *node_type) : BsdfBaseNode(node_type)
1910 {
1911 }
1912
1913 void BsdfNode::compile(SVMCompiler &compiler,
1914                        ShaderInput *param1,
1915                        ShaderInput *param2,
1916                        ShaderInput *param3,
1917                        ShaderInput *param4)
1918 {
1919   ShaderInput *color_in = input("Color");
1920   ShaderInput *normal_in = input("Normal");
1921   ShaderInput *tangent_in = input("Tangent");
1922
1923   if (color_in->link)
1924     compiler.add_node(NODE_CLOSURE_WEIGHT, compiler.stack_assign(color_in));
1925   else
1926     compiler.add_node(NODE_CLOSURE_SET_WEIGHT, color);
1927
1928   int normal_offset = (normal_in) ? compiler.stack_assign_if_linked(normal_in) : SVM_STACK_INVALID;
1929   int tangent_offset = (tangent_in) ? compiler.stack_assign_if_linked(tangent_in) :
1930                                       SVM_STACK_INVALID;
1931   int param3_offset = (param3) ? compiler.stack_assign(param3) : SVM_STACK_INVALID;
1932   int param4_offset = (param4) ? compiler.stack_assign(param4) : SVM_STACK_INVALID;
1933
1934   compiler.add_node(
1935       NODE_CLOSURE_BSDF,
1936       compiler.encode_uchar4(closure,
1937                              (param1) ? compiler.stack_assign(param1) : SVM_STACK_INVALID,
1938                              (param2) ? compiler.stack_assign(param2) : SVM_STACK_INVALID,
1939                              compiler.closure_mix_weight_offset()),
1940       __float_as_int((param1) ? get_float(param1->socket_type) : 0.0f),
1941       __float_as_int((param2) ? get_float(param2->socket_type) : 0.0f));
1942
1943   compiler.add_node(normal_offset, tangent_offset, param3_offset, param4_offset);
1944 }
1945
1946 void BsdfNode::compile(SVMCompiler &compiler)
1947 {
1948   compile(compiler, NULL, NULL);
1949 }
1950
1951 void BsdfNode::compile(OSLCompiler & /*compiler*/)
1952 {
1953   assert(0);
1954 }
1955
1956 /* Anisotropic BSDF Closure */
1957
1958 NODE_DEFINE(AnisotropicBsdfNode)
1959 {
1960   NodeType *type = NodeType::add("anisotropic_bsdf", create, NodeType::SHADER);
1961
1962   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
1963   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
1964   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
1965
1966   static NodeEnum distribution_enum;
1967   distribution_enum.insert("beckmann", CLOSURE_BSDF_MICROFACET_BECKMANN_ANISO_ID);
1968   distribution_enum.insert("GGX", CLOSURE_BSDF_MICROFACET_GGX_ANISO_ID);
1969   distribution_enum.insert("Multiscatter GGX", CLOSURE_BSDF_MICROFACET_MULTI_GGX_ANISO_ID);
1970   distribution_enum.insert("ashikhmin_shirley", CLOSURE_BSDF_ASHIKHMIN_SHIRLEY_ANISO_ID);
1971   SOCKET_ENUM(
1972       distribution, "Distribution", distribution_enum, CLOSURE_BSDF_MICROFACET_GGX_ANISO_ID);
1973
1974   SOCKET_IN_VECTOR(tangent, "Tangent", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TANGENT);
1975
1976   SOCKET_IN_FLOAT(roughness, "Roughness", 0.5f);
1977   SOCKET_IN_FLOAT(anisotropy, "Anisotropy", 0.5f);
1978   SOCKET_IN_FLOAT(rotation, "Rotation", 0.0f);
1979
1980   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
1981
1982   return type;
1983 }
1984
1985 AnisotropicBsdfNode::AnisotropicBsdfNode() : BsdfNode(node_type)
1986 {
1987   closure = CLOSURE_BSDF_MICROFACET_GGX_ANISO_ID;
1988 }
1989
1990 void AnisotropicBsdfNode::attributes(Shader *shader, AttributeRequestSet *attributes)
1991 {
1992   if (shader->has_surface) {
1993     ShaderInput *tangent_in = input("Tangent");
1994
1995     if (!tangent_in->link)
1996       attributes->add(ATTR_STD_GENERATED);
1997   }
1998
1999   ShaderNode::attributes(shader, attributes);
2000 }
2001
2002 void AnisotropicBsdfNode::compile(SVMCompiler &compiler)
2003 {
2004   closure = distribution;
2005
2006   if (closure == CLOSURE_BSDF_MICROFACET_MULTI_GGX_ANISO_ID)
2007     BsdfNode::compile(
2008         compiler, input("Roughness"), input("Anisotropy"), input("Rotation"), input("Color"));
2009   else
2010     BsdfNode::compile(compiler, input("Roughness"), input("Anisotropy"), input("Rotation"));
2011 }
2012
2013 void AnisotropicBsdfNode::compile(OSLCompiler &compiler)
2014 {
2015   compiler.parameter(this, "distribution");
2016   compiler.add(this, "node_anisotropic_bsdf");
2017 }
2018
2019 /* Glossy BSDF Closure */
2020
2021 NODE_DEFINE(GlossyBsdfNode)
2022 {
2023   NodeType *type = NodeType::add("glossy_bsdf", create, NodeType::SHADER);
2024
2025   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2026   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
2027   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2028
2029   static NodeEnum distribution_enum;
2030   distribution_enum.insert("sharp", CLOSURE_BSDF_REFLECTION_ID);
2031   distribution_enum.insert("beckmann", CLOSURE_BSDF_MICROFACET_BECKMANN_ID);
2032   distribution_enum.insert("GGX", CLOSURE_BSDF_MICROFACET_GGX_ID);
2033   distribution_enum.insert("ashikhmin_shirley", CLOSURE_BSDF_ASHIKHMIN_SHIRLEY_ID);
2034   distribution_enum.insert("Multiscatter GGX", CLOSURE_BSDF_MICROFACET_MULTI_GGX_ID);
2035   SOCKET_ENUM(distribution, "Distribution", distribution_enum, CLOSURE_BSDF_MICROFACET_GGX_ID);
2036   SOCKET_IN_FLOAT(roughness, "Roughness", 0.5f);
2037
2038   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
2039
2040   return type;
2041 }
2042
2043 GlossyBsdfNode::GlossyBsdfNode() : BsdfNode(node_type)
2044 {
2045   closure = CLOSURE_BSDF_MICROFACET_GGX_ID;
2046   distribution_orig = NBUILTIN_CLOSURES;
2047 }
2048
2049 void GlossyBsdfNode::simplify_settings(Scene *scene)
2050 {
2051   if (distribution_orig == NBUILTIN_CLOSURES) {
2052     roughness_orig = roughness;
2053     distribution_orig = distribution;
2054   }
2055   else {
2056     /* By default we use original values, so we don't worry about restoring
2057      * defaults later one and can only do override when needed.
2058      */
2059     roughness = roughness_orig;
2060     distribution = distribution_orig;
2061   }
2062   Integrator *integrator = scene->integrator;
2063   ShaderInput *roughness_input = input("Roughness");
2064   if (integrator->filter_glossy == 0.0f) {
2065     /* Fallback to Sharp closure for Roughness close to 0.
2066      * Note: Keep the epsilon in sync with kernel!
2067      */
2068     if (!roughness_input->link && roughness <= 1e-4f) {
2069       VLOG(1) << "Using sharp glossy BSDF.";
2070       distribution = CLOSURE_BSDF_REFLECTION_ID;
2071     }
2072   }
2073   else {
2074     /* If filter glossy is used we replace Sharp glossy with GGX so we can
2075      * benefit from closure blur to remove unwanted noise.
2076      */
2077     if (roughness_input->link == NULL && distribution == CLOSURE_BSDF_REFLECTION_ID) {
2078       VLOG(1) << "Using GGX glossy with filter glossy.";
2079       distribution = CLOSURE_BSDF_MICROFACET_GGX_ID;
2080       roughness = 0.0f;
2081     }
2082   }
2083   closure = distribution;
2084 }
2085
2086 bool GlossyBsdfNode::has_integrator_dependency()
2087 {
2088   ShaderInput *roughness_input = input("Roughness");
2089   return !roughness_input->link &&
2090          (distribution == CLOSURE_BSDF_REFLECTION_ID || roughness <= 1e-4f);
2091 }
2092
2093 void GlossyBsdfNode::compile(SVMCompiler &compiler)
2094 {
2095   closure = distribution;
2096
2097   if (closure == CLOSURE_BSDF_REFLECTION_ID)
2098     BsdfNode::compile(compiler, NULL, NULL);
2099   else if (closure == CLOSURE_BSDF_MICROFACET_MULTI_GGX_ID)
2100     BsdfNode::compile(compiler, input("Roughness"), NULL, input("Color"));
2101   else
2102     BsdfNode::compile(compiler, input("Roughness"), NULL);
2103 }
2104
2105 void GlossyBsdfNode::compile(OSLCompiler &compiler)
2106 {
2107   compiler.parameter(this, "distribution");
2108   compiler.add(this, "node_glossy_bsdf");
2109 }
2110
2111 /* Glass BSDF Closure */
2112
2113 NODE_DEFINE(GlassBsdfNode)
2114 {
2115   NodeType *type = NodeType::add("glass_bsdf", create, NodeType::SHADER);
2116
2117   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2118   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
2119   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2120
2121   static NodeEnum distribution_enum;
2122   distribution_enum.insert("sharp", CLOSURE_BSDF_SHARP_GLASS_ID);
2123   distribution_enum.insert("beckmann", CLOSURE_BSDF_MICROFACET_BECKMANN_GLASS_ID);
2124   distribution_enum.insert("GGX", CLOSURE_BSDF_MICROFACET_GGX_GLASS_ID);
2125   distribution_enum.insert("Multiscatter GGX", CLOSURE_BSDF_MICROFACET_MULTI_GGX_GLASS_ID);
2126   SOCKET_ENUM(
2127       distribution, "Distribution", distribution_enum, CLOSURE_BSDF_MICROFACET_GGX_GLASS_ID);
2128   SOCKET_IN_FLOAT(roughness, "Roughness", 0.0f);
2129   SOCKET_IN_FLOAT(IOR, "IOR", 0.3f);
2130
2131   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
2132
2133   return type;
2134 }
2135
2136 GlassBsdfNode::GlassBsdfNode() : BsdfNode(node_type)
2137 {
2138   closure = CLOSURE_BSDF_SHARP_GLASS_ID;
2139   distribution_orig = NBUILTIN_CLOSURES;
2140 }
2141
2142 void GlassBsdfNode::simplify_settings(Scene *scene)
2143 {
2144   if (distribution_orig == NBUILTIN_CLOSURES) {
2145     roughness_orig = roughness;
2146     distribution_orig = distribution;
2147   }
2148   else {
2149     /* By default we use original values, so we don't worry about restoring
2150      * defaults later one and can only do override when needed.
2151      */
2152     roughness = roughness_orig;
2153     distribution = distribution_orig;
2154   }
2155   Integrator *integrator = scene->integrator;
2156   ShaderInput *roughness_input = input("Roughness");
2157   if (integrator->filter_glossy == 0.0f) {
2158     /* Fallback to Sharp closure for Roughness close to 0.
2159      * Note: Keep the epsilon in sync with kernel!
2160      */
2161     if (!roughness_input->link && roughness <= 1e-4f) {
2162       VLOG(1) << "Using sharp glass BSDF.";
2163       distribution = CLOSURE_BSDF_SHARP_GLASS_ID;
2164     }
2165   }
2166   else {
2167     /* If filter glossy is used we replace Sharp glossy with GGX so we can
2168      * benefit from closure blur to remove unwanted noise.
2169      */
2170     if (roughness_input->link == NULL && distribution == CLOSURE_BSDF_SHARP_GLASS_ID) {
2171       VLOG(1) << "Using GGX glass with filter glossy.";
2172       distribution = CLOSURE_BSDF_MICROFACET_GGX_GLASS_ID;
2173       roughness = 0.0f;
2174     }
2175   }
2176   closure = distribution;
2177 }
2178
2179 bool GlassBsdfNode::has_integrator_dependency()
2180 {
2181   ShaderInput *roughness_input = input("Roughness");
2182   return !roughness_input->link &&
2183          (distribution == CLOSURE_BSDF_SHARP_GLASS_ID || roughness <= 1e-4f);
2184 }
2185
2186 void GlassBsdfNode::compile(SVMCompiler &compiler)
2187 {
2188   closure = distribution;
2189
2190   if (closure == CLOSURE_BSDF_SHARP_GLASS_ID)
2191     BsdfNode::compile(compiler, NULL, input("IOR"));
2192   else if (closure == CLOSURE_BSDF_MICROFACET_MULTI_GGX_GLASS_ID)
2193     BsdfNode::compile(compiler, input("Roughness"), input("IOR"), input("Color"));
2194   else
2195     BsdfNode::compile(compiler, input("Roughness"), input("IOR"));
2196 }
2197
2198 void GlassBsdfNode::compile(OSLCompiler &compiler)
2199 {
2200   compiler.parameter(this, "distribution");
2201   compiler.add(this, "node_glass_bsdf");
2202 }
2203
2204 /* Refraction BSDF Closure */
2205
2206 NODE_DEFINE(RefractionBsdfNode)
2207 {
2208   NodeType *type = NodeType::add("refraction_bsdf", create, NodeType::SHADER);
2209
2210   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2211   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
2212   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2213
2214   static NodeEnum distribution_enum;
2215   distribution_enum.insert("sharp", CLOSURE_BSDF_REFRACTION_ID);
2216   distribution_enum.insert("beckmann", CLOSURE_BSDF_MICROFACET_BECKMANN_REFRACTION_ID);
2217   distribution_enum.insert("GGX", CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID);
2218   SOCKET_ENUM(
2219       distribution, "Distribution", distribution_enum, CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID);
2220
2221   SOCKET_IN_FLOAT(roughness, "Roughness", 0.0f);
2222   SOCKET_IN_FLOAT(IOR, "IOR", 0.3f);
2223
2224   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
2225
2226   return type;
2227 }
2228
2229 RefractionBsdfNode::RefractionBsdfNode() : BsdfNode(node_type)
2230 {
2231   closure = CLOSURE_BSDF_REFRACTION_ID;
2232   distribution_orig = NBUILTIN_CLOSURES;
2233 }
2234
2235 void RefractionBsdfNode::simplify_settings(Scene *scene)
2236 {
2237   if (distribution_orig == NBUILTIN_CLOSURES) {
2238     roughness_orig = roughness;
2239     distribution_orig = distribution;
2240   }
2241   else {
2242     /* By default we use original values, so we don't worry about restoring
2243      * defaults later one and can only do override when needed.
2244      */
2245     roughness = roughness_orig;
2246     distribution = distribution_orig;
2247   }
2248   Integrator *integrator = scene->integrator;
2249   ShaderInput *roughness_input = input("Roughness");
2250   if (integrator->filter_glossy == 0.0f) {
2251     /* Fallback to Sharp closure for Roughness close to 0.
2252      * Note: Keep the epsilon in sync with kernel!
2253      */
2254     if (!roughness_input->link && roughness <= 1e-4f) {
2255       VLOG(1) << "Using sharp refraction BSDF.";
2256       distribution = CLOSURE_BSDF_REFRACTION_ID;
2257     }
2258   }
2259   else {
2260     /* If filter glossy is used we replace Sharp glossy with GGX so we can
2261      * benefit from closure blur to remove unwanted noise.
2262      */
2263     if (roughness_input->link == NULL && distribution == CLOSURE_BSDF_REFRACTION_ID) {
2264       VLOG(1) << "Using GGX refraction with filter glossy.";
2265       distribution = CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID;
2266       roughness = 0.0f;
2267     }
2268   }
2269   closure = distribution;
2270 }
2271
2272 bool RefractionBsdfNode::has_integrator_dependency()
2273 {
2274   ShaderInput *roughness_input = input("Roughness");
2275   return !roughness_input->link &&
2276          (distribution == CLOSURE_BSDF_REFRACTION_ID || roughness <= 1e-4f);
2277 }
2278
2279 void RefractionBsdfNode::compile(SVMCompiler &compiler)
2280 {
2281   closure = distribution;
2282
2283   if (closure == CLOSURE_BSDF_REFRACTION_ID)
2284     BsdfNode::compile(compiler, NULL, input("IOR"));
2285   else
2286     BsdfNode::compile(compiler, input("Roughness"), input("IOR"));
2287 }
2288
2289 void RefractionBsdfNode::compile(OSLCompiler &compiler)
2290 {
2291   compiler.parameter(this, "distribution");
2292   compiler.add(this, "node_refraction_bsdf");
2293 }
2294
2295 /* Toon BSDF Closure */
2296
2297 NODE_DEFINE(ToonBsdfNode)
2298 {
2299   NodeType *type = NodeType::add("toon_bsdf", create, NodeType::SHADER);
2300
2301   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2302   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
2303   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2304
2305   static NodeEnum component_enum;
2306   component_enum.insert("diffuse", CLOSURE_BSDF_DIFFUSE_TOON_ID);
2307   component_enum.insert("glossy", CLOSURE_BSDF_GLOSSY_TOON_ID);
2308   SOCKET_ENUM(component, "Component", component_enum, CLOSURE_BSDF_DIFFUSE_TOON_ID);
2309   SOCKET_IN_FLOAT(size, "Size", 0.5f);
2310   SOCKET_IN_FLOAT(smooth, "Smooth", 0.0f);
2311
2312   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
2313
2314   return type;
2315 }
2316
2317 ToonBsdfNode::ToonBsdfNode() : BsdfNode(node_type)
2318 {
2319   closure = CLOSURE_BSDF_DIFFUSE_TOON_ID;
2320 }
2321
2322 void ToonBsdfNode::compile(SVMCompiler &compiler)
2323 {
2324   closure = component;
2325
2326   BsdfNode::compile(compiler, input("Size"), input("Smooth"));
2327 }
2328
2329 void ToonBsdfNode::compile(OSLCompiler &compiler)
2330 {
2331   compiler.parameter(this, "component");
2332   compiler.add(this, "node_toon_bsdf");
2333 }
2334
2335 /* Velvet BSDF Closure */
2336
2337 NODE_DEFINE(VelvetBsdfNode)
2338 {
2339   NodeType *type = NodeType::add("velvet_bsdf", create, NodeType::SHADER);
2340
2341   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2342   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
2343   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2344   SOCKET_IN_FLOAT(sigma, "Sigma", 1.0f);
2345
2346   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
2347
2348   return type;
2349 }
2350
2351 VelvetBsdfNode::VelvetBsdfNode() : BsdfNode(node_type)
2352 {
2353   closure = CLOSURE_BSDF_ASHIKHMIN_VELVET_ID;
2354 }
2355
2356 void VelvetBsdfNode::compile(SVMCompiler &compiler)
2357 {
2358   BsdfNode::compile(compiler, input("Sigma"), NULL);
2359 }
2360
2361 void VelvetBsdfNode::compile(OSLCompiler &compiler)
2362 {
2363   compiler.add(this, "node_velvet_bsdf");
2364 }
2365
2366 /* Diffuse BSDF Closure */
2367
2368 NODE_DEFINE(DiffuseBsdfNode)
2369 {
2370   NodeType *type = NodeType::add("diffuse_bsdf", create, NodeType::SHADER);
2371
2372   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2373   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
2374   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2375   SOCKET_IN_FLOAT(roughness, "Roughness", 0.0f);
2376
2377   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
2378
2379   return type;
2380 }
2381
2382 DiffuseBsdfNode::DiffuseBsdfNode() : BsdfNode(node_type)
2383 {
2384   closure = CLOSURE_BSDF_DIFFUSE_ID;
2385 }
2386
2387 void DiffuseBsdfNode::compile(SVMCompiler &compiler)
2388 {
2389   BsdfNode::compile(compiler, input("Roughness"), NULL);
2390 }
2391
2392 void DiffuseBsdfNode::compile(OSLCompiler &compiler)
2393 {
2394   compiler.add(this, "node_diffuse_bsdf");
2395 }
2396
2397 /* Disney principled BSDF Closure */
2398 NODE_DEFINE(PrincipledBsdfNode)
2399 {
2400   NodeType *type = NodeType::add("principled_bsdf", create, NodeType::SHADER);
2401
2402   static NodeEnum distribution_enum;
2403   distribution_enum.insert("GGX", CLOSURE_BSDF_MICROFACET_GGX_GLASS_ID);
2404   distribution_enum.insert("Multiscatter GGX", CLOSURE_BSDF_MICROFACET_MULTI_GGX_GLASS_ID);
2405   SOCKET_ENUM(
2406       distribution, "Distribution", distribution_enum, CLOSURE_BSDF_MICROFACET_MULTI_GGX_GLASS_ID);
2407
2408   static NodeEnum subsurface_method_enum;
2409   subsurface_method_enum.insert("burley", CLOSURE_BSSRDF_PRINCIPLED_ID);
2410   subsurface_method_enum.insert("random_walk", CLOSURE_BSSRDF_PRINCIPLED_RANDOM_WALK_ID);
2411   SOCKET_ENUM(subsurface_method,
2412               "Subsurface Method",
2413               subsurface_method_enum,
2414               CLOSURE_BSSRDF_PRINCIPLED_ID);
2415
2416   SOCKET_IN_COLOR(base_color, "Base Color", make_float3(0.8f, 0.8f, 0.8f));
2417   SOCKET_IN_COLOR(subsurface_color, "Subsurface Color", make_float3(0.8f, 0.8f, 0.8f));
2418   SOCKET_IN_FLOAT(metallic, "Metallic", 0.0f);
2419   SOCKET_IN_FLOAT(subsurface, "Subsurface", 0.0f);
2420   SOCKET_IN_VECTOR(subsurface_radius, "Subsurface Radius", make_float3(0.1f, 0.1f, 0.1f));
2421   SOCKET_IN_FLOAT(specular, "Specular", 0.0f);
2422   SOCKET_IN_FLOAT(roughness, "Roughness", 0.5f);
2423   SOCKET_IN_FLOAT(specular_tint, "Specular Tint", 0.0f);
2424   SOCKET_IN_FLOAT(anisotropic, "Anisotropic", 0.0f);
2425   SOCKET_IN_FLOAT(sheen, "Sheen", 0.0f);
2426   SOCKET_IN_FLOAT(sheen_tint, "Sheen Tint", 0.0f);
2427   SOCKET_IN_FLOAT(clearcoat, "Clearcoat", 0.0f);
2428   SOCKET_IN_FLOAT(clearcoat_roughness, "Clearcoat Roughness", 0.03f);
2429   SOCKET_IN_FLOAT(ior, "IOR", 0.0f);
2430   SOCKET_IN_FLOAT(transmission, "Transmission", 0.0f);
2431   SOCKET_IN_FLOAT(transmission_roughness, "Transmission Roughness", 0.0f);
2432   SOCKET_IN_FLOAT(anisotropic_rotation, "Anisotropic Rotation", 0.0f);
2433   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
2434   SOCKET_IN_NORMAL(clearcoat_normal,
2435                    "Clearcoat Normal",
2436                    make_float3(0.0f, 0.0f, 0.0f),
2437                    SocketType::LINK_NORMAL);
2438   SOCKET_IN_NORMAL(tangent, "Tangent", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_TANGENT);
2439   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2440
2441   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
2442
2443   return type;
2444 }
2445
2446 PrincipledBsdfNode::PrincipledBsdfNode() : BsdfBaseNode(node_type)
2447 {
2448   closure = CLOSURE_BSDF_PRINCIPLED_ID;
2449   distribution = CLOSURE_BSDF_MICROFACET_MULTI_GGX_GLASS_ID;
2450   distribution_orig = NBUILTIN_CLOSURES;
2451 }
2452
2453 bool PrincipledBsdfNode::has_surface_bssrdf()
2454 {
2455   ShaderInput *subsurface_in = input("Subsurface");
2456   return (subsurface_in->link != NULL || subsurface > CLOSURE_WEIGHT_CUTOFF);
2457 }
2458
2459 void PrincipledBsdfNode::attributes(Shader *shader, AttributeRequestSet *attributes)
2460 {
2461   if (shader->has_surface) {
2462     ShaderInput *tangent_in = input("Tangent");
2463
2464     if (!tangent_in->link)
2465       attributes->add(ATTR_STD_GENERATED);
2466   }
2467
2468   ShaderNode::attributes(shader, attributes);
2469 }
2470
2471 void PrincipledBsdfNode::compile(SVMCompiler &compiler,
2472                                  ShaderInput *p_metallic,
2473                                  ShaderInput *p_subsurface,
2474                                  ShaderInput *p_subsurface_radius,
2475                                  ShaderInput *p_specular,
2476                                  ShaderInput *p_roughness,
2477                                  ShaderInput *p_specular_tint,
2478                                  ShaderInput *p_anisotropic,
2479                                  ShaderInput *p_sheen,
2480                                  ShaderInput *p_sheen_tint,
2481                                  ShaderInput *p_clearcoat,
2482                                  ShaderInput *p_clearcoat_roughness,
2483                                  ShaderInput *p_ior,
2484                                  ShaderInput *p_transmission,
2485                                  ShaderInput *p_anisotropic_rotation,
2486                                  ShaderInput *p_transmission_roughness)
2487 {
2488   ShaderInput *base_color_in = input("Base Color");
2489   ShaderInput *subsurface_color_in = input("Subsurface Color");
2490   ShaderInput *normal_in = input("Normal");
2491   ShaderInput *clearcoat_normal_in = input("Clearcoat Normal");
2492   ShaderInput *tangent_in = input("Tangent");
2493
2494   float3 weight = make_float3(1.0f, 1.0f, 1.0f);
2495
2496   compiler.add_node(NODE_CLOSURE_SET_WEIGHT, weight);
2497
2498   int normal_offset = compiler.stack_assign_if_linked(normal_in);
2499   int clearcoat_normal_offset = compiler.stack_assign_if_linked(clearcoat_normal_in);
2500   int tangent_offset = compiler.stack_assign_if_linked(tangent_in);
2501   int specular_offset = compiler.stack_assign(p_specular);
2502   int roughness_offset = compiler.stack_assign(p_roughness);
2503   int specular_tint_offset = compiler.stack_assign(p_specular_tint);
2504   int anisotropic_offset = compiler.stack_assign(p_anisotropic);
2505   int sheen_offset = compiler.stack_assign(p_sheen);
2506   int sheen_tint_offset = compiler.stack_assign(p_sheen_tint);
2507   int clearcoat_offset = compiler.stack_assign(p_clearcoat);
2508   int clearcoat_roughness_offset = compiler.stack_assign(p_clearcoat_roughness);
2509   int ior_offset = compiler.stack_assign(p_ior);
2510   int transmission_offset = compiler.stack_assign(p_transmission);
2511   int transmission_roughness_offset = compiler.stack_assign(p_transmission_roughness);
2512   int anisotropic_rotation_offset = compiler.stack_assign(p_anisotropic_rotation);
2513   int subsurface_radius_offset = compiler.stack_assign(p_subsurface_radius);
2514
2515   compiler.add_node(NODE_CLOSURE_BSDF,
2516                     compiler.encode_uchar4(closure,
2517                                            compiler.stack_assign(p_metallic),
2518                                            compiler.stack_assign(p_subsurface),
2519                                            compiler.closure_mix_weight_offset()),
2520                     __float_as_int((p_metallic) ? get_float(p_metallic->socket_type) : 0.0f),
2521                     __float_as_int((p_subsurface) ? get_float(p_subsurface->socket_type) : 0.0f));
2522
2523   compiler.add_node(
2524       normal_offset,
2525       tangent_offset,
2526       compiler.encode_uchar4(
2527           specular_offset, roughness_offset, specular_tint_offset, anisotropic_offset),
2528       compiler.encode_uchar4(
2529           sheen_offset, sheen_tint_offset, clearcoat_offset, clearcoat_roughness_offset));
2530
2531   compiler.add_node(compiler.encode_uchar4(ior_offset,
2532                                            transmission_offset,
2533                                            anisotropic_rotation_offset,
2534                                            transmission_roughness_offset),
2535                     distribution,
2536                     subsurface_method,
2537                     SVM_STACK_INVALID);
2538
2539   float3 bc_default = get_float3(base_color_in->socket_type);
2540
2541   compiler.add_node(
2542       ((base_color_in->link) ? compiler.stack_assign(base_color_in) : SVM_STACK_INVALID),
2543       __float_as_int(bc_default.x),
2544       __float_as_int(bc_default.y),
2545       __float_as_int(bc_default.z));
2546
2547   compiler.add_node(
2548       clearcoat_normal_offset, subsurface_radius_offset, SVM_STACK_INVALID, SVM_STACK_INVALID);
2549
2550   float3 ss_default = get_float3(subsurface_color_in->socket_type);
2551
2552   compiler.add_node(((subsurface_color_in->link) ? compiler.stack_assign(subsurface_color_in) :
2553                                                    SVM_STACK_INVALID),
2554                     __float_as_int(ss_default.x),
2555                     __float_as_int(ss_default.y),
2556                     __float_as_int(ss_default.z));
2557 }
2558
2559 bool PrincipledBsdfNode::has_integrator_dependency()
2560 {
2561   ShaderInput *roughness_input = input("Roughness");
2562   return !roughness_input->link && roughness <= 1e-4f;
2563 }
2564
2565 void PrincipledBsdfNode::compile(SVMCompiler &compiler)
2566 {
2567   compile(compiler,
2568           input("Metallic"),
2569           input("Subsurface"),
2570           input("Subsurface Radius"),
2571           input("Specular"),
2572           input("Roughness"),
2573           input("Specular Tint"),
2574           input("Anisotropic"),
2575           input("Sheen"),
2576           input("Sheen Tint"),
2577           input("Clearcoat"),
2578           input("Clearcoat Roughness"),
2579           input("IOR"),
2580           input("Transmission"),
2581           input("Anisotropic Rotation"),
2582           input("Transmission Roughness"));
2583 }
2584
2585 void PrincipledBsdfNode::compile(OSLCompiler &compiler)
2586 {
2587   compiler.parameter(this, "distribution");
2588   compiler.parameter(this, "subsurface_method");
2589   compiler.add(this, "node_principled_bsdf");
2590 }
2591
2592 bool PrincipledBsdfNode::has_bssrdf_bump()
2593 {
2594   return has_surface_bssrdf() && has_bump();
2595 }
2596
2597 /* Translucent BSDF Closure */
2598
2599 NODE_DEFINE(TranslucentBsdfNode)
2600 {
2601   NodeType *type = NodeType::add("translucent_bsdf", create, NodeType::SHADER);
2602
2603   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2604   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
2605   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2606
2607   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
2608
2609   return type;
2610 }
2611
2612 TranslucentBsdfNode::TranslucentBsdfNode() : BsdfNode(node_type)
2613 {
2614   closure = CLOSURE_BSDF_TRANSLUCENT_ID;
2615 }
2616
2617 void TranslucentBsdfNode::compile(SVMCompiler &compiler)
2618 {
2619   BsdfNode::compile(compiler, NULL, NULL);
2620 }
2621
2622 void TranslucentBsdfNode::compile(OSLCompiler &compiler)
2623 {
2624   compiler.add(this, "node_translucent_bsdf");
2625 }
2626
2627 /* Transparent BSDF Closure */
2628
2629 NODE_DEFINE(TransparentBsdfNode)
2630 {
2631   NodeType *type = NodeType::add("transparent_bsdf", create, NodeType::SHADER);
2632
2633   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2634   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2635
2636   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
2637
2638   return type;
2639 }
2640
2641 TransparentBsdfNode::TransparentBsdfNode() : BsdfNode(node_type)
2642 {
2643   closure = CLOSURE_BSDF_TRANSPARENT_ID;
2644 }
2645
2646 void TransparentBsdfNode::compile(SVMCompiler &compiler)
2647 {
2648   BsdfNode::compile(compiler, NULL, NULL);
2649 }
2650
2651 void TransparentBsdfNode::compile(OSLCompiler &compiler)
2652 {
2653   compiler.add(this, "node_transparent_bsdf");
2654 }
2655
2656 /* Subsurface Scattering Closure */
2657
2658 NODE_DEFINE(SubsurfaceScatteringNode)
2659 {
2660   NodeType *type = NodeType::add("subsurface_scattering", create, NodeType::SHADER);
2661
2662   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2663   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
2664   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2665
2666   static NodeEnum falloff_enum;
2667   falloff_enum.insert("cubic", CLOSURE_BSSRDF_CUBIC_ID);
2668   falloff_enum.insert("gaussian", CLOSURE_BSSRDF_GAUSSIAN_ID);
2669   falloff_enum.insert("burley", CLOSURE_BSSRDF_BURLEY_ID);
2670   falloff_enum.insert("random_walk", CLOSURE_BSSRDF_RANDOM_WALK_ID);
2671   SOCKET_ENUM(falloff, "Falloff", falloff_enum, CLOSURE_BSSRDF_BURLEY_ID);
2672   SOCKET_IN_FLOAT(scale, "Scale", 0.01f);
2673   SOCKET_IN_VECTOR(radius, "Radius", make_float3(0.1f, 0.1f, 0.1f));
2674   SOCKET_IN_FLOAT(sharpness, "Sharpness", 0.0f);
2675   SOCKET_IN_FLOAT(texture_blur, "Texture Blur", 1.0f);
2676
2677   SOCKET_OUT_CLOSURE(BSSRDF, "BSSRDF");
2678
2679   return type;
2680 }
2681
2682 SubsurfaceScatteringNode::SubsurfaceScatteringNode() : BsdfNode(node_type)
2683 {
2684   closure = falloff;
2685 }
2686
2687 void SubsurfaceScatteringNode::compile(SVMCompiler &compiler)
2688 {
2689   closure = falloff;
2690   BsdfNode::compile(
2691       compiler, input("Scale"), input("Texture Blur"), input("Radius"), input("Sharpness"));
2692 }
2693
2694 void SubsurfaceScatteringNode::compile(OSLCompiler &compiler)
2695 {
2696   closure = falloff;
2697   compiler.parameter(this, "falloff");
2698   compiler.add(this, "node_subsurface_scattering");
2699 }
2700
2701 bool SubsurfaceScatteringNode::has_bssrdf_bump()
2702 {
2703   /* detect if anything is plugged into the normal input besides the default */
2704   ShaderInput *normal_in = input("Normal");
2705   return (normal_in->link &&
2706           normal_in->link->parent->special_type != SHADER_SPECIAL_TYPE_GEOMETRY);
2707 }
2708
2709 /* Emissive Closure */
2710
2711 NODE_DEFINE(EmissionNode)
2712 {
2713   NodeType *type = NodeType::add("emission", create, NodeType::SHADER);
2714
2715   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2716   SOCKET_IN_FLOAT(strength, "Strength", 10.0f);
2717   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2718
2719   SOCKET_OUT_CLOSURE(emission, "Emission");
2720
2721   return type;
2722 }
2723
2724 EmissionNode::EmissionNode() : ShaderNode(node_type)
2725 {
2726 }
2727
2728 void EmissionNode::compile(SVMCompiler &compiler)
2729 {
2730   ShaderInput *color_in = input("Color");
2731   ShaderInput *strength_in = input("Strength");
2732
2733   if (color_in->link || strength_in->link) {
2734     compiler.add_node(
2735         NODE_EMISSION_WEIGHT, compiler.stack_assign(color_in), compiler.stack_assign(strength_in));
2736   }
2737   else
2738     compiler.add_node(NODE_CLOSURE_SET_WEIGHT, color * strength);
2739
2740   compiler.add_node(NODE_CLOSURE_EMISSION, compiler.closure_mix_weight_offset());
2741 }
2742
2743 void EmissionNode::compile(OSLCompiler &compiler)
2744 {
2745   compiler.add(this, "node_emission");
2746 }
2747
2748 void EmissionNode::constant_fold(const ConstantFolder &folder)
2749 {
2750   ShaderInput *color_in = input("Color");
2751   ShaderInput *strength_in = input("Strength");
2752
2753   if ((!color_in->link && color == make_float3(0.0f, 0.0f, 0.0f)) ||
2754       (!strength_in->link && strength == 0.0f)) {
2755     folder.discard();
2756   }
2757 }
2758
2759 /* Background Closure */
2760
2761 NODE_DEFINE(BackgroundNode)
2762 {
2763   NodeType *type = NodeType::add("background_shader", create, NodeType::SHADER);
2764
2765   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2766   SOCKET_IN_FLOAT(strength, "Strength", 1.0f);
2767   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2768
2769   SOCKET_OUT_CLOSURE(background, "Background");
2770
2771   return type;
2772 }
2773
2774 BackgroundNode::BackgroundNode() : ShaderNode(node_type)
2775 {
2776 }
2777
2778 void BackgroundNode::compile(SVMCompiler &compiler)
2779 {
2780   ShaderInput *color_in = input("Color");
2781   ShaderInput *strength_in = input("Strength");
2782
2783   if (color_in->link || strength_in->link) {
2784     compiler.add_node(
2785         NODE_EMISSION_WEIGHT, compiler.stack_assign(color_in), compiler.stack_assign(strength_in));
2786   }
2787   else
2788     compiler.add_node(NODE_CLOSURE_SET_WEIGHT, color * strength);
2789
2790   compiler.add_node(NODE_CLOSURE_BACKGROUND, compiler.closure_mix_weight_offset());
2791 }
2792
2793 void BackgroundNode::compile(OSLCompiler &compiler)
2794 {
2795   compiler.add(this, "node_background");
2796 }
2797
2798 void BackgroundNode::constant_fold(const ConstantFolder &folder)
2799 {
2800   ShaderInput *color_in = input("Color");
2801   ShaderInput *strength_in = input("Strength");
2802
2803   if ((!color_in->link && color == make_float3(0.0f, 0.0f, 0.0f)) ||
2804       (!strength_in->link && strength == 0.0f)) {
2805     folder.discard();
2806   }
2807 }
2808
2809 /* Holdout Closure */
2810
2811 NODE_DEFINE(HoldoutNode)
2812 {
2813   NodeType *type = NodeType::add("holdout", create, NodeType::SHADER);
2814
2815   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2816   SOCKET_IN_FLOAT(volume_mix_weight, "VolumeMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2817
2818   SOCKET_OUT_CLOSURE(holdout, "Holdout");
2819
2820   return type;
2821 }
2822
2823 HoldoutNode::HoldoutNode() : ShaderNode(node_type)
2824 {
2825 }
2826
2827 void HoldoutNode::compile(SVMCompiler &compiler)
2828 {
2829   float3 value = make_float3(1.0f, 1.0f, 1.0f);
2830
2831   compiler.add_node(NODE_CLOSURE_SET_WEIGHT, value);
2832   compiler.add_node(NODE_CLOSURE_HOLDOUT, compiler.closure_mix_weight_offset());
2833 }
2834
2835 void HoldoutNode::compile(OSLCompiler &compiler)
2836 {
2837   compiler.add(this, "node_holdout");
2838 }
2839
2840 /* Ambient Occlusion */
2841
2842 NODE_DEFINE(AmbientOcclusionNode)
2843 {
2844   NodeType *type = NodeType::add("ambient_occlusion", create, NodeType::SHADER);
2845
2846   SOCKET_INT(samples, "Samples", 16);
2847
2848   SOCKET_IN_COLOR(color, "Color", make_float3(1.0f, 1.0f, 1.0f));
2849   SOCKET_IN_FLOAT(distance, "Distance", 1.0f);
2850   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
2851
2852   SOCKET_BOOLEAN(inside, "Inside", false);
2853   SOCKET_BOOLEAN(only_local, "Only Local", false);
2854
2855   SOCKET_OUT_COLOR(color, "Color");
2856   SOCKET_OUT_FLOAT(ao, "AO");
2857
2858   return type;
2859 }
2860
2861 AmbientOcclusionNode::AmbientOcclusionNode() : ShaderNode(node_type)
2862 {
2863 }
2864
2865 void AmbientOcclusionNode::compile(SVMCompiler &compiler)
2866 {
2867   ShaderInput *color_in = input("Color");
2868   ShaderInput *distance_in = input("Distance");
2869   ShaderInput *normal_in = input("Normal");
2870   ShaderOutput *color_out = output("Color");
2871   ShaderOutput *ao_out = output("AO");
2872
2873   int flags = (inside ? NODE_AO_INSIDE : 0) | (only_local ? NODE_AO_ONLY_LOCAL : 0);
2874
2875   if (!distance_in->link && distance == 0.0f) {
2876     flags |= NODE_AO_GLOBAL_RADIUS;
2877   }
2878
2879   compiler.add_node(NODE_AMBIENT_OCCLUSION,
2880                     compiler.encode_uchar4(flags,
2881                                            compiler.stack_assign_if_linked(distance_in),
2882                                            compiler.stack_assign_if_linked(normal_in),
2883                                            compiler.stack_assign(ao_out)),
2884                     compiler.encode_uchar4(compiler.stack_assign(color_in),
2885                                            compiler.stack_assign(color_out),
2886                                            samples),
2887                     __float_as_uint(distance));
2888 }
2889
2890 void AmbientOcclusionNode::compile(OSLCompiler &compiler)
2891 {
2892   compiler.parameter(this, "samples");
2893   compiler.parameter(this, "inside");
2894   compiler.parameter(this, "only_local");
2895   compiler.add(this, "node_ambient_occlusion");
2896 }
2897
2898 /* Volume Closure */
2899
2900 VolumeNode::VolumeNode(const NodeType *node_type) : ShaderNode(node_type)
2901 {
2902   closure = CLOSURE_VOLUME_HENYEY_GREENSTEIN_ID;
2903 }
2904
2905 void VolumeNode::compile(SVMCompiler &compiler, ShaderInput *param1, ShaderInput *param2)
2906 {
2907   ShaderInput *color_in = input("Color");
2908
2909   if (color_in->link)
2910     compiler.add_node(NODE_CLOSURE_WEIGHT, compiler.stack_assign(color_in));
2911   else
2912     compiler.add_node(NODE_CLOSURE_SET_WEIGHT, color);
2913
2914   compiler.add_node(
2915       NODE_CLOSURE_VOLUME,
2916       compiler.encode_uchar4(closure,
2917                              (param1) ? compiler.stack_assign(param1) : SVM_STACK_INVALID,
2918                              (param2) ? compiler.stack_assign(param2) : SVM_STACK_INVALID,
2919                              compiler.closure_mix_weight_offset()),
2920       __float_as_int((param1) ? get_float(param1->socket_type) : 0.0f),
2921       __float_as_int((param2) ? get_float(param2->socket_type) : 0.0f));
2922 }
2923
2924 void VolumeNode::compile(SVMCompiler &compiler)
2925 {
2926   compile(compiler, NULL, NULL);
2927 }
2928
2929 void VolumeNode::compile(OSLCompiler & /*compiler*/)
2930 {
2931   assert(0);
2932 }
2933
2934 /* Absorption Volume Closure */
2935
2936 NODE_DEFINE(AbsorptionVolumeNode)
2937 {
2938   NodeType *type = NodeType::add("absorption_volume", create, NodeType::SHADER);
2939
2940   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2941   SOCKET_IN_FLOAT(density, "Density", 1.0f);
2942   SOCKET_IN_FLOAT(volume_mix_weight, "VolumeMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2943
2944   SOCKET_OUT_CLOSURE(volume, "Volume");
2945
2946   return type;
2947 }
2948
2949 AbsorptionVolumeNode::AbsorptionVolumeNode() : VolumeNode(node_type)
2950 {
2951   closure = CLOSURE_VOLUME_ABSORPTION_ID;
2952 }
2953
2954 void AbsorptionVolumeNode::compile(SVMCompiler &compiler)
2955 {
2956   VolumeNode::compile(compiler, input("Density"), NULL);
2957 }
2958
2959 void AbsorptionVolumeNode::compile(OSLCompiler &compiler)
2960 {
2961   compiler.add(this, "node_absorption_volume");
2962 }
2963
2964 /* Scatter Volume Closure */
2965
2966 NODE_DEFINE(ScatterVolumeNode)
2967 {
2968   NodeType *type = NodeType::add("scatter_volume", create, NodeType::SHADER);
2969
2970   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
2971   SOCKET_IN_FLOAT(density, "Density", 1.0f);
2972   SOCKET_IN_FLOAT(anisotropy, "Anisotropy", 0.0f);
2973   SOCKET_IN_FLOAT(volume_mix_weight, "VolumeMixWeight", 0.0f, SocketType::SVM_INTERNAL);
2974
2975   SOCKET_OUT_CLOSURE(volume, "Volume");
2976
2977   return type;
2978 }
2979
2980 ScatterVolumeNode::ScatterVolumeNode() : VolumeNode(node_type)
2981 {
2982   closure = CLOSURE_VOLUME_HENYEY_GREENSTEIN_ID;
2983 }
2984
2985 void ScatterVolumeNode::compile(SVMCompiler &compiler)
2986 {
2987   VolumeNode::compile(compiler, input("Density"), input("Anisotropy"));
2988 }
2989
2990 void ScatterVolumeNode::compile(OSLCompiler &compiler)
2991 {
2992   compiler.add(this, "node_scatter_volume");
2993 }
2994
2995 /* Principled Volume Closure */
2996
2997 NODE_DEFINE(PrincipledVolumeNode)
2998 {
2999   NodeType *type = NodeType::add("principled_volume", create, NodeType::SHADER);
3000
3001   SOCKET_IN_STRING(density_attribute, "Density Attribute", ustring());
3002   SOCKET_IN_STRING(color_attribute, "Color Attribute", ustring());
3003   SOCKET_IN_STRING(temperature_attribute, "Temperature Attribute", ustring());
3004
3005   SOCKET_IN_COLOR(color, "Color", make_float3(0.5f, 0.5f, 0.5f));
3006   SOCKET_IN_FLOAT(density, "Density", 1.0f);
3007   SOCKET_IN_FLOAT(anisotropy, "Anisotropy", 0.0f);
3008   SOCKET_IN_COLOR(absorption_color, "Absorption Color", make_float3(0.0f, 0.0f, 0.0f));
3009   SOCKET_IN_FLOAT(emission_strength, "Emission Strength", 0.0f);
3010   SOCKET_IN_COLOR(emission_color, "Emission Color", make_float3(1.0f, 1.0f, 1.0f));
3011   SOCKET_IN_FLOAT(blackbody_intensity, "Blackbody Intensity", 0.0f);
3012   SOCKET_IN_COLOR(blackbody_tint, "Blackbody Tint", make_float3(1.0f, 1.0f, 1.0f));
3013   SOCKET_IN_FLOAT(temperature, "Temperature", 1500.0f);
3014   SOCKET_IN_FLOAT(volume_mix_weight, "VolumeMixWeight", 0.0f, SocketType::SVM_INTERNAL);
3015
3016   SOCKET_OUT_CLOSURE(volume, "Volume");
3017
3018   return type;
3019 }
3020
3021 PrincipledVolumeNode::PrincipledVolumeNode() : VolumeNode(node_type)
3022 {
3023   closure = CLOSURE_VOLUME_HENYEY_GREENSTEIN_ID;
3024 }
3025
3026 void PrincipledVolumeNode::attributes(Shader *shader, AttributeRequestSet *attributes)
3027 {
3028   if (shader->has_volume) {
3029     ShaderInput *density_in = input("Density");
3030     ShaderInput *blackbody_in = input("Blackbody Intensity");
3031
3032     if (density_in->link || density > 0.0f) {
3033       attributes->add_standard(density_attribute);
3034       attributes->add_standard(color_attribute);
3035     }
3036
3037     if (blackbody_in->link || blackbody_intensity > 0.0f) {
3038       attributes->add_standard(temperature_attribute);
3039     }
3040
3041     attributes->add(ATTR_STD_GENERATED_TRANSFORM);
3042   }
3043
3044   ShaderNode::attributes(shader, attributes);
3045 }
3046
3047 void PrincipledVolumeNode::compile(SVMCompiler &compiler)
3048 {
3049   ShaderInput *color_in = input("Color");
3050   ShaderInput *density_in = input("Density");
3051   ShaderInput *anisotropy_in = input("Anisotropy");
3052   ShaderInput *absorption_color_in = input("Absorption Color");
3053   ShaderInput *emission_in = input("Emission Strength");
3054   ShaderInput *emission_color_in = input("Emission Color");
3055   ShaderInput *blackbody_in = input("Blackbody Intensity");
3056   ShaderInput *blackbody_tint_in = input("Blackbody Tint");
3057   ShaderInput *temperature_in = input("Temperature");
3058
3059   if (color_in->link)
3060     compiler.add_node(NODE_CLOSURE_WEIGHT, compiler.stack_assign(color_in));
3061   else
3062     compiler.add_node(NODE_CLOSURE_SET_WEIGHT, color);
3063
3064   compiler.add_node(NODE_PRINCIPLED_VOLUME,
3065                     compiler.encode_uchar4(compiler.stack_assign_if_linked(density_in),
3066                                            compiler.stack_assign_if_linked(anisotropy_in),
3067                                            compiler.stack_assign(absorption_color_in),
3068                                            compiler.closure_mix_weight_offset()),
3069                     compiler.encode_uchar4(compiler.stack_assign_if_linked(emission_in),
3070                                            compiler.stack_assign(emission_color_in),
3071                                            compiler.stack_assign_if_linked(blackbody_in),
3072                                            compiler.stack_assign(temperature_in)),
3073                     compiler.stack_assign(blackbody_tint_in));
3074
3075   int attr_density = compiler.attribute_standard(density_attribute);
3076   int attr_color = compiler.attribute_standard(color_attribute);
3077   int attr_temperature = compiler.attribute_standard(temperature_attribute);
3078
3079   compiler.add_node(__float_as_int(density),
3080                     __float_as_int(anisotropy),
3081                     __float_as_int(emission_strength),
3082                     __float_as_int(blackbody_intensity));
3083
3084   compiler.add_node(attr_density, attr_color, attr_temperature);
3085 }
3086
3087 void PrincipledVolumeNode::compile(OSLCompiler &compiler)
3088 {
3089   if (Attribute::name_standard(density_attribute.c_str())) {
3090     density_attribute = ustring("geom:" + density_attribute.string());
3091   }
3092   if (Attribute::name_standard(color_attribute.c_str())) {
3093     color_attribute = ustring("geom:" + color_attribute.string());
3094   }
3095   if (Attribute::name_standard(temperature_attribute.c_str())) {
3096     temperature_attribute = ustring("geom:" + temperature_attribute.string());
3097   }
3098
3099   compiler.add(this, "node_principled_volume");
3100 }
3101
3102 /* Principled Hair BSDF Closure */
3103
3104 NODE_DEFINE(PrincipledHairBsdfNode)
3105 {
3106   NodeType *type = NodeType::add("principled_hair_bsdf", create, NodeType::SHADER);
3107
3108   /* Color parametrization specified as enum. */
3109   static NodeEnum parametrization_enum;
3110   parametrization_enum.insert("Direct coloring", NODE_PRINCIPLED_HAIR_REFLECTANCE);
3111   parametrization_enum.insert("Melanin concentration", NODE_PRINCIPLED_HAIR_PIGMENT_CONCENTRATION);
3112   parametrization_enum.insert("Absorption coefficient", NODE_PRINCIPLED_HAIR_DIRECT_ABSORPTION);
3113   SOCKET_ENUM(
3114       parametrization, "Parametrization", parametrization_enum, NODE_PRINCIPLED_HAIR_REFLECTANCE);
3115
3116   /* Initialize sockets to their default values. */
3117   SOCKET_IN_COLOR(color, "Color", make_float3(0.017513f, 0.005763f, 0.002059f));
3118   SOCKET_IN_FLOAT(melanin, "Melanin", 0.8f);
3119   SOCKET_IN_FLOAT(melanin_redness, "Melanin Redness", 1.0f);
3120   SOCKET_IN_COLOR(tint, "Tint", make_float3(1.f, 1.f, 1.f));
3121   SOCKET_IN_VECTOR(absorption_coefficient,
3122                    "Absorption Coefficient",
3123                    make_float3(0.245531f, 0.52f, 1.365f),
3124                    SocketType::VECTOR);
3125
3126   SOCKET_IN_FLOAT(offset, "Offset", 2.f * M_PI_F / 180.f);
3127   SOCKET_IN_FLOAT(roughness, "Roughness", 0.3f);
3128   SOCKET_IN_FLOAT(radial_roughness, "Radial Roughness", 0.3f);
3129   SOCKET_IN_FLOAT(coat, "Coat", 0.0f);
3130   SOCKET_IN_FLOAT(ior, "IOR", 1.55f);
3131
3132   SOCKET_IN_FLOAT(random_roughness, "Random Roughness", 0.0f);
3133   SOCKET_IN_FLOAT(random_color, "Random Color", 0.0f);
3134   SOCKET_IN_FLOAT(random, "Random", 0.0f);
3135
3136   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
3137   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
3138
3139   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
3140
3141   return type;
3142 }
3143
3144 PrincipledHairBsdfNode::PrincipledHairBsdfNode() : BsdfBaseNode(node_type)
3145 {
3146   closure = CLOSURE_BSDF_HAIR_PRINCIPLED_ID;
3147 }
3148
3149 /* Enable retrieving Hair Info -> Random if Random isn't linked. */
3150 void PrincipledHairBsdfNode::attributes(Shader *shader, AttributeRequestSet *attributes)
3151 {
3152   if (!input("Random")->link) {
3153     attributes->add(ATTR_STD_CURVE_RANDOM);
3154   }
3155   ShaderNode::attributes(shader, attributes);
3156 }
3157
3158 /* Prepares the input data for the SVM shader. */
3159 void PrincipledHairBsdfNode::compile(SVMCompiler &compiler)
3160 {
3161   compiler.add_node(NODE_CLOSURE_SET_WEIGHT, make_float3(1.0f, 1.0f, 1.0f));
3162
3163   ShaderInput *roughness_in = input("Roughness");
3164   ShaderInput *radial_roughness_in = input("Radial Roughness");
3165   ShaderInput *random_roughness_in = input("Random Roughness");
3166   ShaderInput *offset_in = input("Offset");
3167   ShaderInput *coat_in = input("Coat");
3168   ShaderInput *ior_in = input("IOR");
3169   ShaderInput *melanin_in = input("Melanin");
3170   ShaderInput *melanin_redness_in = input("Melanin Redness");
3171   ShaderInput *random_color_in = input("Random Color");
3172
3173   int color_ofs = compiler.stack_assign(input("Color"));
3174   int tint_ofs = compiler.stack_assign(input("Tint"));
3175   int absorption_coefficient_ofs = compiler.stack_assign(input("Absorption Coefficient"));
3176
3177   ShaderInput *random_in = input("Random");
3178   int attr_random = random_in->link ? SVM_STACK_INVALID :
3179                                       compiler.attribute(ATTR_STD_CURVE_RANDOM);
3180
3181   /* Encode all parameters into data nodes. */
3182   compiler.add_node(NODE_CLOSURE_BSDF,
3183                     /* Socket IDs can be packed 4 at a time into a single data packet */
3184                     compiler.encode_uchar4(closure,
3185                                            compiler.stack_assign_if_linked(roughness_in),
3186                                            compiler.stack_assign_if_linked(radial_roughness_in),
3187                                            compiler.closure_mix_weight_offset()),
3188                     /* The rest are stored as unsigned integers */
3189                     __float_as_uint(roughness),
3190                     __float_as_uint(radial_roughness));
3191
3192   compiler.add_node(compiler.stack_assign_if_linked(input("Normal")),
3193                     compiler.encode_uchar4(compiler.stack_assign_if_linked(offset_in),
3194                                            compiler.stack_assign_if_linked(ior_in),
3195                                            color_ofs,
3196                                            parametrization),
3197                     __float_as_uint(offset),
3198                     __float_as_uint(ior));
3199
3200   compiler.add_node(compiler.encode_uchar4(compiler.stack_assign_if_linked(coat_in),
3201                                            compiler.stack_assign_if_linked(melanin_in),
3202                                            compiler.stack_assign_if_linked(melanin_redness_in),
3203                                            absorption_coefficient_ofs),
3204                     __float_as_uint(coat),
3205                     __float_as_uint(melanin),
3206                     __float_as_uint(melanin_redness));
3207
3208   compiler.add_node(compiler.encode_uchar4(tint_ofs,
3209                                            compiler.stack_assign_if_linked(random_in),
3210                                            compiler.stack_assign_if_linked(random_color_in),
3211                                            compiler.stack_assign_if_linked(random_roughness_in)),
3212                     __float_as_uint(random),
3213                     __float_as_uint(random_color),
3214                     __float_as_uint(random_roughness));
3215
3216   compiler.add_node(
3217       compiler.encode_uchar4(
3218           SVM_STACK_INVALID, SVM_STACK_INVALID, SVM_STACK_INVALID, SVM_STACK_INVALID),
3219       attr_random,
3220       SVM_STACK_INVALID,
3221       SVM_STACK_INVALID);
3222 }
3223
3224 /* Prepares the input data for the OSL shader. */
3225 void PrincipledHairBsdfNode::compile(OSLCompiler &compiler)
3226 {
3227   compiler.parameter(this, "parametrization");
3228   compiler.add(this, "node_principled_hair_bsdf");
3229 }
3230
3231 /* Hair BSDF Closure */
3232
3233 NODE_DEFINE(HairBsdfNode)
3234 {
3235   NodeType *type = NodeType::add("hair_bsdf", create, NodeType::SHADER);
3236
3237   SOCKET_IN_COLOR(color, "Color", make_float3(0.8f, 0.8f, 0.8f));
3238   SOCKET_IN_NORMAL(normal, "Normal", make_float3(0.0f, 0.0f, 0.0f), SocketType::LINK_NORMAL);
3239   SOCKET_IN_FLOAT(surface_mix_weight, "SurfaceMixWeight", 0.0f, SocketType::SVM_INTERNAL);
3240
3241   static NodeEnum component_enum;
3242   component_enum.insert("reflection", CLOSURE_BSDF_HAIR_REFLECTION_ID);
3243   component_enum.insert("transmission", CLOSURE_BSDF_HAIR_TRANSMISSION_ID);
3244   SOCKET_ENUM(component, "Component", component_enum, CLOSURE_BSDF_HAIR_REFLECTION_ID);
3245   SOCKET_IN_FLOAT(offset, "Offset", 0.0f);
3246   SOCKET_IN_FLOAT(roughness_u, "RoughnessU", 0.2f);
3247   SOCKET_IN_FLOAT(roughness_v, "RoughnessV", 0.2f);
3248   SOCKET_IN_VECTOR(tangent, "Tangent", make_float3(0.0f, 0.0f, 0.0f));
3249
3250   SOCKET_OUT_CLOSURE(BSDF, "BSDF");
3251
3252   return type;
3253 }
3254
3255 HairBsdfNode::HairBsdfNode() : BsdfNode(node_type)
3256 {
3257   closure = CLOSURE_BSDF_HAIR_REFLECTION_ID;
3258 }
3259
3260 void HairBsdfNode::compile(SVMCompiler &compiler)
3261 {
3262   closure = component;
3263
3264   BsdfNode::compile(compiler, input("RoughnessU"), input("RoughnessV"), input("Offset"));
3265 }
3266
3267 void HairBsdfNode::compile(OSLCompiler &compiler)
3268 {
3269   compiler.parameter(this, "component");
3270   compiler.add(this, "node_hair_bsdf");
3271 }
3272
3273 /* Geometry */
3274
3275 NODE_DEFINE(GeometryNode)
3276 {
3277   NodeType *type = NodeType::add("geometry", create, NodeType::SHADER);
3278
3279   SOCKET_IN_NORMAL(normal_osl,
3280                    "NormalIn",
3281                    make_float3(0.0f, 0.0f, 0.0f),
3282                    SocketType::LINK_NORMAL | SocketType::OSL_INTERNAL);
3283
3284   SOCKET_OUT_POINT(position, "Position");
3285   SOCKET_OUT_NORMAL(normal, "Normal");
3286   SOCKET_OUT_NORMAL(tangent, "Tangent");
3287   SOCKET_OUT_NORMAL(true_normal, "True Normal");
3288   SOCKET_OUT_VECTOR(incoming, "Incoming");
3289   SOCKET_OUT_POINT(parametric, "Parametric");
3290   SOCKET_OUT_FLOAT(backfacing, "Backfacing");
3291   SOCKET_OUT_FLOAT(pointiness, "Pointiness");
3292
3293   return type;
3294 }
3295
3296 GeometryNode::GeometryNode() : ShaderNode(node_type)
3297 {
3298   special_type = SHADER_SPECIAL_TYPE_GEOMETRY;
3299 }
3300
3301 void GeometryNode::attributes(Shader *shader, AttributeRequestSet *attributes)
3302 {
3303   if (shader->has_surface) {
3304     if (!output("Tangent")->links.empty()) {
3305       attributes->add(ATTR_STD_GENERATED);
3306     }
3307     if (!output("Pointiness")->links.empty()) {
3308       attributes->add(ATTR_STD_POINTINESS);
3309     }
3310   }
3311
3312   ShaderNode::attributes(shader, attributes);
3313 }
3314
3315 void GeometryNode::compile(SVMCompiler &compiler)
3316 {
3317   ShaderOutput *out;
3318   ShaderNodeType geom_node = NODE_GEOMETRY;
3319   ShaderNodeType attr_node = NODE_ATTR;
3320
3321   if (bump == SHADER_BUMP_DX) {
3322     geom_node = NODE_GEOMETRY_BUMP_DX;
3323     attr_node = NODE_ATTR_BUMP_DX;
3324   }
3325   else if (bump == SHADER_BUMP_DY) {
3326     geom_node = NODE_GEOMETRY_BUMP_DY;
3327     attr_node = NODE_ATTR_BUMP_DY;
3328   }
3329
3330   out = output("Position");
3331   if (!out->links.empty()) {
3332     compiler.add_node(geom_node, NODE_GEOM_P, compiler.stack_assign(out));
3333   }
3334
3335   out = output("Normal");
3336   if (!out->links.empty()) {
3337     compiler.add_node(geom_node, NODE_GEOM_N, compiler.stack_assign(out));
3338   }
3339
3340   out = output("Tangent");
3341   if (!out->links.empty()) {
3342     compiler.add_node(geom_node, NODE_GEOM_T, compiler.stack_assign(out));
3343   }
3344
3345   out = output("True Normal");
3346   if (!out->links.empty()) {
3347     compiler.add_node(geom_node, NODE_GEOM_Ng, compiler.stack_assign(out));
3348   }
3349
3350   out = output("Incoming");
3351   if (!out->links.empty()) {
3352     compiler.add_node(geom_node, NODE_GEOM_I, compiler.stack_assign(out));
3353   }
3354
3355   out = output("Parametric");
3356   if (!out->links.empty()) {
3357     compiler.add_node(geom_node, NODE_GEOM_uv, compiler.stack_assign(out));
3358   }
3359
3360   out = output("Backfacing");
3361   if (!out->links.empty()) {
3362     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_backfacing, compiler.stack_assign(out));
3363   }
3364
3365   out = output("Pointiness");
3366   if (!out->links.empty()) {
3367     if (compiler.output_type() != SHADER_TYPE_VOLUME) {
3368       compiler.add_node(
3369           attr_node, ATTR_STD_POINTINESS, compiler.stack_assign(out), NODE_ATTR_FLOAT);
3370     }
3371     else {
3372       compiler.add_node(NODE_VALUE_F, __float_as_int(0.0f), compiler.stack_assign(out));
3373     }
3374   }
3375 }
3376
3377 void GeometryNode::compile(OSLCompiler &compiler)
3378 {
3379   if (bump == SHADER_BUMP_DX)
3380     compiler.parameter("bump_offset", "dx");
3381   else if (bump == SHADER_BUMP_DY)
3382     compiler.parameter("bump_offset", "dy");
3383   else
3384     compiler.parameter("bump_offset", "center");
3385
3386   compiler.add(this, "node_geometry");
3387 }
3388
3389 int GeometryNode::get_group()
3390 {
3391   ShaderOutput *out;
3392   int result = ShaderNode::get_group();
3393
3394   /* Backfacing uses NODE_LIGHT_PATH */
3395   out = output("Backfacing");
3396   if (!out->links.empty()) {
3397     result = max(result, NODE_GROUP_LEVEL_1);
3398   }
3399
3400   return result;
3401 }
3402
3403 /* TextureCoordinate */
3404
3405 NODE_DEFINE(TextureCoordinateNode)
3406 {
3407   NodeType *type = NodeType::add("texture_coordinate", create, NodeType::SHADER);
3408
3409   SOCKET_BOOLEAN(from_dupli, "From Dupli", false);
3410   SOCKET_BOOLEAN(use_transform, "Use Transform", false);
3411   SOCKET_TRANSFORM(ob_tfm, "Object Transform", transform_identity());
3412
3413   SOCKET_IN_NORMAL(normal_osl,
3414                    "NormalIn",
3415                    make_float3(0.0f, 0.0f, 0.0f),
3416                    SocketType::LINK_NORMAL | SocketType::OSL_INTERNAL);
3417
3418   SOCKET_OUT_POINT(generated, "Generated");
3419   SOCKET_OUT_NORMAL(normal, "Normal");
3420   SOCKET_OUT_POINT(UV, "UV");
3421   SOCKET_OUT_POINT(object, "Object");
3422   SOCKET_OUT_POINT(camera, "Camera");
3423   SOCKET_OUT_POINT(window, "Window");
3424   SOCKET_OUT_NORMAL(reflection, "Reflection");
3425
3426   return type;
3427 }
3428
3429 TextureCoordinateNode::TextureCoordinateNode() : ShaderNode(node_type)
3430 {
3431 }
3432
3433 void TextureCoordinateNode::attributes(Shader *shader, AttributeRequestSet *attributes)
3434 {
3435   if (shader->has_surface) {
3436     if (!from_dupli) {
3437       if (!output("Generated")->links.empty())
3438         attributes->add(ATTR_STD_GENERATED);
3439       if (!output("UV")->links.empty())
3440         attributes->add(ATTR_STD_UV);
3441     }
3442   }
3443
3444   if (shader->has_volume) {
3445     if (!from_dupli) {
3446       if (!output("Generated")->links.empty()) {
3447         attributes->add(ATTR_STD_GENERATED_TRANSFORM);
3448       }
3449     }
3450   }
3451
3452   ShaderNode::attributes(shader, attributes);
3453 }
3454
3455 void TextureCoordinateNode::compile(SVMCompiler &compiler)
3456 {
3457   ShaderOutput *out;
3458   ShaderNodeType texco_node = NODE_TEX_COORD;
3459   ShaderNodeType attr_node = NODE_ATTR;
3460   ShaderNodeType geom_node = NODE_GEOMETRY;
3461
3462   if (bump == SHADER_BUMP_DX) {
3463     texco_node = NODE_TEX_COORD_BUMP_DX;
3464     attr_node = NODE_ATTR_BUMP_DX;
3465     geom_node = NODE_GEOMETRY_BUMP_DX;
3466   }
3467   else if (bump == SHADER_BUMP_DY) {
3468     texco_node = NODE_TEX_COORD_BUMP_DY;
3469     attr_node = NODE_ATTR_BUMP_DY;
3470     geom_node = NODE_GEOMETRY_BUMP_DY;
3471   }
3472
3473   out = output("Generated");
3474   if (!out->links.empty()) {
3475     if (compiler.background) {
3476       compiler.add_node(geom_node, NODE_GEOM_P, compiler.stack_assign(out));
3477     }
3478     else {
3479       if (from_dupli) {
3480         compiler.add_node(texco_node, NODE_TEXCO_DUPLI_GENERATED, compiler.stack_assign(out));
3481       }
3482       else if (compiler.output_type() == SHADER_TYPE_VOLUME) {
3483         compiler.add_node(texco_node, NODE_TEXCO_VOLUME_GENERATED, compiler.stack_assign(out));
3484       }
3485       else {
3486         int attr = compiler.attribute(ATTR_STD_GENERATED);
3487         compiler.add_node(attr_node, attr, compiler.stack_assign(out), NODE_ATTR_FLOAT3);
3488       }
3489     }
3490   }
3491
3492   out = output("Normal");
3493   if (!out->links.empty()) {
3494     compiler.add_node(texco_node, NODE_TEXCO_NORMAL, compiler.stack_assign(out));
3495   }
3496
3497   out = output("UV");
3498   if (!out->links.empty()) {
3499     if (from_dupli) {
3500       compiler.add_node(texco_node, NODE_TEXCO_DUPLI_UV, compiler.stack_assign(out));
3501     }
3502     else {
3503       int attr = compiler.attribute(ATTR_STD_UV);
3504       compiler.add_node(attr_node, attr, compiler.stack_assign(out), NODE_ATTR_FLOAT3);
3505     }
3506   }
3507
3508   out = output("Object");
3509   if (!out->links.empty()) {
3510     compiler.add_node(texco_node, NODE_TEXCO_OBJECT, compiler.stack_assign(out), use_transform);
3511     if (use_transform) {
3512       Transform ob_itfm = transform_inverse(ob_tfm);
3513       compiler.add_node(ob_itfm.x);
3514       compiler.add_node(ob_itfm.y);
3515       compiler.add_node(ob_itfm.z);
3516     }
3517   }
3518
3519   out = output("Camera");
3520   if (!out->links.empty()) {
3521     compiler.add_node(texco_node, NODE_TEXCO_CAMERA, compiler.stack_assign(out));
3522   }
3523
3524   out = output("Window");
3525   if (!out->links.empty()) {
3526     compiler.add_node(texco_node, NODE_TEXCO_WINDOW, compiler.stack_assign(out));
3527   }
3528
3529   out = output("Reflection");
3530   if (!out->links.empty()) {
3531     if (compiler.background) {
3532       compiler.add_node(geom_node, NODE_GEOM_I, compiler.stack_assign(out));
3533     }
3534     else {
3535       compiler.add_node(texco_node, NODE_TEXCO_REFLECTION, compiler.stack_assign(out));
3536     }
3537   }
3538 }
3539
3540 void TextureCoordinateNode::compile(OSLCompiler &compiler)
3541 {
3542   if (bump == SHADER_BUMP_DX)
3543     compiler.parameter("bump_offset", "dx");
3544   else if (bump == SHADER_BUMP_DY)
3545     compiler.parameter("bump_offset", "dy");
3546   else
3547     compiler.parameter("bump_offset", "center");
3548
3549   if (compiler.background)
3550     compiler.parameter("is_background", true);
3551   if (compiler.output_type() == SHADER_TYPE_VOLUME)
3552     compiler.parameter("is_volume", true);
3553   compiler.parameter(this, "use_transform");
3554   Transform ob_itfm = transform_inverse(ob_tfm);
3555   compiler.parameter("object_itfm", ob_itfm);
3556
3557   compiler.parameter(this, "from_dupli");
3558
3559   compiler.add(this, "node_texture_coordinate");
3560 }
3561
3562 /* UV Map */
3563
3564 NODE_DEFINE(UVMapNode)
3565 {
3566   NodeType *type = NodeType::add("uvmap", create, NodeType::SHADER);
3567
3568   SOCKET_STRING(attribute, "attribute", ustring());
3569   SOCKET_IN_BOOLEAN(from_dupli, "from dupli", false);
3570
3571   SOCKET_OUT_POINT(UV, "UV");
3572
3573   return type;
3574 }
3575
3576 UVMapNode::UVMapNode() : ShaderNode(node_type)
3577 {
3578 }
3579
3580 void UVMapNode::attributes(Shader *shader, AttributeRequestSet *attributes)
3581 {
3582   if (shader->has_surface) {
3583     if (!from_dupli) {
3584       if (!output("UV")->links.empty()) {
3585         if (attribute != "")
3586           attributes->add(attribute);
3587         else
3588           attributes->add(ATTR_STD_UV);
3589       }
3590     }
3591   }
3592
3593   ShaderNode::attributes(shader, attributes);
3594 }
3595
3596 void UVMapNode::compile(SVMCompiler &compiler)
3597 {
3598   ShaderOutput *out = output("UV");
3599   ShaderNodeType texco_node = NODE_TEX_COORD;
3600   ShaderNodeType attr_node = NODE_ATTR;
3601   int attr;
3602
3603   if (bump == SHADER_BUMP_DX) {
3604     texco_node = NODE_TEX_COORD_BUMP_DX;
3605     attr_node = NODE_ATTR_BUMP_DX;
3606   }
3607   else if (bump == SHADER_BUMP_DY) {
3608     texco_node = NODE_TEX_COORD_BUMP_DY;
3609     attr_node = NODE_ATTR_BUMP_DY;
3610   }
3611
3612   if (!out->links.empty()) {
3613     if (from_dupli) {
3614       compiler.add_node(texco_node, NODE_TEXCO_DUPLI_UV, compiler.stack_assign(out));
3615     }
3616     else {
3617       if (attribute != "")
3618         attr = compiler.attribute(attribute);
3619       else
3620         attr = compiler.attribute(ATTR_STD_UV);
3621
3622       compiler.add_node(attr_node, attr, compiler.stack_assign(out), NODE_ATTR_FLOAT3);
3623     }
3624   }
3625 }
3626
3627 void UVMapNode::compile(OSLCompiler &compiler)
3628 {
3629   if (bump == SHADER_BUMP_DX)
3630     compiler.parameter("bump_offset", "dx");
3631   else if (bump == SHADER_BUMP_DY)
3632     compiler.parameter("bump_offset", "dy");
3633   else
3634     compiler.parameter("bump_offset", "center");
3635
3636   compiler.parameter(this, "from_dupli");
3637   compiler.parameter(this, "attribute");
3638   compiler.add(this, "node_uv_map");
3639 }
3640
3641 /* Light Path */
3642
3643 NODE_DEFINE(LightPathNode)
3644 {
3645   NodeType *type = NodeType::add("light_path", create, NodeType::SHADER);
3646
3647   SOCKET_OUT_FLOAT(is_camera_ray, "Is Camera Ray");
3648   SOCKET_OUT_FLOAT(is_shadow_ray, "Is Shadow Ray");
3649   SOCKET_OUT_FLOAT(is_diffuse_ray, "Is Diffuse Ray");
3650   SOCKET_OUT_FLOAT(is_glossy_ray, "Is Glossy Ray");
3651   SOCKET_OUT_FLOAT(is_singular_ray, "Is Singular Ray");
3652   SOCKET_OUT_FLOAT(is_reflection_ray, "Is Reflection Ray");
3653   SOCKET_OUT_FLOAT(is_transmission_ray, "Is Transmission Ray");
3654   SOCKET_OUT_FLOAT(is_volume_scatter_ray, "Is Volume Scatter Ray");
3655   SOCKET_OUT_FLOAT(ray_length, "Ray Length");
3656   SOCKET_OUT_FLOAT(ray_depth, "Ray Depth");
3657   SOCKET_OUT_FLOAT(diffuse_depth, "Diffuse Depth");
3658   SOCKET_OUT_FLOAT(glossy_depth, "Glossy Depth");
3659   SOCKET_OUT_FLOAT(transparent_depth, "Transparent Depth");
3660   SOCKET_OUT_FLOAT(transmission_depth, "Transmission Depth");
3661
3662   return type;
3663 }
3664
3665 LightPathNode::LightPathNode() : ShaderNode(node_type)
3666 {
3667 }
3668
3669 void LightPathNode::compile(SVMCompiler &compiler)
3670 {
3671   ShaderOutput *out;
3672
3673   out = output("Is Camera Ray");
3674   if (!out->links.empty()) {
3675     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_camera, compiler.stack_assign(out));
3676   }
3677
3678   out = output("Is Shadow Ray");
3679   if (!out->links.empty()) {
3680     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_shadow, compiler.stack_assign(out));
3681   }
3682
3683   out = output("Is Diffuse Ray");
3684   if (!out->links.empty()) {
3685     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_diffuse, compiler.stack_assign(out));
3686   }
3687
3688   out = output("Is Glossy Ray");
3689   if (!out->links.empty()) {
3690     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_glossy, compiler.stack_assign(out));
3691   }
3692
3693   out = output("Is Singular Ray");
3694   if (!out->links.empty()) {
3695     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_singular, compiler.stack_assign(out));
3696   }
3697
3698   out = output("Is Reflection Ray");
3699   if (!out->links.empty()) {
3700     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_reflection, compiler.stack_assign(out));
3701   }
3702
3703   out = output("Is Transmission Ray");
3704   if (!out->links.empty()) {
3705     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_transmission, compiler.stack_assign(out));
3706   }
3707
3708   out = output("Is Volume Scatter Ray");
3709   if (!out->links.empty()) {
3710     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_volume_scatter, compiler.stack_assign(out));
3711   }
3712
3713   out = output("Ray Length");
3714   if (!out->links.empty()) {
3715     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_ray_length, compiler.stack_assign(out));
3716   }
3717
3718   out = output("Ray Depth");
3719   if (!out->links.empty()) {
3720     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_ray_depth, compiler.stack_assign(out));
3721   }
3722
3723   out = output("Diffuse Depth");
3724   if (!out->links.empty()) {
3725     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_ray_diffuse, compiler.stack_assign(out));
3726   }
3727
3728   out = output("Glossy Depth");
3729   if (!out->links.empty()) {
3730     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_ray_glossy, compiler.stack_assign(out));
3731   }
3732
3733   out = output("Transparent Depth");
3734   if (!out->links.empty()) {
3735     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_ray_transparent, compiler.stack_assign(out));
3736   }
3737
3738   out = output("Transmission Depth");
3739   if (!out->links.empty()) {
3740     compiler.add_node(NODE_LIGHT_PATH, NODE_LP_ray_transmission, compiler.stack_assign(out));
3741   }
3742 }
3743
3744 void LightPathNode::compile(OSLCompiler &compiler)
3745 {
3746   compiler.add(this, "node_light_path");
3747 }
3748
3749 /* Light Falloff */
3750
3751 NODE_DEFINE(LightFalloffNode)
3752 {
3753   NodeType *type = NodeType::add("light_falloff", create, NodeType::SHADER);
3754
3755   SOCKET_IN_FLOAT(strength, "Strength", 100.0f);
3756   SOCKET_IN_FLOAT(smooth, "Smooth", 0.0f);
3757
3758   SOCKET_OUT_FLOAT(quadratic, "Quadratic");
3759   SOCKET_OUT_FLOAT(linear, "Linear");
3760   SOCKET_OUT_FLOAT(constant, "Constant");
3761
3762   return type;
3763 }
3764
3765 LightFalloffNode::LightFalloffNode() : ShaderNode(node_type)
3766 {
3767 }
3768
3769 void LightFalloffNode::compile(SVMCompiler &compiler)
3770 {
3771   ShaderInput *strength_in = input("Strength");
3772   ShaderInput *smooth_in = input("Smooth");
3773
3774   ShaderOutput *out = output("Quadratic");
3775   if (!out->links.empty()) {
3776     compiler.add_node(NODE_LIGHT_FALLOFF,
3777                       NODE_LIGHT_FALLOFF_QUADRATIC,
3778                       compiler.encode_uchar4(compiler.stack_assign(strength_in),
3779                                              compiler.stack_assign(smooth_in),
3780                                              compiler.stack_assign(out)));
3781   }
3782
3783   out = output("Linear");
3784   if (!out->links.empty()) {
3785     compiler.add_node(NODE_LIGHT_FALLOFF,
3786                       NODE_LIGHT_FALLOFF_LINEAR,
3787                       compiler.encode_uchar4(compiler.stack_assign(strength_in),
3788                                              compiler.stack_assign(smooth_in),
3789                                              compiler.stack_assign(out)));
3790   }
3791
3792   out = output("Constant");
3793   if (!out->links.empty()) {
3794     compiler.add_node(NODE_LIGHT_FALLOFF,
3795                       NODE_LIGHT_FALLOFF_CONSTANT,
3796                       compiler.encode_uchar4(compiler.stack_assign(strength_in),
3797                                              compiler.stack_assign(smooth_in),
3798                                              compiler.stack_assign(out)));
3799   }
3800 }
3801
3802 void LightFalloffNode::compile(OSLCompiler &compiler)
3803 {
3804   compiler.add(this, "node_light_falloff");
3805 }
3806
3807 /* Object Info */
3808
3809 NODE_DEFINE(ObjectInfoNode)
3810 {
3811   NodeType *type = NodeType::add("object_info", create, NodeType::SHADER);
3812
3813   SOCKET_OUT_VECTOR(location, "Location");
3814   SOCKET_OUT_FLOAT(object_index, "Object Index");
3815   SOCKET_OUT_FLOAT(material_index, "Material Index");
3816   SOCKET_OUT_FLOAT(random, "Random");
3817
3818   return type;
3819 }
3820
3821 ObjectInfoNode::ObjectInfoNode() : ShaderNode(node_type)
3822 {
3823 }
3824
3825 void ObjectInfoNode::compile(SVMCompiler &compiler)
3826 {
3827   ShaderOutput *out = output("Location");
3828   if (!out->links.empty()) {
3829     compiler.add_node(NODE_OBJECT_INFO, NODE_INFO_OB_LOCATION, compiler.stack_assign(out));
3830   }
3831
3832   out = output("Object Index");
3833   if (!out->links.empty()) {
3834     compiler.add_node(NODE_OBJECT_INFO, NODE_INFO_OB_INDEX, compiler.stack_assign(out));
3835   }
3836
3837   out = output("Material Index");
3838   if (!out->links.empty()) {
3839     compiler.add_node(NODE_OBJECT_INFO, NODE_INFO_MAT_INDEX, compiler.stack_assign(out));
3840   }
3841
3842   out = output("Random");
3843   if (!out->links.empty()) {
3844     compiler.add_node(NODE_OBJECT_INFO, NODE_INFO_OB_RANDOM, compiler.stack_assign(out));
3845   }
3846 }
3847
3848 void ObjectInfoNode::compile(OSLCompiler &compiler)
3849 {
3850   compiler.add(this, "node_object_info");
3851 }
3852
3853 /* Particle Info */
3854
3855 NODE_DEFINE(ParticleInfoNode)
3856 {
3857   NodeType *type = NodeType::add("particle_info", create, NodeType::SHADER);
3858
3859   SOCKET_OUT_FLOAT(index, "Index");
3860   SOCKET_OUT_FLOAT(random, "Random");
3861   SOCKET_OUT_FLOAT(age, "Age");
3862   SOCKET_OUT_FLOAT(lifetime, "Lifetime");
3863   SOCKET_OUT_POINT(location, "Location");
3864 #if 0 /* not yet supported */
3865   SOCKET_OUT_QUATERNION(rotation, "Rotation");
3866 #endif
3867   SOCKET_OUT_FLOAT(size, "Size");
3868   SOCKET_OUT_VECTOR(velocity, "Velocity");
3869   SOCKET_OUT_VECTOR(angular_velocity, "Angular Velocity");
3870
3871   return type;
3872 }
3873
3874 ParticleInfoNode::ParticleInfoNode() : ShaderNode(node_type)
3875 {
3876 }
3877
3878 void ParticleInfoNode::attributes(Shader *shader, AttributeRequestSet *attributes)
3879 {
3880   if (!output("Index")->links.empty())
3881     attributes->add(ATTR_STD_PARTICLE);
3882   if (!output("Random")->links.empty())
3883     attributes->add(ATTR_STD_PARTICLE);
3884   if (!output("Age")->links.empty())
3885     attributes->add(ATTR_STD_PARTICLE);
3886   if (!output("Lifetime")->links.empty())
3887     attributes->add(ATTR_STD_PARTICLE);
3888   if (!output("Location")->links.empty())
3889     attributes->add(ATTR_STD_PARTICLE);
3890 #if 0 /* not yet supported */
3891   if (!output("Rotation")->links.empty())
3892     attributes->add(ATTR_STD_PARTICLE);
3893 #endif
3894   if (!output("Size")->links.empty())
3895     attributes->add(ATTR_STD_PARTICLE);
3896   if (!output("Velocity")->links.empty())
3897     attributes->add(ATTR_STD_PARTICLE);
3898   if (!output("Angular Velocity")->links.empty())
3899     attributes->add(ATTR_STD_PARTICLE);
3900
3901   ShaderNode::attributes(shader, attributes);
3902 }
3903
3904 void ParticleInfoNode::compile(SVMCompiler &compiler)