Search Projects

Thursday, October 5, 2017

Doll - OpenGL programming using glut

Every Child likes doll, play with it. Every adult used to have as decor item in their collections. In this post we are going to draw a doll with OpenGL Programming using Glut. We will use the c/c++ and opengl glut to draw a beautiful doll.


1. Outline of the Doll

First we will outline how our doll should look like. We are going to draw a simple doll, hence we are not going to have complex attire for it. The doll will have head. without hair - simply bald.  It will have coat and pant as cloths and the black shoes. The coat will be simple with few button fully closed.

The doll should look straight forward. The eye would be more opened liked an egg and eyebrow to be cross not parallel nor it is curve. Colors are choice of programmers, hence if you want you can adjust with it as you want it to be.

OpenGL Programming using Glut


2. Draw Doll in OpenGL

As we finished outlining the doll, so we will go to coding part of it. In this OpenGL Programming using Glut, the shape of doll is code as head first, middle part and then legs.

Face/head is coded using the sphere (gluSphere(gluNewQuadric(),1,100,100);) and put egg like shape with dot on it for eyes. A big line will drawn with high thickness to have the eyebrow. Again same gluSphere(gluNewQuadric() is used for drawing the mouse but radius would be very small. Both left and right, eyes as well as eyebrow is coded separately. All object is drawn using transformation matrix.

The Middle part have neckring which is drawn by the use of glutSolidTorus.  Next is the coat and buttons. The belly coat is drawn by using gluCylinder(gluNewQuadric() and the transformation matrix. There is three button each a small sphere.

Bellycoatbottom is drawn using the gluDisk(gluNewQuadric(),0,.8,30,30);, yeah with matrix. Last is shoes which covered by gluSphere in footright and footleft functions.


3. Rendering

Before we go to the one of the main features let first define the global variable that will define initial camera position and viewing window values. Also it is important to define Initialization values for lighting.

We have defined a function which will render the object to make it look more realistic. It helps in enable depth testing, lightning - Ambient, Diffuse and Specular.

4. User Interaction

One of the important part of this OpenGL Programming using Glut is the user interaction. Here we have both keyboard as well as Mouse interactions. With the help of mouse doll can be move in either of directions. Keyboard interactions is listed below-

GLUT_KEY_UP - move one up scaling
GLUT_KEY_DOWN - move one down scaling
GLUT_KEY_RIGHT- move one step right
GLUT_KEY_LEFT- move one step left
GLUT_KEY_F10 - toggle whole screen
GLUT_KEY_F9 - toggle doll with interaction

5. Final Thought

We are able to draw a computer graphics doll with the help of OpenGL Programming using Glut in C/C++. This program have used the lighting and depth of material which is one of the feature of opengl to give a 3D touch to the objects.

Do download the source code and share your experience thoughts suggestions etc to us via comments. You can also contact us for any help or any other query use our contact form. Happy learning! Happy Coding!.


Thursday, September 7, 2017

"Ray" OpenGL Sample Program in Visual Studio

There are many OpenGL sample program  written in early days of OpenGL Development. These Sample Program or sample code written by many of the authors in top university.

In this post were are going to talk about one such sample code written by David Bucciarelli (tech.hmw@plus.it). This article aims to improvise knowledge of seekers, who want to learn opengl programming with sample code. The download source code from the link in the post for this opengl sample code along with mesa version uploaded to github. Do give author the credit if your are using this opengl sample code in your work projects etc.

Download Sample Code                 Github Mesa Version

1.Overview

The OpenGL Sample Program has been tested in Microsoft Visual Studio Ultimate 2010 and will works in almost all the other version as well. It can be executed on other platforms like linux, mac os etc with some modification.

The program consist of  mainly a light source and a spherical mirror placed on square strips. There are other sections like help section and two maps one for texture of plane and other for texture of sphere.

The Program is user interactive, allow use to give input and get desire output. The user interaction has been code with keyboard functionality of OpenGL.

"Ray" OpenGL Sample Program in Visual Studio

2. The OpenGL Sample Program

The Ray V.10 Written by David Bucciarelli is our OpenGL sample program. You need to have MS visual studio to get started with. Also you need to setup the OpenGL environment to execute the apis provided by them for this opengl sample code. Learn how to setup opengl in MS visual studio in window.

Header Files - First of all include the header files, including glut in the program as we do in "hello world opengl". Thereafter write down the global variable which goes on the way as program progress.

Functions - This program have many functions including the basic opengl function like init, reshape, key and main. We have other functions which is created for drawing the objects. Since we required these function to do our work they are called and used in program.

User Interaction - The key board and special key function is written so user can give input and interact with our program.

3. Coding

There is two object - light source and mirror for reflection. We are going to draw both of them with the help of sphere. Hence we need to call the function for drawing sphere. First of all define the radius for the sphere and then also define the width and height for texture (strips) and it's reflection. Also define the frame rate as we are going to use it as well.

Now we will see all the function one by one (excludes basic functions).

gettime(void) - with use of glutget function this function used to check the status of glut and time with GLUT_ELAPSED_TIME.

calcposobs(void) - defines the position (direction) of observer.

special(int k, int x, int y) - define specil keyboard functions for left, right, up and down navigation keys.

key(unsigned char k, int x, int y) - normal user interaction functions assign to different keys.

printstring(void *font, char *string) -  to print the string.

printhelp(void) - use printstring() and display help box. Font we are using is GLUT_BITMAP_HELVETICA (12 and 18 size).

seelight(float p[3],float dir[3]) - the light source.

colorcheckmap(float ppos[3], float c[3]) - this draw the plane map.

updatecheckmap(int slot) - update plane map with change cause by user interaction.

updatereflectmap(int slot) - update reflection map with change cause by user interaction.

drawbase(void) - Our base is square strips or checkers, this function draws it.

drawobj(void) - draw objects.

dojoy(void)- for joystick functions.

updatemaps(void) - Update maps

draw(void) - Finally draws everything on the screen by rendering objects.

initspherepos(void) - details the sphere position.

inittextures(void) - for textures

initdlists(void) - lists

4. User Interactions

The user interaction in this program is given below -

h - Togle Help

f - Togle Fog

b - Togle Back face culling

p - Togle Wire frame

Arrow Keys (navigation key) - Rotate in left, right, up and down respectively to respective keys

a - Increase velocity

z - Decrease velocity
if(joyavailable)
j - Togle jostick control (Joystick control available)
else
(No Joystick control available)

To move the light source: s - left, d - right, e - far, x - near, w - down r - up

To move the mirror sphere: j - left, k - right, i - far, m - near, u - down o - up

1 - Togle the plane texture map window

2 - Togle the sphere texture map window

5. Final Words

The ray - OpenGLSample Program on compilation and execution will show a checker with one mirror in sphere shape and a light source. There is also two maps in left and right. These maps show the plane and reflection textures. A helps popup like appears in beginning itself that give glimpse of all user interactions in the program. The Youtube video above is showing demo of all the functionality of this program.

If you are keen to learn and become an game programmer this program is especially relevant to you. Also in point of view of exam or project preparation is opengl sample code is an additional help.

Finally, do download this program and comment about it in the comment box.


Tuesday, August 1, 2017

3D Primtives in OpenGL

OpenGl Graphics library or OpenGl toolkit provides different API and methods to draw various 2d and 3d objects. In this post we will able show case you the basic 3d shapes. These 3d primitive can be drawn by calling the predefined methods or function in OpenGL.

What are 3D Primtives in OpenGL?

Like points,lines , traingle and polyogn in 2d we have primitives in 3d as well written in OpenGL itself. The library provide us easy access to draw the 2d Objects with one line of code. We can  use 2d primitives to draw the 3d objects but in OpenGL we have predefined code for 3d objects. We can overrides them as well. These code help quickly draw the 3d objects without writing alots of code for them.

There are many 3D objects defined but we mentioned you the 3d basics ones - Sphere, Cube (cuboid), Cone, Torus,  Icosahedron and Teapot.  These 3d objects can be drawn easily by calling the function from OPenGL graphics library, with some input likes radius, length, height and width etc.


Draw the 3D Primtives


Here we will se how to simply call the function for each 3D objects mentioned in the above para. We will also discuss about the parameter they need. In our case we are using wired 3d Objects and not solid ones.

1. Sphere

 void glutWireSphere(GLdouble radius,GLint slices, GLint stacks);

Radius, not need explanation, while slices are no of subdivisions around z-axis, stacks are no of subdivisions along the z-axis. You may consider the slices and stacks to be like of  longitude and latitudes.

2. Cube


void glutWireCube(GLdouble size);

Cube requied one parameter and that's its size.

3. Cone


void glutWireCone(GLdouble base, GLdouble height, GLint slices,
GLint stacks);

Cone is an objects with triangular face and circular bottom. The base here denotes for radius of the circular base or bottom, height is the height of cone. Similar to Sphere, slices are no of subdivisions around z-axis, stacks are no of subdivisions along the z-axis.

4. Torus


void glutSolidTorus(GLdouble innerRadius, GLdouble outerRadius,
GLint nsides, GLint rings);

A torus is an objects that is flat with hole in it's inner part and outer part to be circular. Tours examples are the tubes. The innerRadius and outerRadius represent the inner and outer radii. The nsides represent the no of sides that each radial section contains, while rings represent the no of radial divisions. These two can be understand as sections formed by cutting up to down and left to right respectively, along a fixed axis.

5. Icosahedron

void glutWireIcosahedron(void);

Icosahedron is a solid body with 20 sides. Other solid body are terahedron (4 sides), octahedron(8 sides), dodecahedron(12 sides) etc. These can be also drawn by just replacing name in above like - glutWireTetrahedron.

The GLUT provides functions for these objects with no parameters and with preassigned radii. The preassigned radii of Dodecahedron, Octahedron, Tetrahedron and Icosahedrons are, respectively, sqrt(3), 1, sqrt(3), 1.

One thing you need to do, while rendering set the raddi for them with scaling or translating.

6. Teapot


void glutWireTeapot(GLdouble size);

Here size is relative size of Teapot, which is generated with OpenGL evaluators. Both surface normals and texture coordinates for the teapot are generated.

Below is simple example of drawing these objects with a sample input data.

void drawSphere(void) {
 glutWireSphere(6.0,20,20);
}

void drawCube(void) {
 glutWireCube(6.0);
}

void drawCone(void) {
 glutWireCone(6.0, 8.0, 10, 20);
}

void drawTorus(void) {
 glutWireTorus(1.0, 6.0, 10, 20);
}

void drawIcos(void) {
 glPushMatrix();
 glScalef(6.0,6.0,6.0);
 glutWireIcosahedron();
 glPopMatrix();
}

Now, if you want to draw the solid objects insted of wired just replace wire word to solid like - glutWireCube to glutSolidCube.



You can download the source code for wired 3d primitives and solid 3d primitives.

Thursday, July 6, 2017

WireFrame SnowMan

It's Fun to lean OpenGL!

Today we are going to learn about making an WireFrame SnowMan from scratch.


1. Overview

To draw a snowman in OpenGL C++, you need to first figure out the sketch line. Entire shape need to drawn with the help of proper OpenGL primitives and placed them at proper coordinate positions. So basically you need to understand the coordinate system properly.

>Shape
The shape of Snowman looks to be a big snowball which make body, and small ball over it which forms head. Now we have two dots over the small ball for creating eye and a conical shape for nose.

>3D Coordinates
We will draw the three lines across for each of the x, y, z axis.

>User Interaction
With this program user can move the camera position to left and right and zoom in and out.


2. Draw SnowMan

To draw snow man we use the inbuilt function opengl. To draw the big ball body part, use the glutWireSphere and glutSolidSphere. To draw the eyes use only glutSolidSphere and for nose use glutSolidCone. The color has specified before same as we do in other  cases which you can change. 

glColor3f(1, 1, 1);
glTranslatef(0, 0.75, 0);
glutWireSphere(0.75, 10, 10);
glTranslatef(0, 1, 0);
glutSolidSphere(0.25, 10, 10);
glPushMatrix(); 

//Draw eyes
glTranslatef(0.1, 0, 0.23);
glColor3f(0, 0, 1);
glutSolidSphere(0.03, 10, 10);
glTranslatef(-0.2, 0, 0);
glutSolidSphere(0.03, 10, 10);

glPopMatrix();
glTranslatef(0, -0.05, 0.25);
glColor3f(1, 0, 0);
glutSolidCone(0.025, 0.25, 4, 4);

3. Keyboard Function

First define two global variable angle and zview. These will act the amount of motion or move we required when particular key is pressed. The angle will take care of movement of camera in right and left direction. For zoomin and zoomout- zview has been used. So define a keyboard function and used switch to define the input and take action accordingly. Here we will use the four navigation keys whose GLUT forms are as  - GLUT_KEY_LEFT, GLUT_KEY_RIGHT, GLUT_KEY_UP, and GLUT_KEY_DOWN. Below code explains all.

void processSpecialKeys(int key, int x, int y)
{
switch (key)
{
case GLUT_KEY_LEFT:
angle -= 0.5;
break;

case GLUT_KEY_RIGHT:
angle += 0.5;
break;

case GLUT_KEY_UP:
zView -= 0.5;
break;

case GLUT_KEY_DOWN:
zView += 0.5;
break;
}
}

3. Display Function

We have drawn all the things and put the action for camera movement. One thing we will do in display function is draw the x, y, z axis lines in red color. Now also call all the function which allow OpenGL to display objects on the screen that is drawsnow etc.


void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

gluLookAt(xView, yView, zView,
xView + lx, yView + ly, zView + lz,
0, 1, 0);
glRotatef(angle, 0, 1, 0);

glColor3f(1, 0, 0);
glLineWidth(3);
glBegin(GL_LINES);
glVertex3f(0, 0, 0);
glVertex3f(1.5, 0, 0);
glVertex3f(0, 0, 0);
glVertex3f(0, 3, 0);
glVertex3f(0, 0, 0);
glVertex3f(0, 0, 1.5);
glEnd();

glColor3f(0.5, 0.5, 0.5);
glBegin(GL_QUADS);
glVertex3f(-100, 0, -100);
glVertex3f(-100, 0, 100);
glVertex3f(100, 0, 100);
glVertex3f(100, 0, -100);
glEnd();

drawSnowMan();

glutSwapBuffers();

}

4. Main Function

Finally code the main function which is essential part of any OpenGL program. You can Download the whole source code from the link given.


Share your feedback and ideas in the comment box.

Sunday, June 11, 2017

3D Car Animation OpenGL Computer Graphics Program

We have came across so many Computer Graphics Program that draws Cars, including the racing games. In this post we are presenting 3D Car Animation, which is one the best OpenGL Car Program. This 3D OpenGL Program have so many advance features in it. You can see the below video demo that demonstrate the all features that included in this 3D Animated Program.


Features of the 3D Car Animation OpenGL Program

  1. Start Screen : As you execute the program, first thing come is the start screen where you will see the details of the project. The start screen have name of college and the name of projects. It also have the user interaction instructions about the use of mouse and keyboard functionality. There is option of going to main screen, by pressing 'space' key.
  2. Main Screen: After you get in to main screen from the start screen you will see the 3D Car drawn in blue color. If you press right mouse button you will get the menu options to select for particular functionality to execute. Details is mentioned in below user interaction section.
  3. Comments ; Most of the codes in this 3D OpenGL Program, is commented hence easy to understand the whole program.
3d car animation

User Interaction

The user interaction is one of the most important part of any program. This 3D OpenGL Program also have user interaction both using keyboard as well as mouse. Below is the description of the uses and functionality of keys and menus in this 3D OpenGL Progam.

3d opengl program on car


Mouse Interaction

Press right mouse button to get the mouse. Following is the menus-

Car model mode - This is default mode of car display which will display the only car.
Car driving mode - This will display the driving mode, which includes the long road and green filed.
Fog effect - This will apply the fog around the environment of the car.
Wheel effect - This is one of the finest effect, it will animate the car while it moved as it is moving in the car. 
Toggle light - This will apply the light effect on/off when selected.
Car colors - This menu have submenu which allow to select the color of car. The submenu have the following options - blue, red, green, black, yellow and grey.
Daymode - By default we have Daymode on, in this projects so while in Night mode you can select this to toggle to Daylight mode.
Night mode - This menu will let you switching to the Night mode, by showing darkness around.

Keyboard Interaction

Below is complete description against each key and what they do when pressed.

x- Rotate the car in 'x' direction
y- Rotate the car in 'y' direction
z- Rotate the car in 'z' direction
a- Increase the size of car in'x' direction
s- Increase the size of car in 'y' direction
q- Increase the size of car in 'z' direction
u- Camera top view
f- Camera side view
left arrrow key - Move car in forward direction
right arrow key-  Move car in backward direction
esc - Exit from the program
spacebar - Enter the main screen from start screen.

Source Code

You can download the source code from the google drive link. For report you can download it from the download or contact us to prepare for you.

Tuesday, May 30, 2017

Flag of South Africa

We have a great computer graphics OpenGL Projects on Flag Hoisting. Following that we have developed another graphics program based on Flag. The projects will draw the flag of South Africa.


Projects Description : 

This Computer Graphics projects as mentioned above draw Flag of South Africa. As you can see in the projects output image above, we have flag with flagpole. In this projects there is no user interaction as well as the project is static one. This projects only draw the flag and flagpole nothing else, there is no motion or animation in it.

A basic OpenGL program have included header files, global variable declaration, draw function, init function and main function. This program have only these basic functions, since it not required to have anything else.just draw the primitives to give a proper shape of flag. 

Draw Function

All objects in this project is included in draw function. As you can see the flag have three strips of different color. Also left part have triangular strips, along with a middle rectangular strip. There is also a long with small width rectangle for pole and last but not least the three rectangular flag base. All these strips are drawn with the help of polygon. We have use the glBegin(GL_POLYGON) and glBegin(GL_TRIANGLES) to draw the rectangular (polygon) and triangular objects respectively. 

One of the important thing and the main part is to understand the coordinate system. So, before draw have a sketch of the flag and point out the proper coordinate.  Unlike other complex projects, this projects is simple hence assign the proper coordinate is not a tough task.

glColor3f(1,0,0);
glBegin(GL_POLYGON);
glVertex2f(-15,30);
glVertex2f(-15,23.34);
glVertex2f(15,23.34);
glVertex2f(15,30);
glEnd();

The above mentioned is code snippet of this projects which draw the upper rectangular portion of flag. Similarly with proper coordinate, color section and use of glBegin(GL_POLYGON); (glBegin(GL_TRIANGLES); for triangular) the whole projects can be completed.

What Can be added to this projects

There are many things that can be added to it including the user interaction or waving of flag. many other idea we might find in our previous flag projects. As as creative students you may come up with new idea and implement to make this projects far better.

One of the good part of this projects is that it can be used as framework for drawing other flags.

Video Demo



Friday, May 19, 2017

A Movable Car

For those of you, who want to have a very simple projects here we came a new but simple project. A Movable Car, unlike our car racing projects this is very simple projects, which include  only just a car. So, you will able to learn also how to draw a car from this project. We have also added a simple user interaction which allow user to move the car in all four directions with navigation keys.


A movable Car is very simple OpenGL C program, in which as show in figure we display a Car, which can be move in up,down, left and right with corresponding arrow key. The Car is drawn in red color to match it with Red Ferrari, and there black shield and windows. 

This program in opengl c/c++ is good for beginners, who want to learn opengl from scratch as it has tons of comments for almost all the lines, which highlights the use of each of the function or callbacks used. The function that we have used to draw the car, itself have all the comments which show the parts which are drawing whether it's roof, windows, bumper or skirt. In the comment the left or right side is also mentioned, which let you understand if it is of left or right part.

We have used only keyboard interaction for the user to move the car in the direction they want. In this opengl c programm we have used the function key for the first time. In almost all the use of function key was nil, we have used it here. You might be thinking it to be hard, but it is as normal as we implement return key or esc key for any action. Below is glimpse of how we have used  the function key.

if(key == GLUT_KEY_F2 )
{
//logic goes here
}

if(key == GLUT_KEY_F1 )
{
//logic goes here

Now you all understand how to use the function key. For all special functions visit opengl.org glutSpecialFunc documents.

Keyboard Interaction of Program

Below is description of what action car will perform when user press the mentioned keys.

Up - Car move forward
Down  - Allow to reverse the car
Right - Move in right direction
Left -  Move toward left direction
F1 -  Car turns right backwards
F2 - Car turns left backwards

Future Scope

For those of you, who want to develop something new by taking some code snippet. This project is for you. Download the free source code and develop some unique program like car racing game, car parking game, car simulator etc.

Source code

You can have free access to the source code o A Movable car opengl c++ program. Kindly download it by visiting the Download link. Share your experience, and creativity with the code. 

Friday, April 28, 2017

Rain water harvesting cg projects

Nature has given alot  to mankind, but we have destroyed the balance. We need to save the nature by conserving the resources. Water is one of essential element in our life, hence we need to conserve it. One of the way to conserved Water is by saving rain Water. The process of saving rainwater is done though rainwater harvesting. Our cg project will demonstrate the rainwater harvesting.

What required in the project?

Since we are making rainwater harvesting, so we will draw house with proper implemented rainwater harvesting infrastructure.

What we will draw?
  1. House, with proper induct for saving rainwater.
  2. Pipes, to move water.
  3. Containers with charcoal.
  4. For chlorine bleaching, container with chlorine.
  5. Turbine
  6. Water reservoir or small water tank for storage. 



You might have seen flow of water or liquids in our nuclear power plant project, similarly in this cg project we will move.

Rain falls on house, with induct and pipe water fall to charcoal container and then to chlorine container and finally to turbine. Now purified water goes to water tank where it reserved for use.

The rainwater harvesting cg project is simple but one of the fine project that show our need of daily life.

Download the Source code

video demo will published soon. 

Monday, March 20, 2017

Trippy Animated Computer Graphics Projects

We have seen many animated opengl projects, today we are presenting another projects with animation. The name of the new project is - Trippy.

Trippy means hallucinatory effect or something resemble to hallucination.



The hallucination with different primitive objects like dots, lines and triangles are used. The effect was made more effective with proper use of color as well as texture. To make hallucinating more effective different objects like circle and teaport is also added in option. The number do matters, in hallucination the number have important role to play, hence the project have added the option to add as many as 50 primitive or objects in it.

Our Eye hallucinate with different factor effecting it, one of them is speed. This project also added the option to increase the speed as well as the shape of the primitives or objects that is getting hallucinated.

User Interaction

Right click to get the menu and submenu.

Texture mode :

                      smooth : Set smooth texture to the primitive or objects
                      Chunky :  add a bit of texture to the primitive or objects

Seed mode :
               
                       Primitive : Draw primitive objects like dot, lines and triangles
                        Circle :  Draw circle
                         TeaPort :  Draw Teaport
                        Text : Display the text "OpenGL"

Seed Size :  Tiny, Small, Medium, Large (the size of object or primitives)

Colours :

                   Slow : Display color in slow pattern
                   Medium :  Color hallucination with medium effect
                   Fast : Create the color fastly
                  Random : create random color

Primitive :
                  Dots : Create Dots
                  Lines : Create lines
                  Triangles : Generate Triangle

Number : Number of objects or primitive to drawn - 1, 2,3, 5, 10, 20, 30, 50

Size :  Draw the size as specified on selection - 1, 3, 5

AutoSpin  : Spin the screen

Reset :  Reset to the current object removing past drawn objects

Quit :  Exit from the program

Video Demo

Coming Soon!

Source Code 

You can Download the source code of the project - Trippy Animated Computer Graphics Projects from Google Drive.



Tuesday, February 21, 2017

Car Race OpenGL Program

There are many OpenGL Program in our blog. In this post we are going to discuss about the Car Race game in old style. It is similar to 2d car racing game but little simple.

Like in video game Car race game, we have seen the cars are shaped in rectangular shape. The black meter lined road is coded on which the cars raced. There are 6 lanes in the road on which racer have to move the care to avoid collision. 



Earlier in our many game programs we have much impressive menu or instruction for user. This opengl program also display the menu while game being played. You can see in the image above. The score is also written at the top.


HOW TO PLAY

In menu the basic instruction has been shown but many skipped due to low area to display text. All the other user interaction of this opengl program are mentioned below - 

Start and End
s  - start the game
q - quit the game and exist the program

Color change
Change the track and background color (when game end and show shown).
0 - to white
1 - to red
3 -  to blue

Game Play
2 - down or de-accelerate
4 - toward left
6 - toward right
8 - up or accelarate


Note : In this OpenGL program we have used the glutStrokeCharacter

NAME
       glutStrokeCharacter  -  renders  a  stroke character using OpenGL.

SYNTAX
       void glutStrokeCharacter(void *font, int character);

ARGUMENTS
       font      Stroke font to use.

       character Character to render (not confined to 8 bits).

DESCRIPTION
       Without using any display lists, glutStrokeCharacter  ren
       ders the character in the named stroke font. The available
       fonts are:

       GLUT_STROKE_ROMAN
               A proportionally spaced  Roman  Simplex  font  for
               ASCII  characters  32 through 127. The maximum top
               character in the font is 119.05 units; the  bottom
               descends 33.33 units.

       GLUT_STROKE_MONO_ROMAN
               A  mono-spaced  spaced  Roman  Simplex  font (same
               characters as GLUT_STROKE_ROMAN) for ASCII characte
               ters  32 through 127. The maximum top character in
               the font is  119.05  units;  the  bottom  descends
               33.33  units. Each character is 104.76 units wide.

       Rendering  a  nonexistent  character  has  no  effect.   A
       glTranslatef  is  used to translate the current model view
       matrix to advance the width of the character.

Friday, February 17, 2017

Flag Hoisting Graphics Programs in C/C++

There are many Graphics Program available for C/C++. In our website we have posted so many Graphics Programs in C/C++ which used the OpenGL graphics library. While there few program available for turbo C which used the graphics.h library, but they are outdated. The new time is to adopt opengl, one point to support this is that OpenGL is opensource. The API provided by CGI has so many that we can render to make some good game or other animated programs. You can became a game developer by mastering the graphics programs.Visit OpenGL.org for more. Don't forget to visit the forum.

This blog is dedicated to OpenGL programming and we are focusing on that only, but sometime off topics are good to have. Before getting stated with opengl, we aspect that you all have some knowledge of C/C++. All the programs posted here are written in C/C++ or otherwise mentioned.

Today we are going to see the Flag Hoisting Program in C/C++. This program is submitted by +Srikanth Kini.

Flag Hosting Graphics Programs in C C++


Aim of the Project : The projects objective to show graphically hoisting of a Flag.

Description of the Project : In this project we have 3 people, a flag pole and sun. All these objects are drawn using the basic primitive functions provided in OpenGL. At the beginning flag is down, which is hoisted by a person (first among the three) who walk toward the pole. There is little complication in here as the person don't seems to walk rather moving toward pole. Since this is 2D project it not look realistic.

The person approaches the flagpost and host the flag, which is shown with a good animation. Flag go up and waves out. This is unlike the previous waving flag graphics program in C/C++. There is "Vande Matrama" written in right side as  flag waves. The salutes can also made with animation, which look awesome.

User Interaction : This program has no much user interaction but few. In the beginning as program start there is no motion, so there is s/S key which initiate the  program animation. As s/S is pressed the person in front start moving to host the flag. To exit, just press esc key.

Video Demo



Future enhancements :
  • Convert the Whole Program into 3D version.
  • There are only three people there, more can be added with a proper stadium.
  •  Make the motion more realistic.
  • Flagpost and other can be improve with better quality of graphics design.
  • Sound can be added with National anthem getting sung as flag get hoisted.
  • Flowers should fall as flag get hosted.
To get the source code for this Graphics Programs contact us to our email - openglprojects@gmail.com. Put your comment and let us know your views.

Sunday, January 22, 2017

3D Bouncing Balls gl programming

GL Programming is programming with use of opengl graphics library. OpenGL API contains several functions, which helps rendering 2d/3d image as graphics on computer. It is designed to streamline the process of rendering the different objects on computer screen. One of the best part that OpenGL has over DirectX is that, OpenGL is hardware/OS independent.

Computer Graphics in few decades have grown from 8 bit simple games to large scale scientific research. Now we see in every aspect of life including images, videos, games, application etc there is intense use of graphics. OpenGL and other various graphics API evolves and make our life easier.
In this post we are going to create a 3D bouncing ball program in opengl using C/C++. You can also get this free computer science projects with source code download.

The GL Programming

GLU OpenGL Utility Library and GLUT - The OpenGL Utility Toolkit, have so many features which helps in gl programming. They are standard part of OpenGL implementation, helps in writing programs.

gl programming opengl and glut overview


With gl programming we can do many things including drawing a simple triangle to a large scale complex graphics game. OpenGL considers points, lines, polygons, images, and bitmaps to be primitives or basic elements. With the combination of these elements many complex figures can be obtain.

There are various aspects of GL Programming -
  • Include necessary headers files
  • The functions, methods or commands of opengl starts with gl e.g - glBegin, glEnd etc.
  • In gl programming window management is done via main function which all other related functions.
  • OpenGL do rendering, pipe lining, pixel operation, rasterization, texturing, fragmentation, animation, interactive operations etc.
  • OpenGL operates in different modes or states.
  • OpenGL works on buffers (memories) to display the objects

3D Bouncing Balls

In this post we are going to create a opengl program that will show 3D bouncing balls. Now in detail we are going to tell you what are our objective or aim for coding this gl program.

What we are developing?

First the floor is drawn which is a checkerboard, most likely similar to our opengl chess board program. Then we will draw three balls, of different colors. These balls will bounce up and down on the floor. To make the program or interesting, the user interaction has been added to it. With the help of four navigation key, the floor as well as ball, the whole system can be zoom in/out and can also be move around - simply say moves the camera in different directions - swinging the camera around.
Basically, we are creating an application which shows the balls bouncing on a floor. The animation which make application more interesting, with arrow keys move the camera.

PROJECT MODULES

Apart from the basic modules of a gl programming i.e header files, main function this application has basically in 5 modules. We have defined global array for Colors to be used for balls and floor.
// Colors
GLfloat WHITE[] = {1, 1, 1};
GLfloat RED[] = {1, 0, 0};
GLfloat GREEN[] = {0, 1, 0};
GLfloat MAGENTA[] = {1, 0, 1}
1. CAMERA CLASS - This class will define the methods (functions) that are to be used for movement of camera. The camera moves horizontally in a circle centered at the origin of radius 10. It moves vertically straight up and down.
Here some use of trigonometry comes as we apply the formula with sine and cosine functions from opengl. The variables are defined which will store the position of the camera, it's x-y-z positions. The swing or motion of camera done via the angle, which determine x,z position. Angle will help movement of camera in and around. While the value of y coordinate helps in moving camera up and down.
The functions prototype here will get the information and determine the position of x, y, z coordinate of camera. Also prototype will define animation, movement in four direction - up, down, left and right.

2. BALL CLASS - All the variable and prototype function declared for the balls. A ball has a radius, a color, and bounces up and down between a maximum height and the xz plane. Therefore the x and z coordinates of the balls are fixed. It uses a lame bouncing algorithm, simply moving up or down by a mere 0.05 units at each frame.

The prototype of function that will draw the ball will have following parameters - radius, color, x, y, z. Here x-y-z are coordinate positions. The ball is given a good shape with call of glutSolidSphere .

3. CHECKERBOARD CLASS - We all know a checkerboard is one with alternate square of two different color. This class will define methods and variable for checkerboard. The number of squares in the checker board is set via constructor. Each of the square in checkerboard is 1 x 1 unit. The one of it's corner is (0, 0) and the board stretches out along positive x and positive z directions. It rests on the xz plane.

We have used the concept of Display list in this class to draw the checkerboard. Other like giving the checkerboard lighting, material, ambient opengl function has been called.

4. DISPLAY - Though display is necessary for every application in gl programming, we had called it a separate module. Like all other gl programs, here we define to draw the objects on the screen.

Here we draws one frame, first the checkerboard and then the balls, from the current camera position.

5. USER INTERACTION - Without user interaction the program look dull, hence we have added user interaction to this program with special function (just named so).

The table below will show keys used for user interaction and their uses.

KEY USES
up Move camera up/zoom in
down Move camera down/zoom out
left Move camera left
right Move camera right

Keys as said above will moves the camera according to the key pressed. The glutPostRedisplay(); then ask to refresh the display.

FINAL THOUGHTS

In this 3d bouncing ball gl programming, a timer is also there which requests to draw the next frame. Also the size of the ball and colors are hard-coded which can be change with global array. Similarly size and color of checkerboard is hard-code which also can be changed via program.  We have used navigation key for user interaction, you may like to code any key as per your choice.

The following video will show demo or output of this gl programming. We also states some of the modification you can make in the program. 

Download the source code from Google Drive.

Sunday, January 15, 2017

OpenGL Moving Bézier curves Program in C/C++

In our many tutorial, we have explained about how to create various objects, diagrams, things in OpenGL.  In our earlier tutorial we have explained about how to draw Bézier curves in opengl C/C++ with source code. In this post we will use the same source code and bring motion to our Bézier curves. You will see OpenGL Moving Bézier curves Program in C/C++ explained in this post.

Before going to the tutorial we are going to see the output of our program. Below gif will demo the out put and show Moving Bézier curve.



A curve is collection of set of points which are not in a straight line. They exist in 2d as well as 3d space. Bézier curves are parametric curves which can be generate with some set of points called as control points. Bézier curves are of different degree - linear curves, quadratic curve, cubic curve and high order curve. Following image will show the mathematical representation of Bézier curves -



In our example we will use simple Bézier curves, and give motion to them using two control points.

First we define the global variables which we can use in more than one set of function or methods. We have four set of control points, one each at end of curve and two in the middle. Using the middle control points we will give the curve a movement to change their position in 2d plane.
int bzco[4][2]={{0,0},{99,201},{204,49},{320,300}},c[4],n=3;
You can experiments with the bzco and choose the specific points for motion.

Next is to draw bezier curve, for which we need to define the curve center points. Firs of all we will define a function that will compute the points of the curve. This functions is very important for drawing bezier curves in opengl.

void bezierCoefficients(int n,int *c)
{
	int k,i;
	for(k=0;k<=n;k++)
	{
		c[k]=1;
		for(i=n;i>=k+1;i--)
		c[k]*=i;
		for(i=n-k;i>=2;i--)
			c[k]/=i;

	}
}
In display function we will call the above function and use the GL_LINE_STRIP in loop to develop the curve. The array of x, y coefficients will help in containing value for control and end points. Size of points is also defined using the glPointSize and gluOrtho2D to certain x, y values which define the curve path. You can see code in source code download below.

We have finished drawing Bézier curve but this post is about Moving Bézier curves Program. Hence we need to define a function called motion(), which will give movement to the curve. Simple logic we use to determine the extent of movement is the x, y coefficient point of 2d plane. We will set the value to which curve can move and then came down from there. For this we will use the array which we have declared as global variable.
void motion(void)
{
	bzco[1][0]+=s1x;
	bzco[1][1]+=s1y;
	bzco[2][0]+=s2x;
	bzco[2][1]+=s2y;
if(bzco[1][0]<0 bzco="">320)
{
	s1x=-s1x;
}
if(bzco[1][1]<0 bzco="">300)
{
	s1y=-s1y;
}
if(bzco[2][0]<0 bzco="">320)
{
	s2x=-s2x;
}
if(bzco[2][1]<0 bzco="">300)
{
	s2y=-s2y;
}
glutPostRedisplay();
}
In the above code you can see that first we add the number(distance) to the array and then negate it. So, logic is to first add the value to coefficient to go up and bring them down. You can see we have chosen 300, 320 two different control points. You all can experiment with these points as well and see the the magic yourselves. The glutPostRedisplay(); repeat drawing of objects on screen with call back to main function, hence will repeat the same.

Download the source code of this program from the link given below.