#import "Triangle.h"
#include <OpenGL/gl.h>
#include <stdio.h>
#include <time.h>

@implementation Triangle

- (id) initWithCoder: (NSCoder *) coder
{
/*	SEL theSelector ;
    NSMethodSignature* aSignature ;
    NSInvocation* anInvocation ;
	NSOpenGLPixelFormatAttribute attrs[] = 
    {
        NSOpenGLPFADoubleBuffer,
        nil
    };
    NSOpenGLPixelFormat* pixFmt ;
    long swapInterval ; */

	self = [super initWithCoder: coder] ;
	ver1x = 0.556;
	ver1y = 0.2;
	ver2x = 1.0;
	ver2y = 1.0;
	ver3x = 0.02;
	ver3y = 1.0;

/*        colorIntensity = 1.0 ;
    startTime = [NSDate date] ;
    [startTime retain] ;
	
	pixFmt = [[NSOpenGLPixelFormat alloc] initWithAttributes: attrs] ;
    [self setPixelFormat: pixFmt] ;
    swapInterval = 1 ;
    [[self openGLContext]
	setValues: &swapInterval
	forParameter: NSOpenGLCPSwapInterval ] ;
	
    theSelector = @selector( pulseColor );
    aSignature = [Triangle
                    instanceMethodSignatureForSelector: theSelector] ;
    anInvocation = [NSInvocation
                    invocationWithMethodSignature: aSignature] ;
    [anInvocation setSelector: theSelector] ;
    [anInvocation setTarget: self] ;
    timer = [NSTimer
            scheduledTimerWithTimeInterval: 0.05
            invocation: anInvocation
            repeats: YES] ;
    [timer retain] ; */

	return self ;
}

-(void) awakeFromNib
{
[vertex1x setDoubleValue:ver1x];
[vertex1y setDoubleValue:ver1y];
[vertex2x setDoubleValue:ver2x];
[vertex2y setDoubleValue:ver2y];
[vertex3x setDoubleValue:ver3x];
[vertex3y setDoubleValue:ver3y];
}

- (IBAction)redraw:(id)sender
{
ver1x = [vertex1x doubleValue];
ver1y = [vertex1y doubleValue];
ver2x = [vertex2x doubleValue];
ver2y = [vertex2y doubleValue];
ver3x = [vertex3x doubleValue];
ver3y = [vertex3y doubleValue];
int i;
for (i = 0; i< 10000; i++){
ver3x = ver1x+ 0.00005;
ver3y = ver1y - 0.00005;
[self lockFocus];
[self drawRect:[self frame]];
[self unlockFocus];
NSLog (@"Drawing in step%d", i);
}
}
-(void) dealloc
{
    [timer invalidate] ;
    [timer release] ;
    [startTime release] ;
    [super dealloc] ;
}

- (void) pulseColor
{
    colorIntensity = fabs( sin( 2.0 * M_PI * [startTime timeIntervalSinceNow] ) ) ;
    [self setNeedsDisplay: YES] ;
}

-(void)drawRect:(NSRect)rect
{
	glClearColor( 0, 0, 0, 0 ) ;
	glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ) ;    
	glColor3f( 0.0f, 1.0f, 0.0f ) ;
    glBegin( GL_TRIANGLES) ;
    {
        glVertex3f( ver1x, ver1y, 0.0 ) ;
        glVertex3f( ver2x, ver2y, 0.0 ) ;
	    glVertex3f( ver3x , ver3y, 0.0 ) ;
    }
    glEnd() ;
glFinish();
[[self openGLContext] flushBuffer] ;
}

@end
