Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blender scripting: Indices of selected vertices

Tags:

python

blender

Q: In Blender 2.64, I have a mesh in edit mode with some vertices selected. How can I get or generate a list of indices of the selected vertices in a Python script?

I find the Blender Python API reference utterly confusing to navigate, and Google mostly points to outdated APIs. This is hopefully trivial for the Blender scripting pros.

The indices should be consistent with the vertex indices in an OBJ export of the mesh. I want to write a script exporting the vertex indices in a text file in order to access these vertices in a C++ program.

like image 435
DCS Avatar asked Mar 15 '13 10:03

DCS


2 Answers

Your code only works reliably if you switch to object mode before you execute it. The reason is that while in edit-mode, the mesh data is not synchronized with the mesh from object mode. This is done when you switch back to object mode. You can verify this by switching to edit mode, select some vertices from your object, execute your code, then select different vertices (still in edit mode) and run your script again. You will notice that your list of selected vertices in the Python console will not change. This behaviour is documented. To get the selected vertices in edit mode the following code can serve as a first pointer (tested with 2.66.5 r56033):

import bpy
import bmesh

obj=bpy.context.object
if obj.mode == 'EDIT':
    bm=bmesh.from_edit_mesh(obj.data)
    for v in bm.verts:
        if v.select:
            print(v.co)
else:
    print("Object is not in edit mode.")

Select/deselect nodes and execute the script to see the vertices change.

like image 98
hochl Avatar answered Nov 03 '22 09:11

hochl


Finally found it in a Blog, nice and compact:

Verts = [i.index for i in bpy.context.active_object.data.vertices if i.select]

It is indeed consistent with the vertex ordering in OBJ export (Blender.2.64).

like image 43
DCS Avatar answered Nov 03 '22 08:11

DCS