Here is the code I wrote to add a face to a mesh. The function takes an object and a bmesh derived from the object's mesh data (obj.data
), a list of vertices, uvs and the name of a texture/material. Using this data, the function adds a new face to the object.
The section where I am adding uvs is only slightly different to that in the example provided (see below). It is all written for Blender 2.67b. No idea if it works on older versions, but it's probably ok.
def mesh_append_face( obj, bm, vertex_list, uv_list, texture_name ):
# add vertices and uvs before creating the new face
for vert in vertex_list:
bm.verts.new( ( vert[0], vert[1], vert[2] ) )
bm.faces.new( ( bm.verts[i] for i in range( -len( vertex_list ), 0)) )
# add uvs to the new face
uv_layer = bm.loops.layers.uv.verify()
bm.faces.layers.tex.verify()
face = bm.faces[-1]
for i, loop in enumerate(face.loops):
uv = loop[uv_layer].uv
uv[0] = uv_list[i][0]
uv[1] = uv_list[i][1]
# assign material
try:
material_names = [ m.name for m in obj.data.materials ]
material_id = material_names.index(texture_name)
except ValueError:
obj.data.materials.append(bpy.data.materials[texture_name])
material_id = len(obj.data.materials) - 1
face.material_index = material_id
It is based on this example code from Text Editor
-> Templates
-> Python
-> Operator UV
:
def main(context):
obj = context.active_object
me = obj.data
bm = bmesh.from_edit_mesh(me)
uv_layer = bm.loops.layers.uv.verify()
bm.faces.layers.tex.verify() # currently blender needs both layers.
# adjust UVs
for f in bm.faces:
for l in f.loops:
luv = l[uv_layer]
if luv.select:
# apply the location of the vertex as a UV
luv.uv = l.vert.co.xy
bmesh.update_edit_mesh(me)