Related
I am writing a program to change the size and color of a shape. I have reached the stage where I can change the size of the current shape, but the color does not change. I want to change the color to R, G, B form. Thank you. Please forgive wherever my English is not grammatical. English is not my first language
#include <glut.h>
#include <stdio.h>
#include <stdlib.h>
constexpr auto RED = 1;
constexpr auto GREEN = 2;
constexpr auto BLUE = 3;
float red = 1.0, green = 1.0, blue = 1.0;
GLboolean IsSphere = true;
GLboolean IsSmall = true;
void MyDisplay() {
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.5, 0.0, 0.5);
if ((IsSphere) && (IsSmall))
glutWireSphere(0.2, 15, 15);
else if ((IsSphere) && (!IsSmall))
glutWireSphere(0.4, 15, 15);
else if ((!IsSphere) && (IsSmall))
glutWireTorus(0.1, 0.3, 40, 20);
else glutWireTorus(0.2, 0.5, 40, 20);
glFlush();
}
void MyMainMenu(int entryID) {
if (entryID == 1)
IsSphere = true;
else if (entryID == 2)
IsSphere = false;
else if (entryID == 3)
exit(0);
glutPostRedisplay();
}
void MySubMenu(int entryID) {
if (entryID == 1)
IsSmall = true;
else if (entryID == 2)
IsSmall = false;
glutPostRedisplay();
}
void MySubMenu2(int entryID)
{
switch (entryID) {
case RED: red = 1.0; green = 0.0; blue = 0.0; break;
case GREEN: red = 0.0; green = 1.0; blue = 0.0; break;
case BLUE: red = 0.0; green = 0.0; blue = 1.0; break;
}
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA);
glutInitWindowSize(300, 300);
glutInitWindowPosition(0, 0);
glutCreateWindow("OpenGL Example Drawing");
glClearColor(1.0, 1.0, 1.0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
GLint MySubMenuID = glutCreateMenu(MySubMenu);
glutAddMenuEntry("Small One", 1);
glutAddMenuEntry("Big One", 2);
GLint MySubMenu2ID = glutCreateMenu(MySubMenu2);
glutAddMenuEntry("RED", RED);
glutAddMenuEntry("GREEN", GREEN);
glutAddMenuEntry("BLUE", BLUE);
GLint MyMainMenuID = glutCreateMenu(MyMainMenu);
glutAddMenuEntry("Draw Sphere", 1);
glutAddMenuEntry("Draw Torus", 2);
glutAddSubMenu("Change Size", MySubMenuID);
glutAddSubMenu("Change Color", MySubMenu2ID);
glutAddMenuEntry("Exit", 3);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutDisplayFunc(MyDisplay);
glutMainLoop();
return 0;
}
Use the variables which define the color (red, green, blue) in MyDisplay:
float red = 0.5f, green = 0.0f, blue = 0.5f; // <--- init 0.5, 0, 0.5
void MyDisplay() {
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(red, green, blue); // <----- red, green, blue
// [...]
}
Add glutPostRedisplay to the menu event call back, which is executed when the color is changed:
void MySubMenu2(int entryID)
{
switch (entryID) {
case RED: red = 1.0; green = 0.0; blue = 0.0; break;
case GREEN: red = 0.0; green = 1.0; blue = 0.0; break;
case BLUE: red = 0.0; green = 0.0; blue = 1.0; break;
}
glutPostRedisplay(); // <---- this is missing
}
I want every cube to have a random color but with this code the colors keep changing all the time
int espacioX = -500;
int espacioY = -500;
for(int i=1; i<=100; i++){
for(int j=1; j<=100; j++){
randomR = (double)rand() / (RAND_MAX);
randomG = (double)rand() / (RAND_MAX);
randomB = (double)rand() / (RAND_MAX);
glColor3f(randomR,randomG,randomB);
glTranslatef(espacioX,espacioY,0);
glutSolidCube(9);
glTranslatef(-espacioX,-espacioY,0);
espacioX+=10;
}
glTranslatef(-1000,0,0);
espacioY+=10;
}
How do I make them stay in the same color while the program is running?
Edit:
This is the comple code:
#include <windows.h>
/***** OpenGL library imports. *****/
#include<gl\glut.h> //basic header file for OpenGL
//#include <gl\glaux.h> // Header File For The Glaux Library
/***** C library imports. *****/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int ScreenWidth = 0;
int ScreenHeight = 0;
int last_x = 0, last_y = 0,left = 1,middle = 0,right = 0;
int zoom_y = 0;
int anglex=0, angley=0, anglez=0;
int lookfrom=450;
int ang=0;
void myGlutKeyboard(unsigned char Key, int x, int y)
{
printf("%5d\n",Key);
glutPostRedisplay();
}
void init_GL_params()
{
static GLfloat light_ambient[] = { .250, .250, .250, .250 };
static GLfloat light_diffuse[] = { .250, .250, .25, .250 };
static GLfloat light_specular[] = { .250, .250, .250, .250 };
static GLfloat light1_diffuse[] = { .250, .250, .250, .0 };
static GLfloat light1_specular[] = { .250, .250, .250, .0 };
glEnable (GL_LIGHTING);
glEnable (GL_LIGHT0);
glEnable (GL_LIGHT1);
glDisable (GL_TEXTURE_2D);
glDisable (GL_TEXTURE_GEN_S);
glDisable (GL_TEXTURE_GEN_T);
glShadeModel (GL_FLAT);
glEnable (GL_DEPTH_TEST);
glDepthFunc (GL_LESS);
glEnable (GL_CULL_FACE);
glCullFace (GL_BACK);
glFrontFace (GL_CCW);
glMatrixMode (GL_PROJECTION);
glLoadIdentity();
glLightfv (GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv (GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv (GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT1, GL_DIFFUSE, light1_diffuse);
glLightfv(GL_LIGHT1, GL_SPECULAR, light1_specular);
glLightfv (GL_LIGHT1, GL_AMBIENT, light_ambient);
glColor3f (1.0, 1.0, 1.0);
}
void setLightPosition()
{
static GLfloat light_position[] = { 100, 200.0, 10, 1.0 };
static GLfloat light1_position[] = { -0.0, 300.0, 0.0, 1.0 };
// set the light position (for some reason we have to do this in model view.
glLightfv (GL_LIGHT0, GL_POSITION, light_position);
glLightfv(GL_LIGHT1, GL_POSITION, light1_position);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glEnable(GL_COLOR_MATERIAL);
}
void myGlutDisplay(void)
{
init_GL_params();
// clear the window
glClearColor (0,0,0,0); //Color de fondo R G B
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity();
setLightPosition(); //Posici{on de la fuente de luz
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluPerspective(60.0f, 1.0, 1.0f, 10000.0f);
gluLookAt( //punto de vista
0 ,100 ,lookfrom , // desde donde veo xyz
0, 0, 0, // hacia donde veo xyz
0,1,0 );
glRotatef(anglex, 1.0, 0.0, 0.0);
glRotatef(angley, 0.0, 1.0, 0.0);
glRotatef(anglez, 0.0, 0.0, 1.0);
//Empieza a dibujar
int espacioX = 500;
int espacioY = 500;
double randomR, randomG, randomB;
for(int i=1; i<=100; i++){
for(int j=1; j<=100; j++){
randomR = (double)rand() / (RAND_MAX);
randomG = (double)rand() / (RAND_MAX);
randomB = (double)rand() / (RAND_MAX);
glColor3f(randomR,randomG,randomB);
glTranslatef(espacioX,espacioY,0);
glutSolidCube(9);
glTranslatef(-espacioX,-espacioY,0);
espacioX-=10;
}
glTranslatef(1000,0,0);
espacioY-=10;
}
glFlush(); // Flush The GL Pipeline
glutSwapBuffers();
}
void myGlutReshape2(int mWidth, int mHeight)
{
ScreenWidth = mWidth;
ScreenHeight = mHeight;
glViewport(0, 0, (GLsizei) ScreenWidth, (GLsizei) ScreenHeight);
glutPostRedisplay();
}
/****************************************************************/
void myGlutIdle(void)
{
glutPostRedisplay();
}
/***************************************************************/
void myGlutMouse(int button, int button_state, int x, int y){
if ( (button == GLUT_LEFT_BUTTON) && (button_state == GLUT_DOWN) )
{
last_x = x;
last_y = y;
left = 1;
middle = 0;
right = 0;
}
else if ((button == GLUT_RIGHT_BUTTON) && (button_state == GLUT_DOWN) )
{
zoom_y = y;
right = 1;
left = 0;
middle = 0;
}
}
void myGlutMotion(int x, int y){
if (left){
anglex+= (float) (y - last_y);
angley+= (float) (x - last_x);
last_x = x;
last_y = y;
}
if (right)
{
lookfrom += (y - zoom_y);
zoom_y = y;
}
}
void GlutInit(int argc, char** argv)
{
ScreenWidth = 700;
ScreenHeight = 700;
/****************************************/
/* Initialize GLUT and create window */
/****************************************/
glutInit(&argc, argv);
glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE | GLUT_STENCIL ); //set up the display as a double buffer using RGB values
glutInitWindowPosition(90, 50); //set the position of where you want the window to open
glutInitWindowSize(ScreenWidth, ScreenHeight); //set how big you want the initial window to be
glutCreateWindow("Testing Virtual Environment" ); //what do you want the window to be called (titlebar text)
//register callbacks
glutDisplayFunc(myGlutDisplay); //Register the display callback
glutReshapeFunc(myGlutReshape2); // -- Resize handler
glutKeyboardFunc(myGlutKeyboard); // -- Keyboard handler
glutMouseFunc(myGlutMouse); // -- Mouse Click handler
glutMotionFunc(myGlutMotion); // -- Mous motion handler
glutIdleFunc(myGlutIdle); // -- Idle handler
glFlush();
}
int main( int argc, char **argv )
{
GlutInit(argc, argv);
glutMainLoop();
return 0;
}
It was a sample code so I just posted the part that I edited, sorry. When I did a cube or a sphere with an specific color it always stayed the same so i didn't realiza that this refresh the image all the time. I don't really understand the whole thing so I don't know where it's refreshing the image.
Why not set SEED to some constant value at start of myGlutDisplay(void). That will give you the same random values each frame without any big change in your code for example like this:
void myGlutDisplay(void)
{
init_GL_params();
// clear the window
glClearColor (0,0,0,0); //Color de fondo R G B
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity();
setLightPosition(); //Posici{on de la fuente de luz
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluPerspective(60.0f, 1.0, 1.0f, 10000.0f);
gluLookAt( //punto de vista
0 ,100 ,lookfrom , // desde donde veo xyz
0, 0, 0, // hacia donde veo xyz
0,1,0 );
glRotatef(anglex, 1.0, 0.0, 0.0);
glRotatef(angley, 0.0, 1.0, 0.0);
glRotatef(anglez, 0.0, 0.0, 1.0);
//Empieza a dibujar
int espacioX = 500;
int espacioY = 500;
double randomR, randomG, randomB;
srand(0x98765432); // this is the SEED
for(int i=1; i<=100; i++){
for(int j=1; j<=100; j++){
randomR = (double)rand() / (RAND_MAX);
randomG = (double)rand() / (RAND_MAX);
randomB = (double)rand() / (RAND_MAX);
glColor3f(randomR,randomG,randomB);
glTranslatef(espacioX,espacioY,0);
glutSolidCube(9);
glTranslatef(-espacioX,-espacioY,0);
espacioX-=10;
}
glTranslatef(1000,0,0);
espacioY-=10;
}
glFlush(); // Flush The GL Pipeline
glutSwapBuffers();
}
The value of the SEED will give you the pattern. So changing the constant will change the colors. Beware wrong constant (like 0) can corrupt the randomness of the rand() function.
It seems like you are running this code inside another loop which means you are calculating your random variables every time the scene is redrawn, this would cause the colors to change and the obvious solution would be to poulate your list of cubes once and then iterate through the list drawing the cubes on each scene refresh.
However, without seeing the rest of your code it is unclear. Please include more information so we can give you a better answer.
I am doing a mini project on constructive solid geometry using openGL.I am trying to create two windows ,the first one shows my name,college name and other details and the second one will show the solid geometry window.My second screen is working perfectly fine,and i am able to print text on my first screen,but as the background is black in color and text should come in different colors but it's coming in black color only so it's not visible.Below is the code,can anyone check my code and tell me where's the error.
#include<GL/glut.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<GL/gl.h>
int isMainScreen=1;
enum {
CSG_A, CSG_B, CSG_A_OR_B, CSG_A_AND_B, CSG_A_SUB_B, CSG_B_SUB_A
};
/* just draw single object */
void one(void (*a) (void))
{
glEnable(GL_DEPTH_TEST);
a();
glDisable(GL_DEPTH_TEST);
}
/* "or" is easy; simply draw both objects with depth buffering on */
void or(void (*a) (void), void (*b) (void))
{
glEnable(GL_DEPTH_TEST);
a();
b();
glDisable(GL_DEPTH_TEST);
}
/* Set stencil buffer to show the part of a (front or back face) that's inside b's volume. Requirements: GL_CULL_FACE enabled, depth func GL_LESS Side effects: depth test, stencil func, stencil op */
void
firstInsideSecond(void (*a) (void), void (*b) (void), GLenum face, GLenum test)
{
glEnable(GL_DEPTH_TEST);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
glCullFace(face); /* controls which face of a to use */
a(); /* draw a face of a into depth buffer */
/* use stencil plane to find parts of a in b */
glDepthMask(GL_FALSE);
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_ALWAYS, 0, 0);
glStencilOp(GL_KEEP, GL_KEEP, GL_INCR);
glCullFace(GL_BACK);
b(); /* increment the stencil where the front face of b is drawn */
glStencilOp(GL_KEEP, GL_KEEP, GL_DECR);
glCullFace(GL_FRONT);
b(); /* decrement the stencil buffer where the back face of b is drawn */
glDepthMask(GL_TRUE);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
glStencilFunc(test, 0, 1);
glDisable(GL_DEPTH_TEST);
glCullFace(face);
a(); /* draw the part of a that's in b */
}
void
fixDepth(void (*a) (void))
{
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
glEnable(GL_DEPTH_TEST);
glDisable(GL_STENCIL_TEST);
glDepthFunc(GL_ALWAYS);
a(); /* draw the front face of a, fixing the depth buffer */
glDepthFunc(GL_LESS);
}
/* "and" two objects together */
void
and(void (*a) (void), void (*b) (void))
{
firstInsideSecond(a, b, GL_BACK, GL_NOTEQUAL);
fixDepth(b);
firstInsideSecond(b, a, GL_BACK, GL_NOTEQUAL);
glDisable(GL_STENCIL_TEST); /* reset things */
}
/* subtract b from a */
void
sub(void (*a) (void), void (*b) (void))
{
firstInsideSecond(a, b, GL_FRONT, GL_NOTEQUAL);
fixDepth(b);
firstInsideSecond(b, a, GL_BACK, GL_EQUAL);
glDisable(GL_STENCIL_TEST); /* reset things */
}
enum {
SPHERE = 1, CONE
};
/* Draw a cone */
GLfloat coneX = 0.f, coneY = 0.f, coneZ = 0.f;
void
cone(void)
{
glPushMatrix();
glTranslatef(coneX, coneY, coneZ);
glTranslatef(0.f, 0.f, -30.f);
glCallList(CONE);
glPopMatrix();
}
/* Draw a sphere */
GLfloat sphereX = 0.f, sphereY = 0.f, sphereZ = 0.f;
void
sphere(void)
{
glPushMatrix();
glTranslatef(sphereX, sphereY, sphereZ);
glCallList(SPHERE);
glPopMatrix();
}
int csg_op = CSG_A;
/* add menu callback */
void
menu(int csgop)
{
csg_op = csgop;
glutPostRedisplay();
}
GLfloat viewangle;
void redraw(void)
{
/* clear stencil each time */
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);
glPushMatrix();
glRotatef(viewangle, 0.f, 1.f, 0.f);
switch (csg_op) {
case CSG_A: one(cone);
break;
case CSG_B: one(sphere);
break;
case CSG_A_OR_B: or(cone, sphere);
break;
case CSG_A_AND_B: and(cone, sphere);
break;
case CSG_A_SUB_B: sub(cone, sphere);
break;
case CSG_B_SUB_A: sub(sphere, cone);
break;
}
glPopMatrix();
glutSwapBuffers();
}
/* animate scene by rotating */
enum {
ANIM_LEFT, ANIM_RIGHT
};
int animDirection = ANIM_LEFT;
void
anim(void)
{
if (animDirection == ANIM_LEFT)
viewangle -= 3.f;
else
viewangle += 3.f;
glutPostRedisplay();
}
/* ARGSUSED1 */
/* special keys, like array and F keys */
void
special(int key, int x, int y)
{
switch (key) {
case GLUT_KEY_LEFT: glutIdleFunc(anim);
animDirection = ANIM_LEFT;
break;
case GLUT_KEY_RIGHT: glutIdleFunc(anim);
animDirection = ANIM_RIGHT;
break;
case GLUT_KEY_UP:
case GLUT_KEY_DOWN:
glutIdleFunc(0);
break;
}
}
/* ARGSUSED1 */
void
key(unsigned char key, int x, int y)
{
switch (key) {
case 'a': viewangle -= 10.f;
glutPostRedisplay();
break;
case 's':
viewangle += 10.f;
glutPostRedisplay();
break;
case '\13':
isMainScreen=1;
break;
mydisplay();
case '\033':
exit(0);
}
}
int picked_object;
int xpos = 0, ypos = 0;
int newxpos, newypos;
int startx, starty;
void
mouse(int button, int state, int x, int y)
{
if (state == GLUT_UP) {
picked_object = button;
xpos += newxpos;
ypos += newypos;
newxpos = 0;
newypos = 0;
} else { /* GLUT_DOWN */
startx = x;
starty = y;
}
}
#define DEGTORAD (2 * 3.1415 / 360)
void
motion(int x, int y)
{
GLfloat r, objx, objy, objz;
newxpos = x - startx;
newypos = starty - y;
r = (newxpos + xpos) * 50.f / 512.f;
objx = r * cos(viewangle * DEGTORAD);
objy = (newypos + ypos) * 50.f / 512.f;
objz = r * sin(viewangle * DEGTORAD);
switch (picked_object) {
case CSG_A:
coneX = objx;
coneY = objy;
coneZ = objz;
break;
case CSG_B:
sphereX = objx;
sphereY = objy;
sphereZ = objz;
break;
}
glutPostRedisplay();
}
void drawString1(float x, float y, float z, char * string) {
char * c;
glRasterPos3f(x, y, z);
for (c = string; * c != '\0'; c++) {
glutBitmapCharacter(GLUT_BITMAP_9_BY_15, * c);
}
}
double vp_width = 512.0; // update by reshape
double vp_height = 512.0; // update by reshape
void frontscreen(void)
{
glDisable(GL_LIGHTING);
glMatrixMode( GL_PROJECTION );
glPushMatrix();
glLoadIdentity();
glOrtho( 0, vp_width, vp_height, 0.0, -1.0, 1.0 );
glMatrixMode( GL_MODELVIEW );
glPushMatrix();
glLoadIdentity();
glColor3f(0.7,0.0,1.0);
drawString1(200.0,50.0,0.0,"MVJ College of Engineering");
glColor3f(0.7,0.0,1.0);
drawString1(165.0,90.0,0.0,"DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING");
glColor3f(1.0,0.5,0.6);
drawString1(185.0,130.0,0.0,"A MINI PROJECT ON:COMPUTER GRAPHICS");
glColor3f(1,0,0);
drawString1(175.0,170.0,0.0,"PROJECT TITLE:CONSTRUCTIVE SOLID GEOMETRY");
glColor3f(1,0.5,0);
drawString1(20,380,0.0,"BY:");
glColor3f(0.5,0,0.5);
drawString1(10,410,0.0,"NAME: ANSHU");
glColor3f(0.5,0,0.5);
drawString1(10,425,0.0,"USN:1MJ15CS016");
glColor3f(0.5,0,0.5);
drawString1(10,440,0.0,"SEC:A");
glColor3f(0.5,0,0.5);
drawString1(10,455,0.0,"SEMESTER:VI");
glColor3f(1,0.5,0);
drawString1(420,380,0.0,"GUIDE:");
glColor3f(0.5,0,0.5);
drawString1(390,400,0.0,"NAME:Ms. Devisivashankari p");
glColor3f(1,0.1,1);
drawString1(200,480,0.0,"PRESS ENTER TO START");
glMatrixMode( GL_PROJECTION );
glPopMatrix();
glMatrixMode( GL_MODELVIEW );
glPopMatrix();
glutSwapBuffers(); // <----- glutSwapBuffers insted of glFlush
glutPostRedisplay();
}
void mydisplay() {
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
if (isMainScreen) {
frontscreen();
} else {
redraw();
}
}
int main(int argc, char **argv)
{
static GLfloat lightpos[] =
{25.f, 50.f, -50.f, 1.f};
static GLfloat sphere_mat[] =
{1.f, .5f, 0.f, 1.f};
static GLfloat cone_mat[] =
{0.f, .5f, 1.f, 1.f};
GLUquadricObj *sphere, *cone, *base;
glutInit(&argc, argv);
glutInitWindowSize(1024,720);
glutInitDisplayMode(GLUT_STENCIL | GLUT_DEPTH | GLUT_DOUBLE);
(void) glutCreateWindow("csg");
glutDisplayFunc(frontscreen);
glutKeyboardFunc(key);
glutSpecialFunc(special);
glutMouseFunc(mouse);
glutMotionFunc(motion);
glutCreateMenu(menu);
glutAddMenuEntry("A only", CSG_A);
glutAddMenuEntry("B only", CSG_B);
glutAddMenuEntry("A or B", CSG_A_OR_B);
glutAddMenuEntry("A and B", CSG_A_AND_B);
glutAddMenuEntry("A sub B", CSG_A_SUB_B);
glutAddMenuEntry("B sub A", CSG_B_SUB_A);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glEnable(GL_CULL_FACE);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_POSITION, lightpos);
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
/* make display lists for sphere and cone; for efficiency */
glNewList(SPHERE, GL_COMPILE);
sphere = gluNewQuadric();
glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,sphere_mat);
gluSphere(sphere, 20.f, 64, 64);
gluDeleteQuadric(sphere);
glEndList();
glNewList(CONE, GL_COMPILE);
cone = gluNewQuadric();
base = gluNewQuadric();
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, cone_mat);
gluQuadricOrientation(base, GLU_INSIDE);
gluDisk(base, 0., 15., 64, 1);
gluCylinder(cone, 15., 0., 60., 64, 64);
gluDeleteQuadric(cone);
gluDeleteQuadric(base);
glEndList();
glMatrixMode(GL_PROJECTION);
glOrtho(-50., 50., -50., 50., -50., 50.);
glMatrixMode(GL_MODELVIEW);
glutMainLoop();
return 0; /* ANSI C requires main to return int. */
}
frontscreen method is the first screen which should come.
i am able to print text on my first screen,but as the background is black in color and text should come in different colors but it's coming in black color only so it's not visible
When lighting (GL_LIGHTING) is enabled, then the color is taken from the material parameters (glMaterial).
If you still want to use the current color, the you have to enable GL_COLOR_MATERIAL
and to set the color material paramters (glColorMaterial):
glEnable( GL_COLOR_MATERIAL );
glColorMaterial( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE );
See also Basic OpenGL Lighting.
I recommend to disable lighting when you draw the text:
void frontscreen(void)
{
glDisable( GL_LIGHTING );
.....
}
But to enable lighting when you draw the scene:
void redraw(void)
{
glEnable( GL_LIGHTING );
.....
}
I have an openGL program thats using GLUT and I'm stuck with moving it from the top left corner to bottom right when i resize the window. I'm trying to get a ratio down and i cant figure it out.
#include <stdio.h>
#include <stdlib.h>
#include <GLUT/glut.h>
//global variables
GLsizei wh = 500, ww = 500;
double height;
double width;
double top = 500;
double bottom = 450;
int right = 50;
int left = 0;
double ratiowidth = 500/500;
double ratioheight = 500/500;
void myinit(){
glClearColor (0.0, 0.0, 0.0, 0.0);
}
void reshape(int w, int h){
if(h == 0){
h = 1;
}
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, (GLsizei) w, 0, (GLsizei)h);
glViewport(0,0,w,h);
glMatrixMode(GL_MODELVIEW);
int difference = h - wh;
int difference2 = w - ww;
left = left + difference2;
right = right + difference2;
wh = (GLsizei)h;
ww = (GLsizei)w;
height = h;
width = w;
}
void mouse(int button, int state, int x, int y){
if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN){
top = height;
bottom = height - 50;
right = 50;
left = 0;
ratiowidth = width/height;
ratioheight = height/width;
}
if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN){
exit(0);
}
}
void display(){
glClear (GL_COLOR_BUFFER_BIT);
glColor3i (rand(), rand(), rand());
glBegin(GL_POLYGON);
glVertex3f (left,top,0.0);
glVertex3f (right, top, 0.0);
glVertex3f (right, bottom, 0.0);
glVertex3f (left, bottom, 0.0);
glEnd();
if(bottom == 0 || bottom < 0)
bottom = 0;
else{
left = left + ratiowidth;
right = right + ratiowidth;
top = top - ratioheight;
bottom = bottom - ratioheight;
}
glutSwapBuffers();
usleep(10000);
glutPostRedisplay();
}
int main(int argc, char** argv) {
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(ww, wh);
glutInitWindowPosition(100,100);
glutCreateWindow("moving Square");
myinit();
glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutMainLoop();
return 0;
}
glBegin(GL_POLYGON);
glVertex3f (left,top,0.0);
glVertex3f (right, top, 0.0);
glVertex3f (right, bottom, 0.0);
glVertex3f (left, bottom, 0.0);
glEnd();
Careful with your winding order. glFrontFace() defaults to GL_CCW. Perhaps you meant this:
glBegin(GL_POLYGON);
glVertex3f (left, bottom, 0.0);
glVertex3f (right, bottom, 0.0);
glVertex3f (right, top, 0.0);
glVertex3f (left,top,0.0);
glEnd();
EDIT: This is what I think you were trying to do:
#include <GL/glut.h>
struct State
{
double x; // in units
double y;
double xvel; // in units per second
double yvel;
};
State curState = { 0 };
void myinit()
{
curState.xvel = 100;
curState.yvel = 100;
}
void Integrate( State* state, double dt )
{
state->x += state->xvel * dt;
state->y += state->yvel * dt;
}
double GetSeconds()
{
return glutGet(GLUT_ELAPSED_TIME) / 1000.0f;
}
void reshape(int w, int h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, (GLsizei)w, 0, (GLsizei)h);
}
void mouse(int button, int state, int x, int y)
{
if(button == GLUT_LEFT_BUTTON && state == GLUT_UP)
{
curState.x = 0;
curState.y = 0;
}
if(button == GLUT_RIGHT_BUTTON && state == GLUT_UP)
{
exit(0);
}
}
void display()
{
glClearColor (0.0, 0.0, 0.0, 0.0);
glClear (GL_COLOR_BUFFER_BIT);
float w = 20;
float h = 20;
float x = curState.x;
float y = curState.y;
glColor3ub(rand()%255, rand()%255, rand()%255);
glBegin(GL_QUADS);
glVertex2f( x - w/2, y - h/2 );
glVertex2f( x + w/2, y - h/2 );
glVertex2f( x + w/2, y + h/2 );
glVertex2f( x - w/2, y + h/2 );
glEnd();
static double lastTime = GetSeconds();
double curTime = GetSeconds();
Integrate( &curState, curTime - lastTime );
lastTime = curTime;
glutSwapBuffers();
}
void timer(int extra)
{
glutPostRedisplay();
glutTimerFunc(16, timer, 0);
}
int main(int argc, char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100,100);
glutCreateWindow("moving Square");
myinit();
glutReshapeFunc(reshape);
glutTimerFunc(0, timer, 0);
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutMainLoop();
return 0;
}
Be aware that there are probably some C++-isms in there :)
I created a 5 face box and put a ball inside of it and allowed it to bounce around inside the box. I created this using glOrtho.
I want to create a 3d Brick breaker style game for my course so I want to get my camera down into the box. I changed from glOrtho to gluPerspective. I had to change some values for my box to render correctly but the ball seems to have gone missing unless i put it on the origin.
This is my value initialization:
void variableInits(){
//Floor Plane
pl1.pos.x = 0; pl1.pos.y = -50; pl1.pos.z = 0;
pl1.norm.x = 0; pl1.norm.y = 1; pl1.norm.z = 0;
//Ceiling Plane
pl2.pos.x = 0; pl2.pos.y = 50; pl2.pos.z = 0;
pl2.norm.x = 0; pl2.norm.y = -1; pl2.norm.z = 0;
//Right Wall Plane
pl3.pos.x = 50; pl3.pos.y = 0; pl3.pos.z = 0;
pl3.norm.x = -1; pl3.norm.y = 0; pl3.norm.z = 0;
//Left Wall Plane
pl4.pos.x = -50; pl4.pos.y = 0; pl4.pos.z = 0;
pl4.norm.x = 1; pl4.norm.y = 0; pl4.norm.z = 0;
//Back Wall Plane
pl5.pos.x = 0; pl5.pos.y = 0; pl5.pos.z = -100;
pl5.norm.x = 0; pl5.norm.y = 0; pl5.norm.z = 1;
//Paddle Plane
paddlePlane.max.x=.25; paddlePlane.max.y=.25; paddlePlane.max.z=1;
paddlePlane.min.x=-.25; paddlePlane.min.y=-.25; paddlePlane.min.z=1;
paddlePlane.normals.x=0; paddlePlane.normals.y=0;paddlePlane.normals.z=-0;
//Ball Init
b1.radius = 10;
b1.pathDirection.x = 0; b1.pathDirection.y = 0; b1.pathDirection.z = 0;
b1.pos.x = 0; b1.pos.y = 0, b1.pos.z = -25;
}
So my ball should draw with a radius of 10 on -25 value of the Z axis. Sadly it does not.
Maybe its an issue with my gluPerspective call?
void reshape(int width, int height)
{
if (height==0)
{
height=1;
}
glViewport(0,0,width,height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.0f,50.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
Ill go ahead and post my complete code but it is a bit long.
#include <stdio.h>
#include <gl/glut.h>
#include "pHeader.h"
#define EPSILON 1.0e-8
#define ZERO EPSILON
int g_mainWindow = -1;
float g_lightPos[] = {0, 0, 0, -50};
int angle = 0;
int g_moving;
int g_mouse_x;
int g_mouse_y;
int g_x_angle;
int g_y_angle;
double mX,mY,mZ;
float speed = 1;
plane pl1, pl2, pl3, pl4 ,pl5;
paddlePl paddlePlane;
float collDist = 1000;
ball b1;
void mouse(int button, int state, int x, int y)
{
if (button == GLUT_LEFT_BUTTON && state==GLUT_DOWN)
{
g_moving = 1;
g_mouse_x = x;
g_mouse_y = y;
}
else {
g_moving = 0;
}
}
void mouseDrag(int x, int y)
{
int dx, dy;
if (g_moving){
dx = x - g_mouse_x;
dy = y - g_mouse_y;
g_x_angle += dy;
g_y_angle += dx;
g_mouse_x = x;
g_mouse_y = y;
}
}
void paddle(int x, int y){
GLint viewport[4];
GLdouble modelview[16],projection[16];
glGetIntegerv(GL_VIEWPORT,viewport);
glGetDoublev(GL_MODELVIEW_MATRIX,modelview);
glGetDoublev(GL_PROJECTION_MATRIX,projection);
gluUnProject(x,viewport[3]-y,0,modelview,projection,viewport,&mX,&mY,&mZ);
}
/*************************************************
Vector Math
**************************************************/
float dot(vector XYZ , vector nXYZ){
return (XYZ.x * nXYZ.x) + (XYZ.y * nXYZ.x) + (XYZ.z * nXYZ.z);
}
vector cross(vector v1 , vector v2){
vector result;
result.x = v1.y * v2.z - v1.z * v2.y;
result.y = v1.z * v2.x - v1.x * v2.z;
result.z = v1.x * v2.y - v1.y * v2.x;
return result;
}
vector vectScale(float scale, vector v1){
vector result;
result.x = v1.x * scale;
result.y = v1.y * scale;
result.z = v1.z * scale;
return result;
}
vector vectorSub(vector v1, vector v2){
vector result;
result.x = v1.x - v2.x;
result.y = v1.y - v2.y;
result.z = v1.z - v2.y;
return result;
}
vector flipVect(vector v1){
vector result;
result.x = -v1.x;
result.y = -v1.y;
result.z = -v1.z;
return result;
}
vector vectorAdd(vector v1, vector v2){
vector result;
result.x = v1.x + v2.x;
result.y = v1.y + v2.y;
result.z = v1.z + v2.z;
return result;
}
/****************************************************
End Vecotor Math
****************************************************/
void planeCollision(){
//Check Ceiling
if(b1.pos.y + b1.radius >= 50){
b1.pathDirection = vectorAdd((2 * dot(flipVect(b1.pathDirection), pl2.norm) , pl2.norm) , b1.pathDirection);
}
//Check Floor
if(b1.pos.y-b1.radius <= -50){
b1.pathDirection = vectorAdd((2 * dot(flipVect(b1.pathDirection), pl1.norm) , pl1.norm) , b1.pathDirection);
}
//Check Right Wall
if(b1.pos.x + b1.radius >= 1){
b1.pathDirection = vectorAdd((2 * dot(flipVect(b1.pathDirection), pl3.norm) , pl3.norm) , b1.pathDirection);
}
//Check Left Wall
if(b1.pos.x - b1.radius <= -1){
b1.pathDirection = vectorAdd((2 * dot(flipVect(b1.pathDirection), pl4.norm) , pl4.norm) , b1.pathDirection);
}
//Check Back Wall
if(b1.pos.z - b1.radius <= -1){
b1.pathDirection = vectorAdd((2 * dot(flipVect(b1.pathDirection), pl5.norm) , pl5.norm) , b1.pathDirection);
}
//Check paddle
if(b1.pos.z + b1.radius >= paddlePlane.max.z && b1.pos.x >= paddlePlane.min.x && b1.pos.x <= paddlePlane.max.x && b1.pos.y >= paddlePlane.min.y && b1.pos.y <= paddlePlane.max.y){
b1.pathDirection = vectorAdd((2 * dot(flipVect(b1.pathDirection), paddlePlane.normals) , paddlePlane.normals) , b1.pathDirection);
}
}
void drawPlanes(){
glBegin(GL_QUADS);
//Floor
glColor3f(1,0,0);
glNormal3f( 0.0f , 1.0f, 0.0f);
glVertex3f( 050.0f , -050.0f , -100.0f);
glVertex3f(-050.0f , -050.0f , -100.0f);
glVertex3f(-050.0f , -050.0f , 000.0f);
glVertex3f( 050.0f , -050.0f , 000.0f);
//Ceiling
glColor3f(1,0,1);
glNormal3f(0.0f,-1.0f,0.0f);
glVertex3f( 050.0f, 050.0f, -100.0f);
glVertex3f(-050.0f, 050.0f, -100.0f);
glVertex3f(-050.0f, 050.0f, 000.0f);
glVertex3f( 050.0f, 050.0f, 000.0f);
//Right Wall
glColor3f(0,1,0);
glNormal3f( -1.0f , 0.0f, 0.0f);
glVertex3f(050.0f , 050.0f , 000.0f);
glVertex3f(050.0f , 050.0f , -100.0f);
glVertex3f(050.0f ,-050.0f , -100.0f);
glVertex3f(050.0f ,-050.0f, 000.0f);
//LeftWall
glColor3f(0,1,1);
glNormal3f( 1.0f , 0.0f, 0.0f);
glVertex3f(-050.0f , 050.0f , -100.0f);
glVertex3f(-050.0f , 050.0f , 000.0f);
glVertex3f(-050.0f , -050.0f , 000.0f);
glVertex3f(-050.0f , -050.0f , -100.0f);
//Back Wall
glColor3f(0,0,1);
glNormal3f( 0.0f , 0.0f, 1.0f);
glVertex3f( 050.0f , 050.0f , -100.0f);
glVertex3f(-050.0f , 050.0f , -100.0f);
glVertex3f(-050.0f , -050.0f , -100.0f);
glVertex3f( 050.0f , -050.0f , -100.0f);
glEnd();
}
void ballMove(){
glPushMatrix();
glColor3f(1,1,0);
b1.pos.x += (b1.pathDirection.x * speed); b1.pos.y += (b1.pathDirection.y * speed); b1.pos.z += (b1.pathDirection.z * speed);
glTranslatef(b1.pos.x,b1.pos.y,b1.pos.z);
glutSolidSphere(b1.radius,100,100);
printf("%.2f %.2f %.2f\n", b1.pos.x, b1.pos.y, b1.pos.z);
glPopMatrix();
planeCollision();
}
void drawPaddle(){
//printf("x %f y %f\n" , mX , mY);
glPushMatrix();
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE);
glBegin(GL_QUADS);
glColor3f(1,1,1);
glVertex3f(mX + 25.0f , mY + 25.0f , 0.0f);
glVertex3f(mX + -25.0f , mY + 25.0f , 0.0f);
glVertex3f(mX + -25.0f , mY + -25.0f , 0.0f);
glVertex3f(mX + 25.0f , mY + -25.0f , 0.0f);
glEnd();
glPolygonMode( GL_FRONT_AND_BACK, GL_FILL);
glPopMatrix();
paddlePlane.max.x=mX + 0.25f; paddlePlane.max.y=mY + 0.25f; paddlePlane.max.z=1;
paddlePlane.min.x=mX + -0.25f; paddlePlane.min.y=mY + -0.25f; paddlePlane.min.z=1;
}
void display()
{
float red[] = {1,0,0,1};
float blue[] = {0,0,1,1};
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_NORMALIZE);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
glPushMatrix();
glRotated(g_y_angle, 0, 1, 0);
glRotated(g_x_angle,1,0,0);
glTranslated(0,0,-100);
drawPaddle();
ballMove();
drawPlanes();
glPopMatrix();
angle += 1;
glFlush();
glutSwapBuffers();
}
void reshape(int width, int height)
{
if (height==0)
{
height=1;
}
glViewport(0,0,width,height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.0f,50.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void idle()
{
glutSetWindow(g_mainWindow);
glutPostRedisplay();
}
void variableInits(){
//Floor Plane
pl1.pos.x = 0; pl1.pos.y = -50; pl1.pos.z = 0;
pl1.norm.x = 0; pl1.norm.y = 1; pl1.norm.z = 0;
//Ceiling Plane
pl2.pos.x = 0; pl2.pos.y = 50; pl2.pos.z = 0;
pl2.norm.x = 0; pl2.norm.y = -1; pl2.norm.z = 0;
//Right Wall Plane
pl3.pos.x = 50; pl3.pos.y = 0; pl3.pos.z = 0;
pl3.norm.x = -1; pl3.norm.y = 0; pl3.norm.z = 0;
//Left Wall Plane
pl4.pos.x = -50; pl4.pos.y = 0; pl4.pos.z = 0;
pl4.norm.x = 1; pl4.norm.y = 0; pl4.norm.z = 0;
//Back Wall Plane
pl5.pos.x = 0; pl5.pos.y = 0; pl5.pos.z = -100;
pl5.norm.x = 0; pl5.norm.y = 0; pl5.norm.z = 1;
//Paddle Plane
paddlePlane.max.x=.25; paddlePlane.max.y=.25; paddlePlane.max.z=1;
paddlePlane.min.x=-.25; paddlePlane.min.y=-.25; paddlePlane.min.z=1;
paddlePlane.normals.x=0; paddlePlane.normals.y=0;paddlePlane.normals.z=-0;
//Ball Init
b1.radius = 10;
b1.pathDirection.x = 0; b1.pathDirection.y = 0; b1.pathDirection.z = 0;
b1.pos.x = 0; b1.pos.y = 0, b1.pos.z = -25;
}
int main(int ac, char* av[])
{
glutInit(&ac, av);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
g_mainWindow = glutCreateWindow("Hello, glut");
variableInits();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutIdleFunc(idle);
glutMouseFunc(mouse);
glutMotionFunc(mouseDrag);
glutPassiveMotionFunc(paddle);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
glLightfv(GL_LIGHT0, GL_POSITION, g_lightPos);
glShadeModel(GL_SMOOTH);
glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
glClearDepth(1.0f);
glDepthFunc(GL_LEQUAL);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glutMainLoop(); //no return
}
Header
#pragma once
#ifndef pHeader_INCLUDED
#define pHeader_H_INCLUDED
typedef struct vector{
float x,y,z;
}vector;
typedef struct ball{
float radius;
vector pathDirection;
vector pos;
} ball;
typedef struct planeStruc{
vector pos;
vector norm;
} plane;
typedef struct paddlePlane{
vector min;
vector max;
vector normals;
} paddlePl;
#endif
gluPerspective cannot have a value of 0.0 for the near plane, it either generates an error (I'm not sure) or causes some weird infinity math to happen that's certainly not what you want.
You should make the value of the near plane greater than zero, and ideally as large as possible without cutting off things that you want to see. If you make it too small you'll lose a ton of z precision.
Try a value of 0.1 to start with.