Fix #32796: cycles did not support image auto refresh option.
[blender-staging.git] / intern / cycles / blender / blender_shader.cpp
1 /*
2  * Copyright 2011, Blender Foundation.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  */
18
19 #include "background.h"
20 #include "graph.h"
21 #include "light.h"
22 #include "nodes.h"
23 #include "osl.h"
24 #include "scene.h"
25 #include "shader.h"
26
27 #include "blender_sync.h"
28 #include "blender_util.h"
29
30 #include "util_debug.h"
31
32 CCL_NAMESPACE_BEGIN
33
34 typedef map<void*, ShaderNode*> PtrNodeMap;
35 typedef pair<ShaderNode*, std::string> SocketPair;
36 typedef map<void*, SocketPair> PtrSockMap;
37
38 /* Find */
39
40 void BlenderSync::find_shader(BL::ID id, vector<uint>& used_shaders, int default_shader)
41 {
42         Shader *shader = (id)? shader_map.find(id): scene->shaders[default_shader];
43
44         for(size_t i = 0; i < scene->shaders.size(); i++) {
45                 if(scene->shaders[i] == shader) {
46                         used_shaders.push_back(i);
47                         scene->shaders[i]->tag_used(scene);
48                         break;
49                 }
50         }
51 }
52
53 /* Graph */
54
55 static BL::NodeSocket get_node_output(BL::Node b_node, const string& name)
56 {
57         BL::Node::outputs_iterator b_out;
58
59         for(b_node.outputs.begin(b_out); b_out != b_node.outputs.end(); ++b_out)
60                 if(b_out->name() == name)
61                         return *b_out;
62
63         assert(0);
64
65         return *b_out;
66 }
67
68 static float3 get_node_output_rgba(BL::Node b_node, const string& name)
69 {
70         BL::NodeSocketRGBA sock(get_node_output(b_node, name));
71         return get_float3(sock.default_value());
72 }
73
74 static float get_node_output_value(BL::Node b_node, const string& name)
75 {
76         BL::NodeSocketFloatNone sock(get_node_output(b_node, name));
77         return sock.default_value();
78 }
79
80 static ShaderSocketType convert_socket_type(BL::NodeSocket::type_enum b_type)
81 {
82         switch (b_type) {
83         case BL::NodeSocket::type_VALUE:
84                 return SHADER_SOCKET_FLOAT;
85         case BL::NodeSocket::type_INT:
86                 return SHADER_SOCKET_INT;
87         case BL::NodeSocket::type_VECTOR:
88                 return SHADER_SOCKET_VECTOR;
89         case BL::NodeSocket::type_RGBA:
90                 return SHADER_SOCKET_COLOR;
91         case BL::NodeSocket::type_SHADER:
92                 return SHADER_SOCKET_CLOSURE;
93         case BL::NodeSocket::type_STRING:
94                 return SHADER_SOCKET_STRING;
95         
96         case BL::NodeSocket::type_BOOLEAN:
97         case BL::NodeSocket::type_MESH:
98         default:
99                 return SHADER_SOCKET_FLOAT;
100         }
101 }
102
103 static void set_default_value(ShaderInput *input, BL::NodeSocket sock, BL::BlendData b_data, BL::ID b_id)
104 {
105         /* copy values for non linked inputs */
106         switch(input->type) {
107         case SHADER_SOCKET_FLOAT: {
108                 BL::NodeSocketFloatNone value_sock(sock);
109                 input->set(value_sock.default_value());
110                 break;
111         }
112         case SHADER_SOCKET_INT: {
113                 BL::NodeSocketIntNone value_sock(sock);
114                 input->set((float)value_sock.default_value());
115                 break;
116         }
117         case SHADER_SOCKET_COLOR: {
118                 BL::NodeSocketRGBA rgba_sock(sock);
119                 input->set(get_float3(rgba_sock.default_value()));
120                 break;
121         }
122         case SHADER_SOCKET_NORMAL:
123         case SHADER_SOCKET_POINT:
124         case SHADER_SOCKET_VECTOR: {
125                 BL::NodeSocketVectorNone vec_sock(sock);
126                 input->set(get_float3(vec_sock.default_value()));
127                 break;
128         }
129         case SHADER_SOCKET_STRING: {
130                 BL::NodeSocketStringNone string_sock(sock);
131                 input->set((ustring)blender_absolute_path(b_data, b_id, string_sock.default_value()));
132                 break;
133         }
134         case SHADER_SOCKET_CLOSURE:
135                 break;
136         }
137 }
138
139 static void get_tex_mapping(TextureMapping *mapping, BL::TexMapping b_mapping)
140 {
141         if(!b_mapping)
142                 return;
143
144         mapping->translation = get_float3(b_mapping.translation());
145         mapping->rotation = get_float3(b_mapping.rotation());
146         mapping->scale = get_float3(b_mapping.scale());
147
148         mapping->x_mapping = (TextureMapping::Mapping)b_mapping.mapping_x();
149         mapping->y_mapping = (TextureMapping::Mapping)b_mapping.mapping_y();
150         mapping->z_mapping = (TextureMapping::Mapping)b_mapping.mapping_z();
151 }
152
153 static void get_tex_mapping(TextureMapping *mapping, BL::ShaderNodeMapping b_mapping)
154 {
155         if(!b_mapping)
156                 return;
157
158         mapping->translation = get_float3(b_mapping.translation());
159         mapping->rotation = get_float3(b_mapping.rotation());
160         mapping->scale = get_float3(b_mapping.scale());
161
162         mapping->use_minmax = b_mapping.use_min() || b_mapping.use_max();
163
164         if(b_mapping.use_min())
165                 mapping->min = get_float3(b_mapping.min());
166         if(b_mapping.use_max())
167                 mapping->max = get_float3(b_mapping.max());
168 }
169
170 static ShaderNode *add_node(Scene *scene, BL::BlendData b_data, BL::Scene b_scene, ShaderGraph *graph, BL::ShaderNodeTree b_ntree, BL::ShaderNode b_node)
171 {
172         ShaderNode *node = NULL;
173
174         switch(b_node.type()) {
175                 /* not supported */
176                 case BL::ShaderNode::type_CURVE_VEC: break;
177                 case BL::ShaderNode::type_GEOMETRY: break;
178                 case BL::ShaderNode::type_MATERIAL: break;
179                 case BL::ShaderNode::type_MATERIAL_EXT: break;
180                 case BL::ShaderNode::type_OUTPUT: break;
181                 case BL::ShaderNode::type_SQUEEZE: break;
182                 case BL::ShaderNode::type_TEXTURE: break;
183                 case BL::ShaderNode::type_FRAME: break;
184                 /* handled outside this function */
185                 case BL::ShaderNode::type_GROUP: break;
186                 /* existing blender nodes */
187                 case BL::ShaderNode::type_REROUTE: {
188                         BL::Node::inputs_iterator b_input;
189                         b_node.inputs.begin(b_input);
190                         BL::Node::outputs_iterator b_output;
191                         b_node.outputs.begin(b_output);
192                         ProxyNode *proxy = new ProxyNode(convert_socket_type(b_input->type()), convert_socket_type(b_output->type()));
193                         node = proxy;
194                         break;
195                 }
196                 case BL::ShaderNode::type_CURVE_RGB: {
197                         RGBCurvesNode *ramp = new RGBCurvesNode();
198                         node = ramp;
199                         break;
200                 }
201                 case BL::ShaderNode::type_VALTORGB: {
202                         RGBRampNode *ramp = new RGBRampNode();
203                         BL::ShaderNodeValToRGB b_ramp_node(b_node);
204                         colorramp_to_array(b_ramp_node.color_ramp(), ramp->ramp, RAMP_TABLE_SIZE);
205                         node = ramp;
206                         break;
207                 }
208                 case BL::ShaderNode::type_RGB: {
209                         ColorNode *color = new ColorNode();
210                         color->value = get_node_output_rgba(b_node, "Color");
211                         node = color;
212                         break;
213                 }
214                 case BL::ShaderNode::type_VALUE: {
215                         ValueNode *value = new ValueNode();
216                         value->value = get_node_output_value(b_node, "Value");
217                         node = value;
218                         break;
219                 }
220                 case BL::ShaderNode::type_CAMERA: {
221                         node = new CameraNode();
222                         break;
223                 }
224                 case BL::ShaderNode::type_INVERT: {
225                         node = new InvertNode();
226                         break;
227                 }
228                 case BL::ShaderNode::type_GAMMA: {
229                         node = new GammaNode();
230                         break;
231                 }
232                 case BL::ShaderNode::type_BRIGHTCONTRAST: {
233                         node = new BrightContrastNode();
234                         break;
235                 }
236                 case BL::ShaderNode::type_MIX_RGB: {
237                         BL::ShaderNodeMixRGB b_mix_node(b_node);
238                         MixNode *mix = new MixNode();
239                         mix->type = MixNode::type_enum[b_mix_node.blend_type()];
240                         mix->use_clamp = b_mix_node.use_clamp();
241                         node = mix;
242                         break;
243                 }
244                 case BL::ShaderNode::type_SEPRGB: {
245                         node = new SeparateRGBNode();
246                         break;
247                 }
248                 case BL::ShaderNode::type_COMBRGB: {
249                         node = new CombineRGBNode();
250                         break;
251                 }
252                 case BL::ShaderNode::type_HUE_SAT: {
253                         node = new HSVNode();
254                         break;
255                 }
256                 case BL::ShaderNode::type_RGBTOBW: {
257                         node = new ConvertNode(SHADER_SOCKET_COLOR, SHADER_SOCKET_FLOAT);
258                         break;
259                 }
260                 case BL::ShaderNode::type_MATH: {
261                         BL::ShaderNodeMath b_math_node(b_node);
262                         MathNode *math = new MathNode();
263                         math->type = MathNode::type_enum[b_math_node.operation()];
264                         math->use_clamp = b_math_node.use_clamp();
265                         node = math;
266                         break;
267                 }
268                 case BL::ShaderNode::type_VECT_MATH: {
269                         BL::ShaderNodeVectorMath b_vector_math_node(b_node);
270                         VectorMathNode *vmath = new VectorMathNode();
271                         vmath->type = VectorMathNode::type_enum[b_vector_math_node.operation()];
272                         node = vmath;
273                         break;
274                 }
275                 case BL::ShaderNode::type_NORMAL: {
276                         BL::Node::outputs_iterator out_it;
277                         b_node.outputs.begin(out_it);
278                         BL::NodeSocketVectorNone vec_sock(*out_it);
279
280                         NormalNode *norm = new NormalNode();
281                         norm->direction = get_float3(vec_sock.default_value());
282
283                         node = norm;
284                         break;
285                 }
286                 case BL::ShaderNode::type_MAPPING: {
287                         BL::ShaderNodeMapping b_mapping_node(b_node);
288                         MappingNode *mapping = new MappingNode();
289
290                         get_tex_mapping(&mapping->tex_mapping, b_mapping_node);
291
292                         node = mapping;
293                         break;
294                 }
295
296                 /* new nodes */
297                 case BL::ShaderNode::type_OUTPUT_MATERIAL:
298                 case BL::ShaderNode::type_OUTPUT_WORLD:
299                 case BL::ShaderNode::type_OUTPUT_LAMP: {
300                         node = graph->output();
301                         break;
302                 }
303                 case BL::ShaderNode::type_FRESNEL: {
304                         node = new FresnelNode();
305                         break;
306                 }
307                 case BL::ShaderNode::type_LAYER_WEIGHT: {
308                         node = new LayerWeightNode();
309                         break;
310                 }
311                 case BL::ShaderNode::type_ADD_SHADER: {
312                         node = new AddClosureNode();
313                         break;
314                 }
315                 case BL::ShaderNode::type_MIX_SHADER: {
316                         node = new MixClosureNode();
317                         break;
318                 }
319                 case BL::ShaderNode::type_ATTRIBUTE: {
320                         BL::ShaderNodeAttribute b_attr_node(b_node);
321                         AttributeNode *attr = new AttributeNode();
322                         attr->attribute = b_attr_node.attribute_name();
323                         node = attr;
324                         break;
325                 }
326                 case BL::ShaderNode::type_BACKGROUND: {
327                         node = new BackgroundNode();
328                         break;
329                 }
330                 case BL::ShaderNode::type_HOLDOUT: {
331                         node = new HoldoutNode();
332                         break;
333                 }
334                 case BL::ShaderNode::type_BSDF_ANISOTROPIC: {
335                         node = new WardBsdfNode();
336                         break;
337                 }
338                 case BL::ShaderNode::type_BSDF_DIFFUSE: {
339                         node = new DiffuseBsdfNode();
340                         break;
341                 }
342                 case BL::ShaderNode::type_BSDF_GLOSSY: {
343                         BL::ShaderNodeBsdfGlossy b_glossy_node(b_node);
344                         GlossyBsdfNode *glossy = new GlossyBsdfNode();
345
346                         switch(b_glossy_node.distribution()) {
347                                 case BL::ShaderNodeBsdfGlossy::distribution_SHARP:
348                                         glossy->distribution = ustring("Sharp");
349                                         break;
350                                 case BL::ShaderNodeBsdfGlossy::distribution_BECKMANN:
351                                         glossy->distribution = ustring("Beckmann");
352                                         break;
353                                 case BL::ShaderNodeBsdfGlossy::distribution_GGX:
354                                         glossy->distribution = ustring("GGX");
355                                         break;
356                         }
357                         node = glossy;
358                         break;
359                 }
360                 case BL::ShaderNode::type_BSDF_GLASS: {
361                         BL::ShaderNodeBsdfGlass b_glass_node(b_node);
362                         GlassBsdfNode *glass = new GlassBsdfNode();
363                         switch(b_glass_node.distribution()) {
364                                 case BL::ShaderNodeBsdfGlass::distribution_SHARP:
365                                         glass->distribution = ustring("Sharp");
366                                         break;
367                                 case BL::ShaderNodeBsdfGlass::distribution_BECKMANN:
368                                         glass->distribution = ustring("Beckmann");
369                                         break;
370                                 case BL::ShaderNodeBsdfGlass::distribution_GGX:
371                                         glass->distribution = ustring("GGX");
372                                         break;
373                         }
374                         node = glass;
375                         break;
376                 }
377                 case BL::ShaderNode::type_BSDF_REFRACTION: {
378                         BL::ShaderNodeBsdfRefraction b_refraction_node(b_node);
379                         RefractionBsdfNode *refraction = new RefractionBsdfNode();
380                         switch(b_refraction_node.distribution()) {
381                                 case BL::ShaderNodeBsdfRefraction::distribution_SHARP:
382                                         refraction->distribution = ustring("Sharp");
383                                         break;
384                                 case BL::ShaderNodeBsdfRefraction::distribution_BECKMANN:
385                                         refraction->distribution = ustring("Beckmann");
386                                         break;
387                                 case BL::ShaderNodeBsdfRefraction::distribution_GGX:
388                                         refraction->distribution = ustring("GGX");
389                                         break;
390                         }
391                         node = refraction;
392                         break;
393                 }
394                 case BL::ShaderNode::type_BSDF_TRANSLUCENT: {
395                         node = new TranslucentBsdfNode();
396                         break;
397                 }
398                 case BL::ShaderNode::type_BSDF_TRANSPARENT: {
399                         node = new TransparentBsdfNode();
400                         break;
401                 }
402                 case BL::ShaderNode::type_BSDF_VELVET: {
403                         node = new VelvetBsdfNode();
404                         break;
405                 }
406                 case BL::ShaderNode::type_EMISSION: {
407                         node = new EmissionNode();
408                         break;
409                 }
410                 case BL::ShaderNode::type_AMBIENT_OCCLUSION: {
411                         node = new AmbientOcclusionNode();
412                         break;
413                 }
414                 case BL::ShaderNode::type_VOLUME_ISOTROPIC: {
415                         node = new IsotropicVolumeNode();
416                         break;
417                 }
418                 case BL::ShaderNode::type_VOLUME_TRANSPARENT: {
419                         node = new TransparentVolumeNode();
420                         break;
421                 }
422                 case BL::ShaderNode::type_NEW_GEOMETRY: {
423                         node = new GeometryNode();
424                         break;
425                 }
426                 case BL::ShaderNode::type_LIGHT_PATH: {
427                         node = new LightPathNode();
428                         break;
429                 }
430                 case BL::ShaderNode::type_LIGHT_FALLOFF: {
431                         node = new LightFalloffNode();
432                         break;
433                 }
434                 case BL::ShaderNode::type_OBJECT_INFO: {
435                         node = new ObjectInfoNode();
436                         break;
437                 }
438                 case BL::ShaderNode::type_PARTICLE_INFO: {
439                         node = new ParticleInfoNode();
440                         break;
441                 }
442                 case BL::ShaderNode::type_BUMP: {
443                         node = new BumpNode();
444                         break;
445                 }
446                 case BL::ShaderNode::type_SCRIPT: {
447 #ifdef WITH_OSL
448                         if(scene->params.shadingsystem != SceneParams::OSL)
449                                 break;
450
451                         /* create script node */
452                         BL::ShaderNodeScript b_script_node(b_node);
453                         OSLScriptNode *script_node = new OSLScriptNode();
454                         
455                         /* Generate inputs/outputs from node sockets
456                          *
457                          * Note: the node sockets are generated from OSL parameters,
458                          * so the names match those of the corresponding parameters exactly.
459                          *
460                          * Note 2: ShaderInput/ShaderOutput store shallow string copies only!
461                          * Socket names must be stored in the extra lists instead. */
462                         BL::Node::inputs_iterator b_input;
463
464                         for (b_script_node.inputs.begin(b_input); b_input != b_script_node.inputs.end(); ++b_input) {
465                                 script_node->input_names.push_back(ustring(b_input->name()));
466                                 ShaderInput *input = script_node->add_input(script_node->input_names.back().c_str(), convert_socket_type(b_input->type()));
467                                 set_default_value(input, *b_input, b_data, b_ntree);
468                         }
469
470                         BL::Node::outputs_iterator b_output;
471
472                         for (b_script_node.outputs.begin(b_output); b_output != b_script_node.outputs.end(); ++b_output) {
473                                 script_node->output_names.push_back(ustring(b_output->name()));
474                                 script_node->add_output(script_node->output_names.back().c_str(), convert_socket_type(b_output->type()));
475                         }
476
477                         /* load bytecode or filepath */
478                         OSLShaderManager *manager = (OSLShaderManager*)scene->shader_manager;
479                         string bytecode_hash = b_script_node.bytecode_hash();
480
481                         if(!bytecode_hash.empty()) {
482                                 /* loaded bytecode if not already done */
483                                 if(!manager->shader_test_loaded(bytecode_hash))
484                                         manager->shader_load_bytecode(bytecode_hash, b_script_node.bytecode());
485
486                                 script_node->bytecode_hash = bytecode_hash;
487                         }
488                         else {
489                                 /* set filepath */
490                                 script_node->filepath = blender_absolute_path(b_data, b_ntree, b_script_node.filepath());
491                         }
492                         
493                         node = script_node;
494 #endif
495
496                         break;
497                 }
498                 case BL::ShaderNode::type_TEX_IMAGE: {
499                         BL::ShaderNodeTexImage b_image_node(b_node);
500                         BL::Image b_image(b_image_node.image());
501                         ImageTextureNode *image = new ImageTextureNode();
502                         /* todo: handle generated/builtin images */
503                         if(b_image && b_image.source() != BL::Image::source_MOVIE) {
504                                 image->filename = image_user_file_path(b_image_node.image_user(), b_image, b_scene.frame_current());
505                                 image->animated = b_image_node.image_user().use_auto_refresh();
506                         }
507                         image->color_space = ImageTextureNode::color_space_enum[(int)b_image_node.color_space()];
508                         image->projection = ImageTextureNode::projection_enum[(int)b_image_node.projection()];
509                         image->projection_blend = b_image_node.projection_blend();
510                         get_tex_mapping(&image->tex_mapping, b_image_node.texture_mapping());
511                         node = image;
512                         break;
513                 }
514                 case BL::ShaderNode::type_TEX_ENVIRONMENT: {
515                         BL::ShaderNodeTexEnvironment b_env_node(b_node);
516                         BL::Image b_image(b_env_node.image());
517                         EnvironmentTextureNode *env = new EnvironmentTextureNode();
518                         if(b_image && b_image.source() != BL::Image::source_MOVIE) {
519                                 env->filename = image_user_file_path(b_env_node.image_user(), b_image, b_scene.frame_current());
520                                 env->animated = b_env_node.image_user().use_auto_refresh();
521                         }
522                         env->color_space = EnvironmentTextureNode::color_space_enum[(int)b_env_node.color_space()];
523                         env->projection = EnvironmentTextureNode::projection_enum[(int)b_env_node.projection()];
524                         get_tex_mapping(&env->tex_mapping, b_env_node.texture_mapping());
525                         node = env;
526                         break;
527                 }
528                 case BL::ShaderNode::type_TEX_GRADIENT: {
529                         BL::ShaderNodeTexGradient b_gradient_node(b_node);
530                         GradientTextureNode *gradient = new GradientTextureNode();
531                         gradient->type = GradientTextureNode::type_enum[(int)b_gradient_node.gradient_type()];
532                         get_tex_mapping(&gradient->tex_mapping, b_gradient_node.texture_mapping());
533                         node = gradient;
534                         break;
535                 }
536                 case BL::ShaderNode::type_TEX_VORONOI: {
537                         BL::ShaderNodeTexVoronoi b_voronoi_node(b_node);
538                         VoronoiTextureNode *voronoi = new VoronoiTextureNode();
539                         voronoi->coloring = VoronoiTextureNode::coloring_enum[(int)b_voronoi_node.coloring()];
540                         get_tex_mapping(&voronoi->tex_mapping, b_voronoi_node.texture_mapping());
541                         node = voronoi;
542                         break;
543                 }
544                 case BL::ShaderNode::type_TEX_MAGIC: {
545                         BL::ShaderNodeTexMagic b_magic_node(b_node);
546                         MagicTextureNode *magic = new MagicTextureNode();
547                         magic->depth = b_magic_node.turbulence_depth();
548                         get_tex_mapping(&magic->tex_mapping, b_magic_node.texture_mapping());
549                         node = magic;
550                         break;
551                 }
552                 case BL::ShaderNode::type_TEX_WAVE: {
553                         BL::ShaderNodeTexWave b_wave_node(b_node);
554                         WaveTextureNode *wave = new WaveTextureNode();
555                         wave->type = WaveTextureNode::type_enum[(int)b_wave_node.wave_type()];
556                         get_tex_mapping(&wave->tex_mapping, b_wave_node.texture_mapping());
557                         node = wave;
558                         break;
559                 }
560                 case BL::ShaderNode::type_TEX_CHECKER: {
561                         BL::ShaderNodeTexChecker b_checker_node(b_node);
562                         CheckerTextureNode *checker = new CheckerTextureNode();
563                         get_tex_mapping(&checker->tex_mapping, b_checker_node.texture_mapping());
564                         node = checker;
565                         break;
566                 }
567                 case BL::ShaderNode::type_TEX_BRICK: {
568                         BL::ShaderNodeTexBrick b_brick_node(b_node);
569                         BrickTextureNode *brick = new BrickTextureNode();
570                         brick->offset = b_brick_node.offset();
571                         brick->offset_frequency = b_brick_node.offset_frequency();
572                         brick->squash = b_brick_node.squash();
573                         brick->squash_frequency = b_brick_node.squash_frequency();
574                         get_tex_mapping(&brick->tex_mapping, b_brick_node.texture_mapping());
575                         node = brick;
576                         break;
577                 }
578                 case BL::ShaderNode::type_TEX_NOISE: {
579                         BL::ShaderNodeTexNoise b_noise_node(b_node);
580                         NoiseTextureNode *noise = new NoiseTextureNode();
581                         get_tex_mapping(&noise->tex_mapping, b_noise_node.texture_mapping());
582                         node = noise;
583                         break;
584                 }
585                 case BL::ShaderNode::type_TEX_MUSGRAVE: {
586                         BL::ShaderNodeTexMusgrave b_musgrave_node(b_node);
587                         MusgraveTextureNode *musgrave = new MusgraveTextureNode();
588                         musgrave->type = MusgraveTextureNode::type_enum[(int)b_musgrave_node.musgrave_type()];
589                         get_tex_mapping(&musgrave->tex_mapping, b_musgrave_node.texture_mapping());
590                         node = musgrave;
591                         break;
592                 }
593                 case BL::ShaderNode::type_TEX_COORD: {
594                         BL::ShaderNodeTexCoord b_tex_coord_node(b_node);
595                         TextureCoordinateNode *tex_coord = new TextureCoordinateNode();
596                         tex_coord->from_dupli = b_tex_coord_node.from_dupli();
597                         node = tex_coord;
598                         break;
599                 }
600                 case BL::ShaderNode::type_TEX_SKY: {
601                         BL::ShaderNodeTexSky b_sky_node(b_node);
602                         SkyTextureNode *sky = new SkyTextureNode();
603                         sky->sun_direction = get_float3(b_sky_node.sun_direction());
604                         sky->turbidity = b_sky_node.turbidity();
605                         get_tex_mapping(&sky->tex_mapping, b_sky_node.texture_mapping());
606                         node = sky;
607                         break;
608                 }
609                 case BL::ShaderNode::type_NORMAL_MAP: {
610                         BL::ShaderNodeNormalMap b_normal_map_node(b_node);
611                         NormalMapNode *nmap = new NormalMapNode();
612                         nmap->space = NormalMapNode::space_enum[(int)b_normal_map_node.space()];
613                         nmap->attribute = b_normal_map_node.uv_map();
614                         node = nmap;
615                         break;
616                 }
617                 case BL::ShaderNode::type_TANGENT: {
618                         BL::ShaderNodeTangent b_tangent_node(b_node);
619                         TangentNode *tangent = new TangentNode();
620                         tangent->direction_type = TangentNode::direction_type_enum[(int)b_tangent_node.direction_type()];
621                         tangent->axis = TangentNode::axis_enum[(int)b_tangent_node.axis()];
622                         tangent->attribute = b_tangent_node.uv_map();
623                         node = tangent;
624                         break;
625                 }
626         }
627
628         if(node && node != graph->output())
629                 graph->add(node);
630
631         return node;
632 }
633
634 static SocketPair node_socket_map_pair(PtrNodeMap& node_map, BL::Node b_node, BL::NodeSocket b_socket)
635 {
636         BL::Node::inputs_iterator b_input;
637         BL::Node::outputs_iterator b_output;
638         string name = b_socket.name();
639         bool found = false;
640         int counter = 0, total = 0;
641
642         /* find in inputs */
643         for(b_node.inputs.begin(b_input); b_input != b_node.inputs.end(); ++b_input) {
644                 if(b_input->name() == name) {
645                         if(!found)
646                                 counter++;
647                         total++;
648                 }
649
650                 if(b_input->ptr.data == b_socket.ptr.data)
651                         found = true;
652         }
653
654         if(!found) {
655                 /* find in outputs */
656                 found = false;
657                 counter = 0;
658                 total = 0;
659
660                 for(b_node.outputs.begin(b_output); b_output != b_node.outputs.end(); ++b_output) {
661                         if(b_output->name() == name) {
662                                 if(!found)
663                                         counter++;
664                                 total++;
665                         }
666
667                         if(b_output->ptr.data == b_socket.ptr.data)
668                                 found = true;
669                 }
670         }
671
672         /* rename if needed */
673         if(name == "Shader")
674                 name = "Closure";
675
676         if(total > 1)
677                 name = string_printf("%s%d", name.c_str(), counter);
678
679         return SocketPair(node_map[b_node.ptr.data], name);
680 }
681
682 static void add_nodes(Scene *scene, BL::BlendData b_data, BL::Scene b_scene, ShaderGraph *graph, BL::ShaderNodeTree b_ntree, PtrSockMap& sockets_map)
683 {
684         /* add nodes */
685         BL::ShaderNodeTree::nodes_iterator b_node;
686         PtrNodeMap node_map;
687         PtrSockMap proxy_map;
688
689         for(b_ntree.nodes.begin(b_node); b_node != b_ntree.nodes.end(); ++b_node) {
690                 if(b_node->mute()) {
691                         BL::Node::inputs_iterator b_input;
692                         BL::Node::outputs_iterator b_output;
693                         bool found_match = false;
694
695                         /* this is slightly different than blender logic, we just connect a
696                          * single pair for of input/output, but works ok for the node we have */
697                         for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
698                                 if(b_input->is_linked()) {
699                                         for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
700                                                 if(b_output->is_linked() && b_input->type() == b_output->type()) {
701                                                         ProxyNode *proxy = new ProxyNode(convert_socket_type(b_input->type()), convert_socket_type(b_output->type()));
702                                                         graph->add(proxy);
703
704                                                         proxy_map[b_input->ptr.data] = SocketPair(proxy, proxy->inputs[0]->name);
705                                                         proxy_map[b_output->ptr.data] = SocketPair(proxy, proxy->outputs[0]->name);
706                                                         found_match = true;
707
708                                                         break;
709                                                 }
710                                         }
711                                 }
712
713                                 if(found_match)
714                                         break;
715                         }
716                 }
717                 else if(b_node->is_a(&RNA_NodeGroup)) {
718                         /* add proxy converter nodes for inputs and outputs */
719                         BL::NodeGroup b_gnode(*b_node);
720                         BL::ShaderNodeTree b_group_ntree(b_gnode.node_tree());
721                         if (!b_group_ntree)
722                                 continue;
723
724                         BL::Node::inputs_iterator b_input;
725                         BL::Node::outputs_iterator b_output;
726                         
727                         PtrSockMap group_sockmap;
728                         
729                         for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
730                                 ShaderSocketType extern_type = convert_socket_type(b_input->type());
731                                 ShaderSocketType intern_type = convert_socket_type(b_input->group_socket().type());
732                                 ShaderNode *proxy = graph->add(new ProxyNode(extern_type, intern_type));
733                                 
734                                 /* map the external node socket to the proxy node socket */
735                                 proxy_map[b_input->ptr.data] = SocketPair(proxy, proxy->inputs[0]->name);
736                                 /* map the internal group socket to the proxy node socket */
737                                 group_sockmap[b_input->group_socket().ptr.data] = SocketPair(proxy, proxy->outputs[0]->name);
738                                 
739                                 /* default input values of the group node */
740                                 set_default_value(proxy->inputs[0], *b_input, b_data, b_group_ntree);
741                         }
742                         
743                         for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
744                                 ShaderSocketType extern_type = convert_socket_type(b_output->type());
745                                 ShaderSocketType intern_type = convert_socket_type(b_output->group_socket().type());
746                                 ShaderNode *proxy = graph->add(new ProxyNode(intern_type, extern_type));
747                                 
748                                 /* map the external node socket to the proxy node socket */
749                                 proxy_map[b_output->ptr.data] = SocketPair(proxy, proxy->outputs[0]->name);
750                                 /* map the internal group socket to the proxy node socket */
751                                 group_sockmap[b_output->group_socket().ptr.data] = SocketPair(proxy, proxy->inputs[0]->name);
752                                 
753                                 /* default input values of internal, unlinked group outputs */
754                                 set_default_value(proxy->inputs[0], b_output->group_socket(), b_data, b_group_ntree);
755                         }
756                         
757                         add_nodes(scene, b_data, b_scene, graph, b_group_ntree, group_sockmap);
758                 }
759                 else {
760                         ShaderNode *node = add_node(scene, b_data, b_scene, graph, b_ntree, BL::ShaderNode(*b_node));
761                         
762                         if(node) {
763                                 BL::Node::inputs_iterator b_input;
764                                 
765                                 node_map[b_node->ptr.data] = node;
766                                 
767                                 for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
768                                         SocketPair pair = node_socket_map_pair(node_map, *b_node, *b_input);
769                                         ShaderInput *input = pair.first->input(pair.second.c_str());
770                                         
771                                         assert(input);
772                                         
773                                         /* copy values for non linked inputs */
774                                         set_default_value(input, *b_input, b_data, b_ntree);
775                                 }
776                         }
777                 }
778         }
779
780         /* connect nodes */
781         BL::NodeTree::links_iterator b_link;
782
783         for(b_ntree.links.begin(b_link); b_link != b_ntree.links.end(); ++b_link) {
784                 /* get blender link data */
785                 BL::Node b_from_node = b_link->from_node();
786                 BL::Node b_to_node = b_link->to_node();
787
788                 BL::NodeSocket b_from_sock = b_link->from_socket();
789                 BL::NodeSocket b_to_sock = b_link->to_socket();
790
791                 SocketPair from_pair, to_pair;
792
793                 /* links without a node pointer are connections to group inputs/outputs */
794
795                 /* from sock */
796                 if(b_from_node) {
797                         if (b_from_node.mute() || b_from_node.is_a(&RNA_NodeGroup))
798                                 from_pair = proxy_map[b_from_sock.ptr.data];
799                         else
800                                 from_pair = node_socket_map_pair(node_map, b_from_node, b_from_sock);
801                 }
802                 else
803                         from_pair = sockets_map[b_from_sock.ptr.data];
804
805                 /* to sock */
806                 if(b_to_node) {
807                         if (b_to_node.mute() || b_to_node.is_a(&RNA_NodeGroup))
808                                 to_pair = proxy_map[b_to_sock.ptr.data];
809                         else
810                                 to_pair = node_socket_map_pair(node_map, b_to_node, b_to_sock);
811                 }
812                 else
813                         to_pair = sockets_map[b_to_sock.ptr.data];
814
815                 /* either node may be NULL when the node was not exported, typically
816                  * because the node type is not supported */
817                 if(from_pair.first && to_pair.first) {
818                         ShaderOutput *output = from_pair.first->output(from_pair.second.c_str());
819                         ShaderInput *input = to_pair.first->input(to_pair.second.c_str());
820
821                         graph->connect(output, input);
822                 }
823         }
824 }
825
826 /* Sync Materials */
827
828 void BlenderSync::sync_materials(bool update_all)
829 {
830         shader_map.set_default(scene->shaders[scene->default_surface]);
831
832         /* material loop */
833         BL::BlendData::materials_iterator b_mat;
834
835         for(b_data.materials.begin(b_mat); b_mat != b_data.materials.end(); ++b_mat) {
836                 Shader *shader;
837                 
838                 /* test if we need to sync */
839                 if(shader_map.sync(&shader, *b_mat) || update_all) {
840                         ShaderGraph *graph = new ShaderGraph();
841
842                         shader->name = b_mat->name().c_str();
843                         shader->pass_id = b_mat->pass_index();
844
845                         /* create nodes */
846                         if(b_mat->use_nodes() && b_mat->node_tree()) {
847                                 PtrSockMap sock_to_node;
848                                 BL::ShaderNodeTree b_ntree(b_mat->node_tree());
849
850                                 add_nodes(scene, b_data, b_scene, graph, b_ntree, sock_to_node);
851                         }
852                         else {
853                                 ShaderNode *closure, *out;
854
855                                 closure = graph->add(new DiffuseBsdfNode());
856                                 closure->input("Color")->value = get_float3(b_mat->diffuse_color());
857                                 out = graph->output();
858
859                                 graph->connect(closure->output("BSDF"), out->input("Surface"));
860                         }
861
862                         /* settings */
863                         PointerRNA cmat = RNA_pointer_get(&b_mat->ptr, "cycles");
864                         shader->sample_as_light = get_boolean(cmat, "sample_as_light");
865                         shader->homogeneous_volume = get_boolean(cmat, "homogeneous_volume");
866
867                         shader->set_graph(graph);
868                         shader->tag_update(scene);
869                 }
870         }
871 }
872
873 /* Sync World */
874
875 void BlenderSync::sync_world(bool update_all)
876 {
877         Background *background = scene->background;
878         Background prevbackground = *background;
879
880         BL::World b_world = b_scene.world();
881
882         if(world_recalc || update_all || b_world.ptr.data != world_map) {
883                 Shader *shader = scene->shaders[scene->default_background];
884                 ShaderGraph *graph = new ShaderGraph();
885
886                 /* create nodes */
887                 if(b_world && b_world.use_nodes() && b_world.node_tree()) {
888                         PtrSockMap sock_to_node;
889                         BL::ShaderNodeTree b_ntree(b_world.node_tree());
890
891                         add_nodes(scene, b_data, b_scene, graph, b_ntree, sock_to_node);
892                 }
893                 else if(b_world) {
894                         ShaderNode *closure, *out;
895
896                         closure = graph->add(new BackgroundNode());
897                         closure->input("Color")->value = get_float3(b_world.horizon_color());
898                         out = graph->output();
899
900                         graph->connect(closure->output("Background"), out->input("Surface"));
901                 }
902
903                 /* AO */
904                 if(b_world) {
905                         BL::WorldLighting b_light = b_world.light_settings();
906
907                         if(b_light.use_ambient_occlusion())
908                                 background->ao_factor = b_light.ao_factor();
909                         else
910                                 background->ao_factor = 0.0f;
911
912                         background->ao_distance = b_light.distance();
913                 }
914
915                 shader->set_graph(graph);
916                 shader->tag_update(scene);
917         }
918
919         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
920         background->transparent = get_boolean(cscene, "film_transparent");
921         background->use = render_layer.use_background;
922
923         if(background->modified(prevbackground))
924                 background->tag_update(scene);
925 }
926
927 /* Sync Lamps */
928
929 void BlenderSync::sync_lamps(bool update_all)
930 {
931         shader_map.set_default(scene->shaders[scene->default_light]);
932
933         /* lamp loop */
934         BL::BlendData::lamps_iterator b_lamp;
935
936         for(b_data.lamps.begin(b_lamp); b_lamp != b_data.lamps.end(); ++b_lamp) {
937                 Shader *shader;
938                 
939                 /* test if we need to sync */
940                 if(shader_map.sync(&shader, *b_lamp) || update_all) {
941                         ShaderGraph *graph = new ShaderGraph();
942
943                         /* create nodes */
944                         if(b_lamp->use_nodes() && b_lamp->node_tree()) {
945                                 shader->name = b_lamp->name().c_str();
946
947                                 PtrSockMap sock_to_node;
948                                 BL::ShaderNodeTree b_ntree(b_lamp->node_tree());
949
950                                 add_nodes(scene, b_data, b_scene, graph, b_ntree, sock_to_node);
951                         }
952                         else {
953                                 ShaderNode *closure, *out;
954                                 float strength = 1.0f;
955
956                                 if(b_lamp->type() == BL::Lamp::type_POINT ||
957                                    b_lamp->type() == BL::Lamp::type_SPOT ||
958                                    b_lamp->type() == BL::Lamp::type_AREA)
959                                 {
960                                         strength = 100.0f;
961                                 }
962
963                                 closure = graph->add(new EmissionNode());
964                                 closure->input("Color")->value = get_float3(b_lamp->color());
965                                 closure->input("Strength")->value.x = strength;
966                                 out = graph->output();
967
968                                 graph->connect(closure->output("Emission"), out->input("Surface"));
969                         }
970
971                         shader->set_graph(graph);
972                         shader->tag_update(scene);
973                 }
974         }
975 }
976
977 void BlenderSync::sync_shaders()
978 {
979         /* for auto refresh images */
980         bool auto_refresh_update = false;
981
982         if(preview) {
983                 ImageManager *image_manager = scene->image_manager;
984                 int frame = b_scene.frame_current();
985                 auto_refresh_update = image_manager->set_animation_frame_update(frame);
986         }
987
988         shader_map.pre_sync();
989
990         sync_world(auto_refresh_update);
991         sync_lamps(auto_refresh_update);
992         sync_materials(auto_refresh_update);
993
994         /* false = don't delete unused shaders, not supported */
995         shader_map.post_sync(false);
996 }
997
998 CCL_NAMESPACE_END
999