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