Related
My program refuses to do depth testing. The two sphere objects are always drawn in the order they are created, not according to their position. Sphere alpha is positioned at (0, 0, 1) and Sphere beta is positioned (0, 0, -10), yet OpenGL still draws beta on top of alpha. I set depth test to enabled in my program.
Nothing appears to work. I want OpenGL to do depth test automatically on any objects drawn in the window. Any help or advise would be greatly appreciated. Here is the full code.
#include "GL/freeglut.h"
#include "GL/gl.h"
#include "GL/glu.h"
const int SPHERE_RES = 200;
double Z_INIT = -28.0;
double RADIUS = 2;
double Red[3] = {1, 0, 0};
double Blue[3] = {0, 0, 1};
using namespace std;
/*
* Method handles resize of the window
*/
void handleResize (int w, int h) {
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
double ratio = (float)w/ (float)h;
gluPerspective(45.0, ratio, 1.0, 100.0);
}
/*
* Color and depth is enabled and in this method
*/
void configureColor(void)
{
glClearColor(1.0f, 1.0f, 1.0f, 0.0f); //Set background to white
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);// Clear window.
glDepthFunc(GL_ALWAYS);
glEnable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
}
void display (void) {
configureColor();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
GLfloat sun_direction[] = { 0.0, 0.0, -1.0, 0.0};
glLightfv(GL_LIGHT0, GL_POSITION, sun_direction);
GLUquadric* quad = gluNewQuadric();
//first sphere is drawn
glColor3f(Red[0], Red[1], Red[2]);
glPushMatrix();
glLoadIdentity();
glTranslatef(0, 0, Z_INIT);
glTranslatef(0, 0, 1.0);
gluSphere(quad, RADIUS, SPHERE_RES, SPHERE_RES);
glPopMatrix();
//second sphere is supposed to be drawn behind it,
//but it is drawn on top.
glColor3f(Blue[0], Blue[1], Blue[2]);
glPushMatrix();
glLoadIdentity();
glTranslatef(0, 0, Z_INIT);
glTranslatef(0, 0, -10.0);
gluSphere(quad, RADIUS, SPHERE_RES, SPHERE_RES);
glPopMatrix();
free(quad);
glFlush();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv); //initializes the GLUT
glutInitDisplayMode(GLUT_SINGLE);
glutInitWindowSize(600,600);
glutInitWindowPosition(100,100);
glutCreateWindow("OpenGL - First window demo");
glutReshapeFunc(handleResize);
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
I am using Ubuntu 14.04 operating system.
glDepthFunc(GL_ALWAYS);
This is the reason you see the spheres in the order they are drawn. Setting the depth function to GL_ALWAYS simply means all depth tests always pass, for any fragment, be it closer or farther.
You need GL_LESS for the result you want. A fragment having depth lesser than the one in the frame buffer wins; the closer (lesser z) one wins over the farther (greater z) one.
You can either call glDepthFunc(GL_LESS) or comment out glDepthFunc(GL_ALWAYS) since GL_LESS is the default.
I am currently trying to position a light starting from the bottom left of my screen and illuminating towards the center of my screen but my light source does not appear circular (light does not seem to be coming from a single point).
After moving the light source it shines on the entire object but the desired effect is for the lightsource to only shine (based on a point) towards the right.
void init()
{
camPos[0]= -(size/2)*.1;
camPos[1]= size*.1;
camPos[2]= -(size/2)*.1;
zoom = size/10;
glClearColor(0,0,0,0);
glColor3f(1, 1, 1);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//Enable backface culling
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CW);
//Enable Lighting
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
light_pos[0] = 1;
light_pos[1] = 10;
light_pos[2] = 1;
light_pos[3] = 1;
gluPerspective(45, 1, 1, 100);
};
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//Camera
radians = float(pi*(angle-90.0f)/180.0f);
//initialize look
look[0] = (size/2)*.1;
look[1] = 1;
look[2] = (size/2)*.1;
camPos[0] = look[0] + sin(radians)*zoom;
camPos[1] = size/10;
camPos[2] = look[2] + cos(radians)*zoom;
gluLookAt(camPos[0], camPos[1], camPos[2], look[0],look[1],look[2], 0,1,0);
//lighting
//glColor3f(1,1,1);
float m_amb[] = {0.2, 0.2, 0.2, 1.0};
float m_dif[] = {1, 1, 1, 1.0};
float m_spec[] = {1, 1, 1, 1.0};
float shiny = 27;
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, m_amb);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, m_dif);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, m_spec);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shiny);
glLightfv(GL_LIGHT0, GL_POSITION, light_pos);
glShadeModel(GL_SMOOTH);
drawTerrain(terrainA, size);
glutSwapBuffers();
};
int main (int argc, char** argv)
{
srand(time(NULL));
//When program starts enter value
printf("Enter an int between 50 and 300: ");
scanf("%i",&size);
if ( size < 50 || size > 300){
printf("Invalid size! Please re-run \n");
return 0;
}
populateArray();
//Starts glut
glutInit(&argc, argv);
//Init display
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 800);
glutInitWindowPosition(600, 100);
glutCreateWindow("Terrain");glEnable(GL_DEPTH_TEST);
//Registering Callbacks
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
glutSpecialFunc(special);
glEnable(GL_DEPTH_TEST);
init();
glutMainLoop();
return 0;
};
The general practic is to define light attenuation factors as a coeficients of light equation.
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 1.5);
glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.5);
glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 0.2);
where kc is constant attenuation factor, kl - linear attenuation factor, kq - quadratic attenuation factor, d - distance to light source. You can modify this coeficients to achive the effect you want.
This example could not works correctly so I suggest to build your own light destribution function using shaders, it will be simple to achive desired effect and more effective (and will always work).
I have trouble displaying a texture using OpenGL and C++. I am loading the texture from a RGB Raw file, binding it to a texture, but when I am trying to display the texture on a quad, the texture is white. I am using glGetError and it catches no errors. Here is my code:
#include <iostream>
#include <windows.h> // Standard header for MS Windows applications
#include <GL/gl.h> // Open Graphics Library (OpenGL) header
#include <GL/glut.h> // The GL Utility Toolkit (GLUT) Header
using namespace std;
typedef struct {
int width;
int height;
char* title;
float field_of_view_angle;
float z_near;
float z_far;
} glutWindow;
glutWindow win;
float rotation, distance1;
bool light=TRUE;
bool trans=FALSE;
GLuint tex;
void drawFlatFace(float size)
{
glBegin(GL_QUADS);
glTexCoord2f (0, 0);
glVertex3f(-size, -2*size, size);
glTexCoord2f (1.0, 0);
glVertex3f(size, -2*size, size);
glTexCoord2f (1.0, 1.0);
glVertex3f(size, 2*size, size);
glTexCoord2f (0, 1.0);
glVertex3f(-size, 2*size, size);
glEnd();
}
void drawBlock(float size){
glColor3f(1.0f,1.0f,1.0f);
glPushMatrix();
drawFlatFace (size);
glRotatef (90, 0, 1, 0);
drawFlatFace (size);
glRotatef (90, 0, 1, 0);
drawFlatFace (size);
glRotatef (90, 0, 1, 0);
drawFlatFace (size);
glPopMatrix();
}
GLuint loadTexture(const char * filename) {
GLuint text[1];
GLubyte* bits = new GLubyte[512*256*3];
FILE *file;
fopen_s(&file,filename,"rb");
fread(&bits,(512*256*3),1,file);
fclose(file);
glGenTextures(1,&text[0]);
glBindTexture(GL_TEXTURE_2D,text[0]);
glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
glTexImage2D(GL_TEXTURE_2D, 0, 3,256,512,0,GL_RGB,GL_UNSIGNED_BYTE,bits);
free(bits);
return text[0];
}
void display()
{
GLenum err;
err = glGetError();
if (err != GL_NO_ERROR)
{
cerr << "OpenGL error: " << gluErrorString(err) << endl;
}
tex=loadTexture("tex.raw");
glBindTexture(GL_TEXTURE_2D,tex);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen and Depth Buffer
glLoadIdentity();
gluLookAt( 10+distance1 ,1.4,0, 0,0,0, 0,1,0); // Define a viewing transformation
glRotatef(rotation, 0.f, 1.f, 0.f);
drawBlock(3);
if (light) glEnable(GL_LIGHTING); // Enable Lighting
else glDisable(GL_LIGHTING); // Disable Lighting
if (trans) glEnable (GL_BLEND); // Enable Transparency
else glDisable(GL_BLEND); // Disable Transparency
glutSwapBuffers();
}
void initialize ()
{
glMatrixMode(GL_PROJECTION); // select projection matrix
glViewport(0, 0, win.width, win.height); // set the viewport
glLoadIdentity(); // reset projection matrix
GLfloat aspect = (GLfloat) win.width / win.height;
gluPerspective(win.field_of_view_angle, aspect, win.z_near, win.z_far); // set up a perspective projection matrix
glMatrixMode(GL_MODELVIEW); // specify which matrix is the current matrix
glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ); // specify implementation-specific hints
GLfloat amb_light[] = { 0.3, 0.3, 0.3, 1.0 };
GLfloat diffuse[] = { 0.4, 0.4, 0.4, 1.0 };
GLfloat specular[] = { 0.5, 0.5, 0.5, 1.0 };
glLightModelfv( GL_LIGHT_MODEL_AMBIENT, amb_light );
glLightfv( GL_LIGHT0, GL_SPECULAR, specular );
glLightfv( GL_LIGHT0, GL_DIFFUSE, diffuse );
GLfloat light_position[] = { 1.0, 1.0, 0, 0.0 };
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glEnable( GL_LIGHT0 );
glEnable( GL_COLOR_MATERIAL );
glEnable( GL_LIGHTING );
//glLightModeli( GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE );
glEnable(GL_TEXTURE_2D); // Enable Texture Mapping
glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
glClearDepth(1.0f); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
glTexParameteri( GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
void keyboard ( int key, int mousePositionX, int mousePositionY )
{
switch ( key )
{
case GLUT_KEY_DOWN:
if (distance1<9){
distance1=distance1+.3;
}
break;
case GLUT_KEY_UP:
if (distance1>-9){
distance1=distance1-.3;
}
break;
case GLUT_KEY_LEFT:
rotation=rotation-2;
break;
case GLUT_KEY_RIGHT:
rotation=rotation+2;
break;
case GLUT_KEY_PAGE_UP:
light=TRUE;
break;
case GLUT_KEY_PAGE_DOWN:
light=FALSE;
break;
case GLUT_KEY_HOME:
trans=TRUE;
break;
case GLUT_KEY_END:
trans=FALSE;
break;
default:
break;
}
}
int main(int argc, char **argv)
{
// set window values
win.width = 800;
win.height = 600;
win.title = "Test Texture";
win.field_of_view_angle = 45;
win.z_near = 1.0f;
win.z_far = 500.0f;
// initialize and run program
glutInit(&argc, argv); // GLUT initialization
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH ); // Display Mode
glutInitWindowSize(win.width,win.height); // set window size
glutCreateWindow(win.title); // create Window
// Callback functions
glutDisplayFunc(display); // register Display Function
glutIdleFunc( display ); // register Idle Function
glutSpecialFunc( keyboard ); // register Keyboard Handler
initialize();
glutMainLoop(); // run GLUT mainloop
return 0;
}
I want to add that the Raw file is displayed correctly when loaded in IrfanView as 256x512, 24BPP, RGB (the size is 393,216 bytes or 3*512*256)
This line:
glTexParameteri( GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER, GL_LINEAR);
Shouldn't be in your main intialisation, but instead needs to be done when setting up the texture itself (i.e. after binding).
You may also want to set the MAG_FILTER, and the texture coordinate wrapping modes, as a general rule.
Also, you appear to be loading the texture every time you render. Don't do that, performance will be terrible and you'll run out of memory as GL will keep allocating new textures.
i want to draw a rotating cube in the middle of the screen, and i want it to be lit by a light above it (i want it to look as if the cube was being lit from a fixed screen position). my problem is that i don't know how to prevent the light from rotating with the cube.
here's the code:
(SUMMARY: initGL, paintGL, and resizeGl are the functions that you always have to implement. in paintGL i use makeCube(). in makeCube() i use glBegin(GL_QUADS) to make a cube,and i use calcNormals() to calculate the normals of the cube )
-------------initGL--------------------------
angle=0.0;
glEnable (GL_DEPTH_TEST);
glEnable (GL_LIGHTING);
GLfloat LightDiffuse[]= { 1.0f, 1.0f, 1.0f, 1.0f };
GLfloat LightPosition[]= { 0.0f, 1.5f,1.5f, 1.0f };
glLightfv(GL_LIGHT0, GL_DIFFUSE, LightDiffuse);
glLightfv(GL_LIGHT0, GL_POSITION,LightPosition);
glEnable (GL_LIGHT0);
--------------paintGL------------------
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0, 0.0, -13.0);
glRotatef(angle,0.0f,1.0f,0.0f);
makeCube();
angle+=0.3;
--------------void makeCube()-------------------
float P[8][3]={ {-1,-1, 1},{1,-1, 1},{1,1, 1},{-1,1, 1},
{-1,-1,-1},{1,-1,-1},{1,1,-1},{-1,1,-1}};
float * planes[6][4] ={ {P[0],P[1],P[2],P[3]},
{P[1],P[5],P[6],P[2]},
{P[4],P[7],P[6],P[5]},
{P[0],P[3],P[7],P[4]},
{P[3],P[2],P[6],P[7]},
{P[0],P[4],P[5],P[1]}};
int i;
for(i=0;i<6;i++){
float *normal;
normal = calcNormal(planes[i][0],planes[i][1],planes[i][2]);
glBegin(GL_QUADS);
glNormal3f(normal[0], normal[1], normal[2]);
glVertex3f(planes[i][0][0],planes[i][0][1],planes[i][0][2]);
glVertex3f(planes[i][1][0],planes[i][1][1],planes[i][1][2]);
glVertex3f(planes[i][2][0],planes[i][2][1],planes[i][2][2]);
glVertex3f(planes[i][3][0],planes[i][3][1],planes[i][3][2]);
glEnd();
}
----------------float* calcNormal()----------------------
float vec1[3] = {P2[0]-P1[0],P2[1]-P1[1],P2[2]-P1[2]};
float vec2[3] = {P3[0]-P2[0],P3[1]-P2[1],P3[2]-P2[2]};
float cross[3] = {vec1[1]*vec2[2]-vec2[1]*vec1[2],
vec1[2]*vec2[0]-vec2[2]*vec1[0],
vec1[0]*vec2[1]-vec2[0]*vec1[1]};
float modCross = sqrt(cross[0]*cross[0]+cross[1]*cross[1]+cross[2]*cross[2]);
cross[0]/=modCross;
cross[1]/=modCross;
cross[2]/=modCross;
return cross;
-------------resizeGL--------------------------
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
GLfloat x = GLfloat(width) / height;
glFrustum(-x, +x, -1.0, +1.0, 4.0, 15.0);
glMatrixMode(GL_MODELVIEW);
It seems that you're transforming the position of the light in your paintGL section.
Looking over old code, I found an app in my code directory that loads and rotates .OBJ meshes, while allowing the light to be moved.
I think that the solution is to set the position of the light each frame. (Can't remember it's been over 18 months since I touched the project)
void idleFunc()
{
light(); /// *** I think you need to replicate this functionality ****
glPushMatrix();
myGluLookAt(0.0, -.50, -6.0, /* eye is at (0,0,5) */
0.0, 0.0, 0.0, /* center is at (0,0,0) */
0.0, 1.0, 0.); /* up is in positive Y direction */
transformFunc();
displayFunc();
glPopMatrix();
}
void displayFunc()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (useDrawList)
glCallList(DLid);
else
drawObj(loadedObj);
drawLight0(); // *** just displays an unlit sphere at the position of the light **
glutSwapBuffers();
frameCount++;
}
/* set the poition of each of the lights */
void light()
{
glLightfv(GL_LIGHT0, GL_POSITION, lightPos1);
glLightfv(GL_LIGHT1, GL_POSITION, lightPos2);
}
i solved this problem drawing the cube with VERTEX ARRAYS rather than DIRECT MODE, it seems that rotations or lights affect the object in a different way with each method, which is quite weird
I am currently using the Code::Blocks IDE, c++, opengl and SDL to make a game- and I have hit a severe block in road, if you will. I am using SDL_image to load these jpg images for the textures, but they just will not load. Currently, I have tried placing them in every folder in the project, even places where it would supposedly make no difference. I have tried running both the debug and release versions from the IDE, by double-clicking the executable, and by running the executable from the command line. They all produce the same error: Could not load image: "the path to my image". I have tried using full paths, I have tried using relative paths, I have tried just about everything. I have tried various image formats, to no success. Other useful information may be: I am using ubuntu 11.04, I am using GIMP to create the images, and this is my code in complete (I'm sure most of it is irrelevant, but I am just putting it all down just-in-case):
#include <GL/gl.h>
#include <GL/glu.h>
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include <Cg/cg.h>// NEW: Cg Header
#include <Cg/cgGL.h>// NEW: Cg OpenGL Specific Header
#include <iostream>
#include <math.h>
#include <string>
#include "../include/Camera.h"
#define WINDOW_WIDTH 640
#define WINDOW_HEIGHT 480
// Keydown booleans
bool key[321];
Uint8 *keystate;
float fogDensity = 0.02f;
static float fog_color[] = { 0.8f, 0.8f, 0.8f, 1.0f };
// Process pending events
bool events()
{
SDL_Event event;
if( !SDL_PollEvent(&event) ){
return true;
}
switch( event.type )
{
case SDL_KEYDOWN : key[ event.key.keysym.sym ]=true; break;
case SDL_KEYUP : key[ event.key.keysym.sym ]=false; break;
case SDL_QUIT : return false; break; //one-per-keypress
}
keystate = SDL_GetKeyState(NULL); //continuous
return true;
}
// Initialze OpenGL perspective matrix
void setup(int width, int height)
{
glViewport( 0, 0, width, height );
glMatrixMode( GL_PROJECTION );
glEnable( GL_DEPTH_TEST );
gluPerspective( 45, (float)width/height, 0.1, 100 );
glMatrixMode( GL_MODELVIEW );
}
Camera* cam = new Camera();
GLuint rocktexture; // This is a handle to our texture object
GLuint earthtexture;
//add some default materials here
const GLfloat light_ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f };
const GLfloat light_diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_position[] = { 0.0f, 1.0f, 0.0f, 0.0f };
const GLfloat mat_ambient[] = { 0.7f, 0.7f, 0.7f, 1.0f };
const GLfloat mat_diffuse[] = { 0.8f, 0.8f, 0.8f, 1.0f };
const GLfloat mat_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat high_shininess[] = { 100.0f };
void MouseUpdate() {
int x, y;
SDL_GetMouseState(&x,&y);
SDL_WarpMouse(WINDOW_WIDTH/2,WINDOW_HEIGHT/2);
cam->yaw+=(x-WINDOW_WIDTH/2)*0.2;
cam->pitch+=(y-WINDOW_HEIGHT/2)*0.2;
if(cam->pitch<-90) {
cam->pitch=-90;
}
if(cam->pitch>90) {
cam->pitch=90;
}
}
static void display(void)
{
while(events())
{
MouseUpdate();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glRotatef(cam->pitch,1.0,0.0,0.0); //rotate our camera on the x-axis (left and right)
glRotatef(cam->yaw,0.0,1.0,0.0); //rotate our camera on the y-axis (up and down)
glTranslated(cam->camx,cam->camy,cam->camz); //translate the screen to the position of our camera
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 0);
//glColor4f(1,1,1,0.5);
glPushMatrix();
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess);
//glDisable(GL_CULL_FACE);
glBindTexture(GL_TEXTURE_2D, rocktexture);
glBegin(GL_TRIANGLE_FAN);
glTexCoord2i(0,0);glVertex3f(-32,0,32);
glTexCoord2i(1,0);glVertex3f(32,0,32);
glTexCoord2i(1,1);glVertex3f(32,0,-32);
glTexCoord2i(0,1);glVertex3f(-32,0,-32);
glEnd();
//glEnable(GL_CULL_FACE);
glPopMatrix();
/*glPushMatrix();
GLUquadric* earth = gluNewQuadric();
gluQuadricTexture(earth, true);
gluQuadricDrawStyle(earth, GLU_FILL);
gluQuadricNormals(earth, GLU_SMOOTH);
gluQuadricOrientation(earth, GLU_OUTSIDE);
gluSphere(earth, 1, 16, 16);
gluDeleteQuadric(earth);
glPopMatrix();*/
glFlush();
SDL_GL_SwapBuffers();
if (key[SDLK_ESCAPE] || key[SDLK_q])
{
std::cout<<"Game Ended."<<std::endl;
exit(0);
}
if (keystate[SDLK_w])
{
cam->camx-=sin(cam->yaw*M_PI/180)/4;
cam->camz+=cos(cam->yaw*M_PI/180)/4;
}
if (keystate[SDLK_s])
{
cam->camx+=sin(cam->yaw*M_PI/180)/4;
cam->camz-=cos(cam->yaw*M_PI/180)/4;
}
if (keystate[SDLK_a])
{
cam->camx+=cos(cam->yaw*M_PI/180)/4;
cam->camz+=sin(cam->yaw*M_PI/180)/4;
}
if (keystate[SDLK_d])
{
cam->camx-=cos(cam->yaw*M_PI/180)/4;
cam->camz-=sin(cam->yaw*M_PI/180)/4;
}
}
}
// Load the OpenGL texture
GLuint loadImage(std::string path, GLuint tx,SDL_Surface* sur)
{
GLenum texture_format;
GLint nOfColors;
if ((sur = SDL_LoadBMP(path.c_str())))
{
// Check that the image's width is a power of 2
if ((sur->w & (sur->w - 1)) != 0)
{
printf("warning: image's width is not a power of 2\n");
}
// Also check if the height is a power of 2
if ((sur->h & (sur->h - 1)) != 0)
{
printf("warning: image's height is not a power of 2\n");
}
// get the number of channels in the SDL surface
nOfColors = sur->format->BytesPerPixel;
if (nOfColors == 4) // contains an alpha channel
{
if (sur->format->Rmask == 0x000000ff)
{
texture_format = GL_RGBA;
}
else
{
texture_format = GL_BGRA;
}
}
else if (nOfColors == 3) // no alpha channel
{
if (sur->format->Rmask == 0x000000ff)
{
texture_format = GL_RGB;
}
else
{
texture_format = GL_BGR;
}
}
else
{
printf("warning: the image is not truecolor.. this will probably break\n");
// this error should not go unhandled
}
// Have OpenGL generate a texture object handle for us
glGenTextures( 1, &tx );
// Bind the texture object
glBindTexture( GL_TEXTURE_2D, tx );
// Set the texture's stretching properties
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
// Edit the texture object's image data using the information SDL_Surface gives us
glTexImage2D( GL_TEXTURE_2D, 0, 3, sur->w, sur->h, 0, GL_BGR, GL_UNSIGNED_BYTE, sur->pixels);
//build mip-maps
gluBuild2DMipmaps(tx, 3, sur->w, sur->h, texture_format, GL_UNSIGNED_BYTE, sur->pixels);
}
else
{
printf("SDL could not load image: %s\n", SDL_GetError());
SDL_Quit();
return 1;
}
// Free the SDL_Surface only if it was successfully created
if (sur)
{
SDL_FreeSurface(sur);
}
delete &texture_format;
delete &nOfColors;
return tx;
}
/* Program entry point */
int main(int argc, char *argv[])
{
cam->camz=-5;
cam->camy=-1;
if ( SDL_Init(SDL_INIT_VIDEO) != 0 )
{
std::cout<<"Unable to initialize SDL: %s\n"<<SDL_GetError()<<std::endl;
return 1;
}
const SDL_VideoInfo* info = SDL_GetVideoInfo();
int vidFlags = SDL_OPENGL | SDL_GL_DOUBLEBUFFER;
if (info->hw_available) {vidFlags |= SDL_HWSURFACE;}
else {vidFlags |= SDL_SWSURFACE;}
//int bpp = info->vfmt->BitsPerPixel;
SDL_SetVideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, 32, vidFlags);
SDL_WM_SetCaption( "Treason", NULL);
SDL_WarpMouse(WINDOW_WIDTH/2, WINDOW_HEIGHT/2);
gluLookAt(cam->camx,cam->camy,cam->camz,0,0,0,0,1,0);
glClearColor(0, 0, 0, 0);//background color white
float lmodel_ambient[] = { 0.4f, 0.4f, 0.4f, 1.0f };
float local_view[] = { 0.0f };
glEnable(GL_TEXTURE_2D);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, local_view);
glLightModelf(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
//glEnable(GL_BLEND);
//glBlendFunc(GL_SRC_ALPHA, GL_ONE);
glEnable(GL_DITHER);
//glHint(GL_PHONG_HINT_WIN, GL_NICEST);
glShadeModel(GL_SMOOTH);//GL_PHONG_WIN
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
/* glEnable(GL_FOG);
glHint(GL_FOG_HINT, GL_NICEST);
glEnable(GL_FOG);
glFogi(GL_FOG_MODE, GL_EXP);
glFogf(GL_FOG_DENSITY, fogDensity);
glFogfv(GL_FOG_COLOR, fog_color);*/
// glEnable(GL_STENCIL_TEST);
//glStencilFunc(GL_KEEP, GL_KEEP, GL_INCR);
SDL_Surface *rocktexsur;
rocktexture = loadImage("rock.jpg", rocktexture, rocktexsur);
SDL_Surface *earthtexsur;
earthtexture = loadImage("earth.jpg", earthtexture, earthtexsur);
setup(WINDOW_WIDTH, WINDOW_HEIGHT);
display();
glDeleteTextures(1, &rocktexture);
glDeleteTextures(1, &earthtexture);
return 0;
}
So if you find anything or know any reason why it would return an "SDL could not load image" Error, please respond! I can't continue on my project until this is resolved because it produces a segfault.
SDL by itself can only load BMP images, and it will return an error if you load anything but a BMP in using the function SDL_LoadBMP(). In order to load JPEGs, you need to use the supplemental library SDL_image, which is available at http://www.libsdl.org/projects/SDL_image/ . As JJG answered, the prototype for the function you have to use is:
SDL_Surface *IMG_Load( const char* );
rather than SDL_LoadBMP().
Not an expert on SDL or C++. But I just spent a minute looking over my tiny program I made a while back. I used:
some_image = IMG_Load( "someimage.jpg" );