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