//
//  TestGLView.m
//  Ultimate OpenGL Scroll View
//
//  Created by Max Williams on 17/03/2010.
//  Copyright 2010 Apple Inc. All rights reserved.
//

#import "TestGLView.h"
#import <OpenGL/gl.h>

@implementation TestGLView

- (id)initWithFrame:(NSRect)frame {
	static NSOpenGLPixelFormatAttribute pixelFormatAttributes[] =
	{
		NSOpenGLPFANoRecovery,
		NSOpenGLPFAWindow,
		NSOpenGLPFAAccelerated,
		NSOpenGLPFADoubleBuffer,
		NSOpenGLPFAColorSize, 24,
		NSOpenGLPFAAlphaSize, 8,
		NSOpenGLPFASupersample,
		NSOpenGLPFASampleBuffers, 1,
		NSOpenGLPFASamples, 4,
		(NSOpenGLPixelFormatAttribute)nil	
	};
	NSOpenGLPixelFormat* pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:pixelFormatAttributes];
	
    self = [super initWithFrame:frame pixelFormat:pixelFormat];
	if (self == nil) return nil;
	
	GLint swapInterval = 1;
	[[self openGLContext] setValues:&swapInterval forParameter: NSOpenGLCPSwapInterval];
		
	NSRect bounds = self.bounds;
	bounds.origin = NSMakePoint(-150,-150);
	self.bounds = bounds;
		
    return self;
}

- (void)drawRect:(NSRect)dirtyRect {
	glClearColor(1.0,0.2,0.6,1.0);
	glClear(GL_COLOR_BUFFER_BIT);
	
	glBegin(GL_LINES);
	
	for (int y = -100; y<= 100; y+=10) {
		for (int x = -100; x<= 100; x+=10) {
			glVertex2f(-100,y);
			glVertex2f(100,y);
			glVertex2f(x,-100);
			glVertex2f(x,100);
		}
	}
	
	glEnd();
	
	[[self openGLContext] flushBuffer];
}

- (void)reshape {
	NSRect bounds = [self bounds];
	
	NSLog(@"bounds: %4.1f %4.1f %4.1f %4.1f",bounds.origin.x,bounds.origin.y,bounds.size.width,bounds.size.height);
	NSRect visibleRect = [self visibleRect];
	NSLog(@"visible rect: %4.1f %4.1f %4.1f %4.1f",visibleRect.origin.x,visibleRect.origin.y,visibleRect.size.width,visibleRect.size.height);
	
	// GLsizei x = NSMinX(visibleRect);
	// GLsizei y = NSMinY(visibleRect);
	// 
	// GLfloat w = NSWidth(bounds);
	// GLfloat h = NSHeight(bounds);
	// 
	// NSLog(@"%i, %i, %4.1f, %4.1f",x,y,w,h);
	
	glLoadIdentity();
	
	glViewport(0,0,NSWidth(visibleRect),NSHeight(visibleRect));
	glOrtho(NSMinX(visibleRect), NSMaxX(visibleRect), NSMinY(visibleRect), NSMaxY(visibleRect), -1.0, 1.0);
	// glOrtho(0,w,0,h,-10,10);
	
}


@end
