Snapping an empty to the closest vertex of a cube. "Closest" meaning closest to the viewer.
First, loop through the areas or obtain a SpaceView3D by other means. The type of this area returns
VIEW_3D. It's first space will be a
VIEW_3D space. This space has a
region_3d property, which has a
perspective_matrix appears to be the perspective view transform matrix. Mutliple a 3D Vector by the matrix, to get its position relativ to the camera.
Here is a working sample.
# function returning the closest vertex of
# param 'ob' is an object in the scene with vertices
def get_closest_vertex_position(scene, ob):
# get an area of type VIEW_3D
areas = [a for a in bpy.context.screen.areas if a.type == 'VIEW_3D']
if not len(areas):
region3d = areas.spaces.region_3d
# get the view matrix
view_mat_inv = region3d.view_matrix
vertices = [[v, (view_mat_inv*v.co).length] for v in ob.data.vertices]
vertices = [[v, -(view_mat_inv*v.co).z] for v in ob.data.vertices]
# use a lamda expression to get closest vertex
return min(vertices, key = lambda x: x).co