Problems when dealing with lighting and shadowing in opengl - c

I am trying to put lights, materials and shadows to my robot arm but unfortunately something weird happens (please compile or see the below picture), now I am still annoying by
1) Not showing correct lighting and reflection properties as well as material properties
2) No shadow painted, although I have done the shadow casting in function "void showobj(void)"
I appreciate if anyone can help, I have already working for it 2 days with no progress :(
The following is my code
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <GL/glut.h>
#include "gsrc.h"
#include <Windows.h>
const double PI = 3.14159265;
// angles to rotate the base, lower and upper arms of the robot arm
static GLfloat theta, phi, psi = 0.0;
//Starting time
double startT;
//Time Diff variable
double dif,startTime,endTime,deltaT;
//define n
double n = 3;
//Set the parameters of the light number one
GLfloat Xs = 35.0;
GLfloat Ys = 35.0;
GLfloat Zs = 35.0;
//Shadow color
GLfloat shadowcolor[] = {0.0,0.0,0.0};
//initialize the window and everything to prepare for display
void init_gl() {
//set display color to white
glClearColor(1,1,1,0);
//clear and enable z-buffer
glClear (GL_DEPTH_BUFFER_BIT);
glEnable (GL_DEPTH_TEST);
//clear display window
glClear(GL_COLOR_BUFFER_BIT);
}
//Draw the base of the robot arm
void draw_base(){
glPushMatrix();
//to create the quadric objects
GLUquadric *qobj,*qobjl,*qobju;
qobj = gluNewQuadric();
qobjl = gluNewQuadric();
qobju = gluNewQuadric();
//set the color of the cylinder
glColor3f(1.0,0.0,0.0);
//Re-position the cylinder (x-z plane is the base)
glRotatef(-90,1.0,0.0,0.0);
//Draw the cylinder
gluCylinder(qobj, 30.0, 30.0, 40.0, 40.0, 40.0);
//Draw the upper disk of the base
gluDisk(qobju,0,30,40,40);
glPushMatrix();
//Change the M(lowdisk<updisk)
glTranslatef(0,0,40);
glColor3f(0,0,0);
//Draw the lower disk of the base
gluDisk(qobjl,0,30,40,40);
glPopMatrix();
glPopMatrix();
}
/***********************Texture Work Starts************************************/
//Load the raw file for texture
/* Global Declarations */
#define IW 256 // Image Width
#define IH 256 // Image Height
//3D array to store image data
unsigned char InputImage [IW][IH][4];
// Read an input image from a .raw file with double
void ReadRawImage ( unsigned char Image[][IH][4] )
{
FILE *fp;
int i, j, k;
char* filename;
unsigned char temp;
filename = "floor.raw";
if ((fp = fopen (filename, "rb")) == NULL)
{
printf("Error (ReadImage) : Cannot read the file!!\n");
exit(1);
}
for ( i=0; i<IW; i++)
{
for ( j=0; j<IH; j++)
{
for (k = 0; k < 3; k++) // k = 0 is Red k = 1 is Green K = 2 is Blue
{
fscanf(fp, "%c", &temp);
Image[i][j][k] = (unsigned char) temp;
}
Image[i][j][3] = (unsigned char) 0; // alpha = 0.0
}
}
fclose(fp);
}
/****************************Texture Work Ends***************************************/
/****************************Light and Shadows***************************************/
void lightsrc(){
GLfloat light1PosType [] = {Xs, Ys, Zs, 1.0};
//GLfloat light2PosType [] = {0.0, 100.0, 0.0, 0.0};
glLightfv(GL_LIGHT1, GL_POSITION, light1PosType);
//glEnable(GL_LIGHT1);
//glLightfv(GL_LIGHT2, GL_POSITION, light2PosType);
//glEnable(GL_LIGHT2);
GLfloat whiteColor[] = {1.0, 1.0, 1.0, 1.0};
GLfloat blackColor[] = {0.0, 0.0, 0.0, 1.0};
glLightfv(GL_LIGHT1, GL_AMBIENT, blackColor);
glLightfv(GL_LIGHT1, GL_DIFFUSE, whiteColor);
glLightfv(GL_LIGHT1, GL_SPECULAR, whiteColor);
glEnable(GL_LIGHT1);
glEnable( GL_LIGHTING );
}
/****************************Light and Shadows work ends***************************************/
//Draw the 2x2x2 cube with center (0,1,0)
void cube(){
glPushMatrix();
glTranslatef(0,1,0);
glutSolidCube(2);
glPopMatrix();
}
//Draw the lower arm
void draw_lower_arm(){
glPushMatrix();
glScalef(15.0/2.0,70.0/2.0,15.0/2.0);//scale half is enough (some part is in the negative side)
cube();
glPopMatrix();
}
//Draw the upper arm
void draw_upper_arm(){
glPushMatrix();
glScalef(15.0/2.0,40.0/2.0,15.0/2.0);//scale half is enough (some part is in the negative side)
cube();
glPopMatrix();
}
void drawCoordinates(){
glBegin (GL_LINES);
glColor3f (1,0,0);
glVertex3f (0,0,0);
glVertex3f (600,0,0);
glColor3f (0,1,0);
glVertex3f (0,0,0);
glVertex3f (0,600,0);
glColor3f (0,0,1);
glVertex3f (0,0,0);
glVertex3f (0,0,600);
glEnd();
}
//To draw the whole robot arm
void drawRobot(){
//Robot Drawing Starts
//Rotate the base by theta degrees
glRotatef(theta,0.0,1.0,0.0);
//Draw the base
draw_base();
//M(B<La)
glTranslatef(0.0,40.0,0.0);
//Rotate the lower arm by phi degree
glRotatef(phi,0.0,0.0,1.0);
//change the color of the lower arm
glColor3f(0.0,0.0,1.0);
//Draw the lower arm
draw_lower_arm();
//M(La<Ua)
glTranslatef(0.0,70.0,0.0);
//Rotate the upper arm by psi degree
glRotatef(psi,0.0,0.0,1.0);
//change the color of the upper arm
glColor3f(0.0,1.0,0.0);
//Draw the upper arm
draw_upper_arm();
//Drawing Finish
glutSwapBuffers();
}
void showobj(void) {
//set the projection and perspective parameters/arguments
GLint viewport[4];
glGetIntegerv( GL_VIEWPORT, viewport );
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective( 45, double(viewport[2])/viewport[3], 0.1, 1000 );
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(-200, 300, 200, 0, 0, 0, 0,1,0 );
// get the rotation matrix from the rotation user-interface
glMultMatrixf(gsrc_getmo() );
//Clear the display and ready to show the robot arm
init_gl();
//put the light source
lightsrc();
//Draw coordinates
drawCoordinates();
//give material properties
GLfloat diffuseCoeff[] = {0.2, 0.4, 0.9, 1.0}; // kdR= 0.2, kdG= 0.4, kdB= 0.9
GLfloat specularCoeff[] = {1.0, 1.0, 1.0, 1.0}; //
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, diffuseCoeff);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specularCoeff);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 100.0 ); // ns= 25
//Draw the ground floor
glColor3f(0.4,0.4,0.4);
glPushMatrix();
glRotatef(90,1,0,0);
glRectf(-500,-500,500,500);
glPopMatrix();
int i,j;
GLfloat M[4][4];
for (i=0; i<4; i++){
for (j=0; j<4; j++){
M[i][j] = 0;
}
M[0][0]=M[1][1]=M[2][2]=1;
M[2][3]=-1.0/Zs;
}
//Start drawing shadow
drawRobot(); // draw the objects
glPushMatrix( ); // save state
glMatrixMode(GL_MODELVIEW);
glTranslatef(Xs, Ys, Zs);// Mwc←s
glMultMatrixf(M[4]);// perspective project
glTranslatef(-Xs, -Ys, -Zs);// Ms←wc
glColor3fv (shadowcolor);
//Draw the robot arm
drawRobot();
glPopMatrix(); // restore state
//Shadow drawing ends
glFlush ();
}
//To animate the robot arm
void animate(void)
{
//get the end time
endTime = timeGetTime();
//float angle;
//calculate deltaT
deltaT = (endTime - startTime); //in msecs
//float test;
float deltaTSecs = deltaT/1000.0f; //in secs
//apply moving equation
psi = (90.0) * 0.50 * (1-cos((deltaTSecs/(n+1)) * PI));
glutPostRedisplay ();
}
void main (int argc, char** argv)
{
glutInit(&argc, argv);
//DOUBLE mode better for animation
// Set display mode.
glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGB);
glutInitWindowPosition( 50, 100 ); // Set top-left display-window position.
glutInitWindowSize( 400, 300 ); // Set display-window width and height.
glutCreateWindow( "Robot arm : my first self-learning opengl program" ); // Create display window.
// Register mouse-click and mouse-move glut callback functions
// for the rotation user-interface.
//Allow user to drag the mouse and view the object
glutMouseFunc( gsrc_mousebutton );
glutMotionFunc( gsrc_mousemove );
//record the starting time
startTime = timeGetTime();
// Display everything in showobj function
glutDisplayFunc(showobj);
//Perform background processing tasks or continuous animation
glutIdleFunc(animate);
glutMainLoop();
}

your screen flashes because you are calling glutSwapBuffers() in drawRobot(). That makes your screen repaint two times, once when you draw the robot, and once more when you draw the shadow. Also, you are missing glPushMatrix() at the beginning of drawRobot() and glPopMatrix() at the end. You need to put it there, otherwise it will affect rendering afterwards (the shadow will move with the upper link of the arm).
Then, you specify the shadow matrix wrong. Let's try this:
int i,j;
GLfloat M[4][4];
for (i=0; i<4; i++){
for (j=0; j<4; j++){
M[i][j] = 0;
}
}
M[0][0]=M[1][1]=M[2][2]=1;
M[2][3]=-1.0/Zs;
drawRobot(); // draw the objects
//Start drawing shadow
glEnable(GL_CULL_FACE);
glDisable(GL_LIGHTING); // want constant-color shadow
glPushMatrix( ); // save state
glMatrixMode(GL_MODELVIEW);
glTranslatef(Xs, Ys, Zs);// Mwc←s
glMultMatrixf(&M[0][0]);// perspective project
glTranslatef(-Xs, -Ys, -Zs);// Ms←wc
glColor3fv (shadowcolor);
//Draw the robot arm
drawRobot();
glPopMatrix(); // restore state
glDisable(GL_CULL_FACE);
glEnable(GL_LIGHTING); // enable again ...
//Shadow drawing ends
Also, you can see i've added GL_CULL_FACE arround the shadow, it is to avoid depth fighting. This more or less fixes it technically.
But still - the shadow position is calculated incorrectly. Let's try looking at projection shadows.
So first, we need to have position for the ground plane and for the light:
float g[] = {0, 1, 0, 0}; // ground plane
float l[] = {20, 300, 50, 1}; // light position and "1"
That is a plane equation and a homogenous light position (normal 3D position, padded with a "1"). Then you throw away your shadow matrix setup (glTranslatef(), glMultMatrixf() and glTranslatef()) and call myShadowMatrix(g, l) instead, so it becomes:
glPushMatrix( ); // save state
glMatrixMode(GL_MODELVIEW);
float g[] = {0, 1, 0, 0}; // ground plane
float l[] = {20, 300, 50, 1}; // light position and "1"
myShadowMatrix(g, l);
glColor3fv (shadowcolor);
//Draw the robot arm
drawRobot();
glPopMatrix(); // restore state
And that mostly does work. There is still a lot of z-fighting going on, and the shadow has four different colors. As for the colors, stop calling glColor3f() in drawRobot(), as for the z-fighting, use this:
glPolygonOffset(-1, -1);
glEnable(GL_POLYGON_OFFSET_FILL);
// before
// draw shadow
glDisable(GL_POLYGON_OFFSET_FILL);
// afterwards
And that makes one nice planar shadows demo :). Cheers ...
sw.

Related

Animate rectangle height increase/decrease?

I want to know how can I make an animation that represents a rectangle with height increase/decrease in OpenGL. I know I'm supposed to use the glScale and glTranslate functions.
Below, I will attach the code that I've worked with so far, where I managed to apply a pretty basic transition of a rectangle.
#include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <stdlib.h>
static GLfloat trans = 0.0;
void init(void)
{
glClearColor(0.2, 0.2, 0.2, 0.2);
glShadeModel(GL_FLAT);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glTranslatef(0.0 , trans, 1.0);
glColor3f(1.0, 1.0, 1.0);
glRectf(-25.0, -25.0, 25.0, 25.0);
glPopMatrix();
glColor3f(0.0, 0.0, 1.0);
glRectf(-15.0, -15.0, 15.0, 15.0);
glutSwapBuffers();
}
void transLeft(void)
{
trans = trans - 0.05;
if (trans < -75)
trans = -75;
glutPostRedisplay();
}
void transRight(void)
{
trans = trans + 0.05;
if (trans > 75)
trans = 75;
glutPostRedisplay();
}
void reshape(int w, int h)
{
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-100.0, 100.0, -100.0, 100.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void mouse(int button, int state, int x, int y)
{
switch (button) {
case GLUT_LEFT_BUTTON:
if (state == GLUT_DOWN)
glutIdleFunc(transLeft);
break;
case GLUT_RIGHT_BUTTON:
if (state == GLUT_DOWN)
glutIdleFunc(transRight);
break;
default:
break;
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow(argv[0]);
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMouseFunc(mouse);
glutMainLoop();
return 0;
}
So you want to have variable height rectangle (based on what?).
Yes glScale(1.0,zoom,1.0) placed directly before or after the line
glTranslatef(0.0 , trans, 1.0);
In your display(void) function will do this. Where zoom is holding your animation state and is starting with value zoom=1.0 and to change size you just increment/decrement like this: zoom*=1.025 or zoom/=1.025.
However its usually better to interchange your hard-coded rectangle vertexes with variable ones based on parameter or time or whatever you want to change this with. That way you can interpolate between min and max rectangle size with parameter without changing the matrices which might pose a problem with other objects if you not careful And also this way provides more convenient control of the animation. For example you have:
glRectf(-25.0, -25.0, 25.0, 25.0);
And want to animate it to size:
glRectf(-25.0, -35.0, 25.0, 35.0);
over time so you can do this like this:
add some global or static variables holding your rectangle sizes and position and animation state:
// x0, y0beg, y0end, x1,y1beg,y1end
float myrec[]={-25.0, -25.0, -35.0, 25.0, 25.0, 35.0};
float t=0.0; // parameter in range <0.0,1.0>
in display compute your rectangle actual coordinates and render
You can use linear interpolation like this:
glRectf(myrect[0],myrect[1]+((myrect[2]-myrect[1])*t),
myrect[3],myrect[4]+((myrect[5]-myrect[4])*t));
set you t for animation somewhere
Where depends on what you want to achieve... If you have timer or some call that si repeated again and again you can increment the t in it by some step for example:
t+=dt/T;
if (t>1.0) t=1.0; // use t=0.0; if you want to repeat the animation after it finishes
Where dt is the avg time your call is repeated with and T is the time of whole animation finish. I do not use GLUT so I just assume your Display is called repeatedly (for example 60 times per second) and want the animation to finish in 2 sec then:
// dt = 1.0/60
// T = 2.0
t+=(1.0/120.0);
if (t>1.0) t=1.0; // use t=0.0; if you want to repeat the animation after it
You can also use elapsed time (by measuring it by some OS or environment function you have at your disposal I usually use performance timer/counters on windows) from last call instead of dt.
If you have more of such rectangles you can encapsulate this to some function and simply call it with pointer to its myrect values and parameter t for example:
void draw_rect(float *myrec,float t)
{
glRectf(myrect[0],myrect[1]+((myrect[2]-myrect[1])*t),
myrect[3],myrect[4]+((myrect[5]-myrect[4])*t));
}
float rec0[]={-25.0, -25.0, -35.0, 25.0, 25.0, 35.0};
float rec1[]={-15.0, -15.0, -25.0, 15.0, 15.0, 25.0};
float t=0.0; // parameter in range <0.0,1.0>
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glTranslatef(0.0 , trans, 1.0);
glColor3f(1.0, 1.0, 1.0);
draw_rect(rec0,t);
glPopMatrix();
glColor3f(0.0, 0.0, 1.0);
draw_rect(rec1,t);
glutSwapBuffers();
t+=(1.0/120.0);
if (t>1.0) t=0.0;
}

Why is 3D projection in OpenGL working, but leaving a trail behind?

I just did some math from Wikipedia for 3D projection because I noticed they were simple, library not needed. It does work but, the cube leaves a trail behind as it moves. Note that the cube doesn't actually move, I am actually changing the camera position which makes he cube look like it's moving.
There's no need to point out 100 bad practices that I am doing, I'm aware, this is just supposed to be be a quick test.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <glad/glad.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_opengl.h>
#include <math.h>
#include "utils.h"
#include "keys.h"
char p = 1;
typedef struct Vec3 {
float x;
float y;
float z;
} Vec3;
void Mat_iden(float *m, Uint32 s) {
Uint32 i = 0;
Uint32 unt = s + 1;
while (i < s) {
m[unt * i] = 1;
i++;
}
}
float one[3][3];
float two[3][3];
float three[3][3];
int main() {
SDL_Init(SDL_INIT_VIDEO);
IMG_Init(IMG_INIT_PNG);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
SDL_Window *w = SDL_CreateWindow("Snapdoop", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 500, 500, SDL_WINDOW_OPENGL);
SDL_GLContext c = SDL_GL_CreateContext(w);
gladLoadGLLoader((GLADloadproc)SDL_GL_GetProcAddress);
Mat_iden(one[0], 3);
Mat_iden(two[0], 3);
Mat_iden(three[0], 3);
Shader s[2];
s[0] = Shade("/home/shambhav/eclipse-workspace/Snadoop/src/vs.glsl");
s[1] = Shade("/home/shambhav/eclipse-workspace/Snadoop/src/fs.glsl");
Shade_comp(&s[0], GL_VERTEX_SHADER);
Shade_comp(&s[1], GL_FRAGMENT_SHADER);
Program sp;
Prog_attach(&sp, s, 2);
printf("VS: %s\n", s[0].info);
printf("FS: %s\n", s[1].info);
printf("SP: %s\n", sp.info);
glDeleteShader(s[0].c);
glDeleteShader(s[1].c);
float v[48] = {
//Front
0.25, 0.25, 0.25, 1.0, 1.0, 0.0,
-0.25, 0.25, 0.25, 1.0, 0.0, 0.0,
-0.25, -0.25, 0.25, 0.0, 1.0, 1.0,
0.25, -0.25, 0.25, 0.0, 1.0, 0.0,
//Back
0.25, 0.25, -0.25, 0.0, 0.0, 1.0,
-0.25, 0.25, -0.25, 1.0, 0.0, 1.0,
-0.25, -0.25, -0.25, 1.0, 1.0, 1.0,
0.25, -0.25, -0.25, 0.0, 0.0, 0.0
};
unsigned int i[36] = {
//Front
0, 1, 2,
2, 3, 0,
//Right
0, 3, 7,
7, 4, 0,
//Left
1, 2, 6,
6, 5, 2,
//Back
4, 5, 6,
6, 7, 4,
//Up
0, 1, 5,
5, 4, 0,
//Down
3, 7, 2,
2, 6, 7
};
GLuint VAO, VBO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(v), v, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(i), i, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 6, (void *)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 6, (void *)(sizeof(float) * 3));
glEnableVertexAttribArray(1);
Vec3 cam = {1.0, 1.0, 1.0};
Vec3 theta = {0, 0, 0};
Key k = (const Key){ 0 };
printf("%d\n", k.alpha[9]);
SDL_Event e;
while (p) {
while (SDL_PollEvent(&e)) {
switch (e.type) {
case SDL_QUIT:
p = 0;
break;
case SDL_KEYDOWN:
*key(&k, e.key.keysym.sym) = 1;
break;
case SDL_KEYUP:
*key(&k, e.key.keysym.sym) = 0;
break;
}
}
if (*key(&k, SDLK_RIGHT)) {
cam.x += 0.01;
}
if (*key(&k, SDLK_LEFT)) {
cam.x -= 0.01;
}
if (*key(&k, SDLK_UP)) {
cam.y += 0.01;
}
if (*key(&k, SDLK_DOWN)) {
cam.y -= 0.01;
}
if (*key(&k, 'w')) {
theta.y += 0.01;
}
if (*key(&k, 's')) {
theta.y -= 0.01;
}
if (*key(&k, 'a')) {
theta.x -= 0.01;
}
if (*key(&k, 'd')) {
theta.x += 0.01;
}
if (*key(&k, 'z')) {
theta.z -= 0.01;
}
if (*key(&k, 'x')) {
theta.z += 0.01;
}
if (*key(&k, 'n')) {
cam.z += 0.01;
}
if (*key(&k, 'm')) {
cam.z -= 0.01;
}
one[1][1] = cos(theta.x);
one[1][2] = sin(theta.x);
one[2][1] = -sin(theta.x);
one[2][2] = cos(theta.x);
two[0][0] = cos(theta.y);
two[0][2] = -sin(theta.y);
two[2][0] = sin(theta.y);
two[2][2] = cos(theta.y);
three[0][0] = cos(theta.z);
three[0][1] = sin(theta.z);
three[1][0] = -sin(theta.z);
three[1][1] = cos(theta.z);
glUseProgram(sp.p);
glUniformMatrix3fv(2, 1, GL_FALSE, one[0]);
glUniformMatrix3fv(3, 1, GL_FALSE, two[0]);
glUniformMatrix3fv(4, 1, GL_FALSE, three[0]);
glUniform3f(5, cam.x, cam.y, cam.z);
glClear(GL_DEPTH_BUFFER_BIT);
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0);
SDL_GL_SwapWindow(w);
}
glDeleteProgram(sp.p);
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &EBO);
SDL_GL_DeleteContext(c);
SDL_DestroyWindow(w);
SDL_Quit();
return 0;
}
Vertex Shader(vs.glsl):
#version 450 core
layout (location = 0) in vec3 pos;
layout (location = 1) in vec3 tcol;
layout (location = 2) uniform mat3 x;
layout (location = 3) uniform mat3 y;
layout (location = 4) uniform mat3 z;
layout (location = 5) uniform vec3 c;
out vec3 col;
void main() {
vec3 d = x * y * z * (pos - c);
gl_Position.x = d.x / d.z;
gl_Position.y = d.y / d.z;
gl_Position.z = 0.0;
gl_Position.w = 1.0;
col = tcol;
}
Fragment Shader:
#version 450 core
out vec4 color;
in vec3 col;
void main() {
color = vec4(col, 1.0);
}
I think that keys.h and utils.h should not be here as they are not relevant to OpenGL. And this is a Minimum Reproducible Example as the only extra parts(keys.h and utils.h) are required for managing key data and loading shaders respectively.
Some keys in my code may be inverted, it's just bad code in all ways... Sorry for that.
This is an image I have taken after moving the cube(or the camera perspective to be accurate). One major thing to note is that it seems to be working perfectly other than the trail.
You need to clear the color buffer as well:
glClear(GL_DEPTH_BUFFER_BIT);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClear clears the specified buffers. The buffers are specified with a bit mask. GL_COLOR_BUFFER_BIT indicates to clear the buffers currently enabled for color writing.
The short answer is that you need to change:
glClear(GL_DEPTH_BUFFER_BIT);
...to...
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
More details
Comments have asked for more elaboration, so I'll elaborate.
When you say glClear(GL_DEPTH_BUFFER_BIT) it clears out the pixel values in the Z-Buffer (depth buffer). When you say glClear(GL_COLOR_BUFFER_BIT) it clears out the RGBA channels of the pixels in the color buffer (sets them to the glClearColor). If you say glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT) it clears both the Z-Buffer and the color buffer at the same time. That's what you want to do. You want to start each frame with a fresh black background and draw your content for that frame over top of it.
Think of it like setting each pixel to black and setting the depth value to zero. Actually, it will set the color buffer to the color specified by glClearColor and will set the depth value to the value specified by glClearDepth.
In your comment you said that you thought it "clears the functionality". That's not what glClear does. If you wanted to enable or disable writing to the depth buffer completely, you could do so with with glDepthMask. This function lets you completely disable writes to the depth buffer, potentially while still writing color values to the color buffer. There is a similar function called glColorMask that lets you select which channels of the color buffer (red, green, blue, and/or alpha) you want to write to as well. In this way you could potentially do interesting things like rendering only green, or even doing a special effect where you do a render pass in which you render only depth values and not color values (perhaps in preparation for knocking out a special effect to be applied in a subsequent pass.) glClear, conversely, actually sets the values in the pixels of the color buffer or depth buffer.
In the code you posted, you're only doing glClear(GL_DEPTH_BUFFER_BIT), which is only clearing the depth buffer, but not the color buffer. This essentially leaves all the paint on the canvas from last frame you drew, so leftover images from previous frames remain visible on the screen. You should be clearing both buffers.
Because you only draw your colorful square each frame, you draw a new square over top of whatever was in the buffer from last time. If you're double-buffering (common in full-screen graphics modes, but not windowed graphics modes), you may find that you're drawing over top of a frame from two-frames-ago, which may produce a strobing/flashing marquee effect.
The argument to glClear is called a bitmask. It uses each bit of the mask like a checkbox to select whether a particular kind of buffer should be cleared. Specifying GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT will logically OR the bits together creating a number with both bits set -- which is like checking both checkboxes, saying, "yes, please clear the depth buffer, and yes also clear the color buffer".
There can be up to four different kinds of buffers, not just color and depth. The four mask fields are GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, GL_ACCUM_BUFFER_BIT, and GL_STENCIL_BUFFER_BIT. Each one of these is a bit-field value, a number with a single binary bit set, which can be logically OR'ed together like 4 individual checkboxes. In your application your render target may not have an accumulator buffer or a stencil buffer. Some render targets don't even make use of a depth buffer. It's totally up to how you created your render buffer originally. In your case it looks like you have a buffer with color and depth. So when it comes time to clear the buffer, in preparation for rendering the frame, you'll want to make sure you check both boxes, effectively asking for both the color and depth components of your buffers to be cleared. Do so by passing GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT as the argument to glClear.
The use of bit-fields here is so exemplary, that glClear is actually used on the Wikipedia page for Mask_(computing) - Uses of bitmasks to explain how bitmasks can be used!

Lines and textures will not show up together

Here is how I draw the line and I using mouse to draw the line
static struct
{
GLfloat p[MAX_POINTS][2];
GLuint point_cnt;
} contours [ MAX_CONTOURS ] ;
GLuint point_cnt_mouse;
point_cnt_mouse = contours[contour_cnt].point_cnt;
glColor3f( 0.0, 0.0, 0.0 );
glBegin(GL_LINES);
glLineWidth(5.0);
int i;
int j;
for(i = 0; i <= contour_cnt; i++)
{
GLuint point_cnt;
point_cnt = contours[i].point_cnt;
if (contours[i].point_cnt == 0)
{
glVertex2fv ( P );
glVertex2fv ( P );
}//if
else
{
for(j = 2; j <= point_cnt; j++)
{
glVertex2fv (contours[i].p[j-2]);
glVertex2fv (contours[i].p[j-1]);
}//for
}//else
}//for
if(point_cnt_mouse > 0)
{
glVertex2fv(contours[contour_cnt].p[point_cnt_mouse-1]);
glVertex2fv(P);
}//if
glEnd();
then I use glTexImage2D() to make GL_TEXTURE_2D then
my display is
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glPushMatrix ();
glTranslatef(-4.0, 5.0, -6.0);
//this is box and load texture on it
drawPlane();
glPopMatrix();
glutSwapBuffers();
glFlush();
}
void myinit()
{
glClearColor(1.0, 1.0, 1.0, 1.0);
glEnable(GL_DEPTH_TEST);
//load png image
drawLogo();
glDisable(GL_DEPTH_TEST);
}
Logo won't show up with lines, why? Can any one tell what is wrong with my code?
Make sure to disable texturing (glDisable(GL_TEXTURE_2D)) before drawing your line(s). And re-enable (glEnable(GL_TEXTURE_2D)) before drawing your texture.
If you're using the default GL_MODULATE texture environment make sure to set the current color to white (glColor3ub(255,255,255)) before drawing with the texture. If you draw the texture after the glColor3f( 0.0, 0.0, 0.0 ) in your line routine then GL_MODULATE will multiply all your texel RGB values by zero, giving you black everywhere.
It looks kind of suspicious to me that your display() function never calls drawLogo().
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glPushMatrix ();
glTranslatef(-4.0, 5.0, -6.0);
//this is box and load texture on it
drawPlane();
glPopMatrix();
glutSwapBuffers();
glFlush();
}

Using the following function that draws a filled circle in opengl, how do I make it show at different coordinates of the window?

I have got the following code to draw a filled circle in opengl. The problem is that it draws at the center of the screen. How do I make it draw in another position of it?
Here is the code:
#define CIRCLE_RADIUS = 0.15f
int circle_points = 100;
void draw()
{
glClear(GL_COLOR_BUFFER_BIT);
double angle = 2* PI/circle_points ;
glPolygonMode( GL_FRONT, GL_FILL );
glColor3f(0.2, 0.5, 0.5 );
glBegin(GL_POLYGON);
double angle1 = 0.0;
glVertex2d( CIRCLE_RADIUS * cos(0.0) , CIRCLE_RADIUS * sin(0.0));
int i;
for (i = 0; i < circle_points; i++)
{
glVertex2d(CIRCLE_RADIUS * cos(angle1), CIRCLE_RADIUS *sin(angle1));
angle1 += angle ;
}
glEnd();
glFlush();
}
The obvious way would be to call glTranslate first. Note, however, that you can already accomplish the same a bit more easily with a combination of glPointSize and glPoint:
glPointSize(CIRCLE_RADIUS/2.0f);
glPoint(center_x, center_y, center_z);
Before you start drawing the circles, you'll want something like:
glEnable(GL_POINT_SMOOTH);
glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
Otherwise, your "circles" could end up as squares.
Edit: Without knowing how you've set up your coordinates, it's impossible to know what the "top-left" position is, but you could do something like this:
void draw_circle(float x, float y, float radius) {
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glTranslatef(x, y, 0.0f);
static const int circle_points = 100;
static const float angle = 2.0f * 3.1416f / circle_points;
// this code (mostly) copied from question:
glBegin(GL_POLYGON);
double angle1=0.0;
glVertex2d(radius * cos(0.0) , radius * sin(0.0));
int i;
for (i=0; i<circle_points; i++)
{
glVertex2d(radius * cos(angle1), radius *sin(angle1));
angle1 += angle;
}
glEnd();
glPopMatrix();
}
You could then call (for example):
draw_circle(0.0f, 0.0f, 0.2f); // centered
draw_circle(1.0f, 0.0f, 0.2f); // right of center
draw_circle(1.0f, 1.0f, 0.2f); // right and up from center
Of course, the directions I've given assume haven't (for example) rotated your view, so x increases to the right and y increases upward.

Understanding opengl's (glut) resize

I'm reading the sample code for the bezier curve on the online version of opengl's tutorial.
I'm curious about how is resize being handled in the example cause I figure I might use it on my own version of this program , I placed my questions on its comments:
void reshape(int w, int h)
{
glViewport(0, 0, (GLsizei) w, (GLsizei) h); // what's GLsizei? Why is it called inside glViewPort?
glMatrixMode(GL_PROJECTION); // is it necessary to reset the projection matrix?
glLoadIdentity();
if (w <= h) // is this calculation universal, could I use it on another program?
glOrtho(-5.0, 5.0, -5.0*(GLfloat)h/(GLfloat)w,
5.0*(GLfloat)h/(GLfloat)w, -5.0, 5.0);
else
glOrtho(-5.0*(GLfloat)w/(GLfloat)h,
5.0*(GLfloat)w/(GLfloat)h, -5.0, 5.0, -5.0, 5.0);
glMatrixMode(GL_MODELVIEW); // why do I set to GL_MODELVIEW at the end?
glLoadIdentity(); // why does it get a reset?
}
Full code:
#include <stdlib.h>
#include <GL/glut.h>
GLfloat ctrlpoints[4][3] = {
{ -4.0, -4.0, 0.0}, { -2.0, 4.0, 0.0},
{2.0, -4.0, 0.0}, {4.0, 4.0, 0.0}};
void init(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_FLAT);
glMap1f(GL_MAP1_VERTEX_3, 0.0, 1.0, 3, 4, &ctrlpoints[0][0]);
glEnable(GL_MAP1_VERTEX_3);
}
void display(void)
{
int i;
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_LINE_STRIP);
for (i = 0; i <= 30; i++)
glEvalCoord1f((GLfloat) i/30.0);
glEnd();
/* The following code displays the control points as dots. */
glPointSize(5.0);
glColor3f(1.0, 1.0, 0.0);
glBegin(GL_POINTS);
for (i = 0; i < 4; i++)
glVertex3fv(&ctrlpoints[i][0]);
glEnd();
glFlush();
}
void reshape(int w, int h)
{
glViewport(0, 0, (GLsizei) w, (GLsizei) h); // what's GLsizei? Why is it called inside glViewPort?
glMatrixMode(GL_PROJECTION); // is it necessary to reset the projection matrix?
glLoadIdentity();
if (w <= h) // is this calculation universal, could I use it on another program?
glOrtho(-5.0, 5.0, -5.0*(GLfloat)h/(GLfloat)w,
5.0*(GLfloat)h/(GLfloat)w, -5.0, 5.0);
else
glOrtho(-5.0*(GLfloat)w/(GLfloat)h,
5.0*(GLfloat)w/(GLfloat)h, -5.0, 5.0, -5.0, 5.0);
glMatrixMode(GL_MODELVIEW); // why do I set to GL_MODELVIEW at the end?
glLoadIdentity(); // why does it get a reset?
}
void keyboard(unsigned char key, int x, int y)
{
switch (key) {
case 27:
exit(0);
break;
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow (argv[0]);
init ();
glutDisplayFunc(display);
glutReshapeFunc(reshape); // el reshape funciona correctamente
glutKeyboardFunc (keyboard);
glutMainLoop();
return 0;
}
GLsizei is a type, not a function. Therefore, it's not being called; its being casted; it's converting an int into a GLsizei. It's basically an int, but it makes it clear that you're using it for a size (I think). (I'm a Python programmer, so this is a guess)
glMatrixMode(...);
This does not reset the matrix, unless it is followed by a glLoadIdentity() call. Instead, it sets the current target of OpenGL's matrix operations to the matrix specified. This way, OpenGL knows what matrix you're trying to affect.
I've seen that calcuation before in the OpenGL superbible (or at least something like it); why don't you talk yourself through it and see what it's deciding and why? (Hint (I think): it's trying to keep the viewport square to avoid stretching)
At the end, it sets it back to GL_MODELVIEW since that matrix handles transformations, like translation and rotation, which are used to position vertices onscreen. It should be reset every frame so that your code can assume that the coordinate plane is currently at (0,0); that simplifies calculations about where to translate to.
Also note that reshape is not called by OpenGL, but by GLUT. OpenGL is platform-independent and does not handle windowing; this is why you need GLUT.
If you're new to OpenGL, you should work through it from the beginning - later tutorials will assume this sort of knowledge.

Resources