Cycles / Wavelength to RGB node:
[blender.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*, ShaderInput*> PtrInputMap;
35 typedef map<void*, ShaderOutput*> PtrOutputMap;
36 typedef map<std::string, ProxyNode*> ProxyMap;
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::NodeSocket b_sock = get_node_output(b_node, name);
71         float value[4];
72         RNA_float_get_array(&b_sock.ptr, "default_value", value);
73         return make_float3(value[0], value[1], value[2]);
74 }
75
76 static float get_node_output_value(BL::Node b_node, const string& name)
77 {
78         BL::NodeSocket b_sock = get_node_output(b_node, name);
79         return RNA_float_get(&b_sock.ptr, "default_value");
80 }
81
82 static float3 get_node_output_vector(BL::Node b_node, const string& name)
83 {
84         BL::NodeSocket b_sock = get_node_output(b_node, name);
85         float value[3];
86         RNA_float_get_array(&b_sock.ptr, "default_value", value);
87         return make_float3(value[0], value[1], value[2]);
88 }
89
90 static ShaderSocketType convert_socket_type(BL::NodeSocket b_socket)
91 {
92         switch (b_socket.type()) {
93                 case BL::NodeSocket::type_VALUE:
94                         return SHADER_SOCKET_FLOAT;
95                 case BL::NodeSocket::type_INT:
96                         return SHADER_SOCKET_INT;
97                 case BL::NodeSocket::type_VECTOR:
98                         return SHADER_SOCKET_VECTOR;
99                 case BL::NodeSocket::type_RGBA:
100                         return SHADER_SOCKET_COLOR;
101                 case BL::NodeSocket::type_STRING:
102                         return SHADER_SOCKET_STRING;
103                 case BL::NodeSocket::type_SHADER:
104                         return SHADER_SOCKET_CLOSURE;
105                 
106                 default:
107                         return SHADER_SOCKET_UNDEFINED;
108         }
109 }
110
111 static void set_default_value(ShaderInput *input, BL::Node b_node, BL::NodeSocket b_sock, BL::BlendData b_data, BL::ID b_id)
112 {
113         /* copy values for non linked inputs */
114         switch(input->type) {
115         case SHADER_SOCKET_FLOAT: {
116                 input->set(get_float(b_sock.ptr, "default_value"));
117                 break;
118         }
119         case SHADER_SOCKET_INT: {
120                 input->set((float)get_int(b_sock.ptr, "default_value"));
121                 break;
122         }
123         case SHADER_SOCKET_COLOR: {
124                 input->set(float4_to_float3(get_float4(b_sock.ptr, "default_value")));
125                 break;
126         }
127         case SHADER_SOCKET_NORMAL:
128         case SHADER_SOCKET_POINT:
129         case SHADER_SOCKET_VECTOR: {
130                 input->set(get_float3(b_sock.ptr, "default_value"));
131                 break;
132         }
133         case SHADER_SOCKET_STRING: {
134                 input->set((ustring)blender_absolute_path(b_data, b_id, get_string(b_sock.ptr, "default_value")));
135                 break;
136         }
137         
138         case SHADER_SOCKET_CLOSURE:
139         case SHADER_SOCKET_UNDEFINED:
140                 break;
141         }
142 }
143
144 static void get_tex_mapping(TextureMapping *mapping, BL::TexMapping b_mapping)
145 {
146         if(!b_mapping)
147                 return;
148
149         mapping->translation = get_float3(b_mapping.translation());
150         mapping->rotation = get_float3(b_mapping.rotation());
151         mapping->scale = get_float3(b_mapping.scale());
152
153         mapping->x_mapping = (TextureMapping::Mapping)b_mapping.mapping_x();
154         mapping->y_mapping = (TextureMapping::Mapping)b_mapping.mapping_y();
155         mapping->z_mapping = (TextureMapping::Mapping)b_mapping.mapping_z();
156 }
157
158 static void get_tex_mapping(TextureMapping *mapping, BL::ShaderNodeMapping b_mapping)
159 {
160         if(!b_mapping)
161                 return;
162
163         mapping->translation = get_float3(b_mapping.translation());
164         mapping->rotation = get_float3(b_mapping.rotation());
165         mapping->scale = get_float3(b_mapping.scale());
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_ShaderNodeHueSaturation)) {
235                 node = new HSVNode();
236         }
237         else if (b_node.is_a(&RNA_ShaderNodeRGBToBW)) {
238                 node = new ConvertNode(SHADER_SOCKET_COLOR, SHADER_SOCKET_FLOAT);
239         }
240         else if (b_node.is_a(&RNA_ShaderNodeMath)) {
241                 BL::ShaderNodeMath b_math_node(b_node);
242                 MathNode *math = new MathNode();
243                 math->type = MathNode::type_enum[b_math_node.operation()];
244                         math->use_clamp = b_math_node.use_clamp();
245                 node = math;
246         }
247         else if (b_node.is_a(&RNA_ShaderNodeVectorMath)) {
248                 BL::ShaderNodeVectorMath b_vector_math_node(b_node);
249                 VectorMathNode *vmath = new VectorMathNode();
250                 vmath->type = VectorMathNode::type_enum[b_vector_math_node.operation()];
251                 node = vmath;
252         }
253         else if (b_node.is_a(&RNA_ShaderNodeNormal)) {
254                 BL::Node::outputs_iterator out_it;
255                 b_node.outputs.begin(out_it);
256                 
257                 NormalNode *norm = new NormalNode();
258                 norm->direction = get_node_output_vector(b_node, "Normal");
259                 node = norm;
260         }
261         else if (b_node.is_a(&RNA_ShaderNodeMapping)) {
262                 BL::ShaderNodeMapping b_mapping_node(b_node);
263                 MappingNode *mapping = new MappingNode();
264                 
265                 get_tex_mapping(&mapping->tex_mapping, b_mapping_node);
266                 
267                 node = mapping;
268         }
269         /* new nodes */
270         else if (b_node.is_a(&RNA_ShaderNodeOutputMaterial)
271               || b_node.is_a(&RNA_ShaderNodeOutputWorld)
272               || b_node.is_a(&RNA_ShaderNodeOutputLamp)) {
273                 node = graph->output();
274         }
275         else if (b_node.is_a(&RNA_ShaderNodeFresnel)) {
276                 node = new FresnelNode();
277         }
278         else if (b_node.is_a(&RNA_ShaderNodeLayerWeight)) {
279                 node = new LayerWeightNode();
280         }
281         else if (b_node.is_a(&RNA_ShaderNodeAddShader)) {
282                 node = new AddClosureNode();
283         }
284         else if (b_node.is_a(&RNA_ShaderNodeMixShader)) {
285                 node = new MixClosureNode();
286         }
287         else if (b_node.is_a(&RNA_ShaderNodeAttribute)) {
288                 BL::ShaderNodeAttribute b_attr_node(b_node);
289                 AttributeNode *attr = new AttributeNode();
290                 attr->attribute = b_attr_node.attribute_name();
291                 node = attr;
292         }
293         else if (b_node.is_a(&RNA_ShaderNodeBackground)) {
294                 node = new BackgroundNode();
295         }
296         else if (b_node.is_a(&RNA_ShaderNodeHoldout)) {
297                 node = new HoldoutNode();
298         }
299         else if (b_node.is_a(&RNA_ShaderNodeBsdfAnisotropic)) {
300                 node = new WardBsdfNode();
301         }
302         else if (b_node.is_a(&RNA_ShaderNodeBsdfDiffuse)) {
303                 node = new DiffuseBsdfNode();
304         }
305         else if (b_node.is_a(&RNA_ShaderNodeSubsurfaceScattering)) {
306                 node = new SubsurfaceScatteringNode();
307         }
308         else if (b_node.is_a(&RNA_ShaderNodeBsdfGlossy)) {
309                 BL::ShaderNodeBsdfGlossy b_glossy_node(b_node);
310                 GlossyBsdfNode *glossy = new GlossyBsdfNode();
311                 
312                 switch(b_glossy_node.distribution()) {
313                 case BL::ShaderNodeBsdfGlossy::distribution_SHARP:
314                         glossy->distribution = ustring("Sharp");
315                         break;
316                 case BL::ShaderNodeBsdfGlossy::distribution_BECKMANN:
317                         glossy->distribution = ustring("Beckmann");
318                         break;
319                 case BL::ShaderNodeBsdfGlossy::distribution_GGX:
320                         glossy->distribution = ustring("GGX");
321                         break;
322                 }
323                 node = glossy;
324         }
325         else if (b_node.is_a(&RNA_ShaderNodeBsdfGlass)) {
326                 BL::ShaderNodeBsdfGlass b_glass_node(b_node);
327                 GlassBsdfNode *glass = new GlassBsdfNode();
328                 switch(b_glass_node.distribution()) {
329                 case BL::ShaderNodeBsdfGlass::distribution_SHARP:
330                         glass->distribution = ustring("Sharp");
331                         break;
332                 case BL::ShaderNodeBsdfGlass::distribution_BECKMANN:
333                         glass->distribution = ustring("Beckmann");
334                         break;
335                 case BL::ShaderNodeBsdfGlass::distribution_GGX:
336                         glass->distribution = ustring("GGX");
337                         break;
338                 }
339                 node = glass;
340         }
341         else if (b_node.is_a(&RNA_ShaderNodeBsdfRefraction)) {
342                 BL::ShaderNodeBsdfRefraction b_refraction_node(b_node);
343                 RefractionBsdfNode *refraction = new RefractionBsdfNode();
344                 switch(b_refraction_node.distribution()) {
345                         case BL::ShaderNodeBsdfRefraction::distribution_SHARP:
346                                 refraction->distribution = ustring("Sharp");
347                                 break;
348                         case BL::ShaderNodeBsdfRefraction::distribution_BECKMANN:
349                                 refraction->distribution = ustring("Beckmann");
350                                 break;
351                         case BL::ShaderNodeBsdfRefraction::distribution_GGX:
352                                 refraction->distribution = ustring("GGX");
353                                 break;
354                 }
355                 node = refraction;
356         }
357         else if (b_node.is_a(&RNA_ShaderNodeBsdfToon)) {
358                 BL::ShaderNodeBsdfToon b_toon_node(b_node);
359                 ToonBsdfNode *toon = new ToonBsdfNode();
360                 switch(b_toon_node.component()) {
361                         case BL::ShaderNodeBsdfToon::component_DIFFUSE:
362                                 toon->component = ustring("Diffuse");
363                                 break;
364                         case BL::ShaderNodeBsdfToon::component_GLOSSY:
365                                 toon->component = ustring("Glossy");
366                                 break;
367                 }
368                 node = toon;
369         }
370         else if (b_node.is_a(&RNA_ShaderNodeBsdfTranslucent)) {
371                 node = new TranslucentBsdfNode();
372         }
373         else if (b_node.is_a(&RNA_ShaderNodeBsdfTransparent)) {
374                 node = new TransparentBsdfNode();
375         }
376         else if (b_node.is_a(&RNA_ShaderNodeBsdfVelvet)) {
377                 node = new VelvetBsdfNode();
378         }
379         else if (b_node.is_a(&RNA_ShaderNodeEmission)) {
380                 node = new EmissionNode();
381         }
382         else if (b_node.is_a(&RNA_ShaderNodeAmbientOcclusion)) {
383                 node = new AmbientOcclusionNode();
384         }
385         else if (b_node.is_a(&RNA_ShaderNodeVolumeIsotropic)) {
386                 node = new IsotropicVolumeNode();
387         }
388         else if (b_node.is_a(&RNA_ShaderNodeVolumeTransparent)) {
389                 node = new TransparentVolumeNode();
390         }
391         else if (b_node.is_a(&RNA_ShaderNodeNewGeometry)) {
392                 node = new GeometryNode();
393         }
394         else if (b_node.is_a(&RNA_ShaderNodeWireframe)) {
395                 BL::ShaderNodeWireframe b_wireframe_node(b_node);
396                 WireframeNode *wire = new WireframeNode();
397                 wire->use_pixel_size = b_wireframe_node.use_pixel_size();
398                 node = wire;
399         }
400         else if (b_node.is_a(&RNA_ShaderNodeWavelength)) {
401                 node = new WavelengthNode();
402         }
403         else if (b_node.is_a(&RNA_ShaderNodeLightPath)) {
404                 node = new LightPathNode();
405         }
406         else if (b_node.is_a(&RNA_ShaderNodeLightFalloff)) {
407                 node = new LightFalloffNode();
408         }
409         else if (b_node.is_a(&RNA_ShaderNodeObjectInfo)) {
410                 node = new ObjectInfoNode();
411         }
412         else if (b_node.is_a(&RNA_ShaderNodeParticleInfo)) {
413                 node = new ParticleInfoNode();
414         }
415         else if (b_node.is_a(&RNA_ShaderNodeHairInfo)) {
416                 node = new HairInfoNode();
417         }
418         else if (b_node.is_a(&RNA_ShaderNodeBump)) {
419                 BL::ShaderNodeBump b_bump_node(b_node);
420                 BumpNode *bump = new BumpNode();
421                 bump->invert = b_bump_node.invert();
422                 node = bump;
423         }
424         else if (b_node.is_a(&RNA_ShaderNodeScript)) {
425 #ifdef WITH_OSL
426                 if(scene->shader_manager->use_osl()) {
427                         /* create script node */
428                         BL::ShaderNodeScript b_script_node(b_node);
429                         OSLScriptNode *script_node = new OSLScriptNode();
430                         
431                         /* Generate inputs/outputs from node sockets
432                          *
433                          * Note: the node sockets are generated from OSL parameters,
434                          * so the names match those of the corresponding parameters exactly.
435                          *
436                          * Note 2: ShaderInput/ShaderOutput store shallow string copies only!
437                          * Socket names must be stored in the extra lists instead. */
438                         BL::Node::inputs_iterator b_input;
439                         
440                         for (b_script_node.inputs.begin(b_input); b_input != b_script_node.inputs.end(); ++b_input) {
441                                 script_node->input_names.push_back(ustring(b_input->name()));
442                                 ShaderInput *input = script_node->add_input(script_node->input_names.back().c_str(),
443                                                                             convert_socket_type(*b_input));
444                                 set_default_value(input, b_node, *b_input, b_data, b_ntree);
445                         }
446                         
447                         BL::Node::outputs_iterator b_output;
448                         
449                         for (b_script_node.outputs.begin(b_output); b_output != b_script_node.outputs.end(); ++b_output) {
450                                 script_node->output_names.push_back(ustring(b_output->name()));
451                                 script_node->add_output(script_node->output_names.back().c_str(),
452                                                         convert_socket_type(*b_output));
453                         }
454                         
455                         /* load bytecode or filepath */
456                         OSLShaderManager *manager = (OSLShaderManager*)scene->shader_manager;
457                         string bytecode_hash = b_script_node.bytecode_hash();
458                         
459                         if(!bytecode_hash.empty()) {
460                                 /* loaded bytecode if not already done */
461                                 if(!manager->shader_test_loaded(bytecode_hash))
462                                         manager->shader_load_bytecode(bytecode_hash, b_script_node.bytecode());
463                                 
464                                 script_node->bytecode_hash = bytecode_hash;
465                         }
466                         else {
467                                 /* set filepath */
468                                 script_node->filepath = blender_absolute_path(b_data, b_ntree, b_script_node.filepath());
469                         }
470                         
471                         node = script_node;
472                 }
473 #endif
474         }
475         else if (b_node.is_a(&RNA_ShaderNodeTexImage)) {
476                 BL::ShaderNodeTexImage b_image_node(b_node);
477                 BL::Image b_image(b_image_node.image());
478                 ImageTextureNode *image = new ImageTextureNode();
479                 if(b_image) {
480                         /* builtin images will use callback-based reading because
481                          * they could only be loaded correct from blender side
482                          */
483                         bool is_builtin = b_image.packed_file() ||
484                                           b_image.source() == BL::Image::source_GENERATED ||
485                                           b_image.source() == BL::Image::source_MOVIE;
486
487                         if(is_builtin) {
488                                 /* for builtin images we're using image datablock name to find an image to
489                                  * read pixels from later
490                                  *
491                                  * also store frame number as well, so there's no differences in handling
492                                  * builtin names for packed images and movies
493                                  */
494                                 int scene_frame = b_scene.frame_current();
495                                 int image_frame = image_user_frame_number(b_image_node.image_user(), scene_frame);
496                                 image->filename = b_image.name() + "@" + string_printf("%d", image_frame);
497                                 image->builtin_data = b_image.ptr.data;
498                         }
499                         else {
500                                 image->filename = image_user_file_path(b_image_node.image_user(), b_image, b_scene.frame_current());
501                                 image->builtin_data = NULL;
502                         }
503
504                         image->animated = b_image_node.image_user().use_auto_refresh();
505                 }
506                 image->color_space = ImageTextureNode::color_space_enum[(int)b_image_node.color_space()];
507                 image->projection = ImageTextureNode::projection_enum[(int)b_image_node.projection()];
508                 image->projection_blend = b_image_node.projection_blend();
509                 get_tex_mapping(&image->tex_mapping, b_image_node.texture_mapping());
510                 node = image;
511         }
512         else if (b_node.is_a(&RNA_ShaderNodeTexEnvironment)) {
513                 BL::ShaderNodeTexEnvironment b_env_node(b_node);
514                 BL::Image b_image(b_env_node.image());
515                 EnvironmentTextureNode *env = new EnvironmentTextureNode();
516                 if(b_image) {
517                         bool is_builtin = b_image.packed_file() ||
518                                           b_image.source() == BL::Image::source_GENERATED ||
519                                           b_image.source() == BL::Image::source_MOVIE;
520
521                         if(is_builtin) {
522                                 int scene_frame = b_scene.frame_current();
523                                 int image_frame = image_user_frame_number(b_env_node.image_user(), scene_frame);
524                                 env->filename = b_image.name() + "@" + string_printf("%d", image_frame);
525                                 env->builtin_data = b_image.ptr.data;
526                         }
527                         else {
528                                 env->filename = image_user_file_path(b_env_node.image_user(), b_image, b_scene.frame_current());
529                                 env->animated = b_env_node.image_user().use_auto_refresh();
530                                 env->builtin_data = NULL;
531                         }
532                 }
533                 env->color_space = EnvironmentTextureNode::color_space_enum[(int)b_env_node.color_space()];
534                 env->projection = EnvironmentTextureNode::projection_enum[(int)b_env_node.projection()];
535                 get_tex_mapping(&env->tex_mapping, b_env_node.texture_mapping());
536                 node = env;
537         }
538         else if (b_node.is_a(&RNA_ShaderNodeTexGradient)) {
539                 BL::ShaderNodeTexGradient b_gradient_node(b_node);
540                 GradientTextureNode *gradient = new GradientTextureNode();
541                 gradient->type = GradientTextureNode::type_enum[(int)b_gradient_node.gradient_type()];
542                 get_tex_mapping(&gradient->tex_mapping, b_gradient_node.texture_mapping());
543                 node = gradient;
544         }
545         else if (b_node.is_a(&RNA_ShaderNodeTexVoronoi)) {
546                 BL::ShaderNodeTexVoronoi b_voronoi_node(b_node);
547                 VoronoiTextureNode *voronoi = new VoronoiTextureNode();
548                 voronoi->coloring = VoronoiTextureNode::coloring_enum[(int)b_voronoi_node.coloring()];
549                 get_tex_mapping(&voronoi->tex_mapping, b_voronoi_node.texture_mapping());
550                 node = voronoi;
551         }
552         else if (b_node.is_a(&RNA_ShaderNodeTexMagic)) {
553                 BL::ShaderNodeTexMagic b_magic_node(b_node);
554                 MagicTextureNode *magic = new MagicTextureNode();
555                 magic->depth = b_magic_node.turbulence_depth();
556                 get_tex_mapping(&magic->tex_mapping, b_magic_node.texture_mapping());
557                 node = magic;
558         }
559         else if (b_node.is_a(&RNA_ShaderNodeTexWave)) {
560                 BL::ShaderNodeTexWave b_wave_node(b_node);
561                 WaveTextureNode *wave = new WaveTextureNode();
562                 wave->type = WaveTextureNode::type_enum[(int)b_wave_node.wave_type()];
563                 get_tex_mapping(&wave->tex_mapping, b_wave_node.texture_mapping());
564                 node = wave;
565         }
566         else if (b_node.is_a(&RNA_ShaderNodeTexChecker)) {
567                 BL::ShaderNodeTexChecker b_checker_node(b_node);
568                 CheckerTextureNode *checker = new CheckerTextureNode();
569                 get_tex_mapping(&checker->tex_mapping, b_checker_node.texture_mapping());
570                 node = checker;
571         }
572         else if (b_node.is_a(&RNA_ShaderNodeTexBrick)) {
573                 BL::ShaderNodeTexBrick b_brick_node(b_node);
574                 BrickTextureNode *brick = new BrickTextureNode();
575                 brick->offset = b_brick_node.offset();
576                 brick->offset_frequency = b_brick_node.offset_frequency();
577                 brick->squash = b_brick_node.squash();
578                 brick->squash_frequency = b_brick_node.squash_frequency();
579                 get_tex_mapping(&brick->tex_mapping, b_brick_node.texture_mapping());
580                 node = brick;
581         }
582         else if (b_node.is_a(&RNA_ShaderNodeTexNoise)) {
583                 BL::ShaderNodeTexNoise b_noise_node(b_node);
584                 NoiseTextureNode *noise = new NoiseTextureNode();
585                 get_tex_mapping(&noise->tex_mapping, b_noise_node.texture_mapping());
586                 node = noise;
587         }
588         else if (b_node.is_a(&RNA_ShaderNodeTexMusgrave)) {
589                 BL::ShaderNodeTexMusgrave b_musgrave_node(b_node);
590                 MusgraveTextureNode *musgrave = new MusgraveTextureNode();
591                 musgrave->type = MusgraveTextureNode::type_enum[(int)b_musgrave_node.musgrave_type()];
592                 get_tex_mapping(&musgrave->tex_mapping, b_musgrave_node.texture_mapping());
593                 node = musgrave;
594         }
595         else if (b_node.is_a(&RNA_ShaderNodeTexCoord)) {
596                 BL::ShaderNodeTexCoord b_tex_coord_node(b_node);
597                 TextureCoordinateNode *tex_coord = new TextureCoordinateNode();
598                 tex_coord->from_dupli = b_tex_coord_node.from_dupli();
599                 node = tex_coord;
600         }
601         else if (b_node.is_a(&RNA_ShaderNodeTexSky)) {
602                 BL::ShaderNodeTexSky b_sky_node(b_node);
603                 SkyTextureNode *sky = new SkyTextureNode();
604                 sky->sun_direction = get_float3(b_sky_node.sun_direction());
605                 sky->turbidity = b_sky_node.turbidity();
606                 get_tex_mapping(&sky->tex_mapping, b_sky_node.texture_mapping());
607                 node = sky;
608         }
609         else if (b_node.is_a(&RNA_ShaderNodeNormalMap)) {
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         }
616         else if (b_node.is_a(&RNA_ShaderNodeTangent)) {
617                 BL::ShaderNodeTangent b_tangent_node(b_node);
618                 TangentNode *tangent = new TangentNode();
619                 tangent->direction_type = TangentNode::direction_type_enum[(int)b_tangent_node.direction_type()];
620                 tangent->axis = TangentNode::axis_enum[(int)b_tangent_node.axis()];
621                 tangent->attribute = b_tangent_node.uv_map();
622                 node = tangent;
623         }
624
625         if(node && node != graph->output())
626                 graph->add(node);
627
628         return node;
629 }
630
631 static ShaderInput *node_find_input_by_name(ShaderNode *node, BL::Node b_node, BL::NodeSocket b_socket)
632 {
633         BL::Node::inputs_iterator b_input;
634         string name = b_socket.name();
635         bool found = false;
636         int counter = 0, total = 0;
637         
638         for (b_node.inputs.begin(b_input); b_input != b_node.inputs.end(); ++b_input) {
639                 if (b_input->name() == name) {
640                         if (!found)
641                                 counter++;
642                         total++;
643                 }
644
645                 if(b_input->ptr.data == b_socket.ptr.data)
646                         found = true;
647         }
648         
649         /* rename if needed */
650         if (name == "Shader")
651                 name = "Closure";
652         
653         if (total > 1)
654                 name = string_printf("%s%d", name.c_str(), counter);
655         
656         return node->input(name.c_str());
657 }
658
659 static ShaderOutput *node_find_output_by_name(ShaderNode *node, BL::Node b_node, BL::NodeSocket b_socket)
660 {
661         BL::Node::outputs_iterator b_output;
662         string name = b_socket.name();
663         bool found = false;
664         int counter = 0, total = 0;
665         
666         for (b_node.outputs.begin(b_output); b_output != b_node.outputs.end(); ++b_output) {
667                 if (b_output->name() == name) {
668                         if (!found)
669                                 counter++;
670                         total++;
671                 }
672
673                 if(b_output->ptr.data == b_socket.ptr.data)
674                         found = true;
675         }
676         
677         /* rename if needed */
678         if (name == "Shader")
679                 name = "Closure";
680         
681         if (total > 1)
682                 name = string_printf("%s%d", name.c_str(), counter);
683         
684         return node->output(name.c_str());
685 }
686
687 static void add_nodes(Scene *scene, BL::BlendData b_data, BL::Scene b_scene, ShaderGraph *graph, BL::ShaderNodeTree b_ntree,
688                       const ProxyMap &proxy_input_map, const ProxyMap &proxy_output_map)
689 {
690         /* add nodes */
691         BL::ShaderNodeTree::nodes_iterator b_node;
692         PtrInputMap input_map;
693         PtrOutputMap output_map;
694         
695         BL::Node::inputs_iterator b_input;
696         BL::Node::outputs_iterator b_output;
697
698         for(b_ntree.nodes.begin(b_node); b_node != b_ntree.nodes.end(); ++b_node) {
699                 if (b_node->mute() || b_node->is_a(&RNA_NodeReroute)) {
700                         /* replace muted node with internal links */
701                         BL::Node::internal_links_iterator b_link;
702                         for (b_node->internal_links.begin(b_link); b_link != b_node->internal_links.end(); ++b_link) {
703                                 ProxyNode *proxy = new ProxyNode(convert_socket_type(b_link->to_socket()));
704                                 
705                                 input_map[b_link->from_socket().ptr.data] = proxy->inputs[0];
706                                 output_map[b_link->to_socket().ptr.data] = proxy->outputs[0];
707                                 
708                                 graph->add(proxy);
709                         }
710                 }
711                 else if (b_node->is_a(&RNA_ShaderNodeGroup) || b_node->is_a(&RNA_NodeCustomGroup)) {
712                         
713                         BL::ShaderNodeTree b_group_ntree(PointerRNA_NULL);
714                         if (b_node->is_a(&RNA_ShaderNodeGroup))
715                                 b_group_ntree = BL::ShaderNodeTree(((BL::NodeGroup)(*b_node)).node_tree());
716                         else
717                                 b_group_ntree = BL::ShaderNodeTree(((BL::NodeCustomGroup)(*b_node)).node_tree());
718                         ProxyMap group_proxy_input_map, group_proxy_output_map;
719                         
720                         /* Add a proxy node for each socket
721                          * Do this even if the node group has no internal tree,
722                          * so that links have something to connect to and assert won't fail.
723                          */
724                         for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
725                                 ProxyNode *proxy = new ProxyNode(convert_socket_type(*b_input));
726                                 graph->add(proxy);
727                                 
728                                 /* register the proxy node for internal binding */
729                                 group_proxy_input_map[b_input->identifier()] = proxy;
730                                 
731                                 input_map[b_input->ptr.data] = proxy->inputs[0];
732                                 
733                                 set_default_value(proxy->inputs[0], *b_node, *b_input, b_data, b_ntree);
734                         }
735                         for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
736                                 ProxyNode *proxy = new ProxyNode(convert_socket_type(*b_output));
737                                 graph->add(proxy);
738                                 
739                                 /* register the proxy node for internal binding */
740                                 group_proxy_output_map[b_output->identifier()] = proxy;
741                                 
742                                 output_map[b_output->ptr.data] = proxy->outputs[0];
743                         }
744                         
745                         if (b_group_ntree)
746                                 add_nodes(scene, b_data, b_scene, graph, b_group_ntree, group_proxy_input_map, group_proxy_output_map);
747                 }
748                 else if (b_node->is_a(&RNA_NodeGroupInput)) {
749                         /* map each socket to a proxy node */
750                         for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
751                                 ProxyMap::const_iterator proxy_it = proxy_input_map.find(b_output->identifier());
752                                 if (proxy_it != proxy_input_map.end()) {
753                                         ProxyNode *proxy = proxy_it->second;
754                                         
755                                         output_map[b_output->ptr.data] = proxy->outputs[0];
756                                 }
757                         }
758                 }
759                 else if (b_node->is_a(&RNA_NodeGroupOutput)) {
760                         BL::NodeGroupOutput b_output_node(*b_node);
761                         /* only the active group output is used */
762                         if (b_output_node.is_active_output()) {
763                                 /* map each socket to a proxy node */
764                                 for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
765                                         ProxyMap::const_iterator proxy_it = proxy_output_map.find(b_input->identifier());
766                                         if (proxy_it != proxy_output_map.end()) {
767                                                 ProxyNode *proxy = proxy_it->second;
768                                                 
769                                                 input_map[b_input->ptr.data] = proxy->inputs[0];
770                                                 
771                                                 set_default_value(proxy->inputs[0], *b_node, *b_input, b_data, b_ntree);
772                                         }
773                                 }
774                         }
775                 }
776                 else {
777                         ShaderNode *node = add_node(scene, b_data, b_scene, graph, b_ntree, BL::ShaderNode(*b_node));
778                         
779                         if(node) {
780                                 /* map node sockets for linking */
781                                 for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
782                                         ShaderInput *input = node_find_input_by_name(node, *b_node, *b_input);
783                                         input_map[b_input->ptr.data] = input;
784                                         
785                                         set_default_value(input, *b_node, *b_input, b_data, b_ntree);
786                                 }
787                                 for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
788                                         ShaderOutput *output = node_find_output_by_name(node, *b_node, *b_output);
789                                         output_map[b_output->ptr.data] = output;
790                                 }
791                         }
792                 }
793         }
794
795         /* connect nodes */
796         BL::NodeTree::links_iterator b_link;
797
798         for(b_ntree.links.begin(b_link); b_link != b_ntree.links.end(); ++b_link) {
799                 /* get blender link data */
800                 BL::NodeSocket b_from_sock = b_link->from_socket();
801                 BL::NodeSocket b_to_sock = b_link->to_socket();
802
803                 ShaderOutput *output = 0;
804                 ShaderInput *input = 0;
805                 
806                 PtrOutputMap::iterator output_it = output_map.find(b_from_sock.ptr.data);
807                 if (output_it != output_map.end())
808                         output = output_it->second;
809                 PtrInputMap::iterator input_it = input_map.find(b_to_sock.ptr.data);
810                 if (input_it != input_map.end())
811                         input = input_it->second;
812
813                 /* either node may be NULL when the node was not exported, typically
814                  * because the node type is not supported */
815                 if(output && input)
816                         graph->connect(output, input);
817         }
818 }
819
820 static void add_nodes(Scene *scene, BL::BlendData b_data, BL::Scene b_scene, ShaderGraph *graph, BL::ShaderNodeTree b_ntree)
821 {
822         static const ProxyMap empty_proxy_map;
823         add_nodes(scene, b_data, b_scene, graph, b_ntree, empty_proxy_map, empty_proxy_map);
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                                 BL::ShaderNodeTree b_ntree(b_mat->node_tree());
848
849                                 add_nodes(scene, b_data, b_scene, graph, b_ntree);
850                         }
851                         else {
852                                 ShaderNode *closure, *out;
853
854                                 closure = graph->add(new DiffuseBsdfNode());
855                                 closure->input("Color")->value = get_float3(b_mat->diffuse_color());
856                                 out = graph->output();
857
858                                 graph->connect(closure->output("BSDF"), out->input("Surface"));
859                         }
860
861                         /* settings */
862                         PointerRNA cmat = RNA_pointer_get(&b_mat->ptr, "cycles");
863                         shader->sample_as_light = get_boolean(cmat, "sample_as_light");
864                         shader->homogeneous_volume = get_boolean(cmat, "homogeneous_volume");
865
866                         shader->set_graph(graph);
867                         shader->tag_update(scene);
868                 }
869         }
870 }
871
872 /* Sync World */
873
874 void BlenderSync::sync_world(bool update_all)
875 {
876         Background *background = scene->background;
877         Background prevbackground = *background;
878
879         BL::World b_world = b_scene.world();
880
881         if(world_recalc || update_all || b_world.ptr.data != world_map) {
882                 Shader *shader = scene->shaders[scene->default_background];
883                 ShaderGraph *graph = new ShaderGraph();
884
885                 /* create nodes */
886                 if(b_world && b_world.use_nodes() && b_world.node_tree()) {
887                         BL::ShaderNodeTree b_ntree(b_world.node_tree());
888
889                         add_nodes(scene, b_data, b_scene, graph, b_ntree);
890                 }
891                 else if(b_world) {
892                         ShaderNode *closure, *out;
893
894                         closure = graph->add(new BackgroundNode());
895                         closure->input("Color")->value = get_float3(b_world.horizon_color());
896                         out = graph->output();
897
898                         graph->connect(closure->output("Background"), out->input("Surface"));
899                 }
900
901                 if(b_world) {
902                         /* AO */
903                         BL::WorldLighting b_light = b_world.light_settings();
904
905                         if(b_light.use_ambient_occlusion())
906                                 background->ao_factor = b_light.ao_factor();
907                         else
908                                 background->ao_factor = 0.0f;
909
910                         background->ao_distance = b_light.distance();
911
912                         /* visibility */
913                         PointerRNA cvisibility = RNA_pointer_get(&b_world.ptr, "cycles_visibility");
914                         uint visibility = 0;
915
916                         visibility |= get_boolean(cvisibility, "camera")? PATH_RAY_CAMERA: 0;
917                         visibility |= get_boolean(cvisibility, "diffuse")? PATH_RAY_DIFFUSE: 0;
918                         visibility |= get_boolean(cvisibility, "glossy")? PATH_RAY_GLOSSY: 0;
919                         visibility |= get_boolean(cvisibility, "transmission")? PATH_RAY_TRANSMIT: 0;
920
921                         background->visibility = visibility;
922                 }
923
924                 shader->set_graph(graph);
925                 shader->tag_update(scene);
926         }
927
928         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
929
930         /* when doing preview render check for BI's transparency settings,
931          * this is so because bledner's preview render routines are not able
932          * to tweak all cycles's settings depending on different circumstances
933          */
934         if(b_engine.is_preview() == false)
935                 background->transparent = get_boolean(cscene, "film_transparent");
936         else
937                 background->transparent = b_scene.render().alpha_mode() == BL::RenderSettings::alpha_mode_TRANSPARENT;
938
939         background->use = render_layer.use_background;
940
941         if(background->modified(prevbackground))
942                 background->tag_update(scene);
943 }
944
945 /* Sync Lamps */
946
947 void BlenderSync::sync_lamps(bool update_all)
948 {
949         shader_map.set_default(scene->shaders[scene->default_light]);
950
951         /* lamp loop */
952         BL::BlendData::lamps_iterator b_lamp;
953
954         for(b_data.lamps.begin(b_lamp); b_lamp != b_data.lamps.end(); ++b_lamp) {
955                 Shader *shader;
956                 
957                 /* test if we need to sync */
958                 if(shader_map.sync(&shader, *b_lamp) || update_all) {
959                         ShaderGraph *graph = new ShaderGraph();
960
961                         /* create nodes */
962                         if(b_lamp->use_nodes() && b_lamp->node_tree()) {
963                                 shader->name = b_lamp->name().c_str();
964
965                                 BL::ShaderNodeTree b_ntree(b_lamp->node_tree());
966
967                                 add_nodes(scene, b_data, b_scene, graph, b_ntree);
968                         }
969                         else {
970                                 ShaderNode *closure, *out;
971                                 float strength = 1.0f;
972
973                                 if(b_lamp->type() == BL::Lamp::type_POINT ||
974                                    b_lamp->type() == BL::Lamp::type_SPOT ||
975                                    b_lamp->type() == BL::Lamp::type_AREA)
976                                 {
977                                         strength = 100.0f;
978                                 }
979
980                                 closure = graph->add(new EmissionNode());
981                                 closure->input("Color")->value = get_float3(b_lamp->color());
982                                 closure->input("Strength")->value.x = strength;
983                                 out = graph->output();
984
985                                 graph->connect(closure->output("Emission"), out->input("Surface"));
986                         }
987
988                         shader->set_graph(graph);
989                         shader->tag_update(scene);
990                 }
991         }
992 }
993
994 void BlenderSync::sync_shaders()
995 {
996         /* for auto refresh images */
997         bool auto_refresh_update = false;
998
999         if(preview) {
1000                 ImageManager *image_manager = scene->image_manager;
1001                 int frame = b_scene.frame_current();
1002                 auto_refresh_update = image_manager->set_animation_frame_update(frame);
1003         }
1004
1005         shader_map.pre_sync();
1006
1007         sync_world(auto_refresh_update);
1008         sync_lamps(auto_refresh_update);
1009         sync_materials(auto_refresh_update);
1010
1011         /* false = don't delete unused shaders, not supported */
1012         shader_map.post_sync(false);
1013 }
1014
1015 CCL_NAMESPACE_END
1016