Blender V5.3
blender/shader.cpp
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2011-2022 Blender Foundation
2 *
3 * SPDX-License-Identifier: Apache-2.0 */
4
5#include "scene/shader.h"
6#include "kernel/svm/types.h"
7#include "scene/background.h"
8#include "scene/integrator.h"
9#include "scene/light.h"
10#include "scene/osl.h"
11#include "scene/scene.h"
12#include "scene/shader_graph.h"
13#include "scene/shader_nodes.h"
14
15#include "blender/image.h"
16#include "blender/sync.h"
17#include "blender/util.h"
18
19#include "util/log.h"
20#include "util/set.h"
21#include "util/string.h"
22#include "util/task.h"
23
24#include "BLI_listbase.hh"
25
26#include "BKE_duplilist.hh"
27#include "BKE_node.hh"
28#include "BKE_node_runtime.hh"
29
30#include "NOD_shader.h"
32#include "NOD_shader_raycast.hh"
33
35
36#include "DNA_light_types.h"
37#include "DNA_material_types.h"
38#include "DNA_world_types.h"
39
41
42using PtrInputMap = unordered_multimap<void *, ShaderInput *>;
43using PtrOutputMap = map<void *, ShaderOutput *>;
44using ProxyMap = map<string, ConvertNode *>;
45
46/* Find */
47
48void BlenderSync::find_shader(const blender::ID *id,
49 array<Node *> &used_shaders,
50 Shader *default_shader)
51{
52 Shader *synced_shader = (id) ? shader_map.find(id) : nullptr;
53 Shader *shader = (synced_shader) ? synced_shader : default_shader;
54
55 used_shaders.push_back_slow(shader);
56 shader->tag_used(scene);
57}
58
59/* RNA translation utilities */
60
62{
63 return (VolumeSampling)get_enum(
64 ptr, "volume_sampling", VOLUME_NUM_SAMPLING, VOLUME_SAMPLING_DISTANCE);
65}
66
72
74{
75 return (EmissionSampling)get_enum(
76 ptr, "emission_sampling", EMISSION_SAMPLING_NUM, EMISSION_SAMPLING_AUTO);
77}
78
79static int validate_enum_value(const int value, const int num_values, const int default_value)
80{
81 if (value >= num_values) {
82 return default_value;
83 }
84 return value;
85}
86
88{
89 const int value = b_mat.displacement_method;
91}
92
93template<typename NodeType> static InterpolationType get_image_interpolation(NodeType &b_node)
94{
95 const int value = b_node.interpolation;
98}
99
100template<typename NodeType> static ExtensionType get_image_extension(NodeType &b_node)
101{
102 const int value = b_node.extension;
104}
105
107{
108 const int value = b_image.alpha_mode;
110}
111
112/* Attribute name translation utilities */
113
114/* Since Eevee needs to know whether the attribute is uniform or varying
115 * at the time it compiles the shader for the material, Blender had to
116 * introduce different namespaces (types) in its attribute node. However,
117 * Cycles already has object attributes that form a uniform namespace with
118 * the more common varying attributes. Without completely reworking the
119 * attribute handling in Cycles to introduce separate namespaces (this could
120 * be especially hard for OSL which directly uses the name string), the
121 * space identifier has to be added to the attribute name as a prefix.
122 *
123 * The prefixes include a control character to ensure the user specified
124 * name can't accidentally include a special prefix.
125 */
126
127static const string_view object_attr_prefix("\x01object:");
128static const string_view instancer_attr_prefix("\x01instancer:");
129static const string_view view_layer_attr_prefix("\x01layer:");
130
131static ustring blender_attribute_name_add_type(const string &name, int type)
132{
133 switch (type) {
135 return ustring::concat(object_attr_prefix, name);
137 return ustring::concat(instancer_attr_prefix, name);
139 return ustring::concat(view_layer_attr_prefix, name);
140 default:
141 return ustring(name);
142 }
143}
144
145int blender_attribute_name_split_type(ustring name, string *r_real_name)
146{
147 const string_view sname(name);
148
149 if (sname.substr(0, object_attr_prefix.size()) == object_attr_prefix) {
150 *r_real_name = sname.substr(object_attr_prefix.size());
152 }
153
154 if (sname.substr(0, instancer_attr_prefix.size()) == instancer_attr_prefix) {
155 *r_real_name = sname.substr(instancer_attr_prefix.size());
157 }
158
159 if (sname.substr(0, view_layer_attr_prefix.size()) == view_layer_attr_prefix) {
160 *r_real_name = sname.substr(view_layer_attr_prefix.size());
162 }
163
165}
166
167/* Graph */
168
169static ustring get_node_input_string(const blender::bNode &b_node, const string &name)
170{
171 const blender::bNodeSocket *b_sock = b_node.input_by_identifier(blender::UString(name));
173 const auto &default_value = *b_sock->default_value_typed<blender::bNodeSocketValueString>();
174 return ustring(default_value.value);
175}
176
177static float3 get_node_output_rgba(blender::bNode &b_node, const string &name)
178{
179 blender::bNodeSocket *b_sock = b_node.output_by_identifier(blender::UString(name));
181 const auto &default_value = *b_sock->default_value_typed<blender::bNodeSocketValueRGBA>();
182 return make_float3(default_value.value[0], default_value.value[1], default_value.value[2]);
183}
184
185static float get_node_output_value(blender::bNode &b_node, const string &name)
186{
187 blender::bNodeSocket *b_sock = b_node.output_by_identifier(blender::UString(name));
189 const auto &default_value = *b_sock->default_value_typed<blender::bNodeSocketValueFloat>();
190 return default_value.value;
191}
192
193static float3 get_node_output_vector(blender::bNode &b_node, const string &name)
194{
195 blender::bNodeSocket *b_sock = b_node.output_by_identifier(blender::UString(name));
197 const auto &default_value = *b_sock->default_value_typed<blender::bNodeSocketValueVector>();
198 return make_float3(default_value.value[0], default_value.value[1], default_value.value[2]);
199}
200
202{
203 switch (b_socket.type) {
205 return SocketType::FLOAT;
208 return SocketType::INT;
210 return SocketType::VECTOR;
212 return SocketType::COLOR;
214 return SocketType::STRING;
216 return SocketType::CLOSURE;
217
218 default:
220 }
221}
222
224 blender::bNodeSocket &b_sock,
225 blender::Main &b_data,
226 blender::ID &b_id)
227{
228 Node *node = input->parent;
229 const SocketType &socket = input->socket_type;
230
231 /* copy values for non linked inputs */
232 switch (input->type()) {
233 case SocketType::FLOAT: {
234 const auto &default_value = *b_sock.default_value_typed<blender::bNodeSocketValueFloat>();
235 node->set(socket, default_value.value);
236 break;
237 }
238 case SocketType::INT: {
239 if (b_sock.type == blender::SOCK_BOOLEAN) {
240 const auto &default_value =
241 *b_sock.default_value_typed<blender::bNodeSocketValueBoolean>();
242 /* Make sure to call the int overload of set() since this is an integer socket as far as
243 * Cycles is concerned. */
244 node->set(socket, default_value.value ? 1 : 0);
245 }
246 else {
247 const auto &default_value = *b_sock.default_value_typed<blender::bNodeSocketValueInt>();
248 node->set(socket, default_value.value);
249 }
250 break;
251 }
252 case SocketType::COLOR: {
253 const auto &default_value = *b_sock.default_value_typed<blender::bNodeSocketValueRGBA>();
254 const float *value = default_value.value;
255 node->set(socket, make_float3(value[0], value[1], value[2]));
256 break;
257 }
260 case SocketType::VECTOR: {
261 const auto &default_value = *b_sock.default_value_typed<blender::bNodeSocketValueVector>();
262 const float *value = default_value.value;
263 node->set(socket, make_float3(value[0], value[1], value[2]));
264 break;
265 }
266 case SocketType::STRING: {
267 const auto &default_value = *b_sock.default_value_typed<blender::bNodeSocketValueString>();
268 node->set(socket,
269 (ustring)blender_absolute_path(b_data, &b_id, default_value.value).c_str());
270 break;
271 }
272 default:
273 break;
274 }
275}
276
277static void get_tex_mapping(TextureNode *mapping, const blender::TexMapping *b_mapping)
278{
279 if (!b_mapping) {
280 return;
281 }
282
283 mapping->set_tex_mapping_translation(
284 make_float3(b_mapping->loc[0], b_mapping->loc[1], b_mapping->loc[2]));
285 mapping->set_tex_mapping_rotation(
286 make_float3(b_mapping->rot[0], b_mapping->rot[1], b_mapping->rot[2]));
287 mapping->set_tex_mapping_scale(
288 make_float3(b_mapping->size[0], b_mapping->size[1], b_mapping->size[2]));
289 mapping->set_tex_mapping_type((TextureMapping::Type)b_mapping->type);
290
291 mapping->set_tex_mapping_x_mapping((TextureMapping::Mapping)b_mapping->projx);
292 mapping->set_tex_mapping_y_mapping((TextureMapping::Mapping)b_mapping->projy);
293 mapping->set_tex_mapping_z_mapping((TextureMapping::Mapping)b_mapping->projz);
294}
295
296static bool is_image_animated(blender::eImageSource b_image_source,
297 blender::ImageUser &b_image_user)
298{
299 return (b_image_source == blender::IMA_SRC_MOVIE ||
300 b_image_source == blender::IMA_SRC_SEQUENCE) &&
301 (b_image_user.flag & blender::IMA_ANIM_ALWAYS) != 0;
302}
303
304static std::optional<RaycastNode::AttributeOutputType> raycast_get_attribute_output_type(
305 const blender::eCustomDataType data_type)
306{
307 switch (data_type) {
313 default:
314 break;
315 }
316 LOG_DFATAL << "Unhandled data type " << int(data_type);
317 return std::nullopt;
318}
319
321 const blender::bNode &b_node)
322{
323 auto *storage = static_cast<blender::NodeShaderRaycast *>(b_node.storage);
325 blender::Span(storage->sample_attribute_items, storage->sample_attribute_items_num))
326 {
328
329 const std::optional<RaycastNode::AttributeOutputType> attribute_output_type =
331 if (!attribute_output_type) {
332 continue;
333 }
334
335 const string input_identifier(
336 RaycastSampleAttributeItemsAccessor::input_socket_identifier_for_item(item));
337 const ustring output_identifier(
338 RaycastSampleAttributeItemsAccessor::output_socket_identifier_for_item(item));
339
340 const ustring attribute_name = get_node_input_string(b_node, input_identifier);
341
342 raycast->add_output_attribute_socket(
343 attribute_name, *attribute_output_type, output_identifier);
344
345 /* For color attributes additionally add the corresponding Alpha socket.
346 * This is because colors are RGB, access to Alpha needs special handling. */
347 if (item.data_type == blender::CD_PROP_COLOR) {
348 const ustring alpha_output_identifier(
349 RaycastSampleAttributeItemsAccessor::output_socket_identifier_for_item_alpha(item));
350 raycast->add_output_attribute_socket(
351 attribute_name, RaycastNode::ATTR_OUTPUT_FLOAT_ALPHA, alpha_output_identifier);
352 }
353 }
354}
355
356static ShaderNode *add_node(Scene *scene,
357 blender::RenderEngine &b_engine,
358 blender::Main &b_data,
359 blender::Scene &b_scene,
360 ShaderGraph *graph,
361 blender::bNodeTree &b_ntree,
362 blender::bNode &b_node)
363{
364 using blender::operator""_ustr;
365 ShaderNode *node = nullptr;
366
367 /* existing blender nodes */
368 if (b_node.is_type("ShaderNodeRGBCurve"_ustr)) {
369 const auto &mapping = *static_cast<blender::CurveMapping *>(b_node.storage);
371 array<packed_float3> curve_mapping_curves;
372 float min_x;
373 float max_x;
374 curvemapping_color_to_array(mapping, curve_mapping_curves, RAMP_TABLE_SIZE, true);
375 curvemapping_minmax(mapping, 4, &min_x, &max_x);
376 curves->set_min_x(min_x);
377 curves->set_max_x(max_x);
378 curves->set_curves(curve_mapping_curves);
379 curves->set_extrapolate((mapping.flag & blender::CUMA_EXTEND_EXTRAPOLATE) != 0);
380 node = curves;
381 }
382 if (b_node.is_type("ShaderNodeVectorCurve"_ustr)) {
383 const auto &mapping = *static_cast<blender::CurveMapping *>(b_node.storage);
385 array<packed_float3> curve_mapping_curves;
386 float min_x;
387 float max_x;
388 curvemapping_color_to_array(mapping, curve_mapping_curves, RAMP_TABLE_SIZE, false);
389 curvemapping_minmax(mapping, 3, &min_x, &max_x);
390 curves->set_min_x(min_x);
391 curves->set_max_x(max_x);
392 curves->set_curves(curve_mapping_curves);
393 curves->set_extrapolate((mapping.flag & blender::CUMA_EXTEND_EXTRAPOLATE) != 0);
394 node = curves;
395 }
396 else if (b_node.is_type("ShaderNodeFloatCurve"_ustr)) {
397 const auto &mapping = *static_cast<blender::CurveMapping *>(b_node.storage);
398 FloatCurveNode *curve = graph->create_node<FloatCurveNode>();
399 array<float> curve_mapping_curve;
400 float min_x;
401 float max_x;
402 curvemapping_float_to_array(mapping, curve_mapping_curve, RAMP_TABLE_SIZE);
403 curvemapping_minmax(mapping, 1, &min_x, &max_x);
404 curve->set_min_x(min_x);
405 curve->set_max_x(max_x);
406 curve->set_curve(curve_mapping_curve);
407 curve->set_extrapolate((mapping.flag & blender::CUMA_EXTEND_EXTRAPOLATE) != 0);
408 node = curve;
409 }
410 else if (b_node.is_type("ShaderNodeValToRGB"_ustr)) {
411 RGBRampNode *ramp = graph->create_node<RGBRampNode>();
412 const auto &b_color_ramp = *static_cast<blender::ColorBand *>(b_node.storage);
413 array<packed_float3> ramp_values;
414 array<float> ramp_alpha;
415 colorramp_to_array(b_color_ramp, ramp_values, ramp_alpha, RAMP_TABLE_SIZE);
416 ramp->set_ramp(ramp_values);
417 ramp->set_ramp_alpha(ramp_alpha);
418 ramp->set_interpolate(b_color_ramp.ipotype != blender::COLBAND_INTERP_CONSTANT);
419 node = ramp;
420 }
421 else if (b_node.is_type("ShaderNodeRGB"_ustr)) {
422 ColorNode *color = graph->create_node<ColorNode>();
423 color->set_value(get_node_output_rgba(b_node, "Color"));
424 node = color;
425 }
426 else if (b_node.is_type("FunctionNodeInputVector"_ustr)) {
427 ColorNode *value = graph->create_node<ColorNode>();
428 const auto &storage = *static_cast<const blender::NodeInputVector *>(b_node.storage);
429 value->set_value(make_float3(storage.vector[0], storage.vector[1], storage.vector[2]));
430 node = value;
431 }
432 else if (b_node.is_type("ShaderNodeValue"_ustr)) {
433 ValueNode *value = graph->create_node<ValueNode>();
434 value->set_value(get_node_output_value(b_node, "Value"));
435 node = value;
436 }
437 else if (b_node.is_type("FunctionNodeInputBool"_ustr)) {
438 ValueNode *value = graph->create_node<ValueNode>();
439 const auto &storage = *static_cast<const blender::NodeInputBool *>(b_node.storage);
440 value->set_value(bool(storage.boolean));
441 node = value;
442 }
443 else if (b_node.is_type("FunctionNodeInputInt"_ustr)) {
444 ValueNode *value = graph->create_node<ValueNode>();
445 const auto &storage = *static_cast<const blender::NodeInputInt *>(b_node.storage);
446 value->set_value(storage.integer);
447 node = value;
448 }
449 else if (b_node.is_type("ShaderNodeCameraData"_ustr)) {
450 node = graph->create_node<CameraNode>();
451 }
452 else if (b_node.is_type("ShaderNodeInvert"_ustr)) {
453 node = graph->create_node<InvertNode>();
454 }
455 else if (b_node.is_type("ShaderNodeGamma"_ustr)) {
456 node = graph->create_node<GammaNode>();
457 }
458 else if (b_node.is_type("ShaderNodeBrightContrast"_ustr)) {
460 }
461 else if (b_node.is_type("ShaderNodeMixRGB"_ustr)) {
462 MixNode *mix = graph->create_node<MixNode>();
463 mix->set_mix_type((NodeMix)b_node.custom1);
464 mix->set_use_clamp(b_node.custom2 & blender::SHD_MIXRGB_CLAMP);
465 node = mix;
466 }
467 else if (b_node.is_type("ShaderNodeMix"_ustr)) {
468 const auto &storage = *static_cast<blender::NodeShaderMix *>(b_node.storage);
469 if (storage.data_type == blender::SOCK_VECTOR) {
470 if (storage.factor_mode == blender::NODE_MIX_MODE_UNIFORM) {
471 MixVectorNode *mix_node = graph->create_node<MixVectorNode>();
472 mix_node->set_use_clamp(storage.clamp_factor);
473 node = mix_node;
474 }
475 else {
477 mix_node->set_use_clamp(storage.clamp_factor);
478 node = mix_node;
479 }
480 }
481 else if (storage.data_type == blender::SOCK_RGBA) {
482 MixColorNode *mix_node = graph->create_node<MixColorNode>();
483 mix_node->set_blend_type((NodeMix)storage.blend_type);
484 mix_node->set_use_clamp(storage.clamp_factor);
485 mix_node->set_use_clamp_result(storage.clamp_result);
486 node = mix_node;
487 }
488 else {
489 MixFloatNode *mix_node = graph->create_node<MixFloatNode>();
490 mix_node->set_use_clamp(storage.clamp_factor);
491 node = mix_node;
492 }
493 }
494 else if (b_node.is_type("ShaderNodeSeparateColor"_ustr)) {
495 const auto &storage = *static_cast<blender::NodeCombSepColor *>(b_node.storage);
496 SeparateColorNode *separate_node = graph->create_node<SeparateColorNode>();
497 separate_node->set_color_type((NodeCombSepColorType)storage.mode);
498 node = separate_node;
499 }
500 else if (b_node.is_type("ShaderNodeCombineColor"_ustr)) {
501 const auto &storage = *static_cast<blender::NodeCombSepColor *>(b_node.storage);
502 CombineColorNode *combine_node = graph->create_node<CombineColorNode>();
503 combine_node->set_color_type((NodeCombSepColorType)storage.mode);
504 node = combine_node;
505 }
506 else if (b_node.is_type("ShaderNodeSeparateXYZ"_ustr)) {
507 node = graph->create_node<SeparateXYZNode>();
508 }
509 else if (b_node.is_type("FunctionNodeGetVectorComponent"_ustr)) {
511 }
512 else if (b_node.is_type("ShaderNodeCombineXYZ"_ustr)) {
513 node = graph->create_node<CombineXYZNode>();
514 }
515 else if (b_node.is_type("ShaderNodeHueSaturation"_ustr)) {
516 node = graph->create_node<HSVNode>();
517 }
518 else if (b_node.is_type("ShaderNodeRGBToBW"_ustr)) {
519 node = graph->create_node<RGBToBWNode>();
520 }
521 else if (b_node.is_type("ShaderNodeMapRange"_ustr)) {
522 const auto &storage = *static_cast<blender::NodeMapRange *>(b_node.storage);
523 if (storage.data_type == blender::CD_PROP_FLOAT3) {
524 VectorMapRangeNode *vector_map_range_node = graph->create_node<VectorMapRangeNode>();
525 vector_map_range_node->set_use_clamp(storage.clamp);
526 vector_map_range_node->set_range_type((NodeMapRangeType)storage.interpolation_type);
527 node = vector_map_range_node;
528 }
529 else {
530 MapRangeNode *map_range_node = graph->create_node<MapRangeNode>();
531 map_range_node->set_clamp(storage.clamp);
532 map_range_node->set_range_type((NodeMapRangeType)storage.interpolation_type);
533 node = map_range_node;
534 }
535 }
536 else if (b_node.is_type("ShaderNodeClamp"_ustr)) {
537 ClampNode *clamp_node = graph->create_node<ClampNode>();
538 clamp_node->set_clamp_type((NodeClampType)b_node.custom1);
539 node = clamp_node;
540 }
541 else if (b_node.is_type("ShaderNodeMath"_ustr)) {
542 MathNode *math_node = graph->create_node<MathNode>();
543 math_node->set_math_type((NodeMathType)b_node.custom1);
544 math_node->set_use_clamp(b_node.custom2);
545 node = math_node;
546 }
547 else if (b_node.is_type("FunctionNodeBooleanMath"_ustr)) {
548 BooleanMathNode *boolean_math_node = graph->create_node<BooleanMathNode>();
549 boolean_math_node->set_math_type((NodeBooleanMathType)b_node.custom1);
550 node = boolean_math_node;
551 }
552 else if (b_node.is_type("FunctionNodeIntegerMath"_ustr)) {
553 IntegerMathNode *integer_math_node = graph->create_node<IntegerMathNode>();
554 integer_math_node->set_math_type((NodeIntegerMathType)b_node.custom1);
555 node = integer_math_node;
556 }
557 else if (b_node.is_type("ShaderNodeVectorMath"_ustr)) {
558 VectorMathNode *vector_math_node = graph->create_node<VectorMathNode>();
559 vector_math_node->set_math_type((NodeVectorMathType)b_node.custom1);
560 node = vector_math_node;
561 }
562 else if (b_node.is_type("ShaderNodeVectorRotate"_ustr)) {
563 VectorRotateNode *vector_rotate_node = graph->create_node<VectorRotateNode>();
564 vector_rotate_node->set_rotate_type((NodeVectorRotateType)b_node.custom1);
565 vector_rotate_node->set_invert(b_node.custom2);
566 node = vector_rotate_node;
567 }
568 else if (b_node.is_type("ShaderNodeVectorTransform"_ustr)) {
569 const auto &storage = *static_cast<blender::NodeShaderVectTransform *>(b_node.storage);
571 vtransform->set_transform_type((NodeVectorTransformType)storage.type);
572 vtransform->set_convert_from((NodeVectorTransformConvertSpace)storage.convert_from);
573 vtransform->set_convert_to((NodeVectorTransformConvertSpace)storage.convert_to);
574 node = vtransform;
575 }
576 else if (b_node.is_type("ShaderNodeNormal"_ustr)) {
578 norm->set_direction(get_node_output_vector(b_node, "Normal"));
579 node = norm;
580 }
581 else if (b_node.is_type("ShaderNodeMapping"_ustr)) {
582 MappingNode *mapping = graph->create_node<MappingNode>();
583 mapping->set_mapping_type((NodeMappingType)b_node.custom1);
584 node = mapping;
585 }
586 else if (b_node.is_type("ShaderNodeFresnel"_ustr)) {
587 node = graph->create_node<FresnelNode>();
588 }
589 else if (b_node.is_type("ShaderNodeLayerWeight"_ustr)) {
590 node = graph->create_node<LayerWeightNode>();
591 }
592 else if (b_node.is_type("ShaderNodeAddShader"_ustr)) {
593 node = graph->create_node<AddClosureNode>();
594 }
595 else if (b_node.is_type("ShaderNodeMixShader"_ustr)) {
596 node = graph->create_node<MixClosureNode>();
597 }
598 else if (b_node.is_type("ShaderNodeAttribute"_ustr)) {
599 const auto &storage = *static_cast<blender::NodeShaderAttribute *>(b_node.storage);
600 AttributeNode *attr = graph->create_node<AttributeNode>();
601 attr->set_attribute(blender_attribute_name_add_type(storage.name, storage.type));
602 node = attr;
603 }
604 else if (b_node.is_type("ShaderNodeBackground"_ustr)) {
605 node = graph->create_node<BackgroundNode>();
606 }
607 else if (b_node.is_type("ShaderNodeHoldout"_ustr)) {
608 node = graph->create_node<HoldoutNode>();
609 }
610 else if (b_node.is_type("ShaderNodeBsdfDiffuse"_ustr)) {
611 node = graph->create_node<DiffuseBsdfNode>();
612 }
613 else if (b_node.is_type("ShaderNodeSubsurfaceScattering"_ustr)) {
615
616 switch (b_node.custom1) {
618 subsurface->set_method(CLOSURE_BSSRDF_BURLEY_ID);
619 break;
621 subsurface->set_method(CLOSURE_BSSRDF_RANDOM_WALK_ID);
622 break;
624 subsurface->set_method(CLOSURE_BSSRDF_RANDOM_WALK_SKIN_ID);
625 break;
627 subsurface->set_method(CLOSURE_BSSRDF_RANDOM_WALK_LEGACY_ID);
628 break;
629 }
630
631 node = subsurface;
632 }
633 else if (b_node.is_type("ShaderNodeBsdfMetallic"_ustr)) {
635
636 switch (b_node.custom1) {
638 metal->set_distribution(CLOSURE_BSDF_MICROFACET_BECKMANN_ID);
639 break;
641 metal->set_distribution(CLOSURE_BSDF_MICROFACET_GGX_ID);
642 break;
644 metal->set_distribution(CLOSURE_BSDF_MICROFACET_MULTI_GGX_ID);
645 break;
646 }
647
648 switch (b_node.custom2) {
650 metal->set_fresnel_type(CLOSURE_BSDF_PHYSICAL_CONDUCTOR);
651 break;
653 metal->set_fresnel_type(CLOSURE_BSDF_F82_CONDUCTOR);
654 break;
655 }
656 node = metal;
657 }
658 else if (b_node.is_type("ShaderNodeBsdfAnisotropic"_ustr)) {
659 GlossyBsdfNode *glossy = graph->create_node<GlossyBsdfNode>();
660
661 switch (b_node.custom1) {
663 glossy->set_distribution(CLOSURE_BSDF_MICROFACET_BECKMANN_ID);
664 break;
666 glossy->set_distribution(CLOSURE_BSDF_MICROFACET_GGX_ID);
667 break;
669 glossy->set_distribution(CLOSURE_BSDF_ASHIKHMIN_SHIRLEY_ID);
670 break;
672 glossy->set_distribution(CLOSURE_BSDF_MICROFACET_MULTI_GGX_ID);
673 break;
674 }
675 node = glossy;
676 }
677 else if (b_node.is_type("ShaderNodeBsdfGlass"_ustr)) {
678 GlassBsdfNode *glass = graph->create_node<GlassBsdfNode>();
679 switch (b_node.custom1) {
681 glass->set_distribution(CLOSURE_BSDF_MICROFACET_BECKMANN_GLASS_ID);
682 break;
684 glass->set_distribution(CLOSURE_BSDF_MICROFACET_GGX_GLASS_ID);
685 break;
687 glass->set_distribution(CLOSURE_BSDF_MICROFACET_MULTI_GGX_GLASS_ID);
688 break;
689 }
690 node = glass;
691 }
692 else if (b_node.is_type("ShaderNodeBsdfRefraction"_ustr)) {
693 RefractionBsdfNode *refraction = graph->create_node<RefractionBsdfNode>();
694 switch (b_node.custom1) {
696 refraction->set_distribution(CLOSURE_BSDF_MICROFACET_BECKMANN_REFRACTION_ID);
697 break;
699 refraction->set_distribution(CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID);
700 break;
701 }
702 node = refraction;
703 }
704 else if (b_node.is_type("ShaderNodeBsdfToon"_ustr)) {
705 ToonBsdfNode *toon = graph->create_node<ToonBsdfNode>();
706 switch (b_node.custom1) {
708 toon->set_component(CLOSURE_BSDF_DIFFUSE_TOON_ID);
709 break;
711 toon->set_component(CLOSURE_BSDF_GLOSSY_TOON_ID);
712 break;
713 }
714 node = toon;
715 }
716 else if (b_node.is_type("ShaderNodeBsdfHair"_ustr)) {
717 HairBsdfNode *hair = graph->create_node<HairBsdfNode>();
718 switch (b_node.custom1) {
720 hair->set_component(CLOSURE_BSDF_HAIR_REFLECTION_ID);
721 break;
723 hair->set_component(CLOSURE_BSDF_HAIR_TRANSMISSION_ID);
724 break;
725 }
726 node = hair;
727 }
728 else if (b_node.is_type("ShaderNodeBsdfHairPrincipled"_ustr)) {
729 const auto &storage = *static_cast<blender::NodeShaderHairPrincipled *>(b_node.storage);
730 PrincipledHairBsdfNode *principled_hair = graph->create_node<PrincipledHairBsdfNode>();
731 principled_hair->set_model((NodePrincipledHairModel)validate_enum_value(
733 principled_hair->set_parametrization((NodePrincipledHairParametrization)validate_enum_value(
734 storage.parametrization,
737 node = principled_hair;
738 }
739 else if (b_node.is_type("ShaderNodeBsdfPrincipled"_ustr)) {
740 PrincipledBsdfNode *principled = graph->create_node<PrincipledBsdfNode>();
741 switch (b_node.custom1) {
743 principled->set_distribution(CLOSURE_BSDF_MICROFACET_GGX_GLASS_ID);
744 break;
746 principled->set_distribution(CLOSURE_BSDF_MICROFACET_MULTI_GGX_GLASS_ID);
747 break;
748 }
749 switch (b_node.custom2) {
751 principled->set_subsurface_method(CLOSURE_BSSRDF_BURLEY_ID);
752 break;
754 principled->set_subsurface_method(CLOSURE_BSSRDF_RANDOM_WALK_ID);
755 break;
757 principled->set_subsurface_method(CLOSURE_BSSRDF_RANDOM_WALK_SKIN_ID);
758 break;
760 principled->set_subsurface_method(CLOSURE_BSSRDF_RANDOM_WALK_LEGACY_ID);
761 break;
762 }
763 node = principled;
764 }
765 else if (b_node.is_type("ShaderNodeBsdfTranslucent"_ustr)) {
767 }
768 else if (b_node.is_type("ShaderNodeBsdfTransparent"_ustr)) {
770 }
771 else if (b_node.is_type("ShaderNodeBsdfRayPortal"_ustr)) {
773 }
774 else if (b_node.is_type("ShaderNodeBsdfSheen"_ustr)) {
776 switch (b_node.custom1) {
778 sheen->set_distribution(CLOSURE_BSDF_ASHIKHMIN_VELVET_ID);
779 break;
781 sheen->set_distribution(CLOSURE_BSDF_SHEEN_ID);
782 break;
783 }
784 node = sheen;
785 }
786 else if (b_node.is_type("ShaderNodeEmission"_ustr)) {
787 node = graph->create_node<EmissionNode>();
788 }
789 else if (b_node.is_type("ShaderNodeAmbientOcclusion"_ustr)) {
791 ao->set_samples(b_node.custom1);
792 ao->set_inside(b_node.custom2 & blender::SHD_AO_INSIDE);
793 ao->set_only_local(b_node.custom2 & blender::SHD_AO_LOCAL);
794 node = ao;
795 }
796 else if (b_node.is_type("ShaderNodeVolumeScatter"_ustr)) {
798 switch (b_node.custom1) {
801 break;
804 break;
807 break;
810 break;
812 scatter->set_phase(CLOSURE_VOLUME_MIE_ID);
813 break;
814 }
815 node = scatter;
816 }
817 else if (b_node.is_type("ShaderNodeVolumeAbsorption"_ustr)) {
819 }
820 else if (b_node.is_type("ShaderNodeVolumeCoefficients"_ustr)) {
822 switch (b_node.custom1) {
824 coeffs->set_phase(CLOSURE_VOLUME_HENYEY_GREENSTEIN_ID);
825 break;
827 coeffs->set_phase(CLOSURE_VOLUME_FOURNIER_FORAND_ID);
828 break;
830 coeffs->set_phase(CLOSURE_VOLUME_DRAINE_ID);
831 break;
833 coeffs->set_phase(CLOSURE_VOLUME_RAYLEIGH_ID);
834 break;
836 coeffs->set_phase(CLOSURE_VOLUME_MIE_ID);
837 break;
838 }
839 node = coeffs;
840 }
841 else if (b_node.is_type("ShaderNodeVolumePrincipled"_ustr)) {
843 node = principled;
844 }
845 else if (b_node.is_type("ShaderNodeNewGeometry"_ustr)) {
846 node = graph->create_node<GeometryNode>();
847 }
848 else if (b_node.is_type("ShaderNodeWireframe"_ustr)) {
849 WireframeNode *wire = graph->create_node<WireframeNode>();
850 wire->set_use_pixel_size(b_node.custom1);
851 node = wire;
852 }
853 else if (b_node.is_type("ShaderNodeWavelength"_ustr)) {
854 node = graph->create_node<WavelengthNode>();
855 }
856 else if (b_node.is_type("ShaderNodeBlackbody"_ustr)) {
857 node = graph->create_node<BlackbodyNode>();
858 }
859 else if (b_node.is_type("ShaderNodeLightPath"_ustr)) {
860 node = graph->create_node<LightPathNode>();
861 }
862 else if (b_node.is_type("ShaderNodeLightFalloff"_ustr)) {
864 }
865 else if (b_node.is_type("ShaderNodeObjectInfo"_ustr)) {
866 node = graph->create_node<ObjectInfoNode>();
867 }
868 else if (b_node.is_type("ShaderNodeParticleInfo"_ustr)) {
870 }
871 else if (b_node.is_type("ShaderNodeHairInfo"_ustr)) {
872 node = graph->create_node<HairInfoNode>();
873 }
874 else if (b_node.is_type("ShaderNodePointInfo"_ustr)) {
875 node = graph->create_node<PointInfoNode>();
876 }
877 else if (b_node.is_type("ShaderNodeVolumeInfo"_ustr)) {
878 node = graph->create_node<VolumeInfoNode>();
879 }
880 else if (b_node.is_type("ShaderNodeVertexColor"_ustr)) {
881 const auto &storage = *static_cast<blender::NodeShaderVertexColor *>(b_node.storage);
882 VertexColorNode *vertex_color_node = graph->create_node<VertexColorNode>();
883 vertex_color_node->set_layer_name(ustring(storage.layer_name));
884 node = vertex_color_node;
885 }
886 else if (b_node.is_type("ShaderNodeBump"_ustr)) {
887 BumpNode *bump = graph->create_node<BumpNode>();
888 bump->set_invert(b_node.custom1);
889 node = bump;
890 }
891 else if (b_node.is_type("ShaderNodeScript"_ustr)) {
892#ifdef WITH_OSL
893 const auto &storage = *static_cast<blender::NodeShaderScript *>(b_node.storage);
894 if (scene->shader_manager->use_osl()) {
895 const string bytecode_hash = storage.bytecode_hash;
896 if (!bytecode_hash.empty()) {
897 node = OSLShaderManager::osl_node(graph, scene, "", bytecode_hash, storage.bytecode);
898 }
899 else {
900 const string absolute_filepath = blender_absolute_path(
901 b_data, &b_ntree.id, storage.filepath);
902 node = OSLShaderManager::osl_node(graph, scene, absolute_filepath, "");
903 }
904 }
905#else
906 (void)b_data;
907 (void)b_ntree;
908#endif
909 }
910 else if (b_node.is_type("ShaderNodeTexImage"_ustr)) {
911 const auto &storage = *static_cast<blender::NodeTexImage *>(b_node.storage);
912 blender::Image *b_image = blender::id_cast<blender::Image *>(b_node.id);
913 blender::ImageUser &b_image_user = const_cast<blender::ImageUser &>(storage.iuser);
915
916 image->set_interpolation(get_image_interpolation(storage));
917 image->set_extension(get_image_extension(storage));
918 image->set_projection((NodeImageProjection)storage.projection);
919 image->set_projection_blend(storage.projection_blend);
920 const blender::TexMapping &b_texture_mapping = storage.base.tex_mapping;
921 get_tex_mapping(image, &b_texture_mapping);
922
923 if (b_image) {
924 const blender::eImageSource b_image_source = blender::eImageSource(b_image->source);
925 blender::PointerRNA image_rna_ptr = RNA_id_pointer_create(&b_image->id);
926 image->set_colorspace(ustring(b_image->colorspace_settings.name));
927 image->set_animated(is_image_animated(b_image_source, b_image_user));
928 image->set_alpha_type(get_image_alpha_type(*b_image));
929
930 if (b_image_source == blender::IMA_SRC_TILED) {
932 for (blender::ImageTile &b_tile : b_image->tiles) {
933 tiles.push_back_slow(b_tile.tile_number);
934 }
935 image->set_tiles(tiles);
936 }
937
938 /* builtin images will use callback-based reading because
939 * they could only be loaded correct from blender side
940 */
941 const bool is_builtin = image_is_builtin(*b_image, b_engine);
942
943 if (is_builtin) {
944 /* for builtin images we're using image datablock name to find an image to
945 * read pixels from later
946 *
947 * also store frame number as well, so there's no differences in handling
948 * builtin names for packed images and movies
949 */
950 const int scene_frame = b_scene.r.cfra;
951 const int image_frame = image_user_frame_number(b_image_user, *b_image, scene_frame);
952 if (b_image_source != blender::IMA_SRC_TILED) {
953 image->handle = scene->image_manager->add_image(
954 make_unique<BlenderImageLoader>(b_image,
955 &b_image_user,
956 image_frame,
957 0,
958 (b_engine.flag & blender::RE_ENGINE_PREVIEW) != 0),
959 image->image_params());
960 }
961 else {
963 loaders.reserve(image->get_tiles().size());
964 for (const int tile_number : image->get_tiles()) {
965 loaders.push_back(make_unique<BlenderImageLoader>(
966 b_image,
967 &b_image_user,
968 image_frame,
969 tile_number,
970 (b_engine.flag & blender::RE_ENGINE_PREVIEW) != 0));
971 }
972
973 image->handle = scene->image_manager->add_image(std::move(loaders),
974 image->image_params());
975 }
976 }
977 else {
978 const ustring filename = ustring(
979 image_user_file_path(b_data, b_image_user, *b_image, b_scene.r.cfra));
980 image->set_filename(filename);
981 }
982 }
983 node = image;
984 }
985 else if (b_node.is_type("ShaderNodeTexEnvironment"_ustr)) {
986 const auto &storage = *static_cast<blender::NodeTexEnvironment *>(b_node.storage);
987 blender::Image *b_image = blender::id_cast<blender::Image *>(b_node.id);
988 blender::ImageUser &b_image_user = const_cast<blender::ImageUser &>(storage.iuser);
990
991 env->set_interpolation(get_image_interpolation(storage));
992 env->set_projection((NodeEnvironmentProjection)storage.projection);
993 const blender::TexMapping &b_texture_mapping = storage.base.tex_mapping;
994 get_tex_mapping(env, &b_texture_mapping);
995
996 if (b_image) {
997 const blender::eImageSource b_image_source = blender::eImageSource(b_image->source);
998 blender::PointerRNA image_rna_ptr = RNA_id_pointer_create(&b_image->id);
999 env->set_colorspace(ustring(b_image->colorspace_settings.name));
1000 env->set_animated(is_image_animated(b_image_source, b_image_user));
1001 env->set_alpha_type(get_image_alpha_type(*b_image));
1002
1003 const bool is_builtin = image_is_builtin(*b_image, b_engine);
1004
1005 if (is_builtin) {
1006 const int scene_frame = b_scene.r.cfra;
1007 const int image_frame = image_user_frame_number(b_image_user, *b_image, scene_frame);
1008 env->handle = scene->image_manager->add_image(
1009 make_unique<BlenderImageLoader>(b_image,
1010 &b_image_user,
1011 image_frame,
1012 0,
1013 (b_engine.flag & blender::RE_ENGINE_PREVIEW) != 0),
1014 env->image_params());
1015 }
1016 else {
1017 env->set_filename(
1018 ustring(image_user_file_path(b_data, b_image_user, *b_image, b_scene.r.cfra)));
1019 }
1020 }
1021 node = env;
1022 }
1023 else if (b_node.is_type("ShaderNodeTexGradient"_ustr)) {
1024 const auto &storage = *static_cast<blender::NodeTexGradient *>(b_node.storage);
1026 gradient->set_gradient_type((NodeGradientType)storage.gradient_type);
1027 const blender::TexMapping &b_texture_mapping = storage.base.tex_mapping;
1028 get_tex_mapping(gradient, &b_texture_mapping);
1029 node = gradient;
1030 }
1031 else if (b_node.is_type("ShaderNodeTexVoronoi"_ustr)) {
1032 const auto &storage = *static_cast<blender::NodeTexVoronoi *>(b_node.storage);
1034 voronoi->set_dimensions(storage.dimensions);
1035 voronoi->set_feature((NodeVoronoiFeature)storage.feature);
1036 voronoi->set_metric((NodeVoronoiDistanceMetric)storage.distance);
1037 voronoi->set_use_normalize(storage.normalize);
1038 const blender::TexMapping &b_texture_mapping = storage.base.tex_mapping;
1039 get_tex_mapping(voronoi, &b_texture_mapping);
1040 node = voronoi;
1041 }
1042 else if (b_node.is_type("ShaderNodeTexMagic"_ustr)) {
1043 const auto &storage = *static_cast<blender::NodeTexMagic *>(b_node.storage);
1045 magic->set_depth(storage.depth);
1046 const blender::TexMapping &b_texture_mapping = storage.base.tex_mapping;
1047 get_tex_mapping(magic, &b_texture_mapping);
1048 node = magic;
1049 }
1050 else if (b_node.is_type("ShaderNodeTexWave"_ustr)) {
1051 const auto &storage = *static_cast<blender::NodeTexWave *>(b_node.storage);
1053 wave->set_wave_type((NodeWaveType)storage.wave_type);
1054 wave->set_bands_direction((NodeWaveBandsDirection)storage.bands_direction);
1055 wave->set_rings_direction((NodeWaveRingsDirection)storage.rings_direction);
1056 wave->set_profile((NodeWaveProfile)storage.wave_profile);
1057 const blender::TexMapping &b_texture_mapping = storage.base.tex_mapping;
1058 get_tex_mapping(wave, &b_texture_mapping);
1059 node = wave;
1060 }
1061 else if (b_node.is_type("ShaderNodeTexChecker"_ustr)) {
1062 const auto &storage = *static_cast<blender::NodeTexChecker *>(b_node.storage);
1064 const blender::TexMapping &b_texture_mapping = storage.base.tex_mapping;
1065 get_tex_mapping(checker, &b_texture_mapping);
1066 node = checker;
1067 }
1068 else if (b_node.is_type("ShaderNodeTexBrick"_ustr)) {
1069 const auto &storage = *static_cast<blender::NodeTexBrick *>(b_node.storage);
1071 brick->set_offset(storage.offset);
1072 brick->set_offset_frequency(storage.offset_freq);
1073 brick->set_squash(storage.squash);
1074 brick->set_squash_frequency(storage.squash_freq);
1075 const blender::TexMapping &b_texture_mapping = storage.base.tex_mapping;
1076 get_tex_mapping(brick, &b_texture_mapping);
1077 node = brick;
1078 }
1079 else if (b_node.is_type("ShaderNodeTexNoise"_ustr)) {
1080 const auto &storage = *static_cast<blender::NodeTexNoise *>(b_node.storage);
1082 noise->set_dimensions(storage.dimensions);
1083 noise->set_type((NodeNoiseType)storage.type);
1084 noise->set_use_normalize(storage.normalize);
1085 const blender::TexMapping &b_texture_mapping = storage.base.tex_mapping;
1086 get_tex_mapping(noise, &b_texture_mapping);
1087 node = noise;
1088 }
1089 else if (b_node.is_type("ShaderNodeTexGabor"_ustr)) {
1090 const auto &storage = *static_cast<blender::NodeTexGabor *>(b_node.storage);
1092 gabor->set_type((NodeGaborType)storage.type);
1093 const blender::TexMapping &b_texture_mapping = storage.base.tex_mapping;
1094 get_tex_mapping(gabor, &b_texture_mapping);
1095 node = gabor;
1096 }
1097 else if (b_node.is_type("ShaderNodeTexCoord"_ustr)) {
1099 tex_coord->set_from_dupli(b_node.custom1);
1100 if (const blender::ID *b_object = b_node.id) {
1101 tex_coord->set_use_transform(true);
1102 tex_coord->set_ob_tfm(
1103 get_transform(blender::id_cast<const blender::Object *>(b_object)->object_to_world()));
1104 }
1105 node = tex_coord;
1106 }
1107 else if (b_node.is_type("ShaderNodeTexSky"_ustr)) {
1108 const auto &storage = *static_cast<blender::NodeTexSky *>(b_node.storage);
1109 SkyTextureNode *sky = graph->create_node<SkyTextureNode>();
1110 sky->set_sky_type((NodeSkyType)storage.sky_model);
1111 sky->set_sun_direction(normalize(make_float3(
1112 storage.sun_direction[0], storage.sun_direction[1], storage.sun_direction[2])));
1113 sky->set_turbidity(storage.turbidity);
1114 sky->set_ground_albedo(storage.ground_albedo);
1115 sky->set_sun_disc(storage.sun_disc);
1116 sky->set_sun_size(storage.sun_size);
1117 sky->set_sun_intensity(storage.sun_intensity);
1118 sky->set_sun_elevation(storage.sun_elevation);
1119 sky->set_sun_rotation(storage.sun_rotation);
1120 sky->set_altitude(storage.altitude);
1121 sky->set_air_density(storage.air_density);
1122 sky->set_aerosol_density(storage.aerosol_density);
1123 sky->set_ozone_density(storage.ozone_density);
1124 const blender::TexMapping &b_texture_mapping = storage.base.tex_mapping;
1125 get_tex_mapping(sky, &b_texture_mapping);
1126 node = sky;
1127 }
1128 else if (b_node.is_type("ShaderNodeTexIES"_ustr)) {
1129 const auto &storage = *static_cast<blender::NodeShaderTexIES *>(b_node.storage);
1130 IESLightNode *ies = graph->create_node<IESLightNode>();
1131 switch (storage.mode) {
1133 ies->set_filename(ustring(blender_absolute_path(b_data, &b_ntree.id, storage.filepath)));
1134 break;
1136 ustring ies_content = ustring(get_text_datablock_content(b_node.id));
1137 ies->set_ies(ies_content);
1138 break;
1139 }
1140 node = ies;
1141 }
1142 else if (b_node.is_type("ShaderNodeTexWhiteNoise"_ustr)) {
1143 WhiteNoiseTextureNode *white_noise_node = graph->create_node<WhiteNoiseTextureNode>();
1144 white_noise_node->set_dimensions(b_node.custom1);
1145 node = white_noise_node;
1146 }
1147 else if (b_node.is_type("ShaderNodeNormalMap"_ustr)) {
1148 const auto &storage = *static_cast<blender::NodeShaderNormalMap *>(b_node.storage);
1149 NormalMapNode *nmap = graph->create_node<NormalMapNode>();
1150 nmap->set_space(NodeNormalMapSpace(storage.space));
1151 nmap->set_attribute(ustring(storage.uv_map));
1152 nmap->set_convention(NodeNormalMapConvention(storage.convention));
1153 nmap->set_base(NodeNormalMapBase(storage.base));
1154 node = nmap;
1155 }
1156 else if (b_node.is_type("ShaderNodeRadialTiling"_ustr)) {
1157 const auto &storage = *static_cast<blender::NodeRadialTiling *>(b_node.storage);
1158 RadialTilingNode *radial_tiling = graph->create_node<RadialTilingNode>();
1159 radial_tiling->set_use_normalize(storage.normalize);
1160 node = radial_tiling;
1161 }
1162 else if (b_node.is_type("ShaderNodeTangent"_ustr)) {
1163 const auto &storage = *static_cast<blender::NodeShaderTangent *>(b_node.storage);
1164 TangentNode *tangent = graph->create_node<TangentNode>();
1165 tangent->set_direction_type((NodeTangentDirectionType)storage.direction_type);
1166 tangent->set_axis((NodeTangentAxis)storage.axis);
1167 tangent->set_attribute(ustring(storage.uv_map));
1168 node = tangent;
1169 }
1170 else if (b_node.is_type("ShaderNodeUVMap"_ustr)) {
1171 const auto &storage = *static_cast<blender::NodeShaderUVMap *>(b_node.storage);
1172 UVMapNode *uvm = graph->create_node<UVMapNode>();
1173 uvm->set_attribute(ustring(storage.uv_map));
1174 uvm->set_from_dupli(b_node.custom1);
1175 node = uvm;
1176 }
1177 else if (b_node.is_type("ShaderNodeBevel"_ustr)) {
1178 BevelNode *bevel = graph->create_node<BevelNode>();
1179 bevel->set_samples(b_node.custom1);
1180 node = bevel;
1181 }
1182 else if (b_node.is_type("ShaderNodeDisplacement"_ustr)) {
1184 disp->set_space((NodeNormalMapSpace)b_node.custom1);
1185 node = disp;
1186 }
1187 else if (b_node.is_type("ShaderNodeVectorDisplacement"_ustr)) {
1189 disp->set_space((NodeNormalMapSpace)b_node.custom1);
1190 disp->set_attribute(ustring(""));
1191 node = disp;
1192 }
1193 else if (b_node.is_type("ShaderNodeOutputAOV"_ustr)) {
1194 const auto &storage = *static_cast<blender::NodeShaderOutputAOV *>(b_node.storage);
1195 OutputAOVNode *aov = graph->create_node<OutputAOVNode>();
1196 aov->set_name(ustring(storage.name));
1197 node = aov;
1198 }
1199 else if (b_node.is_type("ShaderNodeRaycast"_ustr)) {
1200 RaycastNode *raycast = graph->create_node<RaycastNode>();
1201 raycast->set_only_local(b_node.custom1);
1202 raycast_add_output_attribute_sockets(raycast, b_node);
1203 node = raycast;
1204 }
1205 else if (b_node.is_type("GeometryNodeInputSceneTime"_ustr)) {
1206 node = graph->create_node<SceneTimeNode>();
1207 }
1208
1209 if (node) {
1210 node->name = b_node.name;
1211 }
1212
1213 return node;
1214}
1215
1217{
1218 if (node->special_type == SHADER_SPECIAL_TYPE_OSL) {
1219 return false;
1220 }
1221
1222 return true;
1223}
1224
1227 blender::bNodeSocket &b_socket)
1228{
1229 using blender::operator""_ustr;
1230 string name = b_socket.identifier;
1231 ShaderInput *input = node->input(name.c_str());
1232
1233 if (!input && node_use_modified_socket_name(node)) {
1234 /* Different internal name for shader. */
1235 if (string_startswith(name, "Shader")) {
1236 string_replace(name, "Shader", "Closure");
1237 }
1238
1239 /* Map mix node internal name for shader. */
1240 if (b_node.is_type("ShaderNodeMix"_ustr)) {
1241 if (string_endswith(name, "Factor_Float")) {
1242 string_replace(name, "Factor_Float", "Factor");
1243 }
1244 else if (string_endswith(name, "Factor_Vector")) {
1245 string_replace(name, "Factor_Vector", "Factor");
1246 }
1247 else if (string_endswith(name, "A_Float")) {
1248 string_replace(name, "A_Float", "A");
1249 }
1250 else if (string_endswith(name, "B_Float")) {
1251 string_replace(name, "B_Float", "B");
1252 }
1253 else if (string_endswith(name, "A_Color")) {
1254 string_replace(name, "A_Color", "A");
1255 }
1256 else if (string_endswith(name, "B_Color")) {
1257 string_replace(name, "B_Color", "B");
1258 }
1259 else if (string_endswith(name, "A_Vector")) {
1260 string_replace(name, "A_Vector", "A");
1261 }
1262 else if (string_endswith(name, "B_Vector")) {
1263 string_replace(name, "B_Vector", "B");
1264 }
1265 }
1266
1267 input = node->input(name.c_str());
1268
1269 if (!input) {
1270 /* Different internal numbering of two sockets with same name.
1271 * Note that the Blender convention for unique socket names changed
1272 * from . to _ at some point, so we check both to handle old files. */
1273 if (string_endswith(name, "_001")) {
1274 string_replace(name, "_001", "2");
1275 }
1276 else if (string_endswith(name, ".001")) {
1277 string_replace(name, ".001", "2");
1278 }
1279 else if (string_endswith(name, "_002")) {
1280 string_replace(name, "_002", "3");
1281 }
1282 else if (string_endswith(name, ".002")) {
1283 string_replace(name, ".002", "3");
1284 }
1285 else {
1286 name += "1";
1287 }
1288
1289 input = node->input(name.c_str());
1290 }
1291 }
1292
1293 return input;
1294}
1295
1298 blender::bNodeSocket &b_socket)
1299{
1300 using blender::operator""_ustr;
1301 string name = b_socket.identifier;
1302 ShaderOutput *output = node->output(name.c_str());
1303
1305 /* Different internal name for shader. */
1306 if (name == "Shader") {
1307 name = "Closure";
1308 output = node->output(name.c_str());
1309 }
1310 /* Map internal name for shader. */
1311 if (b_node.is_type("ShaderNodeMix"_ustr)) {
1312 if (string_endswith(name, "Result_Float")) {
1313 string_replace(name, "Result_Float", "Result");
1314 output = node->output(name.c_str());
1315 }
1316 else if (string_endswith(name, "Result_Color")) {
1317 string_replace(name, "Result_Color", "Result");
1318 output = node->output(name.c_str());
1319 }
1320 else if (string_endswith(name, "Result_Vector")) {
1321 string_replace(name, "Result_Vector", "Result");
1322 output = node->output(name.c_str());
1323 }
1324 }
1325 else if (b_node.is_type("FunctionNodeInputVector"_ustr)) {
1326 /* FunctionNodeInputVector has an output called "Vector", and it uses ColorNode Cycles node
1327 * that has an output called "Color". */
1328 if (name == "Vector") {
1329 name = "Color";
1330 output = node->output(name.c_str());
1331 }
1332 }
1333 }
1334
1335 return output;
1336}
1337
1338static void add_nodes(Scene *scene,
1339 blender::RenderEngine &b_engine,
1340 blender::Main &b_data,
1341 blender::Scene &b_scene,
1342 blender::Depsgraph &b_depsgraph,
1343 ShaderGraph *graph,
1344 blender::bNodeTree &b_ntree,
1345 const ProxyMap &proxy_input_map,
1346 const ProxyMap &proxy_output_map);
1347
1348static void add_nodes_inlined(Scene *scene,
1349 blender::RenderEngine &b_engine,
1350 blender::Main &b_data,
1351 blender::Scene &b_scene,
1352 blender::Depsgraph &b_depsgraph,
1353 ShaderGraph *graph,
1354 blender::bNodeTree &b_ntree,
1355 const ProxyMap &proxy_input_map,
1356 const ProxyMap &proxy_output_map)
1357{
1358 using blender::operator""_ustr;
1359 /* add nodes */
1360 PtrInputMap input_map;
1361 PtrOutputMap output_map;
1362
1363 /* find the node to use for output if there are multiple */
1364 const blender::bNode *output_node = ntreeShaderOutputNode(&b_ntree, blender::SHD_OUTPUT_CYCLES);
1365
1366 /* add nodes */
1367 for (blender::bNode *b_node : b_ntree.all_nodes()) {
1368 if (b_node->is_muted() || b_node->is_reroute()) {
1369 /* replace muted node with internal links */
1370 for (blender::bNodeInternalLink &b_link : b_node->runtime->internal_links) {
1371 blender::bNodeSocket *to_socket = b_link.out;
1372 const SocketType::Type to_socket_type = convert_socket_type(*to_socket);
1373 if (to_socket_type == SocketType::UNDEFINED) {
1374 continue;
1375 }
1376
1377 ConvertNode *proxy = graph->create_node<ConvertNode>(to_socket_type, to_socket_type, true);
1378
1379 /* Muted nodes can result in multiple Cycles input sockets mapping to the same Blender
1380 * input socket, so this needs to be a multimap. */
1381 input_map.emplace(b_link.in, proxy->inputs[0]);
1382 output_map[b_link.out] = proxy->outputs[0];
1383 }
1384 }
1385 else if (b_node->is_group()) {
1386 blender::bNodeTree *b_group_ntree = blender::id_cast<blender::bNodeTree *>(b_node->id);
1387
1388 ProxyMap group_proxy_input_map;
1389 ProxyMap group_proxy_output_map;
1390
1391 /* Add a proxy node for each socket
1392 * Do this even if the node group has no internal tree,
1393 * so that links have something to connect to and assert won't fail.
1394 */
1395 for (blender::bNodeSocket *b_input : b_node->input_sockets()) {
1396 const SocketType::Type input_type = convert_socket_type(*b_input);
1397 if (input_type == SocketType::UNDEFINED) {
1398 continue;
1399 }
1400
1401 ConvertNode *proxy = graph->create_node<ConvertNode>(input_type, input_type, true);
1402
1403 /* register the proxy node for internal binding */
1404 group_proxy_input_map[b_input->identifier] = proxy;
1405
1406 input_map.emplace(b_input, proxy->inputs[0]);
1407
1408 set_default_value(proxy->inputs[0], *b_input, b_data, b_ntree.id);
1409 }
1410 for (blender::bNodeSocket *b_output : b_node->output_sockets()) {
1411 const SocketType::Type output_type = convert_socket_type(*b_output);
1412 if (output_type == SocketType::UNDEFINED) {
1413 continue;
1414 }
1415
1416 ConvertNode *proxy = graph->create_node<ConvertNode>(output_type, output_type, true);
1417
1418 /* register the proxy node for internal binding */
1419 group_proxy_output_map[b_output->identifier] = proxy;
1420
1421 output_map[b_output] = proxy->outputs[0];
1422 }
1423
1424 if (b_group_ntree) {
1425 add_nodes(scene,
1426 b_engine,
1427 b_data,
1428 b_scene,
1429 b_depsgraph,
1430 graph,
1431 *b_group_ntree,
1432 group_proxy_input_map,
1433 group_proxy_output_map);
1434 }
1435 }
1436 else if (b_node->is_type("NodeGroupInput"_ustr)) {
1437 /* map each socket to a proxy node */
1438 for (blender::bNodeSocket *b_output : b_node->output_sockets()) {
1439 const ProxyMap::const_iterator proxy_it = proxy_input_map.find(b_output->identifier);
1440 if (proxy_it != proxy_input_map.end()) {
1441 ConvertNode *proxy = proxy_it->second;
1442
1443 output_map[b_output] = proxy->outputs[0];
1444 }
1445 }
1446 }
1447 else if (b_node->is_type("NodeGroupOutput"_ustr)) {
1448 /* only the active group output is used */
1449 if (b_node->flag & blender::NODE_DO_OUTPUT) {
1450 /* map each socket to a proxy node */
1451 for (blender::bNodeSocket *b_input : b_node->input_sockets()) {
1452 const ProxyMap::const_iterator proxy_it = proxy_output_map.find(b_input->identifier);
1453 if (proxy_it != proxy_output_map.end()) {
1454 ConvertNode *proxy = proxy_it->second;
1455
1456 input_map.emplace(b_input, proxy->inputs[0]);
1457
1458 set_default_value(proxy->inputs[0], *b_input, b_data, b_ntree.id);
1459 }
1460 }
1461 }
1462 }
1463 /* TODO: All the previous cases can be removed? */
1464 else {
1465 ShaderNode *node = nullptr;
1466
1467 if (b_node == output_node) {
1468 node = graph->output();
1469 }
1470 else {
1471 node = add_node(scene, b_engine, b_data, b_scene, graph, b_ntree, *b_node);
1472 }
1473
1474 if (node) {
1475 /* map node sockets for linking */
1476 for (blender::bNodeSocket *b_input : b_node->input_sockets()) {
1477 if (!b_input->is_available()) {
1478 /* Skip unavailable sockets. */
1479 continue;
1480 }
1481 ShaderInput *input = node_find_input_by_name(*b_node, node, *b_input);
1482 if (!input) {
1483 /* XXX should not happen, report error? */
1484 continue;
1485 }
1486 input_map.emplace(b_input, input);
1487
1488 set_default_value(input, *b_input, b_data, b_ntree.id);
1489 }
1490 for (blender::bNodeSocket *b_output : b_node->output_sockets()) {
1491 if (!b_output->is_available()) {
1492 /* Skip unavailable sockets. */
1493 continue;
1494 }
1495 ShaderOutput *output = node_find_output_by_name(*b_node, node, *b_output);
1496 if (!output) {
1497 /* XXX should not happen, report error? */
1498 continue;
1499 }
1500 output_map[b_output] = output;
1501 }
1502 }
1503 }
1504 }
1505
1506 /* connect nodes */
1507 for (blender::bNodeLink *b_link : b_ntree.all_links()) {
1508 /* Ignore invalid links to avoid unwanted cycles created in graph.
1509 * Also ignore links with unavailable sockets. */
1510 if (!((b_link->flag & blender::NODE_LINK_VALID) != 0 && b_link->fromsock->is_available() &&
1511 b_link->tosock->is_available()) ||
1512 b_link->is_muted())
1513 {
1514 continue;
1515 }
1516 /* get blender link data */
1517 blender::bNodeSocket *b_from_sock = b_link->fromsock;
1518 blender::bNodeSocket *b_to_sock = b_link->tosock;
1519
1520 ShaderOutput *output = nullptr;
1521 const PtrOutputMap::iterator output_it = output_map.find(b_from_sock);
1522 if (output_it != output_map.end()) {
1523 output = output_it->second;
1524 }
1525
1526 /* either socket may be nullptr when the node was not exported, typically
1527 * because the node type is not supported */
1528 if (output != nullptr) {
1529 ShaderOutput *output = output_it->second;
1530 auto inputs = input_map.equal_range(b_to_sock);
1531 for (PtrInputMap::iterator input_it = inputs.first; input_it != inputs.second; ++input_it) {
1532 ShaderInput *input = input_it->second;
1533 if (input != nullptr) {
1534 graph->connect(output, input);
1535 }
1536 }
1537 }
1538 }
1539}
1540
1542 blender::Depsgraph &b_depsgraph,
1544{
1545 if (!DEG_is_active(&b_depsgraph)) {
1546 return;
1547 }
1549 const blender::bNodeTree &tree = error.node->owner_tree();
1550 if (const blender::bNodeTree *tree_orig = DEG_get_original(&tree)) {
1551 std::lock_guard lock(tree_orig->runtime->shader_node_errors_mutex);
1552 tree_orig->runtime->shader_node_errors.lookup_or_add_default(error.node->identifier)
1553 .add({error.type, error.message});
1554 }
1555 }
1556}
1557
1558static void add_nodes(Scene *scene,
1559 blender::RenderEngine &b_engine,
1560 blender::Main &b_data,
1561 blender::Scene &b_scene,
1562 blender::Depsgraph &b_depsgraph,
1563 ShaderGraph *graph,
1564 blender::bNodeTree &b_ntree,
1565 const ProxyMap &proxy_input_map,
1566 const ProxyMap &proxy_output_map)
1567{
1569 nullptr, (blender::StringRef(b_ntree.id.name) + " Inlined").c_str(), b_ntree.idname);
1571 inline_params.allow_preserving_repeat_zones = false;
1573 blender::nodes::inline_shader_node_tree(b_ntree, *localtree, inline_params);
1574
1575 store_shader_node_errors(b_depsgraph, inline_params.r_error_messages);
1576
1577 add_nodes_inlined(scene,
1578 b_engine,
1579 b_data,
1580 b_scene,
1581 b_depsgraph,
1582 graph,
1583 *localtree,
1584 proxy_input_map,
1585 proxy_output_map);
1586
1587 BKE_id_free(nullptr, &localtree->id);
1588}
1589
1590static void add_nodes(Scene *scene,
1591 blender::RenderEngine &b_engine,
1592 blender::Main &b_data,
1593 blender::Scene &b_scene,
1594 blender::Depsgraph &b_depsgraph,
1595 ShaderGraph *graph,
1596 blender::bNodeTree &b_ntree)
1597{
1598 static const ProxyMap empty_proxy_map;
1599 add_nodes(scene,
1600 b_engine,
1601 b_data,
1602 b_scene,
1603 b_depsgraph,
1604 graph,
1605 b_ntree,
1606 empty_proxy_map,
1607 empty_proxy_map);
1608}
1609
1610/* Look up and constant fold all references to View Layer attributes. */
1611void BlenderSync::resolve_view_layer_attributes(Shader *shader,
1612 ShaderGraph *graph,
1613 blender::Depsgraph &b_depsgraph)
1614{
1615 bool updated = false;
1616
1617 for (ShaderNode *node : graph->nodes) {
1618 if (node->is_a(AttributeNode::get_node_type())) {
1619 AttributeNode *attr_node = static_cast<AttributeNode *>(node);
1620
1621 std::string real_name;
1622 const int type = blender_attribute_name_split_type(attr_node->get_attribute(), &real_name);
1623
1625 /* Look up the value. */
1626 const blender::ViewLayer *b_layer = DEG_get_evaluated_view_layer(&b_depsgraph);
1627 const blender::Scene *b_scene = DEG_get_evaluated_scene(&b_depsgraph);
1628 float4 value;
1629
1630 BKE_view_layer_find_rgba_attribute(b_scene, b_layer, real_name.c_str(), &value.x);
1631
1632 /* Replace all outgoing links, using appropriate output types. */
1633 const float val_avg = (value.x + value.y + value.z) / 3.0f;
1634
1635 for (ShaderOutput *output : node->outputs) {
1636 float val_float;
1637 float3 val_float3;
1638
1639 if (output->type() == SocketType::FLOAT) {
1640 val_float = (output->name() == "Alpha") ? value.w : val_avg;
1641 val_float3 = make_float3(val_float);
1642 }
1643 else {
1644 val_float = val_avg;
1645 val_float3 = make_float3(value);
1646 }
1647
1648 for (ShaderInput *sock : output->links) {
1649 if (sock->type() == SocketType::FLOAT) {
1650 sock->set(val_float);
1651 }
1652 else if (SocketType::is_float3(sock->type())) {
1653 sock->set(val_float3);
1654 }
1655
1656 sock->constant_folded_in = true;
1657 }
1658
1659 graph->disconnect(output);
1660 }
1661
1662 /* Clear the attribute name to avoid further attempts to look up. */
1663 attr_node->set_attribute(ustring());
1664 updated = true;
1665 }
1666 }
1667 }
1668
1669 if (updated) {
1670 shader_map.set_flag(shader, SHADER_WITH_LAYER_ATTRS);
1671 }
1672 else {
1673 shader_map.clear_flag(shader, SHADER_WITH_LAYER_ATTRS);
1674 }
1675}
1676
1677bool BlenderSync::scene_attr_needs_recalc(Shader *shader, blender::Depsgraph &b_depsgraph)
1678{
1679 if (shader && shader_map.test_flag(shader, SHADER_WITH_LAYER_ATTRS)) {
1680 blender::Scene *scene = DEG_get_evaluated_scene(&b_depsgraph);
1681
1682 return shader_map.check_recalc(&scene->id) ||
1683 shader_map.check_recalc(reinterpret_cast<blender::ID *>(scene->world)) ||
1684 shader_map.check_recalc(reinterpret_cast<blender::ID *>(scene->camera));
1685 }
1686
1687 return false;
1688}
1689
1690/* Sync Materials */
1691
1692void BlenderSync::sync_materials(blender::Depsgraph &b_depsgraph,
1693 bool update_all,
1694 bool update_time)
1695{
1696 shader_map.set_default(scene->default_surface);
1697
1698 TaskPool pool;
1699 set<Shader *> updated_shaders;
1700
1701 /* When consecutive view layers to be rendered have different AOVs or if those AOVs are merely
1702 * reordered, the AOV offsets in the shaders that have AOV output nodes must be updated via
1703 * OutputAOVNode::simplify_settings() further down the line.
1704 * This tracking ensures that the inputs of the AOV output nodes are connected when needed,
1705 * disconnected when not, and that the offsets, which also depend on the data types, are correct.
1706 * Storing the new AOV data must take place even if no shaders are affected so the new data
1707 * is available as the old data when the next view layer is rendered, but the check could be
1708 * deferred.
1709 */
1710 blender::Vector<std::pair<std::string, int>> new_shader_view_layer_aovs;
1711 /* Store info on the new AOVs. */
1712 blender::ViewLayer *const b_view_layer = DEG_get_evaluated_view_layer(&b_depsgraph);
1713 for (blender::ViewLayerAOV &b_aov : b_view_layer->aovs) {
1714 if ((b_aov.flag & blender::AOV_CONFLICT) != 0) {
1715 continue;
1716 }
1717 new_shader_view_layer_aovs.append({b_aov.name, b_aov.type});
1718 }
1719 const bool aovs_changed_between_view_layers = new_shader_view_layer_aovs !=
1720 shader_view_layer_aovs;
1721
1722 blender::DEGIDIterData data{};
1723 data.graph = &b_depsgraph;
1727 &data,
1728 blender::ID *,
1729 b_id)
1730 {
1731 if (b_id->id_type() != blender::ID_MA) {
1732 continue;
1733 }
1734
1735 blender::Material &b_mat = blender::id_cast<blender::Material &>(*b_id);
1736 Shader *shader;
1737
1738 /* test if we need to sync */
1739 if (shader_map.add_or_update(&shader, &b_mat.id) || update_all ||
1740 scene_attr_needs_recalc(shader, b_depsgraph) || aovs_changed_between_view_layers ||
1741 (shader->has_time_dependency && update_time))
1742 {
1743 unique_ptr<ShaderGraph> graph = make_unique<ShaderGraph>();
1744
1745 shader->name = BKE_id_name(b_mat.id);
1746 shader->set_pass_id(b_mat.index);
1747
1748 /* create nodes */
1749 if (b_mat.nodetree) {
1750 add_nodes(scene, *b_engine, *b_data, *b_scene, b_depsgraph, graph.get(), *b_mat.nodetree);
1751 }
1752 else {
1753 DiffuseBsdfNode *diffuse = graph->create_node<DiffuseBsdfNode>();
1754 diffuse->set_color(make_float3(b_mat.r, b_mat.g, b_mat.b));
1755
1756 ShaderNode *out = graph->output();
1757 graph->connect(diffuse->output("BSDF"), out->input("Surface"));
1758 }
1759
1760 resolve_view_layer_attributes(shader, graph.get(), b_depsgraph);
1761
1762 /* settings */
1763 blender::PointerRNA mat_rna_ptr = RNA_id_pointer_create(&b_mat.id);
1764 blender::PointerRNA cmat = RNA_pointer_get(&mat_rna_ptr, "cycles");
1765 shader->set_emission_sampling_method(get_emission_sampling(cmat));
1766 shader->set_use_transparent_shadow(b_mat.blend_flag & blender::MA_BL_TRANSPARENT_SHADOW);
1767 shader->set_use_bump_map_correction(get_boolean(cmat, "use_bump_map_correction"));
1768 shader->set_volume_sampling_method(get_volume_sampling(cmat));
1769 shader->set_volume_interpolation_method(get_volume_interpolation(cmat));
1770 shader->set_volume_step_rate(get_float(cmat, "volume_step_rate"));
1771 shader->set_displacement_method(get_displacement_method(b_mat));
1772
1773 shader->set_graph(std::move(graph));
1774
1775 /* By simplifying the shader graph as soon as possible, some
1776 * redundant shader nodes might be removed which prevents loading
1777 * unnecessary attributes later.
1778 *
1779 * However, since graph simplification also accounts for mix
1780 * weight, this would cause frequent expensive resyncs in interactive
1781 * sessions, so for those sessions optimization is only performed
1782 * right before compiling.
1783 */
1784 if (!preview) {
1785 pool.push([graph = shader->graph.get(), scene = scene] { graph->simplify(scene); });
1786 /* NOTE: Update shaders out of the threads since those routines
1787 * are accessing and writing to a global context.
1788 */
1789 updated_shaders.insert(shader);
1790 }
1791 else {
1792 /* NOTE: Update tagging can access links which are being
1793 * optimized out.
1794 */
1795 shader->tag_update(scene);
1796 }
1797 }
1798 }
1799 ITER_END;
1800
1801 pool.wait_work();
1802
1803 /* Info on the new AOVs becomes info on the old AOVs. */
1804 shader_view_layer_aovs = std::move(new_shader_view_layer_aovs);
1805
1806 for (Shader *shader : updated_shaders) {
1807 shader->tag_update(scene);
1808 }
1809}
1810
1811/* Sync World */
1812
1813void BlenderSync::sync_world(blender::Depsgraph &b_depsgraph,
1814 blender::bScreen *b_screen,
1815 blender::View3D *b_v3d,
1816 bool update_all,
1817 bool update_time)
1818{
1819 Background *background = scene->background;
1820 Integrator *integrator = scene->integrator;
1821 blender::PointerRNA scene_rna_ptr = RNA_id_pointer_create(&b_scene->id);
1822 blender::PointerRNA cscene = RNA_pointer_get(&scene_rna_ptr, "cycles");
1823
1824 blender::World *b_world = view_layer.world_override ? view_layer.world_override : b_scene->world;
1825
1826 const BlenderViewportParameters new_viewport_parameters(b_screen, b_v3d, use_developer_ui);
1827
1828 Shader *shader = scene->default_background;
1829
1830 if (world_recalc || update_all || b_world != world_map ||
1831 viewport_parameters.shader_modified(new_viewport_parameters) ||
1832 scene_attr_needs_recalc(shader, b_depsgraph) || (shader->has_time_dependency && update_time))
1833 {
1834 unique_ptr<ShaderGraph> graph = make_unique<ShaderGraph>();
1835
1836 /* create nodes */
1837 if (new_viewport_parameters.use_scene_world && b_world && b_world->nodetree) {
1838 add_nodes(scene, *b_engine, *b_data, *b_scene, b_depsgraph, graph.get(), *b_world->nodetree);
1839
1840 /* volume */
1841 blender::PointerRNA world_rna_ptr = RNA_id_pointer_create(&b_world->id);
1842 blender::PointerRNA cworld = RNA_pointer_get(&world_rna_ptr, "cycles");
1843 shader->set_volume_sampling_method(get_volume_sampling(cworld));
1844 shader->set_volume_interpolation_method(get_volume_interpolation(cworld));
1845 shader->set_volume_step_rate(get_float(cworld, "volume_step_size"));
1846 }
1847 else if (new_viewport_parameters.use_scene_world && b_world) {
1848 BackgroundNode *background = graph->create_node<BackgroundNode>();
1849 background->set_color(make_float3(b_world->horr, b_world->horg, b_world->horb));
1850
1851 ShaderNode *out = graph->output();
1852 graph->connect(background->output("Background"), out->input("Surface"));
1853 }
1854 else if (!new_viewport_parameters.use_scene_world) {
1855 float3 world_color;
1856 if (b_world) {
1857 world_color = make_float3(b_world->horr, b_world->horg, b_world->horb);
1858 }
1859 else {
1860 world_color = zero_float3();
1861 }
1862
1863 BackgroundNode *background = graph->create_node<BackgroundNode>();
1864 LightPathNode *light_path = graph->create_node<LightPathNode>();
1865
1866 MixNode *mix_scene_with_background = graph->create_node<MixNode>();
1867 mix_scene_with_background->set_color2(world_color);
1868
1869 EnvironmentTextureNode *texture_environment = graph->create_node<EnvironmentTextureNode>();
1870 texture_environment->set_tex_mapping_type(TextureMapping::VECTOR);
1871 float3 rotation_z = texture_environment->get_tex_mapping_rotation();
1872 rotation_z[2] = new_viewport_parameters.studiolight_rotate_z;
1873 texture_environment->set_tex_mapping_rotation(rotation_z);
1874 texture_environment->set_filename(new_viewport_parameters.studiolight_path);
1875
1876 MixNode *mix_intensity = graph->create_node<MixNode>();
1877 mix_intensity->set_mix_type(NODE_MIX_MUL);
1878 mix_intensity->set_fac(1.0f);
1879 mix_intensity->set_color2(make_float3(new_viewport_parameters.studiolight_intensity,
1880 new_viewport_parameters.studiolight_intensity,
1881 new_viewport_parameters.studiolight_intensity));
1882
1883 TextureCoordinateNode *texture_coordinate = graph->create_node<TextureCoordinateNode>();
1884
1885 MixNode *mix_background_with_environment = graph->create_node<MixNode>();
1886 mix_background_with_environment->set_fac(
1887 new_viewport_parameters.studiolight_background_alpha);
1888 mix_background_with_environment->set_color1(world_color);
1889
1890 ShaderNode *out = graph->output();
1891
1892 graph->connect(texture_coordinate->output("Generated"),
1893 texture_environment->input("Vector"));
1894 graph->connect(texture_environment->output("Color"), mix_intensity->input("Color1"));
1895 graph->connect(light_path->output("Is Camera Ray"), mix_scene_with_background->input("Fac"));
1896 graph->connect(mix_intensity->output("Color"), mix_scene_with_background->input("Color1"));
1897 graph->connect(mix_intensity->output("Color"),
1898 mix_background_with_environment->input("Color2"));
1899 graph->connect(mix_background_with_environment->output("Color"),
1900 mix_scene_with_background->input("Color2"));
1901 graph->connect(mix_scene_with_background->output("Color"), background->input("Color"));
1902 graph->connect(background->output("Background"), out->input("Surface"));
1903 }
1904
1905 /* Visibility */
1906 if (b_world) {
1907 blender::PointerRNA world_rna_ptr = RNA_id_pointer_create(&b_world->id);
1908 blender::PointerRNA cvisibility = RNA_pointer_get(&world_rna_ptr, "cycles_visibility");
1910
1911 visibility |= get_boolean(cvisibility, "camera") ? PATH_RAY_VISIBILITY_CAMERA :
1913 visibility |= get_boolean(cvisibility, "diffuse") ? PATH_RAY_VISIBILITY_DIFFUSE :
1915 visibility |= get_boolean(cvisibility, "glossy") ? PATH_RAY_VISIBILITY_GLOSSY :
1917 visibility |= get_boolean(cvisibility, "transmission") ? PATH_RAY_VISIBILITY_TRANSMIT :
1919 visibility |= get_boolean(cvisibility, "scatter") ? PATH_RAY_VISIBILITY_VOLUME_SCATTER :
1921
1922 background->set_visibility(visibility);
1923 }
1924
1925 resolve_view_layer_attributes(shader, graph.get(), b_depsgraph);
1926
1927 shader->set_graph(std::move(graph));
1928 shader->tag_update(scene);
1929 }
1930
1931 /* Fast GI */
1932 if (b_world) {
1933 enum { FAST_GI_METHOD_REPLACE = 0, FAST_GI_METHOD_ADD = 1, FAST_GI_METHOD_NUM };
1934
1935 const bool use_fast_gi = get_boolean(cscene, "use_fast_gi");
1936 if (use_fast_gi) {
1937 const int fast_gi_method = get_enum(
1938 cscene, "fast_gi_method", FAST_GI_METHOD_NUM, FAST_GI_METHOD_REPLACE);
1939 integrator->set_ao_factor((fast_gi_method == FAST_GI_METHOD_REPLACE) ? b_world->aoenergy :
1940 0.0f);
1941 integrator->set_ao_additive_factor(
1942 (fast_gi_method == FAST_GI_METHOD_ADD) ? b_world->aoenergy : 0.0f);
1943 }
1944 else {
1945 integrator->set_ao_factor(0.0f);
1946 integrator->set_ao_additive_factor(0.0f);
1947 }
1948
1949 integrator->set_ao_distance(b_world->aodist);
1950 }
1951 else {
1952 integrator->set_ao_factor(0.0f);
1953 integrator->set_ao_additive_factor(0.0f);
1954 integrator->set_ao_distance(10.0f);
1955 }
1956
1957 background->set_transparent((b_scene->r.alphamode & blender::R_ALPHAPREMUL) != 0);
1958
1959 if (background->get_transparent()) {
1960 background->set_transparent_glass(get_boolean(cscene, "film_transparent_glass"));
1961 background->set_transparent_roughness_threshold(
1962 get_float(cscene, "film_transparent_roughness"));
1963 }
1964 else {
1965 background->set_transparent_glass(false);
1966 background->set_transparent_roughness_threshold(0.0f);
1967 }
1968
1969 background->set_use_shader(view_layer.use_background_shader ||
1970 viewport_parameters.use_custom_shader());
1971
1972 background->set_lightgroup(
1973 ustring((b_world && b_world->lightgroup) ? b_world->lightgroup->name : ""));
1974
1975 background->tag_update(scene);
1976}
1977
1978/* Sync Lights */
1979
1980void BlenderSync::sync_lights(blender::Depsgraph &b_depsgraph, bool update_all, bool update_time)
1981{
1982 shader_map.set_default(scene->default_light);
1983
1984 blender::DEGIDIterData data{};
1985 data.graph = &b_depsgraph;
1989 &data,
1990 blender::ID *,
1991 b_id)
1992 {
1993 if (b_id->id_type() != blender::ID_LA) {
1994 continue;
1995 }
1996
1997 blender::Light &b_light = blender::id_cast<blender::Light &>(*b_id);
1998 Shader *shader;
1999
2000 /* test if we need to sync */
2001 if (shader_map.add_or_update(&shader, &b_light.id) || update_all ||
2002 scene_attr_needs_recalc(shader, b_depsgraph) ||
2003 (shader->has_time_dependency && update_time))
2004 {
2005 unique_ptr<ShaderGraph> graph = make_unique<ShaderGraph>();
2006
2007 /* create nodes */
2008 if (b_light.nodetree) {
2009 shader->name = BKE_id_name(b_light.id);
2010
2011 add_nodes(
2012 scene, *b_engine, *b_data, *b_scene, b_depsgraph, graph.get(), *b_light.nodetree);
2013 }
2014 else {
2015 EmissionNode *emission = graph->create_node<EmissionNode>();
2016 emission->set_color(one_float3());
2017 emission->set_strength(1.0f);
2018
2019 ShaderNode *out = graph->output();
2020 graph->connect(emission->output("Emission"), out->input("Surface"));
2021 }
2022
2023 resolve_view_layer_attributes(shader, graph.get(), b_depsgraph);
2024
2025 shader->set_graph(std::move(graph));
2026 shader->tag_update(scene);
2027 }
2028 }
2029 ITER_END;
2030}
2031
2032void BlenderSync::sync_shaders(blender::Depsgraph &b_depsgraph,
2033 blender::bScreen *b_screen,
2034 blender::View3D *b_v3d,
2035 bool update_all,
2036 bool update_time)
2037{
2038 shader_map.pre_sync();
2039
2040 sync_world(b_depsgraph, b_screen, b_v3d, update_all, update_time);
2041 sync_lights(b_depsgraph, update_all, update_time);
2042 sync_materials(b_depsgraph, update_all, update_time);
2043}
2044
#define ITER_END
#define ITER_BEGIN(callback_begin, callback_next, callback_end, _data_in, _type, _instance)
#define SHD_SHEEN_ASHIKHMIN
#define SHD_SHEEN_MICROFIBER
volatile int lock
static void store_shader_node_errors(blender::Depsgraph &b_depsgraph, const blender::Span< blender::nodes::InlineShaderNodeTreeParams::ErrorMessage > errors)
int blender_attribute_name_split_type(ustring name, string *r_real_name)
static const string_view view_layer_attr_prefix("\x01layer:")
static ustring get_node_input_string(const blender::bNode &b_node, const string &name)
static int validate_enum_value(const int value, const int num_values, const int default_value)
static ShaderInput * node_find_input_by_name(const blender::bNode &b_node, ShaderNode *node, blender::bNodeSocket &b_socket)
static void get_tex_mapping(TextureNode *mapping, const blender::TexMapping *b_mapping)
static void add_nodes_inlined(Scene *scene, blender::RenderEngine &b_engine, blender::Main &b_data, blender::Scene &b_scene, blender::Depsgraph &b_depsgraph, ShaderGraph *graph, blender::bNodeTree &b_ntree, const ProxyMap &proxy_input_map, const ProxyMap &proxy_output_map)
static bool node_use_modified_socket_name(ShaderNode *node)
static void raycast_add_output_attribute_sockets(RaycastNode *raycast, const blender::bNode &b_node)
static float3 get_node_output_rgba(blender::bNode &b_node, const string &name)
static VolumeInterpolation get_volume_interpolation(blender::PointerRNA &ptr)
static VolumeSampling get_volume_sampling(blender::PointerRNA &ptr)
static ShaderNode * add_node(Scene *scene, blender::RenderEngine &b_engine, blender::Main &b_data, blender::Scene &b_scene, ShaderGraph *graph, blender::bNodeTree &b_ntree, blender::bNode &b_node)
static EmissionSampling get_emission_sampling(blender::PointerRNA &ptr)
static float get_node_output_value(blender::bNode &b_node, const string &name)
static bool is_image_animated(blender::eImageSource b_image_source, blender::ImageUser &b_image_user)
static ImageAlphaType get_image_alpha_type(blender::Image &b_image)
static const string_view instancer_attr_prefix("\x01instancer:")
map< string, ConvertNode * > ProxyMap
static float3 get_node_output_vector(blender::bNode &b_node, const string &name)
static std::optional< RaycastNode::AttributeOutputType > raycast_get_attribute_output_type(const blender::eCustomDataType data_type)
static void set_default_value(ShaderInput *input, blender::bNodeSocket &b_sock, blender::Main &b_data, blender::ID &b_id)
static ShaderOutput * node_find_output_by_name(blender::bNode &b_node, ShaderNode *node, blender::bNodeSocket &b_socket)
static ustring blender_attribute_name_add_type(const string &name, int type)
static void add_nodes(Scene *scene, blender::RenderEngine &b_engine, blender::Main &b_data, blender::Scene &b_scene, blender::Depsgraph &b_depsgraph, ShaderGraph *graph, blender::bNodeTree &b_ntree, const ProxyMap &proxy_input_map, const ProxyMap &proxy_output_map)
static SocketType::Type convert_socket_type(const blender::bNodeSocket &b_socket)
unordered_multimap< void *, ShaderInput * > PtrInputMap
static DisplacementMethod get_displacement_method(blender::Material &b_mat)
static ExtensionType get_image_extension(NodeType &b_node)
static const string_view object_attr_prefix("\x01object:")
static InterpolationType get_image_interpolation(NodeType &b_node)
map< void *, ShaderOutput * > PtrOutputMap
#define BLI_assert(a)
#define output
SIMD_FORCE_INLINE btScalar norm() const
Return the norm (length) of the vector.
Definition btVector3.h:263
ImageParams image_params() const
Definition scene.h:133
unique_ptr< ShaderManager > shader_manager
Definition scene.h:169
unique_ptr< ImageManager > image_manager
Definition scene.h:166
OutputNode * output()
unique_ptr_vector< ShaderNode > nodes
T * create_node(Args &&...args)
void disconnect(ShaderOutput *from)
void connect(ShaderOutput *from, ShaderInput *to)
const SocketType & socket_type
ShaderNode * parent
SocketType::Type type() const
bool constant_folded_in
void set(const float f)
ShaderInput * input(const char *name)
unique_ptr_vector< ShaderInput > inputs
ShaderOutput * output(const char *name)
unique_ptr_vector< ShaderOutput > outputs
void set_graph(unique_ptr< ShaderGraph > &&graph)
bool has_time_dependency
void tag_update(Scene *scene)
NODE_DECLARE unique_ptr< ShaderGraph > graph
void tag_used(Scene *scene)
void push(TaskRunFunction &&task)
Definition task.cpp:21
void wait_work(Summary *stats=nullptr)
Definition task.cpp:27
void push_back_slow(const T &t)
void append(const T &value)
T * find(const K &key)
Definition id_map.h:42
#define RAMP_TABLE_SIZE
#define CCL_NAMESPACE_END
ccl_device_forceinline float3 make_float3(const float x, const float y, const float z)
#define storage(slot, qualifiers)
#define image(slot, qualifiers, format)
VecBase< float, D > normalize(VecOp< float, D >) RET
VecBase< float, 4 > float4
VecBase< float, 3 > float3
float noise(float p)
ccl_gpu_kernel_postfix ccl_global KernelWorkTile * tiles
NodeNormalMapBase
NodeVectorTransformType
NodeCombSepColorType
NodeVectorRotateType
NodeMapRangeType
NodeWaveType
@ CLOSURE_VOLUME_RAYLEIGH_ID
@ CLOSURE_BSDF_MICROFACET_GGX_REFRACTION_ID
@ CLOSURE_VOLUME_HENYEY_GREENSTEIN_ID
@ CLOSURE_VOLUME_MIE_ID
@ CLOSURE_BSDF_ASHIKHMIN_SHIRLEY_ID
@ CLOSURE_BSDF_MICROFACET_GGX_GLASS_ID
@ CLOSURE_BSSRDF_BURLEY_ID
@ CLOSURE_BSDF_SHEEN_ID
@ CLOSURE_BSDF_DIFFUSE_TOON_ID
@ CLOSURE_VOLUME_DRAINE_ID
@ CLOSURE_BSDF_MICROFACET_GGX_ID
@ CLOSURE_BSDF_MICROFACET_BECKMANN_REFRACTION_ID
@ CLOSURE_BSDF_MICROFACET_MULTI_GGX_ID
@ CLOSURE_BSDF_HAIR_TRANSMISSION_ID
@ CLOSURE_BSDF_MICROFACET_BECKMANN_GLASS_ID
@ CLOSURE_VOLUME_FOURNIER_FORAND_ID
@ CLOSURE_BSSRDF_RANDOM_WALK_ID
@ CLOSURE_BSDF_PHYSICAL_CONDUCTOR
@ CLOSURE_BSDF_MICROFACET_BECKMANN_ID
@ CLOSURE_BSDF_MICROFACET_MULTI_GGX_GLASS_ID
@ CLOSURE_BSDF_F82_CONDUCTOR
@ CLOSURE_BSSRDF_RANDOM_WALK_LEGACY_ID
@ CLOSURE_BSDF_GLOSSY_TOON_ID
@ CLOSURE_BSDF_HAIR_REFLECTION_ID
@ CLOSURE_BSSRDF_RANDOM_WALK_SKIN_ID
@ CLOSURE_BSDF_ASHIKHMIN_VELVET_ID
NodeBooleanMathType
NodeVoronoiFeature
NodeEnvironmentProjection
NodeGradientType
NodeMathType
NodeIntegerMathType
@ NODE_MIX_MUL
NodeSkyType
NodePrincipledHairModel
@ NODE_PRINCIPLED_HAIR_MODEL_NUM
@ NODE_PRINCIPLED_HAIR_HUANG
NodeWaveProfile
NodeVoronoiDistanceMetric
NodeTangentAxis
NodePrincipledHairParametrization
@ NODE_PRINCIPLED_HAIR_REFLECTANCE
@ NODE_PRINCIPLED_HAIR_PARAMETRIZATION_NUM
NodeNoiseType
NodeWaveBandsDirection
NodeGaborType
NodeNormalMapConvention
NodeTangentDirectionType
NodeVectorMathType
NodeClampType
NodeImageProjection
NodeWaveRingsDirection
NodeMappingType
NodeNormalMapSpace
NodeVectorTransformConvertSpace
uint32_t PathRayVisibility
@ PATH_RAY_VISIBILITY_VOLUME_SCATTER
@ PATH_RAY_VISIBILITY_CAMERA
@ PATH_RAY_VISIBILITY_TRANSMIT
@ PATH_RAY_VISIBILITY_DIFFUSE
@ PATH_RAY_VISIBILITY_NONE
@ PATH_RAY_VISIBILITY_GLOSSY
EmissionSampling
@ EMISSION_SAMPLING_NUM
@ EMISSION_SAMPLING_AUTO
#define LOG_DFATAL
Definition log.h:100
ccl_device_inline float3 one_float3()
Definition math_float3.h:26
CCL_NAMESPACE_BEGIN ccl_device_inline float3 zero_float3()
Definition math_float3.h:17
bNodeTree * node_tree_add_tree(Main *bmain, StringRef name, StringRef idname)
Definition node.cc:4992
bool inline_shader_node_tree(const bNodeTree &src_tree, bNodeTree &dst_tree, InlineShaderNodeTreeParams &params)
@ SHD_PHASE_HENYEY_GREENSTEIN
@ SHD_PHASE_FOURNIER_FORAND
void DEG_iterator_ids_end(BLI_Iterator *iter)
PointerRNA RNA_id_pointer_create(ID *id)
@ SHD_ATTRIBUTE_INSTANCER
@ SHD_ATTRIBUTE_VIEW_LAYER
@ SHD_ATTRIBUTE_GEOMETRY
@ SHD_ATTRIBUTE_OBJECT
const char * BKE_id_name(const ID &id)
@ SHD_PHYSICAL_CONDUCTOR
bool BKE_view_layer_find_rgba_attribute(const Scene *scene, const ViewLayer *layer, const char *name, float r_value[4])
BMesh const char void * data
void DEG_iterator_ids_next(BLI_Iterator *iter)
ViewLayer * DEG_get_evaluated_view_layer(const Depsgraph *graph)
@ SHD_HAIR_REFLECTION
@ SHD_HAIR_TRANSMISSION
PointerRNA RNA_pointer_get(PointerRNA *ptr, const char *name)
@ NODE_MIX_MODE_UNIFORM
@ SHD_SUBSURFACE_RANDOM_WALK_SKIN
@ SHD_SUBSURFACE_RANDOM_WALK
@ SHD_SUBSURFACE_BURLEY
@ SHD_SUBSURFACE_RANDOM_WALK_LEGACY
@ RE_ENGINE_PREVIEW
Definition RE_engine.h:64
void DEG_iterator_ids_begin(BLI_Iterator *iter, DEGIDIterData *data)
Scene * DEG_get_evaluated_scene(const Depsgraph *graph)
@ SHD_GLOSSY_ASHIKHMIN_SHIRLEY
@ SHD_GLOSSY_BECKMANN
@ SHD_GLOSSY_MULTI_GGX
@ CUMA_EXTEND_EXTRAPOLATE
void visibility(Visibility &srt, const ViewCulling &culling, const uint3 global_id, const uint3 local_id, const uint3 workgroup_id)
closure color scatter(string phase, float Anisotropy, float IOR, float Backscatter, float Alpha, float Diameter)
#define mix
VolumeInterpolation
@ VOLUME_NUM_INTERPOLATION
@ VOLUME_INTERPOLATION_LINEAR
DisplacementMethod
@ DISPLACE_NUM_METHODS
@ DISPLACE_BUMP
VolumeSampling
@ VOLUME_NUM_SAMPLING
@ VOLUME_SAMPLING_DISTANCE
@ SHADER_SPECIAL_TYPE_OSL
closure color sheen(normal N, float roughness)
Definition stdcycles.h:96
bool string_startswith(const string_view s, const string_view start)
Definition string.cpp:106
void string_replace(string &haystack, const string &needle, const string &other)
Definition string.cpp:147
bool string_endswith(const string_view s, const string_view end)
Definition string.cpp:122
void set_value(const SocketType &socket, const Node &other, const SocketType &other_socket)
ustring name
Definition graph/node.h:178
static bool is_float3(Type type)
char name[258]
Definition DNA_ID.h:433
eImageUser_Flag flag
struct RenderData r
eTexMapping_Type type
eViewLayerAOVFlag flag
eViewLayerAOVType type
ListBaseT< ViewLayerAOV > aovs
eNodeSocketDatatype type
float y
Definition sky_math.h:225
float z
Definition sky_math.h:225
float x
Definition sky_math.h:225
float w
Definition sky_math.h:225
ImageAlphaType
Definition types_image.h:61
@ IMAGE_ALPHA_NUM_TYPES
Definition types_image.h:68
@ IMAGE_ALPHA_AUTO
Definition types_image.h:66
InterpolationType
Definition types_image.h:24
@ INTERPOLATION_LINEAR
Definition types_image.h:26
@ INTERPOLATION_NUM_TYPES
Definition types_image.h:31
ExtensionType
Definition types_image.h:80
@ EXTENSION_REPEAT
Definition types_image.h:82
@ EXTENSION_NUM_TYPES
Definition types_image.h:90