Opengl translation with glMultMatrixf - c++

Im trying to translate an object without using glTranslate(). I have searched through web and found a function glMultMatrixf(). I wanted to multiply my translation matrix using this function but I couldn't accomplished it. I feel like I'm on the correct path logically but is translating an object this way even possible?
I have written the code using opengl and c++. Here is the code:
#include <iostream>
#include <stdlib.h>
#include <math.h>
#ifdef __APPLE__
#include <OpenGL/OpenGL.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
using namespace std;
float _angle = 0;
typedef GLfloat Matrix4x4 [4][4];
Matrix4x4 matTransl3D;
/* Construct the 4 x 4 identity matrix. */
void matrix4x4SetIdentity (Matrix4x4 matIdent4x4)
{
GLint row, col;
for (row = 0; row < 4; row++)
for (col = 0; col < 4 ; col++)
matIdent4x4 [row][col] = (row == col);
}
void translate3D (GLfloat tx, GLfloat ty, GLfloat tz)
{
/* Initialize translation matrix to identity. */
matrix4x4SetIdentity (matTransl3D);
matTransl3D [0][3] = tx;
matTransl3D [1][3] = ty;
matTransl3D [2][3] = tz;
}
void handleKeypress(unsigned char key, int x, int y) {
switch (key) {
case 27: //Escape key
exit(0);
}
}
void initRendering()
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_NORMALIZE);
}
void handleResize(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, (float)w / (float)h, 1.0, 200.0);
}
void drawScene()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
translate3D(0.0f, 0.0f, -50.0f);
glMultMatrixf(*matTransl3D);
glBegin(GL_TRIANGLE_FAN); // draw triangle
glColor3f(1.0f,0.0f,0.0f); // set color to red
glVertex3f( 0.0f, 3.0f, 0.0f);
glColor3f(0.0f,1.0f,0.0f); // set color to green
glVertex3f(-5.0f, -5.0f, 5.0f);
glColor3f(1.0f,1.0f,0.0f); // set color to yellow
glVertex3f( 5.0f, -5.0f, 5.0f);
glColor3f(0.0f,0.0f,1.0f); // set color to blue
glVertex3f( 5.0f, -5.0f, -5.0f);
glColor3f(1.0f,1.0f,1.0f); // set color to white
glVertex3f( -5.0f, -5.0f, -5.0f);
glColor3f(0.0f,1.0f,0.0f); // set color to green
glVertex3f(-5.0f, -5.0f, 5.0f);
glEnd();
glBegin(GL_QUADS);
glColor3f(0.0f,1.0f,0.0f); // set color to green
glVertex3f(-5.0f, -5.0f, 5.0f);
glColor3f(1.0f,1.0f,1.0f); // set color to white
glVertex3f( -5.0f, -5.0f, -5.0f);
glColor3f(0.0f,0.0f,1.0f); // set color to blue
glVertex3f( 5.0f, -5.0f, -5.0f);
glColor3f(1.0f,1.0f,0.0f); // set color to yellow
glVertex3f( 5.0f, -5.0f, 5.0f);
glEnd();
glutSwapBuffers();
}
//Called every 25 milliseconds
void update(int value) {
_angle += 1.0f;
if (_angle > 360) {
_angle -= 360;
}
glutPostRedisplay();
glutTimerFunc(25, update, 0);
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(400, 400);
glutCreateWindow("Translation 3d");
initRendering();
glutDisplayFunc(drawScene);
glutKeyboardFunc(handleKeypress);
glutReshapeFunc(handleResize);
glutTimerFunc(25, update, 0);
glutMainLoop();
return 0;
}

OpenGL takes matrices as column major, i.e. the indexing is
0 4 8 c
1 5 9 d
2 6 a e
3 7 b f
However you're indexing your translation matrix in the order
0 1 2 3
4 5 6 7
8 9 a b
c d e f

Related

How do I get color to change using glut and openGL?

I am trying to teach myself to animate an object without user input, so far I have figured out how to make a scene rotate. How do I get an object to change color though? I thought the code I have would do it, but it remains a white triangle (not even a different color).
How do I get it to change color at the same time that the triangle or perspective rotates?
Here is my current code:
#include <GL/glut.h>
float color1;
float color2;
float color3;
void changeSize(int w, int h) {
// Prevent a divide by zero, when window is too short
// (you cant make a window of zero width).
if (h == 0)
h = 1;
float ratio = w * 1.0 / h;
// Use the Projection Matrix
glMatrixMode(GL_PROJECTION);
// Reset Matrix
glLoadIdentity();
// Set the viewport to be the entire window
glViewport(0, 0, w, h);
// Set the correct perspective.
gluPerspective(45.0f, ratio, 0.1f, 100.0f);
//changeColor?
color1 += 0.1f;
color2 += 0.3;
color3 += color2;
if (color1 > 1.0)
color1 = 0;
if (color2 > 1.0)
color2 = 0;
if (color3 > 1.0)
color3 = 0;
// Get Back to the Modelview
glMatrixMode(GL_MODELVIEW);
}
float angle = 0.0f;
void renderScene(void) {
// Clear Color and Depth Buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Reset transformations
glLoadIdentity();
// Set the camera
gluLookAt(0.0f, 0.0f, 10.0f,
0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f);
glRotatef(angle, 0.0f, 1.0f, 0.0f);
glBegin(GL_TRIANGLES);
glColor3f(color1, color2, color3);
glVertex3f(2.0f, -2.0f, 0.0f);
glVertex3f(2.0f, 0.0f, 0.0);
glVertex3f(0.0f, 2.0f, 0.0);
glEnd();
angle += 0.1f;
color1 += 0.1f;
color2 += 0.3;
color3 += color2;
glutSwapBuffers();
}
int main(int argc, char **argv) {
// init GLUT and create window
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(100, 100);
glutInitWindowSize(320, 320);
glutCreateWindow("tutorial example");
// register callbacks
glutDisplayFunc(renderScene);
glutReshapeFunc(changeSize);
glutIdleFunc(renderScene);
// enter GLUT event processing cycle
glutMainLoop();
return 1;
}
Float colors have to be in range of [0,1] and you only add something to your values and never reset it to zero, so it becomes greater than 1 in first 10 frames (=very fast), OpenGL clamps it to 1, so you see it white.
I.e. that bunch of ifs in changeSize should actually be in renderScene.
For something simple like this use a glutTimerFunc() callback with a reasonable timeout
Update the angle/color in the timer callback & kick off a repaint
Re-set the projection/modelview matrices each time through the glutDisplayFunc() callback, helps prevent weird matrix problems
All together:
#include <GL/glut.h>
float angle = 0.0f;
float color1 = 0.0f;
float color2 = 0.0f;
float color3 = 0.0f;
void timer( int value )
{
angle += 3.0f;
//changeColor?
color1 += 0.001f;
color2 += 0.003f;
color3 += color2;
if (color1 > 1.0)
color1 = 0;
if (color2 > 1.0)
color2 = 0;
if (color3 > 1.0)
color3 = 0;
glutPostRedisplay();
glutTimerFunc( 16, timer, 0 );
}
void renderScene()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
double w = glutGet( GLUT_WINDOW_WIDTH );
double h = glutGet( GLUT_WINDOW_HEIGHT );
gluPerspective(45.0f, w / h, 0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt
(
0.0f, 0.0f, 10.0f,
0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f
);
glRotatef(angle, 0.0f, 1.0f, 0.0f);
glBegin(GL_TRIANGLES);
glColor3f(color1, color2, color3);
glVertex3f(2.0f, -2.0f, 0.0f);
glVertex3f(2.0f, 0.0f, 0.0);
glVertex3f(0.0f, 2.0f, 0.0);
glEnd();
glutSwapBuffers();
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowSize(320, 320);
glutCreateWindow("tutorial example");
glutDisplayFunc(renderScene);
glutTimerFunc( 0, timer, 0 );
glutMainLoop();
return 1;
}

3D Cube Drawing, Only One Side Is Always On Top

I was working with OpenGL C++ drawing shapes, specifically cubes. In my current project, I managed to draw a cube correctly, but only the side of the cube that gets drawn last doesn't go transparent when the camera is directly on it. The first two sides of the cube go completely transparent when viewed head-on. Is there a way to fix this? Here is the picture. As you can see, the first two sides don't get displayed. Here is my code:
Main.cpp:
#include "Render.h"
#include <stdlib.h>
int screenHeight = 500;
int screenWidth = 500;
int screenFPS = 60;
void MainLoop(int val);
int main(int argc, char* args[])
{
glutInit(&argc, args);
glutInitDisplayMode(GLUT_DOUBLE);
glutInitWindowSize(screenWidth, screenHeight);
glutInitWindowPosition(350, 80);
glutCreateWindow("Cube");
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//glOrtho(0.0f, screenWidth, screenHeight, 0.0f, 0.0f, 1.0f);
gluPerspective(40, 1, 0.5, 20);
glutDisplayFunc(Render);
glViewport(0, 0, screenWidth, screenHeight);
glutKeyboardFunc(HandleKeys);
glutIdleFunc(Animation);
glutTimerFunc(1000 / screenFPS, MainLoop, 0);
glutMainLoop();
return 0;
}
void MainLoop(int val)
{
Render();
glutTimerFunc( 1000 / screenFPS, MainLoop, val );
}
Render.cpp:
#include "Render.h"
#include <iostream>
#include <stdlib.h>
#include <windows.h>
GLfloat xRot, yRot, zRot;
void Render()
{
std::cout << xRot << " " << yRot << " " << zRot << "\n";
glMatrixMode(GL_MODELVIEW);
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glTranslatef(0.0,0.0,-10.5);
glRotatef(yRot, 1.0, 0.0, 0.0);
glRotatef(yRot, 0.0, 1.0, 0.0);
glRotatef(zRot, 0.0, 0.0, 1.0);
glBegin(GL_QUADS);
glColor4f(0.0f, 1.0f, 0.0f, 1.0f);
glVertex3f( 1.0f, 1.0f,-1.0f);
glVertex3f(-1.0f, 1.0f,-1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f);
glColor4f(1.0f, 0.5f, 0.0f, 1.0f);
glVertex3f( 1.0f,-1.0f, 1.0f);
glVertex3f(-1.0f,-1.0f, 1.0f);
glVertex3f(-1.0f,-1.0f,-1.0f);
glVertex3f( 1.0f,-1.0f,-1.0f);
glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f,-1.0f, 1.0f);
glVertex3f( 1.0f,-1.0f, 1.0f);
glColor4f(1.0f, 1.0f, 0.0f, 1.0f);
glVertex3f( 1.0f,-1.0f,-1.0f);
glVertex3f(-1.0f,-1.0f,-1.0f);
glVertex3f(-1.0f, 1.0f,-1.0f);
glVertex3f( 1.0f, 1.0f,-1.0f);
glColor4f(0.0f, 0.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f, 1.0f);
glVertex3f(-1.0f, 1.0f,-1.0f);
glVertex3f(-1.0f,-1.0f,-1.0f);
glVertex3f(-1.0f,-1.0f, 1.0f);
glColor4f(1.0f, 0.0f, 1.0f, 1.0f);
glVertex3f( 1.0f, 1.0f,-1.0f);
glVertex3f( 1.0f, 1.0f, 1.0f);
glVertex3f( 1.0f,-1.0f, 1.0f);
glVertex3f( 1.0f,-1.0f,-1.0f);
glEnd();
glutSwapBuffers();
}
void Animation()
{
yRot += 0.03;
xRot += 0.08;
Render();
}
void HandleKeys(unsigned char key, int x, int y)
{
if(key == 27)
exit(0);
else if(key == 'w')
yRot += 0.55;
else if(key == 'a')
xRot -= 0.55;
else if(key == 's')
yRot -= 0.55;
else if(key == 'd')
xRot += 0.55;
}
Render.h
#include "GLLib.h"
extern int screenHeight;
extern int screenWidth;
extern int screenFPS;
void Render();
void Animation();
void HandleKeys(unsigned char key, int x, int y);
And finally my librarys, GLLib.h:
#ifndef GLLIB_H
#define GLLIB_H
#include <GL/freeglut.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#endif
Chances are that all sides are drawn just fine. The problem is that you don't have a depth buffer. Therefore, everything that is drawn replaces what was drawn previously, no matter if it's in front or behind the previously drawn geometry.
To use a depth buffer, you have to request it during initialization:
glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
and enable depth testing before you start rendering:
glEnable(GL_DEPTH_TEST);
Then, at the start of rendering each frame, you need to clear the depth buffer in addition to the color buffer:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
This will make sure that the front most faces are visible, and the faces behind them are hidden, independent of the drawing order.

C++ and GLUT smooth movement

I am new at using graphics with C++ and I have the following code from this
tutorial
here is the code
#include <windows.h>
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <stdlib.h>
#include <math.h>
float angle = 0.0f;
float lx = 0.0f, lz = -1.0f;
float x = 0.0f, z = 5.0f;
float deltaAngle = 0.0f;
float deltaMove = 0;
void drawSnowMan(){
glColor3f(1.0f, 1.0f, 1.0f);
glTranslatef(0.0f, 0.75f, 0.0f);
glutSolidSphere(0.75f, 20, 20);
glTranslatef(0.0f, 1.0f, 0.0f);
glutSolidSphere(0.25f, 20, 20);
glPushMatrix();
glColor3f(0.0f, 0.0f, 0.0f);
glTranslatef(0.5f, 0.10f, 0.18f);
glutSolidSphere(0.05f, 10, 10);
glTranslatef(-0.1f, 0.0f, 0.0f);
glutSolidSphere(0.05f, 10, 10);
glPopMatrix();
glColor3f(1.0f, 0.5f, 0.5f);
glutSolidCone(0.8f, 0.5f, 10, 2);
}
void changeSize(int w, int h){
if(h == 0)
h = 1;
float ratio = 1.0*w/h;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0,0,w,h);
gluPerspective(45.0f, ratio, 0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW);
}
void computePos(float deltaMove){
x += deltaMove * lx * 0.1f;
z += deltaMove * lz * 0.1f;
}
void computeDir(float deltaAngle){
angle += deltaAngle;
lx = sin(angle/75.0);
lz = -cos(angle/75.0);
}
void pressKey(int key, int xx, int yy){
switch(key){
case GLUT_KEY_LEFT: deltaAngle = -0.5f; break;
case GLUT_KEY_RIGHT: deltaAngle = 0.5; break;
case GLUT_KEY_UP: deltaMove = 0.5f; break;
case GLUT_KEY_DOWN: deltaMove = -0.5f; break;
}
}
void relaseKey(int key, int x, int y){
switch(key){
case GLUT_KEY_LEFT:
case GLUT_KEY_RIGHT: deltaAngle = 0.0f; break;
case GLUT_KEY_UP:
case GLUT_KEY_DOWN: deltaMove = 0; break;
}
}
void renderScene(void){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
if(deltaMove)
computePos(deltaMove);
if(deltaAngle)
computeDir(deltaAngle);
gluLookAt( x, 1.0f, z,
x+lx, 1.0f, z+lz,
0.0f, 1.0f, 0.0f
);
glColor3f(0.9f, 0.9f, 0.9f);
glBegin(GL_QUADS);
glVertex3f(-100.0f, 0.0f, -100.0f);
glVertex3f(-100.0f, 0.0f, 100.0f);
glVertex3f(100.0f, 0.0f, 100.0f);
glVertex3f(100.0f, 0.0f, -100.0f);
glEnd();
angle += 0.1f;
for(int i = -3; i < 3; i++){
for(int j = -3; j < 3; j++){
glPushMatrix();
glTranslatef(i*10.0,0, j*10.0);
drawSnowMan();
glPopMatrix();
}
}
glutSwapBuffers();
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(320,320);
glutInitWindowPosition(100,100);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Lighthouse 3D");
glutDisplayFunc(renderScene);
glutReshapeFunc(changeSize);
glutIdleFunc(renderScene);
glutSpecialFunc(pressKey);
glutIgnoreKeyRepeat(1);
glutSpecialUpFunc(relaseKey);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
return 1;
}
My problem is the following, when i try to turn to the left and i keep the left key pressed everything works perfectly fine. When i try to hit the left once the action is not smooth at all. In some cases if the button stroke is too fast it even turns to the opposite direction!
I assume you mean keyboard instead of mouse, in which case to have a "smoother" and "slower" feel you need to adjust your deltaAngle values, which might be too high.
This is only a temporary fix, since those values may affect other machines in different ways - some may be faster, some may be slower. You need to calculate the host machine's FPS in your render loop and multiply your delta values with it, to have the same performance on every computer. This is called time-based movement and is an essential feature of every modern graphics application.
This is exactly what is happening in the following tutorial, when a dot is moving too fast on the screen.
http://lazyfoo.net/SDL_tutorials/lesson32/index.php
A glutIdleFunc() will eat all your battery/CPU/GPU, use a glutTimerFunc() instead to redraw on a predictable, sane schedule.
Accumulate your input state between frames and apply it in your glutTimerFunc() instead of trying to do it right in your keyup/keydown callbacks.
No need for a glutResizeFunc(), do all that just before your draw.
You're using C++ so you should use the C++ versions of C headers, like <cmath> instead of <math.h>.
All together:
#include <GL/glut.h>
#include <cmath>
#include <map>
std::map< int, bool > keys;
void pressKey(int key, int xx, int yy)
{
keys[ key ] = true;
}
void relaseKey(int key, int x, int y)
{
keys[ key ] = false;
}
float angle = 0.0f;
float lx = 0.0f, lz = -1.0f;
float x = 0.0f, z = 5.0f;
void update()
{
const float angleStep = 0.5f;
if( keys[ GLUT_KEY_LEFT ] ) angle -= angleStep;
if( keys[ GLUT_KEY_RIGHT ] ) angle += angleStep;
const float moveStep = 0.5f;
float move = 0.0f;
if( keys[ GLUT_KEY_DOWN ] ) move -= moveStep;
if( keys[ GLUT_KEY_UP ] ) move += moveStep;
x += move * lx * 0.1f;
z += move * lz * 0.1f;
lx = sin(angle/75.0);
lz = -cos(angle/75.0);
}
void drawSnowMan()
{
glColor3f(1.0f, 1.0f, 1.0f);
glTranslatef(0.0f, 0.75f, 0.0f);
glutSolidSphere(0.75f, 20, 20);
glTranslatef(0.0f, 1.0f, 0.0f);
glutSolidSphere(0.25f, 20, 20);
glPushMatrix();
glColor3f(0.0f, 0.0f, 0.0f);
glTranslatef(0.5f, 0.10f, 0.18f);
glutSolidSphere(0.05f, 10, 10);
glTranslatef(-0.1f, 0.0f, 0.0f);
glutSolidSphere(0.05f, 10, 10);
glPopMatrix();
glColor3f(1.0f, 0.5f, 0.5f);
glutSolidCone(0.8f, 0.5f, 10, 2);
}
void renderScene(void)
{
glEnable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
const double w = glutGet( GLUT_WINDOW_WIDTH );
const double h = glutGet( GLUT_WINDOW_HEIGHT );
gluPerspective(45.0f, w / h, 0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt
(
x, 1.0f, z,
x+lx, 1.0f, z+lz,
0.0f, 1.0f, 0.0f
);
glColor3f(0.9f, 0.9f, 0.9f);
glBegin(GL_QUADS);
glVertex3f(-100.0f, 0.0f, -100.0f);
glVertex3f(-100.0f, 0.0f, 100.0f);
glVertex3f(100.0f, 0.0f, 100.0f);
glVertex3f(100.0f, 0.0f, -100.0f);
glEnd();
for(int i = -3; i < 3; i++)
{
for(int j = -3; j < 3; j++)
{
glPushMatrix();
glTranslatef(i*10.0,0, j*10.0);
drawSnowMan();
glPopMatrix();
}
}
glutSwapBuffers();
}
void timer( int value )
{
update();
glutTimerFunc( 16, timer, 0 );
glutPostRedisplay();
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(320,320);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("Lighthouse 3D");
glutDisplayFunc(renderScene);
glutSpecialFunc(pressKey);
glutSpecialUpFunc(relaseKey);
glutTimerFunc( 0, timer, 0 );
glutMainLoop();
return 1;
}

OpenGL Plane not showing up

I'm making a particle fountain in openGL, I have the particles functioning properly. I decided to add a plane to make it look like they are bouncing off from it. What I'm trying to get is something like this
Unfortunately what I'm getting is this
the plain doesn't seem to be appearing at all. I tried messing with the co-ordinates and that doesn't seem to do anything. This is the image I'm using as the texture, it's a 256 X 256 24bit bmp.
I load the texture in the init function, then call it before I render the particles in the following function
void Load_Plane(){
glEnable(GL_BLEND);
glBlendFunc(GL_ONE_MINUS_SRC_ALPHA, GL_SRC_ALPHA);
glColor4f(0.0f, 0.2f, 0.2f, 0.5f);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, txPlane);
glBegin(GL_QUADS);
glNormal3f(-10.0f, 0.0f, -10.0f);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-10.0f, 0.0f, 10.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 10.0f, 0.0f, 10.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 10.0f, 0.0f, -10.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-10.0f, 0.0f, -10.0f);
glEnd();
}
full code
// particle_fountain.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<stdlib.h>
#include <stdio.h>
#include<Windows.h>
#include <time.h>
#include <GL\glut.h>
#include<GL\GLU.h>
#define MAX_PARTICLES 200 //max number of particles
#define MAX_BOUNCE_COUNT 5 //number of times a particle should bounce
#define MAX_PARTICLE_AGE 95
//Colours
float R = 0.8f;
float G = 0.2f;
float B = 0.0f;
float cR = 0.001f;
float cG = 0.002f;
float cB = 0.003f;
float Size = 0.02f; //size for points
GLuint txParticle;
GLuint txPlane;
struct PARTICLE {
float X,Y,Z; // Current position
float sX,sY,sZ; // Current Speed/Movement
float tX,tY,tZ; // Target Speed/Movement
float R,B,G; // Particle Colour
bool Active; // Is particle Active
int Age; // Age of the particle
int MaxAge; // Maximum Age before particle dies
int BounceCount;
} Particles[MAX_PARTICLES];
void Init_Particles();
void Activate_Particles();
void Adjust_Particles();
void Render_Particles();
bool LoadBitmapTexture(char * FileName, GLuint &texid);
void timer(int extra);
void Load_Plane();
void DrawGLscene();
void Reshape(GLsizei w, GLsizei h);
int main(int argc, char** argv){
glutInit(&argc,argv);
glutInitDisplayMode( GLUT_RGBA| GLUT_DOUBLE );
glutInitWindowSize( 640, 480 );
glutCreateWindow("Particle fountain");
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-1.0, 1.0, -1.0, 1.0, 1.0, 10.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0, -0.9, -3.0);
Init_Particles();
glutDisplayFunc(DrawGLscene);
glutTimerFunc(0, timer, 0);
glutMainLoop();
}
void timer(int extra)
{
glutPostRedisplay();
glutTimerFunc(20, timer, 0);
}
void Load_Plane(){
glEnable(GL_BLEND);
glBlendFunc(GL_ONE_MINUS_SRC_ALPHA, GL_SRC_ALPHA);
glColor4f(0.0f, 0.2f, 0.2f, 0.5f);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, txPlane);
glBegin(GL_QUADS);
glNormal3f(-10.0f, 0.0f, -10.0f);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-10.0f, 0.0f, 10.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex3f( 10.0f, 0.0f, 10.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex3f( 10.0f, 0.0f, -10.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-10.0f, 0.0f, -10.0f);
glEnd();
}
void DrawGLscene(){
Load_Plane();
glPushMatrix();
glScalef(1.0f, -1.0f, 1.0f);
Render_Particles();
glPopMatrix();
Render_Particles();
}
void Init_Particles(){
LoadBitmapTexture("./Particle.bmp", txParticle); //load the particle texture
LoadBitmapTexture("./Plain.bmp",txPlane); //load the plain texture
int p;
srand((int)time(NULL));
for(p=0; p<MAX_PARTICLES; p++){
Particles[p].Active = FALSE;
Particles[p].tX = 0.0f;
Particles[p].tY = -0.1f;
Particles[p].tZ = 0.0f;
}
}
void Activate_Particles(){
int p;
for(p=0; p<MAX_PARTICLES; p++){
if(!Particles[p].Active){
// Start the particle at 0,0,0 origin
Particles[p].X = 0.0f;
Particles[p].Y = 0.0f;
Particles[p].Z = 0.0f;
// The following lines set a random speed value
Particles[p].sX = (((float)((rand() % 100) + 1)) /
1000.0f) - 0.05f;
Particles[p].sY = (((float)((rand() % 100) + 50)) /
500.0f);
Particles[p].sZ = (((float)((rand() % 100) + 1)) /
1000.0f) - 0.05f;
// We also activate the particle
Particles[p].Active = true;
// Set it's Age to zero
Particles[p].Age = 0;
// We also assign a max age to the particles
Particles[p].MaxAge = MAX_PARTICLE_AGE;
// We Also reset the bouncecount to zero
Particles[p].BounceCount = 0;
//Adding the colours
Particles[p].R = R;
Particles[p].G = G;
Particles[p].B = B;
R+=cR;
G+=cG;
B+=cB;
if(R>1.0f){R=1.0f; cR=-cR;}
if(R<0.0f){R=0.0f; cR=-cR;}
if(G>1.0f){G=1.0f; cG=-cG;}
if(G<0.0f){G=0.0f; cG=-cG;}
if(B>1.0f){B=1.0f; cB=-cB;}
if(B<0.0f){B=0.0f; cB=-cB;}
return;
}
}
}
void Adjust_Particles(){
int p;
for(p=0; p<MAX_PARTICLES; p++){
// We move the speed towards the target speed by 1/20 (5%)
Particles[p].sX+= (Particles[p].tX - Particles[p].sX) / 20.0f;
Particles[p].sY+= (Particles[p].tY - Particles[p].sY) / 20.0f;
Particles[p].sZ+= (Particles[p].tZ - Particles[p].sZ) / 20.0f;
// Then we adjust the position of
// the particle by the new speed
Particles[p].X+= Particles[p].sX;
Particles[p].Y+= Particles[p].sY;
Particles[p].Z+= Particles[p].sZ;
// Now for the bounce code.
if(Particles[p].Y < 0.0f){
Particles[p].Y = 0.0f;
Particles[p].sY = -Particles[p].sY;
Particles[p].BounceCount++;
if(Particles[p].BounceCount > MAX_BOUNCE_COUNT){
Particles[p].Active = FALSE;
}
}
// And finally the age check
Particles[p].Age++;
if(Particles[p].Age > Particles[p].MaxAge){
Particles[p].Active = FALSE;
}
}
}
void Render_Particles(){
Activate_Particles();
Adjust_Particles();
glClear( GL_COLOR_BUFFER_BIT );
int p;
// Enable textures and bind our particle texture
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, txParticle);
// Disable Depth testing.
glDisable(GL_DEPTH_TEST);
// Enable blending
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_COLOR,GL_ONE);
for(p=0; p<MAX_PARTICLES; p++){
if(Particles[p].Active){
glColor4f(Particles[p].R,
Particles[p].G,
Particles[p].B, 1.0f);
glPushMatrix();
glTranslatef(Particles[p].X,
Particles[p].Y,
Particles[p].Z);
glBegin(GL_QUADS);
glNormal3f(0.0f, 0.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-Size, -Size, 0.0f);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(Size, -Size, 0.0f);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(Size, Size, 0.0f);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-Size, Size, 0.0f);
glEnd();
glPopMatrix();
}
}
glEnable(GL_DEPTH_TEST);
glutSwapBuffers();
}
bool LoadBitmapTexture(char * FileName, GLuint &texid){
HBITMAP hBMP; // Handle Of The Bitmap
BITMAP BMP; // Bitmap Structure
glGenTextures(1, &texid); // Create The Texture
hBMP=(HBITMAP)LoadImage(GetModuleHandle(NULL),
FileName,
IMAGE_BITMAP, 0, 0,
LR_CREATEDIBSECTION | LR_LOADFROMFILE
);
if (!hBMP) // Does The Bitmap Exist?
return FALSE; // If Not Return False
GetObject(hBMP, sizeof(BMP), &BMP); // Get The Object
// hBMP: Handle To Graphics Object
// sizeof(BMP): Size Of Buffer For Object Information
// &BMP: Buffer For Object Information
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
// Pixel Storage Mode (Word Alignment / 4 Bytes)
// Typical Texture Generation Using Data From The Bitmap
glBindTexture(GL_TEXTURE_2D, texid);// Bind To The Texture ID
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_LINEAR); // Linear Min Filter
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
GL_LINEAR); // Linear Mag Filter
glTexImage2D(GL_TEXTURE_2D, 0, 3, BMP.bmWidth, BMP.bmHeight,
0, GL_BGR_EXT, GL_UNSIGNED_BYTE, BMP.bmBits);
DeleteObject(hBMP); // Delete The Object
return TRUE; // Loading Was Successful
}
It could be that you're not clearing the depth buffer.
It doesn't affect any of the particles because you are disabling depth test when you render them, but when you render the plane, depth test is enabled, and since the depth buffer has not been cleared it has a spaz and doesn't render the plane.
Do
glClear(GL_DEPTH_BUFFER_BIT);
before you render the plane to clear the depth buffer.
EDIT:
This must be it-
You are calling
glClear(GL_COLOR_BUFFER_BIT);
after you render the plane. Look at your DrawGLScene function:
Load_Plane(); // you are drawing the plane here
glPushMatrix();
glScalef(1.0f, -1.0f, 1.0f);
Render_Particles(); // this function calls "glClear( GL_COLOR_BUFFER_BIT );"
// so anything that you rendered before is now removed.
glPopMatrix();
Render_Particles(); // same goes for here.
The solution would be to remove the call to glClear from your Render_Particles function,
and add it to the top of DrawGLScene:
(New DrawGLScene Code)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
Load_Plane();
glPushMatrix();
glScalef(1.0f, -1.0f, 1.0f);
Render_Particles();
glPopMatrix();
Render_Particles();
EDIT #2:
You're calling glutSwapBuffers in the Render_Particles function.
Don't call it there. Call it at the end of DrawGLScene:

Orbiting sphere should cast spot light on central cube

I'm writing a program that draws a rotating cube (with texture) in the middle of the screen followed by a small yellow sphere that orbits around the cube. The idea is to make the sphere as a spot light source that illuminates the cube.
Here is the problem: as you can see in the images below, I'm failing to achieve the spot light effect. It seems that the entire cube gets lighted:
I'm setting GL_SPOT_DIRECTION to be the cube position. I didn't set surface normals because I'm struggling to understand how to compute them for the cube, and I'm not sure a simple graphic application like this really requires it.
I'm sharing the code below:
main.cpp:
#include <QApplication>
#include "glwidget.h"
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
GLWidget gl_widget;
gl_widget.show();
return app.exec();
}
GLWidget.h:
#pragma once
#include <QGLWidget>
#include <QImage>
class GLWidget : public QGLWidget
{
Q_OBJECT
public:
explicit GLWidget(QWidget* parent = 0);
virtual ~GLWidget();
void _draw_texture_cube(int w, int h);
void _draw_light();
/* OpenGL initialization, viewport resizing, and painting */
void initializeGL();
void paintGL();
void resizeGL( int width, int height);
/* enable the user to interact directly with the scene using the keyboard */
void keyPressEvent(QKeyEvent *e);
private:
int _width;
int _height;
QImage* _img;
GLuint _texture;
float xrot;
float yrot;
float zrot;
bool _light_on;
bool _must_rotate;
bool _pause_light;
GLfloat _light_pos[3];
GLfloat _cube_pos[3];
GLUquadricObj* _quadratic;
protected slots:
void _tick();
};
GLWidget.cpp:
#include "GLWidget.h"
#include <iostream>
#include <QKeyEvent>
#include <QTimer>
#include <cmath>
#define LIGHT_MOVEMENT_SPEED 20.0f // Degrees per second
#define pi 3.141592654f
GLWidget::GLWidget(QWidget *parent)
: QGLWidget(parent), _img(NULL), _light_on(true), _must_rotate(true),
_pause_light(false), _quadratic(NULL)
{
_width = 0;
_height = 0;
_texture = 0;
xrot = 0.f;
yrot = 0.f;
zrot = 0.f;
// Set central cube position
_cube_pos[0] = 0.0f;
_cube_pos[1] = 0.0f;
_cube_pos[2] = -7.0f;
// Set light position
_light_pos[0] = 0.5f;
_light_pos[1] = 0.5f;
_light_pos[2] = -7.0f;
}
GLWidget::~GLWidget()
{
if (_img)
delete _img;
glDeleteTextures(1, &_texture);
}
void GLWidget::_tick()
{
update(); // triggers paintGL()
QTimer::singleShot(33, this, SLOT(_tick()));
}
void GLWidget::initializeGL()
{
std::cout << "GLWidget::initializeGL" << std::endl;
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Black Background
glEnable(GL_CULL_FACE);
/* Load bitmap */
glEnable(GL_TEXTURE_RECTANGLE_ARB);
glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
if (!_img)
{
std::cout << "GLWidget::paintGL: loading image" << std::endl;
QImage tmp(":/crate.jpg");
if (tmp.isNull())
{
std::cout << "GLWidget::paintGL: !!! Failed QImage #1" << std::endl;
return;
}
_img = new QImage(QGLWidget::convertToGLFormat(tmp));
}
/* Convert bitmap into texture */
// Create The Texture
glGenTextures(1, &_texture);
// Typical Texture Generation Using Data From The Bitmap
glBindTexture(GL_TEXTURE_RECTANGLE_ARB, _texture);
// Generate The Texture
glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0,
GL_RGBA, _img->width(), _img->height(), 0,
GL_RGBA, GL_UNSIGNED_BYTE, _img->bits());
if (glGetError() != GL_NO_ERROR)
{
std::cout << "GLWidget::paintGL: !!! Failed glTexImage2D" << std::endl;
return;
}
/* Setup lighting */
glShadeModel(GL_SMOOTH); //Smooth color shading
// Light properties
GLfloat AmbientLight[4] = {0.2, 0.2, 0.2, 1.0};
GLfloat DiffuseLight[4] = {0.8, 0.8, 0.8, 1.0}; // color
GLfloat SpecularLight[4] = {1.0, 1.0, 1.0, 1.0}; // bright
GLfloat SpecRef[] = {0.7f, 0.7f, 0.7f, 1.0f};
GLubyte Shine = 60.0;
//glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, AmbientLight);
glLightfv(GL_LIGHT0, GL_AMBIENT, AmbientLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, DiffuseLight);
glLightfv(GL_LIGHT0, GL_SPECULAR, SpecularLight);
glLightfv(GL_LIGHT0, GL_POSITION, _light_pos);
glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
glMaterialfv(GL_FRONT, GL_SPECULAR, SpecRef); // refletância do material
glMaterialf(GL_FRONT, GL_SHININESS, Shine); // concentração do brilho
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 0);
//glColorMaterial(GL_FRONT,GL_DIFFUSE);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
// Sphere
_quadratic = gluNewQuadric(); // Create A Pointer To The Quadric Object
gluQuadricNormals(_quadratic, GLU_SMOOTH); // Create Smooth Normals
gluQuadricTexture(_quadratic, GL_TRUE); // Create Texture Coords
/* Start the timer */
_tick();
}
/* Draw the central cube with texture
*/
void GLWidget::_draw_texture_cube(int w, int h)
{
glPushMatrix();
glTranslatef(_cube_pos[0], _cube_pos[1], _cube_pos[2]);
glRotatef ( xrot, 1.0, 0.0, 0.0 );
glRotatef ( yrot, 0.0, 1.0, 0.0 );
glRotatef ( zrot, 0.0, 0.0, 1.0 );
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_QUADS); // Draw A Cube
// Front Face
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(w, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);
glTexCoord2f(w, h); glVertex3f( 1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, h); glVertex3f(-1.0f, 1.0f, 1.0f);
// Back Face
glTexCoord2f(w, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(w, h); glVertex3f(-1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, h); glVertex3f( 1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
// Top Face
glTexCoord2f(0.0f, h); glVertex3f(-1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(w, 0.0f); glVertex3f( 1.0f, 1.0f, 1.0f);
glTexCoord2f(w, h); glVertex3f( 1.0f, 1.0f, -1.0f);
// Bottom Face
glTexCoord2f(w, h); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, h); glVertex3f( 1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);
glTexCoord2f(w, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
// Right face
glTexCoord2f(w, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
glTexCoord2f(w, h); glVertex3f( 1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, _img->height()); glVertex3f( 1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);
// Left Face
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(w, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(w, h); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, h); glVertex3f(-1.0f, 1.0f, -1.0f);
glEnd();
glPopMatrix();
if (_must_rotate)
{
xrot += 0.6f;
yrot += 0.4f;
zrot += 0.8f;
}
}
/* Draw light source and light model (sphere)
*/
void GLWidget::_draw_light()
{
if (_light_on)
{
glEnable(GL_LIGHT0); // enable lights that we use
}
else
{
glDisable(GL_LIGHT0);
}
static float light_angle = 25.0f;
if (!_pause_light) // stop moving the light source
{
light_angle += LIGHT_MOVEMENT_SPEED * 0.1;
if (light_angle > 360.0f)
light_angle -= 360.0f;
}
/* Set light source position */
_light_pos[0] = 4.0f * (float) cos(light_angle * pi / 180.0f);
_light_pos[1] = 4.0f * (float) sin(light_angle * pi / 180.0f);
_light_pos[2] = -7;
glLightfv(GL_LIGHT0, GL_POSITION, _light_pos);
GLfloat SpotDir[] = {_cube_pos[0], _cube_pos[1], _cube_pos[2], 0.0 };
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, SpotDir);
glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 150.0);
glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 15.0);
/* Set the light model position to be the same as the light source */
glPushMatrix();
glTranslatef(_light_pos[0], _light_pos[1], _light_pos[2]);
glColor3ub(255, 255, 0); // yellow
gluSphere(_quadratic, 0.2f, 32, 32); // draw sphere
glPopMatrix();
}
void GLWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
glMatrixMode ( GL_MODELVIEW ); // Select The Model View Matrix
glLoadIdentity(); // Reset The Current Modelview Matrix
/* Draw central cube */
glEnable(GL_TEXTURE_RECTANGLE_ARB);
glBindTexture(GL_TEXTURE_RECTANGLE_ARB, _texture); // Select Our Texture
_draw_texture_cube(_img->width(), _img->height());
glDisable(GL_TEXTURE_RECTANGLE_ARB);
/* Draw light source and light model*/
_draw_light();
}
void GLWidget::resizeGL( int w, int h)
{
_width = w;
_height = h;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity(); // Reset The Projection Matrix
if (h == 0) // Calculate The Aspect Ratio Of The Window
gluPerspective ( 60, ( float ) w, 0.4, 500.0 );
else
gluPerspective ( 60, ( float ) w / ( float ) h, 0.4, 500.0 );
glMatrixMode ( GL_MODELVIEW ); // Select The Model View Matrix
glLoadIdentity ( ); // Reset The Model View Matrix
gluLookAt(0.0, 0.0, 2.0, // eye
0.0, 0.0, 0.0, // center
0.0, 1.0, 0.0); // up
}
void GLWidget::keyPressEvent(QKeyEvent *e)
{
switch (e->key())
{
case Qt::Key_L:
if (_light_on)
_light_on = false;
else
_light_on = true;
break;
case Qt::Key_P:
if (_pause_light)
_pause_light = false;
else
_pause_light = true;
break;
case Qt::Key_R:
if (_must_rotate)
_must_rotate = false;
else
_must_rotate = true;
break;
default:
break;
}
}
Lighting.pro:
QT += core gui opengl
SOURCES += \
GLWidget.cpp \
main.cpp
HEADERS += \
GLWidget.h
RESOURCES += \
resource.qrc
What needs to be changed in this application in order to achieve the desired effect?
You do not specify any normals for your cube faces. As OpenGL is a state machine, it will use the default surface normal for all vertices, hence all of your faces. As the normal vector is crucial for the lighting, all of your faces will be lit almost identical (vertex postions still are different, but the effect is weak).
You should also be aware that the fixed function lighting of OpenGL is done per vertex. If you really want to see a good spotlight on the cuve, you would either need to tessalate it so more vertices are used where the lighting equation is actually evaluated, or use shaders for per-fragment lighting.