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