Featured post

new redirect for blender.org bpy docs.

http://www.blender.org/api/blender_python_api_current/ As of 10/11 november 2015 we can now link to the current api docs and not be worr...

April 25, 2012

combined edge lengths

Also available as an addon below, but please read through the post too.
small example of how to obtain combined edge lengths, to get the right answers you must:
- select the edges in edit mode
- switch to object mode, then run the script
(confused?)
import bpy

def get_combined_length(object_data, edge_list):
    edge_length = 0
    for edge in edge_list:
        vert1 = edge.vertices[0]
        vert2 = edge.vertices[1]
        co1 = object_data.vertices[vert1].co  
        co2 = object_data.vertices[vert2].co  
        edge_length += (co1-co2).length
         
    return edge_length
    
object_data = bpy.context.active_object.data
selected_edges = [edge for edge in object_data.edges if edge.select]

summed_length = get_combined_length(object_data, selected_edges)
num_edges = len(selected_edges)

print("number of edges: ", num_edges)
print("combined length: ", summed_length)
Maybe there is a prettier solution/rewrite. Although I wouldn't defend the following rewrite as pretty, I do like it because it involves less duplicate code.
import bpy

def get_combined_length(data_verts, edge_list):
    edge_length = 0
    for edge in edge_list:
        co1, co2 = [data_verts[vert].co for vert in edge.vertices]
        edge_length += (co1-co2).length
         
    return edge_length
    
object_data = bpy.context.active_object.data
selected_edges = [edge for edge in object_data.edges if edge.select]

summed_length = get_combined_length(object_data.vertices, selected_edges)
num_edges = len(selected_edges)

print("number of edges: ", num_edges)
print("combined length: ", summed_length)
It's up to you to investigate which method is faster

I've seen a question on the forums at BA about this post, so i'm going to offer a bmesh solution below. This version uses bmesh.from_edit_mesh(mesh). Looks good, and clean.
as addon, stick it in addons_contrib, its a 3dview type addon, it places itself inside the mesh display panel when an object is selected. Instead of the function running continuously you can press 'sum' to get the total length. Get the addon here