
from math import sqrt, pi, sin, cos

import glitch, glitch.glut
from glitch.limbo.lights import LightSwitch, AmbientLight, DiffuseLight
from glitch.limbo.objects import Grid
from glitch.limbo.material import Material
from glitch.limbo.mesh import Mesh
from glitch.limbo.spread import Spread

def make_tetrahedron():
    r3 = sqrt(3)
    mesh = Mesh()
    mesh.vertices = [(0, 0, 0), (0.5, 0, r3/2), (1, 0, 0), (0.5, r3/2, r3/6)]
    mesh.faces = [(0, 2, 1), (1, 3, 0), (0, 3, 2), (1, 2, 3)]
    return mesh

def make_cube():
    mesh = Mesh()
    mesh.vertices = [
        (0., 0., 0.), (0., 0., 1.), (0., 1., 0.), (0., 1., 1.),
        (1., 0., 0.), (1., 0., 1.), (1., 1., 0.), (1., 1., 1.)]
    mesh.faces = [
        (1, 3, 2), (2, 0, 1), # x = 0
        (4, 6, 7), (7, 5, 4), # x = 1
        (0, 4, 5), (5, 1, 0), # y = 0
        (7, 6, 2), (2, 3, 7), # y = 1
        (0, 2, 6), (6, 4, 0), # z = 0
        (5, 7, 3), (3, 1, 5), # z = 1
        ]
    return mesh

def make_sphere():
    # Number of slices.
    m = 20
    # Number of wedges.
    n = 10
    r = 0.5

    vertices = []
    faces = []

    for i in xrange(1, n):
        s = i * pi / n
        r_ = r * sin(s)
        vertices.extend([
            (r + r_ * sin(t * 2 * pi / m),
             r * (1 - cos(s)),
             r + r_ * cos(t * 2 * pi / m))
                for t in xrange(m)])

    for i in xrange(n - 2):
        for j in xrange(m):
            faces.append(
                (m * i + j,
                 m * i + (j + 1) % m,
                 m * (i + 1) + j))
            faces.append(
                (m * i + (j + 1) % m,
                 m * (i + 1) + (j + 1) % m,
                 m * (i + 1) + j))

    l = len(vertices)
    p0 = (0.5, 0, 0.5)
    p1 = (0.5, 1, 0.5)
    vertices.extend([p0, p1])

    for i in xrange(m):
        faces.append((l, (i + 1) % m, i))
        faces.append((l + 1, l - m + i, l - m + (i + 1) % m))

    mesh = Mesh()
    mesh.vertices = vertices
    mesh.faces = faces
    return mesh

if __name__ == '__main__':
    mesh1 = make_tetrahedron()
    mesh2 = make_cube()
    mesh3 = make_sphere()

    camera = glitch.glut.GLUTCamera(eye=[0, 4, 5], ref=[2.5, 0, 2.5], children=[
        glitch.Rotate(90, x=3, children=[
            glitch.Scale(5, 5, 1, children=[Grid()])]),
        LightSwitch(children=[
            AmbientLight(intensity=0.05, x=-1, z=4, y=2, children=[
                DiffuseLight(x=-1, z=4, y=2, children=[
                    Material(r=0.9, g=0.5, b=0.5, children=[
                        Spread(x=2, z=2, children=[mesh1, mesh2, mesh3])
                    ])])])])])
    camera.run()

