7
$\begingroup$

I need to change vertex position in a shapekey through python. Is it possible to do?

Right now i can only get vertices coordinates. But how to change the vertex coordinate of shapekey?

import bpy

obj1 = bpy.context.selected_objects[0]
for vert in obj1.data.vertices:
    print(vert.co)  # this is a vertex coord of the mesh

For example i want to change avertex coordinates of a ShapeKey "Key1". https://i.stack.imgur.com/ywBlg.png

$\endgroup$

2 Answers 2

6
$\begingroup$

Shape key coordinates live in a bmesh "layer"

I have included a copy of http://web.purplefrog.com/~thoth/blender/python-cookbook/explore-shape-keys.html here:

import bpy
import bmesh

def dump(mesh):

    bm = bmesh.new()
    bm.from_mesh(mesh)

    for key in bm.verts.layers.shape.keys():
        val = bm.verts.layers.shape.get(key)
        print("%s = %s" % (key,val) )
        sk=mesh.shape_keys.key_blocks[key]
        print("v=%f, f=%f" % ( sk.value, sk.frame))
        for i in range(len(bm.verts)):
            v = bm.verts[i]
            delta = v[val] - v.co
            if (delta.length > 0):
                print ( "v[%d]+%s" % ( i,delta) )

dump(bpy.context.active_object.data)

Code for creating and populating shape keys can be found at http://web.purplefrog.com/~thoth/blender/python-cookbook/shape-key-fin.html and I have extracted the most interesting bit here:

def addShapeKey(obj, i, nKeys, z1, z2, dTheta, thetaLag):
    kn = "phase %d"%i
    sk = obj.shape_key_add(kn)
    bm = bmesh.new()
    bm.from_mesh(obj.data)
    sl = bm.verts.layers.shape.get(kn)


    for u in range( math.floor(len(bm.verts) / 3)):
        t = math.pi*2*i/nKeys
        bm.verts[u*3][sl] = vert1For(u, t)
        bm.verts[u*3+1][sl] = vert2For(u, t, dTheta, z1)
        bm.verts[u*3+2][sl] = vert3For(u, t, dTheta, z2, thetaLag)

    bm.to_mesh(obj.data)
$\endgroup$
1
  • 3
    $\begingroup$ The Bmesh module is not required to access shape key data, the data path to the vertex coordinates in the standard API is Object.data.shape_keys.key_blocks['Key 1'].data[#].co (substitute Key 1 with the shape key name and # with the vertex index). $\endgroup$
    – CodeManX
    Sep 5, 2014 at 18:45
3
$\begingroup$

Thanks to all of you. CodeMax's line solved the issue! Just select some models with the same points count and make morphs.

https://i.stack.imgur.com/JSZHe.png

import bpy

objAct = bpy.context.scene.objects.active
for obj in bpy.context.selected_objects:
    if obj != objAct:
        shapeKey = objAct.shape_key_add(from_mix=False)
        shapeKey.name = obj.name

        for vert in obj.data.vertices:
            shapeKey.data[vert.index].co = vert.co
            #print(vert.co)  # this is a vertex coord of the mesh
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .