-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoperators.py
3734 lines (3162 loc) · 146 KB
/
operators.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-FileCopyrightText: 2019-2022 Blender Foundation
#
# SPDX-License-Identifier: GPL-2.0-or-later
import itertools
import functools
import bpy
from bpy.types import Operator, PropertyGroup, NodeSocketVirtual
from bpy.props import (
FloatProperty,
EnumProperty,
BoolProperty,
IntProperty,
StringProperty,
FloatVectorProperty,
IntVectorProperty,
CollectionProperty,
)
from bpy_extras.io_utils import ImportHelper, ExportHelper
from mathutils import Vector
from os import path
from glob import glob
from copy import copy
from itertools import chain, islice, zip_longest
from .interface import NWConnectionListInputs, NWConnectionListOutputs
from .utils.constants import (
blend_types,
geo_combine_operations,
vector_operations,
boolean_operations,
shader_operations,
string_operations,
operations,
blend_types_list,
vector_operations_list,
bool_operations_list,
math_operations_list,
navs,
nav_list,
get_texture_node_types,
rl_outputs
)
from .utils.draw import draw_callback_nodeoutline
from .utils.paths import match_files_to_socket_names, split_into_components
from .utils.nodes import (
is_virtual_socket,
n_wise_iter,
next_in_list,
prev_in_list,
filter_nodes_by_type,
node_mid_pt,
get_bounds,
autolink,
node_at_pos,
get_active_tree,
get_nodes_links,
connect_sockets,
is_viewer_socket,
is_viewer_link,
get_group_output_node,
get_output_location,
force_update,
get_internal_socket,
fw_check,
NWBase,
FinishedAutolink,
get_first_enabled_output,
is_visible_socket,
temporary_unframe,
viewer_socket_name
)
from .addon_utils import fetch_user_preferences, safe_poll
from .sock_utils import get_socket_location
class NodeSetting(bpy.types.PropertyGroup):
value: StringProperty(
name="Value",
description="Python expression to be evaluated as the initial node setting",
default="",
)
class NWLazyMix(Operator, NWBase):
"""Add a Mix RGB/Shader node by interactively drawing lines between nodes"""
bl_idname = "node.fw_lazy_mix"
bl_label = "Mix Nodes"
bl_options = {'REGISTER', 'UNDO'}
def modal(self, context, event):
context.area.tag_redraw()
nodes, links = get_nodes_links(context)
cont = True
start_pos = [event.mouse_region_x, event.mouse_region_y]
node1 = None
if not context.scene.NWBusyDrawing:
node1 = node_at_pos(nodes, context, event)
if node1:
context.scene.NWBusyDrawing = node1.name
else:
if context.scene.NWBusyDrawing != 'STOP':
node1 = nodes[context.scene.NWBusyDrawing]
context.scene.NWLazySource = node1.name
context.scene.NWLazyTarget = node_at_pos(nodes, context, event).name
if event.type == 'MOUSEMOVE':
self.mouse_path.append((event.mouse_region_x, event.mouse_region_y))
elif event.type == 'RIGHTMOUSE' and event.value == 'RELEASE':
end_pos = [event.mouse_region_x, event.mouse_region_y]
bpy.types.SpaceNodeEditor.draw_handler_remove(self._handle, 'WINDOW')
node2 = None
node2 = node_at_pos(nodes, context, event)
if node2:
context.scene.NWBusyDrawing = node2.name
if node1 == node2:
cont = False
if cont:
if node1 and node2:
for node in nodes:
node.select = False
node1.select = True
node2.select = True
bpy.ops.node.fw_merge_nodes(mode="MIX", merge_type="AUTO")
context.scene.NWBusyDrawing = ""
return {'FINISHED'}
elif event.type == 'ESC':
print('cancelled')
bpy.types.SpaceNodeEditor.draw_handler_remove(self._handle, 'WINDOW')
return {'CANCELLED'}
return {'RUNNING_MODAL'}
def invoke(self, context, event):
if context.area.type == 'NODE_EDITOR':
# the arguments we pass the the callback
args = (self, context, 'MIX')
# Add the region OpenGL drawing callback
# draw in view space with 'POST_VIEW' and 'PRE_VIEW'
self._handle = bpy.types.SpaceNodeEditor.draw_handler_add(
draw_callback_nodeoutline, args, 'WINDOW', 'POST_PIXEL')
self.mouse_path = []
context.window_manager.modal_handler_add(self)
return {'RUNNING_MODAL'}
else:
self.report({'WARNING'}, "View3D not found, cannot run operator")
return {'CANCELLED'}
class NWLazyConnect(Operator, NWBase):
"""Connect two nodes without clicking a specific socket (automatically determined"""
bl_idname = "node.fw_lazy_connect"
bl_label = "Lazy Connect"
bl_options = {'REGISTER', 'UNDO'}
with_menu: BoolProperty()
def modal(self, context, event):
context.area.tag_redraw()
nodes, links = get_nodes_links(context)
cont = True
start_pos = [event.mouse_region_x, event.mouse_region_y]
node1 = None
if not context.scene.NWBusyDrawing:
node1 = node_at_pos(nodes, context, event)
if node1:
context.scene.NWBusyDrawing = node1.name
else:
if context.scene.NWBusyDrawing != 'STOP':
node1 = nodes[context.scene.NWBusyDrawing]
context.scene.NWLazySource = node1.name
context.scene.NWLazyTarget = node_at_pos(nodes, context, event).name
if event.type == 'MOUSEMOVE':
self.mouse_path.append((event.mouse_region_x, event.mouse_region_y))
elif event.type == 'RIGHTMOUSE' and event.value == 'RELEASE':
end_pos = [event.mouse_region_x, event.mouse_region_y]
bpy.types.SpaceNodeEditor.draw_handler_remove(self._handle, 'WINDOW')
node2 = None
node2 = node_at_pos(nodes, context, event)
if node2:
context.scene.NWBusyDrawing = node2.name
if node1 == node2:
cont = False
link_success = False
if cont:
if node1 and node2:
original_sel = []
original_unsel = []
for node in nodes:
if node.select:
node.select = False
original_sel.append(node)
else:
original_unsel.append(node)
node1.select = True
node2.select = True
# link_success = autolink(node1, node2, links)
if self.with_menu:
if len(node1.outputs) > 1 and node2.inputs:
bpy.ops.wm.call_menu("INVOKE_DEFAULT", name=NWConnectionListOutputs.bl_idname)
elif len(node1.outputs) == 1:
bpy.ops.node.fw_call_inputs_menu(from_socket=0)
else:
try:
link_success = autolink(node1, node2, links)
except FinishedAutolink:
link_success = True
for node in original_sel:
node.select = True
for node in original_unsel:
node.select = False
if link_success:
force_update(context)
context.scene.NWBusyDrawing = ""
return {'FINISHED'}
elif event.type == 'ESC':
bpy.types.SpaceNodeEditor.draw_handler_remove(self._handle, 'WINDOW')
return {'CANCELLED'}
return {'RUNNING_MODAL'}
def invoke(self, context, event):
if context.area.type == 'NODE_EDITOR':
nodes, links = get_nodes_links(context)
node = node_at_pos(nodes, context, event)
if node:
context.scene.NWBusyDrawing = node.name
# the arguments we pass the the callback
mode = "LINK"
if self.with_menu:
mode = "LINKMENU"
args = (self, context, mode)
# Add the region OpenGL drawing callback
# draw in view space with 'POST_VIEW' and 'PRE_VIEW'
self._handle = bpy.types.SpaceNodeEditor.draw_handler_add(
draw_callback_nodeoutline, args, 'WINDOW', 'POST_PIXEL')
self.mouse_path = []
context.window_manager.modal_handler_add(self)
return {'RUNNING_MODAL'}
else:
self.report({'WARNING'}, "View3D not found, cannot run operator")
return {'CANCELLED'}
class NWDeleteUnused(Operator, NWBase):
"""Delete all nodes whose output is not used"""
bl_idname = 'node.fw_del_unused'
bl_label = 'Delete Unused Nodes'
bl_options = {'REGISTER', 'UNDO'}
delete_muted: BoolProperty(
name="Delete Muted",
description="Delete (but reconnect, like Ctrl-X) all muted nodes",
default=True)
delete_frames: BoolProperty(
name="Delete Empty Frames",
description="Delete all frames that have no nodes inside them",
default=True)
def is_unused_node(self, node):
end_types = ['OUTPUT_MATERIAL', 'OUTPUT', 'VIEWER', 'COMPOSITE',
'SPLITVIEWER', 'OUTPUT_FILE', 'LEVELS', 'OUTPUT_LIGHT',
'OUTPUT_WORLD', 'GROUP_INPUT', 'GROUP_OUTPUT', 'FRAME']
if node.type in end_types:
return False
for output in node.outputs:
if output.links:
return False
return True
@classmethod
def poll(cls, context):
valid = False
if fw_check(context):
if context.space_data.node_tree.nodes:
valid = True
return valid
def execute(self, context):
nodes, links = get_nodes_links(context)
# Store selection
selection = []
for node in nodes:
if node.select:
selection.append(node.name)
for node in nodes:
node.select = False
deleted_nodes = []
temp_deleted_nodes = []
del_unused_iterations = len(nodes)
for it in range(0, del_unused_iterations):
temp_deleted_nodes = list(deleted_nodes) # keep record of last iteration
for node in nodes:
if self.is_unused_node(node):
node.select = True
deleted_nodes.append(node.name)
bpy.ops.node.delete()
if temp_deleted_nodes == deleted_nodes: # stop iterations when there are no more nodes to be deleted
break
if self.delete_frames:
repeat = True
while repeat:
frames_in_use = []
frames = []
repeat = False
for node in nodes:
if node.parent:
frames_in_use.append(node.parent)
for node in nodes:
if node.type == 'FRAME' and node not in frames_in_use:
frames.append(node)
if node.parent:
repeat = True # repeat for nested frames
for node in frames:
if node not in frames_in_use:
node.select = True
deleted_nodes.append(node.name)
bpy.ops.node.delete()
if self.delete_muted:
for node in nodes:
if node.mute:
node.select = True
deleted_nodes.append(node.name)
bpy.ops.node.delete_reconnect()
# get unique list of deleted nodes (iterations would count the same node more than once)
deleted_nodes = list(set(deleted_nodes))
for n in deleted_nodes:
self.report({'INFO'}, "Node " + n + " deleted")
num_deleted = len(deleted_nodes)
n = ' node'
if num_deleted > 1:
n += 's'
if num_deleted:
self.report({'INFO'}, "Deleted " + str(num_deleted) + n)
else:
self.report({'INFO'}, "Nothing deleted")
# Restore selection
nodes, links = get_nodes_links(context)
for node in nodes:
if node.name in selection:
node.select = True
return {'FINISHED'}
def invoke(self, context, event):
return context.window_manager.invoke_confirm(self, event)
class NWSwapLinks(Operator, NWBase):
"""Swap the output connections of the two selected nodes, or two similar inputs of a single node"""
bl_idname = 'node.fw_swap_links'
bl_label = 'Swap Links'
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
valid = False
if fw_check(context):
if context.selected_nodes:
valid = len(context.selected_nodes) <= 2
return valid
def execute(self, context):
nodes, links = get_nodes_links(context)
selected_nodes = context.selected_nodes
n1 = selected_nodes[0]
# Swap outputs
if len(selected_nodes) == 2:
n2 = selected_nodes[1]
if n1.outputs and n2.outputs:
n1_outputs = []
n2_outputs = []
out_index = 0
for output in n1.outputs:
if output.links:
for link in output.links:
n1_outputs.append([out_index, link.to_socket])
links.remove(link)
out_index += 1
out_index = 0
for output in n2.outputs:
if output.links:
for link in output.links:
n2_outputs.append([out_index, link.to_socket])
links.remove(link)
out_index += 1
for connection in n1_outputs:
try:
connect_sockets(n2.outputs[connection[0]], connection[1])
except:
self.report({'WARNING'},
"Some connections have been lost due to differing numbers of output sockets")
for connection in n2_outputs:
try:
connect_sockets(n1.outputs[connection[0]], connection[1])
except:
self.report({'WARNING'},
"Some connections have been lost due to differing numbers of output sockets")
else:
if n1.outputs or n2.outputs:
self.report({'WARNING'}, "One of the nodes has no outputs!")
else:
self.report({'WARNING'}, "Neither of the nodes have outputs!")
# Swap Inputs
elif len(selected_nodes) == 1:
if n1.inputs and n1.inputs[0].is_multi_input:
self.report({'WARNING'}, "Can't swap inputs of a multi input socket!")
return {'FINISHED'}
if n1.inputs:
types = []
i = 0
for i1 in n1.inputs:
if i1.is_linked and not i1.is_multi_input:
similar_types = 0
for i2 in n1.inputs:
if i1.type == i2.type and i2.is_linked and not i2.is_multi_input:
similar_types += 1
types.append([i1, similar_types, i])
i += 1
types.sort(key=lambda k: k[1], reverse=True)
if types:
t = types[0]
if t[1] == 2:
for i2 in n1.inputs:
if t[0].type == i2.type == t[0].type and t[0] != i2 and i2.is_linked:
pair = [t[0], i2]
i1f = pair[0].links[0].from_socket
i1t = pair[0].links[0].to_socket
i2f = pair[1].links[0].from_socket
i2t = pair[1].links[0].to_socket
connect_sockets(i1f, i2t)
connect_sockets(i2f, i1t)
if t[1] == 1:
if len(types) == 1:
fs = t[0].links[0].from_socket
i = t[2]
links.remove(t[0].links[0])
if i + 1 == len(n1.inputs):
i = -1
i += 1
while n1.inputs[i].is_linked:
i += 1
connect_sockets(fs, n1.inputs[i])
elif len(types) == 2:
i1f = types[0][0].links[0].from_socket
i1t = types[0][0].links[0].to_socket
i2f = types[1][0].links[0].from_socket
i2t = types[1][0].links[0].to_socket
connect_sockets(i1f, i2t)
connect_sockets(i2f, i1t)
else:
self.report({'WARNING'}, "This node has no input connections to swap!")
else:
self.report({'WARNING'}, "This node has no inputs to swap!")
force_update(context)
return {'FINISHED'}
class NWResetBG(Operator, NWBase):
"""Reset the zoom and position of the background image"""
bl_idname = 'node.fw_bg_reset'
bl_label = 'Reset Backdrop'
bl_options = {'REGISTER', 'UNDO'}
@classmethod
def poll(cls, context):
if fw_check(context):
return context.space_data.tree_type == 'CompositorNodeTree'
return False
def execute(self, context):
space = context.space_data
space.backdrop_zoom = 1
space.backdrop_offset = (0, 0)
return {'FINISHED'}
class NWAddAttrNode(Operator, NWBase):
"""Add an Attribute node with this name"""
bl_idname = 'node.fw_add_attr_node'
bl_label = 'Add Attribute Node'
bl_options = {'REGISTER', 'UNDO'}
attr_name: StringProperty()
attr_type: StringProperty(default='GEOMETRY')
def execute(self, context):
bpy.ops.node.add_node('INVOKE_DEFAULT', use_transform=True, type="ShaderNodeAttribute")
context.active_node.attribute_name = self.attr_name
context.active_node.attribute_type = self.attr_type
return {'FINISHED'}
class NWAddNamedAttrNode(Operator, NWBase):
"""Add an Named Attribute node with the specified name"""
bl_idname = 'node.fw_add_named_attr_node'
bl_label = 'Add Named Attribute Node'
bl_options = {'REGISTER', 'UNDO'}
attr_name: StringProperty()
attr_type: StringProperty()
attr_map = {
'BYTE_COLOR' : 'FLOAT_COLOR',
'FLOAT2' : 'FLOAT_VECTOR',
}
def execute(self, context):
bpy.ops.node.add_node('INVOKE_DEFAULT', use_transform=True, type="GeometryNodeInputNamedAttribute")
active_node = context.active_node
attr_type = self.attr_map.get(self.attr_type, self.attr_type)
active_node.inputs["Name"].default_value = self.attr_name
active_node.data_type = attr_type
return {'FINISHED'}
class NWPreviewNode(Operator, NWBase):
bl_idname = "node.fw_preview_node"
bl_label = "Preview Node"
bl_description = "Connect active node to the Node Group output or the Material Output"
bl_options = {'REGISTER', 'UNDO'}
# If false, the operator is not executed if the current node group happens to be a geometry nodes group.
# This is needed because geometry nodes has its own viewer node that uses the same shortcut as in the compositor.
run_in_geometry_nodes: BoolProperty(default=True)
def __init__(self):
self.shader_output_type = ""
self.shader_output_ident = ""
@classmethod
def poll(cls, context):
if fw_check(context):
space = context.space_data
if space.tree_type == 'ShaderNodeTree' or space.tree_type == 'GeometryNodeTree':
if context.active_node:
if context.active_node.type != "OUTPUT_MATERIAL" or context.active_node.type != "OUTPUT_WORLD":
return True
else:
return True
return False
@classmethod
def get_output_sockets(cls, node_tree):
return [item for item in node_tree.interface.items_tree if item.item_type == 'SOCKET' and item.in_out in {'OUTPUT', 'BOTH'}]
def ensure_viewer_socket(self, node, socket_type, connect_socket=None):
# check if a viewer output already exists in a node group otherwise create
if hasattr(node, "node_tree"):
viewer_socket = None
output_sockets = self.get_output_sockets(node.node_tree)
if len(output_sockets):
free_socket = None
for socket in output_sockets:
if is_viewer_socket(socket) and socket.socket_type == socket_type:
# if viewer output is already used but leads to the same socket we can still use it
is_used = self.is_socket_used_other_mats(socket)
if is_used:
if connect_socket is None:
continue
groupout = get_group_output_node(node.node_tree)
groupout_input = groupout.inputs[i]
links = groupout_input.links
if connect_socket not in [link.from_socket for link in links]:
continue
viewer_socket = socket
break
if not free_socket:
free_socket = socket
if not viewer_socket and free_socket:
viewer_socket = free_socket
if not viewer_socket:
# create viewer socket
viewer_socket = node.node_tree.interface.new_socket(viewer_socket_name, in_out='OUTPUT', socket_type=socket_type)
viewer_socket.NWViewerSocket = True
return viewer_socket
def init_shader_variables(self, space, shader_type):
if shader_type == 'OBJECT':
if space.id not in [light for light in bpy.data.lights]: # cannot use bpy.data.lights directly as iterable
self.shader_output_type = "OUTPUT_MATERIAL"
self.shader_output_ident = "ShaderNodeOutputMaterial"
else:
self.shader_output_type = "OUTPUT_LIGHT"
self.shader_output_ident = "ShaderNodeOutputLight"
elif shader_type == 'WORLD':
self.shader_output_type = "OUTPUT_WORLD"
self.shader_output_ident = "ShaderNodeOutputWorld"
def get_shader_output_node(self, tree):
for node in tree.nodes:
if node.type == self.shader_output_type and node.is_active_output:
return node
@classmethod
def ensure_group_output(cls, tree):
# check if a group output node exists otherwise create
groupout = get_group_output_node(tree)
if not groupout:
groupout = tree.nodes.new('NodeGroupOutput')
loc_x, loc_y = get_output_location(tree)
groupout.location.x = loc_x
groupout.location.y = loc_y
groupout.select = False
# So that we don't keep on adding new group outputs
groupout.is_active_output = True
return groupout
@classmethod
def search_sockets(cls, node, sockets, index=None):
# recursively scan nodes for viewer sockets and store in list
for i, input_socket in enumerate(node.inputs):
if index and i != index:
continue
if input_socket.is_linked:
link = input_socket.links[0]
next_node = link.from_node
external_socket = link.from_socket
if hasattr(next_node, "node_tree"):
for socket_index, socket in enumerate(next_node.node_tree.interface.items_tree):
if socket.identifier == external_socket.identifier:
break
if is_viewer_socket(socket) and socket not in sockets:
sockets.append(socket)
# continue search inside of node group but restrict socket to where we came from
groupout = get_group_output_node(next_node.node_tree)
cls.search_sockets(groupout, sockets, index=socket_index)
@classmethod
def scan_nodes(cls, tree, sockets):
# get all viewer sockets in a material tree
for node in tree.nodes:
if hasattr(node, "node_tree"):
if node.node_tree is None:
continue
for socket in cls.get_output_sockets(node.node_tree):
if is_viewer_socket(socket) and (socket not in sockets):
sockets.append(socket)
cls.scan_nodes(node.node_tree, sockets)
@classmethod
def remove_socket(cls, tree, socket):
interface = tree.interface
interface.remove(socket)
interface.active_index = min(interface.active_index, len(interface.items_tree) - 1)
def link_leads_to_used_socket(self, link):
# return True if link leads to a socket that is already used in this material
socket = get_internal_socket(link.to_socket)
return (socket and self.is_socket_used_active_mat(socket))
def is_socket_used_active_mat(self, socket):
# ensure used sockets in active material is calculated and check given socket
if not hasattr(self, "used_viewer_sockets_active_mat"):
self.used_viewer_sockets_active_mat = []
materialout = self.get_shader_output_node(bpy.context.space_data.node_tree)
if materialout:
self.search_sockets(materialout, self.used_viewer_sockets_active_mat)
return socket in self.used_viewer_sockets_active_mat
def is_socket_used_other_mats(self, socket):
# ensure used sockets in other materials are calculated and check given socket
if not hasattr(self, "used_viewer_sockets_other_mats"):
self.used_viewer_sockets_other_mats = []
for mat in bpy.data.materials:
if mat.node_tree == bpy.context.space_data.node_tree or not hasattr(mat.node_tree, "nodes"):
continue
# get viewer node
materialout = self.get_shader_output_node(mat.node_tree)
if materialout:
self.search_sockets(materialout, self.used_viewer_sockets_other_mats)
return socket in self.used_viewer_sockets_other_mats
@staticmethod
def is_valid_socket(socket):
return not (socket.hide or isinstance(socket, NodeSocketVirtual))
# TODO - FIX THIS NOT WORKING IN THE COMPOSITOR
def invoke(self, context, event):
space = context.space_data
# Ignore operator when running in wrong context.
if self.run_in_geometry_nodes != (space.tree_type == "GeometryNodeTree"):
return {'PASS_THROUGH'}
shader_type = space.shader_type
self.init_shader_variables(space, shader_type)
mlocx = event.mouse_region_x
mlocy = event.mouse_region_y
context.space_data.cursor_location_from_region(event.mouse_region_x, event.mouse_region_y)
# TODO - AVOID USING THIS OPERATOR TO AVOID ADDING TO THE UNDO STACK
select_node = bpy.ops.node.select(location=(mlocx, mlocy), extend=False)
if 'FINISHED' in select_node: # only run if mouse click is on a node
active_tree, path_to_tree = get_active_tree(context)
nodes, links = active_tree.nodes, active_tree.links
base_node_tree = space.node_tree
active = nodes.active
region = context.region
mouse_pos = Vector(region.view2d.region_to_view(mlocx, mlocy))
distance_from_mouse = lambda sock : (mouse_pos - get_socket_location(sock)).magnitude
visible_outputs = filter(self.is_valid_socket, active.outputs)
closest_outputs = sorted(visible_outputs, key=distance_from_mouse)
# For geometry node trees we just connect to the group output
if space.tree_type == "GeometryNodeTree":
valid = False
if active:
for out in active.outputs:
if is_visible_socket(out):
valid = True
break
# Exit early
if not valid:
return {'FINISHED'}
delete_sockets = []
# Scan through all nodes in tree including nodes inside of groups to find viewer sockets
self.scan_nodes(base_node_tree, delete_sockets)
# Find (or create if needed) the output of this node tree
geometryoutput = self.ensure_group_output(base_node_tree)
make_links = [] # store sockets for new links
if active.outputs:
# If there is no 'GEOMETRY' output type - We can't preview the node
try:
socket_to_connect = closest_outputs[0]
except Exception:
return {'FINISHED'}
socket_type = 'GEOMETRY'
# Find an input socket of the output of type geometry
geometryoutindex = None
for i, inp in enumerate(geometryoutput.inputs):
if inp.type == socket_type:
geometryoutindex = i
break
if geometryoutindex is None:
# Create geometry socket
geometryoutput.inputs.new(socket_type, 'Geometry')
geometryoutindex = len(geometryoutput.inputs) - 1
make_links.append((socket_to_connect, geometryoutput.inputs[geometryoutindex]))
output_socket = geometryoutput.inputs[geometryoutindex]
for li_from, li_to in make_links:
connect_sockets(li_from, li_to)
tree = base_node_tree
link_end = output_socket
while tree.nodes.active != active:
node = tree.nodes.active
viewer_socket = self.ensure_viewer_socket(
node, 'NodeSocketGeometry', connect_socket=socket_to_connect if node.node_tree.nodes.active == active else None)
link_start = node.outputs[viewer_socket_name]
node_socket = viewer_socket
if node_socket in delete_sockets:
delete_sockets.remove(node_socket)
connect_sockets(link_start, link_end)
# Iterate
link_end = self.ensure_group_output(node.node_tree).inputs[viewer_socket_name]
tree = tree.nodes.active.node_tree
connect_sockets(socket_to_connect, link_end)
# Delete sockets
for socket in delete_sockets:
tree = socket.id_data
self.remove_socket(tree, socket)
nodes.active = active
active.select = True
force_update(context)
return {'FINISHED'}
# What follows is code for the shader editor
valid = False
if active:
for out in active.outputs:
if is_visible_socket(out):
valid = True
break
if valid:
# get material_output node
materialout = None # placeholder node
delete_sockets = []
# scan through all nodes in tree including nodes inside of groups to find viewer sockets
self.scan_nodes(base_node_tree, delete_sockets)
materialout = self.get_shader_output_node(base_node_tree)
if not materialout:
materialout = base_node_tree.nodes.new(self.shader_output_ident)
materialout.location = get_output_location(base_node_tree)
materialout.select = False
make_links = [] # store sockets for new links
check_links_func = functools.partial(is_viewer_link, output_node=materialout)
#if any(map(check_links_func, closest_outputs[0].links)):
# return {'CANCELLED'}
if active.outputs:
socket_to_connect = closest_outputs[0]
socket_type = 'NodeSocketShader'
materialout_index = 1 if socket_to_connect.name == "Volume" else 0
make_links.append((socket_to_connect, materialout.inputs[materialout_index]))
output_socket = materialout.inputs[materialout_index]
for li_from, li_to in make_links:
connect_sockets(li_from, li_to)
# Create links through node groups until we reach the active node
tree = base_node_tree
link_end = output_socket
while tree.nodes.active != active:
node = tree.nodes.active
viewer_socket = self.ensure_viewer_socket(
node, socket_type, connect_socket=socket_to_connect if node.node_tree.nodes.active == active else None)
link_start = node.outputs[viewer_socket_name]
node_socket = viewer_socket
if node_socket in delete_sockets:
delete_sockets.remove(node_socket)
connect_sockets(link_start, link_end)
# Iterate
link_end = self.ensure_group_output(node.node_tree).inputs[viewer_socket_name]
tree = tree.nodes.active.node_tree
connect_sockets(socket_to_connect, link_end)
# Delete sockets
for socket in delete_sockets:
if not self.is_socket_used_other_mats(socket):
tree = socket.id_data
self.remove_socket(tree, socket)
nodes.active = active
active.select = True
force_update(context)
return {'FINISHED'}
else:
return {'CANCELLED'}
class NWFrameSelected(Operator, NWBase):
bl_idname = "node.fw_frame_selected"
bl_label = "Frame Selected"
bl_description = "Add a frame node and parent the selected nodes to it"
bl_options = {'REGISTER', 'UNDO'}
label_prop: StringProperty(
name='Label',
description='The visual name of the frame node',
default=' '
)
use_custom_color_prop: BoolProperty(
name="Custom Color",
description="Use custom color for the frame node",
default=False
)
color_prop: FloatVectorProperty(
name="Color",
description="The color of the frame node",
default=(0.604, 0.604, 0.604),
min=0, max=1, step=1, precision=3,
subtype='COLOR_GAMMA', size=3
)
def draw(self, context):
layout = self.layout
layout.prop(self, 'label_prop')
layout.prop(self, 'use_custom_color_prop')
col = layout.column()
col.active = self.use_custom_color_prop
col.prop(self, 'color_prop', text="")
def execute(self, context):
nodes, links = get_nodes_links(context)
selected = []
for node in nodes:
if node.select:
selected.append(node)
bpy.ops.node.add_node(type='NodeFrame')
frm = nodes.active
frm.label = self.label_prop
frm.use_custom_color = self.use_custom_color_prop
frm.color = self.color_prop
for node in selected:
node.parent = frm
return {'FINISHED'}
class NWReloadImages(Operator):
bl_idname = "node.fw_reload_images"
bl_label = "Reload Images"
bl_description = "Update all the image nodes to match their files on disk"
@classmethod
def poll(cls, context):
valid = False
if fw_check(context) and context.space_data.tree_type != 'GeometryNodeTree':
if context.active_node is not None:
for out in context.active_node.outputs:
if is_visible_socket(out):
valid = True
break
return valid
def execute(self, context):
nodes, links = get_nodes_links(context)
image_types = ["IMAGE", "TEX_IMAGE", "TEX_ENVIRONMENT", "TEXTURE"]
num_reloaded = 0
for node in nodes:
if node.type in image_types:
if node.type == "TEXTURE":
if node.texture: # node has texture assigned
if node.texture.type in ['IMAGE', 'ENVIRONMENT_MAP']:
if node.texture.image: # texture has image assigned
node.texture.image.reload()
num_reloaded += 1
else:
if node.image:
node.image.reload()
num_reloaded += 1
if num_reloaded:
self.report({'INFO'}, "Reloaded images")
print("Reloaded " + str(num_reloaded) + " images")
force_update(context)
return {'FINISHED'}
else:
self.report({'WARNING'}, "No images found to reload in this node tree")
return {'CANCELLED'}
class NWSwitchNodeType(Operator, NWBase):
"""Switch type of selected nodes """
bl_idname = "node.fw_swtch_node_type"
bl_label = "Switch Node Type"
bl_options = {'REGISTER', 'UNDO'}
to_type: StringProperty(
name="Switch to type",
default='',
)