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