#!/usr/bin/env python

import math
import stlwrite as stl

PI = math.pi

def frange(x, maximum, step):
    while x < maximum:
        yield x
        x += step

def get_ellipse(A,B,x0,y0):
    # Return a list of triangular faces for an axis-aligned ellipse
    # Parameters:
    #   A and B are the semi-major and semi-minor axis lengths
    #   x0 and y0 define the center of the list
    faces = []
    center = (x0,y0,0)
    thetaStep = PI/8
    for theta in frange(0, 2*PI, thetaStep):
        p1 = (x0 + A * math.cos(theta), y0 + B * math.sin(theta), 0)
        p2 = (x0 + A * math.cos(theta+thetaStep), y0 + B * math.sin(theta+thetaStep), 0)
        faces.append([center, p1, p2])
    return faces

def example():
    filename = 'ellipse.stl'
    with open(filename, 'wb') as fp:
        writer = stl.ASCII_STL_Writer(fp)
        writer.add_faces(get_ellipse(2,1,0,0))
        writer.close()
    print('Wrote ' + filename)

if __name__ == '__main__':
    example()
