I want to know how can I make an animation that represents a rectangle with height increase/decrease in OpenGL. I know I'm supposed to use the glScale and glTranslate functions.
Below, I will attach the code that I've worked with so far, where I managed to apply a pretty basic transition of a rectangle.
#include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <stdlib.h>
static GLfloat trans = 0.0;
void init(void)
{
glClearColor(0.2, 0.2, 0.2, 0.2);
glShadeModel(GL_FLAT);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glTranslatef(0.0 , trans, 1.0);
glColor3f(1.0, 1.0, 1.0);
glRectf(-25.0, -25.0, 25.0, 25.0);
glPopMatrix();
glColor3f(0.0, 0.0, 1.0);
glRectf(-15.0, -15.0, 15.0, 15.0);
glutSwapBuffers();
}
void transLeft(void)
{
trans = trans - 0.05;
if (trans < -75)
trans = -75;
glutPostRedisplay();
}
void transRight(void)
{
trans = trans + 0.05;
if (trans > 75)
trans = 75;
glutPostRedisplay();
}
void reshape(int w, int h)
{
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-100.0, 100.0, -100.0, 100.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void mouse(int button, int state, int x, int y)
{
switch (button) {
case GLUT_LEFT_BUTTON:
if (state == GLUT_DOWN)
glutIdleFunc(transLeft);
break;
case GLUT_RIGHT_BUTTON:
if (state == GLUT_DOWN)
glutIdleFunc(transRight);
break;
default:
break;
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow(argv[0]);
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMouseFunc(mouse);
glutMainLoop();
return 0;
}
So you want to have variable height rectangle (based on what?).
Yes glScale(1.0,zoom,1.0) placed directly before or after the line
glTranslatef(0.0 , trans, 1.0);
In your display(void) function will do this. Where zoom is holding your animation state and is starting with value zoom=1.0 and to change size you just increment/decrement like this: zoom*=1.025 or zoom/=1.025.
However its usually better to interchange your hard-coded rectangle vertexes with variable ones based on parameter or time or whatever you want to change this with. That way you can interpolate between min and max rectangle size with parameter without changing the matrices which might pose a problem with other objects if you not careful And also this way provides more convenient control of the animation. For example you have:
glRectf(-25.0, -25.0, 25.0, 25.0);
And want to animate it to size:
glRectf(-25.0, -35.0, 25.0, 35.0);
over time so you can do this like this:
add some global or static variables holding your rectangle sizes and position and animation state:
// x0, y0beg, y0end, x1,y1beg,y1end
float myrec[]={-25.0, -25.0, -35.0, 25.0, 25.0, 35.0};
float t=0.0; // parameter in range <0.0,1.0>
in display compute your rectangle actual coordinates and render
You can use linear interpolation like this:
glRectf(myrect[0],myrect[1]+((myrect[2]-myrect[1])*t),
myrect[3],myrect[4]+((myrect[5]-myrect[4])*t));
set you t for animation somewhere
Where depends on what you want to achieve... If you have timer or some call that si repeated again and again you can increment the t in it by some step for example:
t+=dt/T;
if (t>1.0) t=1.0; // use t=0.0; if you want to repeat the animation after it finishes
Where dt is the avg time your call is repeated with and T is the time of whole animation finish. I do not use GLUT so I just assume your Display is called repeatedly (for example 60 times per second) and want the animation to finish in 2 sec then:
// dt = 1.0/60
// T = 2.0
t+=(1.0/120.0);
if (t>1.0) t=1.0; // use t=0.0; if you want to repeat the animation after it
You can also use elapsed time (by measuring it by some OS or environment function you have at your disposal I usually use performance timer/counters on windows) from last call instead of dt.
If you have more of such rectangles you can encapsulate this to some function and simply call it with pointer to its myrect values and parameter t for example:
void draw_rect(float *myrec,float t)
{
glRectf(myrect[0],myrect[1]+((myrect[2]-myrect[1])*t),
myrect[3],myrect[4]+((myrect[5]-myrect[4])*t));
}
float rec0[]={-25.0, -25.0, -35.0, 25.0, 25.0, 35.0};
float rec1[]={-15.0, -15.0, -25.0, 15.0, 15.0, 25.0};
float t=0.0; // parameter in range <0.0,1.0>
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glTranslatef(0.0 , trans, 1.0);
glColor3f(1.0, 1.0, 1.0);
draw_rect(rec0,t);
glPopMatrix();
glColor3f(0.0, 0.0, 1.0);
draw_rect(rec1,t);
glutSwapBuffers();
t+=(1.0/120.0);
if (t>1.0) t=0.0;
}
Related
I'm trying to 'animate' a rectangle's height based on a random number input. So with each new random number, the rectangle is re-drawn.
How do I do this?
My code:
#include <time.h>
#include <GL/freeglut.h>
#include <GL/gl.h>
float height;
int i;
/* display function - code from:
http://fly.cc.fer.hr/~unreal/theredbook/chapter01.html
This is the actual usage of the OpenGL library.
The following code is the same for any platform */
void renderFunction()
{
srand(time(NULL));
height = rand() % 10;
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0, 0.0, 1.0);
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
glBegin(GL_POLYGON);
glVertex2f(-0.5, -0.5); // bottom left corner
glVertex2f(-0.5, height); // top left corner
glVertex2f(-0.3, height); // top right corner
glVertex2f(-0.3, -0.5); // bottom right corner
glEnd();
glFlush();
}
/* Main method - main entry point of application
the freeglut library does the window creation work for us,
regardless of the platform. */
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE);
glutInitWindowSize(900,600);
glutInitWindowPosition(100,100);
glutCreateWindow("OpenGL - First window demo");
glutDisplayFunc(renderFunction);
glutIdleFunc(renderFunction);
glutReshapeFunc(renderFunction);
glutMainLoop();
return 0;
}
While the program doesn't crash is simply draws a single rectangle.
Given that your sizes are in the range 0.0 <= dimension <= 1.0 and the height you calculate is in the range 0 <= height <= 9, you need to scale the random number like this:
height = (float)rand() / RAND_MAX;
Also please move srand(time(NULL)); from renderFunction() to main() otherwise your rectangle sizes will be clamped during every second.
The rand()%10 returns an integer which is usually greater than or equal to 1. So the height is mostly 1 since the maximum height it can render on the screen is 1.
How is the reshape() function working in this code and how is it getting its parameter from glutReshapeFunc(reshape) without any parameter in reshape of glutReshapeFunc(reshape)?
What is the value of int x, int y in void keyboard (unsigned char key, int x, int y) function?
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
static int year = 0, day = 0;
void init(void)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel (GL_FLAT);
}
void display(void)
{
glClear (GL_COLOR_BUFFER_BIT);
glColor3f (1.0, 1.0, 1.0);
glPushMatrix();
glutWireSphere(1.0, 20, 16); /* draw sun */
glRotatef ((GLfloat) year, 0.0, 1.0, 0.0);
glTranslatef (2.0, 0.0, 0.0);
glRotatef ((GLfloat) day, 0.0, 1.0, 0.0);
glutWireSphere(0.2, 10, 8); /* draw smaller planet */
glPopMatrix();
glutSwapBuffers();
}
void reshape (int w, int h)
{
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluPerspective(60.0, (GLfloat) w/(GLfloat) h, 1.0, 20.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
}
void keyboard (unsigned char key, int x, int y)
{
switch (key) {
case `d':
day = (day + 10) % 360;
glutPostRedisplay();
break;
case `D':
day = (day - 10) % 360;
glutPostRedisplay();
break;
case `y':
year = (year + 5) % 360;
glutPostRedisplay();
break;
case `Y':
year = (year - 5) % 360;
glutPostRedisplay();
break;
default:
break;
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow (argv[0]);
init ();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMainLoop();
return 0;
}
It appears that the glutReshapeFunc() function takes a pointer to a function; presumably, in fact, it is declared as something somewhat similar to:
void glutReshapeFunc(void (*function)(int x, int y));
Similarly, glutDisplayFunc() takes another pointer to a function, and glutKeyboardFunc() also takes a pointer to a function. When a function is specified by name without the function call parentheses after it, it reduces to 'pointer to a function' (or you can think of a bare function name as a pointer to the function body, like a bare array name is a pointer to the start of the array).
You'd have to read the manual to discover the purpose of the x and y parameters to the keyboard() function. They aren't used by the code shown. They are likely the position of something, but which something is less than clear without reading the manual.
reshape and keyboard functions are used as so called callbacks. You're giving GLUT pointers to those functions, GLUT keeps those pointers and calls those function, with parameters, at the times as specified in the GLUT documentation.
About like that:
void (*display_callback)(void);
void (*reshape_callback)(int, int);
void (*keyboard_callback(unsigned char, int, int);
/* ... */
void eventloop(...)
{
while(...) {
if( keyboard_event )
keyboard_callback(keyboard_event->key, mouse_x, mouse_y);
if( window_reshaped )
reshape_callback(window->width, window->height);
if( needs_redraw )
display_callback();
}
}
Now regarding what's done in the reshape callback: Everything that's placed there in beginner tutorials is actually much better done in the display function. Setting the viewport, setting the projection I mean. Later you'll probably want to draw a HUD, some text or a minimap, or a split view. And once you've reached that point, a reshape function doing viewport and projection setup becomes a liability. So get rid of it now.
void display(void)
{
int const w = glutGet(GLUT_WINDOW_WIDTH);
int const h = glutGet(GLUT_WINDOW_HEIGHT);
glClear (GL_COLOR_BUFFER_BIT);
glColor3f (1.0, 1.0, 1.0);
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluPerspective(60.0, (GLfloat) w/(GLfloat) h, 1.0, 20.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
glPushMatrix();
glutWireSphere(1.0, 20, 16); /* draw sun */
glRotatef ((GLfloat) year, 0.0, 1.0, 0.0);
glTranslatef (2.0, 0.0, 0.0);
glRotatef ((GLfloat) day, 0.0, 1.0, 0.0);
glutWireSphere(0.2, 10, 8); /* draw smaller planet */
glPopMatrix();
glutSwapBuffers();
}
I hope this will be a direct answer to this question.
The reshape function is a call back function which is called whenever size or shape of the application window changes. Reshape function takes 2 arguments,they are width and height of reshaped window. Mainly these parameters are used to set a new viewport.
I am trying to draw a 6 sided obelisk using opengl.
Below is the code I use to model the bottom surface of the obelisk:
void drawObelisk() {
glColor3f(1.0,1.0,0.0);
glBegin(GL_POLYGON);
for ( x=0.0; x<2.0*pi/3; x=x+inc )
{
glVertex3f(0.3*cos(x),0.3*sin(x),0.0);
}
glEnd();
}
This code is used to render the model:
void myDisplay(void)
{
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
drawObelisk();
glPopMatrix();
glFlush();
}
void SetupRC(void)
{
glClearColor(0.0, 0.0, 1.0, 1.0);
glOrtho(-6.0,6.0,-6.0,6.0,-6.0,6.0);
}
void main(void)
{
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(640,480);
glutInitWindowPosition(10,15);
glutCreateWindow("Test");
glutDisplayFunc(myDisplay);
SetupRC();
glutIdleFunc(idle);
glutMainLoop();
}
For certain reasons the polygon surface that I drew didn't show up on the screen once the model is rendered.
Give this a shot:
#include <GL/glut.h>
#include <math.h>
void drawObelisk()
{
double pi = 3.14159;
double inc = (2*pi) / 6;
glColor3f(1.0,1.0,0.0);
glBegin(GL_POLYGON);
for( double theta = 0.0; theta < 2*pi; theta += inc )
{
double scale = 2.0;
double x = scale * cos( theta );
double y = scale * sin( theta );
glVertex3d(x,y,0.0);
}
glEnd();
}
void myDisplay(void)
{
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glClearColor(0.0, 0.0, 1.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-6.0,6.0,-6.0,6.0,-6.0,6.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glPushMatrix();
drawObelisk();
glPopMatrix();
glFlush();
}
void main( int argc, char** argv )
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(640,480);
glutInitWindowPosition(10,15);
glutCreateWindow("Test");
glutDisplayFunc(myDisplay);
glutMainLoop();
}
Things that were wonky:
Missing glutInit() call.
glClear()ing the depth buffer without requesting one via GLUT_DEPTH.
Not switching to GL_MODELVIEW after setting your projection matrix.
Original drawObelisk() for-loop only generated two vertices. GL_POLYGON needs a minimum of three.
I am trying to put lights, materials and shadows to my robot arm but unfortunately something weird happens (please compile or see the below picture), now I am still annoying by
1) Not showing correct lighting and reflection properties as well as material properties
2) No shadow painted, although I have done the shadow casting in function "void showobj(void)"
I appreciate if anyone can help, I have already working for it 2 days with no progress :(
The following is my code
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <GL/glut.h>
#include "gsrc.h"
#include <Windows.h>
const double PI = 3.14159265;
// angles to rotate the base, lower and upper arms of the robot arm
static GLfloat theta, phi, psi = 0.0;
//Starting time
double startT;
//Time Diff variable
double dif,startTime,endTime,deltaT;
//define n
double n = 3;
//Set the parameters of the light number one
GLfloat Xs = 35.0;
GLfloat Ys = 35.0;
GLfloat Zs = 35.0;
//Shadow color
GLfloat shadowcolor[] = {0.0,0.0,0.0};
//initialize the window and everything to prepare for display
void init_gl() {
//set display color to white
glClearColor(1,1,1,0);
//clear and enable z-buffer
glClear (GL_DEPTH_BUFFER_BIT);
glEnable (GL_DEPTH_TEST);
//clear display window
glClear(GL_COLOR_BUFFER_BIT);
}
//Draw the base of the robot arm
void draw_base(){
glPushMatrix();
//to create the quadric objects
GLUquadric *qobj,*qobjl,*qobju;
qobj = gluNewQuadric();
qobjl = gluNewQuadric();
qobju = gluNewQuadric();
//set the color of the cylinder
glColor3f(1.0,0.0,0.0);
//Re-position the cylinder (x-z plane is the base)
glRotatef(-90,1.0,0.0,0.0);
//Draw the cylinder
gluCylinder(qobj, 30.0, 30.0, 40.0, 40.0, 40.0);
//Draw the upper disk of the base
gluDisk(qobju,0,30,40,40);
glPushMatrix();
//Change the M(lowdisk<updisk)
glTranslatef(0,0,40);
glColor3f(0,0,0);
//Draw the lower disk of the base
gluDisk(qobjl,0,30,40,40);
glPopMatrix();
glPopMatrix();
}
/***********************Texture Work Starts************************************/
//Load the raw file for texture
/* Global Declarations */
#define IW 256 // Image Width
#define IH 256 // Image Height
//3D array to store image data
unsigned char InputImage [IW][IH][4];
// Read an input image from a .raw file with double
void ReadRawImage ( unsigned char Image[][IH][4] )
{
FILE *fp;
int i, j, k;
char* filename;
unsigned char temp;
filename = "floor.raw";
if ((fp = fopen (filename, "rb")) == NULL)
{
printf("Error (ReadImage) : Cannot read the file!!\n");
exit(1);
}
for ( i=0; i<IW; i++)
{
for ( j=0; j<IH; j++)
{
for (k = 0; k < 3; k++) // k = 0 is Red k = 1 is Green K = 2 is Blue
{
fscanf(fp, "%c", &temp);
Image[i][j][k] = (unsigned char) temp;
}
Image[i][j][3] = (unsigned char) 0; // alpha = 0.0
}
}
fclose(fp);
}
/****************************Texture Work Ends***************************************/
/****************************Light and Shadows***************************************/
void lightsrc(){
GLfloat light1PosType [] = {Xs, Ys, Zs, 1.0};
//GLfloat light2PosType [] = {0.0, 100.0, 0.0, 0.0};
glLightfv(GL_LIGHT1, GL_POSITION, light1PosType);
//glEnable(GL_LIGHT1);
//glLightfv(GL_LIGHT2, GL_POSITION, light2PosType);
//glEnable(GL_LIGHT2);
GLfloat whiteColor[] = {1.0, 1.0, 1.0, 1.0};
GLfloat blackColor[] = {0.0, 0.0, 0.0, 1.0};
glLightfv(GL_LIGHT1, GL_AMBIENT, blackColor);
glLightfv(GL_LIGHT1, GL_DIFFUSE, whiteColor);
glLightfv(GL_LIGHT1, GL_SPECULAR, whiteColor);
glEnable(GL_LIGHT1);
glEnable( GL_LIGHTING );
}
/****************************Light and Shadows work ends***************************************/
//Draw the 2x2x2 cube with center (0,1,0)
void cube(){
glPushMatrix();
glTranslatef(0,1,0);
glutSolidCube(2);
glPopMatrix();
}
//Draw the lower arm
void draw_lower_arm(){
glPushMatrix();
glScalef(15.0/2.0,70.0/2.0,15.0/2.0);//scale half is enough (some part is in the negative side)
cube();
glPopMatrix();
}
//Draw the upper arm
void draw_upper_arm(){
glPushMatrix();
glScalef(15.0/2.0,40.0/2.0,15.0/2.0);//scale half is enough (some part is in the negative side)
cube();
glPopMatrix();
}
void drawCoordinates(){
glBegin (GL_LINES);
glColor3f (1,0,0);
glVertex3f (0,0,0);
glVertex3f (600,0,0);
glColor3f (0,1,0);
glVertex3f (0,0,0);
glVertex3f (0,600,0);
glColor3f (0,0,1);
glVertex3f (0,0,0);
glVertex3f (0,0,600);
glEnd();
}
//To draw the whole robot arm
void drawRobot(){
//Robot Drawing Starts
//Rotate the base by theta degrees
glRotatef(theta,0.0,1.0,0.0);
//Draw the base
draw_base();
//M(B<La)
glTranslatef(0.0,40.0,0.0);
//Rotate the lower arm by phi degree
glRotatef(phi,0.0,0.0,1.0);
//change the color of the lower arm
glColor3f(0.0,0.0,1.0);
//Draw the lower arm
draw_lower_arm();
//M(La<Ua)
glTranslatef(0.0,70.0,0.0);
//Rotate the upper arm by psi degree
glRotatef(psi,0.0,0.0,1.0);
//change the color of the upper arm
glColor3f(0.0,1.0,0.0);
//Draw the upper arm
draw_upper_arm();
//Drawing Finish
glutSwapBuffers();
}
void showobj(void) {
//set the projection and perspective parameters/arguments
GLint viewport[4];
glGetIntegerv( GL_VIEWPORT, viewport );
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective( 45, double(viewport[2])/viewport[3], 0.1, 1000 );
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(-200, 300, 200, 0, 0, 0, 0,1,0 );
// get the rotation matrix from the rotation user-interface
glMultMatrixf(gsrc_getmo() );
//Clear the display and ready to show the robot arm
init_gl();
//put the light source
lightsrc();
//Draw coordinates
drawCoordinates();
//give material properties
GLfloat diffuseCoeff[] = {0.2, 0.4, 0.9, 1.0}; // kdR= 0.2, kdG= 0.4, kdB= 0.9
GLfloat specularCoeff[] = {1.0, 1.0, 1.0, 1.0}; //
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, diffuseCoeff);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specularCoeff);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 100.0 ); // ns= 25
//Draw the ground floor
glColor3f(0.4,0.4,0.4);
glPushMatrix();
glRotatef(90,1,0,0);
glRectf(-500,-500,500,500);
glPopMatrix();
int i,j;
GLfloat M[4][4];
for (i=0; i<4; i++){
for (j=0; j<4; j++){
M[i][j] = 0;
}
M[0][0]=M[1][1]=M[2][2]=1;
M[2][3]=-1.0/Zs;
}
//Start drawing shadow
drawRobot(); // draw the objects
glPushMatrix( ); // save state
glMatrixMode(GL_MODELVIEW);
glTranslatef(Xs, Ys, Zs);// Mwc←s
glMultMatrixf(M[4]);// perspective project
glTranslatef(-Xs, -Ys, -Zs);// Ms←wc
glColor3fv (shadowcolor);
//Draw the robot arm
drawRobot();
glPopMatrix(); // restore state
//Shadow drawing ends
glFlush ();
}
//To animate the robot arm
void animate(void)
{
//get the end time
endTime = timeGetTime();
//float angle;
//calculate deltaT
deltaT = (endTime - startTime); //in msecs
//float test;
float deltaTSecs = deltaT/1000.0f; //in secs
//apply moving equation
psi = (90.0) * 0.50 * (1-cos((deltaTSecs/(n+1)) * PI));
glutPostRedisplay ();
}
void main (int argc, char** argv)
{
glutInit(&argc, argv);
//DOUBLE mode better for animation
// Set display mode.
glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGB);
glutInitWindowPosition( 50, 100 ); // Set top-left display-window position.
glutInitWindowSize( 400, 300 ); // Set display-window width and height.
glutCreateWindow( "Robot arm : my first self-learning opengl program" ); // Create display window.
// Register mouse-click and mouse-move glut callback functions
// for the rotation user-interface.
//Allow user to drag the mouse and view the object
glutMouseFunc( gsrc_mousebutton );
glutMotionFunc( gsrc_mousemove );
//record the starting time
startTime = timeGetTime();
// Display everything in showobj function
glutDisplayFunc(showobj);
//Perform background processing tasks or continuous animation
glutIdleFunc(animate);
glutMainLoop();
}
your screen flashes because you are calling glutSwapBuffers() in drawRobot(). That makes your screen repaint two times, once when you draw the robot, and once more when you draw the shadow. Also, you are missing glPushMatrix() at the beginning of drawRobot() and glPopMatrix() at the end. You need to put it there, otherwise it will affect rendering afterwards (the shadow will move with the upper link of the arm).
Then, you specify the shadow matrix wrong. Let's try this:
int i,j;
GLfloat M[4][4];
for (i=0; i<4; i++){
for (j=0; j<4; j++){
M[i][j] = 0;
}
}
M[0][0]=M[1][1]=M[2][2]=1;
M[2][3]=-1.0/Zs;
drawRobot(); // draw the objects
//Start drawing shadow
glEnable(GL_CULL_FACE);
glDisable(GL_LIGHTING); // want constant-color shadow
glPushMatrix( ); // save state
glMatrixMode(GL_MODELVIEW);
glTranslatef(Xs, Ys, Zs);// Mwc←s
glMultMatrixf(&M[0][0]);// perspective project
glTranslatef(-Xs, -Ys, -Zs);// Ms←wc
glColor3fv (shadowcolor);
//Draw the robot arm
drawRobot();
glPopMatrix(); // restore state
glDisable(GL_CULL_FACE);
glEnable(GL_LIGHTING); // enable again ...
//Shadow drawing ends
Also, you can see i've added GL_CULL_FACE arround the shadow, it is to avoid depth fighting. This more or less fixes it technically.
But still - the shadow position is calculated incorrectly. Let's try looking at projection shadows.
So first, we need to have position for the ground plane and for the light:
float g[] = {0, 1, 0, 0}; // ground plane
float l[] = {20, 300, 50, 1}; // light position and "1"
That is a plane equation and a homogenous light position (normal 3D position, padded with a "1"). Then you throw away your shadow matrix setup (glTranslatef(), glMultMatrixf() and glTranslatef()) and call myShadowMatrix(g, l) instead, so it becomes:
glPushMatrix( ); // save state
glMatrixMode(GL_MODELVIEW);
float g[] = {0, 1, 0, 0}; // ground plane
float l[] = {20, 300, 50, 1}; // light position and "1"
myShadowMatrix(g, l);
glColor3fv (shadowcolor);
//Draw the robot arm
drawRobot();
glPopMatrix(); // restore state
And that mostly does work. There is still a lot of z-fighting going on, and the shadow has four different colors. As for the colors, stop calling glColor3f() in drawRobot(), as for the z-fighting, use this:
glPolygonOffset(-1, -1);
glEnable(GL_POLYGON_OFFSET_FILL);
// before
// draw shadow
glDisable(GL_POLYGON_OFFSET_FILL);
// afterwards
And that makes one nice planar shadows demo :). Cheers ...
sw.
I'm reading the sample code for the bezier curve on the online version of opengl's tutorial.
I'm curious about how is resize being handled in the example cause I figure I might use it on my own version of this program , I placed my questions on its comments:
void reshape(int w, int h)
{
glViewport(0, 0, (GLsizei) w, (GLsizei) h); // what's GLsizei? Why is it called inside glViewPort?
glMatrixMode(GL_PROJECTION); // is it necessary to reset the projection matrix?
glLoadIdentity();
if (w <= h) // is this calculation universal, could I use it on another program?
glOrtho(-5.0, 5.0, -5.0*(GLfloat)h/(GLfloat)w,
5.0*(GLfloat)h/(GLfloat)w, -5.0, 5.0);
else
glOrtho(-5.0*(GLfloat)w/(GLfloat)h,
5.0*(GLfloat)w/(GLfloat)h, -5.0, 5.0, -5.0, 5.0);
glMatrixMode(GL_MODELVIEW); // why do I set to GL_MODELVIEW at the end?
glLoadIdentity(); // why does it get a reset?
}
Full code:
#include <stdlib.h>
#include <GL/glut.h>
GLfloat ctrlpoints[4][3] = {
{ -4.0, -4.0, 0.0}, { -2.0, 4.0, 0.0},
{2.0, -4.0, 0.0}, {4.0, 4.0, 0.0}};
void init(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_FLAT);
glMap1f(GL_MAP1_VERTEX_3, 0.0, 1.0, 3, 4, &ctrlpoints[0][0]);
glEnable(GL_MAP1_VERTEX_3);
}
void display(void)
{
int i;
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_LINE_STRIP);
for (i = 0; i <= 30; i++)
glEvalCoord1f((GLfloat) i/30.0);
glEnd();
/* The following code displays the control points as dots. */
glPointSize(5.0);
glColor3f(1.0, 1.0, 0.0);
glBegin(GL_POINTS);
for (i = 0; i < 4; i++)
glVertex3fv(&ctrlpoints[i][0]);
glEnd();
glFlush();
}
void reshape(int w, int h)
{
glViewport(0, 0, (GLsizei) w, (GLsizei) h); // what's GLsizei? Why is it called inside glViewPort?
glMatrixMode(GL_PROJECTION); // is it necessary to reset the projection matrix?
glLoadIdentity();
if (w <= h) // is this calculation universal, could I use it on another program?
glOrtho(-5.0, 5.0, -5.0*(GLfloat)h/(GLfloat)w,
5.0*(GLfloat)h/(GLfloat)w, -5.0, 5.0);
else
glOrtho(-5.0*(GLfloat)w/(GLfloat)h,
5.0*(GLfloat)w/(GLfloat)h, -5.0, 5.0, -5.0, 5.0);
glMatrixMode(GL_MODELVIEW); // why do I set to GL_MODELVIEW at the end?
glLoadIdentity(); // why does it get a reset?
}
void keyboard(unsigned char key, int x, int y)
{
switch (key) {
case 27:
exit(0);
break;
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow (argv[0]);
init ();
glutDisplayFunc(display);
glutReshapeFunc(reshape); // el reshape funciona correctamente
glutKeyboardFunc (keyboard);
glutMainLoop();
return 0;
}
GLsizei is a type, not a function. Therefore, it's not being called; its being casted; it's converting an int into a GLsizei. It's basically an int, but it makes it clear that you're using it for a size (I think). (I'm a Python programmer, so this is a guess)
glMatrixMode(...);
This does not reset the matrix, unless it is followed by a glLoadIdentity() call. Instead, it sets the current target of OpenGL's matrix operations to the matrix specified. This way, OpenGL knows what matrix you're trying to affect.
I've seen that calcuation before in the OpenGL superbible (or at least something like it); why don't you talk yourself through it and see what it's deciding and why? (Hint (I think): it's trying to keep the viewport square to avoid stretching)
At the end, it sets it back to GL_MODELVIEW since that matrix handles transformations, like translation and rotation, which are used to position vertices onscreen. It should be reset every frame so that your code can assume that the coordinate plane is currently at (0,0); that simplifies calculations about where to translate to.
Also note that reshape is not called by OpenGL, but by GLUT. OpenGL is platform-independent and does not handle windowing; this is why you need GLUT.
If you're new to OpenGL, you should work through it from the beginning - later tutorials will assume this sort of knowledge.