
import time
from math import cos, sin

import OpenGL.GLUT as glut
import PIL.ImageDraw

import glitch
import glitch.glut
import glitch.PIL

white = (255, 255, 255)
black = (0, 0, 0)

class Animate(glitch.PIL.ImageTexture):
    def __init__(self, width, height):
        self.version = 0
        self.width = width
        self.height = height
        image = self._make_image()
        glitch.PIL.ImageTexture.__init__(self, image)

    def upload(self, ctx):
        self.set_from_image(self._make_image())
        glitch.PIL.ImageTexture.upload(self, ctx)

class Bounce(Animate):
    def _draw_image(self, draw):
        size = self.width
        r = size / 60.0
        x = (sin(-self.version * 4.0) / 2.4 + 0.5) * size
        y = (cos(self.version * 3.3) / 2.4 + 0.5) * size
        draw.ellipse(((x - r, y - r), (x + r, y + r)), white)

    def _make_image(self):
        image = PIL.Image.new('RGB', (self.width, self.height), black)
        draw = PIL.ImageDraw.Draw(image)
        self._draw_image(draw)
        return image

def timeout(_ignored=None):
    bounce.version = time.time() - start
    glut.glutPostRedisplay()
    glut.glutTimerFunc(1000 / 30, timeout, None)

start = time.time()
bounce = Bounce(600, 600)
camera = glitch.glut.GLUTCamera(
    eye=[0.5, 0.5, 1],
    ref=[0.5, 0.5, 0],
    children=[
        glitch.ApplyTexture(bounce, children=[
            glitch.TexturedSquare()])])
timeout()
camera.run()
