Blender V5.3
node_tree_update.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include <fmt/format.h>
10
11#include "BLI_listbase.hh"
12#include "BLI_map.hh"
14#include "BLI_noise.hh"
15#include "BLI_rand.hh"
16#include "BLI_set.hh"
17#include "BLI_stack.hh"
18#include "BLI_string.hh"
20#include "BLI_vector_set.hh"
21
22#include "DNA_anim_types.h"
23#include "DNA_modifier_types.h"
24#include "DNA_node_types.h"
25#include "DNA_sequence_types.h"
26
27#include "BKE_anim_data.hh"
28#include "BKE_compositor.hh"
29#include "BKE_image.hh"
30#include "BKE_lib_id.hh"
31#include "BKE_library.hh"
32#include "BKE_main.hh"
33#include "BKE_node.hh"
34#include "BKE_node_enum.hh"
36#include "BKE_node_runtime.hh"
39
40#include "MOD_nodes.hh"
41
43#include "NOD_dependencies.hh"
44#include "NOD_geo_viewer.hh"
50#include "NOD_shader.h"
51#include "NOD_socket.hh"
53#include "NOD_sync_sockets.hh"
54#include "NOD_texture.h"
55
57
58#include "BLT_translation.hh"
59
60#include "RNA_access.hh"
61#include "RNA_define.hh"
62
63#include "SEQ_effects.hh"
64#include "SEQ_iterator.hh"
65#include "SEQ_modifier.hh"
66#include "SEQ_sequencer.hh"
67
68#include "PRF_profile.hh"
69
70namespace blender {
71
72using namespace blender::nodes;
73
92
100
101static void add_node_tag(bNodeTree *ntree, bNode *node, const eNodeTreeChangedFlag flag)
102{
103 add_tree_tag(ntree, flag);
104 node->runtime->changed_flag |= flag;
105}
106
107static void add_socket_tag(bNodeTree *ntree, bNodeSocket *socket, const eNodeTreeChangedFlag flag)
108{
109 add_tree_tag(ntree, flag);
110 socket->runtime->changed_flag |= flag;
111}
112
113namespace bke {
114
122{
123 switch (to->type) {
124 case SOCK_RGBA:
125 switch (from->type) {
126 case SOCK_RGBA:
127 return 4;
128 case SOCK_FLOAT:
129 return 3;
130 case SOCK_INT:
131 return 2;
132 case SOCK_BOOLEAN:
133 return 1;
134 default:
135 return -1;
136 }
137 case SOCK_VECTOR:
138 switch (from->type) {
139 case SOCK_VECTOR:
140 return 4;
141 case SOCK_FLOAT:
142 return 3;
143 case SOCK_INT:
144 return 2;
145 case SOCK_BOOLEAN:
146 return 1;
147 default:
148 return -1;
149 }
150 case SOCK_FLOAT:
151 switch (from->type) {
152 case SOCK_FLOAT:
153 return 5;
154 case SOCK_INT:
155 return 4;
156 case SOCK_BOOLEAN:
157 return 3;
158 case SOCK_RGBA:
159 return 2;
160 case SOCK_VECTOR:
161 return 1;
162 default:
163 return -1;
164 }
165 case SOCK_INT:
166 switch (from->type) {
167 case SOCK_INT:
168 return 5;
169 case SOCK_FLOAT:
170 return 4;
171 case SOCK_BOOLEAN:
172 return 3;
173 case SOCK_RGBA:
174 return 2;
175 case SOCK_VECTOR:
176 return 1;
177 default:
178 return -1;
179 }
180 case SOCK_BOOLEAN:
181 switch (from->type) {
182 case SOCK_BOOLEAN:
183 return 5;
184 case SOCK_INT:
185 return 4;
186 case SOCK_FLOAT:
187 return 3;
188 case SOCK_RGBA:
189 return 2;
190 case SOCK_VECTOR:
191 return 1;
192 default:
193 return -1;
194 }
195 case SOCK_ROTATION:
196 switch (from->type) {
197 case SOCK_ROTATION:
198 return 3;
199 case SOCK_VECTOR:
200 return 2;
201 case SOCK_FLOAT:
202 return 1;
203 default:
204 return -1;
205 }
206 default:
207 break;
208 }
209
210 /* The rest of the socket types only allow an internal link if both the input and output socket
211 * have the same type. If the sockets are custom, we check the idname instead. */
212 if (to->type == from->type && (to->type != SOCK_CUSTOM || to->idname == from->idname)) {
213 return 1;
214 }
215
216 return -1;
217}
218
219/* Check both the tree's own tags and the interface tags. */
220static bool is_tree_changed(const bNodeTree &tree)
221{
223 tree.tree_interface.requires_dependent_tree_updates();
224}
225
226using TreeNodePair = std::pair<bNodeTree *, bNode *>;
227using ObjectModifierPair = std::pair<Object *, ModifierData *>;
228using NodeSocketPair = std::pair<bNode *, bNodeSocket *>;
229using StripModifierPair = std::pair<Scene *, StripModifierData *>;
230using StripEffectPair = std::pair<Scene *, Strip *>;
231using SceneCompositorEffectPair = std::pair<Scene *, SceneCompositorEffect *>;
232
238 private:
239 Main *bmain_;
240 std::optional<Vector<bNodeTree *>> all_trees_;
241 std::optional<MultiValueMap<bNodeTree *, TreeNodePair>> group_node_users_;
242 std::optional<MultiValueMap<bNodeTree *, ObjectModifierPair>> modifiers_users_;
243 std::optional<MultiValueMap<bNodeTree *, StripModifierPair>> strip_modifier_users_;
244 std::optional<MultiValueMap<bNodeTree *, StripEffectPair>> strip_effect_users_;
245 std::optional<MultiValueMap<bNodeTree *, SceneCompositorEffectPair>>
246 scene_compositor_effects_users_;
247
248 public:
249 NodeTreeRelations(Main *bmain) : bmain_(bmain) {}
250
252 {
253 if (all_trees_.has_value()) {
254 return;
255 }
256 all_trees_.emplace();
257 if (bmain_ == nullptr) {
258 return;
259 }
260
261 FOREACH_NODETREE_BEGIN (bmain_, ntree, id) {
262 all_trees_->append(ntree);
263 }
265 }
266
268 {
269 if (group_node_users_.has_value()) {
270 return;
271 }
272 group_node_users_.emplace();
273 if (bmain_ == nullptr) {
274 return;
275 }
276
277 this->ensure_all_trees();
278
279 for (bNodeTree *ntree : *all_trees_) {
280 for (bNode *node : ntree->all_nodes()) {
281 if (node->id == nullptr) {
282 continue;
283 }
284 ID *id = node->id;
285 if (GS(id->name) == ID_NT) {
286 bNodeTree *group = id_cast<bNodeTree *>(id);
287 group_node_users_->add(group, {ntree, node});
288 }
289 }
290 }
291 }
292
294 {
295 if (modifiers_users_.has_value()) {
296 return;
297 }
298 modifiers_users_.emplace();
299 if (bmain_ == nullptr) {
300 return;
301 }
302
303 for (Object &object : bmain_->objects) {
304 for (ModifierData &md : object.modifiers) {
305 if (md.type == eModifierType_Nodes) {
306 NodesModifierData *nmd = reinterpret_cast<NodesModifierData *>(&md);
307 if (nmd->node_group && !ID_MISSING(nmd->node_group)) {
308 modifiers_users_->add(nmd->node_group, {&object, &md});
309 }
310 }
311 }
312 }
313 }
314
316 {
317 if (strip_modifier_users_.has_value() || strip_effect_users_.has_value()) {
318 return;
319 }
320 strip_modifier_users_.emplace();
321 strip_effect_users_.emplace();
322 if (bmain_ == nullptr) {
323 return;
324 }
325
326 for (Scene &scene : bmain_->scenes) {
327 Editing *ed = seq::editing_get(&scene);
328 if (!ed) {
329 continue;
330 }
331 for (Strip *strip : seq::query_all_strips_recursive(&ed->seqbase)) {
332 /* Compositor effects. */
333 if (strip->type == STRIP_TYPE_COMPOSITOR && strip->effectdata != nullptr) {
334 const auto *comp = static_cast<const CompositorEffectVars *>(strip->effectdata);
335 if (comp->node_group != nullptr && !ID_MISSING(comp->node_group)) {
336 strip_effect_users_->add(comp->node_group, {&scene, strip});
337 }
338 }
339
340 /* Compositor modifiers. */
341 for (StripModifierData &modifier : strip->modifiers) {
343 continue;
344 }
345 const SequencerCompositorModifierData *modifier_data =
346 reinterpret_cast<SequencerCompositorModifierData *>(&modifier);
347 if (modifier_data->node_group != nullptr && !ID_MISSING(modifier_data->node_group)) {
348 strip_modifier_users_->add(modifier_data->node_group, {&scene, &modifier});
349 }
350 }
351 }
352 }
353 }
354
356 {
357 if (scene_compositor_effects_users_.has_value()) {
358 return;
359 }
360 scene_compositor_effects_users_.emplace();
361 if (bmain_ == nullptr) {
362 return;
363 }
364
365 for (Scene &scene : bmain_->scenes) {
366 for (SceneCompositorEffect &effect : scene.compositor_effects) {
367 if (effect.node_group && !ID_MISSING(effect.node_group)) {
368 scene_compositor_effects_users_->add(effect.node_group, {&scene, &effect});
369 }
370 }
371 }
372 }
373
375 {
376 BLI_assert(modifiers_users_.has_value());
377 return modifiers_users_->lookup(ntree);
378 }
379
381 {
382 BLI_assert(strip_modifier_users_.has_value());
383 return strip_modifier_users_->lookup(ntree);
384 }
385
387 {
388 BLI_assert(strip_effect_users_.has_value());
389 return strip_effect_users_->lookup(ntree);
390 }
391
393 {
394 BLI_assert(scene_compositor_effects_users_.has_value());
395 return scene_compositor_effects_users_->lookup(ntree);
396 }
397
399 {
400 BLI_assert(group_node_users_.has_value());
401 return group_node_users_->lookup(ntree);
402 }
403
405 {
406 this->ensure_all_trees();
407 return *all_trees_;
408 }
409};
410
413 None = 0u,
416 OtherOutput = 1u << 1,
417 ShaderToRGB = 1u << 2,
419};
421
423 bool interface_changed = false;
424 bool output_changed = false;
425};
426
428 private:
429 Main *bmain_;
430 const NodeTreeUpdateExtraParams &params_;
431 Map<bNodeTree *, TreeUpdateResult> update_result_by_tree_;
432 NodeTreeRelations relations_;
433 bool needs_relations_update_ = false;
434
435 public:
437 : bmain_(bmain), params_(params), relations_(bmain)
438 {
439 }
440
441 void update()
442 {
443 Vector<bNodeTree *> changed_ntrees;
444 FOREACH_NODETREE_BEGIN (bmain_, ntree, id) {
445 if (is_tree_changed(*ntree)) {
446 changed_ntrees.append(ntree);
447 }
448 }
450 this->update_rooted(changed_ntrees);
451 }
452
454 {
455 if (root_ntrees.is_empty()) {
456 return;
457 }
458 PRF_scope_with_name("NodeTreeMainUpdater::update_rooted", ProfileCategory::Core);
459
460 bool is_single_tree_update = false;
461
462 if (root_ntrees.size() == 1) {
463 bNodeTree *ntree = root_ntrees[0];
464 if (!is_tree_changed(*ntree)) {
465 return;
466 }
467 const TreeUpdateResult result = this->update_tree(*ntree);
468 update_result_by_tree_.add_new(ntree, result);
469 if (!result.interface_changed && !result.output_changed) {
470 is_single_tree_update = true;
471 }
472 }
473
474 if (!is_single_tree_update) {
475 Vector<bNodeTree *> ntrees_in_order = this->get_tree_update_order(root_ntrees);
476 for (bNodeTree *ntree : ntrees_in_order) {
477 if (!is_tree_changed(*ntree)) {
478 continue;
479 }
480 if (!update_result_by_tree_.contains(ntree)) {
481 const TreeUpdateResult result = this->update_tree(*ntree);
482 update_result_by_tree_.add_new(ntree, result);
483 }
484 const TreeUpdateResult result = update_result_by_tree_.lookup(ntree);
485 Span<TreeNodePair> dependent_trees = relations_.get_group_node_users(ntree);
486 if (result.output_changed) {
487 for (const TreeNodePair &pair : dependent_trees) {
488 add_node_tag(pair.first, pair.second, NTREE_CHANGED_NODE_OUTPUT);
489 }
490 }
491 if (result.interface_changed) {
492 for (const TreeNodePair &pair : dependent_trees) {
493 add_node_tag(pair.first, pair.second, NTREE_CHANGED_NODE_PROPERTY);
494 }
495 }
496 }
497 }
498
499 for (const auto item : update_result_by_tree_.items()) {
500 bNodeTree *ntree = item.key;
501 const TreeUpdateResult &result = item.value;
502
503 this->reset_changed_flags(*ntree);
504
505 if (result.interface_changed) {
506 if (ntree->type == NTREE_GEOMETRY) {
507 relations_.ensure_modifier_users();
508 for (const ObjectModifierPair &pair : relations_.get_modifier_users(ntree)) {
509 Object *object = pair.first;
510 ModifierData *md = pair.second;
511
512 if (md->type == eModifierType_Nodes) {
514 *bmain_, object, reinterpret_cast<NodesModifierData *>(md));
515 }
516 }
517 }
518 if (ntree->type == NTREE_COMPOSIT) {
519 relations_.ensure_strip_users();
520 for (const StripModifierPair &pair : relations_.get_strip_modifier_users(ntree)) {
521 Scene *scene = pair.first;
522 StripModifierData *md = pair.second;
523
526 *bmain_, *scene, *reinterpret_cast<SequencerCompositorModifierData *>(md));
527 }
528 }
529
530 for (const StripEffectPair &pair : relations_.get_compositor_effect_users(ntree)) {
531 seq::compositor_effect_nodes_update_interface(*bmain_, *pair.first, *pair.second);
532 }
533
534 relations_.ensure_scene_compositor_effects_users();
535 for (const SceneCompositorEffectPair &pair :
536 relations_.get_scene_compositor_effects_users(ntree))
537 {
538 compositor::update_effect_node_group_interface(*bmain_, *pair.first, *pair.second);
539 }
540 }
541 }
542
543 if (result.output_changed) {
545 }
546
547 ID *owner_id = BKE_id_owner_get(&ntree->id);
548 ID &owner_or_self_id = owner_id ? *owner_id : ntree->id;
549 if (params_.tree_changed_fn) {
550 params_.tree_changed_fn(*ntree, owner_or_self_id);
551 }
552 if (params_.tree_output_changed_fn && result.output_changed) {
553 params_.tree_output_changed_fn(*ntree, owner_or_self_id);
554 }
555 }
556
557 if (needs_relations_update_) {
558 if (bmain_) {
560 }
561 }
562 if (bmain_) {
564 }
565 }
566
567 private:
568 enum class ToposortMark {
569 None,
570 Temporary,
571 Permanent,
572 };
573
574 using ToposortMarkMap = Map<bNodeTree *, ToposortMark>;
575
580 Vector<bNodeTree *> get_tree_update_order(Span<bNodeTree *> root_ntrees)
581 {
582 relations_.ensure_group_node_users();
583
584 Set<bNodeTree *> trees_to_update = get_trees_to_update(root_ntrees);
585
586 Vector<bNodeTree *> sorted_ntrees;
587
588 ToposortMarkMap marks;
589 for (bNodeTree *ntree : trees_to_update) {
590 marks.add_new(ntree, ToposortMark::None);
591 }
592 for (bNodeTree *ntree : trees_to_update) {
593 if (marks.lookup(ntree) == ToposortMark::None) {
594 const bool cycle_detected = !this->get_tree_update_order__visit_recursive(
595 ntree, marks, sorted_ntrees);
596 /* This should be prevented by higher level operators. */
597 BLI_assert(!cycle_detected);
598 UNUSED_VARS_NDEBUG(cycle_detected);
599 }
600 }
601
602 std::reverse(sorted_ntrees.begin(), sorted_ntrees.end());
603
604 return sorted_ntrees;
605 }
606
607 bool get_tree_update_order__visit_recursive(bNodeTree *ntree,
608 ToposortMarkMap &marks,
609 Vector<bNodeTree *> &sorted_ntrees)
610 {
611 ToposortMark &mark = marks.lookup(ntree);
612 if (mark == ToposortMark::Permanent) {
613 return true;
614 }
615 if (mark == ToposortMark::Temporary) {
616 /* There is a dependency cycle. */
617 return false;
618 }
619
620 mark = ToposortMark::Temporary;
621
622 for (const TreeNodePair &pair : relations_.get_group_node_users(ntree)) {
623 this->get_tree_update_order__visit_recursive(pair.first, marks, sorted_ntrees);
624 }
625 sorted_ntrees.append(ntree);
626
627 mark = ToposortMark::Permanent;
628 return true;
629 }
630
631 Set<bNodeTree *> get_trees_to_update(Span<bNodeTree *> root_ntrees)
632 {
633 relations_.ensure_group_node_users();
634
635 Set<bNodeTree *> reachable_trees;
636 Stack<bNodeTree *> trees_to_check = root_ntrees;
637
638 while (!trees_to_check.is_empty()) {
639 bNodeTree *ntree = trees_to_check.pop();
640 if (reachable_trees.add(ntree)) {
641 for (const TreeNodePair &pair : relations_.get_group_node_users(ntree)) {
642 trees_to_check.push(pair.first);
643 }
644 }
645 }
646
647 return reachable_trees;
648 }
649
650 TreeUpdateResult update_tree(bNodeTree &ntree)
651 {
652 PRF_scope_with_name("NodeTreeMainUpdater::update_tree", ProfileCategory::Core);
653 TreeUpdateResult result;
654
655 ntree.runtime->link_errors.clear();
657 ntree.runtime->shader_node_errors.clear();
658
660 result.interface_changed = true;
661 result.output_changed = true;
662 }
663
664 if (this->update_panel_toggle_names(ntree)) {
665 result.interface_changed = true;
666 }
667
668 this->update_socket_link_and_use(ntree);
669 this->update_individual_nodes(ntree);
670 this->update_internal_links(ntree);
671 this->update_generic_callback(ntree);
672 this->make_node_previews_dirty(ntree);
673
674 this->propagate_runtime_flags(ntree);
676 if (this->propagate_enum_definitions(ntree)) {
677 result.interface_changed = true;
678 }
679 }
680
681 if (ELEM(ntree.type, NTREE_GEOMETRY, NTREE_COMPOSIT)) {
683 result.interface_changed = true;
684 }
685 }
686
687 if (ntree.type == NTREE_GEOMETRY) {
688 this->update_from_field_inference(ntree);
690 result.interface_changed = true;
691 }
693 result.interface_changed = true;
694 }
695 }
696
697 if (ELEM(ntree.type, NTREE_GEOMETRY, NTREE_COMPOSIT)) {
698 this->update_socket_shapes(ntree);
699 }
700
701 if (ELEM(ntree.type, NTREE_GEOMETRY, NTREE_COMPOSIT)) {
702 this->update_eval_dependencies(ntree);
703 }
704
705 result.output_changed = this->check_if_output_changed(ntree);
706
707 this->update_socket_link_and_use(ntree);
708 this->update_link_validation(ntree);
709
710 if (this->update_nested_node_refs(ntree)) {
711 result.interface_changed = true;
712 }
713
714 if (ntree.type == NTREE_TEXTURE) {
715 ntreeTexCheckCyclics(&ntree);
716 }
717
718 if (ntree.tree_interface.requires_dependent_tree_updates()) {
719 result.interface_changed = true;
720 }
721
722 if (result.interface_changed) {
723 if (ntree.type == NTREE_GEOMETRY) {
725 ntree);
726 }
727 else if (ntree.type == NTREE_COMPOSIT) {
734 }
735 }
736
737#ifndef NDEBUG
738 /* Check the uniqueness of node identifiers. */
739 Set<int32_t> node_identifiers;
740 const Span<const bNode *> nodes = ntree.all_nodes();
741 for (const int i : nodes.index_range()) {
742 const bNode &node = *nodes[i];
743 BLI_assert(node.identifier > 0);
744 node_identifiers.add_new(node.identifier);
745 BLI_assert(node.runtime->index_in_tree == i);
746 }
747#endif
748
749 return result;
750 }
751
752 void update_socket_link_and_use(bNodeTree &tree)
753 {
754 tree.ensure_topology_cache();
755 for (bNodeSocket *socket : tree.all_input_sockets()) {
756 if (socket->directly_linked_links().is_empty()) {
757 socket->link = nullptr;
758 }
759 else {
760 socket->link = socket->directly_linked_links()[0];
761 }
762 }
763
764 this->update_socket_used_tags(tree);
765 }
766
767 void update_socket_used_tags(bNodeTree &tree)
768 {
769 tree.ensure_topology_cache();
770 for (bNodeSocket *socket : tree.all_sockets()) {
771 const bool socket_is_linked = !socket->directly_linked_links().is_empty();
772 SET_FLAG_FROM_TEST(socket->flag, socket_is_linked, SOCK_IS_LINKED);
773 }
774 }
775
776 void update_individual_nodes(bNodeTree &ntree)
777 {
778 for (bNode *node : ntree.all_nodes()) {
780 if (this->should_update_individual_node(ntree, *node)) {
781 bke::bNodeType &ntype = *node->typeinfo;
782 if (ntype.type_legacy == GEO_NODE_VIEWER) {
783 this->remove_unused_geometry_nodes_viewer_sockets(ntree, *node);
784 }
785 if (ntype.declare) {
786 /* Should have been created when the node was registered. */
787 BLI_assert(ntype.static_declaration != nullptr);
790 }
791 }
792 else if (node->is_undefined()) {
793 /* If a node has become undefined (it generally was unregistered from Python), it does
794 * not have a declaration anymore. */
795 delete node->runtime->declaration;
796 node->runtime->declaration = nullptr;
797 for (bNodeSocket &socket : node->inputs) {
798 socket.runtime->declaration = nullptr;
799 }
800 for (bNodeSocket &socket : node->outputs) {
801 socket.runtime->declaration = nullptr;
802 }
803 }
804 if (ntype.updatefunc) {
805 ntype.updatefunc(&ntree, node);
806 }
807 }
808 }
809 }
810
811 bool should_update_individual_node(const bNodeTree &ntree, const bNode &node)
812 {
814 return true;
815 }
816 if (node.runtime->changed_flag & NTREE_CHANGED_NODE_PROPERTY) {
817 return true;
818 }
820 /* Currently we have no way to tell if a node needs to be updated when a link changed. */
821 return true;
822 }
823 if (ntree.tree_interface.requires_dependent_tree_updates()) {
824 if (node.is_group_input() || node.is_group_output()) {
825 return true;
826 }
827 }
828 /* Check paired simulation zone nodes. */
829 if (all_zone_input_node_types().contains(node.type_legacy)) {
830 const bNodeZoneType &zone_type = *zone_type_by_node_type(node.type_legacy);
831 if (const bNode *output_node = zone_type.get_corresponding_output(ntree, node)) {
832 if (output_node->runtime->changed_flag & NTREE_CHANGED_NODE_PROPERTY) {
833 return true;
834 }
835 }
836 }
837 return false;
838 }
839
840 void remove_unused_geometry_nodes_viewer_sockets(bNodeTree &ntree, bNode &viewer_node)
841 {
842 ntree.ensure_topology_cache();
843 Vector<int> item_indices_to_remove;
844 auto &storage = *static_cast<NodeGeometryViewer *>(viewer_node.storage);
845 for (const int i : IndexRange(storage.items_num)) {
846 const NodeGeometryViewerItem &item = storage.items[i];
848 continue;
849 }
850 const std::string identifier_str = GeoViewerItemsAccessor::socket_identifier_for_item(item);
851 const bNodeSocket *socket = viewer_node.input_by_identifier(UString(identifier_str));
852 if (!socket) {
853 continue;
854 }
855 if (!socket->is_directly_linked()) {
856 item_indices_to_remove.append(i);
857 }
858 }
859 std::reverse(item_indices_to_remove.begin(), item_indices_to_remove.end());
860 for (const int i : item_indices_to_remove) {
862 &storage.items_num,
863 &storage.active_index,
864 i,
866 }
867 }
868
869 void update_internal_links(bNodeTree &ntree)
870 {
871 bke::node_tree_runtime::AllowUsingOutdatedInfo allow_outdated_info{ntree};
872 ntree.ensure_topology_cache();
873 for (bNode *node : ntree.all_nodes()) {
874 if (!this->should_update_individual_node(ntree, *node)) {
875 continue;
876 }
877 /* Find all expected internal links. */
878 Vector<bNodeInternalLink> expected_internal_links;
879 for (const bNodeSocket *output_socket : node->output_sockets()) {
880 if (!output_socket->is_available()) {
881 continue;
882 }
883 if (output_socket->runtime->declaration &&
884 output_socket->runtime->declaration->no_mute_links)
885 {
886 continue;
887 }
888 const bNodeSocket *input_socket = this->find_internally_linked_input(ntree, output_socket);
889 if (input_socket == nullptr) {
890 continue;
891 }
892
893 expected_internal_links.append(bNodeInternalLink{
894 const_cast<bNodeSocket *>(input_socket), const_cast<bNodeSocket *>(output_socket)});
895 }
896
897 /* Rebuilt internal links if they have changed. */
898 if (node->runtime->internal_links.size() != expected_internal_links.size()) {
899 this->update_internal_links_in_node(ntree, *node, expected_internal_links);
900 continue;
901 }
902
903 const bool all_expected_internal_links_exist = std::all_of(
904 node->runtime->internal_links.begin(),
905 node->runtime->internal_links.end(),
906 [&](const bNodeInternalLink &link) {
907 return expected_internal_links.as_span().contains(link);
908 });
909
910 if (all_expected_internal_links_exist) {
911 continue;
912 }
913
914 this->update_internal_links_in_node(ntree, *node, expected_internal_links);
915 }
916 }
917
918 const bNodeSocket *find_internally_linked_input(const bNodeTree &ntree,
919 const bNodeSocket *output_socket)
920 {
921 const bNode &node = output_socket->owner_node();
922 if (node.typeinfo->internally_linked_input) {
923 return node.typeinfo->internally_linked_input(ntree, node, *output_socket);
924 }
925
926 const bNodeSocket *selected_socket = nullptr;
927 int selected_priority = -1;
928 bool selected_is_linked = false;
929 for (const bNodeSocket *input_socket : node.input_sockets()) {
930 if (!input_socket->is_available()) {
931 continue;
932 }
933 if (input_socket->runtime->declaration && input_socket->runtime->declaration->no_mute_links)
934 {
935 continue;
936 }
937 const int priority = get_internal_link_type_priority(input_socket->typeinfo,
938 output_socket->typeinfo);
939 if (priority < 0) {
940 continue;
941 }
942 const bool is_linked = input_socket->is_directly_linked();
943 const bool is_preferred = priority > selected_priority || (is_linked && !selected_is_linked);
944 if (!is_preferred) {
945 continue;
946 }
947 selected_socket = input_socket;
948 selected_priority = priority;
949 selected_is_linked = is_linked;
950 }
951 return selected_socket;
952 }
953
954 void update_internal_links_in_node(bNodeTree &ntree,
955 bNode &node,
956 Span<bNodeInternalLink> internal_links)
957 {
958 node.runtime->internal_links.clear();
959 node.runtime->internal_links.extend(internal_links);
961 }
962
963 void update_generic_callback(bNodeTree &ntree)
964 {
965 if (ntree.typeinfo->update == nullptr) {
966 return;
967 }
968 ntree.typeinfo->update(&ntree);
969 }
970
971 void make_node_previews_dirty(bNodeTree &ntree)
972 {
974 for (bNode *node : ntree.all_nodes()) {
975 if (!node->is_group()) {
976 continue;
977 }
978 if (bNodeTree *nested_tree = reinterpret_cast<bNodeTree *>(node->id)) {
979 this->make_node_previews_dirty(*nested_tree);
980 }
981 }
982 }
983
984 void propagate_runtime_flags(const bNodeTree &ntree)
985 {
986 ntree.ensure_topology_cache();
987
988 ntree.runtime->runtime_flag = 0;
989
990 for (const bNode *group_node : ntree.group_nodes()) {
991 const bNodeTree *group = reinterpret_cast<bNodeTree *>(group_node->id);
992 if (group != nullptr) {
993 ntree.runtime->runtime_flag |= group->runtime->runtime_flag;
994 }
995 }
996
997 if (ntree.type == NTREE_SHADER) {
998 /* Check if the tree itself has an animated image. */
999 for (const UString idname : {"ShaderNodeTexImage"_ustr, "ShaderNodeTexEnvironment"_ustr}) {
1000 for (const bNode *node : ntree.nodes_by_type(idname)) {
1001 Image *image = reinterpret_cast<Image *>(node->id);
1002 if (image != nullptr && BKE_image_is_animated(image)) {
1004 break;
1005 }
1006 }
1007 }
1008 /* Check if the tree has a material output. */
1009 for (const UString idname : {"ShaderNodeOutputMaterial"_ustr,
1010 "ShaderNodeOutputLight"_ustr,
1011 "ShaderNodeOutputWorld"_ustr,
1012 "ShaderNodeOutputAOV"_ustr})
1013 {
1014 const Span<const bNode *> nodes = ntree.nodes_by_type(idname);
1015 if (!nodes.is_empty()) {
1017 break;
1018 }
1019 }
1020 }
1021 if (ntree.type == NTREE_GEOMETRY) {
1022 /* Check if there is a simulation zone. */
1023 if (!ntree.nodes_by_type("GeometryNodeSimulationOutput"_ustr).is_empty()) {
1025 }
1026 }
1027 }
1028
1029 void update_from_field_inference(bNodeTree &ntree)
1030 {
1031 /* Automatically tag a bake item as attribute when the input is a field. The flag should not be
1032 * removed automatically even when the field input is disconnected because the baked data may
1033 * still contain attribute data instead of a single value. */
1034 for (bNode *node : ntree.nodes_by_type("GeometryNodeBake"_ustr)) {
1035 NodeGeometryBake &storage = *static_cast<NodeGeometryBake *>(node->storage);
1036 for (const int i : IndexRange(storage.items_num)) {
1037 const bNodeSocket &socket = node->input_socket(i);
1038 NodeGeometryBakeItem &item = storage.items[i];
1039 if (socket.may_be_field()) {
1041 }
1042 }
1043 }
1044 }
1045
1046 static eNodeSocketDisplayShape get_socket_shape(const bNodeSocket &socket,
1047 const bool use_inferred_structure_type = false)
1048 {
1049 const SocketDeclaration *decl = socket.runtime->declaration;
1050 if (!decl) {
1052 }
1053 if (decl->identifier == "__extend__") {
1055 }
1056 const StructureType display_structure_type = use_inferred_structure_type ?
1058 decl->structure_type;
1059 switch (display_structure_type) {
1060 case StructureType::Single:
1062 case StructureType::Dynamic:
1064 case StructureType::Field:
1066 case StructureType::Grid:
1068 case StructureType::List:
1070 }
1073 }
1074
1075 void update_socket_shapes(bNodeTree &ntree)
1076 {
1077 ntree.ensure_topology_cache();
1078 for (bNode *node : ntree.all_nodes()) {
1079 if (node->is_undefined()) {
1080 continue;
1081 }
1082 const bke::bNodeZoneType *closure_zone_type = bke::zone_type_by_node_type(
1084 switch (node->type_legacy) {
1085 case NODE_REROUTE: {
1086 node->input_socket(0).display_shape = SOCK_DISPLAY_SHAPE_CIRCLE;
1087 node->output_socket(0).display_shape = SOCK_DISPLAY_SHAPE_CIRCLE;
1088 break;
1089 }
1090 case NODE_GROUP_OUTPUT:
1091 case NODE_GROUP_INPUT: {
1092 for (bNodeSocket *socket : node->input_sockets()) {
1093 socket->display_shape = get_socket_shape(*socket, true);
1094 }
1095 for (bNodeSocket *socket : node->output_sockets()) {
1096 socket->display_shape = get_socket_shape(*socket, true);
1097 }
1098 break;
1099 }
1100 case NODE_COMBINE_BUNDLE: {
1101 const auto &storage = *static_cast<const NodeCombineBundle *>(node->storage);
1102 for (const int i : IndexRange(storage.items_num)) {
1103 const NodeCombineBundleItem &item = storage.items[i];
1104 bNodeSocket &socket = node->input_socket(i);
1105 socket.display_shape = get_socket_shape(
1107 }
1108 break;
1109 }
1110 case NODE_SEPARATE_BUNDLE: {
1111 const auto &storage = *static_cast<const NodeSeparateBundle *>(node->storage);
1112 for (const int i : IndexRange(storage.items_num)) {
1113 const NodeSeparateBundleItem &item = storage.items[i];
1114 bNodeSocket &socket = node->output_socket(i);
1115 socket.display_shape = get_socket_shape(
1117 }
1118 break;
1119 }
1120 case NODE_CLOSURE_INPUT: {
1121 if (const bNode *closure_output_node = closure_zone_type->get_corresponding_output(
1122 ntree, *node))
1123 {
1124 const auto &storage = *static_cast<const NodeClosureOutput *>(
1125 closure_output_node->storage);
1126 for (const int i : IndexRange(storage.input_items.items_num)) {
1127 const NodeClosureInputItem &item = storage.input_items.items[i];
1128 bNodeSocket &socket = node->output_socket(i);
1129 socket.display_shape = get_socket_shape(
1131 }
1132 }
1133 break;
1134 }
1135 case NODE_CLOSURE_OUTPUT: {
1136 const auto &storage = *static_cast<const NodeClosureOutput *>(node->storage);
1137 for (const int i : IndexRange(storage.output_items.items_num)) {
1138 const NodeClosureOutputItem &item = storage.output_items.items[i];
1139 bNodeSocket &socket = node->input_socket(i);
1140 socket.display_shape = get_socket_shape(
1142 }
1143 break;
1144 }
1145 case NODE_EVALUATE_CLOSURE: {
1146 const auto &storage = *static_cast<const NodeEvaluateClosure *>(node->storage);
1147 for (const int i : IndexRange(storage.input_items.items_num)) {
1148 const NodeEvaluateClosureInputItem &item = storage.input_items.items[i];
1149 bNodeSocket &socket = node->input_socket(i + 1);
1150 socket.display_shape = get_socket_shape(
1152 }
1153 for (const int i : IndexRange(storage.output_items.items_num)) {
1154 const NodeEvaluateClosureOutputItem &item = storage.output_items.items[i];
1155 bNodeSocket &socket = node->output_socket(i);
1156 socket.display_shape = get_socket_shape(
1158 }
1159 break;
1160 }
1161 default: {
1162 /* For other nodes we just use the static structure types defined in the declaration. */
1163 for (bNodeSocket *socket : node->input_sockets()) {
1164 socket->display_shape = get_socket_shape(*socket);
1165 }
1166 for (bNodeSocket *socket : node->output_sockets()) {
1167 socket->display_shape = get_socket_shape(*socket);
1168 }
1169
1170 if (node->is_type("NodeGetBundleItem"_ustr)) {
1171 bNodeSocket &socket = *node->output_by_identifier("Item"_ustr);
1172 const auto &storage = *static_cast<const NodeGetBundleItem *>(node->storage);
1173 socket.display_shape = get_socket_shape(
1174 socket, storage.structure_type == NodeSocketInterfaceStructureType::Auto);
1175 }
1176 else if (node->is_type("NodeStoreBundleItem"_ustr)) {
1177 bNodeSocket &socket = *node->input_by_identifier("Item"_ustr);
1178 const auto &storage = *static_cast<const NodeStoreBundleItem *>(node->storage);
1179 socket.display_shape = get_socket_shape(
1180 socket, storage.structure_type == NodeSocketInterfaceStructureType::Auto);
1181 }
1182 break;
1183 }
1184 }
1185 }
1186 }
1187
1188 void update_eval_dependencies(bNodeTree &ntree)
1189 {
1190 ntree.ensure_topology_cache();
1191 nodes::EvalDependencies new_deps = nodes::gather_eval_dependencies_with_cache(ntree);
1192
1193 /* Check if the dependencies have changed. */
1194 if (!ntree.runtime->eval_dependencies || new_deps != *ntree.runtime->eval_dependencies) {
1195 needs_relations_update_ = true;
1196 ntree.runtime->eval_dependencies = std::make_unique<nodes::EvalDependencies>(
1197 std::move(new_deps));
1198 }
1199 }
1200
1201 bool propagate_enum_definitions(bNodeTree &ntree)
1202 {
1203 ntree.ensure_interface_cache();
1204
1205 /* Propagation from right to left to determine which enum
1206 * definition to use for menu sockets. */
1207 for (bNode *node : ntree.toposort_right_to_left()) {
1208 const bool node_updated = this->should_update_individual_node(ntree, *node);
1209
1210 Vector<bNodeSocket *> locally_defined_enums;
1211 if (node->is_type("GeometryNodeMenuSwitch"_ustr)) {
1212 bNodeSocket &enum_input = node->input_socket(0);
1213 BLI_assert(enum_input.is_available() && enum_input.type == SOCK_MENU);
1214 /* Generate new enum items when the node has changed, otherwise keep existing items. */
1215 if (node_updated) {
1216 const NodeMenuSwitch &storage = *static_cast<NodeMenuSwitch *>(node->storage);
1217 const RuntimeNodeEnumItems *enum_items = this->create_runtime_enum_items(
1218 storage.enum_definition);
1219
1220 this->set_enum_ptr(*enum_input.default_value_typed<bNodeSocketValueMenu>(), enum_items);
1221 /* Remove initial user. */
1222 enum_items->remove_user_and_delete_if_last();
1223 }
1224 locally_defined_enums.append(&enum_input);
1225 }
1226 else if (!node->is_group()) {
1227 /* Gather built-in menus defined by this node. */
1228 for (bNodeSocket *input_socket : node->input_sockets()) {
1229 if (!input_socket->is_available()) {
1230 continue;
1231 }
1232 if (input_socket->type != SOCK_MENU) {
1233 continue;
1234 }
1235 const auto *socket_decl = dynamic_cast<const nodes::decl::Menu *>(
1236 input_socket->runtime->declaration);
1237 if (!socket_decl) {
1238 continue;
1239 }
1240 this->set_enum_ptr(*input_socket->default_value_typed<bNodeSocketValueMenu>(),
1241 socket_decl->items.get());
1242 locally_defined_enums.append(input_socket);
1243 }
1244 }
1245
1246 /* Clear current enum references. */
1247 for (bNodeSocket *socket : node->input_sockets()) {
1248 if (socket->is_available() && socket->type == SOCK_MENU &&
1249 !locally_defined_enums.contains(socket))
1250 {
1251 clear_enum_reference(*socket);
1252 }
1253 }
1254 for (bNodeSocket *socket : node->output_sockets()) {
1255 if (socket->is_available() && socket->type == SOCK_MENU) {
1256 clear_enum_reference(*socket);
1257 }
1258 }
1259
1260 /* Propagate enum references from output links. */
1261 for (bNodeSocket *output : node->output_sockets()) {
1262 if (!output->is_available() || output->type != SOCK_MENU) {
1263 continue;
1264 }
1265 for (const bNodeSocket *input : output->directly_linked_sockets()) {
1266 if (!input->is_available() || input->type != SOCK_MENU) {
1267 continue;
1268 }
1269 this->update_socket_enum_definition(*output->default_value_typed<bNodeSocketValueMenu>(),
1270 *input->default_value_typed<bNodeSocketValueMenu>());
1271 }
1272 }
1273
1274 if (node->is_group()) {
1275 /* Node groups expose internal enum definitions. */
1276 if (node->id == nullptr) {
1277 continue;
1278 }
1279 const bNodeTree *group_tree = reinterpret_cast<bNodeTree *>(node->id);
1280 group_tree->ensure_interface_cache();
1281
1282 for (const int socket_i : group_tree->interface_inputs().index_range()) {
1283 bNodeSocket &input = *node->input_sockets()[socket_i];
1284 const bNodeTreeInterfaceSocket &iosocket = *group_tree->interface_inputs()[socket_i];
1285 BLI_assert(STREQ(input.identifier, iosocket.identifier));
1286 if (input.is_available() && input.type == SOCK_MENU) {
1287 BLI_assert(STREQ(iosocket.socket_type, "NodeSocketMenu"));
1288 this->update_socket_enum_definition(
1289 *input.default_value_typed<bNodeSocketValueMenu>(),
1290 *static_cast<bNodeSocketValueMenu *>(iosocket.socket_data));
1291 }
1292 }
1293 }
1294 else if (node->is_type("GeometryNodeMenuSwitch"_ustr)) {
1295 /* First input is always the node's own menu, propagate only to the enum case inputs. */
1296 const bNodeSocket *output = node->output_sockets().first();
1297 for (bNodeSocket *input : node->input_sockets().drop_front(1)) {
1298 if (input->is_available() && input->type == SOCK_MENU) {
1299 this->update_socket_enum_definition(
1300 *input->default_value_typed<bNodeSocketValueMenu>(),
1301 *output->default_value_typed<bNodeSocketValueMenu>());
1302 }
1303 }
1304 }
1305 else if (node->is_type("GeometryNodeForeachGeometryElementInput"_ustr)) {
1306 /* Propagate menu from element inputs to field inputs. */
1307 BLI_assert(node->input_sockets().size() == node->output_sockets().size());
1308 /* Inputs Geometry, Selection and outputs Index, Element are ignored. */
1309 const IndexRange sockets = node->input_sockets().index_range().drop_front(2);
1310 for (const int socket_i : sockets) {
1311 bNodeSocket *input = node->input_sockets()[socket_i];
1312 bNodeSocket *output = node->output_sockets()[socket_i];
1313 if (input->is_available() && input->type == SOCK_MENU && output->is_available() &&
1314 output->type == SOCK_MENU)
1315 {
1316 this->update_socket_enum_definition(
1317 *input->default_value_typed<bNodeSocketValueMenu>(),
1318 *output->default_value_typed<bNodeSocketValueMenu>());
1319 }
1320 }
1321 }
1322 else {
1323 /* Propagate over internal relations. */
1324 /* XXX Placeholder implementation just propagates all outputs
1325 * to all inputs for built-in nodes This could perhaps use
1326 * input/output relations to handle propagation generically? */
1327 for (bNodeSocket *input : node->input_sockets()) {
1328 if (input->is_available() && input->type == SOCK_MENU) {
1329 for (const bNodeSocket *output : node->output_sockets()) {
1330 if (output->is_available() && output->type == SOCK_MENU) {
1331 this->update_socket_enum_definition(
1332 *input->default_value_typed<bNodeSocketValueMenu>(),
1333 *output->default_value_typed<bNodeSocketValueMenu>());
1334 }
1335 }
1336 }
1337 }
1338 }
1339 }
1340
1341 /* Find conflicts between on corresponding menu sockets on different group input nodes. */
1342 const Span<bNode *> group_input_nodes = ntree.group_input_nodes();
1343 for (const int interface_input_i : ntree.interface_inputs().index_range()) {
1344 const bNodeTreeInterfaceSocket &interface_socket =
1345 *ntree.interface_inputs()[interface_input_i];
1346 if (interface_socket.socket_type != StringRef("NodeSocketMenu")) {
1347 continue;
1348 }
1349 const RuntimeNodeEnumItems *found_enum_items = nullptr;
1350 bool found_conflict = false;
1351 for (bNode *input_node : group_input_nodes) {
1352 const bNodeSocket &socket = input_node->output_socket(interface_input_i);
1353 const auto &socket_value = *socket.default_value_typed<bNodeSocketValueMenu>();
1354 if (socket_value.has_conflict()) {
1355 found_conflict = true;
1356 break;
1357 }
1358 if (found_enum_items == nullptr) {
1359 found_enum_items = socket_value.enum_items;
1360 }
1361 else if (socket_value.enum_items != nullptr) {
1362 if (found_enum_items != socket_value.enum_items) {
1363 found_conflict = true;
1364 break;
1365 }
1366 }
1367 }
1368 if (found_conflict) {
1369 /* Make sure that all group input sockets know that there is a conflict. */
1370 for (bNode *input_node : group_input_nodes) {
1371 bNodeSocket &socket = input_node->output_socket(interface_input_i);
1372 auto &socket_value = *socket.default_value_typed<bNodeSocketValueMenu>();
1373 if (socket_value.enum_items) {
1374 socket_value.enum_items->remove_user_and_delete_if_last();
1375 socket_value.enum_items = nullptr;
1376 }
1378 }
1379 }
1380 else if (found_enum_items != nullptr) {
1381 /* Make sure all corresponding menu sockets have the same menu reference. */
1382 for (bNode *input_node : group_input_nodes) {
1383 bNodeSocket &socket = input_node->output_socket(interface_input_i);
1384 auto &socket_value = *socket.default_value_typed<bNodeSocketValueMenu>();
1385 if (socket_value.enum_items == nullptr) {
1386 found_enum_items->add_user();
1387 socket_value.enum_items = found_enum_items;
1388 }
1389 }
1390 }
1391 }
1392
1393 /* Build list of new enum items for the node tree interface. */
1394 Vector<bNodeSocketValueMenu> interface_enum_items(ntree.interface_inputs().size(), {0});
1395 for (const bNode *group_input_node : ntree.group_input_nodes()) {
1396 for (const int socket_i : ntree.interface_inputs().index_range()) {
1397 const bNodeSocket &output = *group_input_node->output_sockets()[socket_i];
1398
1399 if (output.is_available() && output.type == SOCK_MENU) {
1400 this->update_socket_enum_definition(interface_enum_items[socket_i],
1401 *output.default_value_typed<bNodeSocketValueMenu>());
1402 }
1403 }
1404 }
1405
1406 /* Move enum items to the interface and detect if anything changed. */
1407 bool changed = false;
1408 for (const int socket_i : ntree.interface_inputs().index_range()) {
1409 bNodeTreeInterfaceSocket &iosocket = *ntree.interface_inputs()[socket_i];
1410 if (STREQ(iosocket.socket_type, "NodeSocketMenu")) {
1411 bNodeSocketValueMenu &dst = *static_cast<bNodeSocketValueMenu *>(iosocket.socket_data);
1412 const bNodeSocketValueMenu &src = interface_enum_items[socket_i];
1413 if (dst.enum_items != src.enum_items || dst.has_conflict() != src.has_conflict()) {
1414 changed = true;
1415 if (dst.enum_items) {
1417 }
1418 /* Items are moved, no need to change user count. */
1419 dst.enum_items = src.enum_items;
1421 }
1422 else {
1423 /* If the item isn't move make sure it gets released again. */
1424 if (src.enum_items) {
1426 }
1427 }
1428 }
1429 }
1430
1431 return changed;
1432 }
1433
1438 const RuntimeNodeEnumItems *create_runtime_enum_items(const NodeEnumDefinition &enum_def)
1439 {
1440 RuntimeNodeEnumItems *enum_items = new RuntimeNodeEnumItems();
1441 enum_items->items.reinitialize(enum_def.items_num);
1442 for (const int i : enum_def.items().index_range()) {
1443 const NodeEnumItem &src = enum_def.items()[i];
1444 RuntimeNodeEnumItem &dst = enum_items->items[i];
1445
1446 dst.identifier = src.identifier;
1447 dst.name = src.name ? src.name : "";
1448 dst.description = src.description ? src.description : "";
1449 }
1450 return enum_items;
1451 }
1452
1453 void clear_enum_reference(bNodeSocket &socket)
1454 {
1455 BLI_assert(socket.is_available() && socket.type == SOCK_MENU);
1456 bNodeSocketValueMenu &default_value = *socket.default_value_typed<bNodeSocketValueMenu>();
1457 this->reset_enum_ptr(default_value);
1458 default_value.runtime_flag &= ~NODE_MENU_ITEMS_CONFLICT;
1459 }
1460
1461 void update_socket_enum_definition(bNodeSocketValueMenu &dst, const bNodeSocketValueMenu &src)
1462 {
1463 if (dst.has_conflict()) {
1464 /* Target enum already has a conflict. */
1465 BLI_assert(dst.enum_items == nullptr);
1466 return;
1467 }
1468
1469 if (src.has_conflict()) {
1470 /* Target conflict if any source enum has a conflict. */
1471 this->reset_enum_ptr(dst);
1473 }
1474 else if (!dst.enum_items) {
1475 /* First connection, set the reference. */
1476 this->set_enum_ptr(dst, src.enum_items);
1477 }
1478 else if (src.enum_items && dst.enum_items != src.enum_items) {
1479 /* Error if enum ref does not match other connections. */
1480 this->reset_enum_ptr(dst);
1482 }
1483 }
1484
1485 void reset_enum_ptr(bNodeSocketValueMenu &dst)
1486 {
1487 if (dst.enum_items) {
1489 dst.enum_items = nullptr;
1490 }
1491 }
1492
1493 void set_enum_ptr(bNodeSocketValueMenu &dst, const RuntimeNodeEnumItems *enum_items)
1494 {
1495 if (dst.enum_items) {
1497 dst.enum_items = nullptr;
1498 }
1499 if (enum_items) {
1500 enum_items->add_user();
1501 dst.enum_items = enum_items;
1502 }
1503 }
1504
1505 static Array<ShaderNodeAncestorFlags> shader_tree_tag_inputs_by_ancestor(bNodeTree &ntree)
1506 {
1507 Array<ShaderNodeAncestorFlags> input_ancestors(ntree.all_input_sockets().size(),
1509
1510 for (const bNode *node : ntree.toposort_right_to_left()) {
1511 if (ELEM(node->type_legacy,
1516 {
1517 for (const bNodeSocket *socket : node->input_sockets()) {
1518 input_ancestors[socket->index_in_all_inputs()] =
1519 (node->type_legacy == SH_NODE_OUTPUT_MATERIAL &&
1520 socket->identifier_ustr() == "Surface"_ustr) ?
1523 }
1524 continue;
1525 }
1526
1528 for (const bNodeSocket *socket : node->output_sockets()) {
1529 for (const bNodeLink *link : socket->directly_linked_links()) {
1530 if (link->is_used()) {
1531 node_flags |= input_ancestors[link->tosock->index_in_all_inputs()];
1532 }
1533 }
1534 }
1535
1536 if (node->type_legacy == SH_NODE_SHADERTORGB) {
1538 }
1539 else if (node->type_legacy == SH_NODE_LIGHT_ACCUMULATION) {
1540 /* Reset. We only care about what a lighting node reaches before passing through
1541 * LightAccumulation. */
1542 node_flags = ShaderNodeAncestorFlags::None;
1543 }
1544
1545 for (const bNodeSocket *socket : node->input_sockets()) {
1546 ShaderNodeAncestorFlags &socket_flags = input_ancestors[socket->index_in_all_inputs()];
1547 socket_flags = node_flags;
1548 if (node->type_legacy == SH_NODE_LIGHT_ACCUMULATION && ELEM(socket->identifier_ustr(),
1549 "Diffuse Color"_ustr,
1550 "Glossy Color"_ustr,
1551 "Transmission Color"_ustr))
1552 {
1554 }
1555 }
1556 }
1557
1558 return input_ancestors;
1559 }
1560
1561 static bool is_lighting_node(const bNode &node)
1562 {
1563 switch (node.type_legacy) {
1565 case SH_NODE_LIGHT_INFO:
1568 return true;
1569 /* Attribute and Vector Transform nodes are only lighting nodes in light mode. */
1570 case SH_NODE_ATTRIBUTE:
1571 return static_cast<const NodeShaderAttribute *>(node.storage)->type == SHD_ATTRIBUTE_LIGHT;
1573 const NodeShaderVectTransform *nodeprop = static_cast<const NodeShaderVectTransform *>(
1574 node.storage);
1575 return ELEM(SHD_VECT_TRANSFORM_SPACE_LIGHT, nodeprop->convert_from, nodeprop->convert_to);
1576 }
1577 default:
1578 return false;
1579 }
1580 }
1581
1582 static const char *shader_tree_link_error(bNodeLink &link,
1583 const Span<ShaderNodeAncestorFlags> input_ancestors)
1584 {
1585 const bNode &from_node = *link.fromnode;
1586 if (!is_lighting_node(from_node)) {
1587 return nullptr;
1588 }
1589 const ShaderNodeAncestorFlags to_flags = input_ancestors[link.tosock->index_in_all_inputs()];
1590 if (bool(to_flags & ShaderNodeAncestorFlags::ShaderToRGB)) {
1591 return TIP_("Shader To RGB can't evaluate Lighting nodes");
1592 }
1593 if (from_node.type_legacy == SH_NODE_LIGHT_ACCUMULATION) {
1594 if (bool(to_flags & ShaderNodeAncestorFlags::OtherOutput)) {
1595 return TIP_("Light Accumulation can only be used for the Material Output Surface");
1596 }
1597 }
1598 else {
1601 {
1602 return TIP_(
1603 "Lighting nodes must be connected to the Light sockets of a Light Accumulation node "
1604 "before reaching an output");
1605 }
1607 return TIP_(
1608 "Lighting nodes can't be connected to the Color sockets of a Light Accumulation node");
1609 }
1610 }
1611 return nullptr;
1612 }
1613
1614 void update_link_validation(bNodeTree &ntree)
1615 {
1616 const bNodeTreeZones *fallback_zones = nullptr;
1617 if (ELEM(ntree.type, NTREE_GEOMETRY, NTREE_SHADER, NTREE_COMPOSIT) && !ntree.zones() &&
1619 {
1620 fallback_zones = ntree.runtime->last_valid_zones.get();
1621 }
1622
1623 /* Clear the validity from the previous update first. */
1624 for (bNodeLink &link : ntree.links) {
1625 link.flag |= NODE_LINK_VALID;
1626 }
1627
1628 Array<ShaderNodeAncestorFlags> shader_input_ancestors;
1629 if (ntree.type == NTREE_SHADER) {
1630 shader_input_ancestors = shader_tree_tag_inputs_by_ancestor(ntree);
1631 }
1632
1633 for (bNodeLink &link : ntree.links) {
1634 if (!link.fromsock->is_available() || !link.tosock->is_available()) {
1635 link.flag &= ~NODE_LINK_VALID;
1636 continue;
1637 }
1638 if (link.fromsock->type == SOCK_MENU && link.tosock->type == SOCK_MENU) {
1639 const bNodeSocketValueMenu *from_value =
1640 link.fromsock->default_value_typed<bNodeSocketValueMenu>();
1641 const bNodeSocketValueMenu *to_value =
1642 link.tosock->default_value_typed<bNodeSocketValueMenu>();
1643 if (from_value->has_conflict() || to_value->has_conflict()) {
1644 link.flag &= ~NODE_LINK_VALID;
1645 ntree.runtime->link_errors.add(
1646 NodeLinkKey{link},
1647 NodeLinkError{TIP_("Use node groups to reuse the same menu multiple times")});
1648 continue;
1649 }
1650 }
1651 const bNode &from_node = *link.fromnode;
1652 const bNode &to_node = *link.tonode;
1653 if (from_node.runtime->toposort_left_to_right_index >
1655 {
1656 link.flag &= ~NODE_LINK_VALID;
1657 ntree.runtime->link_errors.add(
1658 NodeLinkKey{link},
1659 NodeLinkError{TIP_("The links form a cycle which is not supported")});
1660 continue;
1661 }
1662 if (ntree.typeinfo->validate_link) {
1663 const eNodeSocketDatatype from_type = link.fromsock->type;
1664 const eNodeSocketDatatype to_type = link.tosock->type;
1665 if (!ntree.typeinfo->validate_link(from_type, to_type)) {
1666 link.flag &= ~NODE_LINK_VALID;
1667 ntree.runtime->link_errors.add(
1668 NodeLinkKey{link},
1669 NodeLinkError{fmt::format("{}: {} " BLI_STR_UTF8_BLACK_RIGHT_POINTING_SMALL_TRIANGLE
1670 " {}",
1671 TIP_("Conversion is not supported"),
1672 TIP_(link.fromsock->typeinfo->label),
1673 TIP_(link.tosock->typeinfo->label))});
1674 continue;
1675 }
1676 }
1677 if (fallback_zones) {
1678 if (!fallback_zones->link_between_sockets_is_allowed(*link.fromsock, *link.tosock)) {
1679 if (const bNodeTreeZone *from_zone = fallback_zones->get_zone_by_socket(*link.fromsock))
1680 {
1681 ntree.runtime->invalid_zone_output_node_ids.add(*from_zone->output_node_id);
1682 }
1683
1684 link.flag &= ~NODE_LINK_VALID;
1685 ntree.runtime->link_errors.add(
1686 NodeLinkKey{link}, NodeLinkError{TIP_("Links can only go into a zone but not out")});
1687 continue;
1688 }
1689 }
1690 if (const char *error = this->get_structure_type_link_error(link)) {
1691 link.flag &= ~NODE_LINK_VALID;
1692 ntree.runtime->link_errors.add(NodeLinkKey{link}, NodeLinkError{error});
1693 continue;
1694 }
1695 if (ntree.type == NTREE_SHADER) {
1696 if (const char *error = shader_tree_link_error(link, shader_input_ancestors)) {
1697 link.flag &= ~NODE_LINK_VALID;
1698 ntree.runtime->link_errors.add(NodeLinkKey{link}, NodeLinkError{error});
1699 continue;
1700 }
1701 }
1702 }
1703 }
1704
1705 const char *get_structure_type_link_error(const bNodeLink &link)
1706 {
1707 const nodes::StructureType from_inferred_type =
1709 if (from_inferred_type == StructureType::Dynamic) {
1710 /* Showing errors in this case results in many false positives in cases where Blender is not
1711 * sure what the actual type is. */
1712 return nullptr;
1713 }
1714 const int from_shape = link.fromsock->display_shape;
1715 const int to_shape = link.tosock->display_shape;
1716 switch (to_shape) {
1718 return nullptr;
1719 }
1721 if (from_shape == SOCK_DISPLAY_SHAPE_LINE) {
1722 return nullptr;
1723 }
1724 if (from_inferred_type == StructureType::Single) {
1725 return nullptr;
1726 }
1727 return TIP_("Input expects a single value");
1728 }
1731 return nullptr;
1732 }
1733 if (ELEM(from_inferred_type, StructureType::Single, StructureType::Field)) {
1734 return nullptr;
1735 }
1736 return TIP_("Input expects a field or single value");
1737 }
1739 if (from_shape == SOCK_DISPLAY_SHAPE_VOLUME_GRID) {
1740 return nullptr;
1741 }
1742 if (from_inferred_type == StructureType::Grid) {
1743 return nullptr;
1744 }
1745 return TIP_("Input expects a volume grid");
1746 }
1748 if (from_shape == SOCK_DISPLAY_SHAPE_LIST) {
1749 return nullptr;
1750 }
1751 if (from_inferred_type == StructureType::List) {
1752 return nullptr;
1753 }
1754 return TIP_("Input expects a list");
1755 }
1756 }
1757 return nullptr;
1758 }
1759
1760 bool check_if_output_changed(const bNodeTree &tree)
1761 {
1762 tree.ensure_topology_cache();
1763
1764 /* Compute a hash that represents the node topology connected to the output. This always has
1765 * to be updated even if it is not used to detect changes right now. Otherwise
1766 * #btree.runtime.output_topology_hash will go out of date. */
1767 const Vector<const bNodeSocket *> tree_output_sockets = this->find_output_sockets(tree);
1768 const uint32_t old_topology_hash = tree.runtime->output_topology_hash;
1769 const uint32_t new_topology_hash = this->get_combined_socket_topology_hash(
1770 tree, tree_output_sockets);
1771 tree.runtime->output_topology_hash = new_topology_hash;
1772
1773 if (const AnimData *adt = BKE_animdata_from_id(&tree.id)) {
1774 /* Drivers may copy values in the node tree around arbitrarily and may cause the output to
1775 * change even if it wouldn't without drivers. Only some special drivers like `frame/5` can
1776 * be used without causing updates all the time currently. In the future we could try to
1777 * handle other drivers better as well.
1778 * Note that this optimization only works in practice when the depsgraph didn't also get a
1779 * copy-on-evaluation tag for the node tree (which happens when changing node properties). It
1780 * does work in a few situations like adding reroutes and duplicating nodes though. */
1781 for (const FCurve &fcurve : adt->drivers) {
1782 const ChannelDriver *driver = fcurve.driver;
1783 const StringRef expression = driver->expression;
1784 if (expression.startswith("frame")) {
1785 const StringRef remaining_expression = expression.drop_known_prefix("frame");
1786 if (remaining_expression.find_first_not_of(" */+-0123456789.") == StringRef::not_found) {
1787 continue;
1788 }
1789 }
1790 /* Unrecognized driver, assume that the output always changes. */
1791 return true;
1792 }
1793 }
1794
1796 return true;
1797 }
1798
1799 if (old_topology_hash != new_topology_hash) {
1800 return true;
1801 }
1802
1803 /* The topology hash can only be used when only topology-changing operations have been done.
1804 */
1805 if (tree.runtime->changed_flag ==
1807 {
1808 if (old_topology_hash == new_topology_hash) {
1809 return false;
1810 }
1811 }
1812
1813 if (!this->check_if_socket_outputs_changed_based_on_flags(tree, tree_output_sockets)) {
1814 return false;
1815 }
1816
1817 return true;
1818 }
1819
1820 Vector<const bNodeSocket *> find_output_sockets(const bNodeTree &tree)
1821 {
1822 Vector<const bNodeSocket *> sockets;
1823 for (const bNode *node : tree.all_nodes()) {
1824 if (!this->is_output_node(*node)) {
1825 continue;
1826 }
1827 for (const bNodeSocket *socket : node->input_sockets()) {
1828 if (!STREQ(socket->idname, "NodeSocketVirtual")) {
1829 sockets.append(socket);
1830 }
1831 }
1832 }
1833 return sockets;
1834 }
1835
1836 bool is_output_node(const bNode &node) const
1837 {
1838 if (node.typeinfo->nclass == NODE_CLASS_OUTPUT) {
1839 return true;
1840 }
1841 if (node.is_group_output()) {
1842 return true;
1843 }
1844 if (node.is_type("GeometryNodeWarning"_ustr)) {
1845 return true;
1846 }
1848 return true;
1849 }
1850 /* Assume node groups without output sockets are outputs. */
1851 if (node.is_group()) {
1852 const bNodeTree *node_group = reinterpret_cast<const bNodeTree *>(node.id);
1853 if (node_group != nullptr &&
1855 {
1856 return true;
1857 }
1858 }
1859 return false;
1860 }
1861
1866 uint32_t get_combined_socket_topology_hash(const bNodeTree &tree,
1867 Span<const bNodeSocket *> sockets)
1868 {
1869 if (tree.has_available_link_cycle()) {
1870 /* Return dummy value when the link has any cycles. The algorithm below could be improved
1871 * to handle cycles more gracefully. */
1872 return 0;
1873 }
1874 Array<uint32_t> hashes = this->get_socket_topology_hashes(tree, sockets);
1875 uint32_t combined_hash = 0;
1876 for (uint32_t hash : hashes) {
1877 combined_hash = noise::hash(combined_hash, hash);
1878 }
1879 return combined_hash;
1880 }
1881
1882 Array<uint32_t> get_socket_topology_hashes(const bNodeTree &tree,
1883 const Span<const bNodeSocket *> sockets)
1884 {
1885 BLI_assert(!tree.has_available_link_cycle());
1886 Array<std::optional<uint32_t>> hash_by_socket_id(tree.all_sockets().size());
1887 Stack<const bNodeSocket *> sockets_to_check = sockets;
1888
1889 auto get_socket_ptr_hash = [&](const bNodeSocket &socket) {
1890 const uint64_t socket_ptr = uintptr_t(&socket);
1891 return noise::hash(socket_ptr, socket_ptr >> 32);
1892 };
1893 const bNodeTreeZones *zones = tree.zones();
1894
1895 while (!sockets_to_check.is_empty()) {
1896 const bNodeSocket &socket = *sockets_to_check.peek();
1897 const bNode &node = socket.owner_node();
1898
1899 if (hash_by_socket_id[socket.index_in_tree()].has_value()) {
1900 sockets_to_check.pop();
1901 /* Socket is handled already. */
1902 continue;
1903 }
1904
1905 uint32_t socket_hash = 0;
1906 if (socket.is_input()) {
1907 /* For input sockets, first compute the hashes of all linked sockets. */
1908 bool all_origins_computed = true;
1909 bool get_value_from_origin = false;
1910 Vector<const bNodeSocket *, 16> origin_sockets;
1911 for (const bNodeLink *link : socket.directly_linked_links()) {
1912 if (link->is_muted()) {
1913 continue;
1914 }
1915 if (!link->is_available()) {
1916 continue;
1917 }
1918 origin_sockets.append(link->fromsock);
1919 }
1920 if (zones) {
1921 if (const bNodeTreeZone *zone = zones->get_zone_by_socket(socket)) {
1922 if (zone->output_node_id == node.identifier) {
1923 if (const bNode *input_node = zone->input_node()) {
1924 origin_sockets.extend(input_node->input_sockets());
1925 }
1926 }
1927 }
1928 }
1929 for (const bNodeSocket *origin_socket : origin_sockets) {
1930 const std::optional<uint32_t> origin_hash =
1931 hash_by_socket_id[origin_socket->index_in_tree()];
1932 if (origin_hash.has_value()) {
1933 if (get_value_from_origin || socket.type != origin_socket->type) {
1934 socket_hash = noise::hash(socket_hash, *origin_hash);
1935 }
1936 else {
1937 /* Copy the socket hash because the link did not change it. */
1938 socket_hash = *origin_hash;
1939 }
1940 get_value_from_origin = true;
1941 }
1942 else {
1943 sockets_to_check.push(origin_socket);
1944 all_origins_computed = false;
1945 }
1946 }
1947 if (!all_origins_computed) {
1948 continue;
1949 }
1950
1951 if (!get_value_from_origin) {
1952 socket_hash = get_socket_ptr_hash(socket);
1953 }
1954 }
1955 else {
1956 bool all_available_inputs_computed = true;
1957 for (const bNodeSocket *input_socket : node.input_sockets()) {
1958 if (input_socket->is_available()) {
1959 if (!hash_by_socket_id[input_socket->index_in_tree()].has_value()) {
1960 sockets_to_check.push(input_socket);
1961 all_available_inputs_computed = false;
1962 }
1963 }
1964 }
1965 if (!all_available_inputs_computed) {
1966 continue;
1967 }
1968 if (node.is_reroute()) {
1969 socket_hash = *hash_by_socket_id[node.input_socket(0).index_in_tree()];
1970 }
1971 else if (node.is_muted()) {
1972 const bNodeSocket *internal_input = socket.internal_link_input();
1973 if (internal_input == nullptr) {
1974 socket_hash = get_socket_ptr_hash(socket);
1975 }
1976 else {
1977 socket_hash = *hash_by_socket_id[internal_input->index_in_tree()];
1978 }
1979 }
1980 else {
1981 socket_hash = get_socket_ptr_hash(socket);
1982 for (const bNodeSocket *input_socket : node.input_sockets()) {
1983 if (input_socket->is_available()) {
1984 const uint32_t input_socket_hash = *hash_by_socket_id[input_socket->index_in_tree()];
1985 socket_hash = noise::hash(socket_hash, input_socket_hash);
1986 }
1987 }
1988
1989 /* The Image Texture node has a special case. The behavior of the color output changes
1990 * depending on whether the Alpha output is linked. */
1991 if (node.is_type("ShaderNodeTexImage"_ustr) && socket.index() == 0) {
1992 BLI_assert(STREQ(socket.name, "Color"));
1993 const bNodeSocket &alpha_socket = node.output_socket(1);
1994 BLI_assert(STREQ(alpha_socket.name, "Alpha"));
1995 if (alpha_socket.is_directly_linked()) {
1996 socket_hash = noise::hash(socket_hash);
1997 }
1998 }
1999 }
2000 }
2001 hash_by_socket_id[socket.index_in_tree()] = socket_hash;
2002 /* Check that nothing has been pushed in the meantime. */
2003 BLI_assert(sockets_to_check.peek() == &socket);
2004 sockets_to_check.pop();
2005 }
2006
2007 /* Create output array. */
2008 Array<uint32_t> hashes(sockets.size());
2009 for (const int i : sockets.index_range()) {
2010 hashes[i] = *hash_by_socket_id[sockets[i]->index_in_tree()];
2011 }
2012 return hashes;
2013 }
2014
2019 bool check_if_socket_outputs_changed_based_on_flags(const bNodeTree &tree,
2020 Span<const bNodeSocket *> sockets)
2021 {
2022 /* Avoid visiting the same socket twice when multiple links point to the same socket. */
2023 Array<bool> pushed_by_socket_id(tree.all_sockets().size(), false);
2024 Stack<const bNodeSocket *> sockets_to_check = sockets;
2025
2026 for (const bNodeSocket *socket : sockets) {
2027 pushed_by_socket_id[socket->index_in_tree()] = true;
2028 }
2029
2030 while (!sockets_to_check.is_empty()) {
2031 const bNodeSocket &socket = *sockets_to_check.pop();
2032 const bNode &node = socket.owner_node();
2034 return true;
2035 }
2036 if (node.runtime->changed_flag != NTREE_CHANGED_NOTHING) {
2037 bool change_affects_output = true;
2038 if (!node.is_muted() && node.runtime->changed_flag == NTREE_CHANGED_INTERNAL_LINK) {
2039 change_affects_output = false;
2040 }
2041 if (node.runtime->changed_flag == NTREE_CHANGED_PARENT) {
2042 change_affects_output = false;
2043 }
2044 if (node.is_muted() && node.runtime->changed_flag == NTREE_CHANGED_NODE_PROPERTY) {
2045 change_affects_output = false;
2046 }
2047 if (change_affects_output) {
2048 return true;
2049 }
2050 }
2051 if (socket.is_input()) {
2052 for (const bNodeSocket *origin_socket : socket.directly_linked_sockets()) {
2053 bool &pushed = pushed_by_socket_id[origin_socket->index_in_tree()];
2054 if (!pushed) {
2055 sockets_to_check.push(origin_socket);
2056 pushed = true;
2057 }
2058 }
2059 }
2060 else {
2061 for (const bNodeSocket *input_socket : node.input_sockets()) {
2062 if (input_socket->is_available()) {
2063 bool &pushed = pushed_by_socket_id[input_socket->index_in_tree()];
2064 if (!pushed) {
2065 sockets_to_check.push(input_socket);
2066 pushed = true;
2067 }
2068 }
2069 }
2070 /* Zones may propagate changes from the input node to the output node even though there is
2071 * no explicit link. */
2072 switch (node.type_legacy) {
2076 const bNodeTreeZones *zones = tree.zones();
2077 if (!zones) {
2078 break;
2079 }
2080 const bNodeTreeZone *zone = zones->get_zone_by_node(node.identifier);
2081 if (!zone || !zone->input_node()) {
2082 break;
2083 }
2084 for (const bNodeSocket *input_socket : zone->input_node()->input_sockets()) {
2085 if (input_socket->is_available()) {
2086 bool &pushed = pushed_by_socket_id[input_socket->index_in_tree()];
2087 if (!pushed) {
2088 sockets_to_check.push(input_socket);
2089 pushed = true;
2090 }
2091 }
2092 }
2093 break;
2094 }
2095 }
2096 /* The Normal node has a special case, because the value stored in the first output
2097 * socket is used as input in the node. */
2098 if ((node.is_type("ShaderNodeNormal"_ustr) || node.is_type("CompositorNodeNormal"_ustr)) &&
2099 socket.index() == 1)
2100 {
2101 BLI_assert(STREQ(socket.name, "Dot"));
2102 const bNodeSocket &normal_output = node.output_socket(0);
2103 BLI_assert(STREQ(normal_output.name, "Normal"));
2104 bool &pushed = pushed_by_socket_id[normal_output.index_in_tree()];
2105 if (!pushed) {
2106 sockets_to_check.push(&normal_output);
2107 pushed = true;
2108 }
2109 }
2110 }
2111 }
2112 return false;
2113 }
2114
2119 bool update_nested_node_refs(bNodeTree &ntree)
2120 {
2121 ntree.ensure_topology_cache();
2122
2123 /* Simplify lookup of old ids. */
2124 Map<bNestedNodePath, int32_t> old_id_by_path;
2125 Set<int32_t> old_ids;
2126 for (const bNestedNodeRef &ref : ntree.nested_node_refs_span()) {
2127 old_id_by_path.add(ref.path, ref.id);
2128 old_ids.add(ref.id);
2129 }
2130
2131 Vector<bNestedNodePath> nested_node_paths;
2132
2133 /* Don't forget nested node refs just because the linked file is not available right now. */
2134 for (const bNestedNodePath &path : old_id_by_path.keys()) {
2135 const bNode *node = ntree.node_by_id(path.node_id);
2136 if (node && node->is_group() && node->id) {
2137 if (node->id->tag & ID_TAG_MISSING) {
2138 nested_node_paths.append(path);
2139 }
2140 }
2141 }
2142 if (ntree.type == NTREE_GEOMETRY) {
2143 /* Create references for simulations and bake nodes in geometry nodes.
2144 * Those are the nodes that we want to store settings for at a higher level. */
2145 for (const UString idname : {"GeometryNodeSimulationOutput"_ustr, "GeometryNodeBake"_ustr}) {
2146 for (const bNode *node : ntree.nodes_by_type(idname)) {
2147 nested_node_paths.append({node->identifier, -1});
2148 }
2149 }
2150 }
2151 /* Propagate references to nested nodes in group nodes. */
2152 for (const bNode *node : ntree.group_nodes()) {
2153 const bNodeTree *group = reinterpret_cast<const bNodeTree *>(node->id);
2154 if (group == nullptr) {
2155 continue;
2156 }
2157 for (const int i : group->nested_node_refs_span().index_range()) {
2158 const bNestedNodeRef &child_ref = group->nested_node_refs[i];
2159 nested_node_paths.append({node->identifier, child_ref.id});
2160 }
2161 }
2162
2163 /* Used to generate new unique IDs if necessary. */
2164 RandomNumberGenerator rng = RandomNumberGenerator::from_random_seed();
2165
2166 Map<int32_t, bNestedNodePath> new_path_by_id;
2167 for (const bNestedNodePath &path : nested_node_paths) {
2168 const int32_t old_id = old_id_by_path.lookup_default(path, -1);
2169 if (old_id != -1) {
2170 /* The same path existed before, it should keep the same ID as before. */
2171 new_path_by_id.add(old_id, path);
2172 continue;
2173 }
2174 int32_t new_id;
2175 while (true) {
2176 new_id = rng.get_int32(INT32_MAX);
2177 if (!old_ids.contains(new_id) && !new_path_by_id.contains(new_id)) {
2178 break;
2179 }
2180 }
2181 /* The path is new, it should get a new ID that does not collide with any existing IDs. */
2182 new_path_by_id.add(new_id, path);
2183 }
2184
2185 /* Check if the old and new references are identical. */
2186 if (!this->nested_node_refs_changed(ntree, new_path_by_id)) {
2187 return false;
2188 }
2189
2190 MEM_SAFE_DELETE(ntree.nested_node_refs);
2191 if (new_path_by_id.is_empty()) {
2192 ntree.nested_node_refs_num = 0;
2193 return true;
2194 }
2195
2196 /* Allocate new array for the nested node references contained in the node tree. */
2197 bNestedNodeRef *new_refs = MEM_new_array<bNestedNodeRef>(size_t(new_path_by_id.size()),
2198 __func__);
2199 int index = 0;
2200 for (const auto item : new_path_by_id.items()) {
2201 bNestedNodeRef &ref = new_refs[index];
2202 ref.id = item.key;
2203 ref.path = item.value;
2204 index++;
2205 }
2206
2207 ntree.nested_node_refs = new_refs;
2208 ntree.nested_node_refs_num = new_path_by_id.size();
2209
2210 return true;
2211 }
2212
2213 bool nested_node_refs_changed(const bNodeTree &ntree,
2214 const Map<int32_t, bNestedNodePath> &new_path_by_id)
2215 {
2216 if (ntree.nested_node_refs_num != new_path_by_id.size()) {
2217 return true;
2218 }
2219 for (const bNestedNodeRef &ref : ntree.nested_node_refs_span()) {
2220 if (!new_path_by_id.contains(ref.id)) {
2221 return true;
2222 }
2223 }
2224 return false;
2225 }
2226
2227 void reset_changed_flags(bNodeTree &ntree)
2228 {
2230 for (bNode *node : ntree.all_nodes()) {
2231 node->runtime->changed_flag = NTREE_CHANGED_NOTHING;
2232 node->runtime->update = 0;
2233 for (bNodeSocket &socket : node->inputs) {
2235 }
2236 for (bNodeSocket &socket : node->outputs) {
2238 }
2239 }
2240
2241 ntree.tree_interface.reset_interface_changed();
2242 }
2243
2247 bool update_panel_toggle_names(bNodeTree &ntree)
2248 {
2249 bool changed = false;
2250 ntree.ensure_interface_cache();
2251 for (bNodeTreeInterfaceItem *item : ntree.interface_items()) {
2252 if (item->item_type != NodeTreeInterfaceItemType::Panel) {
2253 continue;
2254 }
2255 bNodeTreeInterfacePanel *panel = reinterpret_cast<bNodeTreeInterfacePanel *>(item);
2256 if (bNodeTreeInterfaceSocket *toggle_socket = panel->header_toggle_socket()) {
2257 if (!STREQ(panel->name_, toggle_socket->name_)) {
2258 MEM_SAFE_DELETE(toggle_socket->name_);
2259 toggle_socket->name_ = BLI_strdup_null(panel->name_);
2260 changed = true;
2261 }
2262 }
2263 }
2264 return changed;
2265 }
2266};
2267
2268} // namespace bke
2269
2274
2279
2284
2289
2294
2299
2304
2309
2314
2319
2324
2329
2334
2339
2341{
2343}
2344
2346{
2348}
2349
2354
2359
2364
2366{
2367 FOREACH_NODETREE_BEGIN (bmain, ntree, ntree_id) {
2368 for (bNode *node : ntree->all_nodes()) {
2369 if (node->id == id) {
2370 node->runtime->update |= NODE_UPDATE_ID;
2372 }
2373 }
2374 }
2376}
2377
2379{
2380 /* Would have to search for the node that uses the image user for a more detailed tag. */
2382}
2383
2384uint64_t bNestedNodePath::hash() const
2385{
2386 return get_default_hash(this->node_id, this->id_in_node);
2387}
2388
2390{
2391 return a.node_id == b.node_id && a.id_in_node == b.id_in_node;
2392}
2393
2395 const std::optional<Span<bNodeTree *>> modified_trees,
2396 const NodeTreeUpdateExtraParams &params)
2397{
2398 /* Protect from recursive calls into the updating function. Some node update functions might
2399 * trigger this from Python or in other cases. */
2400 if (bmain.is_updating_node_trees) {
2401 return;
2402 }
2403
2404 bmain.is_updating_node_trees = true;
2405 bke::NodeTreeMainUpdater updater{&bmain, params};
2406 if (modified_trees.has_value()) {
2407 updater.update_rooted(*modified_trees);
2408 }
2409 else {
2410 updater.update();
2411 }
2412 bmain.is_updating_node_trees = false;
2413}
2414
2416 bNodeTree &modified_tree,
2417 const NodeTreeUpdateExtraParams &params)
2418{
2419 BKE_ntree_update(bmain, Span{&modified_tree}, params);
2420}
2421
2423{
2425
2426 /* Protect from recursive calls, see #BKE_ntree_update. */
2427 if (tree.runtime->is_updating) {
2428 return;
2429 }
2430
2431 tree.runtime->is_updating = true;
2433 bke::NodeTreeMainUpdater updater{nullptr, params};
2434 updater.update_rooted({&tree});
2435 tree.runtime->is_updating = false;
2436}
2437
2438} // namespace blender
#define NODE_CLASS_OUTPUT
Definition BKE_node.hh:479
#define NODE_REROUTE
Definition BKE_node.hh:867
#define NODE_GROUP_OUTPUT
Definition BKE_node.hh:869
#define FOREACH_NODETREE_END
Definition BKE_node.hh:936
#define FOREACH_NODETREE_BEGIN(bmain, _nodetree, _id)
Definition BKE_node.hh:926
#define NODE_GROUP_INPUT
Definition BKE_node.hh:868
#define SH_NODE_LIGHT_ACCUMULATION
#define NODE_EVALUATE_CLOSURE
#define SH_NODE_LIGHT_EVALUATION
#define SH_NODE_OUTPUT_WORLD
#define SH_NODE_SHADOW_RAYCAST
#define GEO_NODE_VIEWER
#define SH_NODE_LIGHT_INFO
#define GEO_NODE_FOREACH_GEOMETRY_ELEMENT_OUTPUT
#define SH_NODE_VECT_TRANSFORM
#define GEO_NODE_SIMULATION_OUTPUT
#define NODE_CLOSURE_OUTPUT
#define SH_NODE_SHADERTORGB
#define SH_NODE_OUTPUT_MATERIAL
#define NODE_COMBINE_BUNDLE
#define GEO_NODE_REPEAT_OUTPUT
#define NODE_SEPARATE_BUNDLE
#define NODE_CLOSURE_INPUT
#define SH_NODE_OUTPUT_LIGHT
#define SH_NODE_OUTPUT_AOV
#define SH_NODE_ATTRIBUTE
#define INT32_MAX
#define BLI_STR_UTF8_BLACK_RIGHT_POINTING_SMALL_TRIANGLE
#define TIP_(msgid)
#define ID_MISSING(_id)
Definition DNA_ID.h:695
#define PRF_scope_with_name(ui_name, category)
#define BLI_assert_unreachable()
#define UNUSED_VARS_NDEBUG(...)
#define SET_FLAG_FROM_TEST(value, test, flag)
#define BLI_assert(a)
#define ELEM(...)
#define STREQ(a, b)
unsigned long long int uint64_t
#define output
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr IndexRange index_range() const
Definition BLI_span.hh:405
constexpr bool is_empty() const
Definition BLI_span.hh:264
constexpr IndexRange()=default
bool add(const Key &key, const Value &value)
Definition BLI_map.hh:295
Value lookup_default(const Key &key, const Value &default_value) const
Definition BLI_map.hh:570
int64_t size() const
Definition BLI_map.hh:976
KeyIterator keys() const &
Definition BLI_map.hh:875
bool is_empty() const
Definition BLI_map.hh:986
bool contains(const Key &key) const
Definition BLI_map.hh:353
ItemIterator items() const &
Definition BLI_map.hh:902
static RandomNumberGenerator from_random_seed()
Definition rand.cc:288
bool contains(const Key &key) const
Definition BLI_set.hh:310
bool add(const Key &key)
Definition BLI_set.hh:248
void add_new(const Key &key)
Definition BLI_set.hh:233
void clear()
Definition BLI_set.hh:570
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr bool is_empty() const
Definition BLI_span.hh:264
bool is_empty() const
Definition BLI_stack.hh:310
void push(const T &value)
Definition BLI_stack.hh:215
constexpr StringRef drop_known_prefix(StringRef prefix) const
UString()=default
int64_t size() const
bool contains(const T &value) const
void append(const T &value)
void extend(Span< T > array)
NodeTreeMainUpdater(Main *bmain, const NodeTreeUpdateExtraParams &params)
void update_rooted(Span< bNodeTree * > root_ntrees)
nodes::StructureType inferred_structure_type
const nodes::SocketDeclaration * declaration
MultiValueMap< NodeLinkKey, NodeLinkError > link_errors
std::shared_ptr< nodes::GeneratedTreeSrnaData > compositor_effect_nodes_srna_data
std::shared_ptr< nodes::GeneratedTreeSrnaData > scene_compositor_effect_srna_data
CacheMutex geometry_nodes_lazy_function_graph_info_mutex
std::unique_ptr< nodes::EvalDependencies > eval_dependencies
std::shared_ptr< nodes::GeneratedTreeSrnaData > geometry_nodes_srna_data
std::shared_ptr< bNodeTreeZones > last_valid_zones
Map< int32_t, VectorSet< nodes::NodeWarning > > shader_node_errors
std::shared_ptr< nodes::GeneratedTreeSrnaData > compositor_nodes_srna_data
const bNode * input_node() const
const bNodeTreeZone * get_zone_by_node(const int32_t node_id) const
const bNodeTreeZone * get_zone_by_socket(const bNodeSocket &socket) const
bool link_between_sockets_is_allowed(const bNodeSocket &from, const bNodeSocket &to) const
const bNode * get_corresponding_output(const bNodeTree &tree, const bNode &input_bnode) const
constexpr bool startswith(StringRef prefix) const
static constexpr int64_t not_found
constexpr int64_t find_first_not_of(StringRef chars, int64_t pos=0) const
#define storage(slot, qualifiers)
#define image(slot, qualifiers, format)
#define index(i)
uint to_type(bool)
bool contains(const VArray< bool > &varray, const IndexMask &indices_to_check, bool value)
void update_effect_node_group_interface(Main &main, Scene &scene, SceneCompositorEffect &effect)
bool operator==(const Error &left, const Error &right)
std::pair< Scene *, Strip * > StripEffectPair
const bNodeZoneType * zone_type_by_node_type(const int node_type)
std::pair< Object *, ModifierData * > ObjectModifierPair
std::pair< Scene *, SceneCompositorEffect * > SceneCompositorEffectPair
std::pair< Scene *, StripModifierData * > StripModifierPair
std::pair< bNodeTree *, bNode * > TreeNodePair
Span< int > all_zone_input_node_types()
static bool is_tree_changed(const bNodeTree &tree)
std::pair< bNode *, bNodeSocket * > NodeSocketPair
bool node_declaration_ensure(bNodeTree &ntree, bNode &node)
Definition node.cc:5578
ENUM_OPERATORS(ShaderNodeAncestorFlags)
static int get_internal_link_type_priority(const bNodeSocketType *from, const bNodeSocketType *to)
void remove_index(T **items, int *items_num, int *active_index, const int index, void(*destruct_item)(T *))
bool update_tree_gizmo_propagation(bNodeTree &tree)
bool is_builtin_gizmo_node(const bNode &node)
void update_node_declaration_and_sockets(bNodeTree &ntree, bNode &node, Main *bmain)
std::shared_ptr< GeneratedTreeSrnaData > create_compositor_nodes_rna_for_effect(const bNodeTree &tree)
void node_can_sync_cache_clear(Main &bmain)
EvalDependencies gather_eval_dependencies_with_cache(const bNodeTree &ntree)
std::shared_ptr< GeneratedTreeSrnaData > create_scene_compositor_effect_inputs_srna(const bNodeTree &node_group)
std::shared_ptr< GeneratedTreeSrnaData > create_compositor_nodes_rna_for_strip_modifier(const bNodeTree &tree)
std::shared_ptr< GeneratedTreeSrnaData > create_geometry_nodes_rna_for_modifier(const bNodeTree &tree)
uint32_t hash(uint32_t kx)
Definition noise.cc:89
Editing * editing_get(const Scene *scene)
Definition sequencer.cc:304
void compositor_modifier_nodes_update_interface(Main &bmain, Scene &sequencer_scene, SequencerCompositorModifierData &cmd)
VectorSet< Strip * > query_all_strips_recursive(const ListBaseT< Strip > *seqbase)
Definition iterator.cc:123
void compositor_effect_nodes_update_interface(Main &bmain, Scene &sequencer_scene, Strip &strip)
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
@ NODE_GEO_VIEWER_ITEM_FLAG_AUTO_REMOVE
unsigned __int64 uint64_t
Definition BKE_text.h:91
void BKE_ntree_update_tag_node_removed(bNodeTree *ntree)
bool BKE_image_is_animated(Image *image)
void BKE_ntree_update(Main &bmain, std::optional< Span< bNodeTree * > > modified_trees=std::nullopt, const NodeTreeUpdateExtraParams &params={})
void BKE_ntree_update_tag_link_added(bNodeTree *ntree, bNodeLink *link)
void BKE_ntree_update_tag_link_changed(bNodeTree *ntree)
void BKE_ntree_update_tag_socket_new(bNodeTree *ntree, bNodeSocket *socket)
@ NTREE_RUNTIME_FLAG_HAS_IMAGE_ANIMATION
@ NTREE_RUNTIME_FLAG_HAS_MATERIAL_OUTPUT
@ NTREE_RUNTIME_FLAG_HAS_SIMULATION_ZONE
void BKE_ntree_update_tag_id_changed(Main *bmain, ID *id)
void BKE_ntree_update_tag_socket_property(bNodeTree *ntree, bNodeSocket *socket)
@ SOCK_DISPLAY_SHAPE_VOLUME_GRID
@ SOCK_DISPLAY_SHAPE_LINE
@ SOCK_DISPLAY_SHAPE_CIRCLE
@ SOCK_DISPLAY_SHAPE_DIAMOND
@ SOCK_DISPLAY_SHAPE_LIST
@ SHD_ATTRIBUTE_LIGHT
void MOD_nodes_update_interface(Main &bmain, Object *object, NodesModifierData *nmd)
Definition MOD_nodes.cc:405
@ NTREE_CHANGED_REMOVED_SOCKET
@ NTREE_CHANGED_INTERNAL_LINK
@ NTREE_CHANGED_NODE_OUTPUT
@ NTREE_CHANGED_SOCKET_PROPERTY
@ NTREE_CHANGED_NODE_PROPERTY
@ NTREE_CHANGED_REMOVED_NODE
static void add_node_tag(bNodeTree *ntree, bNode *node, const eNodeTreeChangedFlag flag)
void BKE_ntree_update_tag_link_removed(bNodeTree *ntree)
void BKE_ntree_update_tag_parent_change(bNodeTree *ntree, bNode *node)
static void add_socket_tag(bNodeTree *ntree, bNodeSocket *socket, const eNodeTreeChangedFlag flag)
AnimData * BKE_animdata_from_id(const ID *id)
Definition anim_data.cc:93
unsigned int uint32_t
Definition BKE_text.h:81
void BKE_ntree_update_tag_node_mute(bNodeTree *ntree, bNode *node)
void BKE_ntree_update_tag_socket_removed(bNodeTree *ntree)
void BKE_ntree_update_after_single_tree_change(Main &bmain, bNodeTree &modified_tree, const NodeTreeUpdateExtraParams &params={})
void BKE_ntree_update_tag_image_user_changed(bNodeTree *ntree, ImageUser *iuser)
void BKE_ntree_update_tag_node_type(bNodeTree *ntree, bNode *node)
void BKE_ntree_update_tag_socket_type(bNodeTree *ntree, bNodeSocket *socket)
void BKE_ntree_update_tag_all(bNodeTree *ntree)
static void add_tree_tag(bNodeTree *ntree, const eNodeTreeChangedFlag flag)
_W64 unsigned int uintptr_t
Definition BKE_text.h:120
void BKE_ntree_update_without_main(bNodeTree &tree)
@ SHD_VECT_TRANSFORM_SPACE_LIGHT
void ntreeTexCheckCyclics(struct bNodeTree *ntree)
void BKE_ntree_update_tag_node_property(bNodeTree *ntree, bNode *node)
void BKE_ntree_update_tag_missing_runtime_data(bNodeTree *ntree)
void BKE_ntree_update_tag_active_output_changed(bNodeTree *ntree)
ID_Type GS(const char *name)
Definition DNA_ID.h:410
@ ID_TAG_NO_MAIN
Definition DNA_ID.h:981
@ ID_TAG_MISSING
Definition DNA_ID.h:870
signed int int32_t
Definition BKE_text.h:78
ID * BKE_id_owner_get(ID *id, const bool debug_relationship_assert=true)
Definition lib_id.cc:2770
void DEG_relations_tag_update(Main *bmain)
@ GEO_NODE_BAKE_ITEM_IS_ATTRIBUTE
char * BLI_strdup_null(const char *str) ATTR_WARN_UNUSED_RESULT ATTR_MALLOC
void BKE_ntree_update_tag_socket_availability(bNodeTree *ntree, bNodeSocket *socket)
@ eSeqModifierType_Compositor
constexpr uint64_t get_default_hash(const T &v, const Args &...args)
Definition BLI_hash.hh:252
void BKE_ntree_update_tag_link_mute(bNodeTree *ntree, bNodeLink *link)
void BKE_ntree_update_tag_node_internal_link(bNodeTree *ntree, bNode *node)
void BKE_ntree_update_tag_node_new(bNodeTree *ntree, bNode *node)
#define hash
Definition noise_c.cc:156
ChannelDriver * driver
bool is_updating_node_trees
Definition BKE_main.hh:350
NodeSocketInterfaceStructureType structure_type
NodeSocketInterfaceStructureType structure_type
NodeSocketInterfaceStructureType structure_type
NodeSocketInterfaceStructureType structure_type
NodeSocketInterfaceStructureType structure_type
NodeSocketInterfaceStructureType structure_type
ListBaseT< SceneCompositorEffect > compositor_effects
const bke::RuntimeNodeEnumItems * enum_items
bke::bNodeSocketType * typeinfo
eNodeSocketDatatype type
bke::bNodeSocketRuntime * runtime
eNodeSocketDisplayShape display_shape
ListBaseT< bNodeLink > links
bke::bNodeTreeType * typeinfo
bNodeTreeInterface tree_interface
eNodeTree_Type type
bke::bNodeTreeRuntime * runtime
bNestedNodeRef * nested_node_refs
bke::bNodeRuntime * runtime
Span< StripEffectPair > get_compositor_effect_users(bNodeTree *ntree)
Span< SceneCompositorEffectPair > get_scene_compositor_effects_users(bNodeTree *ntree)
Span< bNodeTree * > get_all_trees()
Span< TreeNodePair > get_group_node_users(bNodeTree *ntree)
Span< ObjectModifierPair > get_modifier_users(bNodeTree *ntree)
Span< StripModifierPair > get_strip_modifier_users(bNodeTree *ntree)
Vector< RuntimeNodeEnumItem > items
Defines a socket type.
Definition BKE_node.hh:163
eNodeSocketDatatype type
Definition BKE_node.hh:198
void(*) update(bNodeTree *ntree)
Definition BKE_node.hh:564
bool(*) validate_link(eNodeSocketDatatype from, eNodeSocketDatatype to)
Definition BKE_node.hh:566
void(*) updatefunc(bNodeTree *ntree, bNode *node)
Definition BKE_node.hh:312
NodeDeclareFunction declare
Definition BKE_node.hh:393
nodes::NodeDeclaration * static_declaration
Definition BKE_node.hh:402
static std::string socket_identifier_for_item(const NodeGeometryViewerItem &item)
static void destruct_item(NodeGeometryViewerItem *item)