OpenGL flat shading - Strange lighting behaviour - c++

I have a slight issue with my OpenGL lighting.
It's rendering the model (Utah Teapot) just fine, but I have some weird lighting patterns. The model should be flat shaded with a single ambient light illuminating the scene, but I end up with splotchy light all over the teapot:
This is just a simple exercise to build a model loader in C++ with SFML.
Code is as follows:
bool modelLoader(string fileName, vector<GLfloat>& vertices, vector<GLushort>& indices, vector<GLfloat>& normals)
{
fstream object;
string face;
string dataLine;
string lineChar;
GLfloat point;
GLfloat uvs;
GLfloat storedNorm;
GLushort ind;
vector<GLfloat> storedNormals;
vector<GLfloat> storedUVs;
vector<GLfloat> localNormals , localVertices;
vertices.clear();
indices.clear();
object.open(fileName);
if(!object.is_open())
{
printf("Cannot open file: %f \n", fileName);
return false;
}
while(object>>lineChar)
{
if(lineChar == "v" /*|| dataLine.find("vt ") == 0*/ || lineChar == "f" || lineChar == "vn")
{
if(lineChar == "v")
{
//cout<<"v ";
for(int i=0;i<3;++i)
{
object >> point;
//cout << point << " ";
localVertices.push_back(point);
}
//cout<<endl;
}
else if(lineChar == "vn")
{
//cout<<"vn";
for(int j=0;j<3;++j)
{
object >> point;
//cout<<point<<" ";
localNormals.push_back(point);
}
//cout<<endl;
}
else if(lineChar == "f")
{
for(int k=0;k<3;++k)
{
getline(object, face, '/');
ind = atoi(face.c_str());
indices.push_back(ind-1);
object.ignore(2);
//getline(object, face, '/');
//uvs = atoi(face.c_str());
//storedUVs.push_back(uvs);
getline(object, face, ' ');
storedNorm = atoi(face.c_str());
storedNormals.push_back(storedNorm);
}
}
}
}
for (unsigned int i=0; i<indices.size(); ++i )
{
vertices.push_back(localVertices[indices[i]*3]);
vertices.push_back(localVertices[indices[i]*3 + 1]);
vertices.push_back(localVertices[indices[i]*3 + 2]);
normals.push_back(localNormals[(unsigned int) storedNormals[i]*3]);
normals.push_back(localNormals[(unsigned int) storedNormals[i]*3 + 1]);
normals.push_back(localNormals[(unsigned int) storedNormals[i]*3 + 2]);
}
return true;
}
Main loop:
int main()
{
// Create the main window
sf::Window App(sf::VideoMode(SC_WIDTH, SC_HEIGHT, 32), "SFML OpenGL");
// Create a clock for measuring time elapsed
sf::Clock Clock;
//output version of OpenGL to the console
cout<<"OpenGL version: "<<glGetString(GL_VERSION)<<endl;
// Create the vectors to hold the object data
vector<GLfloat> vertices;
vector<GLushort> indices;
vector<GLfloat> normals;
//Load model
if(!modelLoader("teapot2.obj", vertices, indices, normals))
{
printf("Failed to load model. Make sure the .obj file has no errors.");
system("pause");
return 0;
}
//enable the use of vertex arrays
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
// tell OpenGL where the vertices are with glVertexPointer()
glVertexPointer(3, GL_FLOAT, 0, &vertices[0]);
glNormalPointer(GL_FLOAT, 0, &normals[0]);
//*************************************************************
// Set color and depth clear value
glClearDepth(1.f);
glClearColor(0.f, 0.f, 0.f, 0.f);
// Enable Z-buffer read and write
glDepthMask(GL_TRUE);
// Set up lighting for the scene
GLfloat ambient[4] = {0.f,0.5f,0.5f, 1.f};
glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
// Setup a perspective projection
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(90.f, 1.f, 1.f, 500.f);
// Start game loop
while (App.IsOpened())
{
// Process events
sf::Event Event;
while (App.GetEvent(Event))
{
// Close window : exit
if (Event.Type == sf::Event::Closed)
App.Close();
// Escape key : exit
if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape))
App.Close();
// Resize event : adjust viewport
if (Event.Type == sf::Event::Resized)
glViewport(0, 0, Event.Size.Width, Event.Size.Height);
}
// Set the active window before using OpenGL commands
// It's useless here because active window is always the same,
// but don't forget it if you use multiple windows or controls
App.SetActive();
if((float)Clock.GetElapsedTime()>REFRESH_RATE){
// Clear colour and depth buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Apply some transformations
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.f, 0.f, -5.f);
glRotatef(45.f, 1.f, 1.f, 1.f);
glPushMatrix();
//draw the triangles with glDrawArrays() and then with glDrawElements()
glDrawArrays(GL_TRIANGLES, 0, vertices.size()/3);
//glDrawElements(GL_TRIANGLES, vertices.size(), GL_UNSIGNED_SHORT, &indices[0]);
//glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_SHORT, &indices[0]);
glPopMatrix();
Clock.Reset();
}
// Finally, display rendered frame on screen
App.Display();
}
//delete the vertex arrays using glDisableClientState()
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
return EXIT_SUCCESS;
}
Anyone got any thoughts?

OpenGL lights have default values for all properties (e.g., GL_AMBIENT, GL_DIFFUSE, etc.). In the case of GL_LIGHT0, the diffuse property is not set to zero (which is what you'd need to get only ambient lighting). To remedy that, you'd need to do
GLfloat black[] = { 0.0f, 0.0f, 0.0f, 1.0f };
glLightfv( GL_LIGHT0, GL_DIFFUSE, black );
Since, IIRC, the rest of the light properties are zero already, that should give you ambient-only lighting, which removes the directional component of your lighting. Also, the default mode for glColorMaterial is GL_AMBIENT_AND_DIFFUSE, which sets both the ambient and diffuse material properties to the incoming vertex color. You might consider switching that to ambient only (glColorMaterial( GL_FRONT_AND_BACK, GL_AMBIENT );) as well.
However, the root cause of the oddity of your shading, I think is likely due to non-unit-length normals. You might try adding glEnable( GL_NORMALIZE ); before doing lighting computations.

Related

draw sphere in OpenGL 4.0

my OpenGL version is 4.0. I would like to draw a sphere through latitude and longitude. I use this method:
x=ρsinϕcosθ
y=ρsinϕsinθ
z=ρcosϕ
This is a part of my code:
glm::vec3 buffer[1000];
glm::vec3 outer;
buffercount = 1000;
float section = 10.0f;
GLfloat alpha, beta;
int index = 0;
for (alpha = 0.0 ; alpha <= PI; alpha += PI/section)
{
for (beta = 0.0 ; beta <= 2* PI; beta += PI/section)
{
outer.x = radius*cos(beta)*sin(alpha);
outer.y = radius*sin(beta)*sin(alpha);
outer.z = radius*cos(alpha);
buffer[index] = outer;
index = index +1;
}
}
GLuint sphereVBO, sphereVAO;
glGenVertexArrays(1, &sphereVAO);
glGenBuffers(1,&sphereVBO);
glBindVertexArray(sphereVAO);
glBindBuffer(GL_ARRAY_BUFFER,sphereVBO);
glBufferData(GL_ARRAY_BUFFER,sizeof(glm::vec3) *buffercount ,&buffer[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
...
while (!glfwWindowShouldClose(window))
{
...
...
for (GLuint i = 0; i < buffercount; i++)
{
...
...
glm::mat4 model;
model = glm::translate(model, buffer[i]);
GLfloat angle = 10.0f * i;
model = glm::rotate(model, angle, glm::vec3(1.0f, 0.3f, 0.5f));
glUniformMatrix4fv(modelMat, 1, GL_FALSE, glm::value_ptr(model));
}
glDrawArrays(GL_TRIANGLE_FAN, 0, 900);
glfwSwapBuffers(window);
}
if section = 5, the performance is like this:
if section = 20. the performance is like this:
I think that I might have logic problem in my code. I am struggle in this problem...
-----update-----
I edited my code, It doesn't have any error, but I got a blank screen. I guess that something wrong in my vertex shader. I might pass wrong variables to vertex sheder. Please help me.
gluperspective is deprecated in my OpenGL 4.1
I switch to :
float aspect=float(4.0f)/float(3.0f);
glm::mat4 projection_matrix = glm::perspective(60.0f/aspect,aspect,0.1f,100.0f);
It shows that this error: constant expression evaluates to -1 which cannot be narrowed to type 'GLuint'(aka 'unsigned int')
GLuint sphere_vbo[4]={-1,-1,-1,-1};
GLuint sphere_vao[4]={-1,-1,-1,-1};
I'm not sure how to revise it...I switch to:
GLuint sphere_vbo[4]={1,1,1,1};
GLuint sphere_vao[4]={1,1,1,1};
I put Spektre's code in spherer.h file
This is a part of my main.cpp file:
...
...
Shader shader("basic.vert", "basic.frag");
sphere_init();
while (!glfwWindowShouldClose(window))
{
glfwPollEvents();
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
shader.Use();
GLuint MatrixID = glGetUniformLocation(shader.Program, "MVP");
GLfloat radius = 10.0f;
GLfloat camX = sin(glfwGetTime()) * radius;
GLfloat camZ = cos(glfwGetTime()) * radius;
// view matrix
glm::mat4 view;
view = glm::lookAt(glm::vec3(camX, 0.0, camZ), glm::vec3(0.0, 0.0, 0.0), glm::vec3(0.0, 1.0, 0.0));
glm::mat4 view_matrix = view;
// projection matrix
float aspect=float(4.0f)/float(3.0f);
glm::mat4 projection_matrix = glm::perspective(60.0f/aspect,aspect,0.1f,100.0f);
// model matrix
glm::mat4 model_matrix = glm::mat4(1.0f);// identity
//ModelViewProjection
glm::mat4 model_view_projection = projection_matrix * view_matrix * model_matrix;
glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &model_view_projection[0][0]);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0,0.0,-10.0);
glEnable(GL_DEPTH_TEST);
glDisable(GL_TEXTURE_2D);
sphere_draw();
glFlush();
glfwSwapBuffers(window);
}
sphere_exit();
glfwTerminate();
return 0;
}
This is my vertex shader file:
#version 410 core
uniform mat4 MVP;
layout(location = 0) in vec3 vertexPosition_modelspace;
out vec4 vertexColor;
void main()
{
gl_Position = MVP * vec4(vertexPosition_modelspace,1);
vertexColor = vec4(0, 1, 0, 1.0);
}
I added error-check function get_log in my shader.h file.
...
...
vertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex, 1, &vShaderCode, NULL);
glCompileShader(vertex);
checkCompileErrors(vertex, "VERTEX");
get_log(vertex);
...
...
void get_log(GLuint shader){
GLint isCompiled = 0;
GLchar infoLog[1024];
glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled);
if(isCompiled == GL_FALSE)
{
printf("----error--- \n");
GLint maxLength = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
glGetShaderInfoLog(shader, 1024, NULL, infoLog);
std::cout << "| ERROR::::" << &infoLog << "\n| -- ------------------ --------------------------------- -- |" << std::endl;
glDeleteShader(shader); // Don't leak the shader.
}else{
printf("---no error --- \n");
}
}
I tested both fragment shader and vertex shader, it both showed ---no error---
As I mentioned in the comments you need to add indices to your mesh VAO/VBO. Not sure why GL_QUADS is not implemented on your machine that makes no sense as it is basic primitive so to make this easy to handle I use only GL_TRIANGLES which is far from ideal but what to heck ... Try this:
//---------------------------------------------------------------------------
const int na=36; // vertex grid size
const int nb=18;
const int na3=na*3; // line in grid size
const int nn=nb*na3; // whole grid size
GLfloat sphere_pos[nn]; // vertex
GLfloat sphere_nor[nn]; // normal
//GLfloat sphere_col[nn]; // color
GLuint sphere_ix [na*(nb-1)*6]; // indices
GLuint sphere_vbo[4]={-1,-1,-1,-1};
GLuint sphere_vao[4]={-1,-1,-1,-1};
void sphere_init()
{
// generate the sphere data
GLfloat x,y,z,a,b,da,db,r=3.5;
int ia,ib,ix,iy;
da=2.0*M_PI/GLfloat(na);
db= M_PI/GLfloat(nb-1);
// [Generate sphere point data]
// spherical angles a,b covering whole sphere surface
for (ix=0,b=-0.5*M_PI,ib=0;ib<nb;ib++,b+=db)
for (a=0.0,ia=0;ia<na;ia++,a+=da,ix+=3)
{
// unit sphere
x=cos(b)*cos(a);
y=cos(b)*sin(a);
z=sin(b);
sphere_pos[ix+0]=x*r;
sphere_pos[ix+1]=y*r;
sphere_pos[ix+2]=z*r;
sphere_nor[ix+0]=x;
sphere_nor[ix+1]=y;
sphere_nor[ix+2]=z;
}
// [Generate GL_TRIANGLE indices]
for (ix=0,iy=0,ib=1;ib<nb;ib++)
{
for (ia=1;ia<na;ia++,iy++)
{
// first half of QUAD
sphere_ix[ix]=iy; ix++;
sphere_ix[ix]=iy+1; ix++;
sphere_ix[ix]=iy+na; ix++;
// second half of QUAD
sphere_ix[ix]=iy+na; ix++;
sphere_ix[ix]=iy+1; ix++;
sphere_ix[ix]=iy+na+1; ix++;
}
// first half of QUAD
sphere_ix[ix]=iy; ix++;
sphere_ix[ix]=iy+1-na; ix++;
sphere_ix[ix]=iy+na; ix++;
// second half of QUAD
sphere_ix[ix]=iy+na; ix++;
sphere_ix[ix]=iy-na+1; ix++;
sphere_ix[ix]=iy+1; ix++;
iy++;
}
// [VAO/VBO stuff]
GLuint i;
glGenVertexArrays(4,sphere_vao);
glGenBuffers(4,sphere_vbo);
glBindVertexArray(sphere_vao[0]);
i=0; // vertex
glBindBuffer(GL_ARRAY_BUFFER,sphere_vbo[i]);
glBufferData(GL_ARRAY_BUFFER,sizeof(sphere_pos),sphere_pos,GL_STATIC_DRAW);
glEnableVertexAttribArray(i);
glVertexAttribPointer(i,3,GL_FLOAT,GL_FALSE,0,0);
i=1; // indices
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,sphere_vbo[i]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(sphere_ix),sphere_ix,GL_STATIC_DRAW);
glEnableVertexAttribArray(i);
glVertexAttribPointer(i,4,GL_UNSIGNED_INT,GL_FALSE,0,0);
i=2; // normal
glBindBuffer(GL_ARRAY_BUFFER,sphere_vbo[i]);
glBufferData(GL_ARRAY_BUFFER,sizeof(sphere_nor),sphere_nor,GL_STATIC_DRAW);
glEnableVertexAttribArray(i);
glVertexAttribPointer(i,3,GL_FLOAT,GL_FALSE,0,0);
/*
i=3; // color
glBindBuffer(GL_ARRAY_BUFFER,sphere_vbo[i]);
glBufferData(GL_ARRAY_BUFFER,sizeof(sphere_col),sphere_col,GL_STATIC_DRAW);
glEnableVertexAttribArray(i);
glVertexAttribPointer(i,3,GL_FLOAT,GL_FALSE,0,0);
*/
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER,0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
glDisableVertexAttribArray(3);
}
void sphere_exit()
{
glDeleteVertexArrays(4,sphere_vao);
glDeleteBuffers(4,sphere_vbo);
}
void sphere_draw()
{
glEnable(GL_CULL_FACE);
glFrontFace(GL_CCW);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glBindVertexArray(sphere_vao[0]);
// glDrawArrays(GL_POINTS,0,sizeof(sphere_pos)/sizeof(GLfloat)); // POINTS ... no indices for debug
glDrawElements(GL_TRIANGLES,sizeof(sphere_ix)/sizeof(GLuint),GL_UNSIGNED_INT,0); // indices (choose just one line not both !!!)
glBindVertexArray(0);
}
void gl_draw()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
float aspect=float(xs)/float(ys);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0/aspect,aspect,0.1,100.0);
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0,0.0,-10.0);
glEnable(GL_DEPTH_TEST);
glDisable(GL_TEXTURE_2D);
sphere_draw();
glFlush();
SwapBuffers(hdc);
}
//---------------------------------------------------------------------------
Usage is simple after OpenGL context is created and extensions loaded call sphere_init() before closing app call sphere_exit() (while OpenGL context is still running) and when you want to render call sphere_draw(). I make an gl_draw() example with some settings and here the preview of it:
The point is to create 2D grid of points covering whole surface of sphere (via spherical long,lat a,b angles) and then just create triangles covering whole grid...

Want to draw a wireframe mesh over a solid 3d object imported from blender

So I have this creature and I want to have three distinct modes, a solid, a wireframe and both. All examples using glOffset did not seem to work for me.
Here's my display:
// This function is called to display the scene.
void display()
{
//Background color
glClearColor(1, 1, 1, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
// Matrix setup
glMatrixMode(GL_PROJECTION);
glViewport(0, 0, width, height);
glLoadIdentity();
gluPerspective(40, (float)width / (float)height, 0.1, 1000);
// Matrix setup
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0, 0, -3);
//draw object
glBegin(GL_TRIANGLES);
for (int i = 0; i<mesh->nfaces.size(); i += 1)
for (int j = 0; j<3; j += 1){
glNormal3f(mesh->normal[mesh->nfaces[i][j]][0],
mesh->normal[mesh->nfaces[i][j]][1],
mesh->normal[mesh->nfaces[i][j]][2]);
glVertex3f(mesh->vertex[mesh->faces[i][j]][0],
mesh->vertex[mesh->faces[i][j]][1],
mesh->vertex[mesh->faces[i][j]][2]);
}
glEnd();
glutSwapBuffers();
}
Keyboard code where I tried to implement the shenanigans:
void keyboard(unsigned char key, int x, int y)
{
float colorBronzeDiff[4] = { 0.8, 0.6, 0.0, 1.0 };
switch (key)
{
case(27) :
exit(0);
break;
case('s') :
{
int myFlagCtr = getFlagCtr();
cout << "Pressed Before: " << getFlagCtr() << endl;
if (myFlagCtr == 0) {
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
setFlagCtr(1);
}
else if (myFlagCtr == 1) {
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
setFlagCtr(2);
}
else if (myFlagCtr == 2) {
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(1.0f, 1.0f);
glColor3f(0.0f, 1.0f, 0.0f);
// draw
glDisable(GL_POLYGON_OFFSET_FILL);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
//glEnable( GL_POLYGON_OFFSET_LINE );
//glPolygonOffset( -2.0f, -2.0f );
glColor3f(1.0f, 0.0f, 0.0f);
glLineWidth(1.0f);
// draw
//glDisable( GL_POLYGON_OFFSET_LINE );
setFlagCtr(0);
cout << "Pressed Before: " << getFlagCtr() << endl;
}
break;
}
}
}
And here's main:
void main(int argc, char **argv)
{
// GLUT initialization.
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(width, height);
glutCreateWindow("CodeBase");
// Register call backs.
initialize();
glutDisplayFunc(display);
glutReshapeFunc(reshapeMainWindow);
glutMotionFunc(mouse_motion);
glutIdleFunc(idle);
glutKeyboardFunc(keyboard);
glutMouseFunc(mouse_button);
// Enter GLUT loop.
glutMainLoop();
delete mesh;
}
I assume what I am supposed to do is draw the image twice and then offset it, but for the life of me I can't seem to get this to work. I can't get it to show such a mode by default by putting it directly in display and attempting to draw the object twice.
Edit: In response to latest answer.
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(1.0f, 1.0f);
glColor3f(0.0f, 1.0f, 0.0f);
// draw
//draw object
glBegin(GL_TRIANGLES);
for (int i = 0; i<mesh->nfaces.size(); i += 1)
for (int j = 0; j<3; j += 1){
glNormal3f(mesh->normal[mesh->nfaces[i][j]][0],
mesh->normal[mesh->nfaces[i][j]][1],
mesh->normal[mesh->nfaces[i][j]][2]);
glVertex3f(mesh->vertex[mesh->faces[i][j]][0],
mesh->vertex[mesh->faces[i][j]][1],
mesh->vertex[mesh->faces[i][j]][2]);
}
glEnd();
glDisable(GL_POLYGON_OFFSET_FILL);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glColor3f(1.0f, 0.0f, 0.0f);
glLineWidth(1.0f);
// draw
//draw object
glBegin(GL_TRIANGLES);
for (int i = 0; i<mesh->nfaces.size(); i += 1)
for (int j = 0; j<3; j += 1){
glNormal3f(mesh->normal[mesh->nfaces[i][j]][0],
mesh->normal[mesh->nfaces[i][j]][1],
mesh->normal[mesh->nfaces[i][j]][2]);
glVertex3f(mesh->vertex[mesh->faces[i][j]][0],
mesh->vertex[mesh->faces[i][j]][1],
mesh->vertex[mesh->faces[i][j]][2]);
}
glEnd();
If you want the image to render in both wireframe and solid mode you have to actually execute the geometry rendering functions (eg: glBegin() ... glEnd()) twice.
In your third setting in the keyboard callback you call
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
But you don't draw any geometry between those two calls. GL is a state machine so only the last change to a given state (in this case the polygon drawing mode) will impact the rendering.
your setFlagCtr call should be in the keyboard callback function, but all the other stuff should be in the draw function where for the wire + solid mode you'll have to make sure you're calling this section at least twice:
glBegin(GL_TRIANGLES);
...
glEnd();
Long story short, don't put GL state or rendering management calls anywhere but your display function.

glUseProgram affecting more than just the VAO

I have successfully created a VAO which produces a triangle which can then be rotated with the mouse (with help from shaders).
My problem comes when I try to draw something else using the standard 'glBegin()' and 'glEnd()' functions. It draws successfully, but now, when I try to rotate the triangle the new drawing also rotates.
I know the problem is somehow fixed using the glUseProgram() function, but I'm not entirely sure why or where it should be added.
Here is my code (I've added it all but the main area of focus should be the display() and init() functions:
#include <GL/glew/glew.h>
#include <GL/freeglut.h>
#include <CoreStructures\CoreStructures.h>
#include <iostream>
#include "texture_loader.h"
#include "shader_setup.h"
using namespace std;
using namespace CoreStructures;
float theta = 0.0f;
bool mDown = false;
int mouse_x, mouse_y;
GLuint myShaderProgram;
GLuint locT; // location of "T" uniform variable in myShaderProgram
GLuint locR; // location of "R" uniform variable in myShaderProgram
GLuint sunPosVBO, sunColourVBO, sunIndicesVBO, sunVAO;
// Packed vertex arrays for the star object
// 1) Position Array - Store vertices as (x,y) pairs
static GLfloat sunVertices [] = {
-0.1f, 0.7f,
0.1f, 0.7f,
0.0f, 0.55f
};
// 2) Colour Array - Store RGB values as unsigned bytes
static GLubyte sunColors [] = {
255, 0, 0, 255,
255, 255, 0, 255,
0, 255, 0, 255
};
// 4) Index Array - Store indices to star vertices - this determines the order the vertices are to be processed
static GLubyte sunVertexIndices [] = {0, 1, 2};
void setupSunVAO(void) {
glGenVertexArrays(1, &sunVAO);
glBindVertexArray(sunVAO);
// copy star vertex position data to VBO
glGenBuffers(1, &sunPosVBO);
glBindBuffer(GL_ARRAY_BUFFER, sunPosVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(sunVertices), sunVertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)0);
// copy star vertex colour data to VBO
glGenBuffers(1, &sunColourVBO);
glBindBuffer(GL_ARRAY_BUFFER, sunColourVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(sunColors), sunColors, GL_STATIC_DRAW);
glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, (const GLvoid*)0);
// enable position, colour buffer inputs
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
// setup star vertex index array
glGenBuffers(1, &sunIndicesVBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sunIndicesVBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(sunVertexIndices), sunVertexIndices, GL_STATIC_DRAW);
glBindVertexArray(0);
}
void report_version(void) {
int majorVersion, minorVersion;
glGetIntegerv(GL_MAJOR_VERSION, &majorVersion);
glGetIntegerv(GL_MINOR_VERSION, &minorVersion);
cout << "OpenGL version " << majorVersion << "." << minorVersion << "\n\n";
}
void init(void) {
// initialise glew library
GLenum err = glewInit();
// ensure glew was initialised successfully before proceeding
if (err==GLEW_OK)
cout << "GLEW initialised okay\n";
else
cout << "GLEW could not be initialised\n";
report_version();
glClearColor(0.0, 0.0, 0.0, 0.0);
//
// setup "sun" VBO and VAO object
//
setupSunVAO();
//
// load shader program
//
myShaderProgram = setupShaders(string("Resources\\Shaders\\basic_vertex_shader.txt"), string("Resources\\Shaders\\basic_fragment_shader.txt"));
// get the index / location of the uniform variables "T" and "R" in shader program "myShaderProgram"
locT = glGetUniformLocation(myShaderProgram, "T");
locR = glGetUniformLocation(myShaderProgram, "R");
// "plug-in" shader into GPU pipeline
glUseProgram(myShaderProgram); // we're in the driving seat!!!!! Our shaders now intercept and process our vertices as part of the GPU rendering pipeline (as shown in the lecture notes)
}
// Example rendering functions - draw objects in local, or modelling coordinates
void drawSun(void) {
glBindVertexArray(sunVAO);
glDrawElements(GL_TRIANGLE_STRIP, 3, GL_UNSIGNED_BYTE, (GLvoid*)0);
}
void drawShape()
{
glColor3f(0.0f, 0.6f, 0.2f);
glBegin(GL_POLYGON);
glVertex2f(-1.0f, -1.0f); // Left
glVertex2f(-1.0f, -0.1f);
glVertex2f(-0.9f, -0.05f);
glVertex2f(-0.55f, -0.045f);
glVertex2f(-0.49f, -0.06f);
glVertex2f(-0.4f, -0.055f);
glVertex2f(-0.2f, -0.052f);
glVertex2f(0.0f, -0.02f); // Middle
glVertex2f(0.3f, -0.085f);
glVertex2f(0.5f, -0.08f);
glVertex2f(0.8f, -0.088f);
glVertex2f(1.0f, -0.1f);
glVertex2f(1.0f, -1.0f); // Right
glEnd();
}
//
//
void drawScene()
{
drawSun();
drawShape();
}
void display(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Setup translation matrix and store in T. Pass this over the the shader with the function glUniformMatrix4fv
GUMatrix4 T = GUMatrix4::translationMatrix(0.01f, 0.01f, 0.0f);
glUniformMatrix4fv(locT, 1, GL_FALSE, (GLfloat*)&T);
// Setup rotation matrix and store in R. Pass this over the the shader with the function glUniformMatrix4fv
GUMatrix4 R = GUMatrix4::rotationMatrix(0.0f, 0.0f, theta);
glUniformMatrix4fv(locR, 1, GL_FALSE, (GLfloat*)&R);
// Draw the scene (the above transformations will be applied to each vertex in the vertex shader)
drawScene();
glutSwapBuffers();
}
void mouseButtonDown(int button_id, int state, int x, int y) {
if (button_id==GLUT_LEFT_BUTTON) {
if (state==GLUT_DOWN) {
mouse_x = x;
mouse_y = y;
mDown = true;
} else if (state == GLUT_UP) {
mDown = false;
}
}
}
void mouseMove(int x, int y) {
if (mDown) {
int dx = x - mouse_x;
int dy = y - mouse_y;
float delta_theta = (float)dy * (3.142f * 0.01f);
theta += delta_theta;
mouse_x = x;
mouse_y = y;
glutPostRedisplay();
}
}
void keyDown(unsigned char key, int x, int y) {
if (key=='r') {
theta = 0.0f;
glutPostRedisplay();
}
}
int main(int argc, char **argv) {
glutInit(&argc, argv);
initCOM();
glutInitContextVersion(3, 3);
glutInitContextProfile (GLUT_COMPATIBILITY_PROFILE);
glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
glutInitWindowSize(800, 800);
glutInitWindowPosition(0, 0);
glutCreateWindow("Combining Transforms");
glutDisplayFunc(display);
glutKeyboardFunc(keyDown);
glutMouseFunc(mouseButtonDown);
glutMotionFunc(mouseMove);
init();
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS);
glutMainLoop();
shutdownCOM();
return 0;
}
EDIT
I have an array of x,y vertices and am trying to draw them alongside the above code. For some reason this seems to take vertex data from the sunVAO.
Is there some kind of cache that needs to be cleared? I've searched google and I can't seem to find anyone else who has conflicting VAO and vertex arrays.
(Also, I have checked my code and the vertex data supplied in the array of vertices is correct, they're just not displayed correctly.)
Code:
static GLfloat bottomMarkerVertices[] = {
-0.045f, -0.75f,
0.045f, -0.75f,
-0.07f, -1.0f,
0.07f, -1.0f
};
glVertexPointer(2, GL_FLOAT, 0, bottomMarkerVertices);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
note: vertex arrays have been enabled.
Assuming you're defining your coordinates in normalized device space (suggested by the apparent absence of a projection matrix), the rendering loop needs to look a little like this:
void drawScene()
{
//update shader parameters for the sun shader if necessary
drawSun();
glUseProgram(0);
// at this point, the PROJECTION and MODELVIEW matrices are both the identity
// so the shape is expected to be in NDCs and is not to be transformed
// at all
drawShape();
glUseProgram(progForSun);
}
Note that I don't advise to mix legacy and modern OpenGL like that. The results of vertex processing triggered by drawShape() are only defined because you're using a compatibility profile context.
The two elements of your scene move together because they are both using the same transformation matrices, specificed by these lines:
// Setup translation matrix and store in T. Pass this over the the shader with the function glUniformMatrix4fv
GUMatrix4 T = GUMatrix4::translationMatrix(0.01f, 0.01f, 0.0f);
glUniformMatrix4fv(locT, 1, GL_FALSE, (GLfloat*)&T);
// Setup rotation matrix and store in R. Pass this over the the shader with the function glUniformMatrix4fv
GUMatrix4 R = GUMatrix4::rotationMatrix(0.0f, 0.0f, theta);
glUniformMatrix4fv(locR, 1, GL_FALSE, (GLfloat*)&R);
If you want drawShape() not to move with the mouse, you need to reset locR with a fixed theta value before you call it.
drawSun();
GUMatrix4 R = GUMatrix4::rotationMatrix(0.0f, 0.0f, 0.0f);
glUniformMatrix4fv(locR, 1, GL_FALSE, (GLfloat*)&R);
drawShape();

OpenGL displaying white textures

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.

Sdl_image cannot find my jpg image; Won't load

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" );