Animation in Open GL - opengl
I never got the concept down on how to get an animation working in OpenGL. I was working on his project trying to get it to work but never got the skier to move. Trying to figure out how to get this fixed.
#include "../shared/gltools.h" // OpenGL toolkit
#define PI 3.14159265
float a = -5;//maybe
float b = 29;
float c = 27;
float d = 28.25;
float e = 28.5;
bool lookUp;
bool setback;
bool lookDown;
bool lookLeft;
bool lookRight;
bool walkForward;
bool walkBackward;
bool strafeLeft;
bool strafeRight;
float xTranslation;
float yTranslation;
float zTranslation;
float yRotationAngle;
float zRotationAngle;
float xRotationAngle;
int mouseLastx;
int mouseLasty;
float sunRotationAngle=0;
float sunRadius = 150.0;
float day=0;
float dusk=1;
// Light values and coordinates
GLfloat lightPos[] = { 0.0f, 30.0f, 0.0f, 1.0f };
GLfloat lightPos2[] = { 0.0f, 0.0f, 40.0f, 1.0f };
GLfloat specular[] = { 1.0f, 1.0f, 1.0f, 1.0f};
GLfloat specular2[] = { 0.0f, 1.0f, 0.0f, 1.0f};
GLfloat diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f};
GLfloat diffuse2[] = { 0.0f, 0.3f, 0.0f, 1.0f};
GLloat specref[] = { 1.0f, 1.0f, 1.0f, 1.0f };
GLfloat ambientLight[] = { 0.5f, 0.5f, 0.5f, 1.0f};
GLfloat spotDir[] = { 0.0f, 0.0f, -1.0f };
void mouseMovement(int x, int y)
{
int mouseDiffx=x-mouseLastx;
int mouseDiffy=y-mouseLasty;
mouseLastx=x;
mouseLasty=y; //set lasty to the current y position
xRotationAngle += (GLfloat) mouseDiffy;
yRotationAngle += (GLfloat) mouseDiffx;
if (xRotationAngle>=90)
xRotationAngle=90;
if (xRotationAngle<=-90)
xRotationAngle=-90;
//cout << "x:" << x << "y:" << y << endl;
}
void drawcabin()
{
glColor3ub(0, 0, 0);
glBegin(GL_TRIANGLES);
//glTranslatef(0,-5,0); // move view left
//glNormal3f(-3,0.7,-1.7);
//glutSolidCube(5.0f);
glNormal3d(0,0.7,0.7);
glVertex3d(0,6,0);
glVertex3d(-3,3.5,-2);
glVertex3d(2,3.5,-2);
glNormal3d(2,-1,1);
glVertex3d(0,6,0);
glVertex3d(-3,3.5,-2);
glVertex3d(2,3.5,-2);
glTranslatef(0,-5,0); // move view left
glNormal3d(-3,0.7,-1.7);
glEnd();
glColor3ub(185, 0, 0);
glutSolidCube(5.0f);
}
void drawskislope()
{
glColor3ub(0, 0, 0);
glBegin(GL_QUADS);
glTranslatef(0,-5,90); // move view left
glColor3ub(185, 122, 87);
glNormal3d(0,5,1);
glVertex3d(10,0,5);
glVertex3d(10,.5,5);
glVertex3d(15,.5,5);
glVertex3d(15,0,5);//small square
glColor3ub(201, 192, 187);
glVertex3d(11.5,.5,5);
glVertex3d(13.5,.5,5);
glVertex3d(13.5,-10,5);
glVertex3d(11.5,-10,5);
//slope start
glTranslatef(0,-5,0); // move view left
// glNormal3d(-3,0.7,-1.7);
glEnd();
}
void drawskier()
{
float a = -5;//maybe
float b = 29;
float c = 27;
float d = 28.25;
float e = 28.5;
glBegin(GL_QUADS);
glTranslatef(0,-5,0); // move view
glColor3ub(185, 122, 87);
glNormal3d(0,5,1);
//Do While loop
// do
// {
// to move skier do a loop and update a in the translate
glTranslatef(0,a,0); // move view
glVertex3d(c,0,5);//10
glVertex3d(c,.1,5);//10
glVertex3d(b,.1,5);//15
glVertex3d(b,0,5);//skis on skier
glNormal3d(0,5,1);
glVertex3d(d,0,5);
glVertex3d(d,1.35,5);
glVertex3d(e,1.35,5);
glVertex3d(e,0,5);//body on skier
glutSwapBuffers;
// }while(b>15); //try to animate
glEnd();
glFlush();
b=b-1;
c=c-1;
d=d-1;
e=e-1;
glutPostRedisplay();
glTranslatef(30,3,0); // move view left
glColor3ub(168, 220, 109);
glutSolidSphere(.5,7,8); //sphere-head
glPushMatrix();
glTranslatef(3.5,-100,2);
glutSolidSphere(25,15,15); //sphere
glPopMatrix();
}
void updatescene()
{
}
///////////////////////////////////////////////////////////
// Called to draw scene
void RenderScene(void)
{
GLUquadricObj *pObj; // Quadric Object
pObj = gluNewQuadric();
gluQuadricNormals(pObj, GLU_SMOOTH);
GLfloat horizontalMovement=1;
GLfloat verticalMovement=0;
horizontalMovement=cos(xRotationAngle*PI/180);
verticalMovement=-sin(xRotationAngle*PI/180);
// Reset Model view matrix stack
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
horizontalMovement=cos(xRotationAngle*PI/180);
verticalMovement=-sin(xRotationAngle*PI/180);
if (lookDown)
{
xRotationAngle+=1;
if (xRotationAngle>=90)
xRotationAngle=90;
}
if (lookUp)
{
xRotationAngle-=1;
if (xRotationAngle<=-90)
xRotationAngle=-90;
}
if (lookRight)
{
yRotationAngle+=1;
if (yRotationAngle>=360)
yRotationAngle=0;
}
if (lookLeft)
{
yRotationAngle-=1;
if (yRotationAngle<=-360)
yRotationAngle=0;
}
if (walkForward)
{
zTranslation+=cos(yRotationAngle*PI/180)*horizontalMovement;
xTranslation-=sin(yRotationAngle*PI/180)*horizontalMovement;
yTranslation-=verticalMovement;
}
if (walkBackward)
{
zTranslation-=cos(yRotationAngle*PI/180)*horizontalMovement;
xTranslation+=sin(yRotationAngle*PI/180)*horizontalMovement;
yTranslation+=verticalMovement;
}
if (strafeRight)
{
zTranslation+=cos((yRotationAngle+90)*PI/180);
xTranslation-=sin((yRotationAngle+90)*PI/180);
}
if (strafeLeft)
{
zTranslation-=cos((yRotationAngle+90)*PI/180);
xTranslation+=sin((yRotationAngle+90)*PI/180);
}
if (setback)
{
zTranslation=0;
xTranslation=0;
yTranslation=0;
}
// Reset Model view matrix stack
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(xRotationAngle,1,0,0);
glRotatef(zRotationAngle,0,0,1);
glRotatef(yRotationAngle,0,1,0);
glTranslatef(xTranslation,yTranslation,zTranslation);
//glRotatef(-15,1,0,0);
//glRotatef(90,0,1,0);
glTranslatef(0,-0.50,-10);
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
sunRotationAngle++;
// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3d(0,0,0);
glLineWidth(2);
//snow
glColor3ub(255, 255, 255);
glBegin(GL_QUADS);
glNormal3f(0,1,0);
for (int i=-100;i<=200;i+=10) //x
for (int j=-100;j<=200;j+=10)//z
{
float y1=(-j)*.25;
float y2=(-j+10)*.25;
glVertex3d(i+10,y2,-100);
glVertex3d(i,y2,-100);
glVertex3d(i,y1,-100);
glVertex3d(i+10,y1,-100);
}
glEnd();
glPushMatrix();
glTranslatef(-10,14,-50);
drawcabin();
drawskislope();
drawskier();
glPopMatrix();
// Flush drawing commands
glutSwapBuffers();
glutPostRedisplay();
//GLfloat horizontalMovement=1;
// GLfloat verticalMovement=0;
}
void TimerFunction(int value)
{
// Redraw the scene with new coordinates
glutPostRedisplay();
updatescene();
glutTimerFunc(16,TimerFunction, 1);
}
///////////////////////////////////////////////////////////
// Setup the rendering context
void SetupRC(void)
{
lookUp=false;
lookDown=false;
lookLeft=false;
lookRight=false;
walkForward=false;
walkBackward=false;
strafeLeft=false;
strafeRight=false;
yRotationAngle=0;
xRotationAngle=0;
zRotationAngle=0;
xTranslation=0;
yTranslation=0;
zTranslation=0;
// White background
glClearColor(0.5f,0.95f, 1.0f, 1.0f );
// Set drawing color to green
glColor3f(0.0f, 1.0f, 0.0f);
// Set color shading model to flat
glShadeModel(GL_SMOOTH);
// Clock wise wound polygons are front facing, this is reversed
// because we are using triangle fans
glFrontFace(GL_CCW);
glEnable (GL_DEPTH_TEST);
}
void ChangeSize(int w, int h)
{
//GLfloat nRange = 100.0f;
// Prevent a divide by zero
if(h == 0)
h = 1;
// Set Viewport to window dimensions
glViewport(0, 0, w, h);
// Reset projection matrix stack
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Establish clipping volume (left, right, bottom, top, near, far)
GLfloat fAspect;
fAspect = (GLfloat)w / (GLfloat)h;
//glOrtho(-10,10,-10,10,0,1000);
gluPerspective(45,fAspect,0.1,1000);
// Reset Model view matrix stack
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
// Respond to arrow keys by moving the camera frame of reference
void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
lookUp=true;
if(key == GLUT_KEY_DOWN)
lookDown=true;
if(key == GLUT_KEY_LEFT)
lookLeft=true;
if(key == GLUT_KEY_RIGHT)
lookRight=true;
// Refresh the Window
glutPostRedisplay();
}
void SpecialKeysUp(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
lookUp=false;
if(key == GLUT_KEY_DOWN)
lookDown=false;
if(key == GLUT_KEY_LEFT)
lookLeft=false;
if(key == GLUT_KEY_RIGHT)
lookRight=false;
// Refresh the Window
glutPostRedisplay();
}
void keyboardFunc(unsigned char key, int x, int y)
{
switch(key)
{
case 'w':
walkForward=true;
break;
case 's':
walkBackward=true;
break;
case 'a':
strafeLeft=true;
break;
case 'd':
strafeRight=true;
break;
case 'r':
setback=true;
break;
default:
break;
}
}
void keyboardUpFunc(unsigned char key, int x, int y)
{
switch(key)
{
case 'w':
walkForward=false;
break;
case 's':
walkBackward=false;
break;
case 'a':
strafeLeft=false;
break;
case 'd':
strafeRight=false;
break;
default:
break;
}
}
///////////////////////////////////////////////////////////
// Main program entry point
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(500,500);
glutCreateWindow("Assignment 2");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
glutSpecialFunc(SpecialKeys);
glutSpecialUpFunc(SpecialKeysUp);
glutKeyboardUpFunc(keyboardUpFunc);
glutKeyboardFunc(keyboardFunc);
glutPassiveMotionFunc(mouseMovement);
SetupRC();
glutMainLoop();
return 0;
}
My general approach is to use a glutTimerFunc() callback to post a redisplay event every 16 milliseconds or so (~60 FPS).
Then in the glutDisplayFunc() callback you can grab the new GLUT_ELAPSED_TIME to calculate a delta-time (dt) from the last frame.
With dt in hand you can update any number of variables such as angles or translation offsets. You'll want to use dt instead of fixed increment values to decouple your animation speed from your framerate.
Then back in the glutDisplayFunc() callback you draw a new frame using the updated state variables.
This is an example that uses the method above to rotate a square at about 30 degrees per second:
#include <GL/glut.h>
float angle = 0;
void update( const double dt )
{
// in degrees per second
const float SPEED = 30.0f;
// update angle
angle += ( SPEED * dt );
}
void display()
{
// GLUT_ELAPSED_TIME is in milliseconds
static int prvMs = glutGet( GLUT_ELAPSED_TIME );
const int curMs = glutGet( GLUT_ELAPSED_TIME );
// dt is in seconds
const double dt = ( curMs - prvMs ) / 1000.0;
prvMs = curMs;
// update world state
update( dt );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
// reset projection/modelview matrices each frame;
// this makes sure we have a known-good matrix
// stack each time through display()
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho( -2, 2, -2, 2, -1, 1 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
// draw rotated square
glRotatef( angle, 0, 0, 1 );
glBegin( GL_QUADS );
glColor3ub( 255, 0, 0 );
glVertex2i( -1, -1 );
glVertex2i( 1, -1 );
glVertex2i( 1, 1 );
glVertex2i( -1, 1 );
glEnd();
glutSwapBuffers();
}
void timer( int value )
{
glutPostRedisplay();
glutTimerFunc( 16, timer, 0 );
}
int main( int argc, char **argv )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE );
glutInitWindowSize( 600, 600 );
glutCreateWindow( "GLUT" );
glutDisplayFunc( display );
glutTimerFunc( 0, timer, 0 );
glutMainLoop();
return 0;
}
Related
Position the square on the left after it reaches the top
#include <stdio.h> // this library is for standard input and output #include "glut.h"// this library is for glut the OpenGL Utility Toolkit #include <math.h> float squareX = 0.0f; float squareY = -0.3f; float squareZ = 0.0f; static int flag = 1; void drawShape(void) { glTranslatef(squareX, squareY, squareZ); glBegin(GL_POLYGON); glColor3f(1.0, 0.0, 0.0); glVertex2f(162, 50); glVertex2f(162, 10); glVertex2f(220, 10); glVertex2f(220, 50); glVertex2f(162, 50); glEnd(); } void initRendering() { glEnable(GL_DEPTH_TEST); } // called when the window is resized void handleResize(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0f, (float)w, 0.0f, (float)h, -1.0f, 1.0f); } void drawScene() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); drawShape(); glutSwapBuffers(); } // make the square go up void update(int value) { if (flag) { squareY += 1.0f; if (squareY > 400.0) { flag = 0; } } glutPostRedisplay(); glutTimerFunc(25, update, 0); } // make the square go right /* void update(int value) { if (flag) { squareX += 1.0f; if (squareX > 400.0) { flag = 0; } } glutPostRedisplay(); glutTimerFunc(25, update, 0); } */ int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(400, 400); glutCreateWindow("Moving Square"); initRendering(); glutDisplayFunc(drawScene); glutReshapeFunc(handleResize); glutTimerFunc(25, update, 0); glutMainLoop(); return(0); } I have uploaded this code before but this time I made the square go all the way up. The code just moves the square up, but I don't know how to position it on the left once it reaches the top, so then I can make it move to the right. I have uploaded a demonstration on how I want it to look below. Preview: What I want it to do next:
I recommend to initialize the variables squareX, squareY and squareZ with the start position of the rectangle: float squareX = 162.0f; float squareY = 0.0f; float squareZ = 0.0f; Do not draw a rectangle specific position, but draw a rectangle on the position (0,0) with a length (width, height). Let the model matrix (set by glTranslatef), do the job of the positioning: void drawShape(void) { float width = 58.0f; float height = 40.0f; glTranslatef(squareX, squareY, squareZ); glBegin(GL_POLYGON); glColor3f(1.0, 0.0, 0.0); glVertex2f(0, 0); glVertex2f(width, 0); glVertex2f(width, height); glVertex2f(0, height); glVertex2f(0, 0); glEnd(); } Use a variable state, which has stated the direction of the current movement: int state = 1; // 0: stop; 1: move up; 2: move right If the rectangle a certain position has reached, then the state has to be changed and a the new start position can be set. At the final position, the rectangle can stop or the process can even be restarted: void update(int value) { if (state == 1) // 1 : move up { squareY += 1.0f; if (squareY > 400.0) { state = 2; squareX = 0.0f; squareY = 180.0f; } } else if (state == 2) // 2 : move right { squareX += 1.0f; if (squareX > 400.0) { state = 0; // restart //state = 1; //squareX = 162.0f; //squareY = 0.0f; } } glutPostRedisplay(); glutTimerFunc(25, update, 0); }
Trouble drawing Sierpinski with OpenGL
I am trying to generate the Sierpinski Gasket using a function that draws dot patterns and will generate the gasket. But when I compile and run the program it displays nothing but black screen. What's causing the problem? Here is my code: #include <Windows.h> #include <gl/GL.h> #include <glut.h> void myInit(void) { glClearColor(1.0, 1.0, 1.0, 0.0); glColor3f(0.0f, 0.0f, 0.0f); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, 640.0, 0.0, 480.0); } class GLintPoint { public: GLint x, y; }; int random(int m) { return rand() % m; } void drawDot(GLint x, GLint y) { glBegin(GL_POINTS); glVertex2i(x, y); glEnd(); } void Sierpinski(void) { GLintPoint T[3] = {{ 10, 10 }, {300, 30}, {200, 300}}; int index = random(3); GLintPoint point = T[index]; for (int i = 0; i < 1000; i++) { index = random(3); point.x = (point.x + T[index].x) / 2; point.y = (point.y + T[index].y) / 2; drawDot(point.x, point.y); } glFlush(); } void main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(640, 480); glutInitWindowPosition(100, 150); glutCreateWindow("Sierpinski Gasket"); glutDisplayFunc(drawDot); myInit(); glutMainLoop(); }
If you want to draw black dots on a white background, then you have to clear glClear the background: glClear( GL_COLOR_BUFFER_BIT ); Note, glClearColor sets the color which is used to clear the view port, but doesn't clear anything itself. Your code should look somehow like this: void drawDot(GLint x, GLint y) { glVertex2i(x, y); } void Sierpinski(void) { GLintPoint T[3] = {{ 10, 10 }, {300, 30}, {200, 300}}; int index = random(3); GLintPoint point = T[index]; glClearColor(1.0, 1.0, 1.0, 1.0); // set up white clear color glClear( GL_COLOR_BUFFER_BIT ); // clear the back ground (white) glMatrixMode( GL_MODELVIEW ); glPushMatrix(); // setup model matrix glScalef( 1.5f, 1.5f, 1.0f ); // scale the point distribution glColor3f( 0.0f, 0.0f, 0.0f ); // set black draw color glPointSize( 5.0f ); // set the size of the points glBegin(GL_POINTS); for (int i = 0; i < 1000; i++) { index = random(3); point.x = (point.x + T[index].x) / 2; point.y = (point.y + T[index].y) / 2; drawDot(point.x, point.y); } glEnd(); glPopMatrix(); // reset model matrix glFlush(); }
Changing the view to object in OpenGL
I'm trying to play around with OpenGL and this is my very first code. How can I change to different view to 2 object drawn on the screen? Is there anyway to do this manually, in stead of using function gluPerspective()? I tried glRotatef(60, 0.0, 0.0, 5.0) but there is nothing happen. Cos I want to see other faces of the Pyramid and also different view of the rotating sphere. Also I want to set different colours to different objects that I draw on the screen, how can I do that? The code to set colour for each object, which is glColor3f, I put it in between glPushMatrix() and glPopMatrix(), also I always include the line glLoadIdentity() before starting draw objects on screen. As far as I know, this line will reset the settings of the previous objects and allows me to set new properties for new object. Then why when I press button D, the sphere is blue when it supposes to be in white? Here is my full code: #include <windows.h> #include <GL/glew.h> #include <GL/gl.h> #include <math.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #define X .525731112119133606 #define Z .850650808352039932 #define Y 0.0 #define PI 3.1415926535898 #define CIRCLE_STEP 5000 using namespace std; // Open an OpenGL window GLFWwindow* window; int keyboard = 0, itr; bool big_Sphere = true, sphereWithNormalV = false, animation = false; GLdouble angle = 0; /****Step 1: define vertices in (x, y, z) form****/ // Coordinates to draw a Icosahedron GLfloat icoVertices[12][3] = { {-X, Y, Z}, {X, Y, Z}, {-X, Y, -Z}, {X, Y, -Z}, {Y, Z, X}, {Y, Z, -X}, {Y, -Z, X}, {Y, -Z, -X}, {Z, X, Y}, {-Z, X, Y}, {Z, -X, Y}, {-Z, -X, Y} }; // Coordinates to draw a Pyramid GLfloat pyVertices[4][3] = { {0.0f, 1.0f, 0.0f}, {1.0f, 0.0f, 0.0f}, {-1.0f, 0.0f, 0.0f}, {0.0f, 0.0f, -1.0f} }; static GLuint icoIndices[20][3] = { {0,4,1}, {0,9,4}, {9,5,4}, {4,5,8}, {4,8,1}, {8,10,1}, {8,3,10}, {5,3,8}, {5,2,3}, {2,7,3}, {7,10,3}, {7,6,10}, {7,11,6}, {11,0,6}, {0,1,6}, {6,1,10}, {9,0,11}, {9,11,2}, {9,2,5}, {7,2,11} }; static GLuint pyIndices[4][3] = { {0,1,2}, {0,1,3}, {0,2,3}, {1,2,3} }; /************************/ void normalize3f(float v[3]) { GLfloat d = sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]); if (d == 0.0) { fprintf(stderr, "zero length vector"); return; } v[0] /= d; v[1] /= d; v[2] /= d; } void sphereNormalV(GLfloat p1[3], GLfloat p2[3], GLfloat p3[3]) { glBegin(GL_LINES); glVertex3f(p1[0] *1.5,p1[1] *1.5, p1[2] *1.5); glVertex3fv(p1); glEnd(); glBegin(GL_LINES); glVertex3f(p2[0] *1.1,p2[1] *1.1, p2[2] *1.1); glVertex3fv(p2); glEnd(); glBegin(GL_LINES); glVertex3f(p3[0] *1.1,p3[1] *1.1, p3[2] *1.1); glVertex3fv(p3); glEnd(); } void drawtriangle(float *v1, float *v2, float *v3) { glBegin(GL_LINE_LOOP); //glNormal3fv(v1); glVertex3fv(v1); //glNormal3fv(v2); glVertex3fv(v2); //glNormal3fv(v3); glVertex3fv(v3); glEnd(); } void subdivide(GLfloat *v1, GLfloat *v2, GLfloat *v3, long depth) { GLfloat v12[3], v23[3], v31[3]; GLint i; if (depth == 0){ drawtriangle(v1, v2, v3); if (sphereWithNormalV == true){ sphereNormalV(v1, v2, v3); } return; } for (i = 0; i < 3; i++) { v12[i] = v1[i]+v2[i]; v23[i] = v2[i]+v3[i]; v31[i] = v3[i]+v1[i]; } normalize3f(v12); normalize3f(v23); normalize3f(v31); subdivide(v1, v12, v31, depth-1); subdivide(v2, v23, v12, depth-1); subdivide(v3, v31, v23, depth-1); subdivide(v12, v23, v31, depth-1); } void drawSphere(GLfloat x, GLfloat y, GLfloat z){ glLoadIdentity(); glPushMatrix(); if (big_Sphere == true){ glScaled(0.4, 0.55, 0.4); }else{ glScaled(0.13, 0.18, 0.13); } if (animation){ glTranslatef(x, y, z); } glBegin(GL_LINE_LOOP); for (int i = 0; i < 20; i++) { subdivide(&icoVertices[icoIndices[i][0]][0], &icoVertices[icoIndices[i][1]][0], &icoVertices[icoIndices[i][2]][0], 3); } glEnd(); glPopMatrix(); } void drawPyramid(){//(GLfloat x, GLfloat y, GLfloat z){ glLoadIdentity(); glPushMatrix(); glScaled(0.13, 0.18, 0.13); glBegin(GL_LINE_LOOP); for (int i = 0; i < 4; i++){ glColor3f(1.0f, 0.0f, 0.0f); glVertex3fv(pyVertices[pyIndices[i][0]]); glColor3f(0.0f, 1.0f, 0.0f); glVertex3fv(pyVertices[pyIndices[i][1]]); glColor3f(0.0f, 0.0f, 1.0f); glVertex3fv(pyVertices[pyIndices[i][2]]); } glEnd(); glPopMatrix(); } int getKeyPressed(){ if (glfwGetKey(window, GLFW_KEY_A)){ keyboard = GLFW_KEY_A; } if (glfwGetKey(window, GLFW_KEY_B)){ keyboard = GLFW_KEY_B; } if (glfwGetKey(window, GLFW_KEY_C)){ keyboard = GLFW_KEY_A; } if (glfwGetKey(window, GLFW_KEY_D)){ keyboard = GLFW_KEY_D; } if (glfwGetKey(window, GLFW_KEY_E)){ keyboard = GLFW_KEY_E; } return keyboard; } void controlSphere(bool _big_Sphere, bool _sphereNormalV, bool _animation){ big_Sphere = _big_Sphere; sphereWithNormalV = _sphereNormalV; animation = _animation; } void gluPerspective(double fovy,double aspect, double zNear, double zFar) { // Start in projection mode. glMatrixMode(GL_PROJECTION); glLoadIdentity(); double xmin, xmax, ymin, ymax; ymax = zNear * tan(fovy * PI / 360.0); ymin = -ymax; xmin = ymin * aspect; xmax = ymax * aspect; glFrustum(xmin, xmax, ymin, ymax, zNear, zFar); } int main( void ) { if (!glfwInit()){ fprintf(stderr, "Failed to initialize GLFW.\n"); return -1; } // Create a windowed mode window and its OpenGL context window = glfwCreateWindow(1100, 800, "Hello World", NULL, NULL); if (window == NULL) { fprintf(stderr, "glfw failed to create window.\n"); //glfwTerminate(); return -1; } // Make the window's context current glfwMakeContextCurrent(window); glewInit(); if (glewInit() != GLEW_OK){ fprintf(stderr, "Failed to initialize GLEW: %s.\n", glewGetErrorString(glewInit())); return -1; } // 4x anti aliasing glfwWindowHint(GLFW_SAMPLES, 4); /**Step 3: Main loop for OpenGL draw the shape** /* Main loop */ int i = 0; GLfloat pos_X, pos_Y; glRotatef(60, 0.0f, 0.3f, 0.4f); do{ //glMatrixMode(GL_MODELVIEW); glClear(GL_COLOR_BUFFER_BIT); switch(getKeyPressed()){ case 65: controlSphere(true, false, false); drawSphere(0, 0, 0); break; case 66: controlSphere(true, true, false); drawSphere(0, 0, 0); break; case 67: // drawPyramid(); break; case 68: // drawing a Sphere moving in a circular path controlSphere(false, false, true); angle = 2*PI*i/CIRCLE_STEP; pos_X = cos(angle) * 4.5; pos_Y = sin(angle) * 4.5; drawSphere(pos_X, pos_Y, 0); i += 1; angle += 1; if (angle >= 360){ angle = 0; } // drawing a Pyramid rotate around its y axis drawPyramid(); break; default: controlSphere(true, false, false); drawSphere(0, 0, 0); break; } Sleep(1); // Swap front and back rendering buffers glfwSwapBuffers(window); //Poll for and process events glfwPollEvents(); } // check if the ESC key was pressed or the window was closed while(glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window) == 0); /***********************************************/ // Close window and terminate GLFW glfwDestroyWindow(window); glfwTerminate(); // Exit program exit( EXIT_SUCCESS ); }
Is there anyway to do this manually, in stead of using function gluPerspective()? I don't really understand this question. But if you want to set multiples objects (that have the same parameters) with different transformations, scale, rotation and/or translation, you need to push this to the stack and then draw the desired object. A good starting point can be found here: http://www.songho.ca/opengl/gl_transform.html Also I want to set different colours to different objects that I draw on the screen, how can I do that? Your sphere is blue because the last call for glColor3f() was in drawPyramid(). You can change the color of your ball by just calling glColor3f (1.0f, 1.0f, 1.0f); in the beginning of its draw function: void drawSphere (GLfloat x, GLfloat y, GLfloat z) { glColor3f (1.0f, 1.0f, 1.0f); ... } A really great site to learn OpenGL from the old pipeline (what you just implemented) to the new (GLSL) is http://www.lighthouse3d.com/tutorials/.
You are looking for Multiple viewports which allows the to split the screen. In your case two different viewports two different cameras(one for each) will be enough. Check this post.
OpenGL with two loops, one loop is not working
My OpenGL program is not working properly. Inside the drawScene() function I created two loops. One loop for GL_LINES another loop for GL_POINTS. The GL_LINES loop works fine but GL_POINTS loop doesn't work. Any help appreciated. #include <iostream> #include <stdlib.h> #include <GL/glut.h> #include <math.h> #define PI 3.14159265 using namespace std; //Called when a key is pressed void handleKeypress(unsigned char key, int x, int y) { switch (key) { case 27: //Escape key exit(0); } } //Initializes 3D rendering void initRendering() { glEnable(GL_DEPTH_TEST); glEnable(GL_COLOR_MATERIAL); //Enable color glClearColor(0.7f, 0.9f, 1.0f, 1.0f); //Change the background to sky blue } //Called when the window is resized void handleResize(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0, (double)w / (double)h, 1.0, 200.0); } float _angle = 0.0f; float _cameraAngle = 0.0f; float x = -1.5; float y = -0.5; //Draws the 3D scene void drawScene() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glLineWidth (9.0f); glBegin(GL_LINES); glColor3f(1.0f, 0.0f, 0.0f); double r = 0.5; for(int c = 0;c<=360;c++){ double y = r*cos (c*PI/180); double x = r*sin (c*PI/180); glVertex3d(x,y,-5.0); glVertex3d(0.0,0.0,-5.0); } glEnd(); glPointSize (7.0f); glBegin(GL_POINTS); glColor3f(0.0f, 1.0f, 0.0f); double r = 1.0; for(int c = 0;c<=360;c++){ double y = r*cos (c*PI/180); double x = r*sin (c*PI/180); glVertex3d(x,y,-5.0); //glVertex3d(0.0,0.0,-5.0); } glEnd(); glutSwapBuffers(); //glutPostRedisplay(); } void update(int value) { _angle += 2.0f; if (_angle > 360) { _angle -= 360; } glutPostRedisplay(); glutTimerFunc(60, update, 0); } int main(int argc, char** argv) { //Initialize GLUT glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(400, 400); //Create the window glutCreateWindow("two circle"); initRendering(); //Set handler functions glutDisplayFunc(drawScene); glutKeyboardFunc(handleKeypress); glutReshapeFunc(handleResize); glutTimerFunc(25, update, 0); //Add a timer glutMainLoop(); return 0; }
Right now, you're declaring the variable r in two places: where you set double r = 0.5; and at double r = 1.0; Try changing it to: double r = 0.5; //First loop r = 1.0; //Second loop
How to make a square that changes colors when the user presses some keys? [closed]
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 9 years ago. I wrote a code, but I don't know where it went wrong. Can somebody help me with that? I wrote some comments in my code. If someone could help me I'd be very glad. Because I can't find the error by myself. :( #include <windows.h> #include <gl/glut.h> // Function callback that is called to draw void Desenha(void) { glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Clean the window glClear(GL_COLOR_BUFFER_BIT); // Shows that the color is red // R G B glColor3f(1.0f, 0.0f, 0.0f); // Draw a square glBegin(GL_QUADS); glVertex2i(30,226); glVertex2i(226,30); // Shows that the color is blue glColor3f(0.0f, 0.0f, 1.0f); glVertex2i(30,226); glVertex2i(226,30); glEnd(); // Executes the OpenGL's commands glFlush(); } // rendering void Inicializa (void) { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); } void AlteraTamanhoJanela(GLsizei w, GLsizei h) { // Evita a divisao por zero if(h == 0) h = 1; // Especifica as dimensões da Viewport glViewport(0, 0, w, h); // Inicializa o sistema de coordenadas glMatrixMode(GL_PROJECTION); glLoadIdentity(); // (left, right, bottom, top) if (w <= h) gluOrtho2D (0.0f, 250.0f, 0.0f, 250.0f*h/w); else gluOrtho2D (0.0f, 250.0f*w/h, 0.0f, 250.0f); } // Function callback that is called to manage the keyboard tasks void GerenciaTeclado(unsigned char key, int x, int y) { switch (key) { case 97: case 'a':// change the actual color to red glColor3f(1.0f, 0.0f, 0.0f); break; case 118: case 'v':// change de color do blue glColor3f(0.0f, 0.0f, 1.0f); break; case 27: case 'esc':// close the screen exit(0); break; } glutPostRedisplay(); } // Main Program int main(void) { glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(256,256); glutInitWindowPosition(10,10); glutCreateWindow("Quadrado"); glutDisplayFunc(Desenha); glutReshapeFunc(AlteraTamanhoJanela); Inicializa(); glutMainLoop(); }
Among other things your switch() didn't compile, you were missing a glutInit() call, and you never hooked up GerenciaTeclado() via glutKeyboardFunc(). Try this: #include <GL/glut.h> // Function callback that is called to manage the keyboard taks float r = 0.0f; float g = 0.0f; float b = 0.0f; void GerenciaTeclado(unsigned char key, int x, int y) { switch (key) { case 'a':// change the actual color to red r = 1.0f; g = 0.0f; b = 0.0f; break; case 'v':// change de color do blue r = 0.0f; g = 0.0f; b = 1.0f; break; case 27:// close the screen exit(0); break; } glutPostRedisplay(); } // Function callback that is called to draw void Desenha(void) { // Clean the window glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // Inicializa o sistema de coordenadas glMatrixMode(GL_PROJECTION); glLoadIdentity(); double w = glutGet( GLUT_WINDOW_WIDTH ); double h = glutGet( GLUT_WINDOW_HEIGHT ); double ar = w / h; glOrtho( -2 * ar, 2 * ar, -2, 2, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Draw a square glBegin(GL_QUADS); // Shows that the color is red // R G B glColor3f(r, g, b); glVertex2f(-1, -1); glVertex2f( 1, -1); // Shows that the color is blue glColor3f(0.0f, 0.0f, 1.0f); glVertex2f( 1, 1); glVertex2f(-1, 1); glEnd(); glutSwapBuffers(); } // Main Program int main( int argc, char** argv ) { glutInit( &argc, argv ); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(256,256); glutInitWindowPosition(10,10); glutCreateWindow("Quadrado"); glutDisplayFunc(Desenha); glutKeyboardFunc(GerenciaTeclado); glutMainLoop(); }