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