#!/usr/bin/env python
from OpenGL.GL import *
from OpenGL.GLU import *
import pygame
from pygame.locals import *

from math import *

def resize((width, height)):
    """sets the view based on window width and height"""
    if height==0:
        height=1

    glViewport(0, 0, width, height)

    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    glOrtho(0, width, 0, height, 0, 50)

    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    glRotate(180,1,0,0)
    glTranslate(0,-height,0)


def init():
    """initializes OpenGL settings"""
    glClearColor(0.0, 0.0, 0.0, 0.0)
    glClearDepth(1.0)
    glEnable(GL_DEPTH_TEST)
    glDepthFunc(GL_LEQUAL)

def draw_arrow(x1,y1,x2,y2):
    """draws an arrow pointing from (x1,y1) to (x2,y2)"""

    r = pi+atan2(y1-y2,x1-x2)
    l = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1))

    glPushMatrix()

    glTranslate(x2,y2,0)
    glRotate(r*180/pi,0,0,1)

    glBegin(GL_LINES)
    # the tail
    glColorf(1,0,0)
    glVertex(-l,0)
    glVertex(0,0)

    # the head
    glColorf(0,1,0)
    glVertex(-20,-20)
    glVertex(0,0)

    glColorf(0,0,1)
    glVertex(-20,20)
    glVertex(0,0)
    glEnd()

    glPopMatrix()

def draw_scene():
    """draws the screen without changing OpenGL state except color"""
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)

    glPushMatrix()

    glBegin(GL_LINE_LOOP)
    glColorf(1,1,1,1)
    glVertex(10,10,0)
    glVertex(590,10,0)
    glVertex(590,390,0)
    glVertex(10,390,0)
    glEnd()

    draw_arrow(200,300,50,50)

    glPopMatrix()


pygame.init()
pygame.display.set_mode((600,400), OPENGL|DOUBLEBUF)

resize((600,400))

init()

while 1:
    event = pygame.event.poll()
    if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
        break

    draw_scene()
    pygame.display.flip()
