July 01, 2011

adding faces to an existing mesh

update: use this, it uses BMesh:

this is old, deprecated code. with BMesh you don't have to enter object mode to update. be in objectmode before running this, or modify the code to do that for you.
import bpy

# start with adding a plane at 0,0,0  ,set 3d cursor to 0,0,0
bpy.ops.mesh.primitive_plane_add()
mplane = bpy.context.active_object

# in object mode 
if mplane.mode == 'EDIT':
    bpy.ops.object.mode_set(mode='OBJECT')

# add 4 verts
mplane.data.vertices.add(4)
mplane.data.vertices[-4].co = (1, -1, 1)
mplane.data.vertices[-3].co = (-1, -1, 1)
mplane.data.vertices[-2].co = (-1, 1, 1)
mplane.data.vertices[-1].co = (1, 1, 1)

for m in mplane.data.vertices:
    print(m.co)

print("mplane.data.faces - before")
for l in mplane.data.faces:
    print("face===")
    for em in l.vertices:
        print(em)
        
# add one face    
mplane.data.faces.add(1)
mplane.data.faces[-1].vertices_raw = [7,4,5,6]
mplane.data.update(calc_edges=True)

print("mplane.data.faces - after")
for l in mplane.data.faces:
    print("face===")
    for em in l.vertices:
        print(em)

print("num faces=", len(mplane.data.vertices))
print(mplane.data.faces[-1])