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