Cycles: add random walk subsurface scattering to Principled BSDF.
[blender.git] / intern / cycles / blender / blender_shader.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/background.h"
18 #include "render/graph.h"
19 #include "render/light.h"
20 #include "render/nodes.h"
21 #include "render/osl.h"
22 #include "render/scene.h"
23 #include "render/shader.h"
24
25 #include "blender/blender_texture.h"
26 #include "blender/blender_sync.h"
27 #include "blender/blender_util.h"
28
29 #include "util/util_debug.h"
30 #include "util/util_foreach.h"
31 #include "util/util_string.h"
32 #include "util/util_set.h"
33 #include "util/util_task.h"
34
35 CCL_NAMESPACE_BEGIN
36
37 typedef map<void*, ShaderInput*> PtrInputMap;
38 typedef map<void*, ShaderOutput*> PtrOutputMap;
39 typedef map<string, ConvertNode*> ProxyMap;
40
41 /* Find */
42
43 void BlenderSync::find_shader(BL::ID& id,
44                               vector<Shader*>& used_shaders,
45                               Shader *default_shader)
46 {
47         Shader *shader = (id)? shader_map.find(id): default_shader;
48
49         used_shaders.push_back(shader);
50         shader->tag_used(scene);
51 }
52
53 /* RNA translation utilities */
54
55 static VolumeSampling get_volume_sampling(PointerRNA& ptr)
56 {
57         return (VolumeSampling)get_enum(ptr,
58                                         "volume_sampling",
59                                         VOLUME_NUM_SAMPLING,
60                                         VOLUME_SAMPLING_DISTANCE);
61 }
62
63 static VolumeInterpolation get_volume_interpolation(PointerRNA& ptr)
64 {
65         return (VolumeInterpolation)get_enum(ptr,
66                                              "volume_interpolation",
67                                              VOLUME_NUM_INTERPOLATION,
68                                              VOLUME_INTERPOLATION_LINEAR);
69 }
70
71 static DisplacementMethod get_displacement_method(PointerRNA& ptr)
72 {
73         return (DisplacementMethod)get_enum(ptr,
74                                             "displacement_method",
75                                             DISPLACE_NUM_METHODS,
76                                             DISPLACE_BUMP);
77 }
78
79 static int validate_enum_value(int value, int num_values, int default_value)
80 {
81         if(value >= num_values) {
82                 return default_value;
83         }
84         return value;
85 }
86
87 template<typename NodeType>
88 static InterpolationType get_image_interpolation(NodeType& b_node)
89 {
90         int value = b_node.interpolation();
91         return (InterpolationType)validate_enum_value(value,
92                                                       INTERPOLATION_NUM_TYPES,
93                                                       INTERPOLATION_LINEAR);
94 }
95
96 template<typename NodeType>
97 static ExtensionType get_image_extension(NodeType& b_node)
98 {
99         int value = b_node.extension();
100         return (ExtensionType)validate_enum_value(value,
101                                                   EXTENSION_NUM_TYPES,
102                                                   EXTENSION_REPEAT);
103 }
104
105 /* Graph */
106
107 static BL::NodeSocket get_node_output(BL::Node& b_node, const string& name)
108 {
109         BL::Node::outputs_iterator b_out;
110
111         for(b_node.outputs.begin(b_out); b_out != b_node.outputs.end(); ++b_out)
112                 if(b_out->name() == name)
113                         return *b_out;
114
115         assert(0);
116
117         return *b_out;
118 }
119
120 static float3 get_node_output_rgba(BL::Node& b_node, const string& name)
121 {
122         BL::NodeSocket b_sock = get_node_output(b_node, name);
123         float value[4];
124         RNA_float_get_array(&b_sock.ptr, "default_value", value);
125         return make_float3(value[0], value[1], value[2]);
126 }
127
128 static float get_node_output_value(BL::Node& b_node, const string& name)
129 {
130         BL::NodeSocket b_sock = get_node_output(b_node, name);
131         return RNA_float_get(&b_sock.ptr, "default_value");
132 }
133
134 static float3 get_node_output_vector(BL::Node& b_node, const string& name)
135 {
136         BL::NodeSocket b_sock = get_node_output(b_node, name);
137         float value[3];
138         RNA_float_get_array(&b_sock.ptr, "default_value", value);
139         return make_float3(value[0], value[1], value[2]);
140 }
141
142 static SocketType::Type convert_socket_type(BL::NodeSocket& b_socket)
143 {
144         switch(b_socket.type()) {
145                 case BL::NodeSocket::type_VALUE:
146                         return SocketType::FLOAT;
147                 case BL::NodeSocket::type_INT:
148                         return SocketType::INT;
149                 case BL::NodeSocket::type_VECTOR:
150                         return SocketType::VECTOR;
151                 case BL::NodeSocket::type_RGBA:
152                         return SocketType::COLOR;
153                 case BL::NodeSocket::type_STRING:
154                         return SocketType::STRING;
155                 case BL::NodeSocket::type_SHADER:
156                         return SocketType::CLOSURE;
157                 
158                 default:
159                         return SocketType::UNDEFINED;
160         }
161 }
162
163 static void set_default_value(ShaderInput *input,
164                               BL::NodeSocket& b_sock,
165                               BL::BlendData& b_data,
166                               BL::ID& b_id)
167 {
168         Node *node = input->parent;
169         const SocketType& socket = input->socket_type;
170
171         /* copy values for non linked inputs */
172         switch(input->type()) {
173                 case SocketType::FLOAT: {
174                         node->set(socket, get_float(b_sock.ptr, "default_value"));
175                         break;
176                 }
177                 case SocketType::INT: {
178                         node->set(socket, get_int(b_sock.ptr, "default_value"));
179                         break;
180                 }
181                 case SocketType::COLOR: {
182                         node->set(socket, float4_to_float3(get_float4(b_sock.ptr, "default_value")));
183                         break;
184                 }
185                 case SocketType::NORMAL:
186                 case SocketType::POINT:
187                 case SocketType::VECTOR: {
188                         node->set(socket, get_float3(b_sock.ptr, "default_value"));
189                         break;
190                 }
191                 case SocketType::STRING: {
192                         node->set(socket, (ustring)blender_absolute_path(b_data, b_id, get_string(b_sock.ptr, "default_value")));
193                         break;
194                 }
195                 default:
196                         break;
197         }
198 }
199
200 static void get_tex_mapping(TextureMapping *mapping, BL::TexMapping& b_mapping)
201 {
202         if(!b_mapping)
203                 return;
204
205         mapping->translation = get_float3(b_mapping.translation());
206         mapping->rotation = get_float3(b_mapping.rotation());
207         mapping->scale = get_float3(b_mapping.scale());
208         mapping->type = (TextureMapping::Type)b_mapping.vector_type();
209
210         mapping->x_mapping = (TextureMapping::Mapping)b_mapping.mapping_x();
211         mapping->y_mapping = (TextureMapping::Mapping)b_mapping.mapping_y();
212         mapping->z_mapping = (TextureMapping::Mapping)b_mapping.mapping_z();
213 }
214
215 static void get_tex_mapping(TextureMapping *mapping,
216                             BL::ShaderNodeMapping& b_mapping)
217 {
218         if(!b_mapping)
219                 return;
220
221         mapping->translation = get_float3(b_mapping.translation());
222         mapping->rotation = get_float3(b_mapping.rotation());
223         mapping->scale = get_float3(b_mapping.scale());
224         mapping->type = (TextureMapping::Type)b_mapping.vector_type();
225
226         mapping->use_minmax = b_mapping.use_min() || b_mapping.use_max();
227
228         if(b_mapping.use_min())
229                 mapping->min = get_float3(b_mapping.min());
230         if(b_mapping.use_max())
231                 mapping->max = get_float3(b_mapping.max());
232 }
233
234 static bool is_output_node(BL::Node& b_node)
235 {
236         return (b_node.is_a(&RNA_ShaderNodeOutputMaterial)
237                     || b_node.is_a(&RNA_ShaderNodeOutputWorld)
238                     || b_node.is_a(&RNA_ShaderNodeOutputLamp));
239 }
240
241 static ShaderNode *add_node(Scene *scene,
242                             BL::RenderEngine& b_engine,
243                             BL::BlendData& b_data,
244                             BL::Scene& b_scene,
245                             const bool background,
246                             ShaderGraph *graph,
247                             BL::ShaderNodeTree& b_ntree,
248                             BL::ShaderNode& b_node)
249 {
250         ShaderNode *node = NULL;
251
252         /* existing blender nodes */
253         if(b_node.is_a(&RNA_ShaderNodeRGBCurve)) {
254                 BL::ShaderNodeRGBCurve b_curve_node(b_node);
255                 BL::CurveMapping mapping(b_curve_node.mapping());
256                 RGBCurvesNode *curves = new RGBCurvesNode();
257                 curvemapping_color_to_array(mapping,
258                                             curves->curves,
259                                             RAMP_TABLE_SIZE,
260                                             true);
261                 curvemapping_minmax(mapping, true, &curves->min_x, &curves->max_x);
262                 node = curves;
263         }
264         if(b_node.is_a(&RNA_ShaderNodeVectorCurve)) {
265                 BL::ShaderNodeVectorCurve b_curve_node(b_node);
266                 BL::CurveMapping mapping(b_curve_node.mapping());
267                 VectorCurvesNode *curves = new VectorCurvesNode();
268                 curvemapping_color_to_array(mapping,
269                                             curves->curves,
270                                             RAMP_TABLE_SIZE,
271                                             false);
272                 curvemapping_minmax(mapping, false, &curves->min_x, &curves->max_x);
273                 node = curves;
274         }
275         else if(b_node.is_a(&RNA_ShaderNodeValToRGB)) {
276                 RGBRampNode *ramp = new RGBRampNode();
277                 BL::ShaderNodeValToRGB b_ramp_node(b_node);
278                 BL::ColorRamp b_color_ramp(b_ramp_node.color_ramp());
279                 colorramp_to_array(b_color_ramp, ramp->ramp, ramp->ramp_alpha, RAMP_TABLE_SIZE);
280                 ramp->interpolate = b_color_ramp.interpolation() != BL::ColorRamp::interpolation_CONSTANT;
281                 node = ramp;
282         }
283         else if(b_node.is_a(&RNA_ShaderNodeRGB)) {
284                 ColorNode *color = new ColorNode();
285                 color->value = get_node_output_rgba(b_node, "Color");
286                 node = color;
287         }
288         else if(b_node.is_a(&RNA_ShaderNodeValue)) {
289                 ValueNode *value = new ValueNode();
290                 value->value = get_node_output_value(b_node, "Value");
291                 node = value;
292         }
293         else if(b_node.is_a(&RNA_ShaderNodeCameraData)) {
294                 node = new CameraNode();
295         }
296         else if(b_node.is_a(&RNA_ShaderNodeInvert)) {
297                 node = new InvertNode();
298         }
299         else if(b_node.is_a(&RNA_ShaderNodeGamma)) {
300                 node = new GammaNode();
301         }
302         else if(b_node.is_a(&RNA_ShaderNodeBrightContrast)) {
303                 node = new BrightContrastNode();
304         }
305         else if(b_node.is_a(&RNA_ShaderNodeMixRGB)) {
306                 BL::ShaderNodeMixRGB b_mix_node(b_node);
307                 MixNode *mix = new MixNode();
308                 mix->type = (NodeMix)b_mix_node.blend_type();
309                 mix->use_clamp = b_mix_node.use_clamp();
310                 node = mix;
311         }
312         else if(b_node.is_a(&RNA_ShaderNodeSeparateRGB)) {
313                 node = new SeparateRGBNode();
314         }
315         else if(b_node.is_a(&RNA_ShaderNodeCombineRGB)) {
316                 node = new CombineRGBNode();
317         }
318         else if(b_node.is_a(&RNA_ShaderNodeSeparateHSV)) {
319                 node = new SeparateHSVNode();
320         }
321         else if(b_node.is_a(&RNA_ShaderNodeCombineHSV)) {
322                 node = new CombineHSVNode();
323         }
324         else if(b_node.is_a(&RNA_ShaderNodeSeparateXYZ)) {
325                 node = new SeparateXYZNode();
326         }
327         else if(b_node.is_a(&RNA_ShaderNodeCombineXYZ)) {
328                 node = new CombineXYZNode();
329         }
330         else if(b_node.is_a(&RNA_ShaderNodeHueSaturation)) {
331                 node = new HSVNode();
332         }
333         else if(b_node.is_a(&RNA_ShaderNodeRGBToBW)) {
334                 node = new RGBToBWNode();
335         }
336         else if(b_node.is_a(&RNA_ShaderNodeMath)) {
337                 BL::ShaderNodeMath b_math_node(b_node);
338                 MathNode *math = new MathNode();
339                 math->type = (NodeMath)b_math_node.operation();
340                 math->use_clamp = b_math_node.use_clamp();
341                 node = math;
342         }
343         else if(b_node.is_a(&RNA_ShaderNodeVectorMath)) {
344                 BL::ShaderNodeVectorMath b_vector_math_node(b_node);
345                 VectorMathNode *vmath = new VectorMathNode();
346                 vmath->type = (NodeVectorMath)b_vector_math_node.operation();
347                 node = vmath;
348         }
349         else if(b_node.is_a(&RNA_ShaderNodeVectorTransform)) {
350                 BL::ShaderNodeVectorTransform b_vector_transform_node(b_node);
351                 VectorTransformNode *vtransform = new VectorTransformNode();
352                 vtransform->type = (NodeVectorTransformType)b_vector_transform_node.vector_type();
353                 vtransform->convert_from = (NodeVectorTransformConvertSpace)b_vector_transform_node.convert_from();
354                 vtransform->convert_to = (NodeVectorTransformConvertSpace)b_vector_transform_node.convert_to();
355                 node = vtransform;
356         }
357         else if(b_node.is_a(&RNA_ShaderNodeNormal)) {
358                 BL::Node::outputs_iterator out_it;
359                 b_node.outputs.begin(out_it);
360
361                 NormalNode *norm = new NormalNode();
362                 norm->direction = get_node_output_vector(b_node, "Normal");
363                 node = norm;
364         }
365         else if(b_node.is_a(&RNA_ShaderNodeMapping)) {
366                 BL::ShaderNodeMapping b_mapping_node(b_node);
367                 MappingNode *mapping = new MappingNode();
368
369                 get_tex_mapping(&mapping->tex_mapping, b_mapping_node);
370
371                 node = mapping;
372         }
373         else if(b_node.is_a(&RNA_ShaderNodeFresnel)) {
374                 node = new FresnelNode();
375         }
376         else if(b_node.is_a(&RNA_ShaderNodeLayerWeight)) {
377                 node = new LayerWeightNode();
378         }
379         else if(b_node.is_a(&RNA_ShaderNodeAddShader)) {
380                 node = new AddClosureNode();
381         }
382         else if(b_node.is_a(&RNA_ShaderNodeMixShader)) {
383                 node = new MixClosureNode();
384         }
385         else if(b_node.is_a(&RNA_ShaderNodeAttribute)) {
386                 BL::ShaderNodeAttribute b_attr_node(b_node);
387                 AttributeNode *attr = new AttributeNode();
388                 attr->attribute = b_attr_node.attribute_name();
389                 node = attr;
390         }
391         else if(b_node.is_a(&RNA_ShaderNodeBackground)) {
392                 node = new BackgroundNode();
393         }
394         else if(b_node.is_a(&RNA_ShaderNodeHoldout)) {
395                 node = new HoldoutNode();
396         }
397         else if(b_node.is_a(&RNA_ShaderNodeBsdfAnisotropic)) {
398                 BL::ShaderNodeBsdfAnisotropic b_aniso_node(b_node);
399                 AnisotropicBsdfNode *aniso = new AnisotropicBsdfNode();
400
401                 switch(b_aniso_node.distribution()) {
402                         case BL::ShaderNodeBsdfAnisotropic::distribution_BECKMANN:
403                                 aniso->distribution = CLOSURE_BSDF_MICROFACET_BECKMANN_ANISO_ID;
404                                 break;
405                         case BL::ShaderNodeBsdfAnisotropic::distribution_GGX:
406                                 aniso->distribution = CLOSURE_BSDF_MICROFACET_GGX_ANISO_ID;
407                                 break;
408                         case BL::ShaderNodeBsdfAnisotropic::distribution_MULTI_GGX:
409                                 aniso->distribution = CLOSURE_BSDF_MICROFACET_MULTI_GGX_ANISO_ID;
410                                 break;
411                         case BL::ShaderNodeBsdfAnisotropic::distribution_ASHIKHMIN_SHIRLEY:
412                                 aniso->distribution = CLOSURE_BSDF_ASHIKHMIN_SHIRLEY_ANISO_ID;
413                                 break;
414                 }
415
416                 node = aniso;
417         }
418         else if(b_node.is_a(&RNA_ShaderNodeBsdfDiffuse)) {
419                 node = new DiffuseBsdfNode();
420         }
421         else if(b_node.is_a(&RNA_ShaderNodeSubsurfaceScattering)) {
422                 BL::ShaderNodeSubsurfaceScattering b_subsurface_node(b_node);
423
424                 SubsurfaceScatteringNode *subsurface = new SubsurfaceScatteringNode();
425
426                 switch(b_subsurface_node.falloff()) {
427                         case BL::ShaderNodeSubsurfaceScattering::falloff_CUBIC:
428                                 subsurface->falloff = CLOSURE_BSSRDF_CUBIC_ID;
429                                 break;
430                         case BL::ShaderNodeSubsurfaceScattering::falloff_GAUSSIAN:
431                                 subsurface->falloff = CLOSURE_BSSRDF_GAUSSIAN_ID;
432                                 break;
433                         case BL::ShaderNodeSubsurfaceScattering::falloff_BURLEY:
434                                 subsurface->falloff = CLOSURE_BSSRDF_BURLEY_ID;
435                                 break;
436                         case BL::ShaderNodeSubsurfaceScattering::falloff_RANDOM_WALK:
437                                 subsurface->falloff = CLOSURE_BSSRDF_RANDOM_WALK_ID;
438                                 break;
439                 }
440
441                 node = subsurface;
442         }
443         else if(b_node.is_a(&RNA_ShaderNodeBsdfGlossy)) {
444                 BL::ShaderNodeBsdfGlossy b_glossy_node(b_node);
445                 GlossyBsdfNode *glossy = new GlossyBsdfNode();
446                 
447                 switch(b_glossy_node.distribution()) {
448                         case BL::ShaderNodeBsdfGlossy::distribution_SHARP:
449                                 glossy->distribution = CLOSURE_BSDF_REFLECTION_ID;
450                                 break;
451                         case BL::ShaderNodeBsdfGlossy::distribution_BECKMANN:
452                                 glossy->distribution = CLOSURE_BSDF_MICROFACET_BECKMANN_ID;
453                                 break;
454                         case BL::ShaderNodeBsdfGlossy::distribution_GGX:
455                                 glossy->distribution = CLOSURE_BSDF_MICROFACET_GGX_ID;
456                                 break;
457                         case BL::ShaderNodeBsdfGlossy::distribution_ASHIKHMIN_SHIRLEY:
458                                 glossy->distribution = CLOSURE_BSDF_ASHIKHMIN_SHIRLEY_ID;
459                                 break;
460                         case BL::ShaderNodeBsdfGlossy::distribution_MULTI_GGX:
461                                 glossy->distribution = CLOSURE_BSDF_MICROFACET_MULTI_GGX_ID;
462                                 break;
463                 }
464                 node = glossy;
465         }
466         else if(b_node.is_a(&RNA_ShaderNodeBsdfGlass)) {
467                 BL::ShaderNodeBsdfGlass b_glass_node(b_node);
468                 GlassBsdfNode *glass = new GlassBsdfNode();
469                 switch(b_glass_node.distribution()) {
470                         case BL::ShaderNodeBsdfGlass::distribution_SHARP:
471                                 glass->distribution = CLOSURE_BSDF_SHARP_GLASS_ID;
472                                 break;
473                         case BL::ShaderNodeBsdfGlass::distribution_BECKMANN:
474                                 glass->distribution = CLOSURE_BSDF_MICROFACET_BECKMANN_GLASS_ID;
475                                 break;
476                         case BL::ShaderNodeBsdfGlass::distribution_GGX:
477                                 glass->distribution = CLOSURE_BSDF_MICROFACET_GGX_GLASS_ID;
478                                 break;
479                         case BL::ShaderNodeBsdfGlass::distribution_MULTI_GGX:
480                                 glass->distribution = CLOSURE_BSDF_MICROFACET_MULTI_GGX_GLASS_ID;
481                                 break;
482                 }
483                 node = glass;
484         }
485         else if(b_node.is_a(&RNA_ShaderNodeBsdfRefraction)) {
486                 BL::ShaderNodeBsdfRefraction b_refraction_node(b_node);
487                 RefractionBsdfNode *refraction = new RefractionBsdfNode();
488                 switch(b_refraction_node.distribution()) {
489                         case BL::ShaderNodeBsdfRefraction::distribution_SHARP:
490                                 refraction->distribution = CLOSURE_BSDF_REFRACTION_ID;
491                                 break;
492                         case BL::ShaderNodeBsdfRefraction::distribution_BECKMANN:
493                                 refraction->distribution = CLOSURE_BSDF_MICROFACET_BECKMANN_REFRACTION_ID;
494                                 break;
495                         case BL::ShaderNodeBsdfRefraction::distribution_GGX:
496                                 refraction->distribution = CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID;
497                                 break;
498                 }
499                 node = refraction;
500         }
501         else if(b_node.is_a(&RNA_ShaderNodeBsdfToon)) {
502                 BL::ShaderNodeBsdfToon b_toon_node(b_node);
503                 ToonBsdfNode *toon = new ToonBsdfNode();
504                 switch(b_toon_node.component()) {
505                         case BL::ShaderNodeBsdfToon::component_DIFFUSE:
506                                 toon->component = CLOSURE_BSDF_DIFFUSE_TOON_ID;
507                                 break;
508                         case BL::ShaderNodeBsdfToon::component_GLOSSY:
509                                 toon->component = CLOSURE_BSDF_GLOSSY_TOON_ID;
510                                 break;
511                 }
512                 node = toon;
513         }
514         else if(b_node.is_a(&RNA_ShaderNodeBsdfHair)) {
515                 BL::ShaderNodeBsdfHair b_hair_node(b_node);
516                 HairBsdfNode *hair = new HairBsdfNode();
517                 switch(b_hair_node.component()) {
518                         case BL::ShaderNodeBsdfHair::component_Reflection:
519                                 hair->component = CLOSURE_BSDF_HAIR_REFLECTION_ID;
520                                 break;
521                         case BL::ShaderNodeBsdfHair::component_Transmission:
522                                 hair->component = CLOSURE_BSDF_HAIR_TRANSMISSION_ID;
523                                 break;
524                 }
525                 node = hair;
526         }
527         else if(b_node.is_a(&RNA_ShaderNodeBsdfPrincipled)) {
528                 BL::ShaderNodeBsdfPrincipled b_principled_node(b_node);
529                 PrincipledBsdfNode *principled = new PrincipledBsdfNode();
530                 switch (b_principled_node.distribution()) {
531                         case BL::ShaderNodeBsdfPrincipled::distribution_GGX:
532                                 principled->distribution = CLOSURE_BSDF_MICROFACET_GGX_GLASS_ID;
533                                 break;
534                         case BL::ShaderNodeBsdfPrincipled::distribution_MULTI_GGX:
535                                 principled->distribution = CLOSURE_BSDF_MICROFACET_MULTI_GGX_GLASS_ID;
536                                 break;
537                 }
538                 switch (b_principled_node.subsurface_method()) {
539                         case BL::ShaderNodeBsdfPrincipled::subsurface_method_BURLEY:
540                                 principled->subsurface_method = CLOSURE_BSSRDF_PRINCIPLED_ID;
541                                 break;
542                         case BL::ShaderNodeBsdfPrincipled::subsurface_method_RANDOM_WALK:
543                                 principled->subsurface_method = CLOSURE_BSSRDF_PRINCIPLED_RANDOM_WALK_ID;
544                                 break;
545                 }
546                 node = principled;
547         }
548         else if(b_node.is_a(&RNA_ShaderNodeBsdfTranslucent)) {
549                 node = new TranslucentBsdfNode();
550         }
551         else if(b_node.is_a(&RNA_ShaderNodeBsdfTransparent)) {
552                 node = new TransparentBsdfNode();
553         }
554         else if(b_node.is_a(&RNA_ShaderNodeBsdfVelvet)) {
555                 node = new VelvetBsdfNode();
556         }
557         else if(b_node.is_a(&RNA_ShaderNodeEmission)) {
558                 node = new EmissionNode();
559         }
560         else if(b_node.is_a(&RNA_ShaderNodeAmbientOcclusion)) {
561                 node = new AmbientOcclusionNode();
562         }
563         else if(b_node.is_a(&RNA_ShaderNodeVolumeScatter)) {
564                 node = new ScatterVolumeNode();
565         }
566         else if(b_node.is_a(&RNA_ShaderNodeVolumeAbsorption)) {
567                 node = new AbsorptionVolumeNode();
568         }
569         else if(b_node.is_a(&RNA_ShaderNodeNewGeometry)) {
570                 node = new GeometryNode();
571         }
572         else if(b_node.is_a(&RNA_ShaderNodeWireframe)) {
573                 BL::ShaderNodeWireframe b_wireframe_node(b_node);
574                 WireframeNode *wire = new WireframeNode();
575                 wire->use_pixel_size = b_wireframe_node.use_pixel_size();
576                 node = wire;
577         }
578         else if(b_node.is_a(&RNA_ShaderNodeWavelength)) {
579                 node = new WavelengthNode();
580         }
581         else if(b_node.is_a(&RNA_ShaderNodeBlackbody)) {
582                 node = new BlackbodyNode();
583         }
584         else if(b_node.is_a(&RNA_ShaderNodeLightPath)) {
585                 node = new LightPathNode();
586         }
587         else if(b_node.is_a(&RNA_ShaderNodeLightFalloff)) {
588                 node = new LightFalloffNode();
589         }
590         else if(b_node.is_a(&RNA_ShaderNodeObjectInfo)) {
591                 node = new ObjectInfoNode();
592         }
593         else if(b_node.is_a(&RNA_ShaderNodeParticleInfo)) {
594                 node = new ParticleInfoNode();
595         }
596         else if(b_node.is_a(&RNA_ShaderNodeHairInfo)) {
597                 node = new HairInfoNode();
598         }
599         else if(b_node.is_a(&RNA_ShaderNodeBump)) {
600                 BL::ShaderNodeBump b_bump_node(b_node);
601                 BumpNode *bump = new BumpNode();
602                 bump->invert = b_bump_node.invert();
603                 node = bump;
604         }
605         else if(b_node.is_a(&RNA_ShaderNodeScript)) {
606 #ifdef WITH_OSL
607                 if(scene->shader_manager->use_osl()) {
608                         /* create script node */
609                         BL::ShaderNodeScript b_script_node(b_node);
610
611                         OSLShaderManager *manager = (OSLShaderManager*)scene->shader_manager;
612                         string bytecode_hash = b_script_node.bytecode_hash();
613
614                         if(!bytecode_hash.empty()) {
615                                 node = manager->osl_node("", bytecode_hash, b_script_node.bytecode());
616                         }
617                         else {
618                                 string absolute_filepath = blender_absolute_path(b_data, b_ntree, b_script_node.filepath());
619                                 node = manager->osl_node(absolute_filepath, "");
620                         }
621                 }
622 #else
623                 (void)b_data;
624                 (void)b_ntree;
625 #endif
626         }
627         else if(b_node.is_a(&RNA_ShaderNodeTexImage)) {
628                 BL::ShaderNodeTexImage b_image_node(b_node);
629                 BL::Image b_image(b_image_node.image());
630                 BL::ImageUser b_image_user(b_image_node.image_user());
631                 ImageTextureNode *image = new ImageTextureNode();
632                 if(b_image) {
633                         /* builtin images will use callback-based reading because
634                          * they could only be loaded correct from blender side
635                          */
636                         bool is_builtin = b_image.packed_file() ||
637                                           b_image.source() == BL::Image::source_GENERATED ||
638                                           b_image.source() == BL::Image::source_MOVIE ||
639                                           (b_engine.is_preview() &&
640                                            b_image.source() != BL::Image::source_SEQUENCE);
641
642                         if(is_builtin) {
643                                 /* for builtin images we're using image datablock name to find an image to
644                                  * read pixels from later
645                                  *
646                                  * also store frame number as well, so there's no differences in handling
647                                  * builtin names for packed images and movies
648                                  */
649                                 int scene_frame = b_scene.frame_current();
650                                 int image_frame = image_user_frame_number(b_image_user,
651                                                                           scene_frame);
652                                 image->filename = b_image.name() + "@" + string_printf("%d", image_frame);
653                                 image->builtin_data = b_image.ptr.data;
654                         }
655                         else {
656                                 image->filename = image_user_file_path(b_image_user,
657                                                                        b_image,
658                                                                        b_scene.frame_current());
659                                 image->builtin_data = NULL;
660                         }
661
662                         image->animated = b_image_node.image_user().use_auto_refresh();
663                         image->use_alpha = b_image.use_alpha();
664
665                         /* TODO(sergey): Does not work properly when we change builtin type. */
666                         if(b_image.is_updated()) {
667                                 scene->image_manager->tag_reload_image(
668                                         image->filename.string(),
669                                         image->builtin_data,
670                                         get_image_interpolation(b_image_node),
671                                         get_image_extension(b_image_node),
672                                         image->use_alpha);
673                         }
674                 }
675                 image->color_space = (NodeImageColorSpace)b_image_node.color_space();
676                 image->projection = (NodeImageProjection)b_image_node.projection();
677                 image->interpolation = get_image_interpolation(b_image_node);
678                 image->extension = get_image_extension(b_image_node);
679                 image->projection_blend = b_image_node.projection_blend();
680                 BL::TexMapping b_texture_mapping(b_image_node.texture_mapping());
681                 get_tex_mapping(&image->tex_mapping, b_texture_mapping);
682                 node = image;
683         }
684         else if(b_node.is_a(&RNA_ShaderNodeTexEnvironment)) {
685                 BL::ShaderNodeTexEnvironment b_env_node(b_node);
686                 BL::Image b_image(b_env_node.image());
687                 BL::ImageUser b_image_user(b_env_node.image_user());
688                 EnvironmentTextureNode *env = new EnvironmentTextureNode();
689                 if(b_image) {
690                         bool is_builtin = b_image.packed_file() ||
691                                           b_image.source() == BL::Image::source_GENERATED ||
692                                           b_image.source() == BL::Image::source_MOVIE ||
693                                           (b_engine.is_preview() &&
694                                            b_image.source() != BL::Image::source_SEQUENCE);
695
696                         if(is_builtin) {
697                                 int scene_frame = b_scene.frame_current();
698                                 int image_frame = image_user_frame_number(b_image_user,
699                                                                           scene_frame);
700                                 env->filename = b_image.name() + "@" + string_printf("%d", image_frame);
701                                 env->builtin_data = b_image.ptr.data;
702                         }
703                         else {
704                                 env->filename = image_user_file_path(b_image_user,
705                                                                      b_image,
706                                                                      b_scene.frame_current());
707                                 env->builtin_data = NULL;
708                         }
709
710                         env->animated = b_env_node.image_user().use_auto_refresh();
711                         env->use_alpha = b_image.use_alpha();
712
713                         /* TODO(sergey): Does not work properly when we change builtin type. */
714                         if(b_image.is_updated()) {
715                                 scene->image_manager->tag_reload_image(
716                                         env->filename.string(),
717                                         env->builtin_data,
718                                         get_image_interpolation(b_env_node),
719                                         EXTENSION_REPEAT,
720                                         env->use_alpha);
721                         }
722                 }
723                 env->color_space = (NodeImageColorSpace)b_env_node.color_space();
724                 env->interpolation = get_image_interpolation(b_env_node);
725                 env->projection = (NodeEnvironmentProjection)b_env_node.projection();
726                 BL::TexMapping b_texture_mapping(b_env_node.texture_mapping());
727                 get_tex_mapping(&env->tex_mapping, b_texture_mapping);
728                 node = env;
729         }
730         else if(b_node.is_a(&RNA_ShaderNodeTexGradient)) {
731                 BL::ShaderNodeTexGradient b_gradient_node(b_node);
732                 GradientTextureNode *gradient = new GradientTextureNode();
733                 gradient->type = (NodeGradientType)b_gradient_node.gradient_type();
734                 BL::TexMapping b_texture_mapping(b_gradient_node.texture_mapping());
735                 get_tex_mapping(&gradient->tex_mapping, b_texture_mapping);
736                 node = gradient;
737         }
738         else if(b_node.is_a(&RNA_ShaderNodeTexVoronoi)) {
739                 BL::ShaderNodeTexVoronoi b_voronoi_node(b_node);
740                 VoronoiTextureNode *voronoi = new VoronoiTextureNode();
741                 voronoi->coloring = (NodeVoronoiColoring)b_voronoi_node.coloring();
742                 BL::TexMapping b_texture_mapping(b_voronoi_node.texture_mapping());
743                 get_tex_mapping(&voronoi->tex_mapping, b_texture_mapping);
744                 node = voronoi;
745         }
746         else if(b_node.is_a(&RNA_ShaderNodeTexMagic)) {
747                 BL::ShaderNodeTexMagic b_magic_node(b_node);
748                 MagicTextureNode *magic = new MagicTextureNode();
749                 magic->depth = b_magic_node.turbulence_depth();
750                 BL::TexMapping b_texture_mapping(b_magic_node.texture_mapping());
751                 get_tex_mapping(&magic->tex_mapping, b_texture_mapping);
752                 node = magic;
753         }
754         else if(b_node.is_a(&RNA_ShaderNodeTexWave)) {
755                 BL::ShaderNodeTexWave b_wave_node(b_node);
756                 WaveTextureNode *wave = new WaveTextureNode();
757                 wave->type = (NodeWaveType)b_wave_node.wave_type();
758                 wave->profile = (NodeWaveProfile)b_wave_node.wave_profile();
759                 BL::TexMapping b_texture_mapping(b_wave_node.texture_mapping());
760                 get_tex_mapping(&wave->tex_mapping, b_texture_mapping);
761                 node = wave;
762         }
763         else if(b_node.is_a(&RNA_ShaderNodeTexChecker)) {
764                 BL::ShaderNodeTexChecker b_checker_node(b_node);
765                 CheckerTextureNode *checker = new CheckerTextureNode();
766                 BL::TexMapping b_texture_mapping(b_checker_node.texture_mapping());
767                 get_tex_mapping(&checker->tex_mapping, b_texture_mapping);
768                 node = checker;
769         }
770         else if(b_node.is_a(&RNA_ShaderNodeTexBrick)) {
771                 BL::ShaderNodeTexBrick b_brick_node(b_node);
772                 BrickTextureNode *brick = new BrickTextureNode();
773                 brick->offset = b_brick_node.offset();
774                 brick->offset_frequency = b_brick_node.offset_frequency();
775                 brick->squash = b_brick_node.squash();
776                 brick->squash_frequency = b_brick_node.squash_frequency();
777                 BL::TexMapping b_texture_mapping(b_brick_node.texture_mapping());
778                 get_tex_mapping(&brick->tex_mapping, b_texture_mapping);
779                 node = brick;
780         }
781         else if(b_node.is_a(&RNA_ShaderNodeTexNoise)) {
782                 BL::ShaderNodeTexNoise b_noise_node(b_node);
783                 NoiseTextureNode *noise = new NoiseTextureNode();
784                 BL::TexMapping b_texture_mapping(b_noise_node.texture_mapping());
785                 get_tex_mapping(&noise->tex_mapping, b_texture_mapping);
786                 node = noise;
787         }
788         else if(b_node.is_a(&RNA_ShaderNodeTexMusgrave)) {
789                 BL::ShaderNodeTexMusgrave b_musgrave_node(b_node);
790                 MusgraveTextureNode *musgrave = new MusgraveTextureNode();
791                 musgrave->type = (NodeMusgraveType)b_musgrave_node.musgrave_type();
792                 BL::TexMapping b_texture_mapping(b_musgrave_node.texture_mapping());
793                 get_tex_mapping(&musgrave->tex_mapping, b_texture_mapping);
794                 node = musgrave;
795         }
796         else if(b_node.is_a(&RNA_ShaderNodeTexCoord)) {
797                 BL::ShaderNodeTexCoord b_tex_coord_node(b_node);
798                 TextureCoordinateNode *tex_coord = new TextureCoordinateNode();
799                 tex_coord->from_dupli = b_tex_coord_node.from_dupli();
800                 if(b_tex_coord_node.object()) {
801                         tex_coord->use_transform = true;
802                         tex_coord->ob_tfm = get_transform(b_tex_coord_node.object().matrix_world());
803                 }
804                 node = tex_coord;
805         }
806         else if(b_node.is_a(&RNA_ShaderNodeTexSky)) {
807                 BL::ShaderNodeTexSky b_sky_node(b_node);
808                 SkyTextureNode *sky = new SkyTextureNode();
809                 sky->type = (NodeSkyType)b_sky_node.sky_type();
810                 sky->sun_direction = normalize(get_float3(b_sky_node.sun_direction()));
811                 sky->turbidity = b_sky_node.turbidity();
812                 sky->ground_albedo = b_sky_node.ground_albedo();
813                 BL::TexMapping b_texture_mapping(b_sky_node.texture_mapping());
814                 get_tex_mapping(&sky->tex_mapping, b_texture_mapping);
815                 node = sky;
816         }
817         else if(b_node.is_a(&RNA_ShaderNodeNormalMap)) {
818                 BL::ShaderNodeNormalMap b_normal_map_node(b_node);
819                 NormalMapNode *nmap = new NormalMapNode();
820                 nmap->space = (NodeNormalMapSpace)b_normal_map_node.space();
821                 nmap->attribute = b_normal_map_node.uv_map();
822                 node = nmap;
823         }
824         else if(b_node.is_a(&RNA_ShaderNodeTangent)) {
825                 BL::ShaderNodeTangent b_tangent_node(b_node);
826                 TangentNode *tangent = new TangentNode();
827                 tangent->direction_type = (NodeTangentDirectionType)b_tangent_node.direction_type();
828                 tangent->axis = (NodeTangentAxis)b_tangent_node.axis();
829                 tangent->attribute = b_tangent_node.uv_map();
830                 node = tangent;
831         }
832         else if(b_node.is_a(&RNA_ShaderNodeUVMap)) {
833                 BL::ShaderNodeUVMap b_uvmap_node(b_node);
834                 UVMapNode *uvm = new UVMapNode();
835                 uvm->attribute = b_uvmap_node.uv_map();
836                 uvm->from_dupli = b_uvmap_node.from_dupli();
837                 node = uvm;
838         }
839         else if(b_node.is_a(&RNA_ShaderNodeTexPointDensity)) {
840                 BL::ShaderNodeTexPointDensity b_point_density_node(b_node);
841                 PointDensityTextureNode *point_density = new PointDensityTextureNode();
842                 point_density->filename = b_point_density_node.name();
843                 point_density->space = (NodeTexVoxelSpace)b_point_density_node.space();
844                 point_density->interpolation = get_image_interpolation(b_point_density_node);
845                 point_density->builtin_data = b_point_density_node.ptr.data;
846
847                 /* 1 - render settings, 0 - vewport settings. */
848                 int settings = background ? 1 : 0;
849
850                 /* TODO(sergey): Use more proper update flag. */
851                 if(true) {
852                         b_point_density_node.cache_point_density(b_scene, settings);
853                         scene->image_manager->tag_reload_image(
854                                 point_density->filename.string(),
855                                 point_density->builtin_data,
856                                 point_density->interpolation,
857                                 EXTENSION_CLIP,
858                                 true);
859                 }
860                 node = point_density;
861
862                 /* Transformation form world space to texture space.
863                  *
864                  * NOTE: Do this after the texture is cached, this is because getting
865                  * min/max will need to access this cache.
866                  */
867                 BL::Object b_ob(b_point_density_node.object());
868                 if(b_ob) {
869                         float3 loc, size;
870                         point_density_texture_space(b_scene,
871                                                     b_point_density_node,
872                                                     settings,
873                                                     loc,
874                                                     size);
875                         point_density->tfm =
876                                 transform_translate(-loc) * transform_scale(size) *
877                                 transform_inverse(get_transform(b_ob.matrix_world()));
878                 }
879         }
880         else if(b_node.is_a(&RNA_ShaderNodeBevel)) {
881                 BL::ShaderNodeBevel b_bevel_node(b_node);
882                 BevelNode *bevel = new BevelNode();
883                 bevel->samples = b_bevel_node.samples();
884                 node = bevel;
885         }
886         else if(b_node.is_a(&RNA_ShaderNodeDisplacement)) {
887                 BL::ShaderNodeDisplacement b_disp_node(b_node);
888                 DisplacementNode *disp = new DisplacementNode();
889                 disp->space = (NodeNormalMapSpace)b_disp_node.space();
890                 node = disp;
891         }
892         else if(b_node.is_a(&RNA_ShaderNodeVectorDisplacement)) {
893                 BL::ShaderNodeVectorDisplacement b_disp_node(b_node);
894                 VectorDisplacementNode *disp = new VectorDisplacementNode();
895                 disp->space = (NodeNormalMapSpace)b_disp_node.space();
896                 disp->attribute = "";
897                 node = disp;
898         }
899
900         if(node) {
901                 node->name = b_node.name();
902                 graph->add(node);
903         }
904
905         return node;
906 }
907
908 static bool node_use_modified_socket_name(ShaderNode *node)
909 {
910         if(node->special_type == SHADER_SPECIAL_TYPE_SCRIPT)
911                 return false;
912
913         return true;
914 }
915
916 static ShaderInput *node_find_input_by_name(ShaderNode *node,
917                                             BL::Node& b_node,
918                                             BL::NodeSocket& b_socket)
919 {
920         string name = b_socket.name();
921         
922         if(node_use_modified_socket_name(node)) {
923                 BL::Node::inputs_iterator b_input;
924                 bool found = false;
925                 int counter = 0, total = 0;
926
927                 for(b_node.inputs.begin(b_input); b_input != b_node.inputs.end(); ++b_input) {
928                         if(b_input->name() == name) {
929                                 if(!found)
930                                         counter++;
931                                 total++;
932                         }
933
934                         if(b_input->ptr.data == b_socket.ptr.data)
935                                 found = true;
936                 }
937
938                 /* rename if needed */
939                 if(name == "Shader")
940                         name = "Closure";
941
942                 if(total > 1)
943                         name = string_printf("%s%d", name.c_str(), counter);
944         }
945
946         return node->input(name.c_str());
947 }
948
949 static ShaderOutput *node_find_output_by_name(ShaderNode *node,
950                                               BL::Node& b_node,
951                                               BL::NodeSocket& b_socket)
952 {
953         string name = b_socket.name();
954
955         if(node_use_modified_socket_name(node)) {
956                 BL::Node::outputs_iterator b_output;
957                 bool found = false;
958                 int counter = 0, total = 0;
959
960                 for(b_node.outputs.begin(b_output); b_output != b_node.outputs.end(); ++b_output) {
961                         if(b_output->name() == name) {
962                                 if(!found)
963                                         counter++;
964                                 total++;
965                         }
966
967                         if(b_output->ptr.data == b_socket.ptr.data)
968                                 found = true;
969                 }
970
971                 /* rename if needed */
972                 if(name == "Shader")
973                         name = "Closure";
974
975                 if(total > 1)
976                         name = string_printf("%s%d", name.c_str(), counter);
977         }
978
979         return node->output(name.c_str());
980 }
981
982 static void add_nodes(Scene *scene,
983                       BL::RenderEngine& b_engine,
984                       BL::BlendData& b_data,
985                       BL::Scene& b_scene,
986                       const bool background,
987                       ShaderGraph *graph,
988                       BL::ShaderNodeTree& b_ntree,
989                       const ProxyMap &proxy_input_map,
990                       const ProxyMap &proxy_output_map)
991 {
992         /* add nodes */
993         BL::ShaderNodeTree::nodes_iterator b_node;
994         PtrInputMap input_map;
995         PtrOutputMap output_map;
996
997         BL::Node::inputs_iterator b_input;
998         BL::Node::outputs_iterator b_output;
999
1000         /* find the node to use for output if there are multiple */
1001         bool found_active_output = false;
1002         BL::ShaderNode output_node(PointerRNA_NULL);
1003
1004         for(b_ntree.nodes.begin(b_node); b_node != b_ntree.nodes.end(); ++b_node) {
1005                 if(is_output_node(*b_node)) {
1006                         BL::ShaderNodeOutputMaterial b_output_node(*b_node);
1007
1008                         if(b_output_node.is_active_output()) {
1009                                 output_node = b_output_node;
1010                                 found_active_output = true;
1011                                 break;
1012                         }
1013                         else if(!output_node.ptr.data && !found_active_output) {
1014                                 output_node = b_output_node;
1015                         }
1016                 }
1017         }
1018
1019         /* add nodes */
1020         for(b_ntree.nodes.begin(b_node); b_node != b_ntree.nodes.end(); ++b_node) {
1021                 if(b_node->mute() || b_node->is_a(&RNA_NodeReroute)) {
1022                         /* replace muted node with internal links */
1023                         BL::Node::internal_links_iterator b_link;
1024                         for(b_node->internal_links.begin(b_link); b_link != b_node->internal_links.end(); ++b_link) {
1025                                 BL::NodeSocket to_socket(b_link->to_socket());
1026                                 SocketType::Type to_socket_type = convert_socket_type(to_socket);
1027                                 ConvertNode *proxy = new ConvertNode(to_socket_type, to_socket_type, true);
1028
1029                                 input_map[b_link->from_socket().ptr.data] = proxy->inputs[0];
1030                                 output_map[b_link->to_socket().ptr.data] = proxy->outputs[0];
1031
1032                                 graph->add(proxy);
1033                         }
1034                 }
1035                 else if(b_node->is_a(&RNA_ShaderNodeGroup) || b_node->is_a(&RNA_NodeCustomGroup)) {
1036                         
1037                         BL::ShaderNodeTree b_group_ntree(PointerRNA_NULL);
1038                         if(b_node->is_a(&RNA_ShaderNodeGroup))
1039                                 b_group_ntree = BL::ShaderNodeTree(((BL::NodeGroup)(*b_node)).node_tree());
1040                         else
1041                                 b_group_ntree = BL::ShaderNodeTree(((BL::NodeCustomGroup)(*b_node)).node_tree());
1042                         ProxyMap group_proxy_input_map, group_proxy_output_map;
1043
1044                         /* Add a proxy node for each socket
1045                          * Do this even if the node group has no internal tree,
1046                          * so that links have something to connect to and assert won't fail.
1047                          */
1048                         for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
1049                                 SocketType::Type input_type = convert_socket_type(*b_input);
1050                                 ConvertNode *proxy = new ConvertNode(input_type, input_type, true);
1051                                 graph->add(proxy);
1052
1053                                 /* register the proxy node for internal binding */
1054                                 group_proxy_input_map[b_input->identifier()] = proxy;
1055
1056                                 input_map[b_input->ptr.data] = proxy->inputs[0];
1057
1058                                 set_default_value(proxy->inputs[0], *b_input, b_data, b_ntree);
1059                         }
1060                         for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
1061                                 SocketType::Type output_type = convert_socket_type(*b_output);
1062                                 ConvertNode *proxy = new ConvertNode(output_type, output_type, true);
1063                                 graph->add(proxy);
1064
1065                                 /* register the proxy node for internal binding */
1066                                 group_proxy_output_map[b_output->identifier()] = proxy;
1067
1068                                 output_map[b_output->ptr.data] = proxy->outputs[0];
1069                         }
1070                         
1071                         if(b_group_ntree) {
1072                                 add_nodes(scene,
1073                                           b_engine,
1074                                           b_data,
1075                                           b_scene,
1076                                           background,
1077                                           graph,
1078                                           b_group_ntree,
1079                                           group_proxy_input_map,
1080                                           group_proxy_output_map);
1081                         }
1082                 }
1083                 else if(b_node->is_a(&RNA_NodeGroupInput)) {
1084                         /* map each socket to a proxy node */
1085                         for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
1086                                 ProxyMap::const_iterator proxy_it = proxy_input_map.find(b_output->identifier());
1087                                 if(proxy_it != proxy_input_map.end()) {
1088                                         ConvertNode *proxy = proxy_it->second;
1089
1090                                         output_map[b_output->ptr.data] = proxy->outputs[0];
1091                                 }
1092                         }
1093                 }
1094                 else if(b_node->is_a(&RNA_NodeGroupOutput)) {
1095                         BL::NodeGroupOutput b_output_node(*b_node);
1096                         /* only the active group output is used */
1097                         if(b_output_node.is_active_output()) {
1098                                 /* map each socket to a proxy node */
1099                                 for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
1100                                         ProxyMap::const_iterator proxy_it = proxy_output_map.find(b_input->identifier());
1101                                         if(proxy_it != proxy_output_map.end()) {
1102                                                 ConvertNode *proxy = proxy_it->second;
1103
1104                                                 input_map[b_input->ptr.data] = proxy->inputs[0];
1105
1106                                                 set_default_value(proxy->inputs[0], *b_input, b_data, b_ntree);
1107                                         }
1108                                 }
1109                         }
1110                 }
1111                 else {
1112                         ShaderNode *node = NULL;
1113
1114                         if(is_output_node(*b_node)) {
1115                                 if(b_node->ptr.data == output_node.ptr.data) {
1116                                         node = graph->output();
1117                                 }
1118                         }
1119                         else {
1120                                 BL::ShaderNode b_shader_node(*b_node);
1121                                 node = add_node(scene,
1122                                                 b_engine,
1123                                                 b_data,
1124                                                 b_scene,
1125                                                 background,
1126                                                 graph,
1127                                                 b_ntree,
1128                                                 b_shader_node);
1129                         }
1130
1131                         if(node) {
1132                                 /* map node sockets for linking */
1133                                 for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
1134                                         ShaderInput *input = node_find_input_by_name(node, *b_node, *b_input);
1135                                         if(!input) {
1136                                                 /* XXX should not happen, report error? */
1137                                                 continue;
1138                                         }
1139                                         input_map[b_input->ptr.data] = input;
1140
1141                                         set_default_value(input, *b_input, b_data, b_ntree);
1142                                 }
1143                                 for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
1144                                         ShaderOutput *output = node_find_output_by_name(node, *b_node, *b_output);
1145                                         if(!output) {
1146                                                 /* XXX should not happen, report error? */
1147                                                 continue;
1148                                         }
1149                                         output_map[b_output->ptr.data] = output;
1150                                 }
1151                         }
1152                 }
1153         }
1154
1155         /* connect nodes */
1156         BL::NodeTree::links_iterator b_link;
1157
1158         for(b_ntree.links.begin(b_link); b_link != b_ntree.links.end(); ++b_link) {
1159                 /* Ignore invalid links to avoid unwanted cycles created in graph. */
1160                 if(!b_link->is_valid()) {
1161                         continue;
1162                 }
1163                 /* get blender link data */
1164                 BL::NodeSocket b_from_sock = b_link->from_socket();
1165                 BL::NodeSocket b_to_sock = b_link->to_socket();
1166
1167                 ShaderOutput *output = 0;
1168                 ShaderInput *input = 0;
1169
1170                 PtrOutputMap::iterator output_it = output_map.find(b_from_sock.ptr.data);
1171                 if(output_it != output_map.end())
1172                         output = output_it->second;
1173                 PtrInputMap::iterator input_it = input_map.find(b_to_sock.ptr.data);
1174                 if(input_it != input_map.end())
1175                         input = input_it->second;
1176
1177                 /* either node may be NULL when the node was not exported, typically
1178                  * because the node type is not supported */
1179                 if(output && input)
1180                         graph->connect(output, input);
1181         }
1182 }
1183
1184 static void add_nodes(Scene *scene,
1185                       BL::RenderEngine& b_engine,
1186                       BL::BlendData& b_data,
1187                       BL::Scene& b_scene,
1188                       const bool background,
1189                       ShaderGraph *graph,
1190                       BL::ShaderNodeTree& b_ntree)
1191 {
1192         static const ProxyMap empty_proxy_map;
1193         add_nodes(scene,
1194                   b_engine,
1195                   b_data,
1196                   b_scene,
1197                   background,
1198                   graph,
1199                   b_ntree,
1200                   empty_proxy_map,
1201                   empty_proxy_map);
1202 }
1203
1204 /* Sync Materials */
1205
1206 void BlenderSync::sync_materials(bool update_all)
1207 {
1208         shader_map.set_default(scene->default_surface);
1209
1210         /* material loop */
1211         BL::BlendData::materials_iterator b_mat;
1212
1213         TaskPool pool;
1214         set<Shader*> updated_shaders;
1215
1216         for(b_data.materials.begin(b_mat); b_mat != b_data.materials.end(); ++b_mat) {
1217                 Shader *shader;
1218
1219                 /* test if we need to sync */
1220                 if(shader_map.sync(&shader, *b_mat) || update_all) {
1221                         ShaderGraph *graph = new ShaderGraph();
1222
1223                         shader->name = b_mat->name().c_str();
1224                         shader->pass_id = b_mat->pass_index();
1225
1226                         /* create nodes */
1227                         if(b_mat->use_nodes() && b_mat->node_tree()) {
1228                                 BL::ShaderNodeTree b_ntree(b_mat->node_tree());
1229
1230                                 add_nodes(scene, b_engine, b_data, b_scene, !preview, graph, b_ntree);
1231                         }
1232                         else {
1233                                 DiffuseBsdfNode *diffuse = new DiffuseBsdfNode();
1234                                 diffuse->color = get_float3(b_mat->diffuse_color());
1235                                 graph->add(diffuse);
1236
1237                                 ShaderNode *out = graph->output();
1238                                 graph->connect(diffuse->output("BSDF"), out->input("Surface"));
1239                         }
1240
1241                         /* settings */
1242                         PointerRNA cmat = RNA_pointer_get(&b_mat->ptr, "cycles");
1243                         shader->use_mis = get_boolean(cmat, "sample_as_light");
1244                         shader->use_transparent_shadow = get_boolean(cmat, "use_transparent_shadow");
1245                         shader->heterogeneous_volume = !get_boolean(cmat, "homogeneous_volume");
1246                         shader->volume_sampling_method = get_volume_sampling(cmat);
1247                         shader->volume_interpolation_method = get_volume_interpolation(cmat);
1248                         shader->displacement_method = get_displacement_method(cmat);
1249
1250                         shader->set_graph(graph);
1251
1252                         /* By simplifying the shader graph as soon as possible, some
1253                          * redundant shader nodes might be removed which prevents loading
1254                          * unnecessary attributes later.
1255                          *
1256                          * However, since graph simplification also accounts for e.g. mix
1257                          * weight, this would cause frequent expensive resyncs in interactive
1258                          * sessions, so for those sessions optimization is only performed
1259                          * right before compiling.
1260                          */
1261                         if(!preview) {
1262                                 pool.push(function_bind(&ShaderGraph::simplify, graph, scene));
1263                                 /* NOTE: Update shaders out of the threads since those routines
1264                                  * are accessing and writing to a global context.
1265                                  */
1266                                 updated_shaders.insert(shader);
1267                         }
1268                         else {
1269                                 /* NOTE: Update tagging can access links which are being
1270                                  * optimized out.
1271                                  */
1272                                 shader->tag_update(scene);
1273                         }
1274                 }
1275         }
1276
1277         pool.wait_work();
1278
1279         foreach(Shader *shader, updated_shaders) {
1280                 shader->tag_update(scene);
1281         }
1282 }
1283
1284 /* Sync World */
1285
1286 void BlenderSync::sync_world(bool update_all)
1287 {
1288         Background *background = scene->background;
1289         Background prevbackground = *background;
1290
1291         BL::World b_world = b_scene.world();
1292
1293         if(world_recalc || update_all || b_world.ptr.data != world_map) {
1294                 Shader *shader = scene->default_background;
1295                 ShaderGraph *graph = new ShaderGraph();
1296
1297                 /* create nodes */
1298                 if(b_world && b_world.use_nodes() && b_world.node_tree()) {
1299                         BL::ShaderNodeTree b_ntree(b_world.node_tree());
1300
1301                         add_nodes(scene, b_engine, b_data, b_scene, !preview, graph, b_ntree);
1302
1303                         /* volume */
1304                         PointerRNA cworld = RNA_pointer_get(&b_world.ptr, "cycles");
1305                         shader->heterogeneous_volume = !get_boolean(cworld, "homogeneous_volume");
1306                         shader->volume_sampling_method = get_volume_sampling(cworld);
1307                         shader->volume_interpolation_method = get_volume_interpolation(cworld);
1308                 }
1309                 else if(b_world) {
1310                         BackgroundNode *background = new BackgroundNode();
1311                         background->color = get_float3(b_world.horizon_color());
1312                         graph->add(background);
1313
1314                         ShaderNode *out = graph->output();
1315                         graph->connect(background->output("Background"), out->input("Surface"));
1316                 }
1317
1318                 if(b_world) {
1319                         /* AO */
1320                         BL::WorldLighting b_light = b_world.light_settings();
1321
1322                         background->use_ao = b_light.use_ambient_occlusion();
1323                         background->ao_factor = b_light.ao_factor();
1324                         background->ao_distance = b_light.distance();
1325
1326                         /* visibility */
1327                         PointerRNA cvisibility = RNA_pointer_get(&b_world.ptr, "cycles_visibility");
1328                         uint visibility = 0;
1329
1330                         visibility |= get_boolean(cvisibility, "camera")? PATH_RAY_CAMERA: 0;
1331                         visibility |= get_boolean(cvisibility, "diffuse")? PATH_RAY_DIFFUSE: 0;
1332                         visibility |= get_boolean(cvisibility, "glossy")? PATH_RAY_GLOSSY: 0;
1333                         visibility |= get_boolean(cvisibility, "transmission")? PATH_RAY_TRANSMIT: 0;
1334                         visibility |= get_boolean(cvisibility, "scatter")? PATH_RAY_VOLUME_SCATTER: 0;
1335
1336                         background->visibility = visibility;
1337                 }
1338                 else {
1339                         background->use_ao = false;
1340                         background->ao_factor = 0.0f;
1341                         background->ao_distance = FLT_MAX;
1342                 }
1343
1344                 shader->set_graph(graph);
1345                 shader->tag_update(scene);
1346                 background->tag_update(scene);
1347         }
1348
1349         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
1350
1351         /* when doing preview render check for BI's transparency settings,
1352          * this is so because Blender's preview render routines are not able
1353          * to tweak all cycles's settings depending on different circumstances
1354          */
1355         if(b_engine.is_preview() == false)
1356                 background->transparent = get_boolean(cscene, "film_transparent");
1357         else
1358                 background->transparent = b_scene.render().alpha_mode() == BL::RenderSettings::alpha_mode_TRANSPARENT;
1359
1360         if(background->transparent) {
1361                 background->transparent_glass = get_boolean(cscene, "film_transparent_glass");
1362                 background->transparent_roughness_threshold = get_float(cscene, "film_transparent_roughness");
1363         }
1364         else {
1365                 background->transparent_glass = false;
1366                 background->transparent_roughness_threshold = 0.0f;
1367         }
1368
1369         background->use_shader = render_layer.use_background_shader;
1370         background->use_ao = background->use_ao && render_layer.use_background_ao;
1371
1372         if(background->modified(prevbackground))
1373                 background->tag_update(scene);
1374 }
1375
1376 /* Sync Lamps */
1377
1378 void BlenderSync::sync_lamps(bool update_all)
1379 {
1380         shader_map.set_default(scene->default_light);
1381
1382         /* lamp loop */
1383         BL::BlendData::lamps_iterator b_lamp;
1384
1385         for(b_data.lamps.begin(b_lamp); b_lamp != b_data.lamps.end(); ++b_lamp) {
1386                 Shader *shader;
1387
1388                 /* test if we need to sync */
1389                 if(shader_map.sync(&shader, *b_lamp) || update_all) {
1390                         ShaderGraph *graph = new ShaderGraph();
1391
1392                         /* create nodes */
1393                         if(b_lamp->use_nodes() && b_lamp->node_tree()) {
1394                                 shader->name = b_lamp->name().c_str();
1395
1396                                 BL::ShaderNodeTree b_ntree(b_lamp->node_tree());
1397
1398                                 add_nodes(scene, b_engine, b_data, b_scene, !preview, graph, b_ntree);
1399                         }
1400                         else {
1401                                 float strength = 1.0f;
1402
1403                                 if(b_lamp->type() == BL::Lamp::type_POINT ||
1404                                    b_lamp->type() == BL::Lamp::type_SPOT ||
1405                                    b_lamp->type() == BL::Lamp::type_AREA)
1406                                 {
1407                                         strength = 100.0f;
1408                                 }
1409
1410                                 EmissionNode *emission = new EmissionNode();
1411                                 emission->color = get_float3(b_lamp->color());
1412                                 emission->strength = strength;
1413                                 graph->add(emission);
1414
1415                                 ShaderNode *out = graph->output();
1416                                 graph->connect(emission->output("Emission"), out->input("Surface"));
1417                         }
1418
1419                         shader->set_graph(graph);
1420                         shader->tag_update(scene);
1421                 }
1422         }
1423 }
1424
1425 void BlenderSync::sync_shaders()
1426 {
1427         /* for auto refresh images */
1428         bool auto_refresh_update = false;
1429
1430         if(preview) {
1431                 ImageManager *image_manager = scene->image_manager;
1432                 int frame = b_scene.frame_current();
1433                 auto_refresh_update = image_manager->set_animation_frame_update(frame);
1434         }
1435
1436         shader_map.pre_sync();
1437
1438         sync_world(auto_refresh_update);
1439         sync_lamps(auto_refresh_update);
1440         sync_materials(auto_refresh_update);
1441
1442         /* false = don't delete unused shaders, not supported */
1443         shader_map.post_sync(false);
1444 }
1445
1446 CCL_NAMESPACE_END
1447