__author__ = 'thoth'
import bpy
import bmesh
def material_for_texture(fname):
img = bpy.data.images.load(fname)
tex = bpy.data.textures.new(fname, 'IMAGE')
tex.image = img
mat = bpy.data.materials.new(fname)
mat.texture_slots.add()
ts = mat.texture_slots[0]
ts.texture = tex
ts.texture_coords = 'UV'
ts.uv_layer = 'default'
return mat
def set_UV_editor_texture(mesh):
""" set the image for the face.tex layer on all the faces
so we have a rough idea of what the mesh will look like
in the 3D view's Texture render mode"""
# load the mesh data into a bmesh object
bm = bmesh.new()
bm.from_mesh(mesh)
bm.faces.ensure_lookup_table()
# Get the "tex" layer for the first UV map
# If you don't already have a UV map, why are you even calling this function?
tex_layer = bm.faces.layers.tex[mesh.uv_layers[0].name]
for i in range(len(bm.faces)):
# figure out which material this face uses
mi = bm.faces[i].material_index
mat = mesh.materials[mi]
# Assume that we want to use the image from the first texture slot;
# and assume that the material has a texture in that first slot;
# and assume that the texture is an image texture instead of a procedural texture.
# if any of several assumptions are wrong, this will explode
img = mat.texture_slots[0].texture.image
bm.faces[i][tex_layer].image = img
# copy the modified data into the mesh
bm.to_mesh(mesh)
fname = "/var/tmp/blender/mohawk-seal0001.png"
obj = bpy.context.active_object
mat = material_for_texture(fname)
if len(obj.data.materials)<1:
obj.data.materials.append(mat)
else:
obj.data.materials[0] = mat
set_UV_editor_texture(obj.data)
|
Blender python API quick-start
Syntax highlighting by Pygments.