Merge branch 'blender2.7'
[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_ShaderNodeBsdfHairPrincipled)) {
521                 BL::ShaderNodeBsdfHairPrincipled b_principled_hair_node(b_node);
522                 PrincipledHairBsdfNode *principled_hair = new PrincipledHairBsdfNode();
523                 principled_hair->parametrization = (NodePrincipledHairParametrization) get_enum(b_principled_hair_node.ptr, "parametrization", NODE_PRINCIPLED_HAIR_NUM, NODE_PRINCIPLED_HAIR_REFLECTANCE);
524                 node = principled_hair;
525         }
526         else if(b_node.is_a(&RNA_ShaderNodeBsdfPrincipled)) {
527                 BL::ShaderNodeBsdfPrincipled b_principled_node(b_node);
528                 PrincipledBsdfNode *principled = new PrincipledBsdfNode();
529                 switch (b_principled_node.distribution()) {
530                         case BL::ShaderNodeBsdfPrincipled::distribution_GGX:
531                                 principled->distribution = CLOSURE_BSDF_MICROFACET_GGX_GLASS_ID;
532                                 break;
533                         case BL::ShaderNodeBsdfPrincipled::distribution_MULTI_GGX:
534                                 principled->distribution = CLOSURE_BSDF_MICROFACET_MULTI_GGX_GLASS_ID;
535                                 break;
536                 }
537                 switch (b_principled_node.subsurface_method()) {
538                         case BL::ShaderNodeBsdfPrincipled::subsurface_method_BURLEY:
539                                 principled->subsurface_method = CLOSURE_BSSRDF_PRINCIPLED_ID;
540                                 break;
541                         case BL::ShaderNodeBsdfPrincipled::subsurface_method_RANDOM_WALK:
542                                 principled->subsurface_method = CLOSURE_BSSRDF_PRINCIPLED_RANDOM_WALK_ID;
543                                 break;
544                 }
545                 node = principled;
546         }
547         else if(b_node.is_a(&RNA_ShaderNodeBsdfTranslucent)) {
548                 node = new TranslucentBsdfNode();
549         }
550         else if(b_node.is_a(&RNA_ShaderNodeBsdfTransparent)) {
551                 node = new TransparentBsdfNode();
552         }
553         else if(b_node.is_a(&RNA_ShaderNodeBsdfVelvet)) {
554                 node = new VelvetBsdfNode();
555         }
556         else if(b_node.is_a(&RNA_ShaderNodeEmission)) {
557                 node = new EmissionNode();
558         }
559         else if(b_node.is_a(&RNA_ShaderNodeAmbientOcclusion)) {
560                 BL::ShaderNodeAmbientOcclusion b_ao_node(b_node);
561                 AmbientOcclusionNode *ao = new AmbientOcclusionNode();
562                 ao->samples = b_ao_node.samples();
563                 ao->inside = b_ao_node.inside();
564                 ao->only_local = b_ao_node.only_local();
565                 node = ao;
566         }
567         else if(b_node.is_a(&RNA_ShaderNodeVolumeScatter)) {
568                 node = new ScatterVolumeNode();
569         }
570         else if(b_node.is_a(&RNA_ShaderNodeVolumeAbsorption)) {
571                 node = new AbsorptionVolumeNode();
572         }
573         else if(b_node.is_a(&RNA_ShaderNodeVolumePrincipled)) {
574                 PrincipledVolumeNode *principled = new PrincipledVolumeNode();
575                 node = principled;
576         }
577         else if(b_node.is_a(&RNA_ShaderNodeNewGeometry)) {
578                 node = new GeometryNode();
579         }
580         else if(b_node.is_a(&RNA_ShaderNodeWireframe)) {
581                 BL::ShaderNodeWireframe b_wireframe_node(b_node);
582                 WireframeNode *wire = new WireframeNode();
583                 wire->use_pixel_size = b_wireframe_node.use_pixel_size();
584                 node = wire;
585         }
586         else if(b_node.is_a(&RNA_ShaderNodeWavelength)) {
587                 node = new WavelengthNode();
588         }
589         else if(b_node.is_a(&RNA_ShaderNodeBlackbody)) {
590                 node = new BlackbodyNode();
591         }
592         else if(b_node.is_a(&RNA_ShaderNodeLightPath)) {
593                 node = new LightPathNode();
594         }
595         else if(b_node.is_a(&RNA_ShaderNodeLightFalloff)) {
596                 node = new LightFalloffNode();
597         }
598         else if(b_node.is_a(&RNA_ShaderNodeObjectInfo)) {
599                 node = new ObjectInfoNode();
600         }
601         else if(b_node.is_a(&RNA_ShaderNodeParticleInfo)) {
602                 node = new ParticleInfoNode();
603         }
604         else if(b_node.is_a(&RNA_ShaderNodeHairInfo)) {
605                 node = new HairInfoNode();
606         }
607         else if(b_node.is_a(&RNA_ShaderNodeBump)) {
608                 BL::ShaderNodeBump b_bump_node(b_node);
609                 BumpNode *bump = new BumpNode();
610                 bump->invert = b_bump_node.invert();
611                 node = bump;
612         }
613         else if(b_node.is_a(&RNA_ShaderNodeScript)) {
614 #ifdef WITH_OSL
615                 if(scene->shader_manager->use_osl()) {
616                         /* create script node */
617                         BL::ShaderNodeScript b_script_node(b_node);
618
619                         OSLShaderManager *manager = (OSLShaderManager*)scene->shader_manager;
620                         string bytecode_hash = b_script_node.bytecode_hash();
621
622                         if(!bytecode_hash.empty()) {
623                                 node = manager->osl_node("", bytecode_hash, b_script_node.bytecode());
624                         }
625                         else {
626                                 string absolute_filepath = blender_absolute_path(b_data, b_ntree, b_script_node.filepath());
627                                 node = manager->osl_node(absolute_filepath, "");
628                         }
629                 }
630 #else
631                 (void) b_data;
632                 (void) b_ntree;
633 #endif
634         }
635         else if(b_node.is_a(&RNA_ShaderNodeTexImage)) {
636                 BL::ShaderNodeTexImage b_image_node(b_node);
637                 BL::Image b_image(b_image_node.image());
638                 BL::ImageUser b_image_user(b_image_node.image_user());
639                 ImageTextureNode *image = new ImageTextureNode();
640                 if(b_image) {
641                         /* builtin images will use callback-based reading because
642                          * they could only be loaded correct from blender side
643                          */
644                         bool is_builtin = b_image.packed_file() ||
645                                           b_image.source() == BL::Image::source_GENERATED ||
646                                           b_image.source() == BL::Image::source_MOVIE ||
647                                           (b_engine.is_preview() &&
648                                            b_image.source() != BL::Image::source_SEQUENCE);
649
650                         if(is_builtin) {
651                                 /* for builtin images we're using image datablock name to find an image to
652                                  * read pixels from later
653                                  *
654                                  * also store frame number as well, so there's no differences in handling
655                                  * builtin names for packed images and movies
656                                  */
657                                 int scene_frame = b_scene.frame_current();
658                                 int image_frame = image_user_frame_number(b_image_user,
659                                                                           scene_frame);
660                                 image->filename = b_image.name() + "@" + string_printf("%d", image_frame);
661                                 image->builtin_data = b_image.ptr.data;
662                         }
663                         else {
664                                 image->filename = image_user_file_path(b_image_user,
665                                                                        b_image,
666                                                                        b_scene.frame_current());
667                                 image->builtin_data = NULL;
668                         }
669
670                         image->animated = b_image_node.image_user().use_auto_refresh();
671                         image->use_alpha = b_image.use_alpha();
672
673                         /* TODO: restore */
674                         /* TODO(sergey): Does not work properly when we change builtin type. */
675 #if 0
676                         if(b_image.is_updated()) {
677                                 scene->image_manager->tag_reload_image(
678                                         image->filename.string(),
679                                         image->builtin_data,
680                                         get_image_interpolation(b_image_node),
681                                         get_image_extension(b_image_node),
682                                         image->use_alpha);
683                         }
684 #endif
685                 }
686                 image->color_space = (NodeImageColorSpace)b_image_node.color_space();
687                 image->projection = (NodeImageProjection)b_image_node.projection();
688                 image->interpolation = get_image_interpolation(b_image_node);
689                 image->extension = get_image_extension(b_image_node);
690                 image->projection_blend = b_image_node.projection_blend();
691                 BL::TexMapping b_texture_mapping(b_image_node.texture_mapping());
692                 get_tex_mapping(&image->tex_mapping, b_texture_mapping);
693                 node = image;
694         }
695         else if(b_node.is_a(&RNA_ShaderNodeTexEnvironment)) {
696                 BL::ShaderNodeTexEnvironment b_env_node(b_node);
697                 BL::Image b_image(b_env_node.image());
698                 BL::ImageUser b_image_user(b_env_node.image_user());
699                 EnvironmentTextureNode *env = new EnvironmentTextureNode();
700                 if(b_image) {
701                         bool is_builtin = b_image.packed_file() ||
702                                           b_image.source() == BL::Image::source_GENERATED ||
703                                           b_image.source() == BL::Image::source_MOVIE ||
704                                           (b_engine.is_preview() &&
705                                            b_image.source() != BL::Image::source_SEQUENCE);
706
707                         if(is_builtin) {
708                                 int scene_frame = b_scene.frame_current();
709                                 int image_frame = image_user_frame_number(b_image_user,
710                                                                           scene_frame);
711                                 env->filename = b_image.name() + "@" + string_printf("%d", image_frame);
712                                 env->builtin_data = b_image.ptr.data;
713                         }
714                         else {
715                                 env->filename = image_user_file_path(b_image_user,
716                                                                      b_image,
717                                                                      b_scene.frame_current());
718                                 env->builtin_data = NULL;
719                         }
720
721                         env->animated = b_env_node.image_user().use_auto_refresh();
722                         env->use_alpha = b_image.use_alpha();
723
724                         /* TODO: restore */
725                         /* TODO(sergey): Does not work properly when we change builtin type. */
726 #if 0
727                         if(b_image.is_updated()) {
728                                 scene->image_manager->tag_reload_image(
729                                         env->filename.string(),
730                                         env->builtin_data,
731                                         get_image_interpolation(b_env_node),
732                                         EXTENSION_REPEAT,
733                                         env->use_alpha);
734                         }
735 #endif
736                 }
737                 env->color_space = (NodeImageColorSpace)b_env_node.color_space();
738                 env->interpolation = get_image_interpolation(b_env_node);
739                 env->projection = (NodeEnvironmentProjection)b_env_node.projection();
740                 BL::TexMapping b_texture_mapping(b_env_node.texture_mapping());
741                 get_tex_mapping(&env->tex_mapping, b_texture_mapping);
742                 node = env;
743         }
744         else if(b_node.is_a(&RNA_ShaderNodeTexGradient)) {
745                 BL::ShaderNodeTexGradient b_gradient_node(b_node);
746                 GradientTextureNode *gradient = new GradientTextureNode();
747                 gradient->type = (NodeGradientType)b_gradient_node.gradient_type();
748                 BL::TexMapping b_texture_mapping(b_gradient_node.texture_mapping());
749                 get_tex_mapping(&gradient->tex_mapping, b_texture_mapping);
750                 node = gradient;
751         }
752         else if(b_node.is_a(&RNA_ShaderNodeTexVoronoi)) {
753                 BL::ShaderNodeTexVoronoi b_voronoi_node(b_node);
754                 VoronoiTextureNode *voronoi = new VoronoiTextureNode();
755                 voronoi->coloring = (NodeVoronoiColoring)b_voronoi_node.coloring();
756                 voronoi->metric = (NodeVoronoiDistanceMetric)b_voronoi_node.distance();
757                 voronoi->feature = (NodeVoronoiFeature)b_voronoi_node.feature();
758                 BL::TexMapping b_texture_mapping(b_voronoi_node.texture_mapping());
759                 get_tex_mapping(&voronoi->tex_mapping, b_texture_mapping);
760                 node = voronoi;
761         }
762         else if(b_node.is_a(&RNA_ShaderNodeTexMagic)) {
763                 BL::ShaderNodeTexMagic b_magic_node(b_node);
764                 MagicTextureNode *magic = new MagicTextureNode();
765                 magic->depth = b_magic_node.turbulence_depth();
766                 BL::TexMapping b_texture_mapping(b_magic_node.texture_mapping());
767                 get_tex_mapping(&magic->tex_mapping, b_texture_mapping);
768                 node = magic;
769         }
770         else if(b_node.is_a(&RNA_ShaderNodeTexWave)) {
771                 BL::ShaderNodeTexWave b_wave_node(b_node);
772                 WaveTextureNode *wave = new WaveTextureNode();
773                 wave->type = (NodeWaveType)b_wave_node.wave_type();
774                 wave->profile = (NodeWaveProfile)b_wave_node.wave_profile();
775                 BL::TexMapping b_texture_mapping(b_wave_node.texture_mapping());
776                 get_tex_mapping(&wave->tex_mapping, b_texture_mapping);
777                 node = wave;
778         }
779         else if(b_node.is_a(&RNA_ShaderNodeTexChecker)) {
780                 BL::ShaderNodeTexChecker b_checker_node(b_node);
781                 CheckerTextureNode *checker = new CheckerTextureNode();
782                 BL::TexMapping b_texture_mapping(b_checker_node.texture_mapping());
783                 get_tex_mapping(&checker->tex_mapping, b_texture_mapping);
784                 node = checker;
785         }
786         else if(b_node.is_a(&RNA_ShaderNodeTexBrick)) {
787                 BL::ShaderNodeTexBrick b_brick_node(b_node);
788                 BrickTextureNode *brick = new BrickTextureNode();
789                 brick->offset = b_brick_node.offset();
790                 brick->offset_frequency = b_brick_node.offset_frequency();
791                 brick->squash = b_brick_node.squash();
792                 brick->squash_frequency = b_brick_node.squash_frequency();
793                 BL::TexMapping b_texture_mapping(b_brick_node.texture_mapping());
794                 get_tex_mapping(&brick->tex_mapping, b_texture_mapping);
795                 node = brick;
796         }
797         else if(b_node.is_a(&RNA_ShaderNodeTexNoise)) {
798                 BL::ShaderNodeTexNoise b_noise_node(b_node);
799                 NoiseTextureNode *noise = new NoiseTextureNode();
800                 BL::TexMapping b_texture_mapping(b_noise_node.texture_mapping());
801                 get_tex_mapping(&noise->tex_mapping, b_texture_mapping);
802                 node = noise;
803         }
804         else if(b_node.is_a(&RNA_ShaderNodeTexMusgrave)) {
805                 BL::ShaderNodeTexMusgrave b_musgrave_node(b_node);
806                 MusgraveTextureNode *musgrave = new MusgraveTextureNode();
807                 musgrave->type = (NodeMusgraveType)b_musgrave_node.musgrave_type();
808                 BL::TexMapping b_texture_mapping(b_musgrave_node.texture_mapping());
809                 get_tex_mapping(&musgrave->tex_mapping, b_texture_mapping);
810                 node = musgrave;
811         }
812         else if(b_node.is_a(&RNA_ShaderNodeTexCoord)) {
813                 BL::ShaderNodeTexCoord b_tex_coord_node(b_node);
814                 TextureCoordinateNode *tex_coord = new TextureCoordinateNode();
815                 tex_coord->from_dupli = b_tex_coord_node.from_instancer();
816                 if(b_tex_coord_node.object()) {
817                         tex_coord->use_transform = true;
818                         tex_coord->ob_tfm = get_transform(b_tex_coord_node.object().matrix_world());
819                 }
820                 node = tex_coord;
821         }
822         else if(b_node.is_a(&RNA_ShaderNodeTexSky)) {
823                 BL::ShaderNodeTexSky b_sky_node(b_node);
824                 SkyTextureNode *sky = new SkyTextureNode();
825                 sky->type = (NodeSkyType)b_sky_node.sky_type();
826                 sky->sun_direction = normalize(get_float3(b_sky_node.sun_direction()));
827                 sky->turbidity = b_sky_node.turbidity();
828                 sky->ground_albedo = b_sky_node.ground_albedo();
829                 BL::TexMapping b_texture_mapping(b_sky_node.texture_mapping());
830                 get_tex_mapping(&sky->tex_mapping, b_texture_mapping);
831                 node = sky;
832         }
833         else if(b_node.is_a(&RNA_ShaderNodeTexIES)) {
834                 BL::ShaderNodeTexIES b_ies_node(b_node);
835                 IESLightNode *ies = new IESLightNode();
836                 switch(b_ies_node.mode()) {
837                         case BL::ShaderNodeTexIES::mode_EXTERNAL:
838                                 ies->filename = blender_absolute_path(b_data, b_ntree, b_ies_node.filepath());
839                                 break;
840                         case BL::ShaderNodeTexIES::mode_INTERNAL:
841                                 ies->ies = get_text_datablock_content(b_ies_node.ies().ptr);
842                                 if(ies->ies.empty()) {
843                                         ies->ies = "\n";
844                                 }
845                                 break;
846                 }
847                 node = ies;
848         }
849         else if(b_node.is_a(&RNA_ShaderNodeNormalMap)) {
850                 BL::ShaderNodeNormalMap b_normal_map_node(b_node);
851                 NormalMapNode *nmap = new NormalMapNode();
852                 nmap->space = (NodeNormalMapSpace)b_normal_map_node.space();
853                 nmap->attribute = b_normal_map_node.uv_map();
854                 node = nmap;
855         }
856         else if(b_node.is_a(&RNA_ShaderNodeTangent)) {
857                 BL::ShaderNodeTangent b_tangent_node(b_node);
858                 TangentNode *tangent = new TangentNode();
859                 tangent->direction_type = (NodeTangentDirectionType)b_tangent_node.direction_type();
860                 tangent->axis = (NodeTangentAxis)b_tangent_node.axis();
861                 tangent->attribute = b_tangent_node.uv_map();
862                 node = tangent;
863         }
864         else if(b_node.is_a(&RNA_ShaderNodeUVMap)) {
865                 BL::ShaderNodeUVMap b_uvmap_node(b_node);
866                 UVMapNode *uvm = new UVMapNode();
867                 uvm->attribute = b_uvmap_node.uv_map();
868                 uvm->from_dupli = b_uvmap_node.from_instancer();
869                 node = uvm;
870         }
871         else if(b_node.is_a(&RNA_ShaderNodeTexPointDensity)) {
872                 BL::ShaderNodeTexPointDensity b_point_density_node(b_node);
873                 PointDensityTextureNode *point_density = new PointDensityTextureNode();
874                 point_density->filename = b_point_density_node.name();
875                 point_density->space = (NodeTexVoxelSpace)b_point_density_node.space();
876                 point_density->interpolation = get_image_interpolation(b_point_density_node);
877                 point_density->builtin_data = b_point_density_node.ptr.data;
878                 point_density->image_manager = scene->image_manager;
879
880                 /* TODO(sergey): Use more proper update flag. */
881                 if(true) {
882                         point_density->add_image();
883                         b_point_density_node.cache_point_density(b_depsgraph);
884                         scene->image_manager->tag_reload_image(
885                                 point_density->filename.string(),
886                                 point_density->builtin_data,
887                                 point_density->interpolation,
888                                 EXTENSION_CLIP,
889                                 true);
890                 }
891                 node = point_density;
892
893                 /* Transformation form world space to texture space.
894                  *
895                  * NOTE: Do this after the texture is cached, this is because getting
896                  * min/max will need to access this cache.
897                  */
898                 BL::Object b_ob(b_point_density_node.object());
899                 if(b_ob) {
900                         float3 loc, size;
901                         point_density_texture_space(b_depsgraph,
902                                                     b_point_density_node,
903                                                     loc,
904                                                     size);
905                         point_density->tfm =
906                                 transform_translate(-loc) * transform_scale(size) *
907                                 transform_inverse(get_transform(b_ob.matrix_world()));
908                 }
909         }
910         else if(b_node.is_a(&RNA_ShaderNodeBevel)) {
911                 BL::ShaderNodeBevel b_bevel_node(b_node);
912                 BevelNode *bevel = new BevelNode();
913                 bevel->samples = b_bevel_node.samples();
914                 node = bevel;
915         }
916         else if(b_node.is_a(&RNA_ShaderNodeDisplacement)) {
917                 BL::ShaderNodeDisplacement b_disp_node(b_node);
918                 DisplacementNode *disp = new DisplacementNode();
919                 disp->space = (NodeNormalMapSpace)b_disp_node.space();
920                 node = disp;
921         }
922         else if(b_node.is_a(&RNA_ShaderNodeVectorDisplacement)) {
923                 BL::ShaderNodeVectorDisplacement b_disp_node(b_node);
924                 VectorDisplacementNode *disp = new VectorDisplacementNode();
925                 disp->space = (NodeNormalMapSpace)b_disp_node.space();
926                 disp->attribute = "";
927                 node = disp;
928         }
929
930         if(node) {
931                 node->name = b_node.name();
932                 graph->add(node);
933         }
934
935         return node;
936 }
937
938 static bool node_use_modified_socket_name(ShaderNode *node)
939 {
940         if(node->special_type == SHADER_SPECIAL_TYPE_SCRIPT)
941                 return false;
942
943         return true;
944 }
945
946 static ShaderInput *node_find_input_by_name(ShaderNode *node,
947                                             BL::Node& b_node,
948                                             BL::NodeSocket& b_socket)
949 {
950         string name = b_socket.name();
951
952         if(node_use_modified_socket_name(node)) {
953                 BL::Node::inputs_iterator b_input;
954                 bool found = false;
955                 int counter = 0, total = 0;
956
957                 for(b_node.inputs.begin(b_input); b_input != b_node.inputs.end(); ++b_input) {
958                         if(b_input->name() == name) {
959                                 if(!found)
960                                         counter++;
961                                 total++;
962                         }
963
964                         if(b_input->ptr.data == b_socket.ptr.data)
965                                 found = true;
966                 }
967
968                 /* rename if needed */
969                 if(name == "Shader")
970                         name = "Closure";
971
972                 if(total > 1)
973                         name = string_printf("%s%d", name.c_str(), counter);
974         }
975
976         return node->input(name.c_str());
977 }
978
979 static ShaderOutput *node_find_output_by_name(ShaderNode *node,
980                                               BL::Node& b_node,
981                                               BL::NodeSocket& b_socket)
982 {
983         string name = b_socket.name();
984
985         if(node_use_modified_socket_name(node)) {
986                 BL::Node::outputs_iterator b_output;
987                 bool found = false;
988                 int counter = 0, total = 0;
989
990                 for(b_node.outputs.begin(b_output); b_output != b_node.outputs.end(); ++b_output) {
991                         if(b_output->name() == name) {
992                                 if(!found)
993                                         counter++;
994                                 total++;
995                         }
996
997                         if(b_output->ptr.data == b_socket.ptr.data)
998                                 found = true;
999                 }
1000
1001                 /* rename if needed */
1002                 if(name == "Shader")
1003                         name = "Closure";
1004
1005                 if(total > 1)
1006                         name = string_printf("%s%d", name.c_str(), counter);
1007         }
1008
1009         return node->output(name.c_str());
1010 }
1011
1012 static void add_nodes(Scene *scene,
1013                       BL::RenderEngine& b_engine,
1014                       BL::BlendData& b_data,
1015                       BL::Depsgraph& b_depsgraph,
1016                       BL::Scene& b_scene,
1017                       ShaderGraph *graph,
1018                       BL::ShaderNodeTree& b_ntree,
1019                       const ProxyMap &proxy_input_map,
1020                       const ProxyMap &proxy_output_map)
1021 {
1022         /* add nodes */
1023         BL::ShaderNodeTree::nodes_iterator b_node;
1024         PtrInputMap input_map;
1025         PtrOutputMap output_map;
1026
1027         BL::Node::inputs_iterator b_input;
1028         BL::Node::outputs_iterator b_output;
1029
1030         /* find the node to use for output if there are multiple */
1031         BL::ShaderNode output_node = b_ntree.get_output_node(BL::ShaderNodeOutputMaterial::target_CYCLES);
1032
1033         /* add nodes */
1034         for(b_ntree.nodes.begin(b_node); b_node != b_ntree.nodes.end(); ++b_node) {
1035                 if(b_node->mute() || b_node->is_a(&RNA_NodeReroute)) {
1036                         /* replace muted node with internal links */
1037                         BL::Node::internal_links_iterator b_link;
1038                         for(b_node->internal_links.begin(b_link); b_link != b_node->internal_links.end(); ++b_link) {
1039                                 BL::NodeSocket to_socket(b_link->to_socket());
1040                                 SocketType::Type to_socket_type = convert_socket_type(to_socket);
1041                                 if(to_socket_type == SocketType::UNDEFINED) {
1042                                         continue;
1043                                 }
1044
1045                                 ConvertNode *proxy = new ConvertNode(to_socket_type, to_socket_type, true);
1046
1047                                 input_map[b_link->from_socket().ptr.data] = proxy->inputs[0];
1048                                 output_map[b_link->to_socket().ptr.data] = proxy->outputs[0];
1049
1050                                 graph->add(proxy);
1051                         }
1052                 }
1053                 else if(b_node->is_a(&RNA_ShaderNodeGroup) ||
1054                         b_node->is_a(&RNA_NodeCustomGroup) ||
1055                         b_node->is_a(&RNA_ShaderNodeCustomGroup)) {
1056
1057                         BL::ShaderNodeTree b_group_ntree(PointerRNA_NULL);
1058                         if(b_node->is_a(&RNA_ShaderNodeGroup))
1059                                 b_group_ntree = BL::ShaderNodeTree(((BL::NodeGroup)(*b_node)).node_tree());
1060                         else if (b_node->is_a(&RNA_NodeCustomGroup))
1061                                 b_group_ntree = BL::ShaderNodeTree(((BL::NodeCustomGroup)(*b_node)).node_tree());
1062                         else
1063                                 b_group_ntree = BL::ShaderNodeTree(((BL::ShaderNodeCustomGroup)(*b_node)).node_tree());
1064
1065                         ProxyMap group_proxy_input_map, group_proxy_output_map;
1066
1067                         /* Add a proxy node for each socket
1068                          * Do this even if the node group has no internal tree,
1069                          * so that links have something to connect to and assert won't fail.
1070                          */
1071                         for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
1072                                 SocketType::Type input_type = convert_socket_type(*b_input);
1073                                 if(input_type == SocketType::UNDEFINED) {
1074                                         continue;
1075                                 }
1076
1077                                 ConvertNode *proxy = new ConvertNode(input_type, input_type, true);
1078                                 graph->add(proxy);
1079
1080                                 /* register the proxy node for internal binding */
1081                                 group_proxy_input_map[b_input->identifier()] = proxy;
1082
1083                                 input_map[b_input->ptr.data] = proxy->inputs[0];
1084
1085                                 set_default_value(proxy->inputs[0], *b_input, b_data, b_ntree);
1086                         }
1087                         for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
1088                                 SocketType::Type output_type = convert_socket_type(*b_output);
1089                                 if(output_type == SocketType::UNDEFINED) {
1090                                         continue;
1091                                 }
1092
1093                                 ConvertNode *proxy = new ConvertNode(output_type, output_type, true);
1094                                 graph->add(proxy);
1095
1096                                 /* register the proxy node for internal binding */
1097                                 group_proxy_output_map[b_output->identifier()] = proxy;
1098
1099                                 output_map[b_output->ptr.data] = proxy->outputs[0];
1100                         }
1101
1102                         if(b_group_ntree) {
1103                                 add_nodes(scene,
1104                                           b_engine,
1105                                           b_data,
1106                                           b_depsgraph,
1107                                           b_scene,
1108                                           graph,
1109                                           b_group_ntree,
1110                                           group_proxy_input_map,
1111                                           group_proxy_output_map);
1112                         }
1113                 }
1114                 else if(b_node->is_a(&RNA_NodeGroupInput)) {
1115                         /* map each socket to a proxy node */
1116                         for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
1117                                 ProxyMap::const_iterator proxy_it = proxy_input_map.find(b_output->identifier());
1118                                 if(proxy_it != proxy_input_map.end()) {
1119                                         ConvertNode *proxy = proxy_it->second;
1120
1121                                         output_map[b_output->ptr.data] = proxy->outputs[0];
1122                                 }
1123                         }
1124                 }
1125                 else if(b_node->is_a(&RNA_NodeGroupOutput)) {
1126                         BL::NodeGroupOutput b_output_node(*b_node);
1127                         /* only the active group output is used */
1128                         if(b_output_node.is_active_output()) {
1129                                 /* map each socket to a proxy node */
1130                                 for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
1131                                         ProxyMap::const_iterator proxy_it = proxy_output_map.find(b_input->identifier());
1132                                         if(proxy_it != proxy_output_map.end()) {
1133                                                 ConvertNode *proxy = proxy_it->second;
1134
1135                                                 input_map[b_input->ptr.data] = proxy->inputs[0];
1136
1137                                                 set_default_value(proxy->inputs[0], *b_input, b_data, b_ntree);
1138                                         }
1139                                 }
1140                         }
1141                 }
1142                 else {
1143                         ShaderNode *node = NULL;
1144
1145                         if(b_node->ptr.data == output_node.ptr.data) {
1146                                 node = graph->output();
1147                         }
1148                         else {
1149                                 BL::ShaderNode b_shader_node(*b_node);
1150                                 node = add_node(scene,
1151                                                 b_engine,
1152                                                 b_data,
1153                                                 b_depsgraph,
1154                                                 b_scene,
1155                                                 graph,
1156                                                 b_ntree,
1157                                                 b_shader_node);
1158                         }
1159
1160                         if(node) {
1161                                 /* map node sockets for linking */
1162                                 for(b_node->inputs.begin(b_input); b_input != b_node->inputs.end(); ++b_input) {
1163                                         ShaderInput *input = node_find_input_by_name(node, *b_node, *b_input);
1164                                         if(!input) {
1165                                                 /* XXX should not happen, report error? */
1166                                                 continue;
1167                                         }
1168                                         input_map[b_input->ptr.data] = input;
1169
1170                                         set_default_value(input, *b_input, b_data, b_ntree);
1171                                 }
1172                                 for(b_node->outputs.begin(b_output); b_output != b_node->outputs.end(); ++b_output) {
1173                                         ShaderOutput *output = node_find_output_by_name(node, *b_node, *b_output);
1174                                         if(!output) {
1175                                                 /* XXX should not happen, report error? */
1176                                                 continue;
1177                                         }
1178                                         output_map[b_output->ptr.data] = output;
1179                                 }
1180                         }
1181                 }
1182         }
1183
1184         /* connect nodes */
1185         BL::NodeTree::links_iterator b_link;
1186
1187         for(b_ntree.links.begin(b_link); b_link != b_ntree.links.end(); ++b_link) {
1188                 /* Ignore invalid links to avoid unwanted cycles created in graph. */
1189                 if(!b_link->is_valid()) {
1190                         continue;
1191                 }
1192                 /* get blender link data */
1193                 BL::NodeSocket b_from_sock = b_link->from_socket();
1194                 BL::NodeSocket b_to_sock = b_link->to_socket();
1195
1196                 ShaderOutput *output = 0;
1197                 ShaderInput *input = 0;
1198
1199                 PtrOutputMap::iterator output_it = output_map.find(b_from_sock.ptr.data);
1200                 if(output_it != output_map.end())
1201                         output = output_it->second;
1202                 PtrInputMap::iterator input_it = input_map.find(b_to_sock.ptr.data);
1203                 if(input_it != input_map.end())
1204                         input = input_it->second;
1205
1206                 /* either node may be NULL when the node was not exported, typically
1207                  * because the node type is not supported */
1208                 if(output && input)
1209                         graph->connect(output, input);
1210         }
1211 }
1212
1213 static void add_nodes(Scene *scene,
1214                       BL::RenderEngine& b_engine,
1215                       BL::BlendData& b_data,
1216                       BL::Depsgraph& b_depsgraph,
1217                       BL::Scene& b_scene,
1218                       ShaderGraph *graph,
1219                       BL::ShaderNodeTree& b_ntree)
1220 {
1221         static const ProxyMap empty_proxy_map;
1222         add_nodes(scene,
1223                   b_engine,
1224                   b_data,
1225                   b_depsgraph,
1226                   b_scene,
1227                   graph,
1228                   b_ntree,
1229                   empty_proxy_map,
1230                   empty_proxy_map);
1231 }
1232
1233 /* Sync Materials */
1234
1235 void BlenderSync::sync_materials(BL::Depsgraph& b_depsgraph, bool update_all)
1236 {
1237         shader_map.set_default(scene->default_surface);
1238
1239         TaskPool pool;
1240         set<Shader*> updated_shaders;
1241
1242         BL::Depsgraph::ids_iterator b_id;
1243         for(b_depsgraph.ids.begin(b_id); b_id != b_depsgraph.ids.end(); ++b_id) {
1244                 if(!b_id->is_a(&RNA_Material)) {
1245                         continue;
1246                 }
1247
1248                 BL::Material b_mat(*b_id);
1249                 Shader *shader;
1250
1251                 /* test if we need to sync */
1252                 if(shader_map.sync(&shader, b_mat) || shader->need_sync_object || update_all) {
1253                         ShaderGraph *graph = new ShaderGraph();
1254
1255                         shader->name = b_mat.name().c_str();
1256                         shader->pass_id = b_mat.pass_index();
1257                         shader->need_sync_object = false;
1258
1259                         /* create nodes */
1260                         if(b_mat.use_nodes() && b_mat.node_tree()) {
1261                                 BL::ShaderNodeTree b_ntree(b_mat.node_tree());
1262
1263                                 add_nodes(scene, b_engine, b_data, b_depsgraph, b_scene, graph, b_ntree);
1264                         }
1265                         else {
1266                                 DiffuseBsdfNode *diffuse = new DiffuseBsdfNode();
1267                                 diffuse->color = get_float3(b_mat.diffuse_color());
1268                                 graph->add(diffuse);
1269
1270                                 ShaderNode *out = graph->output();
1271                                 graph->connect(diffuse->output("BSDF"), out->input("Surface"));
1272                         }
1273
1274                         /* settings */
1275                         PointerRNA cmat = RNA_pointer_get(&b_mat.ptr, "cycles");
1276                         shader->use_mis = get_boolean(cmat, "sample_as_light");
1277                         shader->use_transparent_shadow = get_boolean(cmat, "use_transparent_shadow");
1278                         shader->heterogeneous_volume = !get_boolean(cmat, "homogeneous_volume");
1279                         shader->volume_sampling_method = get_volume_sampling(cmat);
1280                         shader->volume_interpolation_method = get_volume_interpolation(cmat);
1281                         shader->displacement_method = get_displacement_method(cmat);
1282
1283                         shader->set_graph(graph);
1284
1285                         /* By simplifying the shader graph as soon as possible, some
1286                          * redundant shader nodes might be removed which prevents loading
1287                          * unnecessary attributes later.
1288                          *
1289                          * However, since graph simplification also accounts for e.g. mix
1290                          * weight, this would cause frequent expensive resyncs in interactive
1291                          * sessions, so for those sessions optimization is only performed
1292                          * right before compiling.
1293                          */
1294                         if(!preview) {
1295                                 pool.push(function_bind(&ShaderGraph::simplify, graph, scene));
1296                                 /* NOTE: Update shaders out of the threads since those routines
1297                                  * are accessing and writing to a global context.
1298                                  */
1299                                 updated_shaders.insert(shader);
1300                         }
1301                         else {
1302                                 /* NOTE: Update tagging can access links which are being
1303                                  * optimized out.
1304                                  */
1305                                 shader->tag_update(scene);
1306                         }
1307                 }
1308         }
1309
1310         pool.wait_work();
1311
1312         foreach(Shader *shader, updated_shaders) {
1313                 shader->tag_update(scene);
1314         }
1315 }
1316
1317 /* Sync World */
1318
1319 void BlenderSync::sync_world(BL::Depsgraph& b_depsgraph, bool update_all)
1320 {
1321         Background *background = scene->background;
1322         Background prevbackground = *background;
1323
1324         BL::World b_world = b_scene.world();
1325
1326         if(world_recalc || update_all || b_world.ptr.data != world_map) {
1327                 Shader *shader = scene->default_background;
1328                 ShaderGraph *graph = new ShaderGraph();
1329
1330                 /* create nodes */
1331                 if(b_world && b_world.use_nodes() && b_world.node_tree()) {
1332                         BL::ShaderNodeTree b_ntree(b_world.node_tree());
1333
1334                         add_nodes(scene, b_engine, b_data, b_depsgraph, b_scene, graph, b_ntree);
1335
1336                         /* volume */
1337                         PointerRNA cworld = RNA_pointer_get(&b_world.ptr, "cycles");
1338                         shader->heterogeneous_volume = !get_boolean(cworld, "homogeneous_volume");
1339                         shader->volume_sampling_method = get_volume_sampling(cworld);
1340                         shader->volume_interpolation_method = get_volume_interpolation(cworld);
1341                 }
1342                 else if(b_world) {
1343                         BackgroundNode *background = new BackgroundNode();
1344                         background->color = get_float3(b_world.color());
1345                         graph->add(background);
1346
1347                         ShaderNode *out = graph->output();
1348                         graph->connect(background->output("Background"), out->input("Surface"));
1349                 }
1350
1351                 if(b_world) {
1352                         /* AO */
1353                         BL::WorldLighting b_light = b_world.light_settings();
1354
1355                         background->use_ao = b_light.use_ambient_occlusion();
1356                         background->ao_factor = b_light.ao_factor();
1357                         background->ao_distance = b_light.distance();
1358
1359                         /* visibility */
1360                         PointerRNA cvisibility = RNA_pointer_get(&b_world.ptr, "cycles_visibility");
1361                         uint visibility = 0;
1362
1363                         visibility |= get_boolean(cvisibility, "camera")? PATH_RAY_CAMERA: 0;
1364                         visibility |= get_boolean(cvisibility, "diffuse")? PATH_RAY_DIFFUSE: 0;
1365                         visibility |= get_boolean(cvisibility, "glossy")? PATH_RAY_GLOSSY: 0;
1366                         visibility |= get_boolean(cvisibility, "transmission")? PATH_RAY_TRANSMIT: 0;
1367                         visibility |= get_boolean(cvisibility, "scatter")? PATH_RAY_VOLUME_SCATTER: 0;
1368
1369                         background->visibility = visibility;
1370                 }
1371                 else {
1372                         background->use_ao = false;
1373                         background->ao_factor = 0.0f;
1374                         background->ao_distance = FLT_MAX;
1375                 }
1376
1377                 shader->set_graph(graph);
1378                 shader->tag_update(scene);
1379                 background->tag_update(scene);
1380         }
1381
1382         PointerRNA cscene = RNA_pointer_get(&b_scene.ptr, "cycles");
1383
1384         /* when doing preview render check for BI's transparency settings,
1385          * this is so because Blender's preview render routines are not able
1386          * to tweak all cycles's settings depending on different circumstances
1387          */
1388         if(b_engine.is_preview() == false)
1389                 background->transparent = get_boolean(cscene, "film_transparent");
1390         else
1391                 background->transparent = b_scene.render().alpha_mode() == BL::RenderSettings::alpha_mode_TRANSPARENT;
1392
1393         if(background->transparent) {
1394                 background->transparent_glass = get_boolean(cscene, "film_transparent_glass");
1395                 background->transparent_roughness_threshold = get_float(cscene, "film_transparent_roughness");
1396         }
1397         else {
1398                 background->transparent_glass = false;
1399                 background->transparent_roughness_threshold = 0.0f;
1400         }
1401
1402         background->use_shader = view_layer.use_background_shader;
1403         background->use_ao = background->use_ao && view_layer.use_background_ao;
1404
1405         if(background->modified(prevbackground))
1406                 background->tag_update(scene);
1407 }
1408
1409 /* Sync Lights */
1410
1411 void BlenderSync::sync_lights(BL::Depsgraph& b_depsgraph, bool update_all)
1412 {
1413         shader_map.set_default(scene->default_light);
1414
1415         BL::Depsgraph::ids_iterator b_id;
1416         for(b_depsgraph.ids.begin(b_id); b_id != b_depsgraph.ids.end(); ++b_id) {
1417                 if(!b_id->is_a(&RNA_Light)) {
1418                         continue;
1419                 }
1420
1421                 BL::Light b_light(*b_id);
1422                 Shader *shader;
1423
1424                 /* test if we need to sync */
1425                 if(shader_map.sync(&shader, b_light) || update_all) {
1426                         ShaderGraph *graph = new ShaderGraph();
1427
1428                         /* create nodes */
1429                         if(b_light.use_nodes() && b_light.node_tree()) {
1430                                 shader->name = b_light.name().c_str();
1431
1432                                 BL::ShaderNodeTree b_ntree(b_light.node_tree());
1433
1434                                 add_nodes(scene, b_engine, b_data, b_depsgraph, b_scene, graph, b_ntree);
1435                         }
1436                         else {
1437                                 float strength = 1.0f;
1438
1439                                 if(b_light.type() == BL::Light::type_POINT ||
1440                                    b_light.type() == BL::Light::type_SPOT ||
1441                                    b_light.type() == BL::Light::type_AREA)
1442                                 {
1443                                         strength = 100.0f;
1444                                 }
1445
1446                                 EmissionNode *emission = new EmissionNode();
1447                                 emission->color = get_float3(b_light.color());
1448                                 emission->strength = strength;
1449                                 graph->add(emission);
1450
1451                                 ShaderNode *out = graph->output();
1452                                 graph->connect(emission->output("Emission"), out->input("Surface"));
1453                         }
1454
1455                         shader->set_graph(graph);
1456                         shader->tag_update(scene);
1457                 }
1458         }
1459 }
1460
1461 void BlenderSync::sync_shaders(BL::Depsgraph& b_depsgraph)
1462 {
1463         /* for auto refresh images */
1464         bool auto_refresh_update = false;
1465
1466         if(preview) {
1467                 ImageManager *image_manager = scene->image_manager;
1468                 int frame = b_scene.frame_current();
1469                 auto_refresh_update = image_manager->set_animation_frame_update(frame);
1470         }
1471
1472         shader_map.pre_sync();
1473
1474         sync_world(b_depsgraph, auto_refresh_update);
1475         sync_lights(b_depsgraph, auto_refresh_update);
1476         sync_materials(b_depsgraph, auto_refresh_update);
1477
1478         /* false = don't delete unused shaders, not supported */
1479         shader_map.post_sync(false);
1480 }
1481
1482 CCL_NAMESPACE_END