-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
2512 lines (1984 loc) · 127 KB
/
__init__.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
import mathutils
import bpy
import hashlib
bl_info = {
"name": "Material Batch Tools",
"description": "Batch tools for quickly modifying, copying, and pasting nodes on all materials in selected objects",
"author": "Theanine3D",
"version": (2, 1, 2),
"blender": (3, 0, 0),
"category": "Material",
"location": "Properties -> Material Properties",
"support": "COMMUNITY"
}
# PROPERTY DEFINITIONS
bake_node_preset = {
"image": "",
"interpolation": "Linear",
"projection": "FLAT",
"projection_blend": 0.0,
"extension": "REPEAT",
"name": "Bake Target Node"
}
node_unify_settings = {
"name": "",
"type": "",
"material": ""
}
class MatBatchProperties(bpy.types.PropertyGroup):
BakeTargetNodeColorEnable: bpy.props.BoolProperty(
name="Enable", description="Enable or disable the optional color decoration for the Bake Target Node", default=True)
BakeTargetNodeColor: bpy.props.FloatVectorProperty(
name="Color", subtype="COLOR", description="Color to use for the Bake Target Node. This is purely cosmetic - it just makes the node easier to find", default=(0.52, 0.145, 0.152), size=3, min=0, max=1)
UVMapNodeTarget: bpy.props.StringProperty(
name="UV Map", description="Name of the UV map to set in the UV Map node", default="UVMap", maxlen=64)
UVMapNodeExtensionFilter: bpy.props.StringProperty(
name="Filter", description="Only the Image Texture nodes that are set to this file format will be modified", default="PNG", maxlen=20)
UVSlotIndex: bpy.props.EnumProperty(
name="UV Slot", description="The UV Slot that will be modified by the buttons below", items=[("1", 'UV Slot 1', 'The first UV slot in the object mesh(es)', 1), ("2", 'UV Slot 2', 'The second UV slot in the object mesh(es)', 2)], default=1)
VCName: bpy.props.StringProperty(
name="Name", description="Name to set in Vertex Color slot 1", default="Col", maxlen=64)
AlphaBlendMode: bpy.props.EnumProperty(
name="Blend Mode", description="The Blend Mode and Shadow Mode to set in the material(s). If set to Alpha Blend, Shadow Mode will be set to Alpha Clip", items=[("OPAQUE", 'Opaque', 'No transparency', 0), ("CLIP", 'Alpha Clip', 'Pixels will be either 100 percent transparent or 100 percent opaque', 1), ("BLEND", 'Alpha Blend', 'Pixels will be anywhere between 0 to 100 percent transparent', 2)], default=0)
AlphaBlendFilter: bpy.props.EnumProperty(
name="Filter", description="Only materials that satisfy this filter will be modified", items=[("NOFILTER", 'None', 'No filter. All materials will be modified', 0), ("PRINCIPLEDNODE", 'Principled BSDF Alpha', 'There must be a Principled node in the material, and its "Alpha" input is either connected to another node or is less than 1.000', 1), ("TRANSPARENTNODE", 'Transparent BSDF', 'There must be at least one Transparent BSDF in the material', 2)], default=0)
AlphaThreshold: bpy.props.FloatProperty(
name="Clip Threshold", subtype="FACTOR", description="This setting is used only by Alpha Clip", default=0.5, min=0.0, max=1.0)
AlphaPrincipledRemove: bpy.props.BoolProperty(
name="Remove Principled BSDF Alpha", description="If this option is enabled, and the Blend Mode is set to Opaque, the Principled BSDF's 'Alpha' input will be disconnected, and its value will be set to 1.0", default=False)
SavedNodeName: bpy.props.StringProperty(
name="Copied Node", description="The name of the node from which settings were copied", default="", maxlen=200)
SavedNodeType: bpy.props.StringProperty(
name="Copied Node Type", description="The type of the node from which settings were copied", default="", maxlen=200)
UnifyFilterLabel: bpy.props.StringProperty(
name="Label Filter", description="If specified, the Unify button will only affect any nodes that have this custom label. Case sensitive! Leave blank if you want to alter ALL nodes of the same type as the template node", default="", maxlen=100)
SwitchShaderTarget: bpy.props.EnumProperty(
name="Shader", description="The shader to switch in all materials in all selected objects to. For example, if you select Principled, any Emission nodes will be switched to Principled", items=[("EMISSION", 'Emission', 'Fullbright / shadeless shader - not affected by scene lighting', 0), ("BSDF_PRINCIPLED", 'Principled BSDF', 'Standard shader in Blender, affected by scene lighting', 1)], default=0)
CopiedTexture: bpy.props.StringProperty(
name="Copied Texture Name", description="The name of the active image texture copied from a selected face", default="", maxlen=200)
Template: bpy.props.EnumProperty(
name="Template", description="The node graph template to apply to all materials in all selected objects", items=[("ECT", 'Emissive + Color + Texture', 'Blends vertex color onto texture, if one exists', 0),
("EC", 'Emissive + Color', 'Ignores image textures completely', 1),
("ACCT", 'Alpha Clip + Color + Texture', 'Transparency via alpha clip, and emission', 2),
("ACT", 'Additive + Color + Texture', 'Combines transparency and emission for an additive effect', 3),
("AC", 'Additive + Color', 'Combines transparency and emission for an additive effect', 4),
("PT", 'Principled + Texture', 'Principled shading, with texture', 5),
("PC", 'Principled + Color', 'Principled shading, with vertex color', 6),
("HDRT", 'HDR Lightmap', "Emissive but with an HDR lightmap applied for baked lighting. Your HDR's UV map must be named 'lightmap', and your HDR's filename must contain either 'light_', '.hdr' or '.exr' to be detected automatically", 7),
("PP", 'Mirror UV', "Mirroring / ping pong effect applied to any UV Maps, on both X and Y axis", 8),
("NO_PP", 'Unmirror UV', "Removes the mirror / ping pong effect from any UV Maps, on both X and Y axis", 9),
], default=0)
SkipTexture: bpy.props.StringProperty(
name="Skip Texture", description="Any texture containing this string in its filename will NOT be assigned in any image texture when applying a material template (optional - leave blank if unneeded)", default="", maxlen=200)
BackfaceCamera: bpy.props.BoolProperty(
name="Camera", description="Affects whether backface culling is enabled for the active camera. In Blender 4.1 or lower, this setting controls the legacy 'Backface Culling' setting", default=True)
BackfaceShadow: bpy.props.BoolProperty(
name="Shadow", description="Affects whether backface culling is enabled for shadows. Only supported in Blender 4.2 or higher", default=True)
BackfaceLightProbe: bpy.props.BoolProperty(
name="Light Probe Volume", description="Affects whether backface culling is enabled for light probe volume capture. Only supported in Blender 4.2 or higher", default=True)
IsolateCollection: bpy.props.BoolProperty(
name="Isolate to Collection", description="If enabled, any isolated meshes are moved to a separate collection for easier finding", default=True)
IsolateTrait: bpy.props.EnumProperty(
name="Trait", description="The trait to look for in materials, in order to isolate their assigned faces into a separate object", items=[("transparent", 'Transparent', "Material uses alpha transparency, via Transparent BSDF or Principled BSDF's alpha slot.", 0),
("emissive", 'Emissive', "Material uses Emission shader or Principled BSDF's Emission slot", 1),
("animated", 'Animated', "Material uses an Image Sequence node, or contains animation data from keyframes and/or drivers", 2),
], default=0)
# FUNCTION DEFINITIONS
def display_msg_box(message="", title="Info", icon='INFO'):
''' Open a pop-up message box to notify the user of something '''
''' Example: '''
''' display_msg_box("This is a message", "This is a custom title", "ERROR") '''
def draw(self, context):
lines = message.split("\n")
for line in lines:
self.layout.label(text=line)
print(line)
bpy.context.window_manager.popup_menu(draw, title=title, icon=icon)
def update_alpha_settings(mat, alpha_mode, shadow_mode, alpha_threshold):
if bpy.app.version >= (4, 2, 0):
if alpha_mode != "CLIP":
# Remove the Math "Greater Than" node if one exists
for node in bpy.data.materials[mat].node_tree.nodes:
if node.type == 'MATH' and node.operation == "GREATER_THAN":
bpy.data.materials[mat].node_tree.nodes.remove(node)
break
if alpha_mode == "BLEND":
alpha_mode = "BLENDED"
elif alpha_mode == "CLIP":
greaterthan_node = None
img_tex_node = None
principled_node = None
mix_shader_node = None
# Search for existing nodes first
for node in bpy.data.materials[mat].node_tree.nodes:
if node.type == 'MATH' and node.operation == "GREATER_THAN":
greaterthan_node = node
continue
elif node.type == 'TEX_IMAGE' and node.image:
img_tex_node = node
continue
elif node.type == 'MIX_SHADER':
mix_shader_node = node
continue
elif node.type == "BSDF_PRINCIPLED":
principled_node = node
continue
if img_tex_node is not None and (principled_node is not None or mix_shader_node is not None):
if greaterthan_node is None:
greaterthan_node = bpy.data.materials[mat].node_tree.nodes.new(type='ShaderNodeMath')
greaterthan_node.operation = "GREATER_THAN"
greaterthan_node.location = (img_tex_node.location.x + 100, img_tex_node.location.y - 286)
bpy.data.materials[mat].node_tree.links.new(img_tex_node.outputs[1], greaterthan_node.inputs[0])
if principled_node is not None:
bpy.data.materials[mat].node_tree.links.new(greaterthan_node.outputs[0], principled_node.inputs[4])
elif mix_shader_node is not None:
bpy.data.materials[mat].node_tree.links.new(greaterthan_node.outputs[0], mix_shader_node.inputs[0])
alpha_mode = "DITHERED"
else:
alpha_mode = "DITHERED"
bpy.data.materials[mat].surface_render_method = alpha_mode
else:
bpy.data.materials[mat].blend_method = alpha_mode
bpy.data.materials[mat].shadow_method = shadow_mode
bpy.data.materials[mat].alpha_threshold = alpha_threshold
def recursive_node_search(startnode, end_node_type):
'''Searches into a node's links for a specific node type. Search ends if a node of the specified type is found, or if .'''
endnode = None
connecting_nodes = list()
for x in range(0, 5, 1):
for i in startnode.inputs:
if len(startnode.inputs) >= (x + 1):
for l in startnode.inputs[x].links:
connecting_nodes.append(
startnode.inputs[x].links[x].from_node)
else:
break
while endnode == None:
for x in range(0, 5, 1):
for n in connecting_nodes:
for i in n.inputs:
if len(startnode.inputs) >= (x + 1):
if len(n.inputs[x].links) > 0:
for l in n.inputs[x].links:
if n.inputs[x].links[x].from_node.type == end_node_type:
endnode = n.inputs[x].links[x].from_node
return endnode
else:
connecting_nodes.append(
n.inputs[x].links[x].from_node)
else:
continue
connecting_nodes.remove(n)
if len(connecting_nodes) < 2:
if len(connecting_nodes) < 1:
return None
elif len(connecting_nodes[0].inputs.links) < 1:
return None
else:
continue
def check_for_selected(objectOnly=False):
list_of_mats = set()
# Check if any objects are selected.
if len(bpy.context.selected_objects) > 0:
# Check if we're only checking for selected objects, regardless if the objects have any materials
if objectOnly == False:
# For each selected object
for obj in bpy.context.selected_objects:
if obj.type == "MESH":
for mat in obj.material_slots.keys():
list_of_mats.add(mat)
if len(list_of_mats) > 0:
return list_of_mats
else:
display_msg_box(
"There are no valid materials in the selected objects", "Error", "ERROR")
return False
else:
return False
def is_node_connected(material, node_to_check):
''' Checks if a specified node is actually connected (indirectly or directly) to the final Material Output'''
output_node = None
# Find the Material Output node
for node in material.node_tree.nodes:
if node.type == 'OUTPUT_MATERIAL':
output_node = node
break
if not output_node:
return False
# Function to recursively check connections
def check_connections(current_node):
if current_node == node_to_check:
return True
for input_socket in current_node.inputs:
for link in input_socket.links:
source_node = link.from_node
if check_connections(source_node):
return True
return False
# Start from the output node and check connections
return check_connections(output_node)
def find_faces_with_material(mesh_obj, material_name):
if material_name not in mesh_obj.data.materials:
return []
mat_index = mesh_obj.data.materials.find(material_name)
faces_with_material = [poly.index for poly in mesh_obj.data.polygons if poly.material_index == mat_index]
return faces_with_material
def separate_faces(mesh_obj, face_indices):
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.reveal()
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.mesh.select_mode(use_extend=False, use_expand=False, type='FACE')
bpy.ops.object.mode_set(mode='OBJECT')
for face_index in face_indices:
if face_index < len(mesh_obj.data.polygons):
mesh_obj.data.polygons[face_index].select = True
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.separate(type='SELECTED')
bpy.ops.object.mode_set(mode='OBJECT')
for obj in bpy.context.selected_objects:
bpy.context.view_layer.objects.active = obj
bpy.ops.object.material_slot_remove_unused()
mesh_obj.select_set(False)
bpy.context.view_layer.objects.active = bpy.context.selected_objects[0]
new_obj = bpy.context.active_object
return new_obj
# Bake Target copy operator
class CopyBakeTargetNode(bpy.types.Operator):
"""Copy the currently active Image Texture node and set it as a preset for baking."""
bl_idname = "material.copy_bake_target"
bl_label = "Copy"
bl_options = {'REGISTER'}
def execute(self, context):
# Check if there's actually an active object and active material
if bpy.context.active_object != None and bpy.context.active_object.active_material != None:
if len(bpy.context.active_object.material_slots) != 0:
if len(bpy.context.active_object.active_material.node_tree.nodes) != 0:
# Check if there's an active node
if bpy.context.active_object.active_material.node_tree.nodes.active != None:
# Check if the selected, active node is actually an Image Texture.
if bpy.context.active_object.active_material.node_tree.nodes.active.type == "TEX_IMAGE":
if bpy.context.active_object.active_material.node_tree.nodes.active.image != None:
bake_node_preset["image"] = bpy.context.active_object.active_material.node_tree.nodes.active.image.name
bake_node_preset["interpolation"] = bpy.context.active_object.active_material.node_tree.nodes.active.interpolation
bake_node_preset["projection"] = bpy.context.active_object.active_material.node_tree.nodes.active.projection
bake_node_preset["projection_blend"] = bpy.context.active_object.active_material.node_tree.nodes.active.projection_blend
bake_node_preset["extension"] = bpy.context.active_object.active_material.node_tree.nodes.active.extension
else:
display_msg_box(
"There is no active Image Texture node. Click on an Image Texture node to set it as active first", "Error", "ERROR")
else:
display_msg_box(
"The active material has no nodes. Select a valid material with at least one Image Texture node", "Error", "ERROR")
else:
display_msg_box(
"There are no valid materials in the active mesh object", "Error", "ERROR")
else:
display_msg_box(
"There is no active mesh object. Click on a mesh object to set it as active first", "Error", "ERROR")
return {'FINISHED'}
# Bake Target paste operator
class PasteBakeTargetNode(bpy.types.Operator):
"""Paste the Bake Target Node in all materials in selected objects, using the node settings previously copied with Copy button"""
bl_idname = "material.paste_bake_target"
bl_label = "Paste"
bl_options = {'REGISTER'}
def execute(self, context):
num_processed = 0
list_of_mats = check_for_selected()
# Check if any objects are selected.
if list_of_mats != False:
# Check if an image texture has actually been copied yet
if bake_node_preset["image"] != "":
# For each material in selected object
for mat in list_of_mats:
# Find Material Output node
reference_node = None
for node in bpy.data.materials[mat].node_tree.nodes:
if node.type == "OUTPUT_MATERIAL":
reference_node = node
break
# If no Material Output node exists, look for an alternative reference node instead
if reference_node is None:
for node in bpy.data.materials[mat].node_tree.nodes:
if node.type == "BSDF_PRINCIPLED" or node.type == "EMISSION":
reference_node = node
break
# If reference node was found:
if reference_node != None:
new_image_node = None
bake_target_exists = False
# Check if Bake Target Node already exists. If so, reset it.
for node in bpy.data.materials[mat].node_tree.nodes:
node.select = False
if "Bake Target Node" in node.name:
new_image_node = node
bake_target_exists = True
break
if not bake_target_exists:
# Create Image Texture node if Bake Target Node doesn't already exist
new_image_node = bpy.data.materials[mat].node_tree.nodes.new(
'ShaderNodeTexImage')
new_image_node.image = bpy.data.images[bake_node_preset["image"]]
new_image_node.location = mathutils.Vector(
((reference_node.location[0] + 180), (reference_node.location[1])))
new_image_node.interpolation = bake_node_preset["interpolation"]
new_image_node.projection = bake_node_preset["projection"]
new_image_node.projection_blend = bake_node_preset["projection_blend"]
new_image_node.extension = bake_node_preset["extension"]
new_image_node.color = bpy.context.scene.MatBatchProperties.BakeTargetNodeColor
new_image_node.use_custom_color = bpy.context.scene.MatBatchProperties.BakeTargetNodeColorEnable
new_image_node.name = "Bake Target Node"
new_image_node.label = "Bake Target"
new_image_node.select = True
bpy.data.materials[mat].node_tree.nodes.active = new_image_node
num_processed += 1
display_msg_box(
f'Created bake target in {num_processed} material(s).', 'Info', 'INFO')
else:
display_msg_box(
"There is no currently set Bake Target. Use the Copy button first to set one", "Error", "ERROR")
return {'FINISHED'}
# Bake Target delete operator
class DeleteBakeTargetNode(bpy.types.Operator):
"""Delete the Bake Target Node, if present, in all materials in selected objects"""
bl_idname = "material.delete_bake_target"
bl_label = "Delete"
bl_options = {'REGISTER'}
def execute(self, context):
num_processed = 0
list_of_mats = check_for_selected()
# Check if any objects are selected.
if list_of_mats != False:
if bake_node_preset["image"] != "":
# For each material in selected object
for mat in list_of_mats:
# Check if Bake Target Node already exists. If so, delete it.
for node in bpy.data.materials[mat].node_tree.nodes:
if "Bake Target Node" in node.name:
bpy.data.materials[mat].node_tree.nodes.remove(
node)
num_processed += 1
break
display_msg_box(
f'Deleted {num_processed} bake target node(s).', 'Info', 'INFO')
else:
display_msg_box(
"There is no currently set Bake Target. Use the Copy button first to set one", "Error", "ERROR")
return {'FINISHED'}
# Assign UV Map Node operator
class AssignUVMapNode(bpy.types.Operator):
"""Assign a UV Map node to any Image Texture that satisfies the entered Filter, in all materials in selected objects"""
bl_idname = "material.assign_uv_map_node"
bl_label = "Assign UV Map Node"
bl_options = {'REGISTER'}
def execute(self, context):
num_processed = 0
list_of_mats = check_for_selected()
# Check if any objects are selected.
if list_of_mats != False:
# For each material in selected object
for mat in list_of_mats:
nodetree = bpy.data.materials[mat].node_tree
links = bpy.data.materials[mat].node_tree.links
# Look for Image Texture nodes
for node in nodetree.nodes:
new_UV_node = None
reference_node = None
if node.type == "TEX_IMAGE" and node.image:
# Skip if it's a Bake Target node
if node.label == "Bake Target":
continue
# Check if Image Texture is in the user's entered format
if node.image.file_format == bpy.context.scene.MatBatchProperties.UVMapNodeExtensionFilter:
# Check if Image Texture already has a node connected to it
if node.inputs[0].links:
# If node connected to it is a UV Map node...
if node.inputs[0].links[0].from_node.type == "UVMAP":
# Delete the old UV Map node
nodetree.nodes.remove(
node.inputs[0].links[0].from_node)
reference_node = node
# If the Image Texture has some other kind of node connected... recursively search to find the closest UV Map node
else:
foundnode = recursive_node_search(
node, "UVMAP")
if foundnode:
reference_node = foundnode.outputs[0].links[0].to_node
nodetree.nodes.remove(
foundnode)
else:
reference_node = node
else:
reference_node = node
# Create new UV Map node
new_UV_node = nodetree.nodes.new(
"ShaderNodeUVMap")
new_UV_node.name = "Batch UV Map"
new_UV_node.uv_map = bpy.context.scene.MatBatchProperties.UVMapNodeTarget
new_UV_node.location = mathutils.Vector(
((reference_node.location[0] - 200), (reference_node.location[1] - 150)))
nodetree.links.new(
new_UV_node.outputs[0], reference_node.inputs[0])
num_processed += 1
continue
display_msg_box(
f'Created and assigned {num_processed} UV Map node(s).', 'Info', 'INFO')
return {'FINISHED'}
# Overwrite UV Slot Name operator
class OverwriteUVSlotName(bpy.types.Operator):
"""Using the specified UV Map name above, this button will overwrite the name of the UV Map in the specified UV slot, in all selected objects. If UV Map slot doesn't exist, a new UV Map will be created with that name"""
bl_idname = "object.overwrite_uv_slot_name"
bl_label = "Overwrite UV Slot Name"
bl_options = {'REGISTER'}
def execute(self, context):
num_processed = 0
# Check if any objects are selected
if check_for_selected(True) != False:
# For each selected object
for obj in bpy.context.selected_objects:
if obj.type == "MESH":
mesh = obj.data
uvslots = mesh.uv_layers
uvslot_index = int(
bpy.context.scene.MatBatchProperties.UVSlotIndex)
uvname = bpy.context.scene.MatBatchProperties.UVMapNodeTarget
counter = 0
for slot in uvslots:
if slot.name == uvname:
if counter != uvslot_index - 1:
slot.name = slot.name + ".001"
else:
counter += 1
if len(uvslots) == 0 and uvslot_index == 1:
uvslots.new(
name=uvname)
elif len(uvslots) == 1 and uvslot_index == 2:
uvslots.new(
name=uvname)
elif len(uvslots) == 0 and uvslot_index == 2:
uvslots.new(
name=uvname + ".001")
uvslots.new(
name=uvname)
elif uvslots[uvslot_index-1] != None:
uvslots[uvslot_index -
1].name = uvname
num_processed += 1
obj.data.update()
display_msg_box(
f'Renamed the UV map layer for {num_processed} object(s).', 'Info', 'INFO')
return {'FINISHED'}
# Set UV Slot as Active opterator
class SetUVSlotAsActive(bpy.types.Operator):
"""Sets the currently selected UV Slot above as the 'active' slot in all selected objects. Does not modify the UV map name"""
bl_idname = "object.set_uv_slot_as_active"
bl_label = "Set UV Slot as Active"
bl_options = {'REGISTER'}
def execute(self, context):
num_processed = 0
# Check if any objects are selected
if check_for_selected(True) != False:
# For each selected object
for obj in bpy.context.selected_objects:
if obj.type == "MESH":
mesh = obj.data
uvslots = mesh.uv_layers
uvslot_index = int(
bpy.context.scene.MatBatchProperties.UVSlotIndex)
if len(uvslots) > 0:
uvslots.active = uvslots[uvslot_index - 1]
num_processed += 1
obj.data.update()
display_msg_box(
f'Set the active UV slot for {num_processed} object(s).', 'Info', 'INFO')
return {'FINISHED'}
# Assign Vertex Color to Nodes operator
class AssignVCToNodes(bpy.types.Operator):
"""Assign the Vertex Color name above to all Color Attribute nodes, in all materials in selected objects"""
bl_idname = "material.assign_vc_to_nodes"
bl_label = "Assign Name to Color Nodes"
bl_options = {'REGISTER'}
def execute(self, context):
num_processed = 0
list_of_mats = check_for_selected()
# Check if any objects are selected.
if list_of_mats != False:
# For each selected object
for obj in bpy.context.selected_objects:
if obj.type == "MESH":
num_processed += 1
# For each material in selected object
for mat in list_of_mats:
for node in bpy.data.materials[mat].node_tree.nodes:
if node.type == "VERTEX_COLOR":
node.layer_name = bpy.context.scene.MatBatchProperties.VCName
elif node.type == "ATTRIBUTE":
node.attribute_name = bpy.context.scene.MatBatchProperties.VCName
obj.data.update()
display_msg_box(
f'Assigned vertex color layer in {num_processed} object(s).', 'Info', 'INFO')
return {'FINISHED'}
# Rename Vertex Color Slot operator
class RenameVertexColorSlot(bpy.types.Operator):
"""Rename the first Vertex Color slot in all selected objects, using the name specified above"""
bl_idname = "object.rename_vertex_color"
bl_label = "Rename Vertex Color Slot 1"
bl_options = {'REGISTER'}
def execute(self, context):
num_processed = 0
# Blender 3.2 renamed "vertex colors" to "color attributes," so let's check the version beforehand
useColorAttributes = (bpy.app.version >= (3, 2, 0))
# Check if any objects are selected
if check_for_selected(True) != False:
# For each selected object
for obj in bpy.context.selected_objects:
if obj.type == "MESH":
mesh = obj.data
if useColorAttributes:
vcslots = mesh.color_attributes
else:
vcslots = mesh.vertex_colors
vcname = bpy.context.scene.MatBatchProperties.VCName
if len(vcslots) > 0:
vcslots[0].name = vcname
else:
if useColorAttributes:
vcslots.new(name=vcname, type="FLOAT_COLOR",
domain="POINT")
# vcslots.new(name=vcname, type="BYTE_COLOR",
# domain="CORNER")
else:
vcslots.new(name=vcname)
num_processed += 1
obj.data.update()
display_msg_box(
f'Renamed {num_processed} vertex color slot(s).', 'Info', 'INFO')
return {'FINISHED'}
# Convert Vertex Color operator
class ConvertVertexColor(bpy.types.Operator):
"""Converts the data type of the first Color Attribute slot in all selected objects, between 'Face Corner Byte Color' and 'Vertex Color'"""
bl_idname = "object.convert_vertex_color"
bl_label = "Convert Vertex Color Slot 1"
bl_options = {'REGISTER'}
def execute(self, context):
# Blender 3.2 renamed "vertex colors" to "color attributes," so let's check the version beforehand
useColorAttributes = (bpy.app.version >= (3, 2, 0))
if not useColorAttributes:
display_msg_box(
f'This feature is only available in Blender 3.2 or higher.', 'Error', 'ERROR')
return {'FINISHED'}
num_processed = 0
# Check if any objects are selected
if check_for_selected(True) != False:
# For each selected object
for obj in bpy.context.selected_objects:
if obj.type == "MESH":
mesh = obj.data
vcslots = mesh.color_attributes
vcname = bpy.context.scene.MatBatchProperties.VCName
if len(vcslots) == 1:
if vcslots[0].data_type == "FLOAT_COLOR":
vcslots.remove(vcslots[0])
vcslots.new(name=vcname, type="BYTE_COLOR",
domain="CORNER")
elif vcslots[0].data_type == "BYTE_COLOR":
vcslots.remove(vcslots[0])
vcslots.new(name=vcname, type="FLOAT_COLOR",
domain="POINT")
num_processed += 1
obj.data.update()
display_msg_box(
f'Converted {num_processed} color attribute slot(s).', 'Info', 'INFO')
return {'FINISHED'}
# Set Blend Mode operator
class SetBlendMode(bpy.types.Operator):
"""Sets the currently selected Blend Mode above as the Blend & Shadow Mode in all materials, in all selected objects"""
bl_idname = "material.set_blend_mode"
bl_label = "Set Blend Mode"
bl_options = {'REGISTER'}
def execute(self, context):
alpha_mode = bpy.context.scene.MatBatchProperties.AlphaBlendMode
shadow_mode = bpy.context.scene.MatBatchProperties.AlphaBlendMode
filter_mode = bpy.context.scene.MatBatchProperties.AlphaBlendFilter
alpha_threshold = bpy.context.scene.MatBatchProperties.AlphaThreshold
principled_alpha_slot = 21 if bpy.app.version < (4, 0, 0) else 4
num_processed = 0
if alpha_mode == "BLEND":
shadow_mode = "CLIP"
list_of_mats = check_for_selected()
# Check if any objects are selected.
if list_of_mats != False:
# For each selected object
for obj in bpy.context.selected_objects:
if obj.type == "MESH":
# For each material in selected object
for mat in list_of_mats:
principled_nodes = []
for node in bpy.data.materials[mat].node_tree.nodes:
if node.type == "BSDF_PRINCIPLED":
principled_nodes.append(node)
# If user also wants to remove any alpha from the Principled node itself too
if bpy.context.scene.MatBatchProperties.AlphaPrincipledRemove == True and alpha_mode == "OPAQUE":
for node in principled_nodes:
if len(node.inputs[principled_alpha_slot].links) > 0:
bpy.data.materials[mat].node_tree.links.remove(
node.inputs[principled_alpha_slot].links[0])
node.inputs[principled_alpha_slot].default_value = 1.0
# Filter 1 - Principled BSDF with Alpha
if filter_mode == "PRINCIPLEDNODE":
for node in bpy.data.materials[mat].node_tree.nodes:
if node.type == "BSDF_PRINCIPLED":
if len(node.inputs[principled_alpha_slot].links) > 0:
update_alpha_settings(mat, alpha_mode, shadow_mode, alpha_threshold)
num_processed += 1
break
else:
if node.inputs[principled_alpha_slot].default_value < 1.0:
update_alpha_settings(mat, alpha_mode, shadow_mode, alpha_threshold)
num_processed += 1
break
# Filter 2 - Transparent BSDF
elif filter_mode == "TRANSPARENTNODE":
for node in bpy.data.materials[mat].node_tree.nodes:
update_alpha_settings(mat, alpha_mode, shadow_mode, alpha_threshold)
num_processed += 1
break
else:
update_alpha_settings(mat, alpha_mode, shadow_mode, alpha_threshold)
num_processed += 1
continue
obj.data.update()
display_msg_box(
f'Updated alpha settings for {str(num_processed)} material(s).', 'Info', 'INFO')
return {'FINISHED'}
# Copy Node Settings operator
class SetAsTemplateNode(bpy.types.Operator):
"""Stores the currently active, selected node as a template"""
bl_idname = "material.set_as_template_node"
bl_label = "Set as Template Node"
bl_options = {'REGISTER'}
def execute(self, context):
global node_unify_settings
node_unify_settings = {
"name": "",
"type": "",
"material": ""
}
# Check if there's an active object
if bpy.context.active_object != None:
# Check if there's an active node
if bpy.context.active_object.active_material.node_tree.nodes.active != None:
active_node = bpy.context.active_object.active_material.node_tree.nodes.active
node_unify_settings["name"] = active_node.name
node_unify_settings["type"] = active_node.type
node_unify_settings["material"] = bpy.context.active_object.active_material.name
bpy.context.scene.MatBatchProperties.SavedNodeName = active_node.name
bpy.context.scene.MatBatchProperties.SavedNodeType = active_node.bl_label
else:
display_msg_box(
"There is no active node. Click on a node to set one as active", "Error", "ERROR")
else:
display_msg_box(
"There is no active mesh object. Click on a mesh object to set one as active", "Error", "ERROR")
return {'FINISHED'}
# Unify Node Settings operator
class UnifyNodeSettings(bpy.types.Operator):
"""Searches for all nodes of the same type, in all materials on selected objects, and copies the template node's settings into those other nodes' settings. The original template node is not modified and must still exist"""
bl_idname = "material.unify_node_settings"
bl_label = "Unify Node Settings"
bl_options = {'REGISTER'}
def execute(self, context):
num_processed = 0
node_type = node_unify_settings["type"]
# Check if template node's material still exists:
if bpy.data.materials.get(node_unify_settings["material"]) != None:
# Check if template node still exists:
if bpy.data.materials[node_unify_settings["material"]].node_tree.nodes.get(node_unify_settings["name"]) != None:
template_node = bpy.data.materials[node_unify_settings["material"]
].node_tree.nodes[node_unify_settings["name"]]
list_of_mats = check_for_selected()
# Check if any objects are selected.
if list_of_mats != False:
# Check if there are any previously copied node settings
if node_unify_settings["name"] != "":
# For each selected object
for obj in bpy.context.selected_objects:
if obj.type == "MESH":
num_processed += 1
# For each material in selected object
for mat in list_of_mats:
valid_nodes = []
for node in bpy.data.materials[mat].node_tree.nodes:
# Check if node is of the saved type
if node.type == node_type:
# Check if a Label Filter was specified
if bpy.context.scene.MatBatchProperties.UnifyFilterLabel != "":
if node.label == bpy.context.scene.MatBatchProperties.UnifyFilterLabel:
valid_nodes.append(node)
else:
continue
else:
valid_nodes.append(node)
for node in valid_nodes:
# Copy and paste inputs from template node
input_counter = 0
for i in node.inputs:
if hasattr(i, "default_value") and hasattr(template_node.inputs[input_counter], "default_value"):
i.default_value = template_node.inputs[
input_counter].default_value
input_counter += 1
# Copy and paste properties from template node, but exclude the properties contained in a "do not use" list
property_list = list(
template_node.bl_rna.properties.keys())
new_property_list = list()
do_not_use = ['rna_type', 'type', 'location', 'width', 'width_hidden', 'height', 'dimensions', 'name', 'label', 'inputs', 'outputs', 'internal_links', 'parent', 'use_custom_color', 'color', 'select', 'show_options',
'show_preview', 'hide', 'mute', 'show_texture', 'bl_idname', 'bl_label', 'bl_description', 'bl_icon', 'bl_static_type', 'bl_width_default', 'bl_width_min', 'bl_width_max', 'bl_height_default', 'bl_height_min', 'bl_height_max']
for prop in property_list:
if prop not in do_not_use:
if node.is_property_readonly(prop) == False:
new_property_list.append(
prop)
for prop in new_property_list:
setattr(
node, prop, eval(f"template_node.{prop}"))
else:
display_msg_box(
"You haven't set a a template yet. Use the Set as Template button to set one.", "Error", "ERROR")
else:
display_msg_box(
"The template node no longer exists. Use the Set as Template button set a new one", "Error", "ERROR")
else:
display_msg_box(
"The template node's parent material no longer exists. Use the Set as Template button set a new one", "Error", "ERROR")
display_msg_box(
f'Applied unified node settings in {num_processed} object(s).', 'Info', 'INFO')
return {'FINISHED'}
# Shader Switch operator
class SwitchShader(bpy.types.Operator):
"""Finds all Principled BSDF or Emission shader nodes, in all materials in all selected objects, and switches them to the shader selected above"""
bl_idname = "material.switch_shader"
bl_label = "Switch Shader"
bl_options = {'REGISTER'}
def execute(self, context):
num_processed = 0
list_of_mats = check_for_selected()
# Check if any objects are selected.
if list_of_mats != False:
old_shader_type = None
target_shader_type = bpy.context.scene.MatBatchProperties.SwitchShaderTarget
if target_shader_type == "EMISSION": # If user wants to switch to Emission
old_shader_type = "BSDF_PRINCIPLED"
else:
old_shader_type = "EMISSION"
# For each selected object
for obj in bpy.context.selected_objects:
if obj.type == "MESH":
# For each material in selected object
for mat in list_of_mats:
material = bpy.data.materials[mat]
# Find the other shader
old_shaders = []
for node in bpy.data.materials[mat].node_tree.nodes:
if node.type == old_shader_type: