-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathfunctions.py
2130 lines (1701 loc) · 80.9 KB
/
functions.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 bpy
import re
import os
from types import SimpleNamespace
from math import degrees
from .enum_values import *
from .preferences import *
# -----------------------------------------------------------------------------
# utility functions
def mu_ui_col_split(layout, factor=0.02):
spl = layout.split(factor=factor)
spl.column()
spl2 = spl.column().split(factor=1-factor/(1-factor))
return spl2.column()
def mu_assign_material_slots(object, material_list):
"""Given an object and a list of material names, removes all material slots from the object
adds new ones for each material in the material list,
adds the materials to the slots as well."""
scene = bpy.context.scene
active_object = bpy.context.active_object
bpy.context.view_layer.objects.active = object
# Remove all current material slots
# By looping until the material slots list is empty
while len(object.material_slots) != 0:
bpy.ops.object.material_slot_remove()
# re-add them and assign material
i = 0
for mat in material_list:
material = bpy.data.materials[mat]
object.data.materials.append(material)
i += 1
# restore active object:
bpy.context.view_layer.objects.active = active_object
def mu_assign_to_data(object, material, index, edit_mode, all = True):
"""Assign the material to the object data (polygons/splines)"""
if object.type == 'MESH':
# now assign the material to the mesh
mesh = object.data
if all:
for poly in mesh.polygons:
poly.material_index = index
else:
for poly in mesh.polygons:
if poly.select:
poly.material_index = index
mesh.update()
elif object.type in {'CURVE', 'SURFACE', 'TEXT'}:
bpy.ops.object.mode_set(mode = 'EDIT') # This only works in Edit mode
# If operator was run in Object mode
if not edit_mode:
# Select everything in Edit mode
bpy.ops.curve.select_all(action = 'SELECT')
# Assign material of the current slot to selection
bpy.ops.object.material_slot_assign()
if not edit_mode:
bpy.ops.object.mode_set(mode = 'OBJECT')
def mu_new_material_name(material):
"""Generate a new material name, if it exists: append a suitable suffix to it"""
for mat in bpy.data.materials:
name = mat.name
if (name == material):
try:
base, suffix = name.rsplit('.', 1)
# trigger the exception
num = int(suffix, 10)
material = base + "." + '%03d' % (num + 1)
except ValueError:
material = material + ".001"
return material
def mu_clear_materials(object):
"""Clear out all the material slots for the current object"""
for mat in object.material_slots:
bpy.ops.object.material_slot_remove()
def mu_assign_material(self, material_name = "Default", override_type = 'APPEND_MATERIAL', link_override = 'KEEP'):
"""Assign the defined material to selected polygons/objects"""
# get active object so we can restore it later
active_object = bpy.context.active_object
edit_mode = False
all_polygons = True
if (not active_object is None) and active_object.mode == 'EDIT':
edit_mode = True
all_polygons = False
bpy.ops.object.mode_set()
# check if material exists, if it doesn't then create it
found = False
for material in bpy.data.materials:
if material.name == material_name:
target = material
found = True
break
if not found:
target = bpy.data.materials.new(mu_new_material_name(material_name))
target.use_nodes = True
index = 0
objects = bpy.context.selected_editable_objects
for obj in objects:
# Apparently selected_editable_objects includes objects as cameras etc
if not obj.type in {'MESH', 'CURVE', 'SURFACE', 'FONT', 'META', 'GPENCIL'}:
continue
if obj.type == 'GPENCIL':
if not target.is_grease_pencil:
continue
elif target.is_grease_pencil:
continue
# set the active object to our object
scene = bpy.context.scene
bpy.context.view_layer.objects.active = obj
if link_override == 'KEEP':
if len(obj.material_slots) > 0:
link = obj.material_slots[0].link
else:
link = 'DATA'
else:
link = link_override
# If we should override all current material slots
if override_type == 'OVERRIDE_ALL' or obj.type == 'META':
# If there's more than one slot, Clear out all the material slots
if len(obj.material_slots) > 1:
mu_clear_materials(obj)
# If there's no slots left/never was one, add a slot
if len(obj.material_slots) == 0:
bpy.ops.object.material_slot_add()
# Assign the material to that slot
obj.material_slots[0].link = link
obj.material_slots[0].material = target
if obj.type == 'META':
self.report({'INFO'}, "Meta balls only support one material, all other materials gets overridden!")
# If we should override each material slot
elif override_type == 'OVERRIDE_SLOTS':
i = 0
# go through each slot
for material in obj.material_slots:
# assign the target material to current slot
if not link_override == 'KEEP':
obj.material_slots[i].link = link
obj.material_slots[i].material = target
i += 1
elif override_type == 'OVERRIDE_CURRENT':
active_slot = obj.active_material_index
if len(obj.material_slots) == 0:
self.report({'INFO'}, 'No material slots found! A material slot was added!')
bpy.ops.object.material_slot_add()
obj.material_slots[active_slot].material = target
# if we should keep the material slots and just append the selected material (if not already assigned)
elif override_type == 'APPEND_MATERIAL':
found = False
i = 0
material_slots = obj.material_slots
if (obj.data.users > 1) and (len(material_slots) >= 1 and material_slots[0].link == 'OBJECT'):
self.report({'WARNING'}, 'Append material is not recommended for linked duplicates! ' +
'Unwanted results might happen!')
# check material slots for material_name materia
for material in material_slots:
if material.name == material_name:
found = True
index = i
# make slot active
obj.active_material_index = i
break
i += 1
if not found:
# In Edit mode, or if there's not a slot, append the assigned material
# If we're overriding, there's currently no materials at all,
# so after this there will be 1
# If not, this adds another slot with the assigned material
index = len(obj.material_slots)
bpy.ops.object.material_slot_add()
obj.material_slots[index].link = link
obj.material_slots[index].material = target
obj.active_material_index = index
if obj.type == 'GPENCIL':
self.report({'WARNING'},
"Material not assigned to Grease Pencil Stroke! Only appended to object!")
else:
mu_assign_to_data(obj, target, index, edit_mode, all_polygons)
# We shouldn't risk unsetting the active object
if not active_object is None:
# restore the active object
bpy.context.view_layer.objects.active = active_object
if edit_mode:
bpy.ops.object.mode_set(mode='EDIT')
return {'FINISHED'}
def mu_select_by_material_name(self, find_material_name, extend_selection = False,
internal = False):
"""Searches through all objects, or the polygons/curves of the current object
to find and select objects/data with the desired material"""
# in object mode selects all objects with material find_material_name
# in edit mode selects all polygons with material find_material_name
find_material = bpy.data.materials.get(find_material_name)
if find_material is None:
self.report({'INFO'}, "The material " + find_material_name + " doesn't exists!")
return {'CANCELLED'} if not internal else -1
# check for edit_mode
edit_mode = False
found_material = False
scene = bpy.context.scene
# set selection mode to polygons
scene.tool_settings.mesh_select_mode = False, False, True
active_object = bpy.context.active_object
if (not active_object is None) and (active_object.mode == 'EDIT'):
edit_mode = True
if not edit_mode:
objects = bpy.context.visible_objects
for obj in objects:
if obj.type in {'MESH', 'CURVE', 'SURFACE', 'FONT', 'META'}:
mat_slots = obj.material_slots
for material in mat_slots:
if material.material == find_material:
obj.select_set(state = True)
found_material = True
# the active object may not have the material!
# set it to one that does!
bpy.context.view_layer.objects.active = obj
break
else:
if not extend_selection:
obj.select_set(state=False)
#deselect non-meshes
elif not extend_selection:
obj.select_set(state=False)
if not found_material:
if not internal:
self.report({'INFO'}, "No objects found with the material " +
find_material_name + "!")
return {'FINISHED'} if not internal else 0
else:
# it's edit_mode, so select the polygons
if active_object.type == 'MESH':
# if not extending the selection, deselect all first
# (Without this, edges/faces were still selected
# while the faces were deselected)
if not extend_selection:
bpy.ops.mesh.select_all(action = 'DESELECT')
objects = bpy.context.selected_editable_objects
for obj in objects:
bpy.context.view_layer.objects.active = obj
if obj.type == 'MESH':
bpy.ops.object.mode_set()
mat_slots = obj.material_slots
# same material can be on multiple slots
slot_indexes = []
i = 0
for material in mat_slots:
if material.material == find_material:
slot_indexes.append(i)
i += 1
mesh = obj.data
for poly in mesh.polygons:
if poly.material_index in slot_indexes:
poly.select = True
found_material = True
elif not extend_selection:
poly.select = False
mesh.update()
bpy.ops.object.mode_set(mode = 'EDIT')
elif obj.type in {'CURVE', 'SURFACE'}:
# For Curve objects, there can only be one material per spline
# and thus each spline is linked to one material slot.
# So to not have to care for different data structures
# for different curve types, we use the material slots
# and the built in selection methods
# (Technically, this should work for meshes as well)
mat_slots = obj.material_slots
i = 0
for material in mat_slots:
bpy.context.active_object.active_material_index = i
if material.material == find_material:
bpy.ops.object.material_slot_select()
found_material = True
elif not extend_selection:
bpy.ops.object.material_slot_deselect()
i += 1
elif not internal:
# Some object types are not supported
# mostly because don't really support selecting by material
# (like Font/Text objects)
# ore that they don't support multiple materials/are just "weird"
# (i.e. Meta balls)
self.report({'WARNING'}, "The type '"
+ obj.type
+ "' isn't supported in Edit mode by Material Utilities!")
#return {'CANCELLED'}
bpy.context.view_layer.objects.active = active_object
if (not found_material) and (not internal):
self.report({'INFO'},
"Material " + find_material_name + " isn't assigned to anything!")
return {'FINISHED'} if not internal else 1
def mu_copy_material_to_others(self):
"""Copy the material to of the current object to the other selected all_objects"""
# Currently uses the built-in method
active_object = bpy.context.active_object
if active_object.mode == 'EDIT':
bpy.ops.object.mode_set()
mesh = active_object.data
materials = active_object.material_slots.keys()
material_index = mesh.polygons[mesh.polygons.active].material_index
material = materials[material_index]
objects = bpy.context.selected_editable_objects
for obj in objects:
try:
mi = obj.material_slots.keys().index(material)
except ValueError:
mi = len(obj.material_slots)
obj.data.materials.append(bpy.data.materials[material])
obj.active_material_index = mi
for p in obj.data.polygons:
if p.select:
p.material_index = mi
bpy.ops.object.mode_set(mode = 'EDIT')
else:
bpy.ops.object.material_slot_copy()
return {'FINISHED'}
def mu_cleanmatslots(self, affect, selected_collection = ""):
"""Clean the material slots of the selected objects"""
# check for edit mode
edit_mode = False
active_object = bpy.context.active_object
if active_object is None:
if len(bpy.context.selected_editable_objects) > 0:
active_object = bpy.context.selected_editable_objects[0]
if affect == 'ACTIVE':
affect = 'SELECTED'
else:
self.report({'ERROR'},
"There are no selected objects! Cancelling!")
return {'CANCELLED'}
if active_object.mode == 'EDIT':
edit_mode = True
bpy.ops.object.mode_set()
objects = []
if affect == 'ACTIVE':
objects = [active_object]
elif affect == 'SELECTED':
objects = bpy.context.selected_editable_objects
elif affect == "ACTIVE_COLLECTION":
objects = bpy.context.collection.objects
elif affect == "SELECTED_COLLECTION":
objects = bpy.data.collections[selected_collection].objects
elif affect == 'SCENE':
objects = bpy.context.scene.objects
else: # affect == 'ALL'
objects = bpy.data.objects
for obj in objects:
used_mat_index = [] # we'll store used materials indices here
material_list = []
material_names = []
assigned_materials = []
materials = obj.material_slots.keys()
# Sanity check, thanks to luckychris (Issue #17)
if len(materials) == 0:
continue
if obj.type == 'MESH':
# check the polygons on the mesh to build a list of used materials
mesh = obj.data
for poly in mesh.polygons:
# get the material index for this face...
material_index = poly.material_index
if material_index >= len(materials):
poly.select = True
self.report({'ERROR'},
"A poly with an invalid material was found, this should not happen! Canceling!")
return {'CANCELLED'}
# indices will be lost: Store face mat use by name
current_mat = materials[material_index]
assigned_materials.append(current_mat)
# check if index is already listed as used or not
found = False
for mat in used_mat_index:
if mat == material_index:
found = True
if not found:
# add this index to the list
used_mat_index.append(material_index)
# re-assign the used materials to the mesh and leave out the unused
for u in used_mat_index:
material_list.append(materials[u])
# we'll need a list of names to get the face indices...
material_names.append(materials[u])
mu_assign_material_slots(obj, material_list)
# restore face indices:
i = 0
for poly in mesh.polygons:
material_index = material_names.index(assigned_materials[i])
poly.material_index = material_index
i += 1
elif obj.type in {'CURVE', 'SURFACE'}:
splines = obj.data.splines
for spline in splines:
# Get the material index of this spline
material_index = spline.material_index
# indices will be last: Store material use by name
current_mat = materials[material_index]
assigned_materials.append(current_mat)
# check if index is already listed as used or not
found = False
for mat in used_mat_index:
if mat == material_index:
found = True
if not found:
# add this index to the list
used_mat_index.append(material_index)
# re-assigned the used materials to the curve and leave out the unused
for u in used_mat_index:
material_list.append(materials[u])
# we'll need a list of names to get the face indices
material_names.append(materials[u])
mu_assign_material_slots(obj, material_list)
# restore spline indices
i = 0
for spline in splines:
material_index = material_names.index(assigned_materials[i])
spline.material_index = material_index
i += 1
else:
# Some object types are not supported
self.report({'WARNING'},
"The type '" + obj.type + "' isn't currently supported " +
"for Material slots cleaning by Material Utilities!")
if edit_mode:
bpy.ops.object.mode_set(mode='EDIT')
return {'FINISHED'}
def mu_remove_material(self, for_active_object = False):
"""Remove the active material slot from selected object(s)"""
if for_active_object:
bpy.ops.object.material_slot_remove()
else:
last_active = bpy.context.active_object
objects = bpy.context.selected_editable_objects
for obj in objects:
bpy.context.view_layer.objects.active = obj
bpy.ops.object.material_slot_remove()
bpy.context.view_layer.objects.active = last_active
return {'FINISHED'}
def mu_remove_all_materials(self, for_active_object = False):
"""Remove all material slots from selected object(s)"""
if for_active_object:
obj = bpy.context.active_object
# Clear out the material slots
obj.data.materials.clear()
else:
last_active = bpy.context.active_object
objects = bpy.context.selected_editable_objects
for obj in objects:
obj.data.materials.clear()
bpy.context.view_layer.objects.active = last_active
return {'FINISHED'}
def mu_do_replace_material(self, mat_org, mat_rep, all_objects=False, update_selection=False):
"""Replace one material with another material"""
if mat_org != mat_rep and None not in (mat_org, mat_rep):
if all_objects:
objs = bpy.data.objects
else:
objs = bpy.context.selected_editable_objects
for obj in objs:
if obj.type == 'MESH':
match = False
for mat in obj.material_slots:
if mat.material == mat_org:
mat.material = mat_rep
# Indicate which objects were affected
if update_selection:
obj.select_set(state = True)
match = True
if update_selection and not match:
obj.select_set(state = False)
def mu_do_replace_multiple_materials(self, mats_org_list, mats_rep_list,
all_objects=False, update_selection=False):
"""Take a list of materials, and replace each of them
with the matching one in the second list"""
mats_org_list_len = len(mats_org_list)
mats_rep_list_len = len(mats_rep_list)
if mats_org_list_len == 0:
self.report({'ERROR'},
"List of materials to replace is empty! Canceling!")
return {'CANCELLED'}
if mats_rep_list_len == 0:
self.report({'ERROR'},
"List of materials to replace with is empty! Canceling!")
return {'CANCELLED'}
mat_rep_last = mats_rep_list[0]
for i in range(mats_org_list_len):
mat_org = mats_org_list[i]
mat_rep = mat_rep_last if i >= mats_rep_list_len else mats_rep_list[i]
mu_do_replace_material(self, mat_org, mat_rep, all_objects, update_selection)
mat_rep_last = mat_rep
return {'FINISHED'}
def mu_replace_material(self, material_a, material_b, all_objects=False,
update_selection=False):
"""Replace one material with another material"""
# material_a is the name of original material
# material_b is the name of the material to replace it with
# 'all' will replace throughout the blend file
mat_org = bpy.data.materials.get(material_a)
mat_rep = bpy.data.materials.get(material_b)
mu_do_replace_material(self, mat_org, mat_rep, all_objects, update_selection)
return {'FINISHED'}
def mu_get_materials_as_list(self, material_str_list):
"""Take a list of material names as strings,
and return a list with matching materials"""
material_list = []
for mat_str in material_str_list:
mat = bpy.data.materials.get(mat_str)
if (mat is None):
self.report({'WARNING'},
"Could not find material '" + mat_str + "'! Skipping!")
else:
material_list.append(mat)
return material_list
def mu_replace_multiple_materials(self, materials_a, materials_b,
all_objects=False, update_selection=False):
"""Replace multiple materials with another material"""
# material_a is a text block with materials to replace
# material_b is a possible text block with materials to replace it with
# 'all' will replace throughout the blend file
mats_org_strlst = []
mats_rep_strlst = []
if not materials_a in bpy.data.texts.keys():
error_msg = "No text block name given" if materials_a == "" else "Couldn't find a text block called " + materials_a
self.report({'ERROR'},
error_msg + "! Canceling!")
return {'CANCELLED'}
mat_org_str = bpy.data.texts[materials_a].as_string()
mats_org_strlst = mat_org_str.split("\n")
if (materials_b != ""):
if not materials_a in bpy.data.texts.keys():
self.report({'ERROR'},
"Couldn't find a text block called " + materials_b + "! Canceling!")
return {'CANCELLED'}
mat_rep_str = bpy.data.texts[materials_b].as_string()
mats_rep_strlst = mat_rep_str.split("\n")
else:
mats_org_strlst_old = mats_org_strlst
mats_org_strlst = []
for mat in mats_org_strlst_old:
mat = mat.replace("\t", " ")
mats = re.split("\s\s+", mat)
mats_org_strlst.append(mats[0])
if len(mats) != 1:
mats_rep_strlst.append(mats[1])
mats_org_list = mu_get_materials_as_list(self, mats_org_strlst)
mats_rep_list = mu_get_materials_as_list(self, mats_rep_strlst)
mats_org_list_len = len(mats_org_list)
mats_rep_list_len = len(mats_rep_list)
if (mats_org_list_len != mats_rep_list_len):
self.report({'WARNING'},
"Mismatching length of material lists, \
unexpected results might occur! %d original materials, \
%d replacement materials" %
(mats_org_list_len, mats_rep_list_len))
return mu_do_replace_multiple_materials(self, mats_org_list, mats_rep_list,
all_objects, update_selection)
def mu_set_fake_user(self, fake_user, materials, selected_collection = ""):
"""Set the fake user flag for the objects material"""
if materials == 'ALL':
mats = (mat for mat in bpy.data.materials if mat.library is None)
elif materials == 'UNUSED':
mats = (mat for mat in bpy.data.materials if mat.library is None and mat.users == 0)
else:
mats = []
if materials == 'ACTIVE':
objs = [bpy.context.active_object]
elif materials == 'SELECTED':
objs = bpy.context.selected_objects
elif materials == "ACTIVE_COLLECTION":
objs = bpy.context.collection.objects
elif materials == "SELECTED_COLLECTION":
objs = bpy.data.collections[selected_collection].objects
elif materials == 'SCENE':
objs = bpy.context.scene.objects
else: # materials == 'USED'
objs = bpy.data.objects
# Maybe check for users > 0 instead?
mats = (mat for ob in objs
if hasattr(ob.data, "materials")
for mat in ob.data.materials
if mat.library is None)
if fake_user == 'TOGGLE':
done_mats = []
for mat in mats:
if not mat.name in done_mats:
mat.use_fake_user = not mat.use_fake_user
done_mats.append(mat.name)
else:
fake_user_val = fake_user == 'ON'
for mat in mats:
mat.use_fake_user = fake_user_val
for area in bpy.context.screen.areas:
if area.type in ('PROPERTIES', 'NODE_EDITOR'):
area.tag_redraw()
return {'FINISHED'}
def mu_change_material_link(self, link, affect, override_data_material = False,
selected_collection = "", unlink_old = False):
"""Change what the materials are linked to (Object or Data),
while keeping materials assigned"""
objects = []
if affect == "ACTIVE":
objects = [bpy.context.active_object]
elif affect == "SELECTED":
objects = bpy.context.selected_objects
elif affect == "ACTIVE_COLLECTION":
objects = bpy.context.collection.objects
elif affect == "SELECTED_COLLECTION":
objects = bpy.data.collections[selected_collection].objects
elif affect == 'Scene':
objects = bpy.context.scene.objects
elif affect == "ALL":
objects = bpy.data.objects
for object in objects:
index = 0
for slot in object.material_slots:
present_material = slot.material
if unlink_old:
slot.material = None
if link == 'TOGGLE':
slot.link = ('DATA' if slot.link == 'OBJECT' else 'OBJECT')
else:
slot.link = link
if slot.link == 'OBJECT':
override_data_material = True
elif slot.material is None:
override_data_material = True
elif not override_data_material:
self.report({'INFO'},
'The object Data for object ' + object.name_full
+ ' already had a material assigned '
+ 'to slot #' + str(index)
+ ' (' + slot.material.name + '), it was not overridden!')
if override_data_material:
slot.material = present_material
index = index + 1
return {'FINISHED'}
def mu_join_objects(self, materials):
"""Join objects together based on their material"""
for material in materials:
mu_select_by_material_name(self, material, False, True)
bpy.ops.object.join()
return {'FINISHED'}
def mu_set_auto_smooth(self, angle, affect, set_smooth_shading, selected_collection = ""):
"""Set Auto smooth values for selected objects"""
# Inspired by colkai
objects = []
objects_affected = 0
if affect == "ACTIVE":
objects = [bpy.context.active_object]
elif affect == "SELECTED":
objects = bpy.context.selected_editable_objects
elif affect == "ACTIVE_COLLECTION":
objects = bpy.context.collection.objects
elif affect == "SELECTED_COLLECTION":
objects = bpy.data.collections[selected_collection].objects
elif affect == 'Scene':
objects = bpy.context.scene.objects
elif affect == "ALL":
objects = bpy.data.objects
if len(objects) == 0:
self.report({'WARNING'}, 'No objects available to set Auto Smooth on')
return {'CANCELLED'}
for object in objects:
if object.type == "MESH":
if set_smooth_shading:
for poly in object.data.polygons:
poly.use_smooth = True
#bpy.ops.object.shade_smooth()
object.data.use_auto_smooth = 1
object.data.auto_smooth_angle = angle # 35 degrees as radians
objects_affected += 1
self.report({'INFO'},
'Auto smooth angle set to %.0f° on %d of %d objects' %
(degrees(angle), objects_affected, len(objects)))
return {'FINISHED'}
def mu_remove_unused_materials(self):
"""Remove any unused (zero users) materials"""
# By request by Hologram
count = 0
for mat in bpy.data.materials:
if mat.users == 0:
bpy.data.materials.remove(mat)
count += 1
self.report({'INFO'}, '%d unused materials were removed' %
(count))
return {'FINISHED'}
def mu_materials_filter_poll(self, material):
return not material.is_grease_pencil
def mu_get_filetype(filename):
"""Look at the filename to determine file type, map type, and colorspace"""
filename = filename.lower()
ext = os.path.splitext(filename)[1].strip('.')
type = 'NOT_IMG'
override_colorspace = False
colorspace = 'NA'
texture_map = 'UNKNOWN'
non_color = False
has_alpha = False
tagged_alpha = False
is_greyscale = False
ignore = False
invert = False
if ext == 'jpeg':
ext = 'jpg'
elif ext == 'tiff':
ext = 'tif'
if ext.upper() in mu_file_types:
type = ext.upper()
colorspace = mu_file_types[type]['colorspace']
override_colorspace = mu_file_types[type]['override_colorspace']
if 'albedo' in filename:
texture_map = 'ALBEDO'
elif 'diff' in filename:
texture_map = 'DIFFUSE'
elif 'rough' in filename:
texture_map = 'ROUGHNESS'
elif 'gloss' in filename:
texture_map = 'GLOSSINESS'
elif 'spec' in filename:
texture_map = 'SPECULAR'
elif 'refl' in filename:
texture_map = 'REFLECTION'
elif 'metal' in filename:
texture_map = 'METALNESS'
elif 'height' in filename:
texture_map = 'HEIGHT'
elif 'disp' in filename or 'dsp' in filename:
texture_map = 'DISPLACEMENT'
elif 'bump' in filename or 'bmp' in filename:
texture_map = 'BUMP'
elif 'nor' in filename or 'nrm' in filename:
texture_map = 'NORMAL'
elif 'col' in filename or 'base' in filename:
texture_map = 'COLOR'
elif 'alpha' in filename or 'opacity' in filename \
or 'transparent' in filename:
texture_map = 'ALPHA'
elif 'mask' in filename:
texture_map = 'MASK'
elif 'trans' in filename:
texture_map = 'TRANSMISSION'
elif 'emission' in filename:
texture_map = 'EMISSION'
elif 'ao' in filename or 'occlusion' in filename:
texture_map = 'AO'
elif 'render' in filename or 'sample' in filename \
or 'preview' in filename or '_sphere' in filename:
texture_map = 'RENDER'
if texture_map in mu_texture_map_options:
ignore = mu_texture_map_options[texture_map]['ignore'] if 'ignore' in mu_texture_map_options[texture_map] else False
if not ignore:
invert = mu_texture_map_options[texture_map]['invert'] if 'invert' in mu_texture_map_options[texture_map] else False
has_alpha = mu_texture_map_options[texture_map]['has_alpha']
non_color = mu_texture_map_options[texture_map]['non_color']
is_greyscale = mu_texture_map_options[texture_map]['is_greyscale']
if 'walpha' in filename or 'withalpha' in filename or 'with_alpha' in filename:
has_alpha = True
tagged_alpha = True
if override_colorspace:
if 'filmic' in filename:
colorspace = 'FILMIC_LOG' if 'log' in filename else 'FILMIC_sRGB'
elif 'acescg' in filename:
colorspace = 'ACEScg'
elif 'aces' in filename:
colorspace = 'ACES'
elif 'linear' in filename:
colorspace = 'LINEAR'
elif 'srgb' in filename:
colorspace = 'sRGB'
return SimpleNamespace(type=type, colorspace=colorspace,
map=texture_map, orig_map=texture_map,
override_colorspace=override_colorspace,
non_color=non_color,is_greyscale=is_greyscale,
has_alpha=has_alpha, tagged_alpha=tagged_alpha,
ignore=ignore, invert=invert)