import bpy
import bmesh
#
# This script shows how to apply an image to the faces of a cube.
#
def material_for_image(fname):
mat = bpy.data.materials.get(fname)
if mat is None:
img = bpy.data.images.load(fname)
# create a texture for the image
tex = bpy.data.textures.new(fname, 'IMAGE')
tex.image = img
# put the texture on a material with UV coordinates
mat = bpy.data.materials.new(fname)
mat.texture_slots.add()
mat.texture_slots[0].texture = tex
mat.texture_slots[0].texture_coords = 'UV'
mat.texture_slots[0].uv_layer = 'default'
return mat
#
def material_on_mesh(mesh, mat):
if len(mesh.materials) > 0:
mesh.materials[0] = mat
else:
mesh.materials.append(mat)
if len(mesh.uv_layers) < 1:
# if we don't yet have a UV layer, let's just throw in a default one.
# This will work fine for square faces, but anything else will need some work.
mesh.uv_textures.new("default")
#
def guess_image_for_material(mat):
"""guess an image which would be appropriate to use for the 3d view for this material"""
for tex_slot in mat.texture_slots:
if tex_slot.texture.type == 'IMAGE':
return tex_slot.texture.image
else:
print(tex_slot.texture.type)
def guess_image_for_mesh(mesh):
"""guess an image which would be appropriate to use for the 3d view for this mesh"""
for mat in mesh.materials:
img = guess_image_for_material(mat)
if img is not None:
return img
return None
def set_preview_tex(mesh):
"""put the image behind the UV layer for the times when you're using the Multitexture shader on the 3D view.
This is not critical for rendering, it's just nice for working in the 3D view."""
bm = bmesh.new()
bm.from_mesh(mesh)
tl = bm.faces.layers.tex.active
if tl:
for f in bm.faces:
f[tl].image = guess_image_for_material(mesh.materials[f.material_index])
bm.to_mesh(mesh)
#
m1 = material_for_image("/var/tmp/bear.png")
for obj in bpy.context.scene.objects:
if obj.select:
material_on_mesh(obj.data, m1)
set_preview_tex(obj.data)
|
Blender python API quick-start
Syntax highlighting by Pygments.