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