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