Cycles: add Principled Volume shader.
[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_ShaderNodeVolumePrincipled)) {
570                 PrincipledVolumeNode *principled = new PrincipledVolumeNode();
571                 node = principled;
572         }
573         else if(b_node.is_a(&RNA_ShaderNodeNewGeometry)) {
574                 node = new GeometryNode();
575         }
576         else if(b_node.is_a(&RNA_ShaderNodeWireframe)) {
577                 BL::ShaderNodeWireframe b_wireframe_node(b_node);
578                 WireframeNode *wire = new WireframeNode();
579                 wire->use_pixel_size = b_wireframe_node.use_pixel_size();
580                 node = wire;
581         }
582         else if(b_node.is_a(&RNA_ShaderNodeWavelength)) {
583                 node = new WavelengthNode();
584         }
585         else if(b_node.is_a(&RNA_ShaderNodeBlackbody)) {
586                 node = new BlackbodyNode();
587         }
588         else if(b_node.is_a(&RNA_ShaderNodeLightPath)) {
589                 node = new LightPathNode();
590         }
591         else if(b_node.is_a(&RNA_ShaderNodeLightFalloff)) {
592                 node = new LightFalloffNode();
593         }
594         else if(b_node.is_a(&RNA_ShaderNodeObjectInfo)) {
595                 node = new ObjectInfoNode();
596         }
597         else if(b_node.is_a(&RNA_ShaderNodeParticleInfo)) {
598                 node = new ParticleInfoNode();
599         }
600         else if(b_node.is_a(&RNA_ShaderNodeHairInfo)) {
601                 node = new HairInfoNode();
602         }
603         else if(b_node.is_a(&RNA_ShaderNodeBump)) {
604                 BL::ShaderNodeBump b_bump_node(b_node);
605                 BumpNode *bump = new BumpNode();
606                 bump->invert = b_bump_node.invert();
607                 node = bump;
608         }
609         else if(b_node.is_a(&RNA_ShaderNodeScript)) {
610 #ifdef WITH_OSL
611                 if(scene->shader_manager->use_osl()) {
612                         /* create script node */
613                         BL::ShaderNodeScript b_script_node(b_node);
614
615                         OSLShaderManager *manager = (OSLShaderManager*)scene->shader_manager;
616                         string bytecode_hash = b_script_node.bytecode_hash();
617
618                         if(!bytecode_hash.empty()) {
619                                 node = manager->osl_node("", bytecode_hash, b_script_node.bytecode());
620                         }
621                         else {
622                                 string absolute_filepath = blender_absolute_path(b_data, b_ntree, b_script_node.filepath());
623                                 node = manager->osl_node(absolute_filepath, "");
624                         }
625                 }
626 #else
627                 (void)b_data;
628                 (void)b_ntree;
629 #endif
630         }
631         else if(b_node.is_a(&RNA_ShaderNodeTexImage)) {
632                 BL::ShaderNodeTexImage b_image_node(b_node);
633                 BL::Image b_image(b_image_node.image());
634                 BL::ImageUser b_image_user(b_image_node.image_user());
635                 ImageTextureNode *image = new ImageTextureNode();
636                 if(b_image) {
637                         /* builtin images will use callback-based reading because
638                          * they could only be loaded correct from blender side
639                          */
640                         bool is_builtin = b_image.packed_file() ||
641                                           b_image.source() == BL::Image::source_GENERATED ||
642                                           b_image.source() == BL::Image::source_MOVIE ||
643                                           (b_engine.is_preview() &&
644                                            b_image.source() != BL::Image::source_SEQUENCE);
645
646                         if(is_builtin) {
647                                 /* for builtin images we're using image datablock name to find an image to
648                                  * read pixels from later
649                                  *
650                                  * also store frame number as well, so there's no differences in handling
651                                  * builtin names for packed images and movies
652                                  */
653                                 int scene_frame = b_scene.frame_current();
654                                 int image_frame = image_user_frame_number(b_image_user,
655                                                                           scene_frame);
656                                 image->filename = b_image.name() + "@" + string_printf("%d", image_frame);
657                                 image->builtin_data = b_image.ptr.data;
658                         }
659                         else {
660                                 image->filename = image_user_file_path(b_image_user,
661                                                                        b_image,
662                                                                        b_scene.frame_current());
663                                 image->builtin_data = NULL;
664                         }
665
666                         image->animated = b_image_node.image_user().use_auto_refresh();
667                         image->use_alpha = b_image.use_alpha();
668
669                         /* TODO(sergey): Does not work properly when we change builtin type. */
670                         if(b_image.is_updated()) {
671                                 scene->image_manager->tag_reload_image(
672                                         image->filename.string(),
673                                         image->builtin_data,
674                                         get_image_interpolation(b_image_node),
675                                         get_image_extension(b_image_node),
676                                         image->use_alpha);
677                         }
678                 }
679                 image->color_space = (NodeImageColorSpace)b_image_node.color_space();
680                 image->projection = (NodeImageProjection)b_image_node.projection();
681                 image->interpolation = get_image_interpolation(b_image_node);
682                 image->extension = get_image_extension(b_image_node);
683                 image->projection_blend = b_image_node.projection_blend();
684                 BL::TexMapping b_texture_mapping(b_image_node.texture_mapping());
685                 get_tex_mapping(&image->tex_mapping, b_texture_mapping);
686                 node = image;
687         }
688         else if(b_node.is_a(&RNA_ShaderNodeTexEnvironment)) {
689                 BL::ShaderNodeTexEnvironment b_env_node(b_node);
690                 BL::Image b_image(b_env_node.image());
691                 BL::ImageUser b_image_user(b_env_node.image_user());
692                 EnvironmentTextureNode *env = new EnvironmentTextureNode();
693                 if(b_image) {
694                         bool is_builtin = b_image.packed_file() ||
695                                           b_image.source() == BL::Image::source_GENERATED ||
696                                           b_image.source() == BL::Image::source_MOVIE ||
697                                           (b_engine.is_preview() &&
698                                            b_image.source() != BL::Image::source_SEQUENCE);
699
700                         if(is_builtin) {
701                                 int scene_frame = b_scene.frame_current();
702                                 int image_frame = image_user_frame_number(b_image_user,
703                                                                           scene_frame);
704                                 env->filename = b_image.name() + "@" + string_printf("%d", image_frame);
705                                 env->builtin_data = b_image.ptr.data;
706                         }
707                         else {
708                                 env->filename = image_user_file_path(b_image_user,
709                                                                      b_image,
710                                                                      b_scene.frame_current());
711                                 env->builtin_data = NULL;
712                         }
713
714                         env->animated = b_env_node.image_user().use_auto_refresh();
715                         env->use_alpha = b_image.use_alpha();
716
717                         /* TODO(sergey): Does not work properly when we change builtin type. */
718                         if(b_image.is_updated()) {
719                                 scene->image_manager->tag_reload_image(
720                                         env->filename.string(),
721                                         env->builtin_data,
722                                         get_image_interpolation(b_env_node),
723                                         EXTENSION_REPEAT,
724                                         env->use_alpha);
725                         }
726                 }
727                 env->color_space = (NodeImageColorSpace)b_env_node.color_space();
728                 env->interpolation = get_image_interpolation(b_env_node);
729                 env->projection = (NodeEnvironmentProjection)b_env_node.projection();
730                 BL::TexMapping b_texture_mapping(b_env_node.texture_mapping());
731                 get_tex_mapping(&env->tex_mapping, b_texture_mapping);
732                 node = env;
733         }
734         else if(b_node.is_a(&RNA_ShaderNodeTexGradient)) {
735                 BL::ShaderNodeTexGradient b_gradient_node(b_node);
736                 GradientTextureNode *gradient = new GradientTextureNode();
737                 gradient->type = (NodeGradientType)b_gradient_node.gradient_type();
738                 BL::TexMapping b_texture_mapping(b_gradient_node.texture_mapping());
739                 get_tex_mapping(&gradient->tex_mapping, b_texture_mapping);
740                 node = gradient;
741         }
742         else if(b_node.is_a(&RNA_ShaderNodeTexVoronoi)) {
743                 BL::ShaderNodeTexVoronoi b_voronoi_node(b_node);
744                 VoronoiTextureNode *voronoi = new VoronoiTextureNode();
745                 voronoi->coloring = (NodeVoronoiColoring)b_voronoi_node.coloring();
746                 BL::TexMapping b_texture_mapping(b_voronoi_node.texture_mapping());
747                 get_tex_mapping(&voronoi->tex_mapping, b_texture_mapping);
748                 node = voronoi;
749         }
750         else if(b_node.is_a(&RNA_ShaderNodeTexMagic)) {
751                 BL::ShaderNodeTexMagic b_magic_node(b_node);
752                 MagicTextureNode *magic = new MagicTextureNode();
753                 magic->depth = b_magic_node.turbulence_depth();
754                 BL::TexMapping b_texture_mapping(b_magic_node.texture_mapping());
755                 get_tex_mapping(&magic->tex_mapping, b_texture_mapping);
756                 node = magic;
757         }
758         else if(b_node.is_a(&RNA_ShaderNodeTexWave)) {
759                 BL::ShaderNodeTexWave b_wave_node(b_node);
760                 WaveTextureNode *wave = new WaveTextureNode();
761                 wave->type = (NodeWaveType)b_wave_node.wave_type();
762                 wave->profile = (NodeWaveProfile)b_wave_node.wave_profile();
763                 BL::TexMapping b_texture_mapping(b_wave_node.texture_mapping());
764                 get_tex_mapping(&wave->tex_mapping, b_texture_mapping);
765                 node = wave;
766         }
767         else if(b_node.is_a(&RNA_ShaderNodeTexChecker)) {
768                 BL::ShaderNodeTexChecker b_checker_node(b_node);
769                 CheckerTextureNode *checker = new CheckerTextureNode();
770                 BL::TexMapping b_texture_mapping(b_checker_node.texture_mapping());
771                 get_tex_mapping(&checker->tex_mapping, b_texture_mapping);
772                 node = checker;
773         }
774         else if(b_node.is_a(&RNA_ShaderNodeTexBrick)) {
775                 BL::ShaderNodeTexBrick b_brick_node(b_node);
776                 BrickTextureNode *brick = new BrickTextureNode();
777                 brick->offset = b_brick_node.offset();
778                 brick->offset_frequency = b_brick_node.offset_frequency();
779                 brick->squash = b_brick_node.squash();
780                 brick->squash_frequency = b_brick_node.squash_frequency();
781                 BL::TexMapping b_texture_mapping(b_brick_node.texture_mapping());
782                 get_tex_mapping(&brick->tex_mapping, b_texture_mapping);
783                 node = brick;
784         }
785         else if(b_node.is_a(&RNA_ShaderNodeTexNoise)) {
786                 BL::ShaderNodeTexNoise b_noise_node(b_node);
787                 NoiseTextureNode *noise = new NoiseTextureNode();
788                 BL::TexMapping b_texture_mapping(b_noise_node.texture_mapping());
789                 get_tex_mapping(&noise->tex_mapping, b_texture_mapping);
790                 node = noise;
791         }
792         else if(b_node.is_a(&RNA_ShaderNodeTexMusgrave)) {
793                 BL::ShaderNodeTexMusgrave b_musgrave_node(b_node);
794                 MusgraveTextureNode *musgrave = new MusgraveTextureNode();
795                 musgrave->type = (NodeMusgraveType)b_musgrave_node.musgrave_type();
796                 BL::TexMapping b_texture_mapping(b_musgrave_node.texture_mapping());
797                 get_tex_mapping(&musgrave->tex_mapping, b_texture_mapping);
798                 node = musgrave;
799         }
800         else if(b_node.is_a(&RNA_ShaderNodeTexCoord)) {
801                 BL::ShaderNodeTexCoord b_tex_coord_node(b_node);
802                 TextureCoordinateNode *tex_coord = new TextureCoordinateNode();
803                 tex_coord->from_dupli = b_tex_coord_node.from_dupli();
804                 if(b_tex_coord_node.object()) {
805                         tex_coord->use_transform = true;
806                         tex_coord->ob_tfm = get_transform(b_tex_coord_node.object().matrix_world());
807                 }
808                 node = tex_coord;
809         }
810         else if(b_node.is_a(&RNA_ShaderNodeTexSky)) {
811                 BL::ShaderNodeTexSky b_sky_node(b_node);
812                 SkyTextureNode *sky = new SkyTextureNode();
813                 sky->type = (NodeSkyType)b_sky_node.sky_type();
814                 sky->sun_direction = normalize(get_float3(b_sky_node.sun_direction()));
815                 sky->turbidity = b_sky_node.turbidity();
816                 sky->ground_albedo = b_sky_node.ground_albedo();
817                 BL::TexMapping b_texture_mapping(b_sky_node.texture_mapping());
818                 get_tex_mapping(&sky->tex_mapping, b_texture_mapping);
819                 node = sky;
820         }
821         else if(b_node.is_a(&RNA_ShaderNodeNormalMap)) {
822                 BL::ShaderNodeNormalMap b_normal_map_node(b_node);
823                 NormalMapNode *nmap = new NormalMapNode();
824                 nmap->space = (NodeNormalMapSpace)b_normal_map_node.space();
825                 nmap->attribute = b_normal_map_node.uv_map();
826                 node = nmap;
827         }
828         else if(b_node.is_a(&RNA_ShaderNodeTangent)) {
829                 BL::ShaderNodeTangent b_tangent_node(b_node);
830                 TangentNode *tangent = new TangentNode();
831                 tangent->direction_type = (NodeTangentDirectionType)b_tangent_node.direction_type();
832                 tangent->axis = (NodeTangentAxis)b_tangent_node.axis();
833                 tangent->attribute = b_tangent_node.uv_map();
834                 node = tangent;
835         }
836         else if(b_node.is_a(&RNA_ShaderNodeUVMap)) {
837                 BL::ShaderNodeUVMap b_uvmap_node(b_node);
838                 UVMapNode *uvm = new UVMapNode();
839                 uvm->attribute = b_uvmap_node.uv_map();
840                 uvm->from_dupli = b_uvmap_node.from_dupli();
841                 node = uvm;
842         }
843         else if(b_node.is_a(&RNA_ShaderNodeTexPointDensity)) {
844                 BL::ShaderNodeTexPointDensity b_point_density_node(b_node);
845                 PointDensityTextureNode *point_density = new PointDensityTextureNode();
846                 point_density->filename = b_point_density_node.name();
847                 point_density->space = (NodeTexVoxelSpace)b_point_density_node.space();
848                 point_density->interpolation = get_image_interpolation(b_point_density_node);
849                 point_density->builtin_data = b_point_density_node.ptr.data;
850
851                 /* 1 - render settings, 0 - vewport settings. */
852                 int settings = background ? 1 : 0;
853
854                 /* TODO(sergey): Use more proper update flag. */
855                 if(true) {
856                         b_point_density_node.cache_point_density(b_scene, settings);
857                         scene->image_manager->tag_reload_image(
858                                 point_density->filename.string(),
859                                 point_density->builtin_data,
860                                 point_density->interpolation,
861                                 EXTENSION_CLIP,
862                                 true);
863                 }
864                 node = point_density;
865
866                 /* Transformation form world space to texture space.
867                  *
868                  * NOTE: Do this after the texture is cached, this is because getting
869                  * min/max will need to access this cache.
870                  */
871                 BL::Object b_ob(b_point_density_node.object());
872                 if(b_ob) {
873                         float3 loc, size;
874                         point_density_texture_space(b_scene,
875                                                     b_point_density_node,
876                                                     settings,
877                                                     loc,
878                                                     size);
879                         point_density->tfm =
880                                 transform_translate(-loc) * transform_scale(size) *
881                                 transform_inverse(get_transform(b_ob.matrix_world()));
882                 }
883         }
884         else if(b_node.is_a(&RNA_ShaderNodeBevel)) {
885                 BL::ShaderNodeBevel b_bevel_node(b_node);
886                 BevelNode *bevel = new BevelNode();
887                 bevel->samples = b_bevel_node.samples();
888                 node = bevel;
889         }
890         else if(b_node.is_a(&RNA_ShaderNodeDisplacement)) {
891                 BL::ShaderNodeDisplacement b_disp_node(b_node);
892                 DisplacementNode *disp = new DisplacementNode();
893                 disp->space = (NodeNormalMapSpace)b_disp_node.space();
894                 node = disp;
895         }
896         else if(b_node.is_a(&RNA_ShaderNodeVectorDisplacement)) {
897                 BL::ShaderNodeVectorDisplacement b_disp_node(b_node);
898                 VectorDisplacementNode *disp = new VectorDisplacementNode();
899                 disp->space = (NodeNormalMapSpace)b_disp_node.space();
900                 disp->attribute = "";
901                 node = disp;
902         }
903
904         if(node) {
905                 node->name = b_node.name();
906                 graph->add(node);
907         }
908
909         return node;
910 }
911
912 static bool node_use_modified_socket_name(ShaderNode *node)
913 {
914         if(node->special_type == SHADER_SPECIAL_TYPE_SCRIPT)
915                 return false;
916
917         return true;
918 }
919
920 static ShaderInput *node_find_input_by_name(ShaderNode *node,
921                                             BL::Node& b_node,
922                                             BL::NodeSocket& b_socket)
923 {
924         string name = b_socket.name();
925         
926         if(node_use_modified_socket_name(node)) {
927                 BL::Node::inputs_iterator b_input;
928                 bool found = false;
929                 int counter = 0, total = 0;
930
931                 for(b_node.inputs.begin(b_input); b_input != b_node.inputs.end(); ++b_input) {
932                         if(b_input->name() == name) {
933                                 if(!found)
934                                         counter++;
935                                 total++;
936                         }
937
938                         if(b_input->ptr.data == b_socket.ptr.data)
939                                 found = true;
940                 }
941
942                 /* rename if needed */
943                 if(name == "Shader")
944                         name = "Closure";
945
946                 if(total > 1)
947                         name = string_printf("%s%d", name.c_str(), counter);
948         }
949
950         return node->input(name.c_str());
951 }
952
953 static ShaderOutput *node_find_output_by_name(ShaderNode *node,
954                                               BL::Node& b_node,
955                                               BL::NodeSocket& b_socket)
956 {
957         string name = b_socket.name();
958
959         if(node_use_modified_socket_name(node)) {
960                 BL::Node::outputs_iterator b_output;
961                 bool found = false;
962                 int counter = 0, total = 0;
963
964                 for(b_node.outputs.begin(b_output); b_output != b_node.outputs.end(); ++b_output) {
965                         if(b_output->name() == name) {
966                                 if(!found)
967                                         counter++;
968                                 total++;
969                         }
970
971                         if(b_output->ptr.data == b_socket.ptr.data)
972                                 found = true;
973                 }
974
975                 /* rename if needed */
976                 if(name == "Shader")
977                         name = "Closure";
978
979                 if(total > 1)
980                         name = string_printf("%s%d", name.c_str(), counter);
981         }
982
983         return node->output(name.c_str());
984 }
985
986 static void add_nodes(Scene *scene,
987                       BL::RenderEngine& b_engine,
988                       BL::BlendData& b_data,
989                       BL::Scene& b_scene,
990                       const bool background,
991                       ShaderGraph *graph,
992                       BL::ShaderNodeTree& b_ntree,
993                       const ProxyMap &proxy_input_map,
994                       const ProxyMap &proxy_output_map)
995 {
996         /* add nodes */
997         BL::ShaderNodeTree::nodes_iterator b_node;
998         PtrInputMap input_map;
999         PtrOutputMap output_map;
1000
1001         BL::Node::inputs_iterator b_input;
1002         BL::Node::outputs_iterator b_output;
1003
1004         /* find the node to use for output if there are multiple */
1005         bool found_active_output = false;
1006         BL::ShaderNode output_node(PointerRNA_NULL);
1007
1008         for(b_ntree.nodes.begin(b_node); b_node != b_ntree.nodes.end(); ++b_node) {
1009                 if(is_output_node(*b_node)) {
1010                         BL::ShaderNodeOutputMaterial b_output_node(*b_node);
1011
1012                         if(b_output_node.is_active_output()) {
1013                                 output_node = b_output_node;
1014                                 found_active_output = true;
1015                                 break;
1016                         }
1017                         else if(!output_node.ptr.data && !found_active_output) {
1018                                 output_node = b_output_node;
1019                         }
1020                 }
1021         }
1022
1023         /* add nodes */
1024         for(b_ntree.nodes.begin(b_node); b_node != b_ntree.nodes.end(); ++b_node) {
1025                 if(b_node->mute() || b_node->is_a(&RNA_NodeReroute)) {
1026                         /* replace muted node with internal links */
1027                         BL::Node::internal_links_iterator b_link;
1028                         for(b_node->internal_links.begin(b_link); b_link != b_node->internal_links.end(); ++b_link) {
1029                                 BL::NodeSocket to_socket(b_link->to_socket());
1030                                 SocketType::Type to_socket_type = convert_socket_type(to_socket);
1031                                 if (to_socket_type == SocketType::UNDEFINED) {
1032                                         continue;
1033                                 }
1034
1035                                 ConvertNode *proxy = new ConvertNode(to_socket_type, to_socket_type, true);
1036
1037                                 input_map[b_link->from_socket().ptr.data] = proxy->inputs[0];
1038                                 output_map[b_link->to_socket().ptr.data] = proxy->outputs[0];
1039
1040                                 graph->add(proxy);
1041                         }
1042                 }
1043                 else if(b_node->is_a(&RNA_ShaderNodeGroup) || b_node->is_a(&RNA_NodeCustomGroup)) {
1044                         
1045                         BL::ShaderNodeTree b_group_ntree(PointerRNA_NULL);
1046                         if(b_node->is_a(&RNA_ShaderNodeGroup))
1047                                 b_group_ntree = BL::ShaderNodeTree(((BL::NodeGroup)(*b_node)).node_tree());
1048                         else
1049                                 b_group_ntree = BL::ShaderNodeTree(((BL::NodeCustomGroup)(*b_node)).node_tree());
1050                         ProxyMap group_proxy_input_map, group_proxy_output_map;
1051
1052                         /* Add a proxy node for each socket
1053                          * Do this even if the node group has no internal tree,
1054                          * so that links have something to connect to and assert won't fail.
1055                          */
1056                         for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
1057                                 SocketType::Type input_type = convert_socket_type(*b_input);
1058                                 if (input_type == SocketType::UNDEFINED) {
1059                                         continue;
1060                                 }
1061
1062                                 ConvertNode *proxy = new ConvertNode(input_type, input_type, true);
1063                                 graph->add(proxy);
1064
1065                                 /* register the proxy node for internal binding */
1066                                 group_proxy_input_map[b_input->identifier()] = proxy;
1067
1068                                 input_map[b_input->ptr.data] = proxy->inputs[0];
1069
1070                                 set_default_value(proxy->inputs[0], *b_input, b_data, b_ntree);
1071                         }
1072                         for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
1073                                 SocketType::Type output_type = convert_socket_type(*b_output);
1074                                 if (output_type == SocketType::UNDEFINED) {
1075                                         continue;
1076                                 }
1077
1078                                 ConvertNode *proxy = new ConvertNode(output_type, output_type, true);
1079                                 graph->add(proxy);
1080
1081                                 /* register the proxy node for internal binding */
1082                                 group_proxy_output_map[b_output->identifier()] = proxy;
1083
1084                                 output_map[b_output->ptr.data] = proxy->outputs[0];
1085                         }
1086                         
1087                         if(b_group_ntree) {
1088                                 add_nodes(scene,
1089                                           b_engine,
1090                                           b_data,
1091                                           b_scene,
1092                                           background,
1093                                           graph,
1094                                           b_group_ntree,
1095                                           group_proxy_input_map,
1096                                           group_proxy_output_map);
1097                         }
1098                 }
1099                 else if(b_node->is_a(&RNA_NodeGroupInput)) {
1100                         /* map each socket to a proxy node */
1101                         for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
1102                                 ProxyMap::const_iterator proxy_it = proxy_input_map.find(b_output->identifier());
1103                                 if(proxy_it != proxy_input_map.end()) {
1104                                         ConvertNode *proxy = proxy_it->second;
1105
1106                                         output_map[b_output->ptr.data] = proxy->outputs[0];
1107                                 }
1108                         }
1109                 }
1110                 else if(b_node->is_a(&RNA_NodeGroupOutput)) {
1111                         BL::NodeGroupOutput b_output_node(*b_node);
1112                         /* only the active group output is used */
1113                         if(b_output_node.is_active_output()) {
1114                                 /* map each socket to a proxy node */
1115                                 for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
1116                                         ProxyMap::const_iterator proxy_it = proxy_output_map.find(b_input->identifier());
1117                                         if(proxy_it != proxy_output_map.end()) {
1118                                                 ConvertNode *proxy = proxy_it->second;
1119
1120                                                 input_map[b_input->ptr.data] = proxy->inputs[0];
1121
1122                                                 set_default_value(proxy->inputs[0], *b_input, b_data, b_ntree);
1123                                         }
1124                                 }
1125                         }
1126                 }
1127                 else {
1128                         ShaderNode *node = NULL;
1129
1130                         if(is_output_node(*b_node)) {
1131                                 if(b_node->ptr.data == output_node.ptr.data) {
1132                                         node = graph->output();
1133                                 }
1134                         }
1135                         else {
1136                                 BL::ShaderNode b_shader_node(*b_node);
1137                                 node = add_node(scene,
1138                                                 b_engine,
1139                                                 b_data,
1140                                                 b_scene,
1141                                                 background,
1142                                                 graph,
1143                                                 b_ntree,
1144                                                 b_shader_node);
1145                         }
1146
1147                         if(node) {
1148                                 /* map node sockets for linking */
1149                                 for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
1150                                         ShaderInput *input = node_find_input_by_name(node, *b_node, *b_input);
1151                                         if(!input) {
1152                                                 /* XXX should not happen, report error? */
1153                                                 continue;
1154                                         }
1155                                         input_map[b_input->ptr.data] = input;
1156
1157                                         set_default_value(input, *b_input, b_data, b_ntree);
1158                                 }
1159                                 for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
1160                                         ShaderOutput *output = node_find_output_by_name(node, *b_node, *b_output);
1161                                         if(!output) {
1162                                                 /* XXX should not happen, report error? */
1163                                                 continue;
1164                                         }
1165                                         output_map[b_output->ptr.data] = output;
1166                                 }
1167                         }
1168                 }
1169         }
1170
1171         /* connect nodes */
1172         BL::NodeTree::links_iterator b_link;
1173
1174         for(b_ntree.links.begin(b_link); b_link != b_ntree.links.end(); ++b_link) {
1175                 /* Ignore invalid links to avoid unwanted cycles created in graph. */
1176                 if(!b_link->is_valid()) {
1177                         continue;
1178                 }
1179                 /* get blender link data */
1180                 BL::NodeSocket b_from_sock = b_link->from_socket();
1181                 BL::NodeSocket b_to_sock = b_link->to_socket();
1182
1183                 ShaderOutput *output = 0;
1184                 ShaderInput *input = 0;
1185
1186                 PtrOutputMap::iterator output_it = output_map.find(b_from_sock.ptr.data);
1187                 if(output_it != output_map.end())
1188                         output = output_it->second;
1189                 PtrInputMap::iterator input_it = input_map.find(b_to_sock.ptr.data);
1190                 if(input_it != input_map.end())
1191                         input = input_it->second;
1192
1193                 /* either node may be NULL when the node was not exported, typically
1194                  * because the node type is not supported */
1195                 if(output && input)
1196                         graph->connect(output, input);
1197         }
1198 }
1199
1200 static void add_nodes(Scene *scene,
1201                       BL::RenderEngine& b_engine,
1202                       BL::BlendData& b_data,
1203                       BL::Scene& b_scene,
1204                       const bool background,
1205                       ShaderGraph *graph,
1206                       BL::ShaderNodeTree& b_ntree)
1207 {
1208         static const ProxyMap empty_proxy_map;
1209         add_nodes(scene,
1210                   b_engine,
1211                   b_data,
1212                   b_scene,
1213                   background,
1214                   graph,
1215                   b_ntree,
1216                   empty_proxy_map,
1217                   empty_proxy_map);
1218 }
1219
1220 /* Sync Materials */
1221
1222 void BlenderSync::sync_materials(bool update_all)
1223 {
1224         shader_map.set_default(scene->default_surface);
1225
1226         /* material loop */
1227         BL::BlendData::materials_iterator b_mat;
1228
1229         TaskPool pool;
1230         set<Shader*> updated_shaders;
1231
1232         for(b_data.materials.begin(b_mat); b_mat != b_data.materials.end(); ++b_mat) {
1233                 Shader *shader;
1234
1235                 /* test if we need to sync */
1236                 if(shader_map.sync(&shader, *b_mat) || update_all) {
1237                         ShaderGraph *graph = new ShaderGraph();
1238
1239                         shader->name = b_mat->name().c_str();
1240                         shader->pass_id = b_mat->pass_index();
1241
1242                         /* create nodes */
1243                         if(b_mat->use_nodes() && b_mat->node_tree()) {
1244                                 BL::ShaderNodeTree b_ntree(b_mat->node_tree());
1245
1246                                 add_nodes(scene, b_engine, b_data, b_scene, !preview, graph, b_ntree);
1247                         }
1248                         else {
1249                                 DiffuseBsdfNode *diffuse = new DiffuseBsdfNode();
1250                                 diffuse->color = get_float3(b_mat->diffuse_color());
1251                                 graph->add(diffuse);
1252
1253                                 ShaderNode *out = graph->output();
1254                                 graph->connect(diffuse->output("BSDF"), out->input("Surface"));
1255                         }
1256
1257                         /* settings */
1258                         PointerRNA cmat = RNA_pointer_get(&b_mat->ptr, "cycles");
1259                         shader->use_mis = get_boolean(cmat, "sample_as_light");
1260                         shader->use_transparent_shadow = get_boolean(cmat, "use_transparent_shadow");
1261                         shader->heterogeneous_volume = !get_boolean(cmat, "homogeneous_volume");
1262                         shader->volume_sampling_method = get_volume_sampling(cmat);
1263                         shader->volume_interpolation_method = get_volume_interpolation(cmat);
1264                         shader->displacement_method = get_displacement_method(cmat);
1265
1266                         shader->set_graph(graph);
1267
1268                         /* By simplifying the shader graph as soon as possible, some
1269                          * redundant shader nodes might be removed which prevents loading
1270                          * unnecessary attributes later.
1271                          *
1272                          * However, since graph simplification also accounts for e.g. mix
1273                          * weight, this would cause frequent expensive resyncs in interactive
1274                          * sessions, so for those sessions optimization is only performed
1275                          * right before compiling.
1276                          */
1277                         if(!preview) {
1278                                 pool.push(function_bind(&ShaderGraph::simplify, graph, scene));
1279                                 /* NOTE: Update shaders out of the threads since those routines
1280                                  * are accessing and writing to a global context.
1281                                  */
1282                                 updated_shaders.insert(shader);
1283                         }
1284                         else {
1285                                 /* NOTE: Update tagging can access links which are being
1286                                  * optimized out.
1287                                  */
1288                                 shader->tag_update(scene);
1289                         }
1290                 }
1291         }
1292
1293         pool.wait_work();
1294
1295         foreach(Shader *shader, updated_shaders) {
1296                 shader->tag_update(scene);
1297         }
1298 }
1299
1300 /* Sync World */
1301
1302 void BlenderSync::sync_world(bool update_all)
1303 {
1304         Background *background = scene->background;
1305         Background prevbackground = *background;
1306
1307         BL::World b_world = b_scene.world();
1308
1309         if(world_recalc || update_all || b_world.ptr.data != world_map) {
1310                 Shader *shader = scene->default_background;
1311                 ShaderGraph *graph = new ShaderGraph();
1312
1313                 /* create nodes */
1314                 if(b_world && b_world.use_nodes() && b_world.node_tree()) {
1315                         BL::ShaderNodeTree b_ntree(b_world.node_tree());
1316
1317                         add_nodes(scene, b_engine, b_data, b_scene, !preview, graph, b_ntree);
1318
1319                         /* volume */
1320                         PointerRNA cworld = RNA_pointer_get(&b_world.ptr, "cycles");
1321                         shader->heterogeneous_volume = !get_boolean(cworld, "homogeneous_volume");
1322                         shader->volume_sampling_method = get_volume_sampling(cworld);
1323                         shader->volume_interpolation_method = get_volume_interpolation(cworld);
1324                 }
1325                 else if(b_world) {
1326                         BackgroundNode *background = new BackgroundNode();
1327                         background->color = get_float3(b_world.horizon_color());
1328                         graph->add(background);
1329
1330                         ShaderNode *out = graph->output();
1331                         graph->connect(background->output("Background"), out->input("Surface"));
1332                 }
1333
1334                 if(b_world) {
1335                         /* AO */
1336                         BL::WorldLighting b_light = b_world.light_settings();
1337
1338                         background->use_ao = b_light.use_ambient_occlusion();
1339                         background->ao_factor = b_light.ao_factor();
1340                         background->ao_distance = b_light.distance();
1341
1342                         /* visibility */
1343                         PointerRNA cvisibility = RNA_pointer_get(&b_world.ptr, "cycles_visibility");
1344                         uint visibility = 0;
1345
1346                         visibility |= get_boolean(cvisibility, "camera")? PATH_RAY_CAMERA: 0;
1347                         visibility |= get_boolean(cvisibility, "diffuse")? PATH_RAY_DIFFUSE: 0;
1348                         visibility |= get_boolean(cvisibility, "glossy")? PATH_RAY_GLOSSY: 0;
1349                         visibility |= get_boolean(cvisibility, "transmission")? PATH_RAY_TRANSMIT: 0;
1350                         visibility |= get_boolean(cvisibility, "scatter")? PATH_RAY_VOLUME_SCATTER: 0;
1351
1352                         background->visibility = visibility;
1353                 }
1354                 else {
1355                         background->use_ao = false;
1356                         background->ao_factor = 0.0f;
1357                         background->ao_distance = FLT_MAX;
1358                 }
1359
1360                 shader->set_graph(graph);
1361                 shader->tag_update(scene);
1362                 background->tag_update(scene);
1363         }
1364
1365         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
1366
1367         /* when doing preview render check for BI's transparency settings,
1368          * this is so because Blender's preview render routines are not able
1369          * to tweak all cycles's settings depending on different circumstances
1370          */
1371         if(b_engine.is_preview() == false)
1372                 background->transparent = get_boolean(cscene, "film_transparent");
1373         else
1374                 background->transparent = b_scene.render().alpha_mode() == BL::RenderSettings::alpha_mode_TRANSPARENT;
1375
1376         if(background->transparent) {
1377                 background->transparent_glass = get_boolean(cscene, "film_transparent_glass");
1378                 background->transparent_roughness_threshold = get_float(cscene, "film_transparent_roughness");
1379         }
1380         else {
1381                 background->transparent_glass = false;
1382                 background->transparent_roughness_threshold = 0.0f;
1383         }
1384
1385         background->use_shader = render_layer.use_background_shader;
1386         background->use_ao = background->use_ao && render_layer.use_background_ao;
1387
1388         if(background->modified(prevbackground))
1389                 background->tag_update(scene);
1390 }
1391
1392 /* Sync Lamps */
1393
1394 void BlenderSync::sync_lamps(bool update_all)
1395 {
1396         shader_map.set_default(scene->default_light);
1397
1398         /* lamp loop */
1399         BL::BlendData::lamps_iterator b_lamp;
1400
1401         for(b_data.lamps.begin(b_lamp); b_lamp != b_data.lamps.end(); ++b_lamp) {
1402                 Shader *shader;
1403
1404                 /* test if we need to sync */
1405                 if(shader_map.sync(&shader, *b_lamp) || update_all) {
1406                         ShaderGraph *graph = new ShaderGraph();
1407
1408                         /* create nodes */
1409                         if(b_lamp->use_nodes() && b_lamp->node_tree()) {
1410                                 shader->name = b_lamp->name().c_str();
1411
1412                                 BL::ShaderNodeTree b_ntree(b_lamp->node_tree());
1413
1414                                 add_nodes(scene, b_engine, b_data, b_scene, !preview, graph, b_ntree);
1415                         }
1416                         else {
1417                                 float strength = 1.0f;
1418
1419                                 if(b_lamp->type() == BL::Lamp::type_POINT ||
1420                                    b_lamp->type() == BL::Lamp::type_SPOT ||
1421                                    b_lamp->type() == BL::Lamp::type_AREA)
1422                                 {
1423                                         strength = 100.0f;
1424                                 }
1425
1426                                 EmissionNode *emission = new EmissionNode();
1427                                 emission->color = get_float3(b_lamp->color());
1428                                 emission->strength = strength;
1429                                 graph->add(emission);
1430
1431                                 ShaderNode *out = graph->output();
1432                                 graph->connect(emission->output("Emission"), out->input("Surface"));
1433                         }
1434
1435                         shader->set_graph(graph);
1436                         shader->tag_update(scene);
1437                 }
1438         }
1439 }
1440
1441 void BlenderSync::sync_shaders()
1442 {
1443         /* for auto refresh images */
1444         bool auto_refresh_update = false;
1445
1446         if(preview) {
1447                 ImageManager *image_manager = scene->image_manager;
1448                 int frame = b_scene.frame_current();
1449                 auto_refresh_update = image_manager->set_animation_frame_update(frame);
1450         }
1451
1452         shader_map.pre_sync();
1453
1454         sync_world(auto_refresh_update);
1455         sync_lamps(auto_refresh_update);
1456         sync_materials(auto_refresh_update);
1457
1458         /* false = don't delete unused shaders, not supported */
1459         shader_map.post_sync(false);
1460 }
1461
1462 CCL_NAMESPACE_END
1463