Week #15 Challenge: OpenGL

  • (2 Pages)
  • +
  • 1
  • 2

24 Replies - 28836 Views - Last Post: 15 May 2011 - 08:53 AM

#1 Core  Icon User is offline

  • using System.Linq;
  • member icon

Reputation: 773
  • View blog
  • Posts: 5,097
  • Joined: 08-December 08

Week #15 Challenge: OpenGL

Post icon  Posted 11 April 2010 - 02:10 PM

*
POPULAR


Week 15 Challenge: OpenGL


Posted Image

OpenGL (Open Graphics Library) is a cross-platform API that lets developers create applications that are actively implementing 2D and 3D graphics. It was started as a project by Silicon Graphics Inc. in 1992 and is currently maintained by the Khronos Group.

The most up-to-date release of OpenGL is 4.0.

The main task of this challenge is to get developers with (or without) OpenGL development experience to experiment with the possibilities offered by OpenGL.

Ideas to get started:
  • Draw a primitive from scratch.
  • Draw a primitive with a texture.
  • Render a 3D model.
  • Experiment with lighting.


Tools/Libraries:
OpenGL requires some additional configuration if the developer did not have it installed. A set of system-specific libraries is required to get it up and running.

To get started, GLUT (OpenGL Utility Toolkit) is needed. For more information about GLUT, please visit this page.

To download GLUT, visit this page.

If you are installing GLUT on Windows, you can watch this video (DevTube for Dream.In.Code) to see the installation steps in detail:



GLUT is generally used from a C++ program, however, binders for other languages are available as well. For a complete list, please visit this page.

The IDE you are using doesn't matter as long as you use a programming language that has a GLUT binder.

Documentation/Guides/Tutorials:
The Official Guide to Learning OpenGL, Version 1.1
OpenGL API Documentation
Swiftless OpenGL Tutorials
Using OpenGL/GLUT to Create 3D Scenes (Part 1, Part 2, Part 3)

If you need more help, feel free to post your question in the forums.

Is This A Good Question/Topic? 7
  • +

Replies To: Week #15 Challenge: OpenGL

#2 Tethik  Icon User is offline

  • D.I.C Head

Reputation: 17
  • View blog
  • Posts: 61
  • Joined: 14-March 10

Re: Week #15 Challenge: OpenGL

Posted 11 April 2010 - 03:03 PM

I've been putting off any kind of API for way too long (console all the way). Great links and tutorials, I'll start studying em tomorrow. Should be fun :D
Was This Post Helpful? 3
  • +
  • -

#3 gabehabe  Icon User is offline

  • GabehabeSwamp
  • member icon




Reputation: 1376
  • View blog
  • Posts: 10,951
  • Joined: 06-February 08

Re: Week #15 Challenge: OpenGL

Posted 11 April 2010 - 03:49 PM

Could've sworn I posted here earlier. O.o

Anyway, I said I was surprised http://nehe.gamedev.net wasn't mentioned, and I've been looking to try OpenGL properly for a while, blah blah blah.

Might give it a go this week. :)
Was This Post Helpful? 4
  • +
  • -

#4 Skaggles  Icon User is offline

  • THE PEN IS MIGHTIER
  • member icon





Reputation: 251
  • View blog
  • Posts: 640
  • Joined: 01-March 09

Re: Week #15 Challenge: OpenGL

Posted 11 April 2010 - 04:21 PM

This is me checking in and saying I'm attempting this one. It's been over a year since I've messed with OpenGL so I'll have to reaquaint myself. I'm actually really interested to see the submissions for this week's challenge.
Was This Post Helpful? 1
  • +
  • -

#5 calebjonasson  Icon User is offline

  • $bert = new DragonUnicorn(); $bert->rawr();
  • member icon

Reputation: 207
  • View blog
  • Posts: 988
  • Joined: 28-February 09

Re: Week #15 Challenge: OpenGL

Posted 11 April 2010 - 04:23 PM

I think I will actually do this one only through c or objective c on the iphone.
Was This Post Helpful? 1
  • +
  • -

#6 Dogstopper  Icon User is online

  • The Ninjaducky
  • member icon



Reputation: 2858
  • View blog
  • Posts: 10,963
  • Joined: 15-July 08

Re: Week #15 Challenge: OpenGL

Posted 11 April 2010 - 08:23 PM

I will definitely give JOGL (Java OpenGL) a shot since I'm sure there will be plenty of C implementations. If possible, I might attempt PyOpenGL as well. This way, we can get several implementations out there.

edit: took me a while to get it figured out (how to install and run it), but after that, it proved easy.

This post has been edited by Dogstopper: 11 April 2010 - 08:24 PM

Was This Post Helpful? 1
  • +
  • -

#7 Raynes  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 610
  • View blog
  • Posts: 2,815
  • Joined: 05-January 09

Re: Week #15 Challenge: OpenGL

Posted 12 April 2010 - 12:42 AM

That 'complete' list isn't quite as complete as you might think. I'm about to edit it to include these awesome OpenGL bindings for Clojure.

I've never played with OpenGL or graphics in general. I'll experiment and try to get a neat Clojure submission in by the end of the week. :>

This post has been edited by Raynes: 12 April 2010 - 12:45 AM

Was This Post Helpful? 1
  • +
  • -

#8 Kohana  Icon User is offline

  • D.I.C Head

Reputation: 22
  • View blog
  • Posts: 55
  • Joined: 09-January 10

Re: Week #15 Challenge: OpenGL

Posted 12 April 2010 - 02:57 AM

*
POPULAR

Allow me to get things started.....

also, who won the last one? I wanna buy GOF's design patterns book. GIEF Voucher!

Just the MAIN from my 28 files of code that make this project.

/*******************************************************
1. Include necessary header files
*******************************************************/
#include "include.h"
//#include "textures.h"
#include "CGModel.h"
#include "Importers\\3dsImporter.h"
#include "Importers\\gsfImporter.h"
#include "Importers\\objImporter.h"
#include "Importers\\md2Importer.h"


/*******************************************************
2. Decleare global variables and constants
*******************************************************/

// Define new type to represent points using homogenous coordinates
//struct CGVector {
//	float			x, y, z, w;
//};


// Define trigonometric constants
const float pi = 3.142f;
const float rad_coeff = pi/180.0f;


bool							initialiseComplete = false;
FILE							*fp = NULL; // debug file
bool							showExtensions = true;

const GLubyte					*glVendorString, *glRendererString, *glVersionString;
const GLubyte					*glExtensionString;

// variables to describe window configuration
int								width = 1024;
int								height = 768;
int								bitsPerPixel = 32; // colour depth
bool							fullscreen = true;	// fullscreen mode

// Note: To enable the full screen option simply comment out the following #define statement
// PLEASE NOTE: FULL SCREEN DOES NOT WORK IN MANY OF THE LABS DUE TO REGISTRY ACCESS ISSUES.
//#define							CG_IGNORE_FULLSCREEN			0x01

TCHAR							appName [] = TEXT("CS3S05");
HINSTANCE						hInstance;
HWND							hwnd_MainWindow	= NULL; // main window handle
HDC								hDC	= NULL; // windows device context
HGLRC							hRC	= NULL; // openGL rendering context
DEVMODE							originalDeviceMode;


// OpenGL textures - example array of textures
GLuint							textureLib[7];
GLUquadric						*skyDome;
GLuint							treeTexture[5];
GLuint							houseTexture[2];

// basic rotational camera model
float							cameraXZ, cameraY, cameraR; 
CGModel							*HouseMesh=NULL;
CGModel							*Man=NULL;
CGModel							*Tree=NULL;
CGModel							*Car=NULL;
CGModel							*streetLamp=NULL;

// Car and light movement
float							carZ=-50.0;
float							breakLightX=-4.0;
float							headLightX=6.0;

//
// Demo-specific global variables
//
bool							drawXAxis=false, drawYAxis=false, drawZAxis=false;
const int						nStars = 500;
CGVector						stars[nStars];
int								starUpdateCounter = 1000; // used for star animation

//
// Example Light
//
// Example light and material

// Define position of light in polar coodinate terms
float			lightTheta = pi/4.0f;
float			lightRadius = 6.0f;


// Light properties

// Define initial position
GLfloat lightPosition[] = {cos(lightTheta)*lightRadius,
							sin(lightTheta)*lightRadius,
							0.0f,
							1.0f};

// Define initial direction
GLfloat lightDirection[] = {-lightPosition[0], -lightPosition[1], -lightPosition[2], 0.0};

float			ambientScale = 0.1f;
GLfloat lightAmbient[] = {ambientScale, ambientScale, ambientScale, 1.0f}; // no ambient light
GLfloat lightDiffuse[] = {1.0f, 1.0f, 1.0f, 1.0f}; // diffuse light
GLfloat lightSpecular[] = {0.0f, 0.0f, 0.0f, 1.0f}; // no specular light

GLfloat testAmbient[] = {0.3, 0.3, 0.3, 0.0f}; 
GLfloat testDiffuse[] = {1.0f, 1.0f, 1.0f, 1.0f}; 
GLfloat testSpecular[] = {0.0f, 0.0f, 0.0f, 1.0f}; 
GLfloat testDirection[] = {0.0, 15.0, 0.0};
GLfloat testPosition[] = {0.0,-30.0,0.0,1.0};

GLfloat	ca = 0.5f, la = 0.0, qa = 0.0; // constant, linear and quadratic attenuation


// Material properties
GLfloat	ambientMaterial[] = {1.0f, 1.0f, 1.0f, 1.0f};
GLfloat diffuseMaterial[] = {0.0f, 0.0f, 0.0f, 1.0f};
GLfloat specularMaterial[] = {1.0f, 1.0, 1.0f, 1.0f};
GLfloat emissiveMaterial[] = {0.0f, 0.0, 0.0f, 1.0f}; // emission colour
GLfloat materialShininess = 10.0f;


/*******************************************************
3. Declare function prototypes
*******************************************************/
int WINAPI WinMain(HINSTANCE h_instance, HINSTANCE h_prev_instance, LPSTR lp_cmd_line, int show_cmd);
void disposeGLWindow();
LRESULT CALLBACK WinProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam);
void forceRedraw(HWND hwnd);
void cgInfinitePerspective(float fov, float aspect, float nearPlane);
void createStarField(CGVector *stars, int nStars);
void renderScene(void);
void drawPrincipleAxes(bool drawX, bool drawY, bool drawZ);
void drawStar(void);
void drawStarField(CGVector *stars, int nStars);
void drawTree(void);
void drawTrees(void);
void drawMountain(void);
void drawFloor(void);
void drawBuildingWall(int TextureChoice);
void drawHouse(void);
void drawRoad(void);
void drawSky(void);
void initlights(float brakeLightX);
void initHeadLights(float headLightX);
void drawWall(void);
void drawCompleteWall(void);
void drawRoadComplete(void);
void drawHouseMesh(void);
void drawStreetLamp(void);
void drawCar(float carZ);

/*******************************************************
4. Function implementation
*******************************************************/

// Main start point for program
int WINAPI WinMain(HINSTANCE h_instance, HINSTANCE h_prev_instance, LPSTR lp_cmd_line, int show_cmd)
{
	WNDCLASSEX							wndclass;
	MSG									msg;
	int									nPixelFormat;
	PIXELFORMATDESCRIPTOR				pfd;
	BOOL								failOpenGLInitialisation=FALSE;
	DWORD								dwExStyle;				// Window Extended Style
	DWORD								dwStyle;				// Window Style
	RECT								windowRect;				// Grabs Rectangle Upper Left / Lower Right Values
	
	hInstance = h_instance;

	// setup debug file
	fopen_s(&fp, "runlog.txt", "w");
	if (!fp)
		return 0;

	// ask to run in fullscreen mode
#ifndef CG_IGNORE_FULLSCREEN
	if (MessageBox(NULL, "Run In Fullscreen Mode?", "FullScreen Mode", MB_YESNO|MB_ICONQUESTION)==IDNO)
		fullscreen = false;
#endif


	// initialise window class
	wndclass.cbSize				= sizeof(wndclass);
	wndclass.style				= CS_DBLCLKS | CS_OWNDC | CS_HREDRAW | CS_VREDRAW; //characteristics of window
	wndclass.lpfnWndProc		= WinProc; // event handler function for window (defined below)
	wndclass.cbClsExtra			= 0;
	wndclass.cbWndExtra			= 0;
	wndclass.hInstance			= GetModuleHandle(NULL);
	wndclass.hIcon				= LoadIcon(NULL, IDI_APPLICATION);
	wndclass.hCursor			= LoadCursor(NULL, IDC_CROSS);
	wndclass.hbrBackground		= (HBRUSH)GetStockObject(BLACK_BRUSH);
	wndclass.lpszMenuName		= NULL;
	wndclass.lpszClassName		= appName;
	wndclass.hIconSm			= NULL;

	// register window class (must be done before we actually create an instance of the window)
	if (!RegisterClassEx(&wndclass)) {
		MessageBox(hwnd_MainWindow, "Error initialising application", "Error", MB_OK);
		return 0;
	}
	
	// setup fullscreen properties if relevant
	if (fullscreen) {

		// save original device mode
		EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &originalDeviceMode);

		DEVMODE				devMode;	

		memset(&devMode, 0, sizeof(devMode));

		devMode.dmSize = sizeof(devMode);
		devMode.dmPelsWidth = width;
		devMode.dmPelsHeight	= height;
		devMode.dmBitsPerPel	= bitsPerPixel;
		devMode.dmFields = DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

		// Attempt to switch to full screen mode - if it fails fall back into normal windowed mode
		// NOTE: CDS_FULLSCREEN removes the taskbar.
		if (ChangeDisplaySettings(&devMode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
			fullscreen = false;
	}


	// setup windows style flags depending on whether or not in full-screen mode
	if (fullscreen) {
		dwExStyle = WS_EX_APPWINDOW; // Window Extended Style
		dwStyle = WS_POPUP; // Window style
		//ShowCursor(FALSE);
	} else {
		dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
		dwStyle = WS_OVERLAPPEDWINDOW;
	}


	// Setup window rect and resize according to set styles
	windowRect.left = (long)0;
	windowRect.right = (long)width;
	windowRect.top = (long)0;
	windowRect.bottom = (long)height;

	AdjustWindowRectEx(&windowRect, dwStyle, FALSE, dwExStyle);		// Adjust Window To True Requested Size

	
	// create main window
	hwnd_MainWindow = CreateWindowEx(dwExStyle, appName, "CS3S05", dwStyle|WS_CLIPSIBLINGS|WS_CLIPCHILDREN,
						  0, 0, windowRect.right-windowRect.left, windowRect.bottom-windowRect.top, NULL, NULL, h_instance, NULL);

	if (!hwnd_MainWindow) {
		disposeGLWindow();
		MessageBox(hwnd_MainWindow, "Error initialising window", "Error", MB_OK);
		return 0;
	}

	ShowWindow(hwnd_MainWindow, show_cmd);
	UpdateWindow(hwnd_MainWindow);
	SetFocus(hwnd_MainWindow);

	// initialise OpenGL
	ZeroMemory(&pfd,sizeof(pfd));
	pfd.nSize = sizeof(pfd);
	pfd.nVersion = 1;
	pfd.dwFlags	= PFD_DOUBLEBUFFER | PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL;
	pfd.iPixelType = PFD_TYPE_RGBA;
	pfd.cColorBits = bitsPerPixel; // want a colour buffer (the image we see)
	pfd.cDepthBits = 24; // depth buffer (highest precision gives better results)
	pfd.iLayerType = PFD_MAIN_PLANE;

	hDC = GetDC(hwnd_MainWindow);

	// main steps to setup OpenGL
	if (!(nPixelFormat = ChoosePixelFormat(hDC, &pfd)))
		failOpenGLInitialisation=TRUE;

	if (!SetPixelFormat(hDC, nPixelFormat, &pfd))
		failOpenGLInitialisation=TRUE;

	if (!(hRC = wglCreateContext(hDC)))
		failOpenGLInitialisation=TRUE;
		
	if (!wglMakeCurrent(hDC,hRC))
		failOpenGLInitialisation=TRUE;

	ReleaseDC(hwnd_MainWindow, hDC);
	hDC = NULL;

	if (failOpenGLInitialisation) {
		disposeGLWindow();
		MessageBox(hwnd_MainWindow, "Error initialising OpenGL", "Error", MB_OK);
		return 0;
	}

	
	// Initialise OpenGL properties

	//
	// Get OpenGL runtime info
	//

	glVendorString = glGetString(GL_VENDOR);
	glRendererString = glGetString(GL_RENDERER);
	glVersionString = glGetString(GL_VERSION);
	glExtensionString = glGetString(GL_EXTENSIONS);
	
	//
	// report runtime info
	//
	if (showExtensions) {
		fprintf(fp, "Vendor: %s\n", glVendorString);
		fprintf(fp, "Renderer: %s\n", glRendererString);
		fprintf(fp, "Version: %s\n\n", glVersionString);

		fprintf(fp, "Extensions supported:\n");

		int			i = 0;
		bool		eos = false;

		while (!eos) {

			if (glExtensionString[i]==0) // all strings in c/c++ are null-terminated
				eos = true;
			else {
				if (glExtensionString[i]==' ')
					fprintf(fp, "\n");
				else
					fprintf(fp, "%c", glExtensionString[i]);
				
				i++;
			}
		}
	}


	// Set Projection and model view transformations
	glMatrixMode(GL_PROJECTION);					// select the projection matrix
	glLoadIdentity();								// reset the projection matrix
	
	glFrustum(-1.0, 1.0, -1.0, 1.0, 1.0, 50.0);

	// Clear all previous transformations
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();


	// Set rendering properties
	glShadeModel(GL_FLAT);							// shading model
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);			// specify background color to black
	
	// function for blending colours
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	
	// Depth sorting parameters
	glDepthFunc(GL_LESS);
	glEnable(GL_DEPTH_TEST);

	// finished setting application up - set flag
	initialiseComplete = true;


	// load textures
	textureLib[0]= loadTexture("Assets\\Textures\\texture1.bmp");
	textureLib[1]= loadTexture("Assets\\Textures\\stoneWallKohana.bmp");
	textureLib[2]= loadTexture("Assets\\Textures\\stoneWall.bmp");
	textureLib[3]= loadTexture("Assets\\Textures\\texture4.bmp");
	textureLib[4]= loadTexture("Assets\\Textures\\texture5.bmp");
	textureLib[5]= loadTexture("Assets\\Textures\\texture6.bmp");
	textureLib[6]= loadTexture("Assets\\Textures\\space.bmp");
	textureLib[7]= loadTexture("Assets\\Textures\\wallTexture.bmp");

	treeTexture[0] = loadTexture("Assets\\Textures\\treeTexture1.bmp");
	treeTexture[1] = loadTexture("Assets\\Textures\\treeTexture2.bmp");

	houseTexture[0]= loadTexture("Assets\\freeHouse\\housemap.bmp");

	skyDome = gluNewQuadric();
	
	// LOAD MESHES -------------------------------------------------

	HouseMesh = new CGModel();
	import3DS("Assets\\freeHouse\\house01.3DS", HouseMesh);
	HouseMesh->attachTextureImage("Assets\\freeHouse\\housemap.bmp");

	Tree = new CGModel();
	import3DS("Assets\\Models\\firtree1.3ds", Tree);

	streetLamp = new CGModel();
	import3DS("Assets\\Models\\s-light.3ds", streetLamp);

	Car = new CGModel();
	importOBJ("Assets\\Models\\Hyundai Coupe.obj", Car);
	Car->attachTextureImage("Assets\\Textures\\UV1024.bmp");
	
	

	// ------------- Global lighting ---------------------------------
	//
	// Setup Lighting
	//

	glEnable(GL_NORMALIZE); // If we scale objects, ensure normal vectors are re-normalised to length 1.0 to keep lighting calculations correct (see lecture notes)
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Best colour interpolation results

	// Setup GL_LIGHT0
	glLightfv(GL_LIGHT1, GL_AMBIENT, lightAmbient);		// Setup ambient light
	glLightfv(GL_LIGHT1, GL_DIFFUSE, lightDiffuse);		// Setup diffuse light
	glLightfv(GL_LIGHT1, GL_SPECULAR, lightSpecular);	// Setup specular light

	glLightf(GL_LIGHT1, GL_CONSTANT_ATTENUATION, ca);
	glLightf(GL_LIGHT1, GL_LINEAR_ATTENUATION, la);
	glLightf(GL_LIGHT1, GL_QUADRATIC_ATTENUATION, qa);

	glLightf(GL_LIGHT1, GL_SPOT_CUTOFF, 180.0f);
	glLightf(GL_LIGHT1, GL_SPOT_EXPONENT, 0.0);


	// OpenGL provides a global ambient light component - we don't want this so set to zero
	GLfloat global_ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f };
	glLightModelfv(GL_LIGHT_MODEL_AMBIENT, global_ambient);

	//--Another light test---
	glLightfv(GL_LIGHT2, GL_AMBIENT, testAmbient);		// Setup ambient light
	glLightfv(GL_LIGHT2, GL_DIFFUSE, testDiffuse);		// Setup diffuse light
	glLightfv(GL_LIGHT2, GL_SPECULAR, testSpecular);	// Setup specular light

	glLightf(GL_LIGHT2, GL_CONSTANT_ATTENUATION, ca);
	glLightf(GL_LIGHT2, GL_LINEAR_ATTENUATION, la);
	glLightf(GL_LIGHT2, GL_QUADRATIC_ATTENUATION, qa);

	glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION,testDirection);
	glLightf(GL_LIGHT2, GL_SPOT_CUTOFF, 30.0f);
	glLightf(GL_LIGHT2, GL_SPOT_EXPONENT, 128.0);
	

	//----------------------------------------------------------------

	//
	// initialise objects used throughout demo
	//

	// If we want random numbers, we need to seed(initialise) the random number generator
	// (We'll do this now because we may need random numbers at some point in the future)
	srand( (unsigned)time( NULL ) );

	createStarField(stars, nStars);

	// Initialise camera position and direction
	cameraXZ = 10.0;
	cameraY = 0.0;
	cameraR = 10.0;

	//
	// main program loop (receive and process Windows events)
	//
	while(1) {
		if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
			if (WM_QUIT == msg.message)
				break;

			TranslateMessage(&msg);
			DispatchMessage(&msg);

		} else {

			// No events pending - do some application specific processing...
			// Note: Another way would be to use a Windows timer object that sends an event
			// to our window so this code could be put into WinProc below.
			starUpdateCounter--;
			if (starUpdateCounter==0) {
				forceRedraw(hwnd_MainWindow);
				starUpdateCounter = 1000;
			}

		}
	}


	// cleanup texture library resources - release back to OpenGL
	glDeleteTextures(6, textureLib);

	disposeGLWindow();

	// close runtime report file if opened
	fclose(fp);

	// exit to windows
	return 0;
}


void disposeGLWindow()
{
	if (fullscreen) {
		if (!ChangeDisplaySettings(NULL,CDS_TEST)) {
			ChangeDisplaySettings(NULL,CDS_RESET);
			ChangeDisplaySettings(&originalDeviceMode, CDS_RESET);
		} else {
			ChangeDisplaySettings(NULL,CDS_RESET);
		}
		//ShowCursor(TRUE);
	}

	if (hRC) {
		if (!wglMakeCurrent(NULL,NULL))
			MessageBox(NULL, "Release Of DC And RC Failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);

		if (!wglDeleteContext(hRC))
			MessageBox(NULL, "Release Rendering Context Failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
		
		hRC=NULL;
	}

	if (hDC && !ReleaseDC(hwnd_MainWindow,hDC)) {
		MessageBox(NULL,"Release Device Context Failed.", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION);
		hDC=NULL;
	}

	if (hwnd_MainWindow && !DestroyWindow(hwnd_MainWindow)) {
		MessageBox(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hwnd_MainWindow=NULL;
	}

	if (!UnregisterClass(appName, hInstance)) {
		MessageBox(NULL,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
		hInstance=NULL;
	}
}


// Main event handler for project
LRESULT CALLBACK WinProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
	RECT				clientRect;
	static POINT		cPos, currentPos, disp;
	static bool			mDown = false;
	HDC					hdc;

	switch(msg)
	{
		case WM_CREATE:
			break;
		
		case WM_SIZE:
			GetClientRect(hwnd, &clientRect);
			glViewport(0, 0, clientRect.right, clientRect.bottom);
			forceRedraw(hwnd);
			break;

		case WM_PAINT:
			if (initialiseComplete) {

				HDC			hdc = NULL;
				
				hdc = GetDC(hwnd);

				renderScene(); // do main rendering when screen in being updated
				SwapBuffers(hdc); // swap rendering buffers for window
				
				ReleaseDC(hwnd, hdc);
				hdc = NULL;

				// validate client area of window
				// This ensures we don't saturate event queue with WM_PAINT events
				GetClientRect(hwnd, &clientRect);
				ValidateRect(hwnd, &clientRect);
			}
			break;


		//
		// Mouse Input
		//
		case WM_LBUTTONDOWN:
			SetCapture(hwnd); // capture the mouse.  MouseUp events received by RenderWinProc, even if mouse outside window bounds

			GetCursorPos(&cPos); // store cursor position
			SetCursorPos(256, 256); // reset to some default position
			
			ShowCursor(FALSE);
			mDown=true;
			
			break;


		case WM_MOUSEMOVE:
		
			if (mDown) {
				
				GetCursorPos(&currentPos); // screen coords
				disp.x = currentPos.x - 256;
				disp.y = currentPos.y - 256;

				cameraXZ += disp.y*0.05f;
				cameraY += disp.x*0.05f;

				InvalidateRect(hwnd, NULL, TRUE);

				SetCursorPos(256, 256);
				
				// Redraw display
				hdc = GetDC(hwnd);
				renderScene(); 
				SwapBuffers(hdc);
				ReleaseDC(hwnd, hdc);
			}
			break;


		case WM_LBUTTONUP:

			if (mDown) {
				SetCursorPos(cPos.x, cPos.y);
				ShowCursor(TRUE);

				mDown = false;
				ReleaseCapture();
			}
			break;


		case WM_MOUSEWHEEL:

			if ((short)HIWORD(wparam)<0)
				cameraR+=3.0;
			if ((short)HIWORD(wparam)>0)
				cameraR-=3.0;

			// Redraw display
			hdc = GetDC(hwnd);
			renderScene(); 
			SwapBuffers(hdc);
			ReleaseDC(hwnd, hdc);

			break;


		case WM_KEYDOWN:

			switch((int)wparam) {
				case VK_ESCAPE:	// Escape
					PostQuitMessage(0);
					break;


				// keys to control display of principle axes

				case '1':
					ambientScale = max(ambientScale - 0.01f, 0.0f);
					lightAmbient[0] = lightAmbient[1] = lightAmbient[2] = ambientScale;
					glLightfv(GL_LIGHT1, GL_AMBIENT, lightAmbient);
					forceRedraw(hwnd);
					break;

				case '2':
					ambientScale = min(1.0f, ambientScale + 0.01f);
					lightAmbient[0] = lightAmbient[1] = lightAmbient[2] = ambientScale;
					glLightfv(GL_LIGHT1, GL_AMBIENT, lightAmbient);
					forceRedraw(hwnd);
					break;
				case '3'://>/ key to toggle z axis on and off
					drawZAxis = !drawZAxis;
					forceRedraw(hwnd);
					break;
				case 'W':
					cameraR=cameraR-0.5;
					forceRedraw(hwnd);
					break;
				case 'S':
					cameraR=cameraR+0.5;
					forceRedraw(hwnd);
					break;
				case 'A':
					glRotatef(cameraY,0.0,-5.0,0.0);
					forceRedraw(hwnd);
					break;
				case 'D':
					glRotatef(cameraY,0.0,5.0,0.0);
					forceRedraw(hwnd);
					break;
				case 'H':
					carZ=carZ+1.0;
					breakLightX=breakLightX+0.07;
					headLightX=headLightX+0.07;
					forceRedraw(hwnd);
					break;
				case 'F':
					carZ=carZ-1.0;
					breakLightX=breakLightX-0.07;
					headLightX=headLightX-0.07;
					forceRedraw(hwnd);
					break;
				// If our event handler does not deal with key press, delegate to default windows event handler
				default:
					return(DefWindowProc(hwnd, msg, wparam, lparam));
			}
			break;


		case WM_CLOSE:
			SendMessage(hwnd, WM_DESTROY, 0, 0);
			break;


		case WM_DESTROY:
			PostQuitMessage(0);
			break;


		default: // If our event handler does not deal with the event, delegate to default windows event handler
			return(DefWindowProc(hwnd, msg, wparam, lparam));
	}

	return(0);
}


void forceRedraw(HWND hwnd)
{
	RECT			clientRect;

	GetClientRect(hwnd, &clientRect);
	InvalidateRect(hwnd, &clientRect, TRUE);
}


// Create perspective projection matrix with far plane at infinity.
// Note: Assumes GL_PROJECTION matrix is current
void cgInfinitePerspective(float fov, float aspect, float nearPlane)
{
	GLfloat			Pinf[4][4] = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}};

	Pinf[1][1] = (1.0f / tan(rad_coeff*(fov/2.0f)));

	Pinf[0][0] = Pinf[1][1] / aspect;

	Pinf[2][2] = -1.0f;
	Pinf[2][3] = -1.0f;

	Pinf[3][2] = -2.0f*nearPlane;
	Pinf[3][3] = 0.0f;

	glMultMatrixf((GLfloat*)&Pinf);
}


// functions to setup and draw a starry backdrop
// createStarField uses rand() to create a random number for each star's position.
void createStarField(CGVector *stars, int nStars)
{
	int					i, t;

	// star starry background
	for (i=0;i<nStars;i++) {
		// get random number for x position
		t = rand();
		stars[i].x = ((((float)t)/32767.0f))*20 - 10;
		
		// ger random number for y position
		t = rand();
		stars[i].y = (((float)t)/32767.0f) * 10;

		stars[i].z = 0.0;
		stars[i].w = 1.0;
	}
}


void renderScene(void)
{
	// 1. Clear the screen
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	
	// save transformations prior to rendering scene
	glPushMatrix();
		
		// Viewing transformations
		glTranslatef(0.0, 0.0, -cameraR);
		glRotatef(cameraXZ, 1.0, 0.0, 0.0);
		glRotatef(cameraY, 0.0, 1.0, 0.0);

		// ---- Turn on lighting ---------
		glEnable(GL_LIGHTING);
		initlights(breakLightX);
		initHeadLights(headLightX);

		glEnable(GL_LIGHT0); //break light
		glEnable(GL_LIGHT1); //global light
		glEnable(GL_LIGHT2); //street light
		glEnable(GL_LIGHT3); //head light

		// Define position and direction (so appear at fixed point in scene)
		glLightfv(GL_LIGHT1, GL_SPOT_DIRECTION, lightDirection);
		glLightfv(GL_LIGHT1, GL_POSITION, lightPosition);

		glLightfv(GL_LIGHT2, GL_SPOT_DIRECTION, testDirection);
		glLightfv(GL_LIGHT2, GL_POSITION, testPosition);


		glColor3f(1.0f, 1.0f, 1.0f);
		glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambientMaterial);
		glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuseMaterial);
		glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specularMaterial);

		 //function for street lights
	
		// draw floor and houses
		
		drawCar(carZ);
		drawHouseMesh();
		drawSky();
		drawFloor();
		drawCompleteWall();
		drawStreetLamp();

		//----Draw Trees-----------------
		glPushMatrix();
		glTranslatef(5.0,0.0,4.0);
		drawTree();
		glPopMatrix();
		
		glPushMatrix();
		glTranslatef(-3.0,0.0,7.0);
		drawTree();
		glPopMatrix();

		glPushMatrix();
		glTranslatef(-6.0,0.0,-12.0);
		drawTree();
		glPopMatrix();
		
		glPushMatrix();
		glTranslatef(-9.0,0.0,-10.0);
		drawTree();
		glPopMatrix();

		// draw house thing

		glPushMatrix();
		glTranslatef(-5.0,0.0,0.0);
		drawHouse();
		glPopMatrix();

		// draw road
		
		drawRoadComplete();

		// disable lights
		glDisable(GL_LIGHT0);
		glDisable(GL_LIGHT1);
		glDisable(GL_LIGHT2);
		glDisable(GL_LIGHTING);
		
	// restore transformations after rendering scene
		
	glPopMatrix();
}//------------------------END SCENE----------------------------


void drawPrincipleAxes(bool drawX, bool drawY, bool drawZ)
{
	if (drawX) {
		glColor3f(1.0, 0.0, 0.0);
		
		glBegin(GL_LINES);

			glVertex3f(0.0, 0.0, 0.0);
			glVertex3f(1.0, 0.0, 0.0);

			glVertex3f(1.025f, 0.025f, 0.0);
			glVertex3f(1.075f, 0.075f, 0.0);

			glVertex3f(1.025f, 0.075f, 0.0);
			glVertex3f(1.075f, 0.025f, 0.0);

		glEnd();
	}

	if (drawY) {
		glColor3f(0.0, 1.0, 0.0);

		glBegin(GL_LINES);

			glVertex3f(0.0, 0.0, 0.0);
			glVertex3f(0.0, 1.0, 0.0);

			glVertex3f(-0.075f, 1.075f, 0.0);
			glVertex3f(-0.05f, 1.05f, 0.0);

			glVertex3f(-0.025f, 1.075f, 0.0);
			glVertex3f(-0.075f, 1.025f, 0.0);

		glEnd();
	}

	if (drawZ) {
		glColor3f(0.0, 0.0, 1.0);

		glBegin(GL_LINES);

			glVertex3f(0.0, 0.0, 0.0);
			glVertex3f(0.0, 0.0, 1.0);

			glVertex3f(0.025f, 0.075f, 1.0);
			glVertex3f(0.075f, 0.075f, 1.0);

			glVertex3f(0.075f, 0.075f, 1.0);
			glVertex3f(0.025f, 0.025f, 1.0);

			glVertex3f(0.025f, 0.025f, 1.0);
			glVertex3f(0.075f, 0.025f, 1.0);

		glEnd();
	}
}
void drawFloor(void)
{
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, textureLib[5]);
	
	glBegin(GL_QUADS);
		
		glNormal3f(0.0,2.0,0.0);
		glTexCoord2f(1.0, 1.0);
		glVertex3f(-15.0f, 0.0, 15.0);

		glNormal3f(0.0,2.0,0.0);
		glTexCoord2f(0.0, 1.0);
		glVertex3f(15.0f, 0.0, 15.0);

		glNormal3f(0.0,2.0,0.0);
		glTexCoord2f(0.0, 0.0);
		glVertex3f(15.0f, 0.0f, -15.0);

		glNormal3f(0.0,2.0,0.0);
		glTexCoord2f(1.0, 0.0);
		glVertex3f(-15.0f, 0.0f, -15.0);

	glEnd();

	glDisable(GL_TEXTURE_2D);

}
void drawBuildingWall(int TextureChoice)
{
	glEnable(GL_TEXTURE_2D);
	
	// render top of tree
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	glBindTexture(GL_TEXTURE_2D, textureLib[TextureChoice]);


	glBegin(GL_QUADS);

		glTexCoord2f(1.0, 1.0);
		glVertex2f(-1.0,0.0);

		glTexCoord2f(0.0, 1.0);
		glVertex2f(-1.0,2.5);

		glTexCoord2f(0.0, 0.0);
		glVertex2f(1.0,2.5);

		glTexCoord2f(1.0, 0.0);
		glVertex2f(1.0,0.0);


	glEnd();

	glDisable(GL_TEXTURE_2D);

}
void drawHouse()
{
	//draw front of house
	glPushMatrix();
		/*drawBuildingWall(1);*/

		glPushMatrix();
			glTranslatef(-1.0,0.0,-1.0);
			glRotated(90.0,0.0,90.0,0.0);
			drawBuildingWall(1);

			glPushMatrix();
				glTranslatef(1.0,0.0,1.0);
				glRotated(90.0,0.0,90.0,0.0);
				drawBuildingWall(2);

				glPushMatrix();
					glTranslatef(-1.0,0.0,-1.0);
					glRotated(90.0,0.0,90.0,0.0);
					drawBuildingWall(2);

				glPopMatrix();

			glPopMatrix();

		glPopMatrix();

	glPopMatrix();
}
void drawWall()
{
	glPushMatrix();
		glTranslatef(15.0,0.0,0.0);
		drawBuildingWall(7);
			glPushMatrix();
			glTranslatef(-2.0,0.0,0.0);
			drawBuildingWall(7);

			glPushMatrix();
			glTranslatef(-2.0,0.0,0.0);
			drawBuildingWall(7);
			

			glPushMatrix();
			glTranslatef(-2.0,0.0,0.0);
			drawBuildingWall(7);
			

			glPushMatrix();
			glTranslatef(-2.0,0.0,0.0);
			drawBuildingWall(7);
			

			glPushMatrix();
			glTranslatef(-2.0,0.0,0.0);
			drawBuildingWall(7);

			glPushMatrix();
			glTranslatef(-2.0,0.0,0.0);
			drawBuildingWall(7);

			glPushMatrix();
			glTranslatef(-2.0,0.0,0.0);
			drawBuildingWall(7);

			glPushMatrix();
			glTranslatef(-2.0,0.0,0.0);
			drawBuildingWall(7);

			glPushMatrix();
			glTranslatef(-2.0,0.0,0.0);
			drawBuildingWall(7);

			glPushMatrix();
			glTranslatef(-2.0,0.0,0.0);
			drawBuildingWall(7);

			glPushMatrix();
			glTranslatef(-2.0,0.0,0.0);
			drawBuildingWall(7);

			glPushMatrix();
			glTranslatef(-2.0,0.0,0.0);
			drawBuildingWall(7);

			glPushMatrix();
			glTranslatef(-2.0,0.0,0.0);
			drawBuildingWall(7);

			glPushMatrix();
			glTranslatef(-2.0,0.0,0.0);
			drawBuildingWall(7);

			glPushMatrix();
			glTranslatef(-2.0,0.0,0.0);
			drawBuildingWall(7);
			
			glPopMatrix();
			glPopMatrix();
			glPopMatrix();
			glPopMatrix();
			glPopMatrix();
			glPopMatrix();
			glPopMatrix();
			glPopMatrix();
			glPopMatrix();
			glPopMatrix();
			glPopMatrix();
			glPopMatrix();
			glPopMatrix();
			glPopMatrix();
			glPopMatrix();

	glPopMatrix();
}
void drawCompleteWall()
{
	glPushMatrix();
	glTranslatef(0.0,0.0,15.0);
	drawWall();
	glPopMatrix();

	glPushMatrix();
	glTranslatef(0.0,0.0,-15.0);
	drawWall();
	glPopMatrix();

	glPushMatrix();
	glTranslatef(15.0,0.0,0.0);
	glRotatef(90.0,0.0,90.0,0.0);
	drawWall();
	glPopMatrix();

	glPushMatrix();
	glTranslatef(-15.0,0.0,0.0);
	glRotatef(90.0,0.0,90.0,0.0);
	drawWall();	
	glPopMatrix();

}


void drawRoad()
{
	glEnable(GL_TEXTURE_2D);

	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	glBindTexture(GL_TEXTURE_2D, textureLib[3]);

	glBegin(GL_QUADS);
	
		glTexCoord2f(1.0, 1.0);
		glNormal3f(0.0,1.0,0.0);
		glVertex3f(-3.0f, 0.01, 1.0);

		glTexCoord2f(0.0, 1.0);
		glVertex3f(3.0f, 0.01, 1.0);

		glTexCoord2f(0.0, 0.0);
		glVertex3f(3.0, 0.01f, -1.0);

		glTexCoord2f(1.0, 0.0);
		glVertex3f(-3.0f, 0.01f, -1.0);

	glEnd();

	glDisable(GL_TEXTURE_2D);
}
void drawSky()
{
	glEnable( GL_TEXTURE_2D );
		glBindTexture( GL_TEXTURE_2D, textureLib[6]);

		gluQuadricTexture(skyDome,GL_TRUE);
		gluSphere(skyDome,50,20,20);

	glDisable(GL_TEXTURE_2D);
}
void initlights(float breakLightX)
{
	GLfloat lampAmbient[] = {1.2, 0.0, 0.0, 1.0};
	GLfloat diffuse[] = {1.0, 1.0, 1.0, 1.0};
	GLfloat lampPosition[] = {breakLightX, 5.0, 0.0, 1.0};


   GLfloat spotDirection[] = {-7.0, -5.0, 0.0};
	GLfloat cutOff = 40.0;
   
	glEnable(GL_NORMALIZE); // If we scale objects, ensure normal vectors are re-normalised to length 1.0 to keep lighting calculations correct (see lecture notes)
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Best colour interpolation results

   glLightfv(GL_LIGHT0, GL_AMBIENT, lampAmbient);
   glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
   glLightfv(GL_LIGHT0, GL_POSITION, lampPosition);

	glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION,spotDirection);
	glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, cutOff);
	glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 40.0f);
        
    //light attenuation (default values used here : no attenuation with the distance)
    glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 1.0f);
    glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.0f);
    glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 0.0f);
   
}
void initHeadLights(float headLightX)
{
	GLfloat lampAmbient[] = {0.5, 0.5, 0.5, 1.0};
	GLfloat diffuse[] = {1.0, 1.0, 1.0, 1.0};
	GLfloat lampPosition[] = {headLightX, 5.0, 0.0, 1.0};


   GLfloat spotDirection[] = {5.0, -5.0, 0.0};
	GLfloat cutOff = 50.0;
   
	glEnable(GL_NORMALIZE); // If we scale objects, ensure normal vectors are re-normalised to length 1.0 to keep lighting calculations correct (see lecture notes)
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Best colour interpolation results

   glLightfv(GL_LIGHT3, GL_AMBIENT, lampAmbient);
   glLightfv(GL_LIGHT3, GL_DIFFUSE, diffuse);
   glLightfv(GL_LIGHT3, GL_POSITION, lampPosition);

	glLightfv(GL_LIGHT3, GL_SPOT_DIRECTION,spotDirection);
	glLightf(GL_LIGHT3, GL_SPOT_CUTOFF, cutOff);
	glLightf(GL_LIGHT3, GL_SPOT_EXPONENT, 30.0f);
        
    //light attenuation (default values used here : no attenuation with the distance)
    glLightf(GL_LIGHT3, GL_CONSTANT_ATTENUATION, 1.0f);
    glLightf(GL_LIGHT3, GL_LINEAR_ATTENUATION, 0.0f);
    glLightf(GL_LIGHT3, GL_QUADRATIC_ATTENUATION, 0.0f);
   
}
void drawRoadComplete()
{
	glPushMatrix();
			glNormal3f(0.0,1.0,0.0);
			glTranslatef(12.0,0.0,1.0);
			drawRoad();

			glPushMatrix();
				glTranslatef(-4.0,0.0,0.0);
				drawRoad();

				glPushMatrix();
					glTranslatef(-4.0,0.0,0.0);
					drawRoad();
			
					glPushMatrix();
						glTranslatef(-4.0,0.0,0.0);
						drawRoad();
			
						glPushMatrix();
							glTranslatef(-4.0,0.0,0.0);
							drawRoad();
			
							glPushMatrix();
								glTranslatef(-4.0,0.0,0.0);
								drawRoad();
								
								glPushMatrix();
									glTranslatef(-4.0,0.0,0.0);
									drawRoad();
			
								glPopMatrix();			
							glPopMatrix();
						glPopMatrix();
					glPopMatrix();
				glPopMatrix();
			glPopMatrix();
		glPopMatrix();

}
void drawHouseMesh()
{	
		//-----Draw house-----------
		glPushMatrix();
		glTranslatef(0.0,2.0,-8.0);
		glScalef(0.05,0.05,0.05);
		glEnable(GL_TEXTURE_2D);
		glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
		HouseMesh->renderTexturedModel();
		glDisable(GL_TEXTURE_2D);
		glPopMatrix();
		//-----end house-----------
}
void drawStreetLamp()
{
	glPushMatrix();
	glScalef(0.015,0.015,0.015);
	glTranslatef(400.0,0.0,150.0);
	glRotatef(90.0,0.0,90.0,0.0);
	streetLamp->render();
	glPopMatrix();
}
void drawTree()
{
	CGPolyMesh	*tree1;
	CGPolyMesh	*tree2;

	tree1 = Tree->getMeshAtIndex(0);
	tree2 = Tree->getMeshAtIndex(1);

	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, treeTexture[1]);
	tree1->render();
	glBindTexture(GL_TEXTURE_2D, treeTexture[0]);
	tree2->render();
	glDisable(GL_TEXTURE_2D);
}
void drawTrees()
{
	glPushMatrix();
	glTranslatef(10.0,0.0,25.0);
	drawTree();
	glTranslatef(5.0,0.0,3.0);
	drawTree();
	glPopMatrix();
	glPopMatrix();
	
}
void drawCar(float carZ)
{

	glPushMatrix();
	glScalef(0.1,0.1,0.1);
	glRotatef(90.0,0.0,90.0,0.0);
	glTranslatef(-6.0,3.0,carZ);
	glEnable(GL_TEXTURE_2D);
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	Car->renderTexturedModel();
	glDisable(GL_TEXTURE_2D);
	glPopMatrix();
}



I won't be including any more in case of wondering eyes. GET YOUR OWN LOADERS :P

But saying that, my scene isn't all that great. You may notice the blocky lights since I used big ass quads. There is however a street lamp. A head and tail lights for the car. The global ambient can be altered to turn night into day on the scene. The car will also move across the road. There is movement across the plain using the WASD keys. 3D movement with the mouse and so on.

Pictures
Posted Image

and

Posted Image

This post has been edited by Kohana: 12 April 2010 - 07:28 AM

Was This Post Helpful? 10
  • +
  • -

#9 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2247
  • View blog
  • Posts: 9,237
  • Joined: 18-February 07

Re: Week #15 Challenge: OpenGL

Posted 12 April 2010 - 07:49 AM

*
POPULAR

For Java Developers may I suggest using JOGL a java OpenGL wrapper. You can get the latest version of JOGL from here or you can explore the Demos and builds via the project home page here.

I am using Eclipse 3.5 and here is how I got a sample OpenGL program working:

<edit>
Note: You only need to create the user library one time, after the first time you can just reuse your user libary. The following describes the creation of the project and the user library all at once.
</edit>

#1 Start Eclipse
#2 Start a new Java Project and give it a name (I used OpenGLTesting)
#3 Click on the libraries tab, then the "Add Library..." button on the right.
#4 Choose "User libary" then next
#5 Click on the "User library" button on the right
#6 Click on the "New" button on the user libraries page and give the library a name (I did JOGL_2.0)
#7 Click "Add JARs..." and find the location of the JOGL libraries (I put them in "C:\JavaExtras\jogl-2.0-windows-i586\lib")
#8 Select these JAR files in the lib directory and press "Open":
  • jogl.all.jar
  • nativewindow.all.jar
  • gluegen-rt.jar
  • (optionally) newt.all.jar

#9 -- if you downloaded the source and documentation you could at this time attach source but I didn't. I would however recommend doing so.
#10 set the Native Library location. Although technically you should only have to do with certain jars that have associated dll files, I just did this for all of the libraries.
--- select "Native library location" under a jar and press "Edit"
--- Browse to or PASTE IN (hint hint) the location of the lib directory: "C:\JavaExtras\jogl-2.0-windows-i586\lib" for me (note to speed up the process you can just double click on the "Native library location" and then paste in the new value. )
#11 Click Ok
#12 Click Ok
#13 Click "Finish" -- you should now have two libraries, the java run time and JOGL
#14 Click Finish

(from here I am going to assume a little more familiarity with Eclipse, if you need more detail please PM me with a query or ask in the Java Forum)
Now in the new Java project start a new package, I called mine: "dic.jogl.testing"

Then I created a new class in the package called "JOGLTest"

HEre is my Source code (note I am no OpenGL guru so don't look at this as an example of how to do things "right"):
package dic.jogl.testing;

import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.nio.DoubleBuffer;

import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.awt.GLCanvas;
import javax.media.opengl.glu.GLU;

import com.sun.opengl.util.Animator;
import com.sun.opengl.util.FPSAnimator;

public class JOGLTest implements GLEventListener {
	GLU glu = new GLU();
	GL2 gl;

	int xQuads;
	int yQuads;

	/*
	 * Phase shift for equation -- used to animate sinusoidal surface.
	 */
	double phase = 0;
	double angle = 0;

	/*
	 * Place to save the current Model View
	 */
	DoubleBuffer modelView = DoubleBuffer.allocate(16);
	DoubleBuffer modelLight = DoubleBuffer.allocate(16);

	/*
	 * Some useful values for the model
	 */

	float[] lightpos = { 0f, 5f, 25f, 1f };
	float[] lightdir = { -1f, -1f, 1f, 0f };

	float[] lightcolor = { 1f, 1f, 1f, 1f };
	float[] colorBlack = { 0.0f, 0.0f, 0.0f, 1.0f };
	float[] colorWhite = { 1.0f, 1.0f, 1.0f, 1.0f };
	float[] colorGray = { 0.5f, 0.5f, 0.5f, 1.0f };
	float[] colorRed = { 1.0f, 0.0f, 0.0f, 1.0f };
	float[] colorBlue = { 0.0f, 0.0f, 0.1f, 1.0f };
	float[] colorYellow = { 1.0f, 1.0f, 0.0f, 1.0f };
	float[] colorLightYellow = { .5f, .5f, 0.0f, 1.0f };

	public JOGLTest(int xq, int yq) {
		xQuads = xq;
		yQuads = yq;
	}

	@Override
	public void init(GLAutoDrawable drawable) {
		gl = drawable.getGL().getGL2();
	}

	@Override
	public void display(GLAutoDrawable drawable) {
		// GL2 gl = drawable.getGL().getGL2();
		// resizeGL(this.width(), this.height());
		// draw the scene:
		// ...
		gl.glClearColor(0.5f, 0.8f, 0.5f, 0);
		gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);
		gl.glMatrixMode(GL2.GL_MODELVIEW);
		gl.glEnable(GL2.GL_LIGHT0);
		gl.glEnable(GL2.GL_DEPTH_TEST);
		gl.glMatrixMode(GL2.GL_MODELVIEW);
		gl.glPushMatrix();
		{
			gl.glLoadMatrixd(modelView);
			// gl.glRotated(.5, .5, 1, .5);
			// Rotate about the Z axis
			gl.glRotated(0.5, 0, 1, 0);
			calculateSurface(-8, -8, 8, 8, xQuads, yQuads);
			gl.glGetDoublev(GL2.GL_MODELVIEW_MATRIX, modelView);
		}
		gl.glPopMatrix();
		// Here we adjust the phase for the next iteration
		phase += .125;

		// Since we are dealing with a sinusoidal surface we can wrap at 2Pi
		if (phase >= 2 * Math.PI) {
			phase = 0;
		}
	}

	/**
	 * This is where I am currently calculating the points and drawing the
	 * surface. Later this will be broken up into more logical units.
	 * 
	 * @param ix
	 *            -- the initial (x,z) coordinates
	 * @param iz
	 * @param xw
	 *            -- The width of the surface along x axis
	 * @param zw
	 *            -- The width of the surface along z axis (actually the z-axis
	 *            in OpenGL)
	 * @param xf
	 *            -- Number of points along the x-axis
	 * @param zf
	 *            -- Number of points along the z-axis
	 */
	private void calculateSurface(double ix, double iz, double ex, double ez,
			int xf, int zf) {
		double xs = (ex - ix) / xf;
		double zs = (ez - iz) / zf;
		double x, z, magnitude;
		double[][] zvalues = new double[xf][zf];
		double[][] xvalues = new double[xf][zf];
		double[][] yvalues = new double[xf][zf];

		for (int i = 0; i < xf; i++) {
			x = ix + xs * i;

			for (int j = 0; j < zf; j++) {
				z = iz + zs * j;
				magnitude = Math.sqrt(z * z + x * x);
				yvalues[i][j] = 1 / (.15 * magnitude + .125)
						* Math.cos(2 * magnitude - phase);
				xvalues[i][j] = x;
				zvalues[i][j] = z;
			}
		}

		// Fill in the quads -- effect is hidden line removal.
		// gl.glEnable( GL2.GL_COLOR_MATERIAL);
		gl.glPolygonMode(GL2.GL_FRONT_AND_BACK, GL2.GL_FILL);
		gl.glEnable(GL2.GL_POLYGON_OFFSET_FILL);
		gl.glPolygonOffset(1.0f, 1.0f);
		drawFrmArrays(xvalues, yvalues, zvalues, false);
		gl.glDisable(GL2.GL_POLYGON_OFFSET_FILL);
	}

	/**
	 * Draw the actual Quads... Here is where the surface is actually drawn.
	 */
	private void drawFrmArrays(double[][] xvalues, double[][] yvalues,
			double[][] zvalues, boolean drawNormals) {
		double x1, y1, z1, x2, y2, z2, nx, ny, nz;

		for (int i = 0; i < xvalues.length - 1; i++) {
			for (int j = 0; j < zvalues[0].length - 1; j++) {
				x1 = xvalues[i + 1][j] - xvalues[i][j];
				y1 = yvalues[i + 1][j] - yvalues[i][j];
				z1 = zvalues[i + 1][j] - zvalues[i][j];
				x2 = xvalues[i][j] - xvalues[i][j + 1];
				y2 = yvalues[i][j] - yvalues[i][j + 1];
				z2 = zvalues[i][j] - zvalues[i][j + 1];
				nx = y1 * z2 - z1 * y2;
				ny = z1 * x2 - x1 * z2;
				nz = x1 * y2 - y1 * x2;
				double size = Math.sqrt(nx * nx + ny * ny + nz * nz);
				nx /= size;
				ny /= size;
				nz /= size;
				float[] color = { .1f, .5f, .8f, .1f };
				gl.glBegin(GL2.GL_QUADS);
				{
					gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_AMBIENT_AND_DIFFUSE
							| GL2.GL_SPECULAR, color, 0);
					gl.glNormal3d(nx, ny, nz);
					gl.glVertex3d(xvalues[i][j + 1], yvalues[i][j + 1],
							zvalues[i][j + 1]);
					gl.glVertex3d(xvalues[i + 1][j + 1], yvalues[i + 1][j + 1],
							zvalues[i + 1][j + 1]);
					gl.glVertex3d(xvalues[i + 1][j], yvalues[i + 1][j],
							zvalues[i + 1][j]);
					gl.glVertex3d(xvalues[i][j], yvalues[i][j], zvalues[i][j]);
				}
				gl.glEnd();

				// Draw The normals
				if (drawNormals) {
					gl.glBegin(GL2.GL_LINES);
					{
						gl.glColor3d(1, 0, 0);
						gl.glVertex3d(xvalues[i][j], yvalues[i][j],
								zvalues[i][j]);
						gl.glVertex3d(xvalues[i][j] + nx / 3, yvalues[i][j]
								+ ny / 3, zvalues[i][j] + nz / 3);
						gl.glColor3d(.1, .5, .8);
					}
					gl.glEnd();
				}
			}
		}
	}

	@Override
	public void dispose(GLAutoDrawable arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void reshape(GLAutoDrawable drawable, int x, int y, int width,
			int height) {
		double aspect = (float) width / (float) height;
		gl.glEnable(GL2.GL_NORMALIZE);
		gl.glEnable(GL2.GL_LIGHTING);
		gl.glMatrixMode(GL2.GL_PROJECTION);
		gl.glLoadIdentity();
		gl.glViewport(0, 0, width, height);
		glu.gluPerspective(65, aspect, .001, 120);
		gl.glGetDoublev(GL2.GL_MODELVIEW_MATRIX, modelLight);
		gl.glMatrixMode(GL2.GL_MODELVIEW);
		gl.glPushMatrix();
		{
			gl.glLoadIdentity();
			gl.glTranslated(0, -2, -15);
			gl.glRotated(45, 1, 0, 0);
			gl.glGetDoublev(GL2.GL_MODELVIEW_MATRIX, modelView);
		}
		gl.glPopMatrix();
	}

	public static void main(String[] args) {
		GLCapabilities caps = new GLCapabilities(null);
		GLCanvas canvas = new GLCanvas(caps);
		JOGLTest test = new JOGLTest(128, 128);
		canvas.addGLEventListener(test);
		final Animator animator = new FPSAnimator(canvas, 60);
		Frame frame = new Frame("JOGL Testing");
		frame.add(canvas);
		frame.setSize(640, 480);
		frame.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				new Thread(new Runnable() {
					public void run() {
						animator.stop();
						System.exit(0);
					}
				}).start();
			}
		});
		frame.setVisible(true);
		animator.start();
	}
}



The above program produces this an animated version of this sinusoidal surface:
Attached Image
Was This Post Helpful? 10
  • +
  • -

#10 programble  Icon User is offline

  • (cons :dic :head)

Reputation: 49
  • View blog
  • Posts: 1,315
  • Joined: 21-February 09

Re: Week #15 Challenge: OpenGL

Posted 12 April 2010 - 05:27 PM

View PostRaynes, on 12 April 2010 - 01:42 AM, said:

That 'complete' list isn't quite as complete as you might think. I'm about to edit it to include these awesome OpenGL bindings for Clojure.

I've never played with OpenGL or graphics in general. I'll experiment and try to get a neat Clojure submission in by the end of the week. :>


I might try that as well :P
Was This Post Helpful? 0
  • +
  • -

#11 SixOfEleven  Icon User is offline

  • using Caffeine;
  • member icon

Reputation: 942
  • View blog
  • Posts: 6,342
  • Joined: 18-October 08

Re: Week #15 Challenge: OpenGL

Posted 12 April 2010 - 08:26 PM

Hope to take a stab at this one. Have been looking at GLUT for a little while as a distraction. Hopefully over the weekend I can get something up and running. Might look into doing something with OpenAL for audio as well but can't be certain on that one.
Was This Post Helpful? 0
  • +
  • -

#12 Skaggles  Icon User is offline

  • THE PEN IS MIGHTIER
  • member icon





Reputation: 251
  • View blog
  • Posts: 640
  • Joined: 01-March 09

Re: Week #15 Challenge: OpenGL

Posted 13 April 2010 - 12:50 AM

*
POPULAR

Here's a little something I just threw together tonight while waiting on my other computer to finish installing stuff. It's nothing too crazy, but it shows the basic setup of GLUT (using freeGLUT). It should compile on Windows and Linux just fine.

#include <stdio.h>
#include <stdlib.h>

#include <GL/freeglut.h>

GLfloat rotation, cubeX, cubeY = 0.0f; /* cube x, y, and x rotation */

/* render a basic wireframe cube using glutWireCube() */
void display(void)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glColor3f(1.0f, 1.0f, 1.0f);
    glLoadIdentity();
    
    gluLookAt(0.0f, 0.0f, 5.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);

    glTranslatef(cubeX, cubeY, 0.0f);
    glRotatef(rotation, 1.0f, 1.0f, 1.0f);

    glutWireCube(2);
    
    glFlush();
    glutSwapBuffers();
    
    rotation = rotation + 0.5f;
}

/* resize the display when the window is resized */
void reshape(int width, int height)
{
    glViewport(0, 0, (GLsizei)width, (GLsizei)height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(60, (GLfloat)width / (GLfloat)height, 1.0f, 100.0f);
    glMatrixMode(GL_MODELVIEW);
}

/* just checking for escape key being pressed here */
void keyboard(unsigned char key, int x, int y)
{
    if (key == '\x1b') {
        exit(0);
    }
}

/* checking for arrow keys */
void special(int key, int x, int y)
{	
	if (key == GLUT_KEY_LEFT)
	{
		cubeX = cubeX - 0.1f;
		if (cubeX <= -5.0f)
		{
			cubeX = 5.0f;
		}
	}
	
	if (key == GLUT_KEY_RIGHT)
	{
		cubeX = cubeX + 0.1f;
		if (cubeX >= 5.0f)
		{
			cubeX = -5.0f;
		}
	}
	
	if (key == GLUT_KEY_UP)
	{
		cubeY = cubeY + 0.1f;
		if (cubeY >= 5.0f)
		{
			cubeY = -5.0f;
		}
	}
	
	if (key == GLUT_KEY_DOWN)
	{
		cubeY = cubeY - 0.1f;
		if (cubeY <= -5.0f)
		{
			cubeY = 5.0f;
		}
	}
    
    /* print the cube's current x, y position */
    printf("X: %.2f, Y: %.2f\n", cubeX, cubeY);
}

int main(int argc, char **argv)
{
    printf("Initializing OpenGL...\n");
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    
    printf("Creating OpenGL window...\n");
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(200, 200);
    glutCreateWindow("OpenGL Test");
    glClearColor(0.4f, 0.5f, 0.9f, 0.0f);
    
    printf("Rendering OpenGL window...\n");
    glutDisplayFunc(display);
    glutIdleFunc(display);
    glutReshapeFunc(reshape);
    glEnable(GL_DEPTH_TEST);
    
    printf("Doing some other stuff...\n");
    glutKeyboardFunc(keyboard);
    glutSpecialFunc(special);
    
    printf("Entering application loop...\n");
    printf("Use the arrow keys to move the cube.\n");
    printf("Press ESC to quit.\n");
    glutMainLoop();

    return 0;
}


This post has been edited by Skaggles: 13 April 2010 - 12:52 AM

Was This Post Helpful? 5
  • +
  • -

#13 yondaime  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 16-August 09

Re: Week #15 Challenge: OpenGL

Posted 13 April 2010 - 10:28 AM

about five months age we get a graphic homework and it was about doing something in OpenGl
I chose to design a living room. it was containing sofas, table and its chairs, television (displaying many photos), and there was a light and a switch to turn it on/off
I hope I can find it and put it here but i don't promise sorry :(
thanx for the challenge
Was This Post Helpful? 0
  • +
  • -

#14 Dogstopper  Icon User is online

  • The Ninjaducky
  • member icon



Reputation: 2858
  • View blog
  • Posts: 10,963
  • Joined: 15-July 08

Re: Week #15 Challenge: OpenGL

Posted 13 April 2010 - 01:17 PM

What the?! I thought I posted here last night...

Anyway, I tested out some JOGL following NickDMax's advise and some random tutorial I found. The tutorials for it are surprisingly not to common, but as the Java game guy round here, I thought I oughta learn it. Well, I gave it a shot. It's not the best, but it draws a Cartesian plane and draws a line on using point-slope form.

Frame class
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.Toolkit;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.media.opengl.awt.GLCanvas;
import javax.media.opengl.GLCapabilities;



public class SimpleJoglApp extends Frame implements ActionListener {
	
	GLCanvas glCanvas;
	SimpleGLEventListener listener =  new SimpleGLEventListener();
	
	TextField xField = new TextField("0", 3);
	TextField yField = new TextField("0", 3);
	TextField slopeField = new TextField("-1", 3);
	

	/**
	 * Kickoff the Jogl JFrame.
	 */
	public static void main(String[] args) {
		new SimpleJoglApp().setVisible(true);
	}
	
	public SimpleJoglApp() {
		super("Cartesian Plane");
		
		addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
            	System.exit(0);
            }
		});
		
		Panel south = new Panel();
		
		south.add(new Label("x:"));
		south.add(xField);
		south.add(new Label("y:"));
		south.add(yField);
		south.add(new Label("Slope:"));
		south.add(slopeField);
		
		Button but = new Button("Draw Line");
		but.addActionListener(this);
		south.add(but);
		
		add(south, BorderLayout.SOUTH);
		
		GLCapabilities glCapabilities = new GLCapabilities(null);
		glCanvas = new GLCanvas(glCapabilities);
		glCanvas.addGLEventListener(listener);
		
		add(glCanvas, BorderLayout.CENTER);
		setSize(500,300);
		
		centerWindow(this);
	}

	private void centerWindow(Component c) {
		Dimension screenSize =	Toolkit.getDefaultToolkit().getScreenSize();
		Dimension frameSize = c.getSize();
		
		if (frameSize.width > screenSize.width) 
			frameSize.width = screenSize.width;
		if (frameSize.height > screenSize.height)
			frameSize.height = screenSize.height;
		
		c.setLocation(
			(screenSize.width - frameSize.width) >> 1,
			(screenSize.height - frameSize.height) >> 1
		);
		
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		listener.a = Double.parseDouble(xField.getText());
		listener.b = Double.parseDouble(yField.getText());
		listener.m = Double.parseDouble(slopeField.getText());
		glCanvas.repaint();
		
	}

}



Event Handling class
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.glu.GLU;


public class SimpleGLEventListener implements GLEventListener {
	
    GLU glu = new GLU();
    GL2 gl;
    
    public double a = 0;
    public double b = 0;
    public double m = -1;
    
    float red;
    float green;
    float blue;
    

	@Override
	public void display(GLAutoDrawable drawable) {
		gl = drawable.getGL().getGL2();
		drawGraph(gl);
		
		red = 1.0f;
		green = 0.2f;
		blue = 0.2f;
		
		gl.glColor3f(red, green, blue);
		
		gl.glBegin(gl.GL_POINTS);
		
			// Each point is actually every 10 pixels
			a *= 10;
			b *= 10;
			
			for (int x = -250; x <= 250; x++) {
				gl.glVertex2d(x, (m * (x - a) + B)/>);
			}
		gl.glEnd();
		
		// Make the point
		red = 1.0f;
		green = 1.0f;
		blue = 1.0f;
		gl.glColor3f(red, green, blue);
		
		gl.glPointSize(4.0f);
		
		gl.glBegin(gl.GL_POINTS);
			gl.glVertex2d(a, B)/>;
		gl.glEnd();
		
		// reset dot size
		gl.glPointSize(2.0f);
	}


	private void drawGraph(GL2 gl) {
		gl.glClear(gl.GL_COLOR_BUFFER_BIT);
		
		// This should make a non-intrusive grey color.
		red = 0.3f; 
		green = 0.3f;
		blue = 0.3f;
		
		gl.glColor3f(red, green, blue);
		gl.glLineWidth(2.0f);
		
		gl.glBegin(GL.GL_LINES);
			// Vertical Lines
			for (int x = -250; x <= 250; x += 10) {
				gl.glVertex2d(x, -150);
				gl.glVertex2d(x, 150);
			}
			
			// Horizontal Lines
			for ( int y = -150; y <= 150; y += 10) {
				gl.glVertex2d(-250, y);
				gl.glVertex2d(250, y);
			}
		gl.glEnd();
		
		// Draw the X and Y axis now.
		red = 0.0f;
		green = 0.4f;
		blue = 0.6f;
		gl.glColor3f(red, green, blue);
		
		gl.glBegin(GL.GL_LINES);
			// Y Axis
			gl.glVertex2d(0, -140);
			gl.glVertex2d(0, 140);
			
			// X Axis
			gl.glVertex2d(-240, 0);
			gl.glVertex2d(240, 0);
		gl.glEnd();
		
		// Draw the heads of the arrows.
		gl.glBegin(gl.GL_TRIANGLES);
			gl.glVertex2d(0, 150);
			gl.glVertex2d(-5, 140);
			gl.glVertex2d(5, 140);
			
			gl.glVertex2d(0, -150);
			gl.glVertex2d(-5, -140);
			gl.glVertex2d(5, -140);
			
			gl.glVertex2d(-250, 0);
			gl.glVertex2d(-240, 5);
			gl.glVertex2d(-240, -5);
			
			gl.glVertex2d(250, 0);
			gl.glVertex2d(240, 5);
			gl.glVertex2d(240, -5);
		gl.glEnd();
	}

	@Override
	public void init(GLAutoDrawable gld) {
		gl = gld.getGL().getGL2();
		
		gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
		
		gl.glLineWidth(2.0f);
		
		gl.glViewport(-250, -150, 250, 150);
		gl.glMatrixMode(GL2.GL_PROJECTION);
		gl.glLoadIdentity();
		glu.gluOrtho2D(-250.0, 250.0, -150.0, 150.0);
	}

	@Override
	public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3,
			int arg4) {}


	@Override
	public void dispose(GLAutoDrawable arg0) {
		// TODO Auto-generated method stub
		
	}

}


Was This Post Helpful? 4
  • +
  • -

#15 gareth00  Icon User is offline

  • New D.I.C Head

Reputation: 5
  • View blog
  • Posts: 49
  • Joined: 08-May 09

Re: Week #15 Challenge: OpenGL

Posted 13 April 2010 - 07:30 PM

QT is a great alternative to GLUT in my opinion. It provides great cross-platform UI design and a wealth of useful libraries. There are some openGL examples that are easy to follow. I have tried both, and I will never use GLUT again.

I swear I was not paid to Nokia to say this!
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2