The purpose of this code is to generate a 'surface' with random Y variation, and then have a light source shine on it and generate areas of brightness and perform shading on darker areas. The problem is, this isn't really happening. The light either illuminates one side or the other, and those sides are all uniformly bright or dark. What am I missing with this? Keep in mind there is a good bit of code that has yet to be removed, but it is not my priority, I'm just trying to get shading functional at this point.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#ifdef MAC
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
//Camera variables
int xangle = -270;
int yangle = 0;
//Control Mode (Rotate mode by default)
int mode = 0;
//Player Position (Y offset so it would not be straddling the grid)
float cubeX = 0;
float cubeY = 0.5;
float cubeZ = 0;
//Vertex arrays for surface
float surfaceX [11][11];
float surfaceY [11][11];
float surfaceZ [11][11];
//Surface Normal arrays
float Nx[11][11];
float Ny[11][11];
float Nz[11][11];
//Color arrays
float R[11][11];
float G[11][11];
float B[11][11];
// Material properties
float Ka = 0.2;
float Kd = 0.4;
float Ks = 0.4;
float Kp = 0.5;
//Random number generator
float RandomNumber(float Min, float Max)
{
return ((float(rand()) / float(RAND_MAX)) * (Max - Min)) + Min;
}
//---------------------------------------
// Initialize material properties
//---------------------------------------
void init_material(float Ka, float Kd, float Ks, float Kp,
float Mr, float Mg, float Mb)
{
// Material variables
float ambient[] = { Ka * Mr, Ka * Mg, Ka * Mb, 1.0 };
float diffuse[] = { Kd * Mr, Kd * Mg, Kd * Mb, 1.0 };
float specular[] = { Ks * Mr, Ks * Mg, Ks * Mb, 1.0 };
// Initialize material
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambient);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, Kp);
}
//---------------------------------------
// Initialize light source
//---------------------------------------
void init_light(int light_source, float Lx, float Ly, float Lz,
float Lr, float Lg, float Lb)
{
// Light variables
float light_position[] = { Lx, Ly, Lz, 0.0 };
float light_color[] = { Lr, Lg, Lb, 1.0 };
// Initialize light source
glEnable(GL_LIGHTING);
glEnable(light_source);
glLightfv(light_source, GL_POSITION, light_position);
glLightfv(light_source, GL_AMBIENT, light_color);
glLightfv(light_source, GL_DIFFUSE, light_color);
glLightfv(light_source, GL_SPECULAR, light_color);
glLightf(light_source, GL_CONSTANT_ATTENUATION, 1.0);
glLightf(light_source, GL_LINEAR_ATTENUATION, 0.0);
glLightf(light_source, GL_QUADRATIC_ATTENUATION, 0.0);
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE);
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
}
//---------------------------------------
// Initialize surface
//---------------------------------------
void init_surface()
{
//Initialize X, select column
for (int i = 0; i < 11; i++)
{
//Select row
for (int j = 0; j < 11; j++)
{
surfaceX[i][j] = i-5;
surfaceY[i][j] = RandomNumber(5, 7) - 5;
surfaceZ[i][j] = j-5;
//std::cout << "Coordinate "<< i << "," << j << std::endl;
}
//std::cout << "Hello world "<< std::endl;
}
//std::cout << "Coordinate -5,-5" << surfaceX[-5][-5] << std::endl;
}
void define_normals()
{
//Define surface normals
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
//Get two tangent vectors
float Ix = surfaceX[i+1][j] - surfaceX[i][j];
float Iy = surfaceY[i+1][j] - surfaceY[i][j];
float Iz = surfaceZ[i+1][j] - surfaceZ[i][j];
float Jx = surfaceX[i][j+1] - surfaceX[i][j];
float Jy = surfaceY[i][j+1] - surfaceY[i][j];
float Jz = surfaceZ[i][j+1] - surfaceZ[i][j];
//Get two tangent vectors
//float Ix = Px[i+1][j] - Px[i][j];
//float Iy = Py[i+1][j] - Py[i][j];
//float Iz = Pz[i+1][j] - Pz[i][j];
//float Jx = Px[i][j+1] - Px[i][j];
//float Jy = Py[i][j+1] - Py[i][j];
//float Jz = Pz[i][j+1] - Pz[i][j];
//Do cross product
Nx[i][j] = Iy * Jz - Iz * Jy;
Ny[i][j] = Iz * Jx - Ix * Jz;
Nz[i][j] = Ix * Jy - Iy * Jx;
//Nx[i][j] = Nx[i][j] * -1;
//Ny[i][j] = Ny[i][j] * -1;
//Nz[i][j] = Nz[i][j] * -1;
float length = sqrt(
Nx[i][j] * Nx[i][j] +
Ny[i][j] * Ny[i][j] +
Nz[i][j] * Nz[i][j]);
if (length > 0)
{
Nx[i][j] /= length;
Ny[j][j] /= length;
Nz[i][j] /= length;
}
}
}
//std::cout << "Surface normal for 0,0: "<< Nx[0][0] << "," << Ny[0][0] << "," << Nz[0][0] << std::endl;
}
void calc_color()
{
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
//Calculate light vector
//Light position, hardcoded for now 0,1,1
float Lx = -1 - surfaceX[i][j];
float Ly = -1 - surfaceY[i][j];
float Lz = -1 - surfaceZ[i][j];
std::cout << "Lx: " << Lx << std::endl;
std::cout << "Ly: " << Ly << std::endl;
std::cout << "Lz: " << Lz << std::endl;
//Grab surface normals
//These are Nx,Ny,Nz due to compiler issues
float Na = Nx[i][j];
float Nb = Ny[i][j];
float Nc = Nz[i][j];
std::cout << "Na: " << Na << std::endl;
std::cout << "Nb: " << Nb << std::endl;
std::cout << "Nc: " << Nc << std::endl;
//Do cross product
float Color = (Na * Lx) + (Nb * Ly) + (Nc * Lz);
std::cout << "Color: " << Color << std::endl;
//Color = Color * -1;
R[i][j] = Color;
G[i][j] = Color;
B[i][j] = Color;
//std::cout << "Color Value: " << std::endl;
////std::cout << "R: " << R[i][j] << std::endl;
//std::cout << "G: " << G[i][j] << std::endl;
//std::cout << "B: " << B[i][j] << std::endl;
}
}
}
//---------------------------------------
// Init function for OpenGL
//---------------------------------------
void init()
{
glClearColor(0.0, 0.0, 0.0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//Viewing Window Modified
glOrtho(-7.0, 7.0, -7.0, 7.0, -7.0, 7.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//Rotates camera
//glRotatef(30.0, 1.0, 1.0, 1.0);
glEnable(GL_DEPTH_TEST);
//Project 3 code
init_surface();
define_normals();
//Shading code
glShadeModel(GL_SMOOTH);
glEnable(GL_NORMALIZE);
init_light(GL_LIGHT0, 0, 1, 1, 0.5, 0.5, 0.5);
//init_light(GL_LIGHT1, 0, 0, 1, 0.5, 0.5, 0.5);
//init_light(GL_LIGHT2, 0, 1, 0, 0.5, 0.5, 0.5);
}
void keyboard(unsigned char key, int x, int y)
{
//Controls
//Toggle Mode
if (key == 'q')
{
if(mode == 0)
{
mode = 1;
std::cout << "Switched to Move mode (" << mode << ")" << std::endl;
}
else if(mode == 1)
{
mode = 0;
std::cout << "Switched to Rotate mode (" << mode << ")" << std::endl;
}
}
////Rotate Camera (mode 0)
//Up & Down
else if (key == 's' && mode == 0)
xangle += 5;
else if (key == 'w' && mode == 0)
xangle -= 5;
//Left & Right
else if (key == 'a' && mode == 0)
yangle -= 5;
else if (key == 'd' && mode == 0)
yangle += 5;
////Move Cube (mode 1)
//Forward & Back
else if (key == 'w' && mode == 1)
{
if (cubeZ > -5)
cubeZ = cubeZ - 1;
else
std::cout << "You have struck an invisible wall! (Min Z bounds)" << std::endl;
}
else if (key == 's' && mode == 1)
{
if (cubeZ < 5)
cubeZ = cubeZ + 1;
else
std::cout << "You have struck an invisible wall! (Max Z bounds)" << std::endl;
}
//Strafe
else if (key == 'd' && mode == 1)
{
if (cubeX < 5)
cubeX = cubeX + 1;
else
std::cout << "You have struck an invisible wall! (Max X bounds)" << std::endl;
}
else if (key == 'a' && mode == 1)
{
if (cubeX > -5)
cubeX = cubeX - 1;
else
std::cout << "You have struck an invisible wall! (Min X bounds)" << std::endl;
}
//Up & Down (Cube offset by +0.5 in Y)
else if (key == 'z' && mode == 1)
{
if (cubeY < 5)
cubeY = cubeY + 1;
else
std::cout << "You've gone too high! Come back! (Max Y bounds)" << std::endl;
}
else if (key == 'x' && mode == 1)
{
if (cubeY > 0.5)
cubeY = cubeY - 1;
else
std::cout << "You've reached bedrock! (Min Y bounds)" << std::endl;
}
//Place/Remove block
else if (key == 'e' && mode == 1)
{
//Occupied(cubeX,cubeY,cubeZ);
}
//Redraw objects
glutPostRedisplay();
}
//---------------------------------------
// Display callback for OpenGL
//---------------------------------------
void display()
{
// Clear the screen
//std::cout << "xangle: " << xangle << std::endl;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//Rotation Code
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(xangle, 1.0, 0.0, 0.0);
glRotatef(yangle, 0.0, 1.0, 0.0);
//Light Code
init_material(Ka, Kd, Ks, 100 * Kp, 0.8, 0.6, 0.4);
calc_color();
//Draw the squares, select column
for (int i = 0; i <= 9; i++)
{
//Select row
for (int j = 0; j <= 9; j++)
{
glBegin(GL_POLYGON);
//Surface starts at top left
//Counter clockwise
// CALCULATE COLOR HERE
// - calculate direction from surface to light
// - calculate dot product of normal and light direction vector
// - call glColor function
//Calculate light vector
//Light position, hardcoded for now 0,1,1
///float Lx = 0 - surfaceX[i][j];
//float Ly = 1 - surfaceY[i][j];
//float Lz = 1 - surfaceZ[i][j];
//Grab surface normals
//These are Nx,Ny,Nz due to compiler issues
//float Na = Nx[i][j];
//float Nb = Ny[i][j];
//float Nc = Nz[i][j];
//Do cross product
//float Color = (Na * Lx) + (Nb * Ly) + (Nc * Lz);
//???
//glColor3fv(Color);
//glColor3f(0.5*Color,0.5*Color,0.5*Color);
glColor3f(R[i][j], G[i][j], B[i][j]);
glVertex3f(surfaceX[i][j], surfaceY[i][j], surfaceZ[i][j]);
glColor3f(R[i][j+1], G[i][j+1], B[i][j+1]);
glVertex3f(surfaceX[i][j+1], surfaceY[i][j+1], surfaceZ[i][j+1]);
glColor3f(R[i+1][j+1], G[i+1][j+1], B[i+1][j+1]);
glVertex3f(surfaceX[i+1][j+1], surfaceY[i+1][j+1], surfaceZ[i+1][j+1]);
glColor3f(R[i+1][j], G[i+1][j], B[i+1][j]);
glVertex3f(surfaceX[i+1][j], surfaceY[i+1][j], surfaceZ[i+1][j]);
glEnd();
}
}
//Draw the normals
for (int i = 0; i <= 10; i++)
{
for (int j = 0; j <= 10; j++)
{
glBegin(GL_LINES);
//glColor3f(0.0, 1.0, 1.0);
float length = 1;
glVertex3f(surfaceX[i][j], surfaceY[i][j], surfaceZ[i][j]);
glVertex3f(surfaceX[i][j]+length*Nx[i][j],
surfaceY[i][j]+length*Ny[i][j],
surfaceZ[i][j]+length*Nz[i][j]);
glEnd();
}
}
glEnd();
glFlush();
//Player Cube
//Cube: midx, midy, midz, size
//+Z = Moving TOWARD camera in opengl
//Origin point for reference
glPointSize(10);
glColor3f(1.0, 1.0, 0.0);
glBegin(GL_POINTS);
glVertex3f(0, 0, 0);
glEnd();
//Assign Color of Lines
float R = 1;
float G = 1;
float B = 1;
glBegin(GL_LINES);
glColor3f(R, G, B);
////Drawing the grid
//Vertical lines
for (int i = 0; i < 11; i++)
{
int b = -5 + i;
glVertex3f(b, 0, -5);
glVertex3f(b, 0, 5);
}
//Horizontal lines
for (int i = 0; i < 11; i++)
{
int b = -5 + i;
glVertex3f(-5,0,b);
glVertex3f(5,0,b);
}
glEnd();
glEnd();
glFlush();
}
//---------------------------------------
// Main program
//---------------------------------------
int main(int argc, char *argv[])
{
srand(time(NULL));
//Print Instructions
std::cout << "Project 3 Controls: " << std::endl;
std::cout << "q switches control mode" << std::endl;
std::cout << "w,a,s,d for camera rotation" << std::endl;
//Required
glutInit(&argc, argv);
//Window will default to a different size without
glutInitWindowSize(500, 500);
//Window will default to a different position without
glutInitWindowPosition(250, 250);
//
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE | GLUT_DEPTH);
//Required
glutCreateWindow("Project 3");
//Required, calls display function
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
//Required
init();
glutMainLoop();
return 0;
}
Both the surface and normals are being generated as well as the color for the given vertex, I'm just not understanding why it isn't working.
The light or brightness of the surface is a function of the incident light vector the view direction and the normal vector of the surface.
You missed to set the normal vector attributes when you render the plane. Set the normal vector attribute by glNormal, before the vertex coordinate is specified:
for (int i = 0; i <= 9; i++)
{
for (int j = 0; j <= 9; j++)
{
glBegin(GL_POLYGON);
glColor3f(R[i][j], G[i][j], B[i][j]);
glNormal3f(Nx[i][j], Ny[i][j], Nz[i][j]);
glVertex3f(surfaceX[i][j], surfaceY[i][j], surfaceZ[i][j]);
glColor3f(R[i][j+1], G[i][j+1], B[i][j+1]);
glNormal3f(Nx[i][j+1], Ny[i][j+1], Nz[i][j+1]);
glVertex3f(surfaceX[i][j+1], surfaceY[i][j+1], surfaceZ[i][j+1]);
glColor3f(R[i+1][j+1], G[i+1][j+1], B[i+1][j+1]);
glNormal3f(Nx[i+1][j+1], Ny[i+1][j+1], Nz[i+1][j+1]);
glVertex3f(surfaceX[i+1][j+1], surfaceY[i+1][j+1], surfaceZ[i+1][j+1]);
glColor3f(R[i+1][j], G[i+1][j], B[i+1][j]);
glNormal3f(Nx[i+1][j], Ny[i+1][j], Nz[i+1][j]);
glVertex3f(surfaceX[i+1][j], surfaceY[i+1][j], surfaceZ[i+1][j]);
glEnd();
}
}
But note, that the quality of the light will be low, because of the Gouraud shading of the Legacy OpenGL standard light model.
See also OpenGL Lighting on texture plane is not working.
Further, the normal vectors are inverted. You can change the direction by swapping the vectors in the cross product:
Nx[i][j] = Iz * Jy - Iy * Jz;
Ny[i][j] = Ix * Jz - Iz * Jx;
Nz[i][j] = Iy * Jx - Ix * Jy;
Side note:
Note, that drawing by glBegin/glEnd sequences, the fixed function matrix stack and fixed function, per vertex light model, is deprecated since decades. See Fixed Function Pipeline and Legacy OpenGL.
Read about Vertex Specification and Shader for a state of the art way of rendering.
Related
In this code, I'm trying to shade a surface properly based on the position of a light which can be moved. So when you move the light, the surface updates. In addition, I'm looking to have two lights of different colors both shading the same surface. Unfortunately, the surface color remains static.
What I'd like:
1) Have the surface update when the light is moved, and a vector that will use both colors(I'm not 100% on how to do this).
2) Have the lights and normals remain a static color regardless of shading/light.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#ifdef MAC
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
//Camera variables
int xangle = -270;
int yangle = 0;
//Control Modes (Rotate mode by default)
int mode = 0;
int lightmode = 0;
//Player Position (Y offset so it would not be straddling the grid)
float cubeX = 0;
float cubeY = 0.5;
float cubeZ = 0;
//Vertex arrays for surface
float surfaceX [12][12];
float surfaceY [12][12];
float surfaceZ [12][12];
//Surface Normal arrays
float Nx[11][11];
float Ny[11][11];
float Nz[11][11];
//Color arrays
float R[11][11];
float G[11][11];
float B[11][11];
//Material properties
float Ka = 0.2;
float Kd = 0.4;
float Ks = 0.4;
float Kp = 0.5;
//Light position and color variables
float Light1x = 0;
float Light1y = 5;
float Light1z = 0;
float Light1r = 1;
float Light1g = 0;
float Light1b = 0;
float Light2x = -5;
float Light2y = 5;
float Light2z = -5;
float Light2r = 0;
float Light2g = 1;
float Light2b = 0;
//Random number generator
float RandomNumber(float Min, float Max)
{
return ((float(rand()) / float(RAND_MAX)) * (Max - Min)) + Min;
}
//---------------------------------------
// Initialize material properties
//---------------------------------------
void init_material(float Ka, float Kd, float Ks, float Kp,
float Mr, float Mg, float Mb)
{
// Material variables
float ambient[] = { Ka * Mr, Ka * Mg, Ka * Mb, 1.0 };
float diffuse[] = { Kd * Mr, Kd * Mg, Kd * Mb, 1.0 };
float specular[] = { Ks * Mr, Ks * Mg, Ks * Mb, 1.0 };
// Initialize material
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambient);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, Kp);
}
//---------------------------------------
// Initialize light source
//---------------------------------------
void init_light(int light_source, float Lx, float Ly, float Lz,
float Lr, float Lg, float Lb)
{
// Light variables
float light_position[] = { Lx, Ly, Lz, 0.0 };
float light_color[] = { Lr, Lg, Lb, 1.0 };
// Initialize light source
glEnable(GL_LIGHTING);
glEnable(light_source);
glLightfv(light_source, GL_POSITION, light_position);
glLightfv(light_source, GL_AMBIENT, light_color);
glLightfv(light_source, GL_DIFFUSE, light_color);
glLightfv(light_source, GL_SPECULAR, light_color);
glLightf(light_source, GL_CONSTANT_ATTENUATION, 1.0);
glLightf(light_source, GL_LINEAR_ATTENUATION, 0.0);
glLightf(light_source, GL_QUADRATIC_ATTENUATION, 0.0);
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE);
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
}
//---------------------------------------
// Initialize surface
//---------------------------------------
void init_surface()
{
//Initialize X, select column
for (int i = 0; i < 12; i++)
{
//Select row
//Surface is +1 so the far right normal will be generated correctly
for (int j = 0; j < 12; j++)
{
//-5 to compensate for negative coordinate values
surfaceX[i][j] = i-5;
//Generate random surface height
surfaceY[i][j] = RandomNumber(5, 7) - 5;
//surfaceY[i][j] = 0;
surfaceZ[i][j] = j-5;
}
}
}
void define_normals()
{
//Define surface normals
for (int i = 0; i < 11; i++)
{
for (int j = 0; j < 11; j++)
{
//Get two tangent vectors
float Ix = surfaceX[i+1][j] - surfaceX[i][j];
float Iy = surfaceY[i+1][j] - surfaceY[i][j];
float Iz = surfaceZ[i+1][j] - surfaceZ[i][j];
float Jx = surfaceX[i][j+1] - surfaceX[i][j];
float Jy = surfaceY[i][j+1] - surfaceY[i][j];
float Jz = surfaceZ[i][j+1] - surfaceZ[i][j];
//Do cross product, inverted for upward normals
Nx[i][j] = - Iy * Jz + Iz * Jy;
Ny[i][j] = - Iz * Jx + Ix * Jz;
Nz[i][j] = - Ix * Jy + Iy * Jx;
//Original vectors
//Nx[i][j] = Iy * Jz - Iz * Jy;
//Ny[i][j] = Iz * Jx - Ix * Jz;
//Nz[i][j] = Ix * Jy - Iy * Jx;
float length = sqrt(
Nx[i][j] * Nx[i][j] +
Ny[i][j] * Ny[i][j] +
Nz[i][j] * Nz[i][j]);
if (length > 0)
{
Nx[i][j] /= length;
Ny[j][j] /= length;
Nz[i][j] /= length;
}
}
}
}
void calc_color()
{
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
//Calculate light vector
//Light position, hardcoded for now 0,1,1
float Lx = Light1x - surfaceX[i][j];
float Ly = Light1y - surfaceY[i][j];
float Lz = Light1z - surfaceZ[i][j];
//std::cout << "Lx: " << Lx << std::endl;
//std::cout << "Ly: " << Ly << std::endl;
//std::cout << "Lz: " << Lz << std::endl;
//Grab surface normals
//These are Nx,Ny,Nz due to compiler issues
float Na = Nx[i][j];
float Nb = Ny[i][j];
float Nc = Nz[i][j];
//std::cout << "Na: " << Na << std::endl;
//std::cout << "Nb: " << Nb << std::endl;
//std::cout << "Nc: " << Nc << std::endl;
//Do cross product
float Color = (Na * Lx) + (Nb * Ly) + (Nc * Lz);
//std::cout << "Color: " << Color << std::endl;
R[i][j] = Color;
G[i][j] = Color;
B[i][j] = Color;
}
}
}
//---------------------------------------
// Init function for OpenGL
//---------------------------------------
void init()
{
glClearColor(0.0, 0.0, 0.0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//Viewing Window Modified
glOrtho(-7.0, 7.0, -7.0, 7.0, -7.0, 7.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//Rotates camera
//glRotatef(30.0, 1.0, 1.0, 1.0);
glEnable(GL_DEPTH_TEST);
//Project 3 code
init_surface();
define_normals();
//Shading code
glShadeModel(GL_SMOOTH);
glEnable(GL_NORMALIZE);
//X,Y,Z - R,G,B
init_light(GL_LIGHT1, Light1x, Light1y, Light1z, Light1r, Light1g, Light1b);
//init_light(GL_LIGHT2, Light2x, Light2y, Light2z, Light2r, Light2g, Light2b);
//init_light(GL_LIGHT2, 0, 1, 0, 0.5, 0.5, 0.5);
}
void keyboard(unsigned char key, int x, int y)
{
///TODO: allow user to change color of light
//Controls
//Toggle Mode
if (key == 'q')
{
if(mode == 0)
{
mode = 1;
std::cout << "Switched to Light mode (" << mode << ")" << std::endl;
}
else if(mode == 1)
{
mode = 0;
std::cout << "Switched to Rotate mode (" << mode << ")" << std::endl;
}
}
//Toggle light control
else if (key == 'e')
{
if(lightmode == 0)
{
lightmode = 1;
std::cout << "Switched to controlling light 2 (" << lightmode << ")" << std::endl;
}
else if(lightmode == 1)
{
lightmode = 0;
std::cout << "Switched to controlling light 1 (" << lightmode << ")" << std::endl;
}
}
////Rotate Camera (mode 0)
//Up & Down
else if (key == 's' && mode == 0)
xangle += 5;
else if (key == 'w' && mode == 0)
xangle -= 5;
//Left & Right
else if (key == 'a' && mode == 0)
yangle -= 5;
else if (key == 'd' && mode == 0)
yangle += 5;
////Move Light (mode 1)
//Forward & Back
else if (key == 'w' && mode == 1)
{
if (lightmode == 0)
{
Light1z = Light1z - 1;
//init_surface();
//define_normals();
calc_color();
glutPostRedisplay();
}
else if (lightmode == 1)
Light2z = Light2z - 1;
//init_surface();
}
else if (key == 's' && mode == 1)
{
if (lightmode == 0)
Light1z = Light1z + 1;
else if (lightmode == 1)
Light2z = Light2z + 1;
}
//Strafe
else if (key == 'd' && mode == 1)
{
if (lightmode == 0)
Light1x = Light1x + 1;
else if (lightmode == 1)
Light2x = Light2x + 1;
}
else if (key == 'a' && mode == 1)
{
if (lightmode == 0)
Light1x = Light1x - 1;
else if (lightmode == 1)
Light2x = Light2x - 1;
}
//Up & Down (Cube offset by +0.5 in Y)
else if (key == 'z' && mode == 1)
{
if (lightmode == 0)
Light1y = Light1y + 1;
else if (lightmode == 1)
Light2y = Light2y + 1;
}
else if (key == 'x' && mode == 1)
{
if (lightmode == 0)
Light1y = Light1y - 1;
else if (lightmode == 1)
Light2y = Light2y - 1;
}
//Redraw objects
glutPostRedisplay();
}
//---------------------------------------
// Display callback for OpenGL
//---------------------------------------
void display()
{
// Clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//Rotation Code
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(xangle, 1.0, 0.0, 0.0);
glRotatef(yangle, 0.0, 1.0, 0.0);
//Light Code
init_material(Ka, Kd, Ks, 100 * Kp, 0.8, 0.6, 0.4);
//Color Code
calc_color();
//Draw the squares, select column
for (int i = 0; i <= 9; i++)
{
//Select row
for (int j = 0; j <= 9; j++)
{
glBegin(GL_POLYGON);
//Surface starts at top left
//Counter clockwise
glColor3f(R[i][j], G[i][j], B[i][j]);
glNormal3f(Nx[i][j], Ny[i][j], Nz[i][j]);
glVertex3f(surfaceX[i][j], surfaceY[i][j], surfaceZ[i][j]);
glColor3f(R[i][j+1], G[i][j+1], B[i][j+1]);
glNormal3f(Nx[i][j+1], Ny[i][j+1], Nz[i][j+1]);
glVertex3f(surfaceX[i][j+1], surfaceY[i][j+1], surfaceZ[i][j+1]);
glColor3f(R[i+1][j+1], G[i+1][j+1], B[i+1][j+1]);
glNormal3f(Nx[i+1][j+1], Ny[i+1][j+1], Nz[i+1][j+1]);
glVertex3f(surfaceX[i+1][j+1], surfaceY[i+1][j+1], surfaceZ[i+1][j+1]);
glColor3f(R[i+1][j], G[i+1][j], B[i+1][j]);
glNormal3f(Nx[i+1][j], Ny[i+1][j], Nz[i+1][j]);
glVertex3f(surfaceX[i+1][j], surfaceY[i+1][j], surfaceZ[i+1][j]);
glEnd();
}
}
//Draw the normals
for (int i = 0; i <= 10; i++)
{
for (int j = 0; j <= 10; j++)
{
glBegin(GL_LINES);
//glColor3f(0.0, 1.0, 1.0);
float length = 1;
glVertex3f(surfaceX[i][j], surfaceY[i][j], surfaceZ[i][j]);
glVertex3f(surfaceX[i][j]+length*Nx[i][j],
surfaceY[i][j]+length*Ny[i][j],
surfaceZ[i][j]+length*Nz[i][j]);
glEnd();
}
}
//Marking location of lights
glPointSize(10);
glBegin(GL_POINTS);
glColor3f(Light1r, Light1g, Light1b);
glVertex3f(Light1x, Light1y, Light1z);
glEnd();
glPointSize(10);
glBegin(GL_POINTS);
glColor3f(Light2r, Light2g, Light2b);
glVertex3f(Light2x, Light2y, Light2z);
glEnd();
//+Z = Moving TOWARD camera in opengl
//Origin point for reference
glPointSize(10);
glColor3f(1.0, 1.0, 0.0);
glBegin(GL_POINTS);
glVertex3f(0, 0, 0);
glEnd();
//Assign Color of Lines
float R = 1;
float G = 1;
float B = 1;
glBegin(GL_LINES);
glColor3f(R, G, B);
////Drawing the grid
//Vertical lines
for (int i = 0; i < 11; i++)
{
int b = -5 + i;
glVertex3f(b, 0, -5);
glVertex3f(b, 0, 5);
}
//Horizontal lines
for (int i = 0; i < 11; i++)
{
int b = -5 + i;
glVertex3f(-5,0,b);
glVertex3f(5,0,b);
}
glEnd();
glFlush();
}
//---------------------------------------
// Main program
//---------------------------------------
int main(int argc, char *argv[])
{
srand(time(NULL));
//Print Instructions
std::cout << "Project 3 Controls: " << std::endl;
std::cout << "q switches control mode" << std::endl;
std::cout << "w,a,s,d for camera rotation" << std::endl;
//Required
glutInit(&argc, argv);
//Window will default to a different size without
glutInitWindowSize(500, 500);
//Window will default to a different position without
glutInitWindowPosition(250, 250);
//
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE | GLUT_DEPTH);
//Required
glutCreateWindow("Project 3");
//Required, calls display function
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
//Required
init();
glutMainLoop();
return 0;
}
1) Have the surface update when the light is moved
You missed to update the position of the light, when the light was moved. Set the light position at the begin of the function display.
Note, when the light position is set by glLightfv(GL_LIGHT0, GL_POSITION, pos), then
pos is multiplied by the current model view matrix.
So the light has to be set after the model view matrix was "cleared" by glLoadIdentity:
void display()
{
// Clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//Rotation Code
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// init light
init_light(GL_LIGHT1, Light1x, Light1y, Light1z, Light1r, Light1g, Light1b);
init_light(GL_LIGHT2, Light2x, Light2y, Light2z, Light2r, Light2g, Light2b);
glRotatef(xangle, 1.0, 0.0, 0.0);
glRotatef(yangle, 0.0, 1.0, 0.0);
// [...]
}
2) Have the lights and normals remain a static color regardless of shading/light.
Enable lighting before drawing the surface, but disable lighting before drawing the lines and points:
void display()
{
// [...]
// switch on lighting
glEnable(GL_LIGHTING);
//Draw the squares, select column
for (int i = 0; i <= 9; i++)
{
// [...]
}
// switch off lighting
glDisable(GL_LIGHTING);
//Draw the normals
for (int i = 0; i <= 10; i++)
{
// [...]
}
// [...]
}
I've been working on my own implementation of a Gouraud style shading model, and I've got the rest of it working pretty much how I want it, but the problem I've run into is it only shows white light. The calc_color function is where this operation is being performed. The Color variable represents the total light of the R, G and B values for that given location. I've been assigning Color to all three arrays just to get the shading implemented properly, but now that that is complete, I'd like to figure out a way to extract the R, G and B values from that total light value.
I've tried several different things, like taking the total light, and taking a percentage of the Light1r, etc. values but it always ends up looking strange or too bright.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#ifdef MAC
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
using namespace std;
//Camera variables
int xangle = -270;
int yangle = 0;
//Control Modes (Rotate mode by default)
int mode = 0;
int lightmode = 0;
//Player Position (Y offset so it would not be straddling the grid)
float cubeX = 0;
float cubeY = 0.5;
float cubeZ = 0;
//Vertex arrays for surface
float surfaceX [12][12];
float surfaceY [12][12];
float surfaceZ [12][12];
//Surface Normal arrays
float Nx[11][11];
float Ny[11][11];
float Nz[11][11];
//Color arrays
float R[11][11];
float G[11][11];
float B[11][11];
//Light position and color variables
float Light1x = 0;
float Light1y = 5;
float Light1z = 0;
float Light1r = 0;
float Light1g = 1;
float Light1b = 0;
float Light2x = -5;
float Light2y = 5;
float Light2z = -5;
float Light2r = 0;
float Light2g = 1;
float Light2b = 0;
//Random number generator
float RandomNumber(float Min, float Max)
{
return ((float(rand()) / float(RAND_MAX)) * (Max - Min)) + Min;
}
//---------------------------------------
// Initialize surface
//---------------------------------------
void init_surface()
{
//Initialize X, select column
for (int i = 0; i < 12; i++)
{
//Select row
//Surface is +1 so the far right normal will be generated correctly
for (int j = 0; j < 12; j++)
{
//-5 to compensate for negative coordinate values
surfaceX[i][j] = i-5;
//Generate random surface height
surfaceY[i][j] = RandomNumber(5, 7) - 5;
//surfaceY[i][j] = 0;
surfaceZ[i][j] = j-5;
}
}
}
void define_normals()
{
//Define surface normals
for (int i = 0; i < 11; i++)
{
for (int j = 0; j < 11; j++)
{
//Get two tangent vectors
float Ix = surfaceX[i+1][j] - surfaceX[i][j];
float Iy = surfaceY[i+1][j] - surfaceY[i][j];
float Iz = surfaceZ[i+1][j] - surfaceZ[i][j];
float Jx = surfaceX[i][j+1] - surfaceX[i][j];
float Jy = surfaceY[i][j+1] - surfaceY[i][j];
float Jz = surfaceZ[i][j+1] - surfaceZ[i][j];
//Do cross product, inverted for upward normals
Nx[i][j] = - Iy * Jz + Iz * Jy;
Ny[i][j] = - Iz * Jx + Ix * Jz;
Nz[i][j] = - Ix * Jy + Iy * Jx;
//Original vectors
//Nx[i][j] = Iy * Jz - Iz * Jy;
//Ny[i][j] = Iz * Jx - Ix * Jz;
//Nz[i][j] = Ix * Jy - Iy * Jx;
float length = sqrt(
Nx[i][j] * Nx[i][j] +
Ny[i][j] * Ny[i][j] +
Nz[i][j] * Nz[i][j]);
if (length > 0)
{
Nx[i][j] /= length;
Ny[j][j] /= length;
Nz[i][j] /= length;
}
}
}
}
void calc_color()
{
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
//Calculate light vector
//Light position, hardcoded for now 0,1,1
float Lx = Light1x - surfaceX[i][j];
float Ly = Light1y - surfaceY[i][j];
float Lz = Light1z - surfaceZ[i][j];
float length = sqrt(Lx * Lx + Ly * Ly + Lz * Lz);
if (length > 0)
{
Lx /= length;
Ly /= length;
Lz /= length;
}
//std::cout << "Lx: " << Lx << std::endl;
//std::cout << "Ly: " << Ly << std::endl;
//std::cout << "Lz: " << Lz << std::endl;
//Grab surface normals
//These are Nx,Ny,Nz due to compiler issues
float Na = Nx[i][j];
float Nb = Ny[i][j];
float Nc = Nz[i][j];
//std::cout << "Na: " << Na << std::endl;
//std::cout << "Nb: " << Nb << std::endl;
//std::cout << "Nc: " << Nc << std::endl;
//Do cross product
float Color = (Na * Lx) + (Nb * Ly) + (Nc * Lz);
std::cout << "Color: " << Color << std::endl;
//if (Color > 0)
//{
// Color = Color / 100;
//}
//Percent of light color
//float Ramt = (Light1r/2) / Color;
//float Gamt = (Light1g/2) / Color;
//float Bamt = (Light1b/2) / Color;
//R[i][j] = Ramt * Color;
//G[i][j] = Gamt * Color;
//B[i][j] = Bamt * Color;
R[i][j] = Color;
G[i][j] = Color;
B[i][j] = Color;
}
}
}
//---------------------------------------
// Init function for OpenGL
//---------------------------------------
void init()
{
glClearColor(0.0, 0.0, 0.0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//Viewing Window Modified
glOrtho(-7.0, 7.0, -7.0, 7.0, -7.0, 7.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//Rotates camera
//glRotatef(30.0, 1.0, 1.0, 1.0);
glEnable(GL_DEPTH_TEST);
//Project 3 code
init_surface();
define_normals();
//Shading code
// glShadeModel(GL_SMOOTH);
// glEnable(GL_NORMALIZE);
//X,Y,Z - R,G,B
// init_light(GL_LIGHT1, Light1x, Light1y, Light1z, Light1r, Light1g, Light1b);
// init_light(GL_LIGHT2, Light2x, Light2y, Light2z, Light2r, Light2g, Light2b);
//init_light(GL_LIGHT2, 0, 1, 0, 0.5, 0.5, 0.5);
}
void keyboard(unsigned char key, int x, int y)
{
///TODO: allow user to change color of light
//Controls
//Toggle Mode
if (key == 'q')
{
if(mode == 0)
{
mode = 1;
std::cout << "Switched to Light mode (" << mode << ")" << std::endl;
}
else if(mode == 1)
{
mode = 0;
std::cout << "Switched to Rotate mode (" << mode << ")" << std::endl;
}
}
//Toggle light control
else if (key == 'e' && mode == 1)
{
if(lightmode == 0)
{
lightmode = 1;
std::cout << "Switched to controlling light 2 (" << lightmode << ")" << std::endl;
}
else if(lightmode == 1)
{
lightmode = 0;
std::cout << "Switched to controlling light 1 (" << lightmode << ")" << std::endl;
}
}
////Rotate Camera (mode 0)
//Up & Down
else if (key == 's' && mode == 0)
xangle += 5;
else if (key == 'w' && mode == 0)
xangle -= 5;
//Left & Right
else if (key == 'a' && mode == 0)
yangle -= 5;
else if (key == 'd' && mode == 0)
yangle += 5;
////Move Light (mode 1)
//Forward & Back
else if (key == 'w' && mode == 1)
{
if (lightmode == 0)
{
Light1z = Light1z - 1;
//init_surface();
//define_normals();
//calc_color();
//glutPostRedisplay();
}
else if (lightmode == 1)
Light2z = Light2z - 1;
//init_surface();
}
else if (key == 's' && mode == 1)
{
if (lightmode == 0)
Light1z = Light1z + 1;
else if (lightmode == 1)
Light2z = Light2z + 1;
}
//Strafe
else if (key == 'd' && mode == 1)
{
if (lightmode == 0)
Light1x = Light1x + 1;
else if (lightmode == 1)
Light2x = Light2x + 1;
}
else if (key == 'a' && mode == 1)
{
if (lightmode == 0)
Light1x = Light1x - 1;
else if (lightmode == 1)
Light2x = Light2x - 1;
}
//Up & Down (Cube offset by +0.5 in Y)
else if (key == 'z' && mode == 1)
{
if (lightmode == 0)
Light1y = Light1y + 1;
else if (lightmode == 1)
Light2y = Light2y + 1;
}
else if (key == 'x' && mode == 1)
{
if (lightmode == 0)
Light1y = Light1y - 1;
else if (lightmode == 1)
Light2y = Light2y - 1;
}
//Redraw objects
glutPostRedisplay();
}
//---------------------------------------
// Display callback for OpenGL
//---------------------------------------
void display()
{
// Clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//Rotation Code
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(xangle, 1.0, 0.0, 0.0);
glRotatef(yangle, 0.0, 1.0, 0.0);
//Light Code
// init_material(Ka, Kd, Ks, 100 * Kp, 0.8, 0.6, 0.4);
// init_light(GL_LIGHT1, Light1x, Light1y, Light1z, Light1r, Light1g, Light1b);
// init_light(GL_LIGHT2, Light2x, Light2y, Light2z, Light2r, Light2g, Light2b);
// glEnable(GL_LIGHTING);
//Color Code
calc_color();
//Draw the squares, select column
for (int i = 0; i <= 9; i++)
{
//Select row
for (int j = 0; j <= 9; j++)
{
glBegin(GL_POLYGON);
//Surface starts at top left
//Counter clockwise
glColor3f(R[i][j], G[i][j], B[i][j]);
std::cout << R[i][j] << " " << G[i][j] << " " << B[i][j] << endl;
// glNormal3f(Nx[i][j], Ny[i][j], Nz[i][j]);
glVertex3f(surfaceX[i][j], surfaceY[i][j], surfaceZ[i][j]);
glColor3f(R[i][j+1], G[i][j+1], B[i][j+1]);
// glNormal3f(Nx[i][j+1], Ny[i][j+1], Nz[i][j+1]);
glVertex3f(surfaceX[i][j+1], surfaceY[i][j+1], surfaceZ[i][j+1]);
glColor3f(R[i+1][j+1], G[i+1][j+1], B[i+1][j+1]);
// glNormal3f(Nx[i+1][j+1], Ny[i+1][j+1], Nz[i+1][j+1]);
glVertex3f(surfaceX[i+1][j+1], surfaceY[i+1][j+1], surfaceZ[i+1][j+1]);
glColor3f(R[i+1][j], G[i+1][j], B[i+1][j]);
// glNormal3f(Nx[i+1][j], Ny[i+1][j], Nz[i+1][j]);
glVertex3f(surfaceX[i+1][j], surfaceY[i+1][j], surfaceZ[i+1][j]);
glEnd();
}
}
// glDisable(GL_LIGHTING);
//Draw the normals
for (int i = 0; i <= 10; i++)
{
for (int j = 0; j <= 10; j++)
{
glBegin(GL_LINES);
glColor3f(0.0, 1.0, 1.0);
float length = 1;
glVertex3f(surfaceX[i][j], surfaceY[i][j], surfaceZ[i][j]);
glVertex3f(surfaceX[i][j]+length*Nx[i][j],
surfaceY[i][j]+length*Ny[i][j],
surfaceZ[i][j]+length*Nz[i][j]);
glEnd();
}
}
//Marking location of lights
glPointSize(10);
glBegin(GL_POINTS);
glColor3f(Light1r, Light1g, Light1b);
glVertex3f(Light1x, Light1y, Light1z);
glEnd();
glPointSize(10);
glBegin(GL_POINTS);
glColor3f(Light2r, Light2g, Light2b);
glVertex3f(Light2x, Light2y, Light2z);
glEnd();
//+Z = Moving TOWARD camera in opengl
//Origin point for reference
glPointSize(10);
glColor3f(1.0, 1.0, 0.0);
glBegin(GL_POINTS);
glVertex3f(0, 0, 0);
glEnd();
//Assign Color of Lines
float R = 1;
float G = 1;
float B = 1;
glBegin(GL_LINES);
glColor3f(R, G, B);
////Drawing the grid
//Vertical lines
for (int i = 0; i < 11; i++)
{
int b = -5 + i;
glVertex3f(b, 0, -5);
glVertex3f(b, 0, 5);
}
//Horizontal lines
for (int i = 0; i < 11; i++)
{
int b = -5 + i;
glVertex3f(-5,0,b);
glVertex3f(5,0,b);
}
glEnd();
glFlush();
}
//---------------------------------------
// Main program
//---------------------------------------
int main(int argc, char *argv[])
{
srand(time(NULL));
//Print Instructions
std::cout << "Project 3 Controls: " << std::endl;
std::cout << "q switches control mode" << std::endl;
std::cout << "w,a,s,d for camera rotation" << std::endl;
//Required
glutInit(&argc, argv);
//Window will default to a different size without
glutInitWindowSize(500, 500);
//Window will default to a different position without
glutInitWindowPosition(250, 250);
//
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE | GLUT_DEPTH);
//Required
glutCreateWindow("Project 3");
//Required, calls display function
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
//Required
init();
glutMainLoop();
return 0;
}
A common formula to calculate a a diffuse light is to calculate the Dot product of the normal vector of the surface and the vector to from the surface to the light source. See How does this faking the light work on aerotwist?.
kd = max(0, L dot N)
To get the color of the light, the RGB values are component wise multiplied by the diffuse coefficient:
(Cr, Cg, Cb) = (LCr, LCg, LCb) * kd
If there are multiple light sources, then the light colors are summed:
(Cr, Cg, Cb) = (LC1r, LC1g, LC1b) * max(0, L1 dot N) + (LC2r, LC2g, LC2b) * max(0, L2 dot N)
Note, if the surface (material) has an additional color, then ths color would have to be component wise multiplied to the final color:
(Cr, Cg, Cb) = (Cr, Cg, Cb) * (CMr, CMg, CMb)
Write a function which calculates the light for 1 single light source and add the light to the final color:
void add_light_color(int i, int j, float lpx, float lpy, float lpz, float lcr, float lcg, float lcb)
{
float Lx = lpx - surfaceX[i][j];
float Ly = lpy - surfaceY[i][j];
float Lz = lpz - surfaceZ[i][j];
float length = sqrt(Lx * Lx + Ly * Ly + Lz * Lz);
if (length <= 0.0)
return;
float kd = Lx/length * Nx[i][j] + Ly/length * Ny[i][j] + Ly/length * Ny[i][j];
if ( kd <= 0.0 )
return;
R[i][j] += kd * lcr;
G[i][j] += kd * lcg;
B[i][j] += kd * lcb;
}
Traverse the filed of attributes, set each color (0, 0, 0) and use the above function to add the color form each light source:
void calc_color()
{
float lp1[] = {Light1x, Light1y, Light1z};
float lp2[] = {Light2x, Light2y, Light2z};
float lc1[] = {Light1r, Light1g, Light1b};
float lc2[] = {Light2r, Light2g, Light2b};
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
R[i][j] = G[i][j] = B[i][j] = 0.0;
add_light_color(i, j, Light1x, Light1y, Light1z, Light1r, Light1g, Light1b);
add_light_color(i, j, Light2x, Light2y, Light2z, Light2r, Light2g, Light2b);
}
}
}
The result for the following light color settings:
float Light1r = 1;
float Light1g = 0;
float Light1b = 0;
float Light2r = 0;
float Light2g = 1;
float Light2b = 0;
I recommend to write your first Shader program, which does per fragment lighting and consists of a Vertex Shader and a Fragment Shader.
The program has to use GLSL version 2.00 (OpenGL Shading Language 1.20 Specification). This program can access the Fixed function attributes by the built in variables gl_Vertex, gl_Normal and gl_Color, as the fixed function matrices gl_NormalMatrix, gl_ModelViewMatrix and gl_ModelViewProjectionMatrix and the function ftransform().
See als Built in Vertex Attributes and Hello World in GLSL.
Further the program has to use Uniform Variables for the light colors and positions.
The Vertex shader transforms the model space coordinates and vectors to view space and pass the to the fragment shader by Varying Variables:
std::string vertex_shader = R"(
#version 120
uniform vec3 u_light_pos_1;
uniform vec3 u_light_pos_2;
varying vec3 v_pos;
varying vec3 v_nv;
varying vec4 v_color;
varying vec3 v_light_pos1;
varying vec3 v_light_pos2;
void main()
{
v_pos = (gl_ModelViewMatrix * gl_Vertex).xyz;
v_nv = gl_NormalMatrix * gl_Normal;
v_color = gl_Color;
v_light_pos1 = (gl_ModelViewMatrix * vec4(u_light_pos_1, 1.0)).xyz;
v_light_pos2 = (gl_ModelViewMatrix * vec4(u_light_pos_2, 1.0)).xyz;
gl_Position = ftransform();
}
)";
The fragment shader dose the per Fragment Light calculations in view space:
std::string fragment_shader = R"(
#version 120
varying vec3 v_pos;
varying vec3 v_nv;
varying vec4 v_color;
varying vec3 v_light_pos1;
varying vec3 v_light_pos2;
uniform vec3 u_light_col_1;
uniform vec3 u_light_col_2;
void main()
{
vec3 N = normalize(v_nv);
vec3 L1 = normalize(v_light_pos1 - v_pos);
vec3 L2 = normalize(v_light_pos2 - v_pos);
float kd_1 = max(0.0, dot(L1, N));
float kd_2 = max(0.0, dot(L2, N));
vec3 light_sum = kd_1 * u_light_col_1 + kd_2 * u_light_col_2;
gl_FragColor = vec4(v_color.rgb * light_sum, v_color.a);
}
)";
Compile the shader stages
GLuint generate_shader(GLenum stage, const std::string &source)
{
GLuint shader_obj = glCreateShader(stage);
const char *srcCodePtr = source.c_str();
glShaderSource(shader_obj, 1, &srcCodePtr, nullptr);
glCompileShader(shader_obj);
GLint status;
glGetShaderiv(shader_obj, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE)
{
GLint maxLen;
glGetShaderiv(shader_obj, GL_INFO_LOG_LENGTH, &maxLen);
std::vector< char >log( maxLen );
GLsizei len;
glGetShaderInfoLog(shader_obj, maxLen, &len, log.data());
std::cout << "compile error:" << std::endl << log.data() << std::endl;
}
return shader_obj;
}
and link the program.
GLuint generate_program(const std::string &vert_sh, const std::string &frag_sh)
{
std::cout << "compile vertex shader" << std::endl;
GLuint vert_obj = generate_shader(GL_VERTEX_SHADER, vert_sh);
std::cout << "compile fragment shader" << std::endl;
GLuint frag_obj = generate_shader(GL_FRAGMENT_SHADER, frag_sh);
std::cout << "link shader program" << std::endl;
GLuint program_obj = glCreateProgram();
glAttachShader(program_obj, vert_obj);
glAttachShader(program_obj, frag_obj);
glLinkProgram(program_obj);
GLint status;
glGetProgramiv(program_obj, GL_LINK_STATUS, &status);
if (status == GL_FALSE)
{
GLint maxLen;
glGetProgramiv(program_obj, GL_INFO_LOG_LENGTH, &maxLen);
std::vector< char >log( maxLen );
GLsizei len;
glGetProgramInfoLog(program_obj, maxLen, &len, log.data());
std::cout << "link error:" << std::endl << log.data() << std::endl;
}
glDeleteShader(vert_obj);
glDeleteShader(frag_obj);
return program_obj;
}
Further get the uniform locations by glGetUniformLocation in the function init:
GLuint diffuse_prog_obj = 0;
GLint loc_l_pos[] = {-1, -1};
GLint loc_l_col[] = {-1, -1};
void init()
{
diffuse_prog_obj = generate_program(vertex_shader, fragment_shader);
loc_l_pos[0] = glGetUniformLocation(diffuse_prog_obj, "u_light_pos_1");
loc_l_pos[1] = glGetUniformLocation(diffuse_prog_obj, "u_light_pos_2");
loc_l_col[0] = glGetUniformLocation(diffuse_prog_obj, "u_light_col_1");
loc_l_col[1] = glGetUniformLocation(diffuse_prog_obj, "u_light_col_2");
// [...]
}
The shader program can be used by glUseProgram. The uniforms are set by glUniform*.
Beside the vertex coordinates, the normal vector attributes have to be set per vertex, to make the light calculations proper work. But it is sufficient to set a single color for the entire mesh:
void display()
{
// [...]
// install program
glUseProgram(diffuse_prog_obj);
// set light positions and colors
glUniform3f(loc_l_pos[0], Light1x, Light1y, Light1z);
glUniform3f(loc_l_pos[1], Light2x, Light2y, Light2z);
glUniform3f(loc_l_col[0], Light1r, Light1g, Light1b);
glUniform3f(loc_l_col[1], Light2r, Light2g, Light2b);
// set object color
glColor3f(1, 1, 0.5);
//Draw the squares, select column
for (int i = 0; i <= 9; i++)
{
//Select row
for (int j = 0; j <= 9; j++)
{
glBegin(GL_POLYGON);
std::cout << R[i][j] << " " << G[i][j] << " " << B[i][j] << endl;
glNormal3f(Nx[i][j], Ny[i][j], Nz[i][j]);
glVertex3f(surfaceX[i][j], surfaceY[i][j], surfaceZ[i][j]);
glNormal3f(Nx[i][j+1], Ny[i][j+1], Nz[i][j+1]);
glVertex3f(surfaceX[i][j+1], surfaceY[i][j+1], surfaceZ[i][j+1]);
glNormal3f(Nx[i+1][j+1], Ny[i+1][j+1], Nz[i+1][j+1]);
glVertex3f(surfaceX[i+1][j+1], surfaceY[i+1][j+1], surfaceZ[i+1][j+1]);
glNormal3f(Nx[i+1][j], Ny[i+1][j], Nz[i+1][j]);
glVertex3f(surfaceX[i+1][j], surfaceY[i+1][j], surfaceZ[i+1][j]);
glEnd();
}
}
// invalidate installed program
glUseProgram(0);
// [...]
}
See the preview of you program, with the applied suggestions:
so I got an image as a texture for a square, but the problem is that whenever I run the code I get this:
But when I take this line out:
glTexImage2D(GL_TEXTURE_2D, 0, 3, image1->sizeX, image1->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, image1->data);
Then I get this output (the white space is where I want to put the image as a texture):
Or if I change the third parameter to 5, then I get this output. But I know that the texture does display correctly when I run the code below, but the output is still like the first image at the top. How would I go about fixing the output so that it looks like the second image with the texture showing? Note that the texture DOES display fine with my code, you just cant see it becuase it's hidden becuase the whole output wont display properly.
#include <GL/glut.h>
#include <iostream>
#include <unistd.h>
#include <math.h>
#include <GL/gl.h>
#include <opencv2/opencv.hpp> //for OpenCV 3.x
#include <opencv/highgui.h> //for OpenCV 3.x
#include <cstdio>
#include <stdlib.h>
#include <string.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <stdio.h>
#include <math.h>
#define UpperBD 80
#define PI 3.1415926
#define Num_pts 10
using namespace std;
float Xe = 200.0f;//100
float Ye = 300.0f;
float Ze = 450.0f;
float Rho = sqrt(pow(Xe,2) + pow(Ye,2) + pow(Ze,2));
float D_focal = 100.0f;
GLuint texture[2];
struct Image {
unsigned long sizeX;
unsigned long sizeY;
char *data;
};
typedef struct Image Image;
#define checkImageWidth 64
#define checkImageHeight 64
GLubyte checkImage[checkImageWidth][checkImageHeight][3];
void makeCheckImage(void){
int i, j, c;
for (i = 0; i < checkImageWidth; i++) {
for (j = 0; j < checkImageHeight; j++) {
c = ((((i&0x8)==0)^((j&0x8)==0)))*255;
checkImage[i][j][0] = (GLubyte) c;
checkImage[i][j][1] = (GLubyte) c;
checkImage[i][j][2] = (GLubyte) c;
}
}
}
int ImageLoad(char *filename, Image *image) {
FILE *file;
unsigned long size; // size of the image in bytes.
unsigned long i; // standard counter.
unsigned short int planes; // number of planes in image (must be 1)
unsigned short int bpp; // number of bits per pixel (must be 24)
char temp; // temporary color storage for bgr-rgb conversion.
// make sure the file is there.
if ((file = fopen(filename, "rb"))==NULL){
printf("File Not Found : %s\n",filename);
return 0;
}
// seek through the bmp header, up to the width/height:
fseek(file, 18, SEEK_CUR);
// read the width
if ((i = fread(&image->sizeX, 4, 1, file)) != 1) {
printf("Error reading width from %s.\n", filename);
return 0;
}
if ((i = fread(&image->sizeY, 4, 1, file)) != 1) {
printf("Error reading height from %s.\n", filename);
return 0;
}
size = image->sizeX * image->sizeY * 3;
// read the planes
if ((fread(&planes, 2, 1, file)) != 1) {
printf("Error reading planes from %s.\n", filename);
return 0;
}
if (planes != 1) {
printf("Planes from %s is not 1: %u\n", filename, planes);
return 0;
}
// read the bitsperpixel
if ((i = fread(&bpp, 2, 1, file)) != 1) {
printf("Error reading bpp from %s.\n", filename);
return 0;
}
if (bpp != 24) {
printf("Bpp from %s is not 24: %u\n", filename, bpp);
return 0;
}
// seek past the rest of the bitmap header.
fseek(file, 24, SEEK_CUR);
// read the data.
image->data = (char *) malloc(size);
if (image->data == NULL) {
printf("Error allocating memory for color-corrected image data");
return 0;
}
if ((i = fread(image->data, size, 1, file)) != 1) {
printf("Error reading image data from %s.\n", filename);
return 0;
}
for (i=0;i<size;i+=3) { // reverse all of the colors. (bgr -> rgb)
temp = image->data[i];
image->data[i] = image->data[i+2];
image->data[i+2] = temp;
}
// we're done.
return 1;
}
Image * loadTexture(){
Image *image1;
// allocate space for texture
image1 = (Image *) malloc(sizeof(Image));
if (image1 == NULL) {
printf("Error allocating space for image");
exit(0);
}
if (!ImageLoad("g.bmp", image1)) {
exit(1);
}
return image1;
}
void myinit(void)
//something in this function is making it not appear properly
{
// glClearColor (0.5, 0.5, 0.5, 0.0);
// glEnable(GL_DEPTH_TEST);
// glDepthFunc(GL_LESS);
Image *image1 = loadTexture();
// makeCheckImage();
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
// Create Texture
glGenTextures(2, texture);
glBindTexture(GL_TEXTURE_2D, texture[0]);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); //scale linearly when image bigger than texture
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); //scale linearly when image smalled than texture
glTexImage2D(GL_TEXTURE_2D, 0, 3, image1->sizeX, image1->sizeY, 0, GL_RGB, GL_UNSIGNED_BYTE, image1->data);
//above line causing problem
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
glBindTexture(GL_TEXTURE_2D, texture[1]);
// glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
// glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
// glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
// glTexImage2D(GL_TEXTURE_2D, 0, 3, checkImageWidth, checkImageHeight, 0, GL_RGB, GL_UNSIGNED_BYTE,&checkImage[0][0][0]);
glEnable(GL_TEXTURE_2D);
// glShadeModel(GL_FLAT);
}
typedef struct {
float X[UpperBD];
float Y[UpperBD];
float Z[UpperBD];
} pworld;
typedef struct {
float X[UpperBD];
float Y[UpperBD];
float Z[UpperBD];
} pviewer;
typedef struct{
float X[UpperBD];
float Y[UpperBD];
} pperspective;
typedef struct{
float X[UpperBD];
float Y[UpperBD];
} pattern2DL;
typedef struct{
float X[UpperBD];
float Y[UpperBD];
} arrowpoint;
typedef struct {
float r[UpperBD], g[UpperBD], b[UpperBD];
} pt_diffuse;
void mydisplay()
{
// define x-y coordinate
float p1x=-1.0f, p1y= 0.0f;
float p2x= 1.0f, p2y= 0.0f;
float p3x= 0.0f, p3y= 1.0f;
float p4x= 0.0f, p4y=-1.0f;
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
pworld world;
pviewer viewer;
pperspective perspective;
pattern2DL letterL;
arrowpoint arrow;
//define the x-y-z world coordinate
world.X[0] = 0.0; world.Y[0] = 0.0; world.Z[0] = 0.0; // origin
world.X[1] = 50.0; world.Y[1] = 0.0; world.Z[1] = 0.0; // x-axis
world.X[2] = 0.0; world.Y[2] = 50.0; world.Z[2] = 0.0; // y-axis
world.X[3] = 0.0; world.Y[3] = 0.0; world.Z[3] = 50.0; // y-axis
//define projection plane world coordinate , THIS IS THE SQUARE AROUND THE LETTERS
world.X[4] = 60.0; world.Y[4] = -50.0; world.Z[4] = 0.0;
world.X[5] = 60.0; world.Y[5] = 50.0; world.Z[5] = 0.0; // base line
world.X[7] = 60.0; world.Y[7] = -50.0; world.Z[7] = 100.0; // side bar
world.X[6] = 60.0; world.Y[6] = 50.0; world.Z[6] = 100.0; // side bar
//define 2D pattern letter A
letterL.X[0] = -10.0; letterL.Y[0] = 10.0;
letterL.X[1] = -15.0; letterL.Y[1] = 10.0;
letterL.X[2] = -20.0; letterL.Y[2] = 30.0;
letterL.X[3] = -40.0; letterL.Y[3] = 30.0;
letterL.X[4] = -45.0; letterL.Y[4] = 10.0;
letterL.X[5] = -50.0; letterL.Y[5] = 10.0;
letterL.X[6] = -37.0; letterL.Y[6] = 70.0;
letterL.X[7] = -23.0; letterL.Y[7] = 70.0;
letterL.X[8] = -25.0; letterL.Y[8] = 40.0;
letterL.X[9] = -35.0; letterL.Y[9] = 40.0;
letterL.X[10] = -30.0; letterL.Y[10] = 60.0;
//letter B
letterL.X[11] = 10.0; letterL.Y[11] = 10.0;
letterL.X[12] = 10.0; letterL.Y[12] = 70.0;
letterL.X[13] = 20.0; letterL.Y[13] = 10.0;
letterL.X[14] = 20.0; letterL.Y[14] = 70.0;
letterL.X[15] = 20.0; letterL.Y[15] = 60.0;
letterL.X[16] = 20.0; letterL.Y[16] = 45.0;
letterL.X[17] = 20.0; letterL.Y[17] = 35.0;
letterL.X[18] = 20.0; letterL.Y[18] = 20.0;
letterL.X[19] = 25.0; letterL.Y[19] = 58.0;
letterL.X[20] = 27.0; letterL.Y[20] = 56.0;
letterL.X[21] = 28.0; letterL.Y[21] = 52.0;
letterL.X[22] = 27.0; letterL.Y[22] = 49.0;
letterL.X[23] = 25.0; letterL.Y[23] = 47.0;
letterL.X[24] = 25.0; letterL.Y[24] = 33.0;
letterL.X[25] = 27.0; letterL.Y[25] = 31.0;
letterL.X[26] = 28.0; letterL.Y[26] = 27.0;
letterL.X[27] = 27.0; letterL.Y[27] = 24.0;
letterL.X[28] = 25.0; letterL.Y[28] = 22.0;
letterL.X[29] = 30.0; letterL.Y[29] = 65.0;
letterL.X[30] = 34.0; letterL.Y[30] = 60.0;
letterL.X[31] = 34.0; letterL.Y[31] = 50.0;
letterL.X[32] = 30.0; letterL.Y[32] = 45.0;
letterL.X[33] = 25.0; letterL.Y[33] = 40.0;
letterL.X[34] = 30.0; letterL.Y[34] = 38.0;
letterL.X[35] = 34.0; letterL.Y[35] = 30.0;
letterL.X[36] = 34.0; letterL.Y[36] = 20.0;
letterL.X[37] = 30.0; letterL.Y[37] = 15.0;
arrow.X[0] = 0.0; arrow.Y[0] = 25.0;
arrow.X[1] = 0.0; arrow.Y[1] = 75.0;
arrow.X[2] = 60.0; arrow.Y[2] = 75.0;
arrow.X[3] = 60.0; arrow.Y[3] = 85.0;
arrow.X[4] = 90.0; arrow.Y[4] = 50.0;
arrow.X[5] = 60.0; arrow.Y[5] = 15.0;
arrow.X[6] = 60.0; arrow.Y[6] = 25.0;
arrow.X[7] = 0.0; arrow.Y[7] = 25.0;
arrow.X[8] = 0.0; arrow.Y[8] = 75.0;
arrow.X[9] = 60.0; arrow.Y[9] = 75.0;
arrow.X[10] = 60.0; arrow.Y[10] = 85.0;
arrow.X[11] = 90.0; arrow.Y[11] = 50.0;
arrow.X[12] = 60.0; arrow.Y[12] = 15.0;
arrow.X[13] = 60.0; arrow.Y[13] = 25.0;
//decoration
for(int i = 0; i <= 37; i++)
{
world.X[8+i] = 60.0;
world.Y[8+i] = letterL.X[i];
world.Z[8+i] = letterL.Y[i];
}
//arrow
for(int j = 0; j <= 6; j++)
{
world.X[46+j] = arrow.X[j]-50;//-50
world.Y[46+j] = arrow.Y[j];
world.Z[46+j] = 100.0;//CHANGE TO 150?
}
for(int k = 0; k <= 6; k++)
{
world.X[53+k] = arrow.X[k]-50;
world.Y[53+k] = arrow.Y[k];
world.Z[53+k] = 110.0;//CHANGE TO 150?
}
float sPheta = Ye / sqrt(pow(Xe,2) + pow(Ye,2));
float cPheta = Xe / sqrt(pow(Xe,2) + pow(Ye,2));
float sPhi = sqrt(pow(Xe,2) + pow(Ye,2)) / Rho;
float cPhi = Ze / Rho;
float xMin = 1000.0, xMax = -1000.0;
float yMin = 1000.0, yMax = -1000.0;
//47 is normal vector 46 is a, 45 is ps, 7 is top left box vertex
//COMUTER SHADE OF FLOATING ARROW DUE NEXT WEEK
world.X[60] = -200.0; world.Y[60]=50.0; world.Z[60]=200.0;//ps
world.X[61] = 0.0; world.Y[61]=0.0; world.Z[61]=0.0;//vector a
world.X[62] = 0.0; world.Y[62]=0.0; world.Z[62]=1.0;//VECTOR N
float tmp = (world.X[62]*(world.X[61]-world.X[60]))
+(world.Y[62]*(world.Y[61]-world.Y[60]))
+(world.Z[62]*(world.Z[61]-world.Z[60]));
cout << tmp;
float lambda = tmp/((world.X[62]*(world.X[60]-world.X[7]))
+(world.Y[62]*(world.Y[60]-world.Y[7]))
+(world.Z[62]*(world.Z[60]-world.Z[7])));
cout << lambda;
float lambda_2 = tmp/((world.X[62]*(world.X[60]-world.X[6]))//MAKE ARROW HIGHER, ABOVE PROJECTION PLANE SQUARE
+(world.Y[62]*(world.Y[60]-world.Y[6]))
+(world.Z[62]*(world.Z[60]-world.Z[6])));
cout << lambda_2;
world.X[63] = world.X[60]+lambda*(world.X[60]-world.X[7]);//interseciton point for p7, X COMP
world.Y[63] = world.Y[60]+lambda*(world.Y[60]-world.Y[7]);//Y COMP
world.Z[63] = 0.0;
world.X[64] = world.X[60]+lambda_2*(world.X[60]-world.X[6]);//interseciton point for p7, X COMP
world.Y[64] = world.Y[60]+lambda_2*(world.Y[60]-world.Y[6]);//Y COMP
world.Z[64] = 0.0;
//for arrow's shade, 46-52
float lambda_arrow1 = tmp/((world.X[62]*(world.X[60]-world.X[46]))
+(world.Y[62]*(world.Y[60]-world.Y[46]))
+(world.Z[62]*(world.Z[60]-world.Z[46])));
float lambda_arrow2 = tmp/((world.X[62]*(world.X[60]-world.X[47]))//MAKE ARROW HIGHER, ABOVE PROJECTION PLANE SQUARE
+(world.Y[62]*(world.Y[60]-world.Y[47]))
+(world.Z[62]*(world.Z[60]-world.Z[47])));
float lambda_arrow3 = tmp/((world.X[62]*(world.X[60]-world.X[48]))
+(world.Y[62]*(world.Y[60]-world.Y[48]))
+(world.Z[62]*(world.Z[60]-world.Z[48])));
float lambda_arrow4 = tmp/((world.X[62]*(world.X[60]-world.X[49]))
+(world.Y[62]*(world.Y[60]-world.Y[49]))
+(world.Z[62]*(world.Z[60]-world.Z[49])));
float lambda_arrow5 = tmp/((world.X[62]*(world.X[60]-world.X[50]))
+(world.Y[62]*(world.Y[60]-world.Y[50]))
+(world.Z[62]*(world.Z[60]-world.Z[50])));
float lambda_arrow6 = tmp/((world.X[62]*(world.X[60]-world.X[51]))
+(world.Y[62]*(world.Y[60]-world.Y[51]))
+(world.Z[62]*(world.Z[60]-world.Z[51])));
float lambda_arrow7 = tmp/((world.X[62]*(world.X[60]-world.X[52]))
+(world.Y[62]*(world.Y[60]-world.Y[52]))
+(world.Z[62]*(world.Z[60]-world.Z[52])));
world.X[65] = world.X[60]+lambda_arrow1*(world.X[60]-world.X[46]);//interseciton point for p7, X COMP
world.Y[65] = world.Y[60]+lambda_arrow1*(world.Y[60]-world.Y[46]);//Y COMP
world.Z[65] = 0.0;
world.X[66] = world.X[60]+lambda_arrow2*(world.X[60]-world.X[47]);//interseciton point for p7, X COMP
world.Y[66] = world.Y[60]+lambda_arrow2*(world.Y[60]-world.Y[47]);//Y COMP
world.Z[66] = 0.0;
world.X[67] = world.X[60]+lambda_arrow3*(world.X[60]-world.X[48]);//interseciton point for p7, X COMP
world.Y[67] = world.Y[60]+lambda_arrow3*(world.Y[60]-world.Y[48]);//Y COMP
world.Z[67] = 0.0;
world.X[68] = world.X[60]+lambda_arrow4*(world.X[60]-world.X[49]);//interseciton point for p7, X COMP
world.Y[68] = world.Y[60]+lambda_arrow4*(world.Y[60]-world.Y[49]);//Y COMP
world.Z[68] = 0.0;
world.X[69] = world.X[60]+lambda_arrow5*(world.X[60]-world.X[50]);//interseciton point for p7, X COMP
world.Y[69] = world.Y[60]+lambda_arrow5*(world.Y[60]-world.Y[50]);//Y COMP
world.Z[69] = 0.0;
world.X[70] = world.X[60]+lambda_arrow6*(world.X[60]-world.X[51]);//interseciton point for p7, X COMP
world.Y[70] = world.Y[60]+lambda_arrow6*(world.Y[60]-world.Y[51]);//Y COMP
world.Z[70] = 0.0;
world.X[71] = world.X[60]+lambda_arrow7*(world.X[60]-world.X[52]);//interseciton point for p7, X COMP
world.Y[71] = world.Y[60]+lambda_arrow7*(world.Y[60]-world.Y[52]);//Y COMP
world.Z[71] = 0.0;
// -----------diffuse reflection-----------*
pt_diffuse diffuse; //diffuse.r[3]
//-------reflectivity coefficient-----------*
#define Kdr 0.8
#define Kdg 0.0
#define Kdb 0.0
// define additional pts to find diffuse reflection
//world.X[49] = world.X[45] + lambda_2*(world.X[45] - world.X[6]);
//--------compute distance------------------*//change 45 to 60!!!!!!
float distance[UpperBD];
for (int i=63; i<=71; i++) {
distance[i] = sqrt(pow((world.X[i]-world.X[60]),2)+ //intersect pt p7
pow((world.Y[i]-world.Y[60]),2)+
pow((world.X[i]-world.X[60]),2) );
//std::cout << "distance[i] " << distance[i] << std::endl;
}
// for (int i=4; i<=5; i++){
// distance[i] = sqrt(pow((world.X[i]-world.X[60]),2)+ //pt p4 of projection plane
// pow((world.Y[i]-world.Y[60]),2)+
// pow((world.X[i]-world.X[60]),2) );
// //std::cout << "distance[i] " << distance[i] << std::endl;
// }
//--------compute angle---------------------*
float angle[UpperBD], tmp_dotProd[UpperBD], tmp_mag_dotProd[UpperBD];
for (int i=63; i<=71; i++){
tmp_dotProd[i] = world.Z[i]-world.X[60];
std::cout << " tmp_dotProd[i] " << tmp_dotProd[i] << std::endl;
tmp_mag_dotProd[i] = sqrt(pow((world.X[i]-world.X[60]),2)+ //[45] pt light source
pow((world.Y[i]-world.Y[60]),2)+
pow((world.Z[i]-world.Z[60]),2) );
std::cout << " tmp_mag_dotProd[i] 1 " << tmp_mag_dotProd[i] << std::endl;
angle[i] = tmp_dotProd[i]/ tmp_mag_dotProd[i];
std::cout << "angle[i] " << angle[i] << std::endl;
//compute color intensity
diffuse.r[i] = Kdr * angle[i] / pow(distance[i],2) ;
diffuse.g[i] = Kdg * angle[i] / pow(distance[i],2) ;
diffuse.b[i] = Kdb * angle[i] / pow(distance[i],2) ;
}
// for (int i=4; i<=5; i++){
//
// tmp_dotProd[i] = world.Z[i]-world.X[45];
// std::cout << " tmp_dotProd[i] " << tmp_dotProd[i] << std::endl;
//
// tmp_mag_dotProd[i] = sqrt(pow((world.X[i]-world.X[45]),2)+ //[45] pt light source
// pow((world.Y[i]-world.Y[45]),2)+
// pow((world.Z[i]-world.Z[45]),2) );
// std::cout << " tmp_mag_dotProd[i] 1 " << tmp_mag_dotProd[i] << std::endl;
//
// angle[i] = tmp_dotProd[i]/ tmp_mag_dotProd[i];
// std::cout << "angle[i] " << angle[i] << std::endl;
//
// //compute color intensity
// diffuse.r[i] = Kdr * angle[i] / pow(distance[i],2) ;
// diffuse.g[i] = Kdg * angle[i] / pow(distance[i],2) ;
// diffuse.b[i] = Kdb * angle[i] / pow(distance[i],2) ;
//
// //std::cout << "diffuse.r[i] " << diffuse.r[i] << std::endl;
// //std::cout << "diffuse.g[i] " << diffuse.g[i] << std::endl;
// }
//
for(int i = 0; i < UpperBD; i++)
{
viewer.X[i] = -sPheta * world.X[i] + cPheta * world.Y[i];
viewer.Y[i] = -cPheta * cPhi * world.X[i]
- cPhi * sPheta * world.Y[i]
+ sPhi * world.Z[i];
viewer.Z[i] = -sPhi * cPheta * world.X[i]
- sPhi * cPheta * world.Y[i]
-cPheta * world.Z[i] + Rho;
// cout << i;
}
for(int i = 0; i <= UpperBD; i++)
{
perspective.X[i] = D_focal * viewer.X[i] / viewer.Z[i] ;
perspective.Y[i] = D_focal * viewer.Y[i] / viewer.Z[i] ;
if (perspective.X[i] > xMax) xMax = perspective.X[i];
if (perspective.X[i] < xMin) xMin = perspective.X[i];
if (perspective.Y[i] > yMax) yMax = perspective.Y[i];
if (perspective.Y[i] < yMin) yMin = perspective.Y[i];
/////*
//std::cout << "xMin " << xMin << std::endl;
// std::cout << "xMax " << xMax << std::endl;
// std::cout << "yMin " << yMin << std::endl;
// std::cout << "yMax " << yMax << std::endl;
//*/
}
for(int i = 0; i <= UpperBD; i++)
{
if ((xMax-xMin) != 0) perspective.X[i] = perspective.X[i]/(xMax-xMin);
if ((yMax-yMin) != 0) perspective.Y[i] = perspective.Y[i]/(yMax-yMin);
std::cout << i << perspective.X[i] << perspective.Y[i] << std::endl;
}
glViewport(0,0,1550,1250);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glBegin(GL_LINES);
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 0.0, 0.0);
glVertex2f(perspective.X[0],perspective.Y[0]);
glVertex2f(perspective.X[1],perspective.Y[1]);
glColor3f(0.0, 1.0, 0.0);
glVertex2f(perspective.X[0],perspective.Y[0]);
glVertex2f(perspective.X[2],perspective.Y[2]);
glColor3f(0.0, 0.0, 1.0);
glVertex2f(perspective.X[0],perspective.Y[0]);
glVertex2f(perspective.X[3],perspective.Y[3]);
glColor3f(1.0, 1.0, 0.0); // projection plane , square
glVertex2f(perspective.X[4],perspective.Y[4]);
glVertex2f(perspective.X[5],perspective.Y[5]);
glVertex2f(perspective.X[4],perspective.Y[4]);
glVertex2f(perspective.X[7],perspective.Y[7]);
glVertex2f(perspective.X[5],perspective.Y[5]);
glVertex2f(perspective.X[6],perspective.Y[6]);
glVertex2f(perspective.X[6],perspective.Y[6]);
glVertex2f(perspective.X[7],perspective.Y[7]);
glEnd();
glColor3f(0.0, 1.0, 0.0); // LETTER A STARTS HERE
glBegin(GL_POLYGON);
glVertex2f(perspective.X[13],perspective.Y[13]);
glVertex2f(perspective.X[12],perspective.Y[12]);
glVertex2f(perspective.X[11],perspective.Y[11]);
glVertex2f(perspective.X[12],perspective.Y[12]);
glVertex2f(perspective.X[14],perspective.Y[14]);
glVertex2f(perspective.X[13],perspective.Y[13]);
glVertex2f(perspective.X[18],perspective.Y[18]);
glVertex2f(perspective.X[17],perspective.Y[17]);
glVertex2f(perspective.X[11],perspective.Y[11]);
glVertex2f(perspective.X[17],perspective.Y[17]);
glVertex2f(perspective.X[18],perspective.Y[18]);
glVertex2f(perspective.X[14],perspective.Y[14]);
glEnd();
glColor3f(0.0, 1.0, 0.0);
glBegin(GL_POLYGON);
glVertex2f(perspective.X[8],perspective.Y[8]);
glVertex2f(perspective.X[15],perspective.Y[15]);
glVertex2f(perspective.X[14],perspective.Y[14]);
glVertex2f(perspective.X[15],perspective.Y[15]);
glVertex2f(perspective.X[14],perspective.Y[14]);
glVertex2f(perspective.X[18],perspective.Y[18]);
glVertex2f(perspective.X[16],perspective.Y[16]);
glVertex2f(perspective.X[18],perspective.Y[18]);
glVertex2f(perspective.X[16],perspective.Y[16]);
glVertex2f(perspective.X[10],perspective.Y[10]);
glVertex2f(perspective.X[9],perspective.Y[9]);
glVertex2f(perspective.X[10],perspective.Y[10]);
glVertex2f(perspective.X[8],perspective.Y[8]);
glVertex2f(perspective.X[9],perspective.Y[9]);
glEnd();
glColor3f(0.0, 1.0, 0.0);
glBegin(GL_POLYGON);
glVertex2f(perspective.X[16],perspective.Y[16]);
glVertex2f(perspective.X[17],perspective.Y[17]);
//etc...
glEnd();
glColor3f(0.0, 1.0, 0.0); //LETTER B STARTS HERE
glBegin(GL_POLYGON);
glVertex2f(perspective.X[19],perspective.Y[19]);
glVertex2f(perspective.X[20],perspective.Y[20]);
//etc...
glEnd();
glColor3f(0.0, 1.0, 0.0);
glBegin(GL_LINES);
//
glVertex2f(perspective.X[23],perspective.Y[23]);
glVertex2f(perspective.X[24],perspective.Y[24]);
glVertex2f(perspective.X[25],perspective.Y[25]);
glVertex2f(perspective.X[26],perspective.Y[26]);
glEnd();
glColor3f(0.0, 1.0, 0.0);
glBegin(GL_POLYGON);
glVertex2f(perspective.X[27],perspective.Y[27]);
glVertex2f(perspective.X[28],perspective.Y[28]);
//etc...
glEnd();
glColor3f(0.0, 1.0, 0.0);
glBegin(GL_POLYGON);
glVertex2f(perspective.X[29],perspective.Y[29]);
glVertex2f(perspective.X[30],perspective.Y[30]);
//etc...
glEnd();
glColor3f(0.0, 1.0, 0.0);
glBegin(GL_POLYGON);
glVertex2f(perspective.X[24],perspective.Y[24]);
glVertex2f(perspective.X[41],perspective.Y[41]);
//etc...
glEnd();
glColor3f(0.0, 1.0, 0.0);
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_LINES);//3D arrow starts here
glVertex2f(perspective.X[46],perspective.Y[46]);
glVertex2f(perspective.X[47],perspective.Y[47]);
//etc...
glEnd(); //end arrow
glColor3f(1.0, 1.0, 0.0);
glBegin(GL_LINES);
glVertex2f(perspective.X[63],perspective.Y[63]);
glVertex2f(perspective.X[64],perspective.Y[64]);
//etc...
glEnd(); //end arrow
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_LINES);
//arrow shadow
glVertex2f(perspective.X[65],perspective.Y[65]);
glVertex2f(perspective.X[66],perspective.Y[66]);
//etc...
glEnd();
glBindTexture(GL_TEXTURE_2D, texture[1]);
// glutSolidTeapot(0.1);
glBindTexture(GL_TEXTURE_2D, texture[0]);
glEnable( GL_TEXTURE_2D );
glColor4f( 1.0f, 1.0f, 1.0f, 1.0f );
glBegin(GL_QUADS);
glVertex2f(perspective.X[4],perspective.Y[4]);
glTexCoord2f(0.0, 0.0);
glVertex2f(perspective.X[5],perspective.Y[5]);
glTexCoord2f(0.1, 0.0);
glVertex2f(perspective.X[4],perspective.Y[4]);
glTexCoord2f(0.1, 0.1);
glVertex2f(perspective.X[7],perspective.Y[7]);
glTexCoord2f(0.0, 0.1);
glVertex2f(perspective.X[5],perspective.Y[5]);
glVertex2f(perspective.X[6],perspective.Y[6]);
glVertex2f(perspective.X[6],perspective.Y[6]);
glVertex2f(perspective.X[7],perspective.Y[7]);
glEnd();
glDisable( GL_TEXTURE_2D );
//glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
#define display_scaling 200000.0
#define display_shifting 0.2
for (int i=63; i<=71; i++) {
float r, g, b;
r = display_scaling*diffuse.r[i]+display_shifting;
//r = display_scaling*diffuse.r[i];
g = diffuse.g[i]; b = diffuse.b[i] ;
glColor3f(r, g, b);
std::cout << "display_scaling*diffuse.r[i] " << r << std::endl;
glBegin(GL_POLYGON);
glVertex2f(perspective.X[i],perspective.Y[i]);
glVertex2f(perspective.X[i]+0.1,perspective.Y[i]);
glVertex2f(perspective.X[i]+0.1,perspective.Y[i]+0.1);
glVertex2f(perspective.X[i],perspective.Y[i]+0.1);
glEnd();
}
gluPerspective(45.0,0.5,1.0,60.0);
gluOrtho2D(5, 10, 0.0, 10);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glutSwapBuffers();
glFlush();
//sleep(5);
}
int main(int argc, char** argv)
{
cv::Mat image = cv::imread("b.jpg", CV_LOAD_IMAGE_COLOR);
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB );
glutInitWindowSize(900, 1000);
glutCreateWindow("lab");
//imshow( "lab", image );
glutDisplayFunc(mydisplay);
myinit();
glutMainLoop();
}
glEnable(GL_TEXTURE_2D) has to be removed from myinit, because it is done immediately before the object with the texture is drawn.
Further use the STB library, which can be found at GitHub - nothings/stb to load the bitmap:
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
void myinit(void)
{
glGenTextures(2, texture);
int cx, cy, ch;
stbi_uc *img = stbi_load("g.bmp", &cx, &cy, &ch, 3);
if (!img)
return;
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glBindTexture(GL_TEXTURE_2D, texture[0]);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, 3, cx, cy, 0, GL_RGB, GL_UNSIGNED_BYTE, img);
stbi_image_free( img );
// ....
}
The number of vertex coordinates is UpperBD, so the maximum index is UpperBD-1 or < UpperBD, but not <= UpperBD.
Change (2 times):
for(int i = 0; i <= UpperBD; i++)
for(int i = 0; i < UpperBD; i++)
gluPerspective and gluOrtho2D at once makes no sense at all.
Init the projection matrix and the model view matrix at the begin of each frame in mydisplay:
void mydisplay()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0,0.5,1.0,60.0);
//gluOrtho2D(5, 10, 0.0, 10);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT);
.....
}
When the vertex coordinate is set by glVertex the current texture coordinates, and is associated with the vertex coordinate. This means glTexCoord has to be dine before glVertex. A GL_QUAD primitive consitis of 4 vertices and each vertex coordinate needs its own texture coordinate:
glBindTexture(GL_TEXTURE_2D, texture[0]);
glEnable( GL_TEXTURE_2D );
glColor4f( 1.0f, 1.0f, 1.0f, 1.0f );
glBegin(GL_QUADS);
glTexCoord2f(0.0, 0.0);
glVertex2f(perspective.X[4],perspective.Y[4]);
glTexCoord2f(1.0, 0.0);
glVertex2f(perspective.X[5],perspective.Y[5]);
glTexCoord2f(1.0, 1.0);
glVertex2f(perspective.X[6],perspective.Y[6]);
glTexCoord2f(0.0, 1.0);
glVertex2f(perspective.X[7],perspective.Y[7]);
glEnd();
Firstly thanks for giving your time.This is one of question which has a lot of answers but it does not work, here I am trying to take an example and let's see if we can solve this and maybe someone will get benefited again in future.
So the problem is we have glreadpixel() calling on a point on a circle, which is drawn by bresenham function.
But the thing is its not even giving any value than 0,0,0 for RGB on changing the background colour of the window.
Here is the big code, enjoy experimenting. I have tried everything. By the way, I am developing n macOS (OpenGL is hardware independent )
using namespace std;
#include <GLUT/glut.h>
#include <iostream>
#include <vector>
#include <CoreGraphics/CoreGraphics.h>
int r = 40;
int flag = 0;
int cordinates [50][3]=
{
{50, 50} , //0 station
{400, 450} , //1 station
{750, 250} //2 station
};
int matrix[50][50] = {
{0,1,1},
{1,0,1},
{1,1,0}
};
int trains[50][50] = {
{3,4,0,1,999},
{11,1,1,2,999},
{0,0,0,999}
};
int x,y;
int *x1, *y3, x2, y2;
int xx,yy,xxx,yyy,p,q,vertexcount,counter;
int xinc,xinc3,i,j,system_time,flag1,time_chekcer_cnt,dda =0;
char buf3[12],buf[12];
float tempx0,tempy0,tempx1,tempy1;
int train0 = 999 ;int start0,speed0,next0,nextx0,nexty0,final0 = 999 ;//999 signifies invalid
int train1 ,start1, speed1,next1,nextx1,nexty1,final1 = 999 ;//999 signifies invalid
int train2 ,start2, speed2,next2,final2 = 999 ;//999 signifies invalid
void init2D()
{
glClearColor(0,0,0,0.0);
glMatrixMode (GL_PROJECTION);
glLoadIdentity();
gluOrtho2D (0.0, 900.0, 0.0, 900.0);
}
;
void bresenham_circle(const int h, const int k,const int r)
{
int x=0,y=r,p=(3-(2*r));
do{
//Read pixel
unsigned char pixelub[3];
// glReadPixels(<#GLint x#>, <#GLint y#>, <#GLsizei width#>, <#GLsizei height#>, <#GLenum format#>, <#GLenum type#>, <#GLvoid *pixels#>)
glPointSize(1);
//draw two points
glColor3f(1.0, 1.0, 0.0);
glBegin(GL_POINTS);
glVertex2i((h+x),(k+y));
glEnd();
//color detection start
glReadPixels
(
(h+x),(k+y),
1, 1,
GLUT_RGB, GL_UNSIGNED_BYTE, &pixelub
);
//print
cout <<"reading pixel : "<<(h+x)<<" "<<(k+y);
printf("r: %u g: %u b: %u\n", pixelub[0], pixelub[1], pixelub[2]);
cout << endl;
//end
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_POINTS);
glVertex2i((h+y),(k+x));
glEnd();
glBegin(GL_POINTS);
glVertex2i((h+y),(k-x));
glEnd();
glBegin(GL_POINTS);
glVertex2i((h+x),(k-y));
glEnd();
glBegin(GL_POINTS);
glVertex2i((h-x),(k-y));
glEnd();
glBegin(GL_POINTS);
glVertex2i((h-y),(k-x));
glEnd();
glBegin(GL_POINTS);
glVertex2i((h-y),(k+x));
glEnd();
glBegin(GL_POINTS);
glVertex2i((h-x),(k+y));
glEnd();
x++;
if(p<0){
p+= ((4*x)+6);
}else {
y--;
p+=(4*(x-y)+10);
}
}
while (x<=y);
}
void drawBitmapText(char *string,float x,float y,float z)
{
char *c;
glRasterPos3f(x, y,z);
for (c=string; *c != NULL; c++)
{
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, *c);
}
}
void systemtime(){
sprintf(buf, "%d", system_time); // puts string into buffer
printf("%s\n", buf);
sprintf(buf3, "%d", system_time-1); // puts string into buffer
if(system_time >1){
glColor3f(1.0, 1.0, 1.0);
drawBitmapText(buf3,200,200,0);
glColor3f(0.0, 1.0, 0.0);
drawBitmapText(buf,200,200,0);
system_time =system_time+1;
}else {
drawBitmapText(buf,200,200,0);
system_time =system_time+1;
}
};
void draw_pixel(int x, int y){
glPointSize(5);
glColor3f(1.0, 1.0, 0.0);
glBegin(GL_POINTS);
cout << "\n THIS IS PRINTING X and Y :"<<x<<" & "<<y<<endl;
glVertex2i(x, y);
glEnd();
glFlush();
}
//bresenham ..... i vant DDA
void draw_dda( float *x0, float *y0, int x1, int y1,int speed) {
//cout << "\n LOOPING FOR START CORDIANTES : X0 and Y0 "<<*x0<<*y0<<endl;
int dx = x1 - *x0;
int dy = y1 - *y0;
//GLfloat x1 = p1.x; GLfloat y1 = p1.y;
GLfloat step = 0;
if(abs(dx) > abs(dy)) {
step = abs(dx);
} else {
step = abs(dy);
}
GLfloat xInc = dx/step;
GLfloat yInc = dy/step;
for (int speed_count = 0 ; speed_count < speed ; speed_count++){
glPointSize(5);
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_POINTS);
//cout << "\n THIS IS PRINTING X and Y :"<<xInc<<" & "<<yInc<<endl;
glVertex2i(*x0, *y0);
glEnd();
int cy1 = *y0;
int cx1 = *x0;
//cout << "\n calling bresenham";
glColor3f(1.0, 1.0, 1.0);
bresenham_circle(cx1, cy1, r);
//cout << " \n" <<cx1<<" "<<cy1<<" "<<r;
while (flag != 1){
r--;
//cout <<"\n r is "<<r<<endl;
if (r == 0){
flag = 1;
}
}
r =40;flag= 0;
*x0 = *x0+xInc;
*y0 = *y0+yInc;
glColor3f(1.0, 0.0, 0.0);
int cy = *y0;
int cx = *x0;
//cout << "\n calling bresenham";
bresenham_circle(cx, cy, r);
//cout << " \n" <<cx<<" "<<cy<<" "<<r;
while (flag != 1){
r--;
//cout <<"\n r is "<<r<<endl;
if (r == 0){
flag = 1;
}
}
r =40;flag= 0;
//cout << "\n THIS IS PRINTING X and Y :"<<xInc<<" & "<<yInc<<endl;
}
}
void drawline(float *x0, float *y0, int x1, int y1)
{ cout << "\n LOOPING FOR START CORDIANTES : ("<<*x0<<","<<*y0<<") To ("<<x1<<","<<y1<<")"<<endl;
int dx, dy, p, x, y;
dx=x1-*x0;
dy=y1-*y0;
x=*x0;
y=*y0;
p=2*dy-dx;
//cout << "X and X1 "<<x<<x1<<endl;
if (x<x1)
{
if(p>=0)
{
draw_pixel(x,y);
//cout << ">>>>>. Y INCREMENTED >>>>> "<<y<<endl;
y=y+1;
p=p+2*dy-2*dx;
}
else
{ //cout << "\n >>>>>NOT Y INCREMENTED >>>>> "<<y<<endl;
draw_pixel(x,y);
//cout << "X and Y "<<x<<y<<endl;
p=p+2*dy;
}
x=x+1;
}
*x0=x;
*y0=y;
//cout << "\n X "<<x<<" and Y "<<y<<endl;
//cout << "\n X0 "<<*x0<<" and Y0 "<<*y0<<endl;
}
void display_ndots()
{glClear(GL_COLOR_BUFFER_BIT);
glPointSize(5);
glColor3f(1.0, 0.0, 0.0);
//draw two points
glBegin(GL_POINTS);
for(int i = 0; i < 10; i++)
{ xx = cordinates[i][0];
yy = cordinates[i][1];
glVertex2i(xx,yy);
//printf("%i",xx);
}
glEnd();
glColor3f(0.0, 1.0, 0.0);
//draw a line
glLineWidth(3);
glBegin(GL_LINES);
for(counter = 0 ; counter < 3 ; counter ++){
for (p = 0 ; p < 3 ; p ++){
for (q = 0 ; q < 3 ; q ++){
if( matrix[p][q] == 1){
xx = cordinates[p][0];
yy = cordinates[p][1];
xxx = cordinates[q][0];
yyy = cordinates[q][1];
glVertex2i(xx,yy);
glVertex2i(xxx,yyy);
}
}
}
}
glEnd();
systemtime();
time_chekcer_cnt = 0;
for(time_chekcer_cnt = 0 ; time_chekcer_cnt <10 ; time_chekcer_cnt ++){
if (system_time == trains[time_chekcer_cnt][0]){
switch (time_chekcer_cnt)
{
case 0: printf("Trian number %i have been started server time is %i \n",time_chekcer_cnt,system_time);
/*Initializing Train Data*/
train0 = time_chekcer_cnt;
speed0 = trains[time_chekcer_cnt][1];
start0 = trains[time_chekcer_cnt][2];
cout<<"\n >>>>>>>>>>>>>"<<start0<<endl;
tempx0 = cordinates[start0][0];
tempy0 = cordinates[start0][1];
next0 = trains[time_chekcer_cnt][3];
nextx0 = cordinates[next0][0];
nexty0 = cordinates[next0][1];
;
i=0;
while (trains[time_chekcer_cnt][i] != 999) {
i = i+1;
}
final0 = trains[time_chekcer_cnt][i-1];//999 signifies invalid
printf("\nfinal station is %i \n",final0);
//tempx01 = cordinates[start0][0]+10;
//tempy01 = cordinates[start0][1];
break;
case 1:
printf("Trian number %i have been started server time is %i \n",time_chekcer_cnt,system_time);
/*Initializing Train Data*/
train1 = time_chekcer_cnt;
speed1 = trains[time_chekcer_cnt][1];
start1 = trains[time_chekcer_cnt][2];
cout<<"\n >>>>>>>>>>>>>"<<start0<<endl;
tempx1 = cordinates[start0][0];
tempy1 = cordinates[start0][1];
next1 = trains[time_chekcer_cnt][3];
nextx1 = cordinates[next0][0];
nexty1 = cordinates[next0][1];
;
i=0;
while (trains[time_chekcer_cnt][i] != 999) {
i = i+1;
}
final1 = trains[time_chekcer_cnt][i-1];//999 signifies invalid
printf("\nfinal station is %i \n",final0);
break;
//default: // code to be executed if n doesn't match any cases
}
}
}
if (train0 != 999){
glColor3f(1.0, 1.0, 0.0);
draw_dda( &tempx0, &tempy0 ,nextx0, nexty0,speed0);
cout << "Draving from corinates ("<<tempx0<<","<<tempy0<<") To ("<<nextx0<<","<<nexty0<<")"<<endl;
}
if (train1 != 999){
glColor3f(1.0, 1.0, 0.0);
/// cout << "original x and y are "<<nextx0<<" & "<<nexty0;
draw_dda( &tempx1, &tempy1 ,nextx1, nexty1,speed1);
cout << "Draving from corinates ("<<tempx0<<","<<tempy0<<") To ("<<nextx0<<","<<nexty0<<")"<<endl;
// drawline( &tempx0, &tempy0 ,nextx0, nexty0);
//draw_dda( &tempx01, &tempy01 ,nextx0+10, nexty0);
// cout<<"After call by reference it is :"<<nextx0<<" & "<<nexty0;
}
/*bresenham_circle(100, 100, r);
while (flag != 1){
r--;
cout <<"\n r is "<<r<<endl;
if (r == 0){
flag = 1;
}
}*/
glFlush();
glGetError();
}
void timlycall (int unused) {
glutPostRedisplay();
glutTimerFunc(1000, timlycall, 0);
}
int main(int argc,char *argv[])
{
glutInit(&argc,argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (900, 900);
glutInitWindowPosition (0, 0);
glutCreateWindow ("points and lines");
init2D();
glutDisplayFunc(display_ndots);
//glutDisplayFunc(init2D);
glutTimerFunc(0, timlycall, 0);
glutMainLoop();
return 0;
}
Please not macos have library GLUT but windows have GL
Update 1.0
OK folks we have made some progress :
Using GLUT_RGB in glreadpixel() gives error code 1280 i.e. detected
by method BDL have provided. Which stands for incorrect enumeration ,
so use GL_RGB inside glreadpixel()
Now one more interesting thing we have to tackle, i.e now GlReadPixel
is giving r:255 g: 255 b: 255 as output , i.e background color
instead of color that must be yellow , because we are calling the
function on point which lies on the circle that too after its
painted.
You are passing a wrong enumeration to glReadPixels. GLUT_RGB is not the same as GL_RGB and may thus not be used for this function.
This would have been reported as a GL_INVALID_ENUM error by glGetError(), but the error code is never checked. You should use something like:
GLenum error = glGetError();
if (error != GL_NO_ERROR)
std::cout << "OpenGL error: " << error << std::endl;
I am having a problem with changing the size of a polygon that I am calling from a text file using vertices. Whenever I try and change the coordinates of the vertices in the text file and run the program the shape stays the same size and when I go back to the text file all the coordinates have changed back. How can I change the shapes size?
Here is the code I'm using for this:
void cal_vertices() {
// open a file for writing pentagon vertices
ofstream outfile("vertices1.txt");
float a = 2 * 3.1415926 / 5.0;
float x1 = 0.0, y1 = 1.0;
outfile << x1 << " " << y1 << endl;;
float x, y;
for (int i = 1; i < 5; i++) {
x = x1 * cos(a * i) - y1 * sin(a * i);
y = y1 * cos(a * i) + x1 * sin(a * i);
outfile << x << " " << y << endl;;
}
outfile.close();
}
void read_vertices() {
//reads verticies from the text file
ifstream infile("vertices1.txt");
for (int i = 0; i < 5; i++){
infile >> vertices[i][0];
infile >> vertices[i][1];
cout << vertices[i][0] << " " << vertices[i][1] << endl;
}
}
void init(){
cal_vertices();
read_vertices();
glNewList(listname, GL_COMPILE);
glColor4f(red, green, blue, 1.0);
glBegin(GL_LINE_LOOP);
for (int i = 0; i < 5; i++){
glVertex3f(vertices[i][0], vertices[i][1], 0.0);
}
glEnd();
glEndList();
Try this:
glPushMatrix ();
glScalef (2.0F, 2.0F, 2.0F);
glBegin(GL_LINE_LOOP);
...
glEnd();
glPopMatrix ();
That should double the size of your polygon in each dimension.