Thursday, March 22, 2007

Monday, March 19, 2007

Chales,,,
forgot to give you all the code, well here is what I added to the robot proyect to draw the blasting hand:

void DrawPalm(float xPos,float yPos,float zPos)
{
glPushMatrix();
glColor3f(1.0f,0.0f,0.0f);
glTranslatef(xPos,yPos,zPos);
glScalef(4.0f, 4.0f, 1.0f);
DrawCube(0.0f, 0.0f, 0.0f);

glPopMatrix();

}
void DrawFinger(float xPos, float yPos,float zPos)
{
glPushMatrix();
glColor3f(1.0f,1.0f,1.0f);
glTranslatef(xPos,yPos,zPos);
glPushMatrix();

glScalef(0.5f, 2.0f, 1.0);
DrawCube(0.0f, 0.0f, 0.0f);

glPopMatrix();
glColor3f(0.0f,1.0f,1.0f);
glTranslatef(0.0,0.5,zPos);
glPushMatrix();
glScalef(0.5f, 0.5f, 1.0f);
DrawCube(0.0f,0.0f,0.0f);
glPopMatrix();
glColor3f(1.0,0.0,1.0);
glTranslatef(0.0,0.5,zPos);
glPushMatrix();
glScalef(0.5f, 0.5f, 1.0f);
DrawCube(0.0f,0.0f,0.0f);


glPopMatrix();
glPopMatrix();

}
void DrawThumb(float xPos,float yPos,float zPos)
{
glPushMatrix();
glColor3f(1.0f,1.0f,1.0f);
glTranslatef(xPos,yPos,zPos);
glPushMatrix();
glScalef(2.0f, 1.0f, 1.0f);
DrawCube(0.0f, 0.0f, 0.0f);

glPopMatrix();
glColor3f(0.0f,1.0f,1.0f);
glTranslatef(1.0,0,zPos);
glPushMatrix();
glScalef(1.0f,1.0f,1.0f);
DrawCube(0.0f,0.0f,0.0f);
glPopMatrix();
glColor3f(1.0,0.0,1.0);
glTranslatef(0.5,0,zPos);
glPushMatrix();
glScalef(0.5f,1.0f,1.0f);
DrawCube(0.0f,0.0f,0.0f);


glPopMatrix();
glPopMatrix();
}
void DrawHand(float xPos,float yPos,float zPos)
{
//DrawHand();

DrawPalm(10.0f,2.0f,0.0f);
DrawFinger(10.0f,4.0f,-1.0f);
DrawFinger(9.0f,4.0f,-0.5f);
DrawFinger(8.0f,4.0f,-0.5f);
DrawFinger(7.0f,4.0f,-0.5f);
DrawThumb(12.0f,-1.0f,-2.0);
}

With that done, perhaps we need to give the robots little hands, so they can trwirl their partners around, or give high fives to cool dancing couples...
yeah, they need hands:
Here is a little hand I made for all theseive objectives----------------------------------->

In this picture, the hand is flexed a little as to give an image that it is holding something, or maybe scatching a fat belly. We can articulate the fingers as to make the hand hold or not something. We can also make the hand wave.

ich esse, was ich mag, und leide, was ich muss...
ich esse, was ich mag, und leide,was ich muss....










And as usual, here is the code,


Magic Dancing Robot, do your thing!

....................................
Now we´re going to check out a nice ball dance between my dear robot friends I have been building.








Here´s the code:
* i just added more robots to the scene that´s all:


#pragma comment(linker, "/subsystem:windows")

#include

#include

#include

#include

/* . These variables will control angles,

fullscreen, and the global device context.

*/

HDC g_HDC;

float
angle = 0.0f;

float
legAngle[2] = {0.0f, 0.0f};

float
armAngle[2] = {0.0f, 0.0f};

bool
fullScreen = false;

/* Function: DrawSquare

Purpose: As the name would suggest, this is

the function for drawing the cubes.

*/

void
DrawSquare(float xPos, float yPos, float zPos)

{

glPushMatrix();

glBegin(GL_POLYGON);

/* This is the front face*/

glVertex3f(0.0f, 0.0f, 0.0f);

glVertex3f(-1.0f, 0.0f, 0.0f);

glVertex3f(-1.0f, -1.0f, 0.0f);

glVertex3f(0.0f, -1.0f, 0.0f);

glEnd();

glPopMatrix();

}

/* Function: DrawArm

Purpose: This function draws the arm

for the robot.

*/

void
DrawArm(float xPos, float yPos, float zPos)

{

glPushMatrix();

/* Sets color to red*/

glColor3f(1.0f, 0.0f, 0.0f);

glTranslatef(xPos, yPos, zPos);

/* Creates 1 x 4 x 1 cube*/

glScalef(1.0f, 4.0f, 1.0f);

DrawSquare(0.0f, 0.0f, 0.0f);

glPopMatrix();
/* This will draw the gross part of the arm.*/

glPushMatrix();

/* Sets color to red*/

glColor3f(0.0f, 1.0f, 0.0f);

glTranslatef(xPos+1, yPos-4.0f, zPos);

/* Creates 1 x 4 x 1 cube*/

glScalef(2.0f, 2.0f, 1.0f);

DrawSquare(0.0f, 0.0f, 0.0f);

glPopMatrix();
/* This will draw the robot´s hand*/
glPushMatrix();

/* Sets color to red*/

glColor3f(1.0f, 1.0f, 1.0f);

glTranslatef(xPos+1, yPos-6.0f, zPos);

/* Creates 1 x 4 x 1 cube*/

glScalef(1.0f, 1.0f, 1.0f);

DrawSquare(0.0f, 0.0f, 0.0f);

glPopMatrix();

}

/* Function: DrawHead

Purpose: This function will create the

head for the robot.

*/

void
DrawHead(float xPos, float yPos, float zPos)

{

glPushMatrix();

/* Sets color to white*/

glColor3f(1.0f, 1.0f, 1.0f);

glTranslatef(xPos, yPos, zPos);

/* Creates 2 x 2 x 2 cube*/

glScalef(2.0f, 2.0f, 2.0f);

DrawSquare(0.0f, 0.0f, 0.0f);

glPopMatrix();

}

/* Function: DrawTorso

Purpose: Function will do as suggested

and draw a torso for our robot.

*/

void
DrawTorso(float xPos, float yPos, float zPos)

{

glPushMatrix();

/* Sets color to blue*/

glColor3f(0.0f, 0.0f, 1.0f);

glTranslatef(xPos, yPos, zPos);

/* Creates 3 x 5 x 1 cube*/

glScalef(3.0f, 5.0f, 1.0f);

DrawSquare(0.0f, 0.0f, 0.0f);

glPopMatrix();

}

/* Function: DrawLeg

Purpose: Not to sound repetitve, but as suggested

this function will draw our robots legs.

*/

void
DrawLeg(float xPos, float yPos, float zPos)

{

glPushMatrix();

/* Sets color to yellow*/

glColor3f(0.0f, 0.0f, 1.0f);

glTranslatef(xPos, yPos, zPos);

/* Creates 1 x 5 x 1 cube*/

glScalef(1.0f, 5.0f, 1.0f);

DrawSquare(1.0f, 0.0f, 0.0f);

glPopMatrix();
/*This will draw the gross part of the leg for the robot.*/

glPushMatrix();

glColor3f(1.0f,1.0f,1.0f);

glTranslatef(xPos,yPos-5,zPos);

glScalef(2.0f,5.0f,1.0f);

DrawSquare(0.0f, 0.0f, 0.0f);

glPopMatrix();
/*This will draw the robot´s foot*/
glPushMatrix();

glColor3f(0.0f,1.0f,0.0f);

glTranslatef(xPos,yPos-10,zPos);

glScalef(3.0f,2.0f,1.0f);

DrawSquare(0.0f, 0.0f, 0.0f);

glPopMatrix();



}

/* Function: DrawRobot

Purpose: Function to draw our entire robot

*/

void
DrawRobot(float xPos, float yPos, float zPos)

{

/* Variables for state of robots legs. True

means the leg is forward, and False means

the leg is back. The same applies to the

robots arm states.

*/

static bool leg1 = true;

static bool leg2 = false;

static bool arm1 = true;

static bool arm2 = false;

glPushMatrix();

/* This will draw our robot at the

desired coordinates.

*/

glTranslatef(xPos, yPos, zPos);

/* These three lines will draw the

various components of our robot.

*/

DrawHead(1.0f, 2.0f, 0.0f);

DrawTorso(1.5f, 0.0f, 0.0f);

glPushMatrix();



/* If the arm is moving forward we will increase

the angle; otherwise, we will decrease the

angle.

*/

if (arm1)

{

armAngle[0] = armAngle[0] + 1.0f;

}

else

{

armAngle[0] = armAngle[0] - 1.0f;

}

/* Once the arm has reached its max angle

in one direction, we want it to reverse

and change direction.

*/

if (armAngle[0] >= 15.0f)

{

arm1 =
false;

}

if (armAngle[0] <= 15.0f) { arm1 = true; } /* Here we are going to move the arm away from the torso and rotate. This will create a walking effect. */ glTranslatef(0.0f, -0.5f, 0.0f); glRotatef(armAngle[0], 1.0f, 0.0f, 0.0f); DrawArm(2.5f, 0.0f, -0.5f); glPopMatrix(); glPushMatrix(); /* If the arm is moving forward we will increase the angle, otherwise we will decrease the angle */ if (arm2) { armAngle[1] = armAngle[1] + 1.0f; } else { armAngle[1] = armAngle[1] - 1.0f; } /* Here we are going to move the arm away from the torso and rotate. This will create a walking effect. */ glTranslatef(0.0f, -0.5f, 0.0f); glRotatef(armAngle[1], 1.0f, 0.0f, 0.0f); DrawArm(-1.5f, 0.0f, -0.5f); glPopMatrix(); /* Now its time to rotate the legs relative to the robots position in the world, this is the first leg, ie the right one. */ glPushMatrix(); /* If the leg is moving forward we will increase the angle; otherwise, we will decrease the angle. */ if (leg1) { legAngle[0] = legAngle[0] + 1.0f; } else { legAngle[0] = legAngle[0] - 1.0f; } /* Once the leg has reached its max angle in one direction, we want it to reverse and change direction. */ if (legAngle[0] >= 15.0f)

{

leg1 =
false;

}

if (legAngle[0] <= -15.0f) { leg1 = true; } /* Here we are going to move the leg away from the torso and rotate. This will create a walking effect. */ glTranslatef(0.0f, -0.5f, 0.0f); glRotatef(legAngle[0], 1.0f, 0.0f, 0.0f); /* Time to draw the leg. */ DrawLeg(-0.5f, -5.0f, -0.5f); glPopMatrix(); /* Same as above, for the left leg. */ glPushMatrix(); /* If the leg is moving forward we will increase the angle, otherwise we will decrease the angle */ if (leg2) { legAngle[1] = legAngle[1] + 1.0f; } else { legAngle[1] = legAngle[1] - 1.0f; } /* Once the leg has reached its max angle in one direction, we want it to reverse and change direction. */ if (legAngle[1] >= 15.0f)

{

leg2 =
false;

}

if (legAngle[1] <= -15.0f) { leg2 = true; } /* Here we are going to move the leg away from the torso and rotate. This will create a walking effect. */ glTranslatef(0.0f, -0.5f, 0.0f); glRotatef(legAngle[1], 1.0f, 0.0f, 0.0f); DrawLeg(1.5f, -5.0f, -0.5f); glPopMatrix(); glPopMatrix(); } /* Function: Render Purpose: This function will be responsible for the rendering, got to love my descriptive function names : ) */ void Render() { /* Enable depth testing */ glEnable(GL_DEPTH_TEST); /* Heres our rendering. Clears the screen to black, clear the color and depth buffers, and reset our modelview matrix. */ glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); /* Increase rotation angle counter */ angle = angle + 1.0f; /* Reset after we have completed a circle */ if (angle >= 360.0f)

{

angle = 0.0f;

}

glPushMatrix();

glLoadIdentity();

/* Move to 0,0,-30 , rotate the robot on

its y axis, draw the robot, and dispose

of the current matrix.

*/

glTranslatef(0.0f, 0.0f, -30.0f);

glRotatef(angle, 0.0f, 1.0f, 0.0f);

DrawRobot(0.0f, 0.0f, 0.0f);

glPopMatrix();

glFlush();


glPushMatrix();

glLoadIdentity();

/* Move to 0,0,-30 , rotate the robot on

its y axis, draw the robot, and dispose

of the current matrix.

*/
glScalef(2,.5,1);
glRotatef(angle, 0.0f, 0.0f, 1.0f);
glTranslatef(-3.0f, 1.0f, 2.0f);



DrawRobot(0.0f, 0.0f, 0.0f);

glPopMatrix();
glFlush();

glPushMatrix();

glLoadIdentity();

/* Move to 0,0,-30 , rotate the robot on

its y axis, draw the robot, and dispose

of the current matrix.

*/
glScalef(.5,.5,.5);
glRotatef(angle, 0.0f, 1.0f, 0.0f);
glTranslatef(5.0f, 0.0f, 2.0f);



DrawRobot(0.0f, 0.0f, 0.0f);

glPopMatrix();
glFlush();



glPushMatrix();

glLoadIdentity();

/* Move to 0,0,-30 , rotate the robot on

its y axis, draw the robot, and dispose

of the current matrix.

*/

glTranslatef(1.0f, 1.0f, 1.0f);
glRotatef(angle, 1.0f, 0.0f, 0.0f);
glScalef(.5,-1.5,.5);




DrawRobot(0.0f, 0.0f, 0.0f);

glPopMatrix();
glFlush();



glPushMatrix();

glLoadIdentity();

/* Move to 0,0,-30 , rotate the robot on

its y axis, draw the robot, and dispose

of the current matrix.

*/

glRotatef(angle, 0.0f, 1.0f, 0.0f);
glTranslatef(-2.0f, -1.0f, 3.0f);



DrawRobot(0.0f, 0.0f, 0.0f);

glPopMatrix();

/* Bring back buffer to foreground

*/

SwapBuffers(g_HDC);

}

//function to set the pixel format for the device context

/* Function: SetupPixelFormat

Purpose: This function will be responsible

for setting the pixel format for the

device context.

*/

void
SetupPixelFormat(HDC hDC)

{

/* Pixel format index

*/

int nPixelFormat;

static PIXELFORMATDESCRIPTOR pfd = {

sizeof(PIXELFORMATDESCRIPTOR), //size of structure

1,
//default version

PFD_DRAW_TO_WINDOW |
//window drawing support

PFD_SUPPORT_OPENGL |
//opengl support

PFD_DOUBLEBUFFER,
//double buffering support

PFD_TYPE_RGBA,
//RGBA color mode

32,
//32 bit color mode

0, 0, 0, 0, 0, 0,
//ignore color bits

0,
//no alpha buffer

0,
//ignore shift bit

0,
//no accumulation buffer

0, 0, 0, 0,
//ignore accumulation bits

16,
//16 bit z-buffer size

0,
//no stencil buffer

0,
//no aux buffer

PFD_MAIN_PLANE,
//main drawing plane

0,
//reserved

0, 0, 0 };
//layer masks ignored

/* Choose best matching format*/

nPixelFormat = ChoosePixelFormat(hDC, &pfd);

/* Set the pixel format to the device context*/

SetPixelFormat(hDC, nPixelFormat, &pfd);

}

/* Windows Event Procedure Handler

*/

LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)

{

/* Rendering and Device Context

variables are declared here.

*/

static HGLRC hRC;

static HDC hDC;

/* Width and Height for the

window our robot is to be

displayed in.

*/

int width, height;

switch(message)

{

case WM_CREATE: //window being created

hDC = GetDC(hwnd);
//get current windows device context

g_HDC = hDC;

SetupPixelFormat(hDC);
//call our pixel format setup function

/* Create rendering context and make it current

*/

hRC = wglCreateContext(hDC);

wglMakeCurrent(hDC, hRC);

return 0;

break;

case WM_CLOSE: //window is closing

/* Deselect rendering context and delete it*/

wglMakeCurrent(hDC, NULL);

wglDeleteContext(hRC);

/* Send quit message to queue*/

PostQuitMessage(0);

return 0;

break;

case WM_SIZE:

/* Retrieve width and height*/

height = HIWORD(lParam);

width = LOWORD(lParam);

/* Don't want a divide by 0*/

if (height == 0)

{

height = 1;

}

/* Reset the viewport to new dimensions*/

glViewport(0, 0, width, height);

/* Set current Matrix to projection*/

glMatrixMode(GL_PROJECTION);

glLoadIdentity();
//reset projection matrix

/* Time to calculate aspect ratio of

our window.

*/

gluPerspective(54.0f, (GLfloat)width/(GLfloat)height, 1.0f, 1000.0f);

glMatrixMode(GL_MODELVIEW);
//set modelview matrix

glLoadIdentity();
//reset modelview matrix

return 0;

break;

default:

break;

}

return (DefWindowProc(hwnd, message, wParam, lParam));

}

int
APIENTRY WinMain(HINSTANCE hInstance,

HINSTANCE hPrevInstance,

LPSTR lpCmdLine,

int nCmdShow)

{

WNDCLASSEX windowClass;
//window class

HWND hwnd;
//window handle

MSG msg;
//message

bool done; //flag for completion of app

DWORD dwExStyle;
//window extended style

DWORD dwStyle;
//window style

RECT windowRect;

/* Screen/display attributes*/

int width = 800;

int height = 600;

int bits = 32;

windowRect.left =(
long)0; //set left value to 0

windowRect.right =(
long)width; //set right value to requested width

windowRect.top =(
long)0; //set top value to 0

windowRect.bottom =(
long)height;//set bottom value to requested height

/* Fill out the window class structure*/

windowClass.cbSize =
sizeof(WNDCLASSEX);

windowClass.style = CS_HREDRAW | CS_VREDRAW;

windowClass.lpfnWndProc = WndProc;

windowClass.cbClsExtra = 0;

windowClass.cbWndExtra = 0;

windowClass.hInstance = hInstance;

windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);

windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);

windowClass.hbrBackground = NULL;

windowClass.lpszMenuName = NULL;

windowClass.lpszClassName =
"MyClass";

windowClass.hIconSm = LoadIcon(NULL, IDI_WINLOGO);

/* Register window class*/

if (!RegisterClassEx(&windowClass))

{

return 0;

}

/* Check if fullscreen is on*/

if (fullScreen)

{

DEVMODE dmScreenSettings;

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

dmScreenSettings.dmSize =
sizeof(dmScreenSettings);

dmScreenSettings.dmPelsWidth = width;
//screen width

dmScreenSettings.dmPelsHeight = height;
//screen height

dmScreenSettings.dmBitsPerPel = bits;
//bits per pixel

dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;

if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN !=

DISP_CHANGE_SUCCESSFUL))

{

/* Setting display mode failed, switch to windowed*/

MessageBox(NULL,
"Display mode failed", NULL, MB_OK);

fullScreen =
false;

}

}

/* Check if fullscreen is still on*/

if (fullScreen)

{

dwExStyle = WS_EX_APPWINDOW;
//window extended style

dwStyle = WS_POPUP;
//windows style

ShowCursor(FALSE);
//hide mouse pointer

}

else

{

dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
//window extended style

dwStyle = WS_OVERLAPPEDWINDOW;
//windows style

}

AdjustWindowRectEx(&windowRect, dwStyle, FALSE, dwExStyle);

/* Class registerd, so now create our window*/

hwnd = CreateWindowEx(NULL,
"MyClass", //class name

"OpenGL Robot", //app name

dwStyle |

WS_CLIPCHILDREN |

WS_CLIPSIBLINGS,

0, 0,
//x and y coords

windowRect.right - windowRect.left,

windowRect.bottom - windowRect.top,
//width, height

NULL,
//handle to parent

NULL,
//handle to menu

hInstance,
//application instance

NULL);
//no xtra params

/* Check if window creation failed (hwnd = null ?)*/

if (!hwnd)

{

return 0;

}

ShowWindow(hwnd, SW_SHOW);
//display window

UpdateWindow(hwnd);
//update window

done =
false; //initialize loop condition variable

/* Main message loop*/

while (!done)

{

PeekMessage(&msg, hwnd, NULL, NULL, PM_REMOVE);

if (msg.message == WM_QUIT) //did we revieve a quit message?

{

done =
true;

}

else

{

Render();

TranslateMessage(&msg);

DispatchMessage(&msg);

}

}

if (fullScreen)

{

ChangeDisplaySettings(NULL, 0);

ShowCursor(TRUE);

}

return msg.wParam;

}

Tuesday, March 13, 2007



Another nice morning to just get up and write...

As I promised last week, I did some reading on Open Gl, and I made a new program which displays now a dancing robot on the screen. This program was actually much more easier to do than the last one I showed here, since I finally understood how to use the functions glPushMatrix and glPopMatrix. Why are these two functions important ?

If you decide not to implement them, and just end up using glTranslatef(xPos,yPos-10,zPos) or glScale etc, what´s going to be happening is that you`re going to be moving your whole scene or scaling your whole scene, so you will loose power in saying what it is you want to move or scale. Let´s say you already drew correctly the robot´s head and torso, and you just wanted to add the robot´s right arm, you wnat the piece of code you already drew to stay put, you don´t need it to be moving around, you woulkd just have to move the new arm figure to upper shoulder. To acomplish this, you use Pop and Push. You are actually drawing once again the robot, but the stack is keeping the order in which the robot to be drawn, and it just moves what you ask it to, what you push into or pop out of the stack.

Anyway, perhaps it will be a lot more clearer with a piece of code:

.....................................................................................................................................................................

#pragma comment(linker, "/subsystem:windows")

#include

#include

#include

#include

/* . These variables will control angles,

fullscreen, and the global device context.

*/

HDC g_HDC;

float
angle = 0.0f;

float
legAngle[2] = {0.0f, 0.0f};

float
armAngle[2] = {0.0f, 0.0f};

bool
fullScreen = false;

/* Function: DrawSquare

Purpose: As the name would suggest, this is

the function for drawing the cubes.

*/

void
DrawSquare(float xPos, float yPos, float zPos)

{

glPushMatrix();

glBegin(GL_POLYGON);

/* This is the front face*/

glVertex3f(0.0f, 0.0f, 0.0f);

glVertex3f(-1.0f, 0.0f, 0.0f);

glVertex3f(-1.0f, -1.0f, 0.0f);

glVertex3f(0.0f, -1.0f, 0.0f);

glEnd();

glPopMatrix();

}

/* Function: DrawArm

Purpose: This function draws the arm

for the robot.

*/

void
DrawArm(float xPos, float yPos, float zPos)

{

glPushMatrix();

/* Sets color to red*/

glColor3f(1.0f, 0.0f, 0.0f);

glTranslatef(xPos, yPos, zPos);

/* Creates 1 x 4 x 1 cube*/

glScalef(1.0f, 4.0f, 1.0f);

DrawSquare(0.0f, 0.0f, 0.0f);

glPopMatrix();
/* This will draw the gross part of the arm.*/

glPushMatrix();

/* Sets color to red*/

glColor3f(0.0f, 1.0f, 0.0f);

glTranslatef(xPos+1, yPos-4.0f, zPos);

/* Creates 1 x 4 x 1 cube*/

glScalef(2.0f, 2.0f, 1.0f);

DrawSquare(0.0f, 0.0f, 0.0f);

glPopMatrix();
/* This will draw the robot´s hand*/
glPushMatrix();

/* Sets color to red*/

glColor3f(1.0f, 1.0f, 1.0f);

glTranslatef(xPos+1, yPos-6.0f, zPos);

/* Creates 1 x 4 x 1 cube*/

glScalef(1.0f, 1.0f, 1.0f);

DrawSquare(0.0f, 0.0f, 0.0f);

glPopMatrix();

}

/* Function: DrawHead

Purpose: This function will create the

head for the robot.

*/

void
DrawHead(float xPos, float yPos, float zPos)

{

glPushMatrix();

/* Sets color to white*/

glColor3f(1.0f, 1.0f, 1.0f);

glTranslatef(xPos, yPos, zPos);

/* Creates 2 x 2 x 2 cube*/

glScalef(2.0f, 2.0f, 2.0f);

DrawSquare(0.0f, 0.0f, 0.0f);

glPopMatrix();

}

/* Function: DrawTorso

Purpose: Function will do as suggested

and draw a torso for our robot.

*/

void
DrawTorso(float xPos, float yPos, float zPos)

{

glPushMatrix();

/* Sets color to blue*/

glColor3f(0.0f, 0.0f, 1.0f);

glTranslatef(xPos, yPos, zPos);

/* Creates 3 x 5 x 1 cube*/

glScalef(3.0f, 5.0f, 1.0f);

DrawSquare(0.0f, 0.0f, 0.0f);

glPopMatrix();

}

/* Function: DrawLeg

Purpose: Not to sound repetitve, but as suggested

this function will draw our robots legs.

*/

void
DrawLeg(float xPos, float yPos, float zPos)

{

glPushMatrix();

/* Sets color to yellow*/

glColor3f(0.0f, 0.0f, 1.0f);

glTranslatef(xPos, yPos, zPos);

/* Creates 1 x 5 x 1 cube*/

glScalef(1.0f, 5.0f, 1.0f);

DrawSquare(1.0f, 0.0f, 0.0f);

glPopMatrix();
/*This will draw the gross part of the leg for the robot.*/

glPushMatrix();

glColor3f(1.0f,1.0f,1.0f);

glTranslatef(xPos,yPos-5,zPos);

glScalef(2.0f,5.0f,1.0f);

DrawSquare(0.0f, 0.0f, 0.0f);

glPopMatrix();
/*This will draw the robot´s foot*/
glPushMatrix();

glColor3f(0.0f,1.0f,0.0f);

glTranslatef(xPos,yPos-10,zPos);

glScalef(3.0f,2.0f,1.0f);

DrawSquare(0.0f, 0.0f, 0.0f);

glPopMatrix();



}

/* Function: DrawRobot

Purpose: Function to draw our entire robot

*/

void
DrawRobot(float xPos, float yPos, float zPos)

{

/* Variables for state of robots legs. True

means the leg is forward, and False means

the leg is back. The same applies to the

robots arm states.

*/

static bool leg1 = true;

static bool leg2 = false;

static bool arm1 = true;

static bool arm2 = false;

glPushMatrix();

/* This will draw our robot at the

desired coordinates.

*/

glTranslatef(xPos, yPos, zPos);

/* These three lines will draw the

various components of our robot.

*/

DrawHead(1.0f, 2.0f, 0.0f);

DrawTorso(1.5f, 0.0f, 0.0f);

glPushMatrix();



/* If the arm is moving forward we will increase

the angle; otherwise, we will decrease the

angle.

*/

if (arm1)

{

armAngle[0] = armAngle[0] + 1.0f;

}

else

{

armAngle[0] = armAngle[0] - 1.0f;

}

/* Once the arm has reached its max angle

in one direction, we want it to reverse

and change direction.

*/

if (armAngle[0] >= 15.0f)

{

arm1 =
false;

}

if (armAngle[0] <= 15.0f) { arm1 = true; } /* Here we are going to move the arm away from the torso and rotate. This will create a walking effect. */ glTranslatef(0.0f, -0.5f, 0.0f); glRotatef(armAngle[0], 1.0f, 0.0f, 0.0f); DrawArm(2.5f, 0.0f, -0.5f); glPopMatrix(); glPushMatrix(); /* If the arm is moving forward we will increase the angle, otherwise we will decrease the angle */ if (arm2) { armAngle[1] = armAngle[1] + 1.0f; } else { armAngle[1] = armAngle[1] - 1.0f; } /* Here we are going to move the arm away from the torso and rotate. This will create a walking effect. */ glTranslatef(0.0f, -0.5f, 0.0f); glRotatef(armAngle[1], 1.0f, 0.0f, 0.0f); DrawArm(-1.5f, 0.0f, -0.5f); glPopMatrix(); /* Now its time to rotate the legs relative to the robots position in the world, this is the first leg, ie the right one. */ glPushMatrix(); /* If the leg is moving forward we will increase the angle; otherwise, we will decrease the angle. */ if (leg1) { legAngle[0] = legAngle[0] + 1.0f; } else { legAngle[0] = legAngle[0] - 1.0f; } /* Once the leg has reached its max angle in one direction, we want it to reverse and change direction. */ if (legAngle[0] >= 15.0f)

{

leg1 =
false;

}

if (legAngle[0] <= -15.0f) { leg1 = true; } /* Here we are going to move the leg away from the torso and rotate. This will create a walking effect. */ glTranslatef(0.0f, -0.5f, 0.0f); glRotatef(legAngle[0], 1.0f, 0.0f, 0.0f); /* Time to draw the leg. */ DrawLeg(-0.5f, -5.0f, -0.5f); glPopMatrix(); /* Same as above, for the left leg. */ glPushMatrix(); /* If the leg is moving forward we will increase the angle, otherwise we will decrease the angle */ if (leg2) { legAngle[1] = legAngle[1] + 1.0f; } else { legAngle[1] = legAngle[1] - 1.0f; } /* Once the leg has reached its max angle in one direction, we want it to reverse and change direction. */ if (legAngle[1] >= 15.0f)

{

leg2 =
false;

}

if (legAngle[1] <= -15.0f) { leg2 = true; } /* Here we are going to move the leg away from the torso and rotate. This will create a walking effect. */ glTranslatef(0.0f, -0.5f, 0.0f); glRotatef(legAngle[1], 1.0f, 0.0f, 0.0f); DrawLeg(1.5f, -5.0f, -0.5f); glPopMatrix(); glPopMatrix(); } /* Function: Render Purpose: This function will be responsible for the rendering, got to love my descriptive function names : ) */ void Render() { /* Enable depth testing */ glEnable(GL_DEPTH_TEST); /* Heres our rendering. Clears the screen to black, clear the color and depth buffers, and reset our modelview matrix. */ glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); /* Increase rotation angle counter */ angle = angle + 1.0f; /* Reset after we have completed a circle */ if (angle >= 360.0f)

{

angle = 0.0f;

}

glPushMatrix();

glLoadIdentity();

/* Move to 0,0,-30 , rotate the robot on

its y axis, draw the robot, and dispose

of the current matrix.

*/

glTranslatef(0.0f, 0.0f, -30.0f);

glRotatef(angle, 0.0f, 1.0f, 0.0f);

DrawRobot(0.0f, 0.0f, 0.0f);

glPopMatrix();

glFlush();

/* Bring back buffer to foreground

*/

SwapBuffers(g_HDC);

}

//function to set the pixel format for the device context

/* Function: SetupPixelFormat

Purpose: This function will be responsible

for setting the pixel format for the

device context.

*/

void
SetupPixelFormat(HDC hDC)

{

/* Pixel format index

*/

int nPixelFormat;

static PIXELFORMATDESCRIPTOR pfd = {

sizeof(PIXELFORMATDESCRIPTOR), //size of structure

1,
//default version

PFD_DRAW_TO_WINDOW |
//window drawing support

PFD_SUPPORT_OPENGL |
//opengl support

PFD_DOUBLEBUFFER,
//double buffering support

PFD_TYPE_RGBA,
//RGBA color mode

32,
//32 bit color mode

0, 0, 0, 0, 0, 0,
//ignore color bits

0,
//no alpha buffer

0,
//ignore shift bit

0,
//no accumulation buffer

0, 0, 0, 0,
//ignore accumulation bits

16,
//16 bit z-buffer size

0,
//no stencil buffer

0,
//no aux buffer

PFD_MAIN_PLANE,
//main drawing plane

0,
//reserved

0, 0, 0 };
//layer masks ignored

/* Choose best matching format*/

nPixelFormat = ChoosePixelFormat(hDC, &pfd);

/* Set the pixel format to the device context*/

SetPixelFormat(hDC, nPixelFormat, &pfd);

}

/* Windows Event Procedure Handler

*/

LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)

{

/* Rendering and Device Context

variables are declared here.

*/

static HGLRC hRC;

static HDC hDC;

/* Width and Height for the

window our robot is to be

displayed in.

*/

int width, height;

switch(message)

{

case WM_CREATE: //window being created

hDC = GetDC(hwnd);
//get current windows device context

g_HDC = hDC;

SetupPixelFormat(hDC);
//call our pixel format setup function

/* Create rendering context and make it current

*/

hRC = wglCreateContext(hDC);

wglMakeCurrent(hDC, hRC);

return 0;

break;

case WM_CLOSE: //window is closing

/* Deselect rendering context and delete it*/

wglMakeCurrent(hDC, NULL);

wglDeleteContext(hRC);

/* Send quit message to queue*/

PostQuitMessage(0);

return 0;

break;

case WM_SIZE:

/* Retrieve width and height*/

height = HIWORD(lParam);

width = LOWORD(lParam);

/* Don't want a divide by 0*/

if (height == 0)

{

height = 1;

}

/* Reset the viewport to new dimensions*/

glViewport(0, 0, width, height);

/* Set current Matrix to projection*/

glMatrixMode(GL_PROJECTION);

glLoadIdentity();
//reset projection matrix

/* Time to calculate aspect ratio of

our window.

*/

gluPerspective(54.0f, (GLfloat)width/(GLfloat)height, 1.0f, 1000.0f);

glMatrixMode(GL_MODELVIEW);
//set modelview matrix

glLoadIdentity();
//reset modelview matrix

return 0;

break;

default:

break;

}

return (DefWindowProc(hwnd, message, wParam, lParam));

}

int
APIENTRY WinMain(HINSTANCE hInstance,

HINSTANCE hPrevInstance,

LPSTR lpCmdLine,

int nCmdShow)

{

WNDCLASSEX windowClass;
//window class

HWND hwnd;
//window handle

MSG msg;
//message

bool done; //flag for completion of app

DWORD dwExStyle;
//window extended style

DWORD dwStyle;
//window style

RECT windowRect;

/* Screen/display attributes*/

int width = 800;

int height = 600;

int bits = 32;

windowRect.left =(
long)0; //set left value to 0

windowRect.right =(
long)width; //set right value to requested width

windowRect.top =(
long)0; //set top value to 0

windowRect.bottom =(
long)height;//set bottom value to requested height

/* Fill out the window class structure*/

windowClass.cbSize =
sizeof(WNDCLASSEX);

windowClass.style = CS_HREDRAW | CS_VREDRAW;

windowClass.lpfnWndProc = WndProc;

windowClass.cbClsExtra = 0;

windowClass.cbWndExtra = 0;

windowClass.hInstance = hInstance;

windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);

windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);

windowClass.hbrBackground = NULL;

windowClass.lpszMenuName = NULL;

windowClass.lpszClassName =
"MyClass";

windowClass.hIconSm = LoadIcon(NULL, IDI_WINLOGO);

/* Register window class*/

if (!RegisterClassEx(&windowClass))

{

return 0;

}

/* Check if fullscreen is on*/

if (fullScreen)

{

DEVMODE dmScreenSettings;

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

dmScreenSettings.dmSize =
sizeof(dmScreenSettings);

dmScreenSettings.dmPelsWidth = width;
//screen width

dmScreenSettings.dmPelsHeight = height;
//screen height

dmScreenSettings.dmBitsPerPel = bits;
//bits per pixel

dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;

if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN !=

DISP_CHANGE_SUCCESSFUL))

{

/* Setting display mode failed, switch to windowed*/

MessageBox(NULL,
"Display mode failed", NULL, MB_OK);

fullScreen =
false;

}

}

/* Check if fullscreen is still on*/

if (fullScreen)

{

dwExStyle = WS_EX_APPWINDOW;
//window extended style

dwStyle = WS_POPUP;
//windows style

ShowCursor(FALSE);
//hide mouse pointer

}

else

{

dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
//window extended style

dwStyle = WS_OVERLAPPEDWINDOW;
//windows style

}

AdjustWindowRectEx(&windowRect, dwStyle, FALSE, dwExStyle);

/* Class registerd, so now create our window*/

hwnd = CreateWindowEx(NULL,
"MyClass", //class name

"OpenGL Robot", //app name

dwStyle |

WS_CLIPCHILDREN |

WS_CLIPSIBLINGS,

0, 0,
//x and y coords

windowRect.right - windowRect.left,

windowRect.bottom - windowRect.top,
//width, height

NULL,
//handle to parent

NULL,
//handle to menu

hInstance,
//application instance

NULL);
//no xtra params

/* Check if window creation failed (hwnd = null ?)*/

if (!hwnd)

{

return 0;

}

ShowWindow(hwnd, SW_SHOW);
//display window

UpdateWindow(hwnd);
//update window

done =
false; //initialize loop condition variable

/* Main message loop*/

while (!done)

{

PeekMessage(&msg, hwnd, NULL, NULL, PM_REMOVE);

if (msg.message == WM_QUIT) //did we revieve a quit message?

{

done =
true;

}

else

{

Render();

TranslateMessage(&msg);

DispatchMessage(&msg);

}

}

if (fullScreen)

{

ChangeDisplaySettings(NULL, 0);

ShowCursor(TRUE);

}

return msg.wParam;

}

Thursday, March 08, 2007




Hoy es de esos dìas, en los que despierto y deseo ..you know...hacer un autómata que...:
sólo acepte tener 3 b´s. Conteniendo el alfabeto a,b.

la imagen rosita muestra esta automáta...

Además de esto, también desperté con ganas de hacer una autómata que sólo acepte palabras de longitud 6....

y pueees la imagen moradita es la que corresponde a esta otra automáta.

ah con que ganas despierta uno....

Tuesday, March 06, 2007


Speaking of which, I have a nifty picture of the robot that I have just recently made the code for...

I must say, that I have had a lot of problems building this figure...Because I didn`t use POP or PUSH!!! People pleeease read about what does glPushMatrix() and glPopMatrix() do ! It is sooo important!..it really caused me a lot of trouble. I went to bed very late last night, cuz I couldn`t finish the damn leg of this thing. It was really giving me a lot of trouble!..and all cuz I just couldn`t put myself upto reading more about how to do it correctly.

...Speaking of which...
tonight is also poems night.Specially tonight! why tonight, you might ask?...
Well, basically cuz I`ve been with my dear boy for 7 months now...and this calls for a poemy night with nice night poems:

Somewhere on the other side of this wide night
and the distance between us, I am thinking of you.
The room is turning slowly away from the moon.

This is pleasurable. Or shall I cross that out and say
it is sad? In one of the tenses I singing
an impossible song of desire that you cannot hear.

La lala la. See? I close my eyes and imagine
the dark hills I would have to cross
to reach you. For I am in love with you and this

is what it is like or what it is like in words...

Transformaciones Geometricas.

Una transformaciòn geomètrica permite eliminar la distorciòn geomètrica que pudiese existir cuando una imagen es capturada.

Una transformaciòn geòmetrica es una funciòn de vectores que mapea el pixel (x,y) a una nueva posición (x',y'),Las transformaciones más usuales son las traslaciones, rotaciones y escalado.

· Traslación : Una traslaciòn simplemente mueve un objeto de un lugar a otro, al poner un ligero offset en X y en Y:


El segundo tipo de transformacion que existe se llama escalamiento. El escalamiento cambia el tamaño del objeto al multiplcar las coordenadas X y Y de un objeto por una constante de escalamiento.S

scaling
Figure 5: Scaling by Sx=2 Sy=2.

El ùltimo tipo de transformaciòn que veremos es la de rotacion. Puntos son rotados con respecto al origen un cierto àngulo.

rotation around the origin
Figure 6: Rotation around the origin.

object rotation
Figure 7: Rotation of an object by 45 degrees.

Las tres transformaciones se llevan acabo al efectuar multiplicaciones entre matrices.

Las matrices con las que se multiplica a los vectores son respectivamente:


transformation matrices
Figure 8: Formulas para translacion, escalamiento y rotaciòn.



Ahora bien OpenGl, nos brinda difernetes funciones para llevar acabo estas operaciones.

o Traslación (Translation)

glTranslatef( GLfloat x, GLfloat y, GLfloat z); en donde la función toma la medida de las variables x, y ,z para mover el objeto en sus ejes correspondientes dichas unidades.

o Escala (Scaling)
glScalef(GLfloat x , GLfloat y, Glfloat z); en donde cada uno de los parámetros mostrados indica la coordenada por la cual se multiplicará el valor real del objeto para posteriormente escalarlo a la medida deseada.

o Rotación

glRotatef(GLfloat angle, GLfloat x, GLfloat y, Glfloar z); en donde el parámetro se refiere a el ángulo que se desea rotar el objeto ; así tambien los tres subsecuentes especifican la rotaciòn a través de algun eje en especifico dando lugar asì al vector.

Charlando ahora de otro tema, entremos a ver que diablos es
GL_PROJECTION: Es bàsicamnete una matriz de transformaciòn que se aplica a todos los puntos que vienen despuès de este comando. GL_MODELVIEW es una matriz de transformaciòn que se aplica a cada punto de un modelo en particular. Hay una jeraqruia entre las transformaciones , se tiene a GL_PROJECTION hasta arriba y se tienen como ramas a GL_MODEL .

Por ello, antes de realizar una operación de transformación es necesario indicar sobre que matriz se va a realizar. Se especifica con la función glMatrixMode(Glenum mode) que tiene como argumento una de las tres constantes enumeradas. Se comporta como un estado, por tanto, hasta que se especifique un nuevo estado todas las transformaciones se realizan sobre la última matriz especificada.Para poder intercambiar entre una y otra matriz se emplea el comando glMatrixMode(Glenum mode) y posteriormente se inicia la matriz con glLoadIdentity()

A continuaciòn mostrarè un còdigo para ejemplificar màs esto:

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1, 1, -1, 1, -1.0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1, 1, -1, 1, -1.0, 1.0);
glTranslate( 100, 100, 100 );
glRotateF( 45, 1, 0, 0 );
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslate( modelx, modely, modelz );
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1, 1, -1, 1, -1.0, 1.0);
glTranslate( camerax, cameray, cameraz );

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslate( carx, cary, carz );
// draw car here, by specifying various gl vertices

glLoadIdentity();
glTranslate( battleshipx, battleshipy, battleshipz );
// draw battleship here, by specifying various gl vertices
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1, 1, -1, 1, -1.0, 1.0);
glTranslate( camerax, cameray, cameraz );
glRotateF( cameraanglex, 1, 0, 0 );


¿ Què podemos concluir del còdigo anterior?
Es una MENTIRA QUE SE USA LA CAMARA, It is, because its pretty
obvious that we're really moving the entire world to get our picture,
and not some "camera"!!!

Ahora bien...ya que estamos chlando tan agusto, toquemos otro tema interesantòn:


En la función display() se encuentran las llamadas a dos funciones de matrices que todavía no han sido comentadas. Se trata de glPushMatrix() y glPopMatrix(). Para comprender su funcionamiento, primero se va a experimentar que es lo que ocurre cuando no están dichas llamadas. Para ello se comentan en la función display() ambas llamadas:

void display(void) {

...

// glPushMatrix();

...

glTranslatef(0.0, 0.0, .5);

...

// glPopMatrix();

glutSwapBuffers();

}

Al ejecutar de nuevo la aplicación, primeramente tiene el mismo aspecto que sin comentar las llamadas, pero si obligamos a que se llame varias veces a la función display(), por ejemplo pulsando la tecla “c” (que activa y desactiva los polígonos posteriores del objeto), vemos que además de producirse el efecto de cambiar el modo GL_CULL_FACE, el objeto se va moviendo progresivamente a lo largo de eje “Z”.

La razón de este movimiento es que en la función display está incluida una llamada a glTranslatef() que se utiliza para posicionar uno de los objetos. Como se ha explicado anteriormente, las funciones de traslación multiplican la matriz actual por una matriz de traslación creada con los argumentos que se le pasan, por tanto, sucesivas llamadas a la función display() provocan sucesivas multiplicaciones de la matriz actual con el efecto que se observa de incrementar la traslación.

Para solucionar este problema OpenGL dispone de unos stacks o pilas de matrices, que ermiten almacenar y recuperar una matriz anterior. Aunque OpenGL dispone de pilas para las matrices GL_MODELVIEW y GL_PROJECTION, sólo se suele utilizar la pila de GL_MODELVIEW. Una pila es un almacén con funcionamiento LIFO, el último en entrar es el primero en salir, por lo que suele comparar a una pila de platos en la que sólo se puede dejar uno encima de la pila o coger el superior que es el último depositado. La pila de matrices tiene el mismo funcionamiento sustituyendo los platos por matrices. La matriz superior de la pila es sobre la que se aplican las distintas transformaciones, multiplicándola por la matriz que generan las distintas funciones.

Para poder guardar una determinada matriz y posteriormente recuperarla OpenGLdispone de las dos funciones comentadas: glPushMatrix() y glPopMatrix().

La función glPushMatrix() realiza una copia de la matriz superior y la pone encima de la pila, de tal forma que las dos matrices superiores son iguales. En la figura 1 se observa la pila en la situación inicial con una sola matriz, al llamar a la función glPushMatrix() se duplica la matriz superior. Las siguientes transformaciones que se realizan se aplican sólo a la matriz superior de la pila, quedando la anterior con los valores que tenía en el momento de llamar a la función glPushMatrix().

La función glPopMatrix() elimina la matriz superior, quedando en la parte superior de

la pila la matriz que estaba en el momento de llamar a la función glPushMatrix().


En la función display() al llamar a la función glPushMatrix() se realiza una copia de la matriz actual. La traslación en el eje Z se realiza en la matriz superior de la pila, es decir, en la copia de la matriz, de tal forma que al llamar a la función glPopMatrix(), como se muestra en la figura 1, se elimina la matriz superior, que es la que tenía el efecto de esta transformación, quedando la matriz que estaba en el momento de llamar a glPushMatrix(). Al descomentar las llamadas a las funciones glPushMatrix() y glPopMatrix() las transformaciones realizadas entre ambas no afectan al resto de la aplicación.



Pues parece ser que ya mero estamos listos para entrar a programar en Opengl...But there is still something very important about OpenGl that you should know about:

Para crear cualquier figura geométrica en OpenGL hay que definir los vértices entre un par de llamadas a las funciones glBegin() y glEnd(). A la función glBegin se le puede pasar un argumento que determina qué tipo de figura geométrica se va construir. Después se definen los vértices mediante llamadas a la función glVertex. A ontinuación vemos un ejemplo en el que se define el polígono de la figura.

glBegin (GL_POLYGON);

glVertex2f (0.0, 0.0);

glVertex2f (0.0, 3.0);

glVertex2f (3.0, 3.0);

glVertex2f (4.0, 1.5);

glVertex2f (3.0, 0.0);

glEnd ();



void glBegin (GLenum mode);

Marca el principio de una lista de vértices que describen una primitivageométrica



void glEnd (void);

Marca el final de una lista de vértices.


Another yet interesting subject is of course: MODElADO gEOMETRICO!

Un modelo geometrico describe la figura de un objeto fisico o matematico mediante conceptos geometricos. El modelado geometrico es la construcion o
uso de modelos geometricos.
Los modelos Geometricos se suelen usar en computacion grafica,diseÑo asistido por computadora, asi como en muchas otras ramas aplicadas, como es
procesamiento de imagenes medicas.
 
 
Los modelos geometricos se pueden construir para objetos de cualquier Dimension en cualquier espacio geometricos. Asi los diferentes tipos de
modelados geometricos se distinguen  justo en la dimension para la cual han sido construido. Tanto
los modelos para   dimensiones de 2D y 3D son usados mucho en computacion grafica.
 
 
Los modelos geometricos se  distinguinguen mucho  de los modelos orientados a objetos, debido a que esos modelos  definen la figura usando
implicitamente un algoritmo.  Tambien contrastan con las imàgenes digitales y los modelos
volumetricos, asi como con modelos matematicos implicitos  como es el set zero
de un polinomio arbitrario. Sin embargo, la distincion es en ocasiones un
poco confusa, por ejemplo figuras geometricas pueden ser representadas por objetos,
una imagen digital puede ser interpretada como una coleccion de cuadrados de
colores, figuaras gèometricas, como peude ser un cìrculo, està  definido por una ecuacion matematica implicita. Asimismo, el modelado de un
objeto fractal requiere de una combiancion de difernetes tipos de tecnicas.


And since we are writing on into the night, let`s touch yet another matter:


glClearColor - Especifica  valores para limpiar  el buffer de color.
Su especificacion esta dada por:
 
void glClearColor( GLclampf  red, GLclampf green, GLclampf blue,Glclampf alpha )
 
Los parámetros son:  red, green, blue, alpha
 
Especifica  los valores rojo, verde, azul y alpha que son usados cuando  el buffer de  color es reseteado.  Los valores iniciales son todos cero.
 
Descripción: GLClearColor especifica los valores red, green, blue y alpha que serán usados por glClear para limpiar los colores del buffer. Los valores especificados por glClearColor están dentro del rango de [0,1].
 
 
glClear - Limpia los buffers para poner nuevos valores.
 
C ESPECICACION:void glClear(    GLbitfield mask   )
 
PARAMETROS: mask       Es una serie de Operaciones Bitwise de las masks que indican  los buffers que deben ser vaciados.
Las 4 mascaras son GL_COLOR_BUFFER_BIT,GL_DEPTH_BUFFER_BIT, GL_ACCUM_BUFFER_BIT, and
                               GL_STENCIL_BUFFER_BIT.
 
DESCRIPCION: glClear  pone en el área del bitplane los valores antes seccionados por el             glClearColor, glClearIndex, glClearDepth,glClearStencil,y glClearAccum. Múltiples bufferS de color
pueden ser limpiados simultáneamente al seleccionar mas de un buffer a la vez utilizando la herramienta de glDrawBuffer.
 
 glClear toma un solo argumento que es el resultante de la operación
bitwise OR de diversos valores, este argumento indica cual de los buffers ha de ser limpiado.
 
 
               
EJEMPLO DE CODIGO USANDO glClear y glClearColor
 
 
 
               #include 
#include 
#include 
using namespace std;
 
// function prototypes
void disp(void);
void keyb(unsigned char key, int x, int y);
 
 
// window identifier
static int win;
 
int main(int argc, char **argv){
 
  //////////
  // INIT //
  //////////
 
  // initialize glut
  glutInit(&argc, argv);
 
  // specify the display mode to be RGB and single buffering
  // we use single buffering since this will be non animated
  glutInitDisplayMode(GLUT_RGBA | GLUT_SINGLE);
 
  // define the size
  glutInitWindowSize(500,500);
 
  // the position where the window will appear
  glutInitWindowPosition(100,100);
 
 
  // if we would want fullscreen:
  // glutFullScreen();
 
  // create the window, set the title and keep the
  // window identifier.
  win = glutCreateWindow("Yet another teapot");
 
  //////////////
  // CALLBACK //
  //////////////
 
  glutDisplayFunc(disp);
  glutKeyboardFunc(keyb);
 
  ////////////
  // OPENGL //
  ////////////
 
  // define the color we use to clearscreen
  glClearColor(0.0,0.0,0.0,0.0);
 
 
 
  // enter the main loop
  glutMainLoop();
 
  return 0;
}
 
 
void disp(void){
 
  // do  a clearscreen
  glClear(GL_COLOR_BUFFER_BIT);
 
  // draw something
 
  glutWireTeapot(0.5);
  // glutSolidTeapot(0.5);
  // glutWireSphere(0.5,100,100);
  // glutSolidSphere(0.5,100,100);
  // glutWireTorus(0.3,0.5,100,100);
  // glutSolidTorus(0.3,0.5,100,100);
  // glutWireIcosahedron();
  // glutSolidIcosahedron();
  // glutWireDodecahedron();
  // glutSolidDodecahedron();
  // glutWireCone(0.5,0.5,100,100);
  // glutSolidCone(0.5,0.5,100,100);
  // glutWireCube(0.5);
  // glutSolidCube(0.5);
}
 
void keyb(unsigned char key, int x, int y){
  cout << "Pressed key " <<>
")";
  cout <<>
  if(key == 'q'){
    cout << "Got q,so quitting " <<>
    glutDestroyWindow(win);
    exit(0);
  }
9)
glutInit
 
glutInit es utilizada para inicializar la  librería de  GLUT.
Se usa de la siguiente forma:
void glutInit(int *argcp, char **argv);
argcp: es un apuntador a la variable argc del main.
argv: la variable argv sin modificar del main.
Descripción:glutInit inicializara la librería GLUT y negociara una sesión con la ventana
del  sistema .
 
 
glutInitDisplayMode: Asigna el modo de display inicial.
Se utiliza de la siguiente forma:
void glutInitDisplayMode(unsigned int mode);
mode: Es el modo de display. Algunos ejemplos son:
GLUT_RGBA: Mascara bit para seleccionar una ventana de modo RBGA.
GLUT_STEREO: Mascara de bit para seleccionar una ventana de tipo stereo.
 
glutInitWindowPosition pone el valor inicial de la ventana . La sintaxis para su uso es:
 
glutInitWindowPosition(x,y) x, y: localización de la ventana en pixeles.
 
 
glutInitWindowSize — Pone el tamaño de la ventana inicial.
glutInitWindowSize(width,height)
 
glutCreateWindow (): Crea una ventana de nivel superior. La sintaxis es: int glutCreateWindow(char *name)
 
glutDisplayFunc(): Fija el callback del display para la ventana en cuestion.Se utiliza de la siguiente forma:
void glutDisplayFunc(void (*func)(void));
 
func es la nueva funcion de callback.
Cuando GLUT determina que el plano normal de la ventan necesita volverse a desplejar, el display callback para la ventana es llamado.
 
glutReshapeFunc() pone el callback de  la redefinicion del tamanio para la ventana en cuestion.
 
void glutReshapeFunc(void (*func)(int width, int height));
func: es la nueva funcion  reshape callback
 
El  reshape callback es llamado cuando se cambia el tamanio de la ventana.
 
glutKeyboardFunc(): Pone el callback del teclado para la ventana actual.
void glutKeyboardFunc(void (*func)(unsigned char key,int x, int y));
func: es la nueva funcion  teclado callback
glutMainLoop() mete el  loop del  evento de procesameinto de GLUT. Una vez que es llamada esta rutina nunca retornara
 
Hemos estado usando mucho la palabra callback aquì...but what the f* es un callback?
 
Callback: Se dice que existe un callback, cuando ocurre un cierto  evento y uno programa la respuesta que dará el programa.
Uno define que función será llamada (called) cuando sucede un evento.  Ahora bien, Glut tiene una serie de callbacks bien definidas.
ejemplo:
void glutDisplayFunc(void (*func)(void));
Esto especifica la función que necesita ser llamada cuando se redibuja la ventana



Hey Everybody...
I have just made a fancy mancy robot man!!
Yeaaah..very nice robot man. For all you C++ and opengl looovers, here is the code, with which I made it with:

#include   // Header File For Windows
#include // Header File For The OpenGL32 Library
#include // Header File For The GLu32 Library
#include // Header File For The Glaux Library

HDC hDC=NULL; // Private GDI Device Context
HGLRC hRC=NULL; // Permanent Rendering Context
HWND hWnd=NULL; // Holds Our Window Handle
HINSTANCE hInstance; // Holds The Instance Of The Application

bool keys[256]; // Array Used For The Keyboard Routine
bool active=TRUE; // Window Active Flag Set To TRUE By Default
bool fullscreen=TRUE; // Fullscreen Flag Set To Fullscreen Mode By Default

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); // Declaration For
WndProc

GLvoid ReSizeGLScene(GLsizei width, GLsizei height) // Resize And
Initialize The GL Window
{
if (height==0) // Prevent A Divide By Zero By
{
height=1; // Making Height Equal One
}

glViewport(0,0,width,height); // Reset The Current Viewport

glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity(); // Reset The Projection Matrix

// Calculate The Aspect Ratio Of The Window
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);

glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity(); // Reset The Modelview Matrix
}

int InitGL(GLvoid) // All Setup For OpenGL Goes Here
{
glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
glClearDepth(1.0f); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice
Perspective Calculations
return TRUE; // Initialization Went OK
}

int DrawGLScene(GLvoid) // Here's Where We Do All The Drawing
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And
Depth Buffer
glLoadIdentity(); // Reset The Current Modelview Matrix
/*glTranslatef(0.0f,0.0f,-6.0f); // Move Left 1.5 Units And Into The
Screen 6.0
glBegin(GL_QUADS); // Drawing Using Triangles
glVertex3f(0.0f, 0.0f, 0.0f); // Top Left
glVertex3f( 1.0f, 0.0f, 0.0f); // Top Right
glVertex3f( 1.0f,1.0f, 0.0f); // Bottom Right
glVertex3f(0.0f,1.0f, 0.0f);
glEnd();*/

glTranslatef(0.0f,0.0f,-8.0f);
glBegin(GL_QUADS);


glVertex3f(0.0f, 0.0f, 0.0f); // Top Left
glVertex3f( 1.0f, 0.0f, 0.0f); // Top Right
glVertex3f( 1.0f,2.0f, 0.0f); // Bottom Right

glVertex3f(0.0f,2.0f, 0.0f);
glEnd();




glTranslatef(0.0f,-3.0f,-8.0f);
glBegin(GL_QUADS);


glVertex3f(0.0f, 0.0f, 0.0f); // Top Left
glVertex3f( 0.5f, 0.0f, 0.0f); // Top Right
glVertex3f( 0.5f,3.0f, 0.0f); // Bottom Right

glVertex3f(0.0f,3.0f, 0.0f);
glEnd();

glTranslatef(-0.5f,-3.0f,-8.0f);//cuadrado ancho.
glBegin(GL_QUADS);


glVertex3f(0.0f, 0.0f, 0.0f); // Top Left
glVertex3f( 1.5f, 0.0f, 0.0f); // Top Right
glVertex3f( 1.5f,3.0f, 0.0f); // Bottom Right

glVertex3f(0.0f,3.0f, 0.0f);
glEnd();

glTranslatef(-1.5f,-2.0f,-8.0f);
glBegin(GL_QUADS);


glVertex3f(0.0f, 0.0f, 0.0f); // Top Left
glVertex3f( 3.0f, 0.0f, 0.0f); // Top Right
glVertex3f( 3.0f,1.0f, 0.0f); // Bottom Right

glVertex3f(0.0f,1.0f, 0.0f);
glEnd();

glTranslatef(2.0f,18.0f,-8.0f);//Brazo.
glBegin(GL_QUADS);


glVertex3f(0.0f, 0.0f, 0.0f); // Top Left
glVertex3f( -3.0f, 0.0f, 0.0f); // Top Right
glVertex3f( -3.0f,-1.0f, 0.0f); // Bottom Right

glVertex3f(0.0f,-1.0f, 0.0f);
glEnd();

glTranslatef(-3.0f,2.5f,-8.0f);//Brazo.
glBegin(GL_QUADS);


glVertex3f(0.0f, 0.0f, 0.0f); // Top Left
glVertex3f( -3.0f, 0.0f, 0.0f); // Top Right
glVertex3f( -3.0f,-2.0f, 0.0f); // Bottom Right

glVertex3f(0.0f,-2.0f, 0.0f);
glEnd();

glTranslatef(-3.0f,1.7f,-8.0f);//Brazo.
glBegin(GL_QUADS);


glVertex3f(0.0f, 0.0f, 0.0f); // Top Left
glVertex3f( -3.0f, 0.0f, 0.0f); // Top Right
glVertex3f( -3.0f,-1.5f, 0.0f); // Bottom Right

glVertex3f(0.0f,-1.5f, 0.0f);
glEnd();

glTranslatef(8.0f,5.9f,-8.0f);//Brazo.
glBegin(GL_QUADS);


glVertex3f(0.0f, 0.0f, 0.0f); // Top Left
glVertex3f( 4.0f, 0.0f, 0.0f); // Top Right
glVertex3f( 4.0f,-4.0f, 0.0f); // Bottom Right

glVertex3f(0.0f,-4.0f, 0.0f);
glEnd();

glTranslatef(7.0f,-2.0f,-8.0f);//Brazo.
glBegin(GL_QUADS);


glVertex3f(0.0f, 0.0f, 0.0f); // Top Left
glVertex3f( 4.5f, 0.0f, 0.0f); // Top Right
glVertex3f( 4.5f,-2.0f, 0.0f); // Bottom Right

glVertex3f(0.0f,-2.0f, 0.0f);
glEnd();

glTranslatef(6.0f,-0.5f,-8.0f);//Brazo.
glBegin(GL_QUADS);


glVertex3f(0.0f, 0.0f, 0.0f); // Top Left
glVertex3f( 4.5f, 0.0f, 0.0f); // Top Right
glVertex3f( 4.5f,3.0f, 0.0f); // Bottom Right

glVertex3f(0.0f,3.0f, 0.0f);
glEnd();

glTranslatef(6.5f,4.5f,-8.0f);//Brazo.
glBegin(GL_QUADS);


glVertex3f(0.0f, 0.0f, 0.0f); // Top Left
glVertex3f( 2.0f, 0.0f, 0.0f); // Top Right
glVertex3f( 2.0f,-2.0f, 0.0f);
glVertex3f( 0.0f,-2.0f, 0.0f);
glEnd();


glTranslatef(-12.5f,-22.0f,-8.0f);//Brazo.
glBegin(GL_QUADS);


glVertex3f(0.0f, 0.0f, 0.0f); // Top Left
glVertex3f( 3.0f, 0.0f, 0.0f); // Top Right
glVertex3f( 3.0f,-13.0f, 0.0f);
glVertex3f( 0.0f,-13.0f, 0.0f);
glEnd();


glTranslatef(-6.0f,-13.0f,-8.0f);//Brazo.
glBegin(GL_QUADS);


glVertex3f(0.0f, 0.0f, 0.0f); // Top Left
glVertex3f( 10.0f, 0.0f, 0.0f); // Top Right
glVertex3f( 10.0f,-13.0f, 0.0f);
glVertex3f( 0.0f,-13.0f, 0.0f);
glEnd();

glTranslatef(0.0f,-13.0f,-8.0f);//Brazo.
glBegin(GL_QUADS);


glVertex3f(0.0f, 0.0f, 0.0f); // Top Left
glVertex3f( 4.0f, 0.0f, 0.0f); // Top Right
glVertex3f( 4.0f,2.0f, 0.0f);
glVertex3f( 0.0f,-2.0f, 0.0f);
glEnd();






// Finished Drawing The Triangle
//glTranslatef(0.0f,1.0f,-6.0f); // Move Right 3 Units




return TRUE; // Everything Went OK
}

GLvoid KillGLWindow(GLvoid) // Properly Kill The Window
{
if (fullscreen) // Are We In Fullscreen Mode?
{
ChangeDisplaySettings(NULL,0); // If So Switch Back To The Desktop
ShowCursor(TRUE); // Show Mouse Pointer
}

if (hRC) // Do We Have A Rendering Context?
{
if (!wglMakeCurrent(NULL,NULL)) // Are We Able To Release The DC And
RC Contexts?
{
MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK |
MB_ICONINFORMATION);
}

if (!wglDeleteContext(hRC)) // Are We Able To Delete The RC?
{
MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN
ERROR",MB_OK | MB_ICONINFORMATION);
}
hRC=NULL; // Set RC To NULL
}

if (hDC && !ReleaseDC(hWnd,hDC)) // Are We Able To Release The DC
{
MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK |
MB_ICONINFORMATION);
hDC=NULL; // Set DC To NULL
}

if (hWnd && !DestroyWindow(hWnd)) // Are We Able To Destroy The Window?
{
MessageBox(NULL,"Could Not Release hWnd.","SHUTDOWN ERROR",MB_OK |
MB_ICONINFORMATION);
hWnd=NULL; // Set hWnd To NULL
}

if (!UnregisterClass("OpenGL",hInstance)) // Are We Able To Unregister
Class
{
MessageBox(NULL,"Could Not Unregister Class.","SHUTDOWN ERROR",MB_OK |
MB_ICONINFORMATION);
hInstance=NULL; // Set hInstance To NULL
}
}

/* This Code Creates Our OpenGL Window. Parameters Are: *
* title - Title To Appear At The Top Of The Window *
* width - Width Of The GL Window Or Fullscreen Mode *
* height - Height Of The GL Window Or Fullscreen Mode *
* bits - Number Of Bits To Use For Color (8/16/24/32) *
* fullscreenflag - Use Fullscreen Mode (TRUE) Or Windowed Mode (FALSE) */

BOOL CreateGLWindow(char* title, int width, int height, int bits, bool
fullscreenflag)
{
GLuint PixelFormat; // Holds The Results After Searching For A Match
WNDCLASS wc; // Windows Class Structure
DWORD dwExStyle; // Window Extended Style
DWORD dwStyle; // Window Style
RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values
WindowRect.left=(long)0; // Set Left Value To 0
WindowRect.right=(long)width; // Set Right Value To Requested Width
WindowRect.top=(long)0; // Set Top Value To 0
WindowRect.bottom=(long)height; // Set Bottom Value To Requested Height

fullscreen=fullscreenflag; // Set The Global Fullscreen Flag

hInstance = GetModuleHandle(NULL); // Grab An Instance For Our Window
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw On Size, And Own
DC For Window.
wc.lpfnWndProc = (WNDPROC) WndProc; // WndProc Handles Messages
wc.cbClsExtra = 0; // No Extra Window Data
wc.cbWndExtra = 0; // No Extra Window Data
wc.hInstance = hInstance; // Set The Instance
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load The Default Icon
wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer
wc.hbrBackground = NULL; // No Background Required For GL
wc.lpszMenuName = NULL; // We Don't Want A Menu
wc.lpszClassName = "OpenGL"; // Set The Class Name

if (!RegisterClass(&wc)) // Attempt To Register The Window Class
{
MessageBox(NULL,"Failed To Register The Window
Class.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

if (fullscreen) // Attempt Fullscreen Mode?
{
DEVMODE dmScreenSettings; // Device Mode
memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure
Memory's Cleared
dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode
Structure
dmScreenSettings.dmPelsWidth = width; // Selected Screen Width
dmScreenSettings.dmPelsHeight = height; // Selected Screen Height
dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel
dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

// Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets
Rid Of Start Bar.
if
(ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
{
// If The Mode Fails, Offer Two Options. Quit Or Use Windowed Mode.
if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported
By\nYour Video Card. Use Windowed Mode Instead?","NeHe
GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
{
fullscreen=FALSE; // Windowed Mode Selected. Fullscreen = FALSE
}
else
{
// Pop Up A Message Box Letting User Know The Program Is Closing.
MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP);
return FALSE; // Return FALSE
}
}
}

if (fullscreen) // Are We Still In Fullscreen Mode?
{
dwExStyle=WS_EX_APPWINDOW; // Window Extended Style
dwStyle=WS_POPUP; // Windows Style
ShowCursor(FALSE); // Hide Mouse Pointer
}
else
{
dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style
dwStyle=WS_OVERLAPPEDWINDOW; // Windows Style
}

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

// Create The Window
if (!(hWnd=CreateWindowEx( dwExStyle, // Extended Style For The
Window
"OpenGL", // Class Name
title, // Window Title
dwStyle | // Defined Window Style
WS_CLIPSIBLINGS | // Required Window Style
WS_CLIPCHILDREN, // Required Window Style
0, 0, // Window Position
WindowRect.right-WindowRect.left, // Calculate Window Width
WindowRect.bottom-WindowRect.top, // Calculate Window Height
NULL, // No Parent Window
NULL, // No Menu
hInstance, // Instance
NULL))) // Dont Pass Anything To WM_CREATE
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Window Creation
Error.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

static PIXELFORMATDESCRIPTOR pfd= // pfd Tells Windows How We Want
Things To Be
{
sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1, // Version Number
PFD_DRAW_TO_WINDOW | // Format Must Support Window
PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
PFD_DOUBLEBUFFER, // Must Support Double Buffering
PFD_TYPE_RGBA, // Request An RGBA Format
bits, // Select Our Color Depth
0, 0, 0, 0, 0, 0, // Color Bits Ignored
0, // No Alpha Buffer
0, // Shift Bit Ignored
0, // No Accumulation Buffer
0, 0, 0, 0, // Accumulation Bits Ignored
16, // 16Bit Z-Buffer (Depth Buffer)
0, // No Stencil Buffer
0, // No Auxiliary Buffer
PFD_MAIN_PLANE, // Main Drawing Layer
0, // Reserved
0, 0, 0 // Layer Masks Ignored
};

if (!(hDC=GetDC(hWnd))) // Did We Get A Device Context?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Create A GL Device
Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd))) // Did Windows Find A
Matching Pixel Format?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Find A Suitable
PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

if(!SetPixelFormat(hDC,PixelFormat,&pfd)) // Are We Able To Set The Pixel
Format?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Set The
PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

if (!(hRC=wglCreateContext(hDC))) // Are We Able To Get A Rendering
Context?
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Create A GL Rendering
Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

if(!wglMakeCurrent(hDC,hRC)) // Try To Activate The Rendering Context
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Can't Activate The GL Rendering
Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

ShowWindow(hWnd,SW_SHOW); // Show The Window
SetForegroundWindow(hWnd); // Slightly Higher Priority
SetFocus(hWnd); // Sets Keyboard Focus To The Window
ReSizeGLScene(width, height); // Set Up Our Perspective GL Screen

if (!InitGL()) // Initialize Our Newly Created GL Window
{
KillGLWindow(); // Reset The Display
MessageBox(NULL,"Initialization
Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION);
return FALSE; // Return FALSE
}

return TRUE; // Success
}

LRESULT CALLBACK WndProc( HWND hWnd, // Handle For This Window
UINT uMsg, // Message For This Window
WPARAM wParam, // Additional Message Information
LPARAM lParam) // Additional Message Information
{
switch (uMsg) // Check For Windows Messages
{
case WM_ACTIVATE: // Watch For Window Activate Message
{
if (!HIWORD(wParam)) // Check Minimization State
{
active=TRUE; // Program Is Active
}
else
{
active=FALSE; // Program Is No Longer Active
}

return 0; // Return To The Message Loop
}

case WM_SYSCOMMAND: // Intercept System Commands
{
switch (wParam) // Check System Calls
{
case SC_SCREENSAVE: // Screensaver Trying To Start?
case SC_MONITORPOWER: // Monitor Trying To Enter Powersave?
return 0; // Prevent From Happening
}
break; // Exit
}

case WM_CLOSE: // Did We Receive A Close Message?
{
PostQuitMessage(0); // Send A Quit Message
return 0; // Jump Back
}

case WM_KEYDOWN: // Is A Key Being Held Down?
{
keys[wParam] = TRUE; // If So, Mark It As TRUE
return 0; // Jump Back
}

case WM_KEYUP: // Has A Key Been Released?
{
keys[wParam] = FALSE; // If So, Mark It As FALSE
return 0; // Jump Back
}

case WM_SIZE: // Resize The OpenGL Window
{
ReSizeGLScene(LOWORD(lParam),HIWORD(lParam)); // LoWord=Width,
HiWord=Height
return 0; // Jump Back
}
}

// Pass All Unhandled Messages To DefWindowProc
return DefWindowProc(hWnd,uMsg,wParam,lParam);
}

int WINAPI WinMain( HINSTANCE hInstance, // Instance
HINSTANCE hPrevInstance, // Previous Instance
LPSTR lpCmdLine, // Command Line Parameters
int nCmdShow) // Window Show State
{
MSG msg; // Windows Message Structure
BOOL done=FALSE; // Bool Variable To Exit Loop

// Ask The User Which Screen Mode They Prefer
if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start
FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
{
fullscreen=FALSE; // Windowed Mode
}

// Create Our OpenGL Window
if (!CreateGLWindow("NeHe's OpenGL Framework",640,480,16,fullscreen))
{
return 0; // Quit If Window Was Not Created
}

while(!done) // Loop That Runs While done=FALSE
{
if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is There A Message Waiting?
{
if (msg.message==WM_QUIT) // Have We Received A Quit Message?
{
done=TRUE; // If So done=TRUE
}
else // If Not, Deal With Window Messages
{
TranslateMessage(&msg); // Translate The Message
DispatchMessage(&msg); // Dispatch The Message
}
}
else // If There Are No Messages
{
// Draw The Scene. Watch For ESC Key And Quit Messages From
DrawGLScene()
if (active) // Program Active?
{
if (keys[VK_ESCAPE]) // Was ESC Pressed?
{
done=TRUE; // ESC Signalled A Quit
}
else // Not Time To Quit, Update Screen
{
DrawGLScene(); // Draw The Scene
SwapBuffers(hDC); // Swap Buffers (Double Buffering)
}
}

if (keys[VK_F1]) // Is F1 Being Pressed?
{
keys[VK_F1]=FALSE; // If So Make Key FALSE
KillGLWindow(); // Kill Our Current Window
fullscreen=!fullscreen; // Toggle Fullscreen / Windowed Mode
// Recreate Our OpenGL Window
if (!CreateGLWindow("NeHe's OpenGL Framework",640,480,16,fullscreen))
{
return 0; // Quit If Window Was Not Created
}
}
}
}

// Shutdown
KillGLWindow(); // Kill The Window
return (msg.wParam); // Exit The Program


}