# This program is part of a set of animations and demonstrations that encourage students
# to pose vaguely mathematical questions. This particular program draws a bar whose
# length is proportional to |sin(t)|, as t slowly increases from 0. Hopefully this prompts
# questions related to functions, or rates, such as "why does it grow faster at some times
# and slower at others," "why does it oscillate," etc.

# History:
#
#   August 2017 -- Created by Doug Baldwin from a previous Pyglet test program.
#
#   July 2016 -- Pyglet test created by Doug Baldwin.




import pyglet
from pyglet.gl import *
from math import sin, fmod, pi




# Keep t, from which I can calculate the length of the bar, in a global variable, and
# update it with periodic callback function.

t = 0

def updateT( dt ) :						# The callback function that increases t
	global t
	t = fmod( t + 0.01, 2.0 * pi )


# Create the window.

mainWindow = pyglet.window.Window( width = 512, height = 512 )


# Give the window a display callback

@mainWindow.event
def on_draw() :

	# Calculate the extent (half length) of the bar and where to draw it horizontally.
	extent = 3.0 * sin( t )
	x = pi - 2.0 * abs( t - pi )

	glClearColor( 0.8, 0.8, 0.8, 1.0 )
	glClear( GL_COLOR_BUFFER_BIT )
	glMatrixMode( GL_PROJECTION )
	glLoadIdentity()
	glOrtho( -3.5, 3.5, -3.5, 3.5, -1, 1 )
	glMatrixMode( GL_MODELVIEW )
	glLoadIdentity()
	
	glColor3f( 0, 0, 1 )
	glLineWidth( 10.0 )
		
	glBegin( GL_LINES )
	glVertex2f( x, -extent )
	glVertex2f( x, extent )
	glEnd()


# Schedule the function that increases t to run often enough that the bar will seem to
# grow smoothly.

pyglet.clock.schedule_interval( updateT, 1.0/30.0 )


# Run until the user closes the window.

pyglet.app.run()