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