Cycles: Make all #include statements relative to cycles source directory
[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 "render/background.h"
18 #include "render/graph.h"
19 #include "render/light.h"
20 #include "render/nodes.h"
21 #include "render/osl.h"
22 #include "render/scene.h"
23 #include "render/shader.h"
24
25 #include "blender/blender_texture.h"
26 #include "blender/blender_sync.h"
27 #include "blender/blender_util.h"
28
29 #include "util/util_debug.h"
30 #include "util/util_string.h"
31 #include "util/util_task.h"
32
33 CCL_NAMESPACE_BEGIN
34
35 typedef map<void*, ShaderInput*> PtrInputMap;
36 typedef map<void*, ShaderOutput*> PtrOutputMap;
37 typedef map<string, ConvertNode*> ProxyMap;
38
39 /* Find */
40
41 void BlenderSync::find_shader(BL::ID& id,
42                               vector<Shader*>& used_shaders,
43                               Shader *default_shader)
44 {
45         Shader *shader = (id)? shader_map.find(id): default_shader;
46
47         used_shaders.push_back(shader);
48         shader->tag_used(scene);
49 }
50
51 /* RNA translation utilities */
52
53 static VolumeSampling get_volume_sampling(PointerRNA& ptr)
54 {
55         return (VolumeSampling)get_enum(ptr,
56                                         "volume_sampling",
57                                         VOLUME_NUM_SAMPLING,
58                                         VOLUME_SAMPLING_DISTANCE);
59 }
60
61 static VolumeInterpolation get_volume_interpolation(PointerRNA& ptr)
62 {
63         return (VolumeInterpolation)get_enum(ptr,
64                                              "volume_interpolation",
65                                              VOLUME_NUM_INTERPOLATION,
66                                              VOLUME_INTERPOLATION_LINEAR);
67 }
68
69 static DisplacementMethod get_displacement_method(PointerRNA& ptr)
70 {
71         return (DisplacementMethod)get_enum(ptr,
72                                             "displacement_method",
73                                             DISPLACE_NUM_METHODS,
74                                             DISPLACE_BUMP);
75 }
76
77 static int validate_enum_value(int value, int num_values, int default_value)
78 {
79         if(value >= num_values) {
80                 return default_value;
81         }
82         return value;
83 }
84
85 template<typename NodeType>
86 static InterpolationType get_image_interpolation(NodeType& b_node)
87 {
88         int value = b_node.interpolation();
89         return (InterpolationType)validate_enum_value(value,
90                                                       INTERPOLATION_NUM_TYPES,
91                                                       INTERPOLATION_LINEAR);
92 }
93
94 template<typename NodeType>
95 static ExtensionType get_image_extension(NodeType& b_node)
96 {
97         int value = b_node.extension();
98         return (ExtensionType)validate_enum_value(value,
99                                                   EXTENSION_NUM_TYPES,
100                                                   EXTENSION_REPEAT);
101 }
102
103 /* Graph */
104
105 static BL::NodeSocket get_node_output(BL::Node& b_node, const string& name)
106 {
107         BL::Node::outputs_iterator b_out;
108
109         for(b_node.outputs.begin(b_out); b_out != b_node.outputs.end(); ++b_out)
110                 if(b_out->name() == name)
111                         return *b_out;
112
113         assert(0);
114
115         return *b_out;
116 }
117
118 static float3 get_node_output_rgba(BL::Node& b_node, const string& name)
119 {
120         BL::NodeSocket b_sock = get_node_output(b_node, name);
121         float value[4];
122         RNA_float_get_array(&b_sock.ptr, "default_value", value);
123         return make_float3(value[0], value[1], value[2]);
124 }
125
126 static float get_node_output_value(BL::Node& b_node, const string& name)
127 {
128         BL::NodeSocket b_sock = get_node_output(b_node, name);
129         return RNA_float_get(&b_sock.ptr, "default_value");
130 }
131
132 static float3 get_node_output_vector(BL::Node& b_node, const string& name)
133 {
134         BL::NodeSocket b_sock = get_node_output(b_node, name);
135         float value[3];
136         RNA_float_get_array(&b_sock.ptr, "default_value", value);
137         return make_float3(value[0], value[1], value[2]);
138 }
139
140 static SocketType::Type convert_socket_type(BL::NodeSocket& b_socket)
141 {
142         switch(b_socket.type()) {
143                 case BL::NodeSocket::type_VALUE:
144                         return SocketType::FLOAT;
145                 case BL::NodeSocket::type_INT:
146                         return SocketType::INT;
147                 case BL::NodeSocket::type_VECTOR:
148                         return SocketType::VECTOR;
149                 case BL::NodeSocket::type_RGBA:
150                         return SocketType::COLOR;
151                 case BL::NodeSocket::type_STRING:
152                         return SocketType::STRING;
153                 case BL::NodeSocket::type_SHADER:
154                         return SocketType::CLOSURE;
155                 
156                 default:
157                         return SocketType::UNDEFINED;
158         }
159 }
160
161 static void set_default_value(ShaderInput *input,
162                               BL::NodeSocket& b_sock,
163                               BL::BlendData& b_data,
164                               BL::ID& b_id)
165 {
166         Node *node = input->parent;
167         const SocketType& socket = input->socket_type;
168
169         /* copy values for non linked inputs */
170         switch(input->type()) {
171                 case SocketType::FLOAT: {
172                         node->set(socket, get_float(b_sock.ptr, "default_value"));
173                         break;
174                 }
175                 case SocketType::INT: {
176                         node->set(socket, get_int(b_sock.ptr, "default_value"));
177                         break;
178                 }
179                 case SocketType::COLOR: {
180                         node->set(socket, float4_to_float3(get_float4(b_sock.ptr, "default_value")));
181                         break;
182                 }
183                 case SocketType::NORMAL:
184                 case SocketType::POINT:
185                 case SocketType::VECTOR: {
186                         node->set(socket, get_float3(b_sock.ptr, "default_value"));
187                         break;
188                 }
189                 case SocketType::STRING: {
190                         node->set(socket, (ustring)blender_absolute_path(b_data, b_id, get_string(b_sock.ptr, "default_value")));
191                         break;
192                 }
193                 default:
194                         break;
195         }
196 }
197
198 static void get_tex_mapping(TextureMapping *mapping, BL::TexMapping& b_mapping)
199 {
200         if(!b_mapping)
201                 return;
202
203         mapping->translation = get_float3(b_mapping.translation());
204         mapping->rotation = get_float3(b_mapping.rotation());
205         mapping->scale = get_float3(b_mapping.scale());
206         mapping->type = (TextureMapping::Type)b_mapping.vector_type();
207
208         mapping->x_mapping = (TextureMapping::Mapping)b_mapping.mapping_x();
209         mapping->y_mapping = (TextureMapping::Mapping)b_mapping.mapping_y();
210         mapping->z_mapping = (TextureMapping::Mapping)b_mapping.mapping_z();
211 }
212
213 static void get_tex_mapping(TextureMapping *mapping,
214                             BL::ShaderNodeMapping& b_mapping)
215 {
216         if(!b_mapping)
217                 return;
218
219         mapping->translation = get_float3(b_mapping.translation());
220         mapping->rotation = get_float3(b_mapping.rotation());
221         mapping->scale = get_float3(b_mapping.scale());
222         mapping->type = (TextureMapping::Type)b_mapping.vector_type();
223
224         mapping->use_minmax = b_mapping.use_min() || b_mapping.use_max();
225
226         if(b_mapping.use_min())
227                 mapping->min = get_float3(b_mapping.min());
228         if(b_mapping.use_max())
229                 mapping->max = get_float3(b_mapping.max());
230 }
231
232 static bool is_output_node(BL::Node& b_node)
233 {
234         return (b_node.is_a(&RNA_ShaderNodeOutputMaterial)
235                     || b_node.is_a(&RNA_ShaderNodeOutputWorld)
236                     || b_node.is_a(&RNA_ShaderNodeOutputLamp));
237 }
238
239 static ShaderNode *add_node(Scene *scene,
240                             BL::RenderEngine& b_engine,
241                             BL::BlendData& b_data,
242                             BL::Scene& b_scene,
243                             const bool background,
244                             ShaderGraph *graph,
245                             BL::ShaderNodeTree& b_ntree,
246                             BL::ShaderNode& b_node)
247 {
248         ShaderNode *node = NULL;
249
250         /* existing blender nodes */
251         if(b_node.is_a(&RNA_ShaderNodeRGBCurve)) {
252                 BL::ShaderNodeRGBCurve b_curve_node(b_node);
253                 BL::CurveMapping mapping(b_curve_node.mapping());
254                 RGBCurvesNode *curves = new RGBCurvesNode();
255                 curvemapping_color_to_array(mapping,
256                                             curves->curves,
257                                             RAMP_TABLE_SIZE,
258                                             true);
259                 curvemapping_minmax(mapping, true, &curves->min_x, &curves->max_x);
260                 node = curves;
261         }
262         if(b_node.is_a(&RNA_ShaderNodeVectorCurve)) {
263                 BL::ShaderNodeVectorCurve b_curve_node(b_node);
264                 BL::CurveMapping mapping(b_curve_node.mapping());
265                 VectorCurvesNode *curves = new VectorCurvesNode();
266                 curvemapping_color_to_array(mapping,
267                                             curves->curves,
268                                             RAMP_TABLE_SIZE,
269                                             false);
270                 curvemapping_minmax(mapping, false, &curves->min_x, &curves->max_x);
271                 node = curves;
272         }
273         else if(b_node.is_a(&RNA_ShaderNodeValToRGB)) {
274                 RGBRampNode *ramp = new RGBRampNode();
275                 BL::ShaderNodeValToRGB b_ramp_node(b_node);
276                 BL::ColorRamp b_color_ramp(b_ramp_node.color_ramp());
277                 colorramp_to_array(b_color_ramp, ramp->ramp, ramp->ramp_alpha, RAMP_TABLE_SIZE);
278                 ramp->interpolate = b_color_ramp.interpolation() != BL::ColorRamp::interpolation_CONSTANT;
279                 node = ramp;
280         }
281         else if(b_node.is_a(&RNA_ShaderNodeRGB)) {
282                 ColorNode *color = new ColorNode();
283                 color->value = get_node_output_rgba(b_node, "Color");
284                 node = color;
285         }
286         else if(b_node.is_a(&RNA_ShaderNodeValue)) {
287                 ValueNode *value = new ValueNode();
288                 value->value = get_node_output_value(b_node, "Value");
289                 node = value;
290         }
291         else if(b_node.is_a(&RNA_ShaderNodeCameraData)) {
292                 node = new CameraNode();
293         }
294         else if(b_node.is_a(&RNA_ShaderNodeInvert)) {
295                 node = new InvertNode();
296         }
297         else if(b_node.is_a(&RNA_ShaderNodeGamma)) {
298                 node = new GammaNode();
299         }
300         else if(b_node.is_a(&RNA_ShaderNodeBrightContrast)) {
301                 node = new BrightContrastNode();
302         }
303         else if(b_node.is_a(&RNA_ShaderNodeMixRGB)) {
304                 BL::ShaderNodeMixRGB b_mix_node(b_node);
305                 MixNode *mix = new MixNode();
306                 mix->type = (NodeMix)b_mix_node.blend_type();
307                 mix->use_clamp = b_mix_node.use_clamp();
308                 node = mix;
309         }
310         else if(b_node.is_a(&RNA_ShaderNodeSeparateRGB)) {
311                 node = new SeparateRGBNode();
312         }
313         else if(b_node.is_a(&RNA_ShaderNodeCombineRGB)) {
314                 node = new CombineRGBNode();
315         }
316         else if(b_node.is_a(&RNA_ShaderNodeSeparateHSV)) {
317                 node = new SeparateHSVNode();
318         }
319         else if(b_node.is_a(&RNA_ShaderNodeCombineHSV)) {
320                 node = new CombineHSVNode();
321         }
322         else if(b_node.is_a(&RNA_ShaderNodeSeparateXYZ)) {
323                 node = new SeparateXYZNode();
324         }
325         else if(b_node.is_a(&RNA_ShaderNodeCombineXYZ)) {
326                 node = new CombineXYZNode();
327         }
328         else if(b_node.is_a(&RNA_ShaderNodeHueSaturation)) {
329                 node = new HSVNode();
330         }
331         else if(b_node.is_a(&RNA_ShaderNodeRGBToBW)) {
332                 node = new RGBToBWNode();
333         }
334         else if(b_node.is_a(&RNA_ShaderNodeMath)) {
335                 BL::ShaderNodeMath b_math_node(b_node);
336                 MathNode *math = new MathNode();
337                 math->type = (NodeMath)b_math_node.operation();
338                 math->use_clamp = b_math_node.use_clamp();
339                 node = math;
340         }
341         else if(b_node.is_a(&RNA_ShaderNodeVectorMath)) {
342                 BL::ShaderNodeVectorMath b_vector_math_node(b_node);
343                 VectorMathNode *vmath = new VectorMathNode();
344                 vmath->type = (NodeVectorMath)b_vector_math_node.operation();
345                 node = vmath;
346         }
347         else if(b_node.is_a(&RNA_ShaderNodeVectorTransform)) {
348                 BL::ShaderNodeVectorTransform b_vector_transform_node(b_node);
349                 VectorTransformNode *vtransform = new VectorTransformNode();
350                 vtransform->type = (NodeVectorTransformType)b_vector_transform_node.vector_type();
351                 vtransform->convert_from = (NodeVectorTransformConvertSpace)b_vector_transform_node.convert_from();
352                 vtransform->convert_to = (NodeVectorTransformConvertSpace)b_vector_transform_node.convert_to();
353                 node = vtransform;
354         }
355         else if(b_node.is_a(&RNA_ShaderNodeNormal)) {
356                 BL::Node::outputs_iterator out_it;
357                 b_node.outputs.begin(out_it);
358
359                 NormalNode *norm = new NormalNode();
360                 norm->direction = get_node_output_vector(b_node, "Normal");
361                 node = norm;
362         }
363         else if(b_node.is_a(&RNA_ShaderNodeMapping)) {
364                 BL::ShaderNodeMapping b_mapping_node(b_node);
365                 MappingNode *mapping = new MappingNode();
366
367                 get_tex_mapping(&mapping->tex_mapping, b_mapping_node);
368
369                 node = mapping;
370         }
371         else if(b_node.is_a(&RNA_ShaderNodeFresnel)) {
372                 node = new FresnelNode();
373         }
374         else if(b_node.is_a(&RNA_ShaderNodeLayerWeight)) {
375                 node = new LayerWeightNode();
376         }
377         else if(b_node.is_a(&RNA_ShaderNodeAddShader)) {
378                 node = new AddClosureNode();
379         }
380         else if(b_node.is_a(&RNA_ShaderNodeMixShader)) {
381                 node = new MixClosureNode();
382         }
383         else if(b_node.is_a(&RNA_ShaderNodeAttribute)) {
384                 BL::ShaderNodeAttribute b_attr_node(b_node);
385                 AttributeNode *attr = new AttributeNode();
386                 attr->attribute = b_attr_node.attribute_name();
387                 node = attr;
388         }
389         else if(b_node.is_a(&RNA_ShaderNodeBackground)) {
390                 node = new BackgroundNode();
391         }
392         else if(b_node.is_a(&RNA_ShaderNodeHoldout)) {
393                 node = new HoldoutNode();
394         }
395         else if(b_node.is_a(&RNA_ShaderNodeBsdfAnisotropic)) {
396                 BL::ShaderNodeBsdfAnisotropic b_aniso_node(b_node);
397                 AnisotropicBsdfNode *aniso = new AnisotropicBsdfNode();
398
399                 switch(b_aniso_node.distribution()) {
400                         case BL::ShaderNodeBsdfAnisotropic::distribution_BECKMANN:
401                                 aniso->distribution = CLOSURE_BSDF_MICROFACET_BECKMANN_ANISO_ID;
402                                 break;
403                         case BL::ShaderNodeBsdfAnisotropic::distribution_GGX:
404                                 aniso->distribution = CLOSURE_BSDF_MICROFACET_GGX_ANISO_ID;
405                                 break;
406                         case BL::ShaderNodeBsdfAnisotropic::distribution_MULTI_GGX:
407                                 aniso->distribution = CLOSURE_BSDF_MICROFACET_MULTI_GGX_ANISO_ID;
408                                 break;
409                         case BL::ShaderNodeBsdfAnisotropic::distribution_ASHIKHMIN_SHIRLEY:
410                                 aniso->distribution = CLOSURE_BSDF_ASHIKHMIN_SHIRLEY_ANISO_ID;
411                                 break;
412                 }
413
414                 node = aniso;
415         }
416         else if(b_node.is_a(&RNA_ShaderNodeBsdfDiffuse)) {
417                 node = new DiffuseBsdfNode();
418         }
419         else if(b_node.is_a(&RNA_ShaderNodeSubsurfaceScattering)) {
420                 BL::ShaderNodeSubsurfaceScattering b_subsurface_node(b_node);
421
422                 SubsurfaceScatteringNode *subsurface = new SubsurfaceScatteringNode();
423
424                 switch(b_subsurface_node.falloff()) {
425                         case BL::ShaderNodeSubsurfaceScattering::falloff_CUBIC:
426                                 subsurface->falloff = CLOSURE_BSSRDF_CUBIC_ID;
427                                 break;
428                         case BL::ShaderNodeSubsurfaceScattering::falloff_GAUSSIAN:
429                                 subsurface->falloff = CLOSURE_BSSRDF_GAUSSIAN_ID;
430                                 break;
431                         case BL::ShaderNodeSubsurfaceScattering::falloff_BURLEY:
432                                 subsurface->falloff = CLOSURE_BSSRDF_BURLEY_ID;
433                                 break;
434                 }
435
436                 node = subsurface;
437         }
438         else if(b_node.is_a(&RNA_ShaderNodeBsdfGlossy)) {
439                 BL::ShaderNodeBsdfGlossy b_glossy_node(b_node);
440                 GlossyBsdfNode *glossy = new GlossyBsdfNode();
441                 
442                 switch(b_glossy_node.distribution()) {
443                         case BL::ShaderNodeBsdfGlossy::distribution_SHARP:
444                                 glossy->distribution = CLOSURE_BSDF_REFLECTION_ID;
445                                 break;
446                         case BL::ShaderNodeBsdfGlossy::distribution_BECKMANN:
447                                 glossy->distribution = CLOSURE_BSDF_MICROFACET_BECKMANN_ID;
448                                 break;
449                         case BL::ShaderNodeBsdfGlossy::distribution_GGX:
450                                 glossy->distribution = CLOSURE_BSDF_MICROFACET_GGX_ID;
451                                 break;
452                         case BL::ShaderNodeBsdfGlossy::distribution_ASHIKHMIN_SHIRLEY:
453                                 glossy->distribution = CLOSURE_BSDF_ASHIKHMIN_SHIRLEY_ID;
454                                 break;
455                         case BL::ShaderNodeBsdfGlossy::distribution_MULTI_GGX:
456                                 glossy->distribution = CLOSURE_BSDF_MICROFACET_MULTI_GGX_ID;
457                                 break;
458                 }
459                 node = glossy;
460         }
461         else if(b_node.is_a(&RNA_ShaderNodeBsdfGlass)) {
462                 BL::ShaderNodeBsdfGlass b_glass_node(b_node);
463                 GlassBsdfNode *glass = new GlassBsdfNode();
464                 switch(b_glass_node.distribution()) {
465                         case BL::ShaderNodeBsdfGlass::distribution_SHARP:
466                                 glass->distribution = CLOSURE_BSDF_SHARP_GLASS_ID;
467                                 break;
468                         case BL::ShaderNodeBsdfGlass::distribution_BECKMANN:
469                                 glass->distribution = CLOSURE_BSDF_MICROFACET_BECKMANN_GLASS_ID;
470                                 break;
471                         case BL::ShaderNodeBsdfGlass::distribution_GGX:
472                                 glass->distribution = CLOSURE_BSDF_MICROFACET_GGX_GLASS_ID;
473                                 break;
474                         case BL::ShaderNodeBsdfGlass::distribution_MULTI_GGX:
475                                 glass->distribution = CLOSURE_BSDF_MICROFACET_MULTI_GGX_GLASS_ID;
476                                 break;
477                 }
478                 node = glass;
479         }
480         else if(b_node.is_a(&RNA_ShaderNodeBsdfRefraction)) {
481                 BL::ShaderNodeBsdfRefraction b_refraction_node(b_node);
482                 RefractionBsdfNode *refraction = new RefractionBsdfNode();
483                 switch(b_refraction_node.distribution()) {
484                         case BL::ShaderNodeBsdfRefraction::distribution_SHARP:
485                                 refraction->distribution = CLOSURE_BSDF_REFRACTION_ID;
486                                 break;
487                         case BL::ShaderNodeBsdfRefraction::distribution_BECKMANN:
488                                 refraction->distribution = CLOSURE_BSDF_MICROFACET_BECKMANN_REFRACTION_ID;
489                                 break;
490                         case BL::ShaderNodeBsdfRefraction::distribution_GGX:
491                                 refraction->distribution = CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID;
492                                 break;
493                 }
494                 node = refraction;
495         }
496         else if(b_node.is_a(&RNA_ShaderNodeBsdfToon)) {
497                 BL::ShaderNodeBsdfToon b_toon_node(b_node);
498                 ToonBsdfNode *toon = new ToonBsdfNode();
499                 switch(b_toon_node.component()) {
500                         case BL::ShaderNodeBsdfToon::component_DIFFUSE:
501                                 toon->component = CLOSURE_BSDF_DIFFUSE_TOON_ID;
502                                 break;
503                         case BL::ShaderNodeBsdfToon::component_GLOSSY:
504                                 toon->component = CLOSURE_BSDF_GLOSSY_TOON_ID;
505                                 break;
506                 }
507                 node = toon;
508         }
509         else if(b_node.is_a(&RNA_ShaderNodeBsdfHair)) {
510                 BL::ShaderNodeBsdfHair b_hair_node(b_node);
511                 HairBsdfNode *hair = new HairBsdfNode();
512                 switch(b_hair_node.component()) {
513                         case BL::ShaderNodeBsdfHair::component_Reflection:
514                                 hair->component = CLOSURE_BSDF_HAIR_REFLECTION_ID;
515                                 break;
516                         case BL::ShaderNodeBsdfHair::component_Transmission:
517                                 hair->component = CLOSURE_BSDF_HAIR_TRANSMISSION_ID;
518                                 break;
519                 }
520                 node = hair;
521         }
522         else if(b_node.is_a(&RNA_ShaderNodeBsdfTranslucent)) {
523                 node = new TranslucentBsdfNode();
524         }
525         else if(b_node.is_a(&RNA_ShaderNodeBsdfTransparent)) {
526                 node = new TransparentBsdfNode();
527         }
528         else if(b_node.is_a(&RNA_ShaderNodeBsdfVelvet)) {
529                 node = new VelvetBsdfNode();
530         }
531         else if(b_node.is_a(&RNA_ShaderNodeEmission)) {
532                 node = new EmissionNode();
533         }
534         else if(b_node.is_a(&RNA_ShaderNodeAmbientOcclusion)) {
535                 node = new AmbientOcclusionNode();
536         }
537         else if(b_node.is_a(&RNA_ShaderNodeVolumeScatter)) {
538                 node = new ScatterVolumeNode();
539         }
540         else if(b_node.is_a(&RNA_ShaderNodeVolumeAbsorption)) {
541                 node = new AbsorptionVolumeNode();
542         }
543         else if(b_node.is_a(&RNA_ShaderNodeNewGeometry)) {
544                 node = new GeometryNode();
545         }
546         else if(b_node.is_a(&RNA_ShaderNodeWireframe)) {
547                 BL::ShaderNodeWireframe b_wireframe_node(b_node);
548                 WireframeNode *wire = new WireframeNode();
549                 wire->use_pixel_size = b_wireframe_node.use_pixel_size();
550                 node = wire;
551         }
552         else if(b_node.is_a(&RNA_ShaderNodeWavelength)) {
553                 node = new WavelengthNode();
554         }
555         else if(b_node.is_a(&RNA_ShaderNodeBlackbody)) {
556                 node = new BlackbodyNode();
557         }
558         else if(b_node.is_a(&RNA_ShaderNodeLightPath)) {
559                 node = new LightPathNode();
560         }
561         else if(b_node.is_a(&RNA_ShaderNodeLightFalloff)) {
562                 node = new LightFalloffNode();
563         }
564         else if(b_node.is_a(&RNA_ShaderNodeObjectInfo)) {
565                 node = new ObjectInfoNode();
566         }
567         else if(b_node.is_a(&RNA_ShaderNodeParticleInfo)) {
568                 node = new ParticleInfoNode();
569         }
570         else if(b_node.is_a(&RNA_ShaderNodeHairInfo)) {
571                 node = new HairInfoNode();
572         }
573         else if(b_node.is_a(&RNA_ShaderNodeBump)) {
574                 BL::ShaderNodeBump b_bump_node(b_node);
575                 BumpNode *bump = new BumpNode();
576                 bump->invert = b_bump_node.invert();
577                 node = bump;
578         }
579         else if(b_node.is_a(&RNA_ShaderNodeScript)) {
580 #ifdef WITH_OSL
581                 if(scene->shader_manager->use_osl()) {
582                         /* create script node */
583                         BL::ShaderNodeScript b_script_node(b_node);
584
585                         OSLShaderManager *manager = (OSLShaderManager*)scene->shader_manager;
586                         string bytecode_hash = b_script_node.bytecode_hash();
587
588                         if(!bytecode_hash.empty()) {
589                                 node = manager->osl_node("", bytecode_hash, b_script_node.bytecode());
590                         }
591                         else {
592                                 string absolute_filepath = blender_absolute_path(b_data, b_ntree, b_script_node.filepath());
593                                 node = manager->osl_node(absolute_filepath, "");
594                         }
595                 }
596 #else
597                 (void)b_data;
598                 (void)b_ntree;
599 #endif
600         }
601         else if(b_node.is_a(&RNA_ShaderNodeTexImage)) {
602                 BL::ShaderNodeTexImage b_image_node(b_node);
603                 BL::Image b_image(b_image_node.image());
604                 BL::ImageUser b_image_user(b_image_node.image_user());
605                 ImageTextureNode *image = new ImageTextureNode();
606                 if(b_image) {
607                         /* builtin images will use callback-based reading because
608                          * they could only be loaded correct from blender side
609                          */
610                         bool is_builtin = b_image.packed_file() ||
611                                           b_image.source() == BL::Image::source_GENERATED ||
612                                           b_image.source() == BL::Image::source_MOVIE ||
613                                           (b_engine.is_preview() &&
614                                            b_image.source() != BL::Image::source_SEQUENCE);
615
616                         if(is_builtin) {
617                                 /* for builtin images we're using image datablock name to find an image to
618                                  * read pixels from later
619                                  *
620                                  * also store frame number as well, so there's no differences in handling
621                                  * builtin names for packed images and movies
622                                  */
623                                 int scene_frame = b_scene.frame_current();
624                                 int image_frame = image_user_frame_number(b_image_user,
625                                                                           scene_frame);
626                                 image->filename = b_image.name() + "@" + string_printf("%d", image_frame);
627                                 image->builtin_data = b_image.ptr.data;
628                         }
629                         else {
630                                 image->filename = image_user_file_path(b_image_user,
631                                                                        b_image,
632                                                                        b_scene.frame_current());
633                                 image->builtin_data = NULL;
634                         }
635
636                         image->animated = b_image_node.image_user().use_auto_refresh();
637                         image->use_alpha = b_image.use_alpha();
638
639                         /* TODO(sergey): Does not work properly when we change builtin type. */
640                         if(b_image.is_updated()) {
641                                 scene->image_manager->tag_reload_image(
642                                         image->filename.string(),
643                                         image->builtin_data,
644                                         get_image_interpolation(b_image_node),
645                                         get_image_extension(b_image_node),
646                                         image->use_alpha);
647                         }
648                 }
649                 image->color_space = (NodeImageColorSpace)b_image_node.color_space();
650                 image->projection = (NodeImageProjection)b_image_node.projection();
651                 image->interpolation = get_image_interpolation(b_image_node);
652                 image->extension = get_image_extension(b_image_node);
653                 image->projection_blend = b_image_node.projection_blend();
654                 BL::TexMapping b_texture_mapping(b_image_node.texture_mapping());
655                 get_tex_mapping(&image->tex_mapping, b_texture_mapping);
656                 node = image;
657         }
658         else if(b_node.is_a(&RNA_ShaderNodeTexEnvironment)) {
659                 BL::ShaderNodeTexEnvironment b_env_node(b_node);
660                 BL::Image b_image(b_env_node.image());
661                 BL::ImageUser b_image_user(b_env_node.image_user());
662                 EnvironmentTextureNode *env = new EnvironmentTextureNode();
663                 if(b_image) {
664                         bool is_builtin = b_image.packed_file() ||
665                                           b_image.source() == BL::Image::source_GENERATED ||
666                                           b_image.source() == BL::Image::source_MOVIE ||
667                                           (b_engine.is_preview() &&
668                                            b_image.source() != BL::Image::source_SEQUENCE);
669
670                         if(is_builtin) {
671                                 int scene_frame = b_scene.frame_current();
672                                 int image_frame = image_user_frame_number(b_image_user,
673                                                                           scene_frame);
674                                 env->filename = b_image.name() + "@" + string_printf("%d", image_frame);
675                                 env->builtin_data = b_image.ptr.data;
676                         }
677                         else {
678                                 env->filename = image_user_file_path(b_image_user,
679                                                                      b_image,
680                                                                      b_scene.frame_current());
681                                 env->builtin_data = NULL;
682                         }
683
684                         env->animated = b_env_node.image_user().use_auto_refresh();
685                         env->use_alpha = b_image.use_alpha();
686
687                         /* TODO(sergey): Does not work properly when we change builtin type. */
688                         if(b_image.is_updated()) {
689                                 scene->image_manager->tag_reload_image(
690                                         env->filename.string(),
691                                         env->builtin_data,
692                                         get_image_interpolation(b_env_node),
693                                         EXTENSION_REPEAT,
694                                         env->use_alpha);
695                         }
696                 }
697                 env->color_space = (NodeImageColorSpace)b_env_node.color_space();
698                 env->interpolation = get_image_interpolation(b_env_node);
699                 env->projection = (NodeEnvironmentProjection)b_env_node.projection();
700                 BL::TexMapping b_texture_mapping(b_env_node.texture_mapping());
701                 get_tex_mapping(&env->tex_mapping, b_texture_mapping);
702                 node = env;
703         }
704         else if(b_node.is_a(&RNA_ShaderNodeTexGradient)) {
705                 BL::ShaderNodeTexGradient b_gradient_node(b_node);
706                 GradientTextureNode *gradient = new GradientTextureNode();
707                 gradient->type = (NodeGradientType)b_gradient_node.gradient_type();
708                 BL::TexMapping b_texture_mapping(b_gradient_node.texture_mapping());
709                 get_tex_mapping(&gradient->tex_mapping, b_texture_mapping);
710                 node = gradient;
711         }
712         else if(b_node.is_a(&RNA_ShaderNodeTexVoronoi)) {
713                 BL::ShaderNodeTexVoronoi b_voronoi_node(b_node);
714                 VoronoiTextureNode *voronoi = new VoronoiTextureNode();
715                 voronoi->coloring = (NodeVoronoiColoring)b_voronoi_node.coloring();
716                 BL::TexMapping b_texture_mapping(b_voronoi_node.texture_mapping());
717                 get_tex_mapping(&voronoi->tex_mapping, b_texture_mapping);
718                 node = voronoi;
719         }
720         else if(b_node.is_a(&RNA_ShaderNodeTexMagic)) {
721                 BL::ShaderNodeTexMagic b_magic_node(b_node);
722                 MagicTextureNode *magic = new MagicTextureNode();
723                 magic->depth = b_magic_node.turbulence_depth();
724                 BL::TexMapping b_texture_mapping(b_magic_node.texture_mapping());
725                 get_tex_mapping(&magic->tex_mapping, b_texture_mapping);
726                 node = magic;
727         }
728         else if(b_node.is_a(&RNA_ShaderNodeTexWave)) {
729                 BL::ShaderNodeTexWave b_wave_node(b_node);
730                 WaveTextureNode *wave = new WaveTextureNode();
731                 wave->type = (NodeWaveType)b_wave_node.wave_type();
732                 wave->profile = (NodeWaveProfile)b_wave_node.wave_profile();
733                 BL::TexMapping b_texture_mapping(b_wave_node.texture_mapping());
734                 get_tex_mapping(&wave->tex_mapping, b_texture_mapping);
735                 node = wave;
736         }
737         else if(b_node.is_a(&RNA_ShaderNodeTexChecker)) {
738                 BL::ShaderNodeTexChecker b_checker_node(b_node);
739                 CheckerTextureNode *checker = new CheckerTextureNode();
740                 BL::TexMapping b_texture_mapping(b_checker_node.texture_mapping());
741                 get_tex_mapping(&checker->tex_mapping, b_texture_mapping);
742                 node = checker;
743         }
744         else if(b_node.is_a(&RNA_ShaderNodeTexBrick)) {
745                 BL::ShaderNodeTexBrick b_brick_node(b_node);
746                 BrickTextureNode *brick = new BrickTextureNode();
747                 brick->offset = b_brick_node.offset();
748                 brick->offset_frequency = b_brick_node.offset_frequency();
749                 brick->squash = b_brick_node.squash();
750                 brick->squash_frequency = b_brick_node.squash_frequency();
751                 BL::TexMapping b_texture_mapping(b_brick_node.texture_mapping());
752                 get_tex_mapping(&brick->tex_mapping, b_texture_mapping);
753                 node = brick;
754         }
755         else if(b_node.is_a(&RNA_ShaderNodeTexNoise)) {
756                 BL::ShaderNodeTexNoise b_noise_node(b_node);
757                 NoiseTextureNode *noise = new NoiseTextureNode();
758                 BL::TexMapping b_texture_mapping(b_noise_node.texture_mapping());
759                 get_tex_mapping(&noise->tex_mapping, b_texture_mapping);
760                 node = noise;
761         }
762         else if(b_node.is_a(&RNA_ShaderNodeTexMusgrave)) {
763                 BL::ShaderNodeTexMusgrave b_musgrave_node(b_node);
764                 MusgraveTextureNode *musgrave = new MusgraveTextureNode();
765                 musgrave->type = (NodeMusgraveType)b_musgrave_node.musgrave_type();
766                 BL::TexMapping b_texture_mapping(b_musgrave_node.texture_mapping());
767                 get_tex_mapping(&musgrave->tex_mapping, b_texture_mapping);
768                 node = musgrave;
769         }
770         else if(b_node.is_a(&RNA_ShaderNodeTexCoord)) {
771                 BL::ShaderNodeTexCoord b_tex_coord_node(b_node);
772                 TextureCoordinateNode *tex_coord = new TextureCoordinateNode();
773                 tex_coord->from_dupli = b_tex_coord_node.from_dupli();
774                 if(b_tex_coord_node.object()) {
775                         tex_coord->use_transform = true;
776                         tex_coord->ob_tfm = get_transform(b_tex_coord_node.object().matrix_world());
777                 }
778                 node = tex_coord;
779         }
780         else if(b_node.is_a(&RNA_ShaderNodeTexSky)) {
781                 BL::ShaderNodeTexSky b_sky_node(b_node);
782                 SkyTextureNode *sky = new SkyTextureNode();
783                 sky->type = (NodeSkyType)b_sky_node.sky_type();
784                 sky->sun_direction = normalize(get_float3(b_sky_node.sun_direction()));
785                 sky->turbidity = b_sky_node.turbidity();
786                 sky->ground_albedo = b_sky_node.ground_albedo();
787                 BL::TexMapping b_texture_mapping(b_sky_node.texture_mapping());
788                 get_tex_mapping(&sky->tex_mapping, b_texture_mapping);
789                 node = sky;
790         }
791         else if(b_node.is_a(&RNA_ShaderNodeNormalMap)) {
792                 BL::ShaderNodeNormalMap b_normal_map_node(b_node);
793                 NormalMapNode *nmap = new NormalMapNode();
794                 nmap->space = (NodeNormalMapSpace)b_normal_map_node.space();
795                 nmap->attribute = b_normal_map_node.uv_map();
796                 node = nmap;
797         }
798         else if(b_node.is_a(&RNA_ShaderNodeTangent)) {
799                 BL::ShaderNodeTangent b_tangent_node(b_node);
800                 TangentNode *tangent = new TangentNode();
801                 tangent->direction_type = (NodeTangentDirectionType)b_tangent_node.direction_type();
802                 tangent->axis = (NodeTangentAxis)b_tangent_node.axis();
803                 tangent->attribute = b_tangent_node.uv_map();
804                 node = tangent;
805         }
806         else if(b_node.is_a(&RNA_ShaderNodeUVMap)) {
807                 BL::ShaderNodeUVMap b_uvmap_node(b_node);
808                 UVMapNode *uvm = new UVMapNode();
809                 uvm->attribute = b_uvmap_node.uv_map();
810                 uvm->from_dupli = b_uvmap_node.from_dupli();
811                 node = uvm;
812         }
813         else if(b_node.is_a(&RNA_ShaderNodeTexPointDensity)) {
814                 BL::ShaderNodeTexPointDensity b_point_density_node(b_node);
815                 PointDensityTextureNode *point_density = new PointDensityTextureNode();
816                 point_density->filename = b_point_density_node.name();
817                 point_density->space = (NodeTexVoxelSpace)b_point_density_node.space();
818                 point_density->interpolation = get_image_interpolation(b_point_density_node);
819                 point_density->builtin_data = b_point_density_node.ptr.data;
820
821                 /* 1 - render settings, 0 - vewport settings. */
822                 int settings = background ? 1 : 0;
823
824                 /* TODO(sergey): Use more proper update flag. */
825                 if(true) {
826                         b_point_density_node.cache_point_density(b_scene, settings);
827                         scene->image_manager->tag_reload_image(
828                                 point_density->filename.string(),
829                                 point_density->builtin_data,
830                                 point_density->interpolation,
831                                 EXTENSION_CLIP,
832                                 true);
833                 }
834                 node = point_density;
835
836                 /* Transformation form world space to texture space.
837                  *
838                  * NOTE: Do this after the texture is cached, this is because getting
839                  * min/max will need to access this cache.
840                  */
841                 BL::Object b_ob(b_point_density_node.object());
842                 if(b_ob) {
843                         float3 loc, size;
844                         point_density_texture_space(b_scene,
845                                                     b_point_density_node,
846                                                     settings,
847                                                     loc,
848                                                     size);
849                         point_density->tfm =
850                                 transform_translate(-loc) * transform_scale(size) *
851                                 transform_inverse(get_transform(b_ob.matrix_world()));
852                 }
853         }
854
855         if(node) {
856                 node->name = b_node.name();
857                 graph->add(node);
858         }
859
860         return node;
861 }
862
863 static bool node_use_modified_socket_name(ShaderNode *node)
864 {
865         if(node->special_type == SHADER_SPECIAL_TYPE_SCRIPT)
866                 return false;
867
868         return true;
869 }
870
871 static ShaderInput *node_find_input_by_name(ShaderNode *node,
872                                             BL::Node& b_node,
873                                             BL::NodeSocket& b_socket)
874 {
875         string name = b_socket.name();
876         
877         if(node_use_modified_socket_name(node)) {
878                 BL::Node::inputs_iterator b_input;
879                 bool found = false;
880                 int counter = 0, total = 0;
881
882                 for(b_node.inputs.begin(b_input); b_input != b_node.inputs.end(); ++b_input) {
883                         if(b_input->name() == name) {
884                                 if(!found)
885                                         counter++;
886                                 total++;
887                         }
888
889                         if(b_input->ptr.data == b_socket.ptr.data)
890                                 found = true;
891                 }
892
893                 /* rename if needed */
894                 if(name == "Shader")
895                         name = "Closure";
896
897                 if(total > 1)
898                         name = string_printf("%s%d", name.c_str(), counter);
899         }
900
901         return node->input(name.c_str());
902 }
903
904 static ShaderOutput *node_find_output_by_name(ShaderNode *node,
905                                               BL::Node& b_node,
906                                               BL::NodeSocket& b_socket)
907 {
908         string name = b_socket.name();
909
910         if(node_use_modified_socket_name(node)) {
911                 BL::Node::outputs_iterator b_output;
912                 bool found = false;
913                 int counter = 0, total = 0;
914
915                 for(b_node.outputs.begin(b_output); b_output != b_node.outputs.end(); ++b_output) {
916                         if(b_output->name() == name) {
917                                 if(!found)
918                                         counter++;
919                                 total++;
920                         }
921
922                         if(b_output->ptr.data == b_socket.ptr.data)
923                                 found = true;
924                 }
925
926                 /* rename if needed */
927                 if(name == "Shader")
928                         name = "Closure";
929
930                 if(total > 1)
931                         name = string_printf("%s%d", name.c_str(), counter);
932         }
933
934         return node->output(name.c_str());
935 }
936
937 static void add_nodes(Scene *scene,
938                       BL::RenderEngine& b_engine,
939                       BL::BlendData& b_data,
940                       BL::Scene& b_scene,
941                       const bool background,
942                       ShaderGraph *graph,
943                       BL::ShaderNodeTree& b_ntree,
944                       const ProxyMap &proxy_input_map,
945                       const ProxyMap &proxy_output_map)
946 {
947         /* add nodes */
948         BL::ShaderNodeTree::nodes_iterator b_node;
949         PtrInputMap input_map;
950         PtrOutputMap output_map;
951
952         BL::Node::inputs_iterator b_input;
953         BL::Node::outputs_iterator b_output;
954
955         /* find the node to use for output if there are multiple */
956         bool found_active_output = false;
957         BL::ShaderNode output_node(PointerRNA_NULL);
958
959         for(b_ntree.nodes.begin(b_node); b_node != b_ntree.nodes.end(); ++b_node) {
960                 if(is_output_node(*b_node)) {
961                         BL::ShaderNodeOutputMaterial b_output_node(*b_node);
962
963                         if(b_output_node.is_active_output()) {
964                                 output_node = b_output_node;
965                                 found_active_output = true;
966                                 break;
967                         }
968                         else if(!output_node.ptr.data && !found_active_output) {
969                                 output_node = b_output_node;
970                         }
971                 }
972         }
973
974         /* add nodes */
975         for(b_ntree.nodes.begin(b_node); b_node != b_ntree.nodes.end(); ++b_node) {
976                 if(b_node->mute() || b_node->is_a(&RNA_NodeReroute)) {
977                         /* replace muted node with internal links */
978                         BL::Node::internal_links_iterator b_link;
979                         for(b_node->internal_links.begin(b_link); b_link != b_node->internal_links.end(); ++b_link) {
980                                 BL::NodeSocket to_socket(b_link->to_socket());
981                                 SocketType::Type to_socket_type = convert_socket_type(to_socket);
982                                 ConvertNode *proxy = new ConvertNode(to_socket_type, to_socket_type, true);
983
984                                 input_map[b_link->from_socket().ptr.data] = proxy->inputs[0];
985                                 output_map[b_link->to_socket().ptr.data] = proxy->outputs[0];
986
987                                 graph->add(proxy);
988                         }
989                 }
990                 else if(b_node->is_a(&RNA_ShaderNodeGroup) || b_node->is_a(&RNA_NodeCustomGroup)) {
991                         
992                         BL::ShaderNodeTree b_group_ntree(PointerRNA_NULL);
993                         if(b_node->is_a(&RNA_ShaderNodeGroup))
994                                 b_group_ntree = BL::ShaderNodeTree(((BL::NodeGroup)(*b_node)).node_tree());
995                         else
996                                 b_group_ntree = BL::ShaderNodeTree(((BL::NodeCustomGroup)(*b_node)).node_tree());
997                         ProxyMap group_proxy_input_map, group_proxy_output_map;
998
999                         /* Add a proxy node for each socket
1000                          * Do this even if the node group has no internal tree,
1001                          * so that links have something to connect to and assert won't fail.
1002                          */
1003                         for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
1004                                 SocketType::Type input_type = convert_socket_type(*b_input);
1005                                 ConvertNode *proxy = new ConvertNode(input_type, input_type, true);
1006                                 graph->add(proxy);
1007
1008                                 /* register the proxy node for internal binding */
1009                                 group_proxy_input_map[b_input->identifier()] = proxy;
1010
1011                                 input_map[b_input->ptr.data] = proxy->inputs[0];
1012
1013                                 set_default_value(proxy->inputs[0], *b_input, b_data, b_ntree);
1014                         }
1015                         for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
1016                                 SocketType::Type output_type = convert_socket_type(*b_output);
1017                                 ConvertNode *proxy = new ConvertNode(output_type, output_type, true);
1018                                 graph->add(proxy);
1019
1020                                 /* register the proxy node for internal binding */
1021                                 group_proxy_output_map[b_output->identifier()] = proxy;
1022
1023                                 output_map[b_output->ptr.data] = proxy->outputs[0];
1024                         }
1025                         
1026                         if(b_group_ntree) {
1027                                 add_nodes(scene,
1028                                           b_engine,
1029                                           b_data,
1030                                           b_scene,
1031                                           background,
1032                                           graph,
1033                                           b_group_ntree,
1034                                           group_proxy_input_map,
1035                                           group_proxy_output_map);
1036                         }
1037                 }
1038                 else if(b_node->is_a(&RNA_NodeGroupInput)) {
1039                         /* map each socket to a proxy node */
1040                         for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
1041                                 ProxyMap::const_iterator proxy_it = proxy_input_map.find(b_output->identifier());
1042                                 if(proxy_it != proxy_input_map.end()) {
1043                                         ConvertNode *proxy = proxy_it->second;
1044
1045                                         output_map[b_output->ptr.data] = proxy->outputs[0];
1046                                 }
1047                         }
1048                 }
1049                 else if(b_node->is_a(&RNA_NodeGroupOutput)) {
1050                         BL::NodeGroupOutput b_output_node(*b_node);
1051                         /* only the active group output is used */
1052                         if(b_output_node.is_active_output()) {
1053                                 /* map each socket to a proxy node */
1054                                 for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
1055                                         ProxyMap::const_iterator proxy_it = proxy_output_map.find(b_input->identifier());
1056                                         if(proxy_it != proxy_output_map.end()) {
1057                                                 ConvertNode *proxy = proxy_it->second;
1058
1059                                                 input_map[b_input->ptr.data] = proxy->inputs[0];
1060
1061                                                 set_default_value(proxy->inputs[0], *b_input, b_data, b_ntree);
1062                                         }
1063                                 }
1064                         }
1065                 }
1066                 else {
1067                         ShaderNode *node = NULL;
1068
1069                         if(is_output_node(*b_node)) {
1070                                 if(b_node->ptr.data == output_node.ptr.data) {
1071                                         node = graph->output();
1072                                 }
1073                         }
1074                         else {
1075                                 BL::ShaderNode b_shader_node(*b_node);
1076                                 node = add_node(scene,
1077                                                 b_engine,
1078                                                 b_data,
1079                                                 b_scene,
1080                                                 background,
1081                                                 graph,
1082                                                 b_ntree,
1083                                                 b_shader_node);
1084                         }
1085
1086                         if(node) {
1087                                 /* map node sockets for linking */
1088                                 for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
1089                                         ShaderInput *input = node_find_input_by_name(node, *b_node, *b_input);
1090                                         if(!input) {
1091                                                 /* XXX should not happen, report error? */
1092                                                 continue;
1093                                         }
1094                                         input_map[b_input->ptr.data] = input;
1095
1096                                         set_default_value(input, *b_input, b_data, b_ntree);
1097                                 }
1098                                 for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
1099                                         ShaderOutput *output = node_find_output_by_name(node, *b_node, *b_output);
1100                                         if(!output) {
1101                                                 /* XXX should not happen, report error? */
1102                                                 continue;
1103                                         }
1104                                         output_map[b_output->ptr.data] = output;
1105                                 }
1106                         }
1107                 }
1108         }
1109
1110         /* connect nodes */
1111         BL::NodeTree::links_iterator b_link;
1112
1113         for(b_ntree.links.begin(b_link); b_link != b_ntree.links.end(); ++b_link) {
1114                 /* Ignore invalid links to avoid unwanted cycles created in graph. */
1115                 if(!b_link->is_valid()) {
1116                         continue;
1117                 }
1118                 /* get blender link data */
1119                 BL::NodeSocket b_from_sock = b_link->from_socket();
1120                 BL::NodeSocket b_to_sock = b_link->to_socket();
1121
1122                 ShaderOutput *output = 0;
1123                 ShaderInput *input = 0;
1124
1125                 PtrOutputMap::iterator output_it = output_map.find(b_from_sock.ptr.data);
1126                 if(output_it != output_map.end())
1127                         output = output_it->second;
1128                 PtrInputMap::iterator input_it = input_map.find(b_to_sock.ptr.data);
1129                 if(input_it != input_map.end())
1130                         input = input_it->second;
1131
1132                 /* either node may be NULL when the node was not exported, typically
1133                  * because the node type is not supported */
1134                 if(output && input)
1135                         graph->connect(output, input);
1136         }
1137 }
1138
1139 static void add_nodes(Scene *scene,
1140                       BL::RenderEngine& b_engine,
1141                       BL::BlendData& b_data,
1142                       BL::Scene& b_scene,
1143                       const bool background,
1144                       ShaderGraph *graph,
1145                       BL::ShaderNodeTree& b_ntree)
1146 {
1147         static const ProxyMap empty_proxy_map;
1148         add_nodes(scene,
1149                   b_engine,
1150                   b_data,
1151                   b_scene,
1152                   background,
1153                   graph,
1154                   b_ntree,
1155                   empty_proxy_map,
1156                   empty_proxy_map);
1157 }
1158
1159 /* Sync Materials */
1160
1161 void BlenderSync::sync_materials(bool update_all)
1162 {
1163         shader_map.set_default(scene->default_surface);
1164
1165         /* material loop */
1166         BL::BlendData::materials_iterator b_mat;
1167
1168         TaskPool pool;
1169
1170         for(b_data.materials.begin(b_mat); b_mat != b_data.materials.end(); ++b_mat) {
1171                 Shader *shader;
1172
1173                 /* test if we need to sync */
1174                 if(shader_map.sync(&shader, *b_mat) || update_all) {
1175                         ShaderGraph *graph = new ShaderGraph();
1176
1177                         shader->name = b_mat->name().c_str();
1178                         shader->pass_id = b_mat->pass_index();
1179
1180                         /* create nodes */
1181                         if(b_mat->use_nodes() && b_mat->node_tree()) {
1182                                 BL::ShaderNodeTree b_ntree(b_mat->node_tree());
1183
1184                                 add_nodes(scene, b_engine, b_data, b_scene, !preview, graph, b_ntree);
1185                         }
1186                         else {
1187                                 DiffuseBsdfNode *diffuse = new DiffuseBsdfNode();
1188                                 diffuse->color = get_float3(b_mat->diffuse_color());
1189                                 graph->add(diffuse);
1190
1191                                 ShaderNode *out = graph->output();
1192                                 graph->connect(diffuse->output("BSDF"), out->input("Surface"));
1193                         }
1194
1195                         /* settings */
1196                         PointerRNA cmat = RNA_pointer_get(&b_mat->ptr, "cycles");
1197                         shader->use_mis = get_boolean(cmat, "sample_as_light");
1198                         shader->use_transparent_shadow = get_boolean(cmat, "use_transparent_shadow");
1199                         shader->heterogeneous_volume = !get_boolean(cmat, "homogeneous_volume");
1200                         shader->volume_sampling_method = get_volume_sampling(cmat);
1201                         shader->volume_interpolation_method = get_volume_interpolation(cmat);
1202                         shader->displacement_method = (experimental) ? get_displacement_method(cmat) : DISPLACE_BUMP;
1203
1204                         shader->set_graph(graph);
1205
1206                         /* By simplifying the shader graph as soon as possible, some redundant shader nodes
1207                          * might be removed which prevents loading unneccessary attributes later.
1208                          *
1209                          * However, since graph simplification also accounts for e.g. mix weight, this would
1210                          * cause frequent expensive resyncs in interactive sessions, so for those sessions
1211                          * optimization is only performed right before compiling. */
1212                         if(!preview) {
1213                                 pool.push(function_bind(&ShaderGraph::simplify, shader->graph, scene));
1214                         }
1215
1216                         shader->tag_update(scene);
1217                 }
1218         }
1219
1220         pool.wait_work();
1221 }
1222
1223 /* Sync World */
1224
1225 void BlenderSync::sync_world(bool update_all)
1226 {
1227         Background *background = scene->background;
1228         Background prevbackground = *background;
1229
1230         BL::World b_world = b_scene.world();
1231
1232         if(world_recalc || update_all || b_world.ptr.data != world_map) {
1233                 Shader *shader = scene->default_background;
1234                 ShaderGraph *graph = new ShaderGraph();
1235
1236                 /* create nodes */
1237                 if(b_world && b_world.use_nodes() && b_world.node_tree()) {
1238                         BL::ShaderNodeTree b_ntree(b_world.node_tree());
1239
1240                         add_nodes(scene, b_engine, b_data, b_scene, !preview, graph, b_ntree);
1241
1242                         /* volume */
1243                         PointerRNA cworld = RNA_pointer_get(&b_world.ptr, "cycles");
1244                         shader->heterogeneous_volume = !get_boolean(cworld, "homogeneous_volume");
1245                         shader->volume_sampling_method = get_volume_sampling(cworld);
1246                         shader->volume_interpolation_method = get_volume_interpolation(cworld);
1247                 }
1248                 else if(b_world) {
1249                         BackgroundNode *background = new BackgroundNode();
1250                         background->color = get_float3(b_world.horizon_color());
1251                         graph->add(background);
1252
1253                         ShaderNode *out = graph->output();
1254                         graph->connect(background->output("Background"), out->input("Surface"));
1255                 }
1256
1257                 if(b_world) {
1258                         /* AO */
1259                         BL::WorldLighting b_light = b_world.light_settings();
1260
1261                         if(b_light.use_ambient_occlusion())
1262                                 background->ao_factor = b_light.ao_factor();
1263                         else
1264                                 background->ao_factor = 0.0f;
1265
1266                         background->ao_distance = b_light.distance();
1267
1268                         /* visibility */
1269                         PointerRNA cvisibility = RNA_pointer_get(&b_world.ptr, "cycles_visibility");
1270                         uint visibility = 0;
1271
1272                         visibility |= get_boolean(cvisibility, "camera")? PATH_RAY_CAMERA: 0;
1273                         visibility |= get_boolean(cvisibility, "diffuse")? PATH_RAY_DIFFUSE: 0;
1274                         visibility |= get_boolean(cvisibility, "glossy")? PATH_RAY_GLOSSY: 0;
1275                         visibility |= get_boolean(cvisibility, "transmission")? PATH_RAY_TRANSMIT: 0;
1276                         visibility |= get_boolean(cvisibility, "scatter")? PATH_RAY_VOLUME_SCATTER: 0;
1277
1278                         background->visibility = visibility;
1279                 }
1280                 else {
1281                         background->ao_factor = 0.0f;
1282                         background->ao_distance = FLT_MAX;
1283                 }
1284
1285                 shader->set_graph(graph);
1286                 shader->tag_update(scene);
1287                 background->tag_update(scene);
1288         }
1289
1290         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
1291
1292         /* when doing preview render check for BI's transparency settings,
1293          * this is so because Blender's preview render routines are not able
1294          * to tweak all cycles's settings depending on different circumstances
1295          */
1296         if(b_engine.is_preview() == false)
1297                 background->transparent = get_boolean(cscene, "film_transparent");
1298         else
1299                 background->transparent = b_scene.render().alpha_mode() == BL::RenderSettings::alpha_mode_TRANSPARENT;
1300
1301         background->use_shader = render_layer.use_background_shader;
1302         background->use_ao = render_layer.use_background_ao;
1303
1304         if(background->modified(prevbackground))
1305                 background->tag_update(scene);
1306 }
1307
1308 /* Sync Lamps */
1309
1310 void BlenderSync::sync_lamps(bool update_all)
1311 {
1312         shader_map.set_default(scene->default_light);
1313
1314         /* lamp loop */
1315         BL::BlendData::lamps_iterator b_lamp;
1316
1317         for(b_data.lamps.begin(b_lamp); b_lamp != b_data.lamps.end(); ++b_lamp) {
1318                 Shader *shader;
1319
1320                 /* test if we need to sync */
1321                 if(shader_map.sync(&shader, *b_lamp) || update_all) {
1322                         ShaderGraph *graph = new ShaderGraph();
1323
1324                         /* create nodes */
1325                         if(b_lamp->use_nodes() && b_lamp->node_tree()) {
1326                                 shader->name = b_lamp->name().c_str();
1327
1328                                 BL::ShaderNodeTree b_ntree(b_lamp->node_tree());
1329
1330                                 add_nodes(scene, b_engine, b_data, b_scene, !preview, graph, b_ntree);
1331                         }
1332                         else {
1333                                 float strength = 1.0f;
1334
1335                                 if(b_lamp->type() == BL::Lamp::type_POINT ||
1336                                    b_lamp->type() == BL::Lamp::type_SPOT ||
1337                                    b_lamp->type() == BL::Lamp::type_AREA)
1338                                 {
1339                                         strength = 100.0f;
1340                                 }
1341
1342                                 EmissionNode *emission = new EmissionNode();
1343                                 emission->color = get_float3(b_lamp->color());
1344                                 emission->strength = strength;
1345                                 graph->add(emission);
1346
1347                                 ShaderNode *out = graph->output();
1348                                 graph->connect(emission->output("Emission"), out->input("Surface"));
1349                         }
1350
1351                         shader->set_graph(graph);
1352                         shader->tag_update(scene);
1353                 }
1354         }
1355 }
1356
1357 void BlenderSync::sync_shaders()
1358 {
1359         /* for auto refresh images */
1360         bool auto_refresh_update = false;
1361
1362         if(preview) {
1363                 ImageManager *image_manager = scene->image_manager;
1364                 int frame = b_scene.frame_current();
1365                 auto_refresh_update = image_manager->set_animation_frame_update(frame);
1366         }
1367
1368         shader_map.pre_sync();
1369
1370         sync_world(auto_refresh_update);
1371         sync_lamps(auto_refresh_update);
1372         sync_materials(auto_refresh_update);
1373
1374         /* false = don't delete unused shaders, not supported */
1375         shader_map.post_sync(false);
1376 }
1377
1378 CCL_NAMESPACE_END
1379