Related
I am trying to draw some random points as the star in the window,
but points are not showing. But others objects are showing correctly.
My source code:
#include<windows.h>
#include <GL\glut.h>
#include <math.h> // For math routines (such as sqrt & trig).
GLfloat xRotated, yRotated, zRotated;
GLdouble radius=3;
GLfloat qaBlack[] = {0.0, 0.0, 0.0, 1.0}; //Black Color
GLfloat qaGreen[] = {0.0, 1.0, 0.0, 1.0}; //Green Color
GLfloat qaWhite[] = {1.0, 1.0, 1.0, 1.0}; //White Color
GLfloat qaRed[] = {1.0, 0.0, 0.0, 1.0}; //Red Color
// Set lighting intensity and color
GLfloat qaSpecularLight[] = {1.0, 1.0, 1.0, 1.0};
GLfloat emitLight[] = {0.9, 0.9, 0.9, 0.9};
GLfloat Noemit[] = {0.0, 0.0, 0.0, 1.0};
// Light source position
GLfloat qaLightPosition[] = {1, 1, 1, 1};
void display(void);
void reshape(int x, int y);
void idleFunc(void)
{
if ( zRotated > 360.0 ) {
zRotated -= 360.0*floor(zRotated/360.0); // Don't allow overflow
}
if ( yRotated > 360.0 ) {
yRotated -= 360.0*floor(yRotated/360.0); // Don't allow overflow
}
zRotated += 0.05;
yRotated +=0.01;
display();
}
void initLighting()
{
// Enable lighting
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_SPECULAR, qaSpecularLight);
}
void display(void){
glMatrixMode(GL_MODELVIEW);
// clear the drawing buffer.
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
// clear the identity matrix.
glLoadIdentity();
glTranslatef(0.0,0.0,-40.0);
glPushMatrix();
glutSolidSphere(radius,25,25);
glPopMatrix();
glPopMatrix();
glPushMatrix();
glRotatef(yRotated,0.0,2.0,0.0);
glTranslatef(5.0,0.0,0.0);
// Set the light position
glLightfv(GL_LIGHT0, GL_POSITION, qaLightPosition);
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, emitLight); // Make sphere glow (emissive)
glutSolidSphere(radius/6,25,25);
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, Noemit);
glPopMatrix();
glTranslatef(0.0,0.0,0.0);
glPushMatrix();
glColor3f(1.0, 1.0, 1.0);
glPointSize(3);
for(int i=1;i<100;i++){
int x = rand()%640 ;
int y = rand()%480;
glBegin(GL_POINTS);
glVertex2i (x,y);
glEnd();
}
glPopMatrix();
glLoadIdentity();
glColor3f(1.0, 1.0, 1.0);
glPointSize(3);
for(int i=1;i<100;i++){
int x = rand()%640 ;
int y = rand()%480;
glBegin(GL_POINTS);
glVertex2i (x,y);
glEnd();
}
glFlush(); //FOR RENDERING
glutSwapBuffers();
}
void reshape(int x, int y){
if(y == 0 || x == 0) return;
glMatrixMode(GL_PROJECTION);
gluPerspective(20.0,(GLdouble)x/(GLdouble)y,0.6,40.0);
glMatrixMode(GL_MODELVIEW);
glViewport(0,0,x,y); //Use the whole window for rendering
}
int main (int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH );
glutInitWindowSize(1000,600);
glutCreateWindow("Project_KD");
initLighting();
xRotated = yRotated = zRotated = 0.0;
glutIdleFunc(idleFunc);
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}
Lots of wonkiness:
Couple instances of unmatched glPushMatrix()/glPopMatrix() calls; avoid over-/under-flowing the matrix stack; I like to use extra scopes to visually indicate matrix stack nesting.
Your point drawing was assuming an ortho projection while you only set a perspective one.
You left lighting enabled while trying to draw your points, resulting in very dark points everywhere except the bottom-left.
Your point drawing loop was duplicated for some reason; if you want double the stars adjust the for-loop end value instead of copy-pasting the loop.
You should use glutPostRedisplay() in your idle callback instead of calling display() directly.
Set your projection/modelview matrices each time through display() instead of setting them in a resize callback; helps reduce a source of mysterious matrix errors. The default resize callback calls glViewport() for you so you don't have to worry about doing that.
You're drawing the points ("stars"?) after the 3D spheres; I think the intent was to draw them before so they're "underneath".
Unholy mishmash of code formatting; recommend something like clang-format to keep that in check.
If you're using FreeGLUT on Windows (which you ought to be; it's really the only maintained GLUT implementation left) you don't need the #include <Windows.h>.
Recommend using a timer callback instead of an idle callback to update your simulation/animation. Without vsync that idle callback will be called incredibly often. With a timer callback you can simulate the even ~16 millisecond frames a vsync'd system will give you.
All together:
#include <GL/glut.h>
#include <cmath>
GLfloat xRotated, yRotated, zRotated;
GLdouble radius = 3;
void timer( int value )
{
if( zRotated > 360.0 )
{
zRotated -= 360.0 * floor( zRotated / 360.0 ); // Don't allow overflow
}
if( yRotated > 360.0 )
{
yRotated -= 360.0 * floor( yRotated / 360.0 ); // Don't allow overflow
}
zRotated += 5.0;
yRotated += 1.0;
glutTimerFunc( 16, timer, 0 );
glutPostRedisplay();
}
void display()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glDepthMask( GL_FALSE );
glDisable( GL_DEPTH_TEST );
glDisable( GL_LIGHTING );
// 2D rendering
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho( 0, 640, 0, 480, -1, 1 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glPushMatrix();
{
glColor3f( 1.0, 1.0, 1.0 );
glPointSize( 3 );
glBegin( GL_POINTS );
for( int i = 1; i < 100; i++ )
{
int x = rand() % 640;
int y = rand() % 480;
glVertex2i( x, y );
}
glEnd();
}
glPopMatrix();
glDepthMask( GL_TRUE );
glEnable( GL_DEPTH_TEST );
// Enable lighting
glEnable( GL_LIGHTING );
glEnable( GL_LIGHT0 );
GLfloat qaSpecularLight[] = {1.0, 1.0, 1.0, 1.0};
glLightfv( GL_LIGHT0, GL_SPECULAR, qaSpecularLight );
// 3D rendering
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
double w = glutGet( GLUT_WINDOW_WIDTH );
double h = glutGet( GLUT_WINDOW_HEIGHT );
gluPerspective( 20.0, w / h, 0.1, 80.0 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
glTranslatef( 0.0, 0.0, -40.0 );
glPushMatrix();
{
glutSolidSphere( radius, 25, 25 );
}
glPopMatrix();
glPushMatrix();
{
glRotatef( yRotated, 0.0, 2.0, 0.0 );
glTranslatef( 5.0, 0.0, 0.0 );
GLfloat qaLightPosition[] = {1, 1, 1, 1};
glLightfv( GL_LIGHT0, GL_POSITION, qaLightPosition );
GLfloat emitLight[] = {0.9, 0.9, 0.9, 0.9};
glMaterialfv( GL_FRONT_AND_BACK, GL_EMISSION, emitLight ); // Make sphere glow (emissive)
glutSolidSphere( radius / 6, 25, 25 );
GLfloat Noemit[] = {0.0, 0.0, 0.0, 1.0};
glMaterialfv( GL_FRONT_AND_BACK, GL_EMISSION, Noemit );
}
glPopMatrix();
glutSwapBuffers();
}
int main( int argc, char** argv )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH );
glutInitWindowSize( 1000, 600 );
glutCreateWindow( "Project_KD" );
xRotated = yRotated = zRotated = 0.0;
glutDisplayFunc( display );
glutTimerFunc( 0, timer, 0 );
glutMainLoop();
return 0;
}
I have created a bowling game in OpenGL using Eclipse.
Now I want to change the view of camera upon key-pressed.
But When I press x button, everything disappears.
Here us the code: -
#include <GL/glut.h>
#include <stdlib.h>
int refreshMillis = 30; // Refresh period in milliseconds
int windowWidth = 640; // Windowed mode's width
int windowHeight = 480; // Windowed mode's height
int windowPosX = 50; // Windowed mode's top-left corner x
int windowPosY = 50; // Windowed mode's top-left corner y
bool fullScreenMode = false; // Full-screen or windowed mode?
GLfloat ballTSpeed = 0.15f; // Ball's speed in y directions
GLfloat x = 1.0f, y = 10.0f, z = 10.0f, i = 0.0f, j = 0.0f, k = 0.0f, a = 0.0f,
b = 0.0f, c = -1.0f;
bool moveBallUp = false, moveBallDown = false, isCollision = false, resetCall =
false;
//
GLfloat cone1[] = { 0.0f, 2.5f, -11.0f, /*rotated*/30.0f, -1.5, 0.0, 0.0 };
GLfloat cone2[] = { 2.0f, 2.5f, -11.0f, /*rotated*/30.0f, -1.5, 0.0, 0.0 };
GLfloat cone3[] = { -2.0f, 2.5f, -11.0f, /*rotated*/30.0f, -1.5, 0.0, 0.0 };
GLfloat ball[] = {/* X */0.0f, /* Y */-2.0f, /* Z */-6.0f, /*sphere*/1.0f, 50.0,
50.0 };
//
void resetGame() {
resetCall = true;
cone1[0] = 0.0f;
cone1[1] = 2.5f;
cone1[2] = -11.0f;
/*rotated*/
cone1[3] = 30.0f;
cone1[4] = -1.5;
cone1[5] = 0.0;
cone1[6] = 0.0;
cone2[0] = 2.0f;
cone2[1] = 2.5f;
cone2[2] = -11.0f;
/*rotated*/
cone2[3] = 30.0f;
cone2[4] = -1.5;
cone2[5] = 0.0;
cone2[6] = 0.0;
cone3[0] = -2.0f;
cone3[1] = 2.5f;
cone3[2] = -11.0f;
/*rotated*/
cone3[3] = 30.0f;
cone3[4] = -1.5;
cone3[5] = 0.0;
cone3[6] = 0.0;
}
const GLfloat light_ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f };
const GLfloat light_diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_position[] = { 2.0f, 5.0f, 5.0f, 0.0f };
const GLfloat mat_ambient[] = { 0.7f, 0.7f, 0.7f, 1.0f };
const GLfloat mat_diffuse[] = { 0.8f, 0.8f, 0.8f, 1.0f };
const GLfloat mat_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat high_shininess[] = { 100.0f };
static void resize(int width, int height) {
const float ar = (float) width / (float) height;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-ar, ar, -1.0, 1.0, 1.0, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(x, y, z, i, j, k, a, b, c);
// eyex, eyey, eyez, centerx, centery, centerz, upx, upy, upz
}
/* Called back when the timer expired */
void Timer(int value) {
glutPostRedisplay(); // Post a paint request to activate display()
glutTimerFunc(refreshMillis, Timer, 0); // subsequent timer call at milliseconds
}
void keyboard(unsigned char key, int x, int y) {
switch (key) {
case 27: // ESC key
exit(0);
break;
case 'r':
resetGame();
break;
case 'i':
x += 0.5;
gluLookAt(x, y, z, i, j, k, a, b, c);
// eyex, eyey, eyez, centerx, centery, centerz, upx, upy, upz
}
}
void specialKeys(int key, int x, int y) {
switch (key) {
case GLUT_KEY_F1: // F1: Toggle between full-screen and windowed mode
fullScreenMode = !fullScreenMode; // Toggle state
if (fullScreenMode) { // Full-screen mode
windowPosX = glutGet(GLUT_WINDOW_X ); // Save parameters for restoring later
windowPosY = glutGet(GLUT_WINDOW_Y );
windowWidth = glutGet(GLUT_WINDOW_WIDTH );
windowHeight = glutGet(GLUT_WINDOW_HEIGHT );
glutFullScreen(); // Switch into full screen
} else { // Windowed mode
glutReshapeWindow(windowWidth, windowHeight); // Switch into windowed mode
glutPositionWindow(windowPosX, windowPosX); // Position top-left corner
}
break;
case GLUT_KEY_UP:
if (!isCollision)
moveBallUp = true;
break;
case GLUT_KEY_PAGE_UP:
ballTSpeed *= 1.2f;
break;
}
}
static void display(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (moveBallUp) {
ball[1] += ballTSpeed;
ball[2] -= 0.02 + ballTSpeed;
}
if (ball[1] >= (cone1[1] - 0.4) && ball[1] <= cone1[1]) {
if (!isCollision)
{
cone1[0] -= 0.5;
cone1[4] -= 10.0;
cone1[5] += 10.0;
cone1[2] += -0.3;
cone2[0] += 0.5;
cone2[4] -= 10.0;
cone2[5] -= 10.0;
cone2[2] += -0.4;
cone3[0] += 0.5;
cone3[4] -= 10.0;
cone3[5] -= 10.0;
cone3[2] += -0.4;
}
isCollision = true;
moveBallUp = false; // stop moving the ball
}
if (resetCall) {
if ((ball[1] >= -2.0f && ball[1] <= -1.6f)
&& (ball[2] >= -6.0f && ball[2] <= -5.6f)) {
resetCall = false;
isCollision = false;
}
else {
ball[1] -= ballTSpeed;
ball[2] += 0.02 + ballTSpeed;
}
}
glColor3d(1, 1, 0);
glPushMatrix();
glTranslated(cone1[0], cone1[1], cone1[2]);
glRotated(cone1[3], cone1[4], cone1[5], cone1[6]);
glutSolidCone(1, 2, 50, 50);
glPopMatrix();
glColor3d(1, 0, 1);
glPushMatrix();
glTranslated(cone2[0], cone2[1], cone2[2]);
glRotated(cone2[3], cone2[4], cone2[5], cone2[6]);
glutSolidCone(1, 2, 50, 50);
glPopMatrix();
glColor3d(0, 0, 1);
glPushMatrix();
glTranslated(cone3[0], cone3[1], cone3[2]);
glRotated(cone3[3], cone3[4], cone3[5], cone3[6]);
glutSolidCone(1, 2, 50, 50);
glPopMatrix();
glColor3d(1, 0, 0);
glPushMatrix();
glTranslated(ball[0], ball[1], ball[2]);
glutSolidSphere(ball[3], ball[4], ball[5]);
glPopMatrix();
glPushMatrix();
glColor3d(0.6, 1, 0.20);
glBegin(GL_QUADS);
glVertex3f(16.0, 5.0, -25.0);
glVertex3f(-16.0, 5.0, -25.0);
glVertex3f(-6.0, -4.0, -5.0);
glVertex3f(6.0, -4.0, -5.0);
glEnd();
glColor3d(1, 1, 0);
glBegin(GL_QUADS);
glVertex3f(16.0, 15.0, -25.0);
glVertex3f(-16.0, 15.0, -25.0);
glVertex3f(-16.0, -4.0, -25.0);
glVertex3f(16.0, -4.0, -25.0);
glEnd();
glutSwapBuffers();
}
/* Program entry point */
int main(int argc, char *argv[]) {
glutInit(&argc, argv);
glutInitWindowSize(windowWidth, windowHeight); // Initial window width and height
glutInitWindowPosition(windowPosX, windowPosY); // Initial window top-left corner (x, y)
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Balling Game 3d");
glutReshapeFunc(resize);
glutDisplayFunc(display);
glClearColor(1, 1, 1, 1);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess);
glutTimerFunc(0, Timer, 0); // First timer call immediately
glutSpecialFunc(specialKeys); // Register callback handler for special-key event
glutKeyboardFunc(keyboard); // Register callback handler for special-key event
glutMainLoop();
return EXIT_SUCCESS;
}
In the code case 'i':
x += 0.5;
gluLookAt(x, y, z, i, j, k, a, b, c);
// eyex, eyey, eyez, centerx, centery, centerz, upx, upy, upz
Camera view should be changed as I guess but I know that I am doing wrong. Please tell me how to do this?
Never call OpenGL functions from input event handlers. Only misery and dispair comes out of this.
In your input event handlers set variables from the user input data and trigger a redraw. In the drawing function parameterize the rendering process from those variables.
You can remove the resize handler entirely. Setup viewport and projection in the display function
static void display(void) {
int const width = glutGet(GLUT_WINDOW_WIDTH);
int const height = glutGet(GLUT_WINDOW_HEIGHT);
float const ar = (float) width / (float) height;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-ar, ar, -1.0, 1.0, 1.0, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(view_x, view_y, view_z, target_x, target_y, target_z, up_x, up_y, up_z);
// eyex, eyey, eyez, centerx, centery, centerz, upx, upy, upz
/* ... */
In the keyboard handler just set variables and trigger a redisplay
void keyboard(unsigned char key, int mouse_x, int mouse_y) {
switch (key) {
case 27: // ESC key
exit(0);
break;
case 'r':
resetGame();
break;
case 'i':
view_x += 0.5;
/* don't call gluLookAt here! */
}
glutPostRedisplay();
}
I am using Visual C++ and GLUT. Am I missing something such a normals? this is the exact code I am using. I tried to insert glNormal3f(0, 0, 1); before the vertex statements but this did not change anything. The glutSolidSphere renders just as I expect it to but not the quad.
#include "stdafx.h"
#include <stdlib.h>
#include <GL/glut.h>
float spin = 0.0f;
float zDir = 0;
GLfloat diffuseIntensity[] = {.75, .75, .75, 1};
GLfloat specularHue[] = {0, 0, .5f, 1};
GLfloat shininess[] = {5};
void moveCamera();
void checkKeys(int, int, int);
void setUpLighting();
void changeSize(int w, int h) {
if (h == 0)
h = 1;
float ratio = w * 1.0 / h;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, w, h);
gluPerspective(45,ratio,1,1000);
glMatrixMode(GL_MODELVIEW);
}
void renderScene(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
moveCamera();
glTranslatef(0, 0, zDir-5);
glEnable(GL_COLOR_MATERIAL);
glShadeModel(GL_FLAT);
glMaterialfv(GL_FRONT, GL_SHININESS, shininess);
glMaterialfv(GL_FRONT, GL_SPECULAR, specularHue);
glPushMatrix();
glRotatef(90, 1, 0, 0);
glRotatef(spin, 0, 0, 1);
glutSolidSphere(.5f, 24, 24);
glPopMatrix();
spin += .01f;
if(spin > 360) spin -= 360;
glBegin(GL_QUADS);
glVertex3f(-10, 0, -10);
glVertex3f(-10, 0, 10);
glVertex3f(10, 0, 10);
glVertex3f(10, 0, -10);
glEnd();
glutSwapBuffers();
glutPostRedisplay();
}
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(100,100);
glutInitWindowSize(800,600);
glutCreateWindow("Lighthouse3D - GLUT Tutorial");
glutDisplayFunc(renderScene);
glutReshapeFunc(changeSize);
glutSpecialFunc(checkKeys);
glEnable(GL_DEPTH_TEST);
setUpLighting();
glutMainLoop();
return 1;
}
void moveCamera(){
glTranslatef(0, 0, zDir);
}
void checkKeys(int key, int x, int y){
switch(key){
case GLUT_KEY_UP:
zDir += .1f;
glutPostRedisplay();
break;
case GLUT_KEY_DOWN:
zDir += -.1f;
glutPostRedisplay();
break;
case GLUT_KEY_END:
exit(0);
}
}
void setUpLighting(){
GLfloat position0[] = {3, 1, 0, 1};
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_POSITION, position0);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseIntensity);
}
Give this a shot:
#include <GL/glut.h>
float zDir = 12;
void checkKeys(int key, int x, int y)
{
switch(key)
{
case GLUT_KEY_UP:
zDir += -.5f;
glutPostRedisplay();
break;
case GLUT_KEY_DOWN:
zDir += .5f;
glutPostRedisplay();
break;
case GLUT_KEY_END:
exit(0);
}
}
float spin = 0;
void renderScene(void)
{
glEnable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
double w = glutGet( GLUT_WINDOW_WIDTH );
double h = glutGet( GLUT_WINDOW_HEIGHT );
gluPerspective(45,w/h,0.1,100);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0, 0, -zDir);
// set up light
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
GLfloat diffuseIntensity[] = {.75, .75, .75, 1};
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseIntensity);
// draw sphere at light position
glDisable( GL_LIGHTING );
glPushMatrix();
// spin light position around the y axis
glRotatef( -spin, 0, 1, 0 );
GLfloat position0[] = {3,3,3, 1};
glLightfv(GL_LIGHT0, GL_POSITION, position0);
glTranslatef( position0[0], position0[1], position0[2] );
glColor3ub(255,255,255);
glutSolidSphere(0.1,8,8);
glPopMatrix();
glEnable( GL_LIGHTING );
// draw sphere
glEnable(GL_COLOR_MATERIAL);
glShadeModel(GL_FLAT);
GLfloat specularHue[] = {0, 0, .5f, 1};
GLfloat shininess[] = {5};
glMaterialfv(GL_FRONT, GL_SHININESS, shininess);
glMaterialfv(GL_FRONT, GL_SPECULAR, specularHue);
spin += .01f;
if(spin > 360) spin -= 360;
glPushMatrix();
glRotatef(spin, 0, 1, 0);
glutSolidSphere(2, 24, 24);
glPopMatrix();
// draw quad
glColor3ub(255,0,0);
glPushMatrix();
glScalef( 3, 3, 3 );
glBegin(GL_QUADS);
glNormal3f( 0, 0, 1 );
glVertex2f( -1, -1 );
glVertex2f( 1, -1 );
glVertex2f( 1, 1 );
glVertex2f( -1, 1 );
glEnd();
glPopMatrix();
glutSwapBuffers();
glutPostRedisplay();
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(100,100);
glutInitWindowSize(800,600);
glutCreateWindow("Lighthouse3D - GLUT Tutorial");
glutDisplayFunc(renderScene);
glutSpecialFunc(checkKeys);
glutMainLoop();
return 1;
}
The quad is rendered, but you don't see it because it is drawn very much like the surface of a table and your eyes are at the same level of the table. Because of this, the effect is like that of which nothing was drawn at all. That or you'll see a line.
Your rotation above, being wrapped in a PushMatrix/PopMatrix only works with the solid sphere.
I have some questions about how to move an object by pressing a key. All I want to do is to press the up button in my keyboard and make the object move one unit.
void display(){
//Clear Window
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glBegin(GL_POLYGON);
glColor3f(1.0, 0.0, 0.0);
glVertex2f(-0.1, -0.2);
glVertex2f(-0.1, 0.2);
glVertex2f(0.1, 0.2);
glVertex2f(0.1, -0.2);
glEnd();
glPopMatrix();
glFlush();
}
void keyboardListener(int key)
{
if( key == GLUT_KEY_UP)
{
glTranslatef(1.0, 0.0, 0.0);
glutPostRedisplay();
}
}
Whats missing or what concept I am not understanding?
use this:
#include <stdio.h>
#include <gl/glut.h>
GLfloat rotation = 90.0;
float posX = 0, posY = 0, posZ = 0;
void reshape(int width, int heigth){
/* window ro reshape when made it bigger or smaller*/
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//clip the windows so its shortest side is 2.0
if (width < heigth) {
glOrtho(-2.0, 2.0, -2.0 * (GLfloat)heigth / (GLfloat)width, 2.0 * (GLfloat)heigth / (GLfloat)width, 2.0, 2.0);
}
else{
glOrtho(-2.0, 2.0, -2.0 * (GLfloat)width / (GLfloat)heigth, 2.0 * (GLfloat)width / (GLfloat)heigth,2.0 , 2.0);
}
// set viewport to use the entire new window
glViewport(0, 0, width, heigth);
}
void rect(){
glBegin(GL_POLYGON);
glColor3f(1.0, 0.0, 0.0);
glVertex2f(-0.1, -0.2);
glVertex2f(-0.1, 0.2);
glVertex2f(0.1, 0.2);
glVertex2f(0.1, -0.2);
glEnd();
}
void display(){
//Clear Window
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glPushMatrix();
glTranslatef(posX,posY,posZ);
rect();
glPopMatrix();
glFlush();
}
void init(){
// set clear color to black
glClearColor(0.0, 0.0, 0.0, 0.0);
// set fill color to white
glColor3f(1.0, 1.0, 1.0);
//set up standard orthogonal view with clipping
//box as cube of side 2 centered at origin
//This is the default view and these statements could be removed
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-1.0, 1.0, -1.0, 1.0);
}
float move_unit = 0.1f;
void keyboardown(int key, int x, int y)
{
switch (key){
case GLUT_KEY_RIGHT:
posX+=move_unit;;
break;
case GLUT_KEY_LEFT:
posX-=move_unit;;
break;
case GLUT_KEY_UP:
posY+=move_unit;;
break;
case GLUT_KEY_DOWN:
posY-=move_unit;;
break;
default:
break;
}
glutPostRedisplay();
}
int main(int argc, char** argv){
//initialize mode and open a windows in upper left corner of screen
//Windows tittle is name of program
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0, 0);
glutCreateWindow("Practice 1");
glutDisplayFunc(display);
init();
glutSpecialFunc(keyboardown);
glutMainLoop();
}
The easiest way is to do something like so
float posX = 0, posY = 0, posZ = 0;
void display(){
glClear(GL_COLOR_BUFFER_BIT);
glTranslate(posX,posY,posZ);
drawPolygon();
//...
}
void keyboardListener(int key){
if(key == GLUT_KEY_RIGHT){ posX++; }
else if(key == GLUT_KEY_LEFT){ posX--; }
//..similar for up/down
glutPostRedisplay();
}
This code draws a circle and is moved upon left, right, up or down key pressed.
#include <cmath>
#include <stdio.h>
float posX = 0.01, posY = -0.1, posZ = 0;
void circ() {
glColor3f(0.0, 0.0, 1.0);
glBegin(GL_TRIANGLE_FAN);
for (int i = 0; i <= 300; i++) {
angle = 2 * PI * i / 300;
x = cos(angle) / 20;
y = sin(angle) / 20;
glVertex2d(x, y);
}
glEnd();
}
void display() {
glClearColor(1.0, 1.0, 1.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-1.0, 1.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glPushMatrix();
glTranslatef(posX, posY, posZ);
circ();
glPopMatrix();
glutSwapBuffers();
}
**float move_unit = 0.02f;
void keyboardown(int key, int x, int y) {
switch (key) {
case GLUT_KEY_RIGHT:
posX += move_unit;
break;
case GLUT_KEY_LEFT:
posX -= move_unit;
break;
case GLUT_KEY_UP:
posY += move_unit;
break;
case GLUT_KEY_DOWN:
posY -= move_unit;
break;
default:
break;
}
glutPostRedisplay();
}**
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(600, 500);
glutInitWindowPosition(0, 0);
glutCreateWindow("Example");
glutDisplayFunc(display);
glutSpecialFunc(keyboardown);
glutMainLoop();
}
I am trying to make a motorcycle with primitive shapes. For some reason, the shapes that I have made are see-through. I am not specifying any alpha anywhere; here is my code:
#include <GL/glut.h>
#include <math.h>
GLUquadricObj *quadratic;
static int isWire = 0; // Is wireframe?
static int distance = 10;
static float angleH = 0;
static float angleV = 0;
static float R = 2.0; // Radius of hemisphere.
static int p = 4; // Number of longitudinal slices.
static int q = 6; // Number of latitudinal slices.
#define PI 3.14159265358979324
static unsigned int pipe, seat, cover, wheel, wheelCenter, cycles; // parts of the motorcycle to make as display lists.
GLUquadricObj *cylinder;
void drawCoordinates();
void drawMotorcycle();
void drawTrailer();
void drawHemisphere();
void drawCylinder(float x, float y, float z);
void drawHandle(float x, float y, float z);
void drawLight();
void drawBase();
void setup();
void display () {
/* clear window */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(distance*cos(angleH), distance*cos(angleV), distance*sin(angleH), 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
/* future matrix manipulations should affect the modelview matrix */
glMatrixMode(GL_MODELVIEW);
if (isWire) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glPushMatrix();
drawCoordinates();
glPushMatrix();
glTranslatef(0.0, 0.0, 0.0); // Move the motorcycle around the world space
drawMotorcycle();
drawTrailer();
glPopMatrix();
glPopMatrix();
/* flush drawing routines to the window */
glFlush();
}
void drawCoordinates()
{
/***************** DRAW AXIS *****************/
glPushMatrix();
GLUquadricObj *xAxis;
xAxis=gluNewQuadric();
glColor3f(1,0,0);
glRotatef(-90, 0, 1, 0);
gluCylinder(xAxis,0.05,0.05,1,5,5);
glPopMatrix();
glPushMatrix();
GLUquadricObj *yAxis;
yAxis=gluNewQuadric();
glColor3f(0,1,0);
glRotatef(-90, 1, 0, 0);
gluCylinder(yAxis,0.05,0.05,1,5,5);
glPopMatrix();
glPushMatrix();
GLUquadricObj *zAxis;
zAxis=gluNewQuadric();
glColor3f(0,0,1);
gluCylinder(zAxis,0.05,0.05,1,5,5);
glPopMatrix();
/***************** END OF DRAW AXIS *****************/
}
void drawMotorcycle()
{
//DRAW ENGINE
glPushMatrix();
//drawCoordinates();
glColor3f(.6, 0, 0);
glScalef(1.4, 0.8, 1.0);
glutSolidSphere(1,8,8);
glPushMatrix();
//drawCoordinates();
glPopMatrix();
glPopMatrix();
//DRAW PIPES UNDER ENGINE
glPushMatrix();
glRotatef(-90, 1, 0, 0);
glRotatef(80, 0, 1, 0);
glTranslatef(0.5, 1.0, -1.5);
glCallList(pipe);
glTranslatef(0.0, -2.0, 0.0);
glCallList(pipe);
glPopMatrix();
//DRAW SEAT
glPushMatrix();
glPushMatrix();
glRotatef(15, 0, 0, 1);
glTranslatef(-2.0, -0.4, 0.0);
glScalef(2.0, 0.2, 1.2);
glCallList(seat);
glPopMatrix();
//DRAW BACK SEAT
glRotatef(-40, 0, 0, 1);
glTranslatef(-2.3, -2.8, 0.0);
glScalef(2.0, 0.2, 1.2);
glCallList(seat);
glPopMatrix();
//DRAW FRONT PLATE
glPushMatrix();
glRotatef(120, 0, 0, 1);
glTranslatef(0.8, -1.3, 0.0);
glScalef(2.0, 0.2, 1.35);
glColor3f(0.5,0.0,0.0);
glutSolidCube(1);
glPushMatrix();
//drawCoordinates();
glPopMatrix();
glPopMatrix();
//DRAW FRONT PIPES
glPushMatrix();
glRotatef(-90, 1, 0, 0);
glRotatef(-30, 0, 1, 0);
glTranslatef(1.3, -0.9, -5.7);
glScalef(1.0, 1.0, 2.5);
glCallList(pipe);
glTranslatef(0.0, 1.7, 0.0);
glCallList(pipe);
glPopMatrix();
//DRAW WHEEL COVERS
glPushMatrix();
glTranslatef(3.5, -3.0, 0.0);
glScalef(1.0, 0.5, 1.0);
glRotatef(45, 0, 0, 1);
glCallList(cover);
glTranslatef(-5.5, 0.0, 0.0);
glRotatef(-100, 0, 0, 1);
glTranslatef(-8.5, 0.2, 0.0);
glCallList(cover);
glPopMatrix();
//DRAW WHEELS
glPushMatrix();
glTranslatef(3.9, -4.1, 0.0);
glCallList(wheel);
glTranslatef(-9.2, 2.0, 0.0);
glCallList(wheel);
glPopMatrix();
//DRAW WHEEL CENTER PIECES
glPushMatrix();
glTranslatef(3.9, -4.1, 0.0);
glCallList(wheelCenter);
glTranslatef(-9.2, 2.0, 0.0);
glCallList(wheelCenter);
glPopMatrix();
//DRAW CYCLES AROUND WHEELS
glPushMatrix();
glTranslatef(3.9, -4.1, 0.0);
glRotatef(-90, 1, 0, 0);
for(int i=0; i<8; i++)
{
glRotatef(45, 0, 1, 0);
glPushMatrix();
glCallList(cycles);
glPopMatrix();
}
glTranslatef(-9.2, 0.0, 2.0);
for(int i=0; i<8; i++)
{
glRotatef(45, 0, 1, 0);
glPushMatrix();
glCallList(cycles);
glPopMatrix();
}
glPopMatrix();
//DRAW HANDLE BARS
glPushMatrix();
glTranslatef(0.2, 2.0, 0.0);
glRotatef(-45, 1, 0, 0);
glScalef(0.7, 0.7, 0.7);
glCallList(pipe);
glRotatef(-90, 1, 0, 0);
glCallList(pipe);
glPopMatrix();
//DRAW LIGHT
glPushMatrix();
glTranslatef(1.0, 1.0, 0.0);
glColor3f(0.5, 0.5, 0.0);
//glScalef(1.0, 0.5, 1.0);
glutSolidSphere(0.5, 5, 5);
glPushMatrix();
//drawCoordinates();
glPopMatrix();
glPopMatrix();
//DRAW BASE
glPushMatrix();
glRotatef(10.0, 0.0, 0.0, 1.0);
glScalef(3.5, 1.5, 1.0);
glTranslatef(-0.4, -1.0, 0.0);
glColor3f(0.3, 0.3, 0.3);
glutSolidCube(1);
glPopMatrix();
//GAS TANK
glPushMatrix();
glScalef(2.5, 1.0, 0.8);
glTranslatef(-0.8, -1.7, -1.4);
glCallList(pipe);
glPopMatrix();
}
void drawTrailer()
{
//DRAW BODY
glPushMatrix();
glColor3f(0.0, 0.0, 0.3);
glScalef(2.0, 2.5, 1.5);
glTranslatef(-4.5, -0.5, 0.0);
glutSolidCube(1);
glPopMatrix();
//DRAW WHEELS
glPushMatrix();
glPushMatrix();
glScalef(0.8, 0.8, 0.8);
glTranslatef(-12.0, -1.5, 2.0);
glCallList(wheel);
glCallList(wheelCenter);
glRotatef(90, 1, 0, 0);
for(int i=0; i<8; i++)
{
glRotatef(45, 0, 1, 0);
glPushMatrix();
glCallList(cycles);
glPopMatrix();
}
glPopMatrix();
glPushMatrix();
glScalef(0.8, 0.8, 0.8);
glTranslatef(-12.0, -1.5, -2.0);
glCallList(wheel);
glCallList(wheelCenter);
glRotatef(90, 1, 0, 0);
for(int i=0; i<8; i++)
{
glRotatef(45, 0, 1, 0);
glPushMatrix();
glCallList(cycles);
glPopMatrix();
}
glPopMatrix();
glPopMatrix();
//DRAW CONNECTION TO MOTORCYCLE
glPushMatrix();
glRotatef(90, 0, 1, 0);
glTranslatef(0.0, -1.0, -8.0);
glCallList(pipe);
glPopMatrix();
}
void drawHemisphere()
{
for(int j = 0; j < q; j++)
{
// One latitudinal triangle strip.
glBegin(GL_TRIANGLE_STRIP);
for(int i = 0; i <= p; i++)
{
glVertex3f( R * cos( (float)(j+1)/q * PI/2.0 ) * cos( 2.0 * (float)i/p * PI ),
R * sin( (float)(j+1)/q * PI/2.0 ),
R * cos( (float)(j+1)/q * PI/2.0 ) * sin( 2.0 * (float)i/p * PI ) );
glVertex3f( R * cos( (float)j/q * PI/2.0 ) * cos( 2.0 * (float)i/p * PI ),
R * sin( (float)j/q * PI/2.0 ),
R * cos( (float)j/q * PI/2.0 ) * sin( 2.0 * (float)i/p * PI ) );
}
glEnd();
}
}
void reshape (int w, int h)
{
// (Window of width = zero is not possible).
if(h == 0)
h = 1;
float ratio = 1.0* w / h;
// Reset the coordinate system before modifying
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Set the viewport to be the entire window
glViewport(0, 0, w, h);
// Set the correct perspective.
gluPerspective(90,ratio,-1,1);
}
// Keyboard input processing routine.
void keyInput(unsigned char key, int x, int y)
{
switch(key)
{
case 'c' : distance = 10; angleH=0; angleV=0.0; break;
case 'C' : distance = 10; angleH=0; angleV=0.0; break;
case 'f': distance = (distance == 4)? 4:distance-1; break;
case 'F': distance = (distance == 4)? 4:distance-1; break;
case 'b': distance = (distance == 20)? 20:distance+1; break;
case 'B': distance = (distance == 20)? 20:distance+1; break;
case 'w': if (isWire == 0) isWire = 1; else isWire = 0; break;
case 'W': if (isWire == 0) isWire = 1; else isWire = 0; break;
//case 27: exit(0); break;
default: break;
}
}
void specialKeyboard(int key, int x, int y) {
switch (key)
{
case GLUT_KEY_RIGHT:
angleH -= .2;
break;
case GLUT_KEY_LEFT:
angleH += .2;
break;
case GLUT_KEY_UP:
angleV += .2;
break;
case GLUT_KEY_DOWN:
angleV -= .2;
break;
}
}
void update(void){
glutPostRedisplay();
}
void setup()
{
// PARTS
pipe = glGenLists(1);
seat = glGenLists(1);
cover = glGenLists(1);
wheel = glGenLists(1);
wheelCenter = glGenLists(1);
cycles = glGenLists(1);
glNewList(pipe, GL_COMPILE); // Any cylinder on the motorcycle
GLUquadricObj *cylinder;
cylinder=gluNewQuadric();
glPushMatrix();
glColor3f(.5,.5,.5);
gluCylinder(cylinder,0.2,0.2,3,5,5);
glPushMatrix();
//drawCoordinates();
glPopMatrix();
glPopMatrix();
glEndList();
glNewList(seat, GL_COMPILE);
glPushMatrix();
glColor3f(0.5, 0.35, 0.05);
glutSolidCube(1);
glPushMatrix();
//drawCoordinates();
glPopMatrix();
glPopMatrix();
glEndList();
glNewList(cover, GL_COMPILE);
glPushMatrix();
glColor3f(0.5, 0.0, 0.0);
drawHemisphere();
glPushMatrix();
//drawCoordinates();
glPopMatrix();
glPopMatrix();
glEndList();
glNewList(wheel, GL_COMPILE);
glPushMatrix();
glColor3f(0.1, 0.1, 0.1);
glutSolidTorus(0.2, 1.2, 20, 20);
glPushMatrix();
//drawCoordinates();
glPopMatrix();
glPopMatrix();
glEndList();
glNewList(wheelCenter, GL_COMPILE);
glPushMatrix();
glColor3f(0.4, 0.5, 0.5);
glScalef(1.0, 0.5, 1.0);
glutSolidSphere(0.8, 5, 5);
glPushMatrix();
//drawCoordinates();
glPopMatrix();
glPopMatrix();
glEndList();
glNewList(cycles, GL_COMPILE);
glColor3f(0.5, 0.5, 0.5);
glScalef(0.25, 0.25, 0.25);
cylinder=gluNewQuadric();
gluCylinder(cylinder,0.5,0.5,5,15,5);
glEndList();
}
int main (int argc, char** argv) {
/* initialize GLUT, using any commandline parameters passed to the
program */
glutInit(&argc,argv);
/* setup the size, position, and display mode for new windows */
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH );
/* create and set up a window */
glutCreateWindow("Motorcycle");
setup(); // Build all the display lists, ready to use
glutIdleFunc(update);
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyInput);
glutSpecialFunc(specialKeyboard);
/* set up depth-buffering */
glEnable(GL_DEPTH_TEST);
/* background color */
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
/* tell GLUT to wait for events */
glutMainLoop();
return 0;
}
You can rotate the camera with the arrow keys to see that the objects are see through. How can I fix this? Is there anything else I can do to improve my code?
In reshape():
// Set the correct perspective.
gluPerspective(90,ratio,-1,1);
I'm guessing you transliterated parameters from a glOrtho() call, where a negative zNear is perfectly legitimate.
From the gluPerspective() docs:
zNear: Specifies the distance from the viewer to the near clipping plane (always positive).
Try this:
gluPerspective(90,ratio,1,100);
You need to add glEnable(GL_DEPTH_TEST); to your initialization function.