import bpy
import bmesh
def findDupImages():
perPath = {}
for img in bpy.data.images:
if img.filepath=='':
continue
q = perPath.get(img.filepath)
if q:
q["images"].append(img.name)
else:
q = { "filepath": img.filepath,
"images" : [img.name]
}
perPath[img.filepath] = q
return perPath
def rewriteTex(rewrite):
# do the textures
for tex in bpy.data.textures:
# print(tex.name)
if tex and tex.type=="IMAGE":
n1 = tex.image.name
n2 = rewrite.get(n1)
if (n2):
print("%s => %s" % (tex.name, n2))
tex.image = bpy.data.images[n2]
# this next bit condenses images that show up in the UV/image editor
for mesh in bpy.data.meshes:
bm = bmesh.new()
bm.from_mesh(mesh)
tl = bm.faces.layers.tex.active
if tl:
dirty=False
for f in bm.faces:
img = f[tl].image
if img:
n2 = rewrite.get(img.name)
if n2:
f[tl].image = bpy.data.images[n2]
dirty=True
if dirty:
bm.to_mesh(mesh)
def buildRewriteDict(perPath):
rval = {}
for path,q in perPath.items():
imgs = q["images"]
for idx in range(1,len(imgs)):
rval[imgs[idx]] = imgs[0]
return rval
def hasProblemImage(obj, dict):
if (obj.type!="MESH"):
print(obj.type)
return False
for m in obj.data.materials:
if (materialHasProblemImage(m, dict)):
return True
bm = bmesh.new()
bm.from_mesh(obj.data)
tl = bm.faces.layers.tex.active
# print(tl)
if tl:
for f in bm.faces:
img = f[tl].image
if img and dict.get(f[tl].image.name):
return True
return False
def materialHasProblemImage(m, dict):
for tex_ in m.texture_slots:
if (tex_ is None):
continue
tex = tex_.texture
if (tex.type=="IMAGE" and dict.get(tex.image.name)):
return True
return False
def selectProblemObjects(dict):
for obj in bpy.data.objects:
if (hasProblemImage(obj, dict)):
obj.select = True
#for img in bpy.data.images:
# print(img.name)
#print ("done")
perPath= findDupImages()
rewriteDict = buildRewriteDict(perPath)
print (rewriteDict)
selectProblemObjects(rewriteDict)
rewriteTex(rewriteDict)
|
Blender python API quick-start
Syntax highlighting by Pygments.