# Kambi: trivial example of adding a new mesh.
#
# Tries to be as simple as possible and use Blender standard modules,
# so it doesn't use "add_object_utils" helper (see e.g. add_torus),
# and it loads mesh.vertices / faces directly (no tricks with foreach_set).

import math
import bpy

def polygon(number_of_points, radius):

        mesh = bpy.data.meshes.new("Circle")
        mesh.vertices.add(number_of_points + 1)

        # add side vertexes
        for i in range(0, number_of_points):
                angle = 2 * math.pi * i / number_of_points
                mesh.vertices[i].co = (
                        radius * math.cos(angle),
                        radius * math.sin(angle),
                        0.0)

        # add a vertex to the center
        mesh.vertices[number_of_points].co = (0.0, 0.0, 0.0)

        # connect the vertices to form faces
        mesh.faces.add(number_of_points)
        for i in range(0, number_of_points):
                mesh.faces[i].vertices = (i, (i+1) % number_of_points, number_of_points)

        # necessary to create appropriate edges (implicitly defined by faces).
	# Without this, edges may not appear correctly for some time
	# (e.g. until we enter edit mode).
        mesh.update()

        # create and add an object containing mesh (remember that
        # in Blender, "mesh" is only a data inside a container "object").
        # Note: see add_object_utils helper module for a more fancy way
	# to add an object, honoring standard selection and edit/object
	# mode behavior.
        obj = bpy.data.objects.new("CircleObject", mesh)
        bpy.context.scene.objects.link(obj)

polygon(32, 1.0)
