26286 total geeks with 3498 solutions
Recent challengers:
 Welcome, you are an anonymous user! [register] [login] Get a yourname@osix.net email address 

Articles

GEEK

User's box
Username:
Password:

Forgot password?
New account

Shoutbox
MaxMouse
It's Friday... That's good enough for me!
CodeX
non stop lolz here but thats soon to end thanks to uni, surely the rest of the world is going good?
stabat
how things are going guys? Here... boring...
CodeX
I must be going wrong on the password lengths then, as long as it was done on ECB
MaxMouse
lol... the key is in hex (MD5: of the string "doit" without the "'s) and is in lower case. Maybe i should have submitted this as a challenge!

Donate
Donate and help us fund new challenges
Donate!
Due Date: May 31
May Goal: $40.00
Gross: $0.00
Net Balance: $0.00
Left to go: $40.00
Contributors


News Feeds
The Register
Yahoo! Oz! PAYS!
Punters! Pittance!
To! Search!
AMD"s three new
low-power chips
pose potent
challenge to Intel
Social network bins
Beijing"s banned
buzzwords
Footy lovers hit in
Wembley playoff
card snatch scam
Fairphone goes on
sale to all
SCADA security is
better and worse
than we think
Herschel Space
Observatory spots
galaxies merging
Ctl-P for pizza
Report: China IP
theft now equal in
value to US exports
to Asia
Kim Dotcom claims
invention of
two-factor
authentication
Slashdot
Teens, Social
Media, and Privacy
Physicists Create
Quantum Link
Between Photons
That Don"t Exist At
the Same Time
Missile Test
Creates Huge
Expanding Halo of
Light Over Hawaii
3D Printers For
Peace Contest
Intel"s Linux
OpenGL Driver
Faster Than Apple"s
OS X Driver
Rough Roving:
Curiosity"s Wheels
Show Damage
Tesla Motors Repays
$465M Government
Loan 9 Years Early
Why the "Star Trek
Computer" Will Be
Open Source and
Apache Licensed
NYPD Detective
Accused of Hiring
Email Hackers
Scientists Find
Vitamin C Kills
Drug-Resistant
Tuberculosis
Article viewer

Getting started with OpenGL



Written by:dimport
Published by:Nightscript
Published on:2003-06-21 07:19:46
Topic:C
Search OSI about C.More articles by dimport.
 viewed 6883 times send this article printer friendly

Digg this!
    Rate this article :
Welcome to the first tutorial on OpenGL. This tutorial assumes that you have basic knowledge of c++. In this tutorial you will learn how to initialize an OpenGL window and how to display a 3D triangle on the screen.

The first step is to initialize the window. There are two ways to do this. The first is to use windows code to set up the window, and the other way is to use GLUT which stands for GL Utility Toolkit. This greatly simplifies window creation and makes porting very easy. In this tutorial we will be using GLUT to initialize the window to minimize confusion.

You will first have to install GLUT if you have not already done so, you can obtain pre-compiled binaries form here: http://www.xmission.com/~nate/glut.html .

Don't forget to link OpenGL32.lib, GLu32.lib and GLUT32.lib otherwise your OpenGL programs won't compile.

Now that you have installed GLUT we are ready to start coding.


 
#ifdef _WIN32
 #include
 #endif
 
 
#include
 #include
 #include


The first 3 lines check if we are using windows and if so it includes "windows.h" which is required in a windows OpenGL application. The next 3 lines are the headers nessesary for us to use OpenGL in our program.

 int main(int argc, char *argv[])
 {
 glutInit (&argc,argv);
 glutInitDisplayMode (GLUT_DOUBLE|GLUT_RGB);
 glutInitWindowSize (640, 480);
 glutInitWindowPosition (0, 0);
 glutCreateWindow ("OpenGL lesson 1");
 
 
init ();
 glutDisplayFunc (render);
 glutReshapeFunc (reshape);
 glutMainLoop ();
 return 0;
 }
 


GLUT requires that you initialize it in the main() function which is what we are doing here. The first line simply initializes GLUT. The second line tells GLUT what kind of a display we want to use. The two parameters we send to it are GLUT_DOUBLE which means that we want a double buffered window and GLUT_RGB. Then we specify the window size and window position. The two calls 'glutDisplayFunc' and 'glutReshapeFunc' tell GLUT which of our functions to call when it needs to draw the scene and reshape the window. Functions that you pass to GLUT like this must be voids and not accept extra parameters unless they are supposed to. The next call tells GLUT to enter its main loop where it automaticaly calls functions like reshape and render when needed, it does not return once called.

 
 void init(void)
 {
 glClearColor(0.0 , 0.0 , 0.0 , 0.0);
 glShadeModel(GL_SMOOTH);
 
 
glClearDepth(1.0f);
 glEnable(GL_DEPTH_TEST);
 glDepthFunc(GL_LEQUAL);
 
 
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
 }



This function is called during initialization before the main loop is entered. The first line sets the clear colour, the colour with which the screen is cleared, to black. The first 3 numbers are the intensities of red, green and blue. The fourth number is the alpha value but dont worry about that when clearing the screen. The second line tells OpenGL that we want to use smooth shading on our polygons which means that colours will be 'spread' accross polygons rather then looking flat. The middle 3 lines set up the depth buffer. The depth buffer is what sorts out which objects to draw first so that if there is an object in front of another object it is drawn that way. The final line improves the look of the perspective.


void render(void)
 {
 glClear(GL_COLOR_BUFFER_BIT);
 glLoadIdentity();
 
 
glTranslatef(0.0, 0.0, -4.0);
 
 
glBegin(GL_TRIANGLES);
 glVertex3f(-1.0, -1.0, 0.0);
 glVertex3f(1.0, -1.0, 0.0);
 glVertex3f(0.0, 1.0, 0.0);
 glEnd();
 
 
glutSwapBuffers();
 }


This is where the stuff gets drawn on to the screen. First the scene is cleared with the colour we specified in our init()function, which in our case is black. 'glLoadIdentity()' tells OpenGL to reset the current matrix which is the modelview matrix.

The model view matrix contains data for the current position and rotation of the camera. A matrix is a 2D array of numbers which are used to store information. The next line tells OpenGL to move the camera back by 4.0 measurments.

In OpenGL the camera looks down the Z axis by default, so moving negatively along the Z axis will result in the camera moving backwards. The reason we do this is that because the triangle we are about to draw will be drawn at position 0,0,0 by default, where the camera starts off, so if we dont move the camera back we won't be able to see it.

Next we put something on the screen. To do this we first have to specify the type of objects we want to draw, we do this with 'glBegin(GL_TRIANGLES)' which tells OpenGL that we want to draw triangles. The next 3 lines specify positions in space where points should be plotted, when using GL_TRIANGES every 3 points that are specified are linked together to draw a triangle, if for example only 5 points are specified only one trialnge will be drawn using the first 3 points. The points are specified as X,Y,Z. 'glEnd()' tells OpenGL that we have finished specifing points.

Remember how we told GLUT to use double buffer mode? well this is where it comes into effect. First the objects are drawn onto the unseen buffer, then the buffers are swaped to reveal what was drawn.


 
void reshape(GLint width, GLint height)
 {
 glViewport(0, 0, width, height);
 glMatrixMode(GL_PROJECTION);
 glLoadIdentity();
 gluPerspective(65.0, (float)width / height, 1, 1000);
 glMatrixMode(GL_MODELVIEW);
 }



This function is called by GLUT when the window needs to be reshaped. The first line resets the viewport to the new size of the window. Then the projection matrix is reset in the next 2 lines and after that the perspective matrix is set up. The perspective matrix is what adds perspective to the scene, meaning that things get smaller in the distance. Then the model view matrix is reset.

The code in this tutorial should produce a white, static triangle in the middle of a black scene. I hope you have enjoyed reading this tutorial and have gained something from it."

This article was originally written by barnseyboy

Did you like this article? There are hundreds more.

Comments:
<none>
Anonymously add a comment: (or register here)
(registration is really fast and we send you no spam)
BB Code is enabled.
Captcha Number:


Blogs: (People who have posted blogs on this subject..)
amisauv
Creating a Lexical Analyzer in C on Tue 9th Dec 11am
#include<stdio.h> #include<string.h> #include<conio.h> #include<ctype.h> /*************************************** ************************* Functions prototype. **************************************** *************************/ void Open_File(
amisauv
Controling digital circuit through computer on Tue 9th Dec 10am
this code access the lpt port.here only 4 of the total 8 pins are used but can be modified for full 8 pins.it has a complete GUI with mouse & keyboard interactive control panel.works well in win98, but not in winxp. #include<stdio.h> #include<conio.
amisauv
/* Computerised Electrical Equipment Control */ /* PC BASED DEVICE CONTROLLER * on Tue 9th Dec 10am
#include<stdio.h> #include<conio.h> #include<dos.h> void main() { void tone(void); int p=0x0378; char ex={"Created By Mrc"}; int j; char ex1={"For Further Details & Improvements"}; int k; char ex2={"Contact : E-mail : anbudan
amisauv
Calendar Program on Tue 9th Dec 10am
This program prints Weekdays of specified date. It even prints calendar of a given year too. /*Ccalendar library*/ #include<stdio.h> #include<string.h> #include<conio.h> int getNumberOfDays(int month,int year) { switch(month) { case
amisauv
Calculator: on Tue 9th Dec 10am
#include"graphics.h" #include"dos.h" #include"stdio.h" #include"math.h" union REGS i,o; char text={ "7","8","9","*","4","5","6","/","1","2", "3","+","0","00",".","-","M","M+", "M-","+/-","MR","MC","x^2","sr","OFF","A C","CE","="}; int s=0,k=0,pass
amisauv
INFECTED CODES WRITTEN IN C\C++ on Tue 9th Dec 10am
This is a simple code that changes system time and date. It is written using c/c++ but can be easily converted to java. #include "stdio.h" #include "process.h" #include "dos.h" int main(void) { struct date new_date; struct date old_date; s
amisauv
A C programme which can print the file name it is kept in on Tue 9th Dec 9am
#include<stdio.h> main(){ printf(”the source file name is %s\n”,__FILE__); } actually __FILE__ is a macro which stands for the file name the programme is kept in and the compiler does the rest .. for you ..
amisauv
BOOTSECTOR EDITOR: on Tue 9th Dec 9am
Code : /*program to save the partion table of your hard disk for future use. it will save your partition table in a file partition.dat */ #include<stdio.h> #include<bios.h> #include<conio.h> #include<stdlib.h> #include<ctype.h> void main () {
amisauv
BLINKING STAR : on Tue 9th Dec 9am
#include<conio.h> #include<graphics.h> #include<stdlib.h> #include<dos.h> void main() { int gdriver=DETECT,gmode; int i,x,y; initgraph(&gdriver,&gmode,"e: cgi"); while(!kbhit()) { x=random(640); y=random(480); setcolor
amisauv
// To print semicolons using C programming without using semicolons any where i on Tue 9th Dec 9am
// To print semicolons using C programming without using semicolons any where in the C code in program. // #include<stdio.h> #include<conio.h> void main() { char a; a=59; if(printf("%c",a)){} getch();

Test Yourself: (why not try testing your skill on this subject? Clicking the link will start the test.)
BSD sockets API by skrye

This is a test of your knowledge of the BSD socket interface
C Programming by keoki

This test is aimed at a C programmer that is at an intermediate level.


     
Your Ad Here
 
Copyright Open Source Institute, 2006