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