Find faces

Objectives

a Often an object is collection of huge number of polygons, it is not easy to find the index values for a spezific area or number of polygons. A little script helps you to find the polygones of interest.

Instructions

Tasks:
  1. Test the script and discover how the functions work.
  2. Change the color of eyes from »Suzanne«.
  3. Try to colorize the mouth of »Suzanne«.
  4. Try colorize a part of a figure that you created yourself.

The script

#!bpy
"""
Name: 'show_faces.py'
Blender: 2.68
Group: 'Material'
Tooltip: 'Materialien an einzelne Flächen zuweisen'
"""
import bpy

red = bpy.data.materials.new('Red')
blue = bpy.data.materials.new('Blue')
yellow = bpy.data.materials.new('Yellow')


def setColor(obj, material, color):
    material.diffuse_color = color
    material.specular_hardness = 200
    obj.data.materials.append(material)


def monkey():
    """ a new monkey """

    bpy.ops.mesh.primitive_monkey_add(location=(0, 0, 1), rotation=(0, 0, .5))
    ob = bpy.context.object
    ob.name = 'Suzanne'

    setColor(ob, red, (1, 0, 0))
    setColor(ob, yellow, (1, 1, 0))
    setColor(ob, blue, (0, 0, 1))

    # colorize the whole object
    for poly in ob.data.polygons:
        poly.material_index = 1


def coloredEyes(name):
    bpy.context.scene.objects.active = bpy.data.objects[name]
    me = bpy.context.object

    # changes are visible after switch to the edit mode
    bpy.ops.object.mode_set(mode='EDIT')
    bpy.ops.object.mode_set(mode='OBJECT')
    polygons_augen = [48, 49, 50, 51, 52, 53, 54, 55,
                      56, 57, 58, 59, 60, 61, 62, 63]
    # blue Eyes
    for poly in me.data.polygons:
        if poly.index in polygons_augen:
            poly.material_index = 2
            print(poly.index, polygons_augen)


def getIndexOfFaces(name):
    """ Print the index of faces to the console

        - Switch to the edit-Mode
        - select faces
        - the output ist shown in the console
    """
    bpy.context.scene.objects.active = bpy.data.objects[name]
    bpy.ops.object.mode_set(mode='EDIT')
    bpy.ops.object.mode_set(mode='OBJECT')
    me = bpy.context.object.data
    for poly in me.polygons:
        if poly.select:
            print("Polygon index: %d, length: %d" % (poly.index,
                                                     poly.loop_total))
    bpy.ops.object.mode_set(mode='EDIT')


if __name__ == '__main__':
    # collect the object names
    obj_names = []
    for obj in bpy.context.scene.objects:
        obj_names.append(obj.name)
    # if no Suzanne is in the list, create one
    if not obj_names.count("Suzanne"):
        monkey()
    # switch in the edit mode (3D View) and selct one ore more faces
    # selected index nummers can be found on the command line
    getIndexOfFaces('Suzanne')

    # If you put the printed index values in a function
    # the process is repeatable

    coloredEyes('Suzanne')