#!BPY
"""
Name: \'Material by Element\'
Blender: 262
Group: \'Material\'
Tooltip: \'Material by Element\'
"""
import bpy
import random
import string
print("MaterialByElement:") #to test output...
scena = bpy.context.scene #active scene
contesto = bpy.context #context
N=8 #n. of material you want to be created
K=40 #KAOS - N*5 gives more contrast - N*20 is regular
MATNAME="MatByEl_" #this constant will be use to choose materials\' name
#put here RGB values of main color:
#(N is calculated here do not recalcute it every time
r=0.2 #R
g=0.01 #G
b=0.02 #B
i = 0 #reset counter
mats=bpy.data.materials
obj=scena.objects.active #makes it active
objName=obj.name[0:obj.name.find(\'.\')] #take the first part of object\'s name
#blender usually give a name to the separated part
#taking "name"+"."+progressive number
bpy.ops.object.editmode_toggle() #enters in edit mode
bpy.ops.mesh.separate(type=\'LOOSE\') #separate it by loose parts
bpy.ops.object.editmode_toggle() #exit edit mode
#unlink all materials and deletes them
for matter in mats:
m_name=matter.name
if m_name.find(MATNAME) != -1:
print(m_name+" deleted") #for debugging purposes
matter.user_clear() #unlink
bpy.data.materials.remove(matter) #remove "matter" from materials slot
i+=1
i=0 #reset counter
#creates new material set
for i in range(0,N):
k=bpy.data.materials.new(MATNAME+"_"+str(i))
#this is to have more difference between objects
if i%2==0:
k.diffuse_color=(r+(i/K), g+(i/K), b+(i/K))
else:
k.diffuse_color=(r-(i/K), g-(i/K), b-(i/K))
matter=bpy.data.materials #gets material list
bpy.ops.object.select_pattern(pattern=objName+"*", case_sensitive=True, extend=True)
for obj in contesto.selected_objects: #for every object in selection
scena.objects.active = obj #makes it active
for mat in obj.material_slots:
bpy.ops.object.material_slot_remove() #remove all materials
bpy.ops.object.material_slot_add() #add ONE material
obj.data.materials[0]=matter[random.randrange(0,N-1)] #assign one of the N materials