Crash in glDrawArrays for large models - c++

I have implemented a simple (slow) method that would imitate OpenGL immediate mode for drawing lines.
Each frame, I add a pair of vertices, that indicate lines to vector structure, as well as add some specified or default color to another vector structure.
void WindowsGraphicsManager::vertex(float x, float y, float z) {
vertices_.push_back(x);
vertices_.push_back(y);
vertices_.push_back(z);
colors_.push_back(vertexColor_.getR());
colors_.push_back(vertexColor_.getG());
colors_.push_back(vertexColor_.getB());
colors_.push_back(vertexColor_.getA());
}
And at the end of each frame I clear these vectors.
My render code looks like this:
void WindowsGraphicsManager::renderVertices(Mat4 mat) {
if (vertices_.size() == 0) {
return;
}
static Shader* shader = (Shader*) services_->getRM()->get(
Resource::SHADER, "openglimmediate");
glUseProgram(shader->getId());
shader->setMatrix4(Shader::WVP, mat);
glEnableVertexAttribArray(shader->getHandle(Shader::POS));
glVertexAttribPointer(shader->getHandle(Shader::POS),
3, GL_FLOAT, GL_FALSE, 0, &vertices_[0]);
glEnableVertexAttribArray(shader->getHandle(Shader::COL));
glVertexAttribPointer(shader->getHandle(Shader::COL),
4, GL_FLOAT, GL_FALSE, 0, &colors_[0]);
//LOGI("Before crash.");
//LOGI("Vertices size: %d", vertices_.size());
//LOGI("Colors size: %d", colors_.size());
//INFO: Vertices size: 607590
//INFO: Colors size: 810120
glDrawArrays(GL_LINES, 0, vertices_.size() / 3);
CHECK_GL_ERROR("Rendering lines.");
//LOGI("After crash.");
glDisableVertexAttribArray(shader->getHandle(Shader::COL));
glDisableVertexAttribArray(shader->getHandle(Shader::POS));
vertices_.clear();
colors_.clear();
}
When I add 607590 floats (divide by 3 for vertices) to vertices vector, rendering crashes on line with glDrawArrays function. Strange thing though, when I first maximize the window and render, then it works fine for model with 607590 floats, though it still crashes for model with ~800k flaots.
What might be causing this?
[Edit] Before rendering vertices I call one other method. After removing it, rendering stopped crashing, so I guess I do something wrong here.
inline void WindowsGraphicsManager::renderNode(
Node* node, Mat4 mat, bool ortho)
{
if (!node->getState(Node::RENDERABLE)) {
return;
}
// Retrieve model data.
Renderable* renderable = 0;
Resource* resource = 0;
if (node->hasResource(Resource::SPRITE)) {
resource = node->getResource(Resource::SPRITE);
renderable = dynamic_cast<Renderable*>(resource);
}
else if (node->hasResource(Resource::STATIC_OBJECT)) {
resource = node->getResource(Resource::STATIC_OBJECT);
renderable = dynamic_cast<Renderable*>(resource);
StaticObject* so = static_cast<StaticObject*>(resource);
// Check for frustum culling.
if (so->getBoundingVolume() != 0
&& so->getBoundingVolume()->isInFrustum(
services_->getCamera(), node->getPos())
== BoundingVolume::OUTSIDE)
{
return;
}
}
else if (node->hasResource(Resource::DYNAMIC_OBJECT)) {
resource = node->getResource(Resource::DYNAMIC_OBJECT);
renderable = dynamic_cast<Renderable*>(resource);
}
if (renderable == 0) {
LOGW("Renderable with name \"%s\" is null.",
node->getName().c_str());
return;
}
// Retrieve node shader or use default.
Shader* shader = static_cast<Shader*>(
node->getResource(Resource::SHADER));
if (shader == 0) {
LOGW("Unable to retrieve shader for node: %s.",
node->getName().c_str());
return;
}
int shaderId = shader->getId();
// Select shader program to use.
glUseProgram(shaderId);
CHECK_GL_ERROR("glUseProgram");
Mat4 res;
if (!ortho) {
Matrix::multiply(mat, node->getMatrix(), res);
}
else {
Mat4 tmp;
Mat4 pos;
Mat4 rot;
Mat4 scale;
Vec3 p = node->getPos();
Vec3 r = node->getRot();
Vec3 s = node->getScale();
float width = s.getX();
float height = s.getY();
float x = p.getX();
float y = p.getY();
Matrix::translate(pos, x, y, p.getZ());
Matrix::rotateXYZ(rot, r.getX(), r.getY(), r.getZ());
Matrix::scale(scale, width, height, 1.0f);
Matrix::multiply(mat, pos, res);
Matrix::multiply(res, rot, tmp);
Matrix::multiply(tmp, scale, res);
}
// World * View * Projection matrix.
shader->setMatrix4(Shader::WVP, res);
// World matrix.
shader->setMatrix4(Shader::W, node->getMatrix());
// Normal matrix.
if (shader->hasHandle(Shader::N)) {
Mat3 normalMatrix;
Matrix::toMat3(node->getMatrix(), normalMatrix);
shader->setMatrix3(Shader::N, normalMatrix);
}
// Light position.
float* lightPos = new float[lights_.size() * 3];
if (lights_.size() > 0 && shader->hasHandle(Shader::LIGHT_POS)) {
for (UINT i = 0; i < lights_.size(); i++) {
Vec3& pos = lights_[i]->getPos();
lightPos[i * 3 + 0] = pos.getX();
lightPos[i * 3 + 1] = pos.getY();
lightPos[i * 3 + 2] = pos.getZ();
}
shader->setVector3(Shader::LIGHT_POS, lightPos, lights_.size());
}
delete lightPos;
// Light count.
shader->setInt(Shader::LIGHT_COUNT, lights_.size());
//shader->setVector3(Shader::LIGHT_POS,
// services_->getEnv()->getSunPos()->toArray());
// Eye position.
shader->setVector3(Shader::EYE_POS,
services_->getCamera()->getPos().toArray());
// Fog color.
if (shader->hasHandle(Shader::FOG_COLOR)) {
shader->setVector3(Shader::FOG_COLOR,
services_->getEnv()->getFogColor());
}
// Fog density.
shader->setFloat(Shader::FOG_DENSITY, services_->getEnv()->getFogDensity());
// Timer.
shader->setFloat(Shader::TIMER,
(float) services_->getSystem()->getTimeElapsed());
// Bind combined buffer object.
if (renderable->getCBO() > 0) {
int stride = renderable->getVertexStride();
glBindBuffer(GL_ARRAY_BUFFER, renderable->getCBO());
if (shader->hasHandle(Shader::POS)) {
glEnableVertexAttribArray(shader->getHandle(Shader::POS));
glVertexAttribPointer(
shader->getHandle(Shader::POS), 3, GL_FLOAT, GL_FALSE,
stride, ((char*) 0) + renderable->getPosOffset());
}
if (renderable->getNormalOffset() != -1
&& shader->hasHandle(Shader::NORMAL)) {
glEnableVertexAttribArray(shader->getHandle(Shader::NORMAL));
glVertexAttribPointer(
shader->getHandle(Shader::NORMAL), 3, GL_FLOAT, GL_FALSE,
stride, ((char*) 0) + renderable->getNormalOffset());
}
if (renderable->getUVOffset() != -1 && shader->hasHandle(Shader::UV)) {
glEnableVertexAttribArray(shader->getHandle(Shader::UV));
glVertexAttribPointer(
shader->getHandle(Shader::UV), 2, GL_FLOAT, GL_FALSE,
stride, ((char*) 0) + renderable->getUVOffset());
}
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
else {
return;
}
// Bind cube map.
if (node->hasResource(Resource::CUBE_MAP)
&& shader->hasHandle(Shader::CUBE_MAP)) {
glActiveTexture(GL_TEXTURE0);
CHECK_GL_ERROR("glActiveTexture");
CubeMap* t = static_cast<CubeMap*>(
node->getResource(Resource::CUBE_MAP));
glBindTexture(GL_TEXTURE_CUBE_MAP, t->getId());
CHECK_GL_ERROR("glBindTexture");
glUniform1i(shader->getHandle(Shader::CUBE_MAP), 0);
CHECK_GL_ERROR("glUniform1i");
}
int hTextures[8];
hTextures[0] = glGetUniformLocation(shader->getId(),
SHADER_MAIN_TEXTURE);
// Bind the texture.
vector<Resource*> textures = node->getResources(Resource::TEXTURE_2D);
UINT size = textures.size() < 8 ? textures.size() : 7;
UINT texture = 0;
for (UINT i = 0; i < size; i++) {
texture = i + 1;
const string& name = textures[i]->getName();
Texture2D* tex = static_cast<Texture2D*>(textures[i]);
string textName = name.substr(0, name.length() - 4);
hTextures[texture] = glGetUniformLocation(shader->getId(),
textName.c_str());
if (hTextures[texture] == -1) {
continue;
}
glActiveTexture(GL_TEXTURE0 + i + 1);
CHECK_GL_ERROR("glActiveTexture");
glBindTexture(GL_TEXTURE_2D, tex->getId());
CHECK_GL_ERROR("glBindTexture");
glUniform1i(hTextures[texture], texture);
CHECK_GL_ERROR("glUniform1i");
}
// Render node.
// BoundingVolume* volume = (*model->getBoundingVolumes())[i];
// if (model->hasBoundingVolumes()) {
// if (volume->isInFrustum(services_->getCamera(), node)
// == BoundingVolume::OUTSIDE) {
// continue;
// }
// }
int renderType;
switch (renderable->getRenderType()) {
case Renderable::RENDER_TYPE_POINTS:
renderType = GL_POINTS;
//glPointSize(renderable->getPointSize());
break;
case Renderable::RENDER_TYPE_LINES:
renderType = GL_LINES;
glLineWidth(renderable->getLineWidth());
break;
case Renderable::RENDER_TYPE_TRIANGLE_FAN:
renderType = GL_TRIANGLE_FAN;
break;
case Renderable::RENDER_TYPE_TRIANGLE_STRIP:
renderType = GL_TRIANGLE_STRIP;
break;
default:
renderType = GL_TRIANGLES;
break;
}
if (renderable->getWindingType() == Renderable::WINDING_TYPE_CCW) {
glFrontFace(GL_CCW);
}
else {
glFrontFace(GL_CW);
}
if (renderable->getCullFace()) {
glEnable(GL_CULL_FACE);
}
else {
glDisable(GL_CULL_FACE);
}
UINT renderCount = renderable->getRenderCount();
int lastTexture = 0;
for (UINT i = 0; i < renderable->getRenderCount(); i++) {
renderable->setRenderable(i);
// Ambient material color.
if (shader->hasHandle(Shader::AMBIENT)) {
shader->setVector3(Shader::AMBIENT,
renderable->getAmbient().toArray());
}
// Diffuse material color.
if (shader->hasHandle(Shader::DIFFUSE)) {
shader->setVector3(Shader::DIFFUSE,
renderable->getDiffuse().toArray());
}
// Specular material color.
if (shader->hasHandle(Shader::SPECULAR)) {
shader->setVector3(Shader::SPECULAR,
renderable->getSpecular().toArray());
}
// Specular material color intensity.
shader->setFloat(Shader::SPECULARITY, renderable->getSpecularity());
// Model transparency.
shader->setFloat(Shader::TRANSPARENCY, renderable->getTransparency());
// Bind main texture.
if (renderable->getTexture() != lastTexture
&& hTextures[0] != -1) {
lastTexture = renderable->getTexture();
if (shader->hasHandle(Shader::MAIN_TEXTURE)) {
if (lastTexture == 0) {
shader->setFloat(Shader::MAIN_TEXTURE, 0.0f);
}
else {
shader->setFloat(Shader::MAIN_TEXTURE, 1.0f);
}
}
glActiveTexture(GL_TEXTURE0);
CHECK_GL_ERROR("glActiveTexture");
glBindTexture(GL_TEXTURE_2D, renderable->getTexture());
CHECK_GL_ERROR("glBindTexture");
glUniform1i(hTextures[0], 0);
CHECK_GL_ERROR("glUniform1i");
}
if (renderable->getIBO() > 0) {
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,
renderable->getIBO());
if (renderable->getIndexType() ==
Renderable::INDEX_TYPE_USHORT) {
glDrawElements(renderType,
renderable->getIndexCount(),
GL_UNSIGNED_SHORT,
0);
CHECK_GL_ERROR("glDrawElements");
}
else {
glDrawElements(renderType,
renderable->getIndexCount(),
GL_UNSIGNED_INT,
0);
CHECK_GL_ERROR("glDrawElementsInt");
}
}
else {
glDrawArrays(renderType, 0, renderable->getVertexCount() / 3);
CHECK_GL_ERROR("glDrawArrays");
}
}
//// Unbind the cube map.
//if (node->hasResource(Resource::CUBE_MAP)) {
// glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
//}
//// Unbind the textures.
//for (UINT i = 0; i < 8; i++) {
// glActiveTexture(GL_TEXTURE0 + i);
// CHECK_GL_ERROR("glActiveTexture");
// glBindTexture(GL_TEXTURE_2D, 0);
//}
}

So the problem was glBindBuffer() call after this part of code:
// Bind combined buffer object.
if (renderable->getCBO() > 0) {
int stride = renderable->getVertexStride();
glBindBuffer(GL_ARRAY_BUFFER, renderable->getCBO());
if (shader->hasHandle(Shader::POS)) {
glEnableVertexAttribArray(shader->getHandle(Shader::POS));
glVertexAttribPointer(
shader->getHandle(Shader::POS), 3, GL_FLOAT, GL_FALSE,
stride, ((char*) 0) + renderable->getPosOffset());
}
if (renderable->getNormalOffset() != -1
&& shader->hasHandle(Shader::NORMAL)) {
glEnableVertexAttribArray(shader->getHandle(Shader::NORMAL));
glVertexAttribPointer(
shader->getHandle(Shader::NORMAL), 3, GL_FLOAT, GL_FALSE,
stride, ((char*) 0) + renderable->getNormalOffset());
}
if (renderable->getUVOffset() != -1 && shader->hasHandle(Shader::UV)) {
glEnableVertexAttribArray(shader->getHandle(Shader::UV));
glVertexAttribPointer(
shader->getHandle(Shader::UV), 2, GL_FLOAT, GL_FALSE,
stride, ((char*) 0) + renderable->getUVOffset());
}
glBindBuffer(GL_ARRAY_BUFFER, 0);
I had to move glBindBuffer() to the end of same method, and I also wrote glDisableVertexAttribArray for position, normal and UV buffers. This solved the problem, but I'm not sure why. I thought there is no need to call glDisableVertexAttribArray for VBO.
I think this problem is specific for NVIDIA drivers and gives first chance exception for nvoglv32.dll.

Related

OpenGL: Strange normal rendering

I have a issue with OpenGL normals.
I'm rendering the dragon model, but I have some weird normal patterns.
Here is screenshot from my render:
render_screen
this is my buffer creation methods:
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
if (has_position) {
glGenBuffers(1, &vertex_buffer);
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * 3 * sizeof(float), vertices.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(kVertexArray);
glVertexAttribPointer(kVertexArray, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
}
if (has_normal) {
glGenBuffers(1, &normal_buffer);
glBindBuffer(GL_ARRAY_BUFFER, normal_buffer);
glBufferData(GL_ARRAY_BUFFER, normals.size() * 3 * sizeof(float), normals.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(kNormalArray);
glVertexAttribPointer(kNormalArray, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
}
if (has_tex_coord) {
glGenBuffers(1, &tex_coord_buffer);
glBindBuffer(GL_ARRAY_BUFFER, tex_coord_buffer);
glBufferData(GL_ARRAY_BUFFER, tex_coords.size() * 3 * sizeof(float), tex_coords.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(kTexCoordArray);
glVertexAttribPointer(kTexCoordArray, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
}
if (has_index) {
glGenBuffers(1, &index_buffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_buffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * 3 * sizeof(unsigned short), indices.data(), GL_STATIC_DRAW);
glBindVertexArray(0);
}
and draw with:
glDrawElements(GL_TRIANGLES, indices.size() * 3, GL_UNSIGNED_SHORT, BUFFER_OFFSET(0));
Wavefront obj loader method:
bool Loadfs() {
CVector3<float> vertex;
CVector3<unsigned short> vindex, tindex, nindex;
while(file_stream->offset_ < file_stream->size_) {
if (file_stream->buffer_[file_stream->offset_] == '#') {
char comment[512] = {0};
file_stream->ReadLine(comment); // check return code -> "its local variable return address"
file_stream->SkipLine();
}
else if (file_stream->buffer_[file_stream->offset_] == 'v') {
file_stream->offset_++;
if (file_stream->buffer_[file_stream->offset_] == ' ') {
has_position = true;
file_stream->offset_++;
file_stream->SkipWhiteSpace();
vertex.x = file_stream->ReadFloat();
file_stream->SkipWhiteSpace();
vertex.y = file_stream->ReadFloat();
file_stream->SkipWhiteSpace();
vertex.z = file_stream->ReadFloat();
file_stream->SkipLine();
vertices.push_back(vertex);
}
else if (file_stream->buffer_[file_stream->offset_] == 'n') {
has_normal = true;
file_stream->offset_++;
file_stream->SkipWhiteSpace();
vertex.x = file_stream->ReadFloat();
file_stream->SkipWhiteSpace();
vertex.y = file_stream->ReadFloat();
file_stream->SkipWhiteSpace();
vertex.z = file_stream->ReadFloat();
file_stream->SkipLine();
normals.push_back(vertex);
}
else if (file_stream->buffer_[file_stream->offset_] == 't') {
has_tex_coord = true;
file_stream->offset_++;
file_stream->SkipWhiteSpace();
vertex.x = file_stream->ReadFloat();
file_stream->SkipWhiteSpace();
vertex.y = file_stream->ReadFloat();
file_stream->SkipWhiteSpace();
vertex.z = file_stream->ReadFloat();
file_stream->SkipLine();
tex_coords.push_back(vertex);
}
}
else if (file_stream->buffer_[file_stream->offset_] == 'f') {
has_index = true;
file_stream->offset_++;
file_stream->SkipWhiteSpace();
//
if (has_position) {
vindex.x = file_stream->ReadShort();
}
if (has_tex_coord) {
file_stream->offset_++;
tindex.x = file_stream->ReadShort();
}
if (has_normal) {
file_stream->offset_++;
nindex.x = file_stream->ReadShort();
}
file_stream->SkipWhile(' ');
//
if (has_position) {
vindex.y = file_stream->ReadShort();
}
if (has_tex_coord) {
file_stream->offset_++;
tindex.y = file_stream->ReadShort();
}
if (has_normal) {
file_stream->offset_++;
nindex.y = file_stream->ReadShort();
}
file_stream->SkipWhile(' ');
//
if (has_position) {
vindex.z = file_stream->ReadShort();
}
if (has_tex_coord) {
file_stream->offset_++;
tindex.z = file_stream->ReadShort();
}
if (has_normal) {
file_stream->offset_++;
nindex.z = file_stream->ReadShort();
}
vi.push_back(--vindex);
ti.push_back(--tindex);
ni.push_back(--nindex);
//indices.push_back(--vindex);
}
else file_stream->SkipLine();
}
indices.insert(indices.end(), vi.begin(), vi.end());
return true;
}
Here vs:glsl main methods:
position_ = MV * vec4(vVertex, 1.0);
normal_ = normalize(N * vNormal);
texture_ = vTexture;
//shadow_ = S * M * vec4(vVertex, 1.0);
gl_Position = MVP * vec4(vVertex, 1.0);
and fs.glsl main methods:
vec3 rgb = vec3(1.0, 1.0, 1.0);
rgb = PhongShade(g_light, g_material, position_, normal_);
_frag_color = vec4(rgb, 1.0);
//_frag_color = texel * vec4(ambient + diffuse + specular, 1.0);
Anyone got any thoughts?
The problem is that OpenGL uses a single index buffer to index the vertex position, texture coordinates and normal buffers, using the same index for each (3 indices for a triangle), whereas the Wavefront obj format allows each face to specify separate indices for the vertex position, texture coordinate and normal independently (9 indices in total for a triangle).
It's not clear from your code but most likely you are not actually using the ti and ni index arrays that you are reading in, but are creating your index_buffer from vi, so the vertex indices are being used to index into normal_buffer and tex_coord_buffer, giving the strange results.
To fix this issue you need to create buffers of vertex coordinates, tex coordinates and normal coordinates with an entry for each unique combination of vertex position index, tex coord index and normal index that is used in a face definition in the obj file, then make your index buffer index into these arrays such that a particular face vertex has the same index for each. Ideally this would be done as a pre-processing step instead of at load time.
Alternatively, abandon indexed rendering with glDrawElements and use glDrawArrays instead. Write out one entry to each of the arrays for each face vertex, based on the face vertex indices for the position, tex coord and normal, and then render that. This is less efficient however.
Another solution (if it's possible) is to export the obj file in such a way that each face vertex uses the same indices for position, tex coord and normal.

OpenGL vertex shader transform, object disappearing

I have successfully set up a shader and a test triangle for OpenGL. And I want to set up a transformation uniform that can be applied in the vertex shader. Problem is, I can't see my object anymore after I multiply my vec4 position with the mat4 transform. Where am I doing something wrong?
Vertex shader:
#version 120
attribute vec3 vertices;
attribute vec3 colors;
attribute vec2 texCoords;
uniform mat4 transform;
varying vec3 shared_colors;
varying vec2 shared_texCoords;
void main() {
gl_Position = transform * vec4(vertices, 1.0);
//Send data to fragment shader
shared_colors = colors;
shared_texCoords = texCoords;
}
Fragment shader:
#version 120
uniform sampler2D diffuse;
varying vec3 shared_colors;
varying vec2 shared_texCoords;
void main() {
gl_FragColor = vec4(shared_colors, 1);
//gl_FragColor = texture2D(diffuse, shared_texCoords); //vec4(1, 0, 0, 1);
}
Shader class:
#include "Shader.h"
Shader::Shader(string fileName) {
m_program = glCreateProgram();
m_shaders[SHA_VERTEX] = createShader(loadShader(fileName + ".vs"), GL_VERTEX_SHADER);
m_shaders[SHA_FRAGMENT] = createShader(loadShader(fileName + ".fs"), GL_FRAGMENT_SHADER);
for (int i = 0; i < SHA_COUNT; i++) {
glAttachShader(m_program, m_shaders[i]);
}
glBindAttribLocation(m_program, VBO_VERTEX, "vertices");
glBindAttribLocation(m_program, VBO_COLOR, "colors");
glBindAttribLocation(m_program, VBO_TEXCORD, "texCoords");
glLinkProgram(m_program);
checkShaderError(m_program, GL_LINK_STATUS, true, "Error linking shader program");
glValidateProgram(m_program);
checkShaderError(m_program, GL_VALIDATE_STATUS, true, "Invalid shader program");
m_uniforms[UNI_TRANSFORM] = glGetUniformLocation(m_program, "transform");
}
Shader::~Shader() {
for (int i = 0; i < SHA_COUNT; i++) {
glDetachShader(m_program, m_shaders[i]);
glDeleteShader(m_shaders[i]);
}
glDeleteProgram(m_program);
}
string Shader::loadShader(string filePath) {
ifstream file;
file.open((filePath).c_str());
string output;
string line;
if(file.is_open()) {
while(file.good()) {
getline(file, line);
output.append(line + "\n");
}
}
else {
printf("Unable to load shader: %s\n", filePath.c_str());
}
return output;
}
void Shader::checkShaderError(GLuint shader, GLuint flag, bool isProgram, string errorMessage) {
GLint success = 0;
GLchar error[1024] = {0};
if (isProgram) {
glGetProgramiv(shader, flag, &success);
}
else {
glGetShaderiv(shader, flag, &success);
}
if (success == GL_FALSE) {
if(isProgram) {
glGetProgramInfoLog(shader, sizeof(error), NULL, error);
}
else {
glGetShaderInfoLog(shader, sizeof(error), NULL, error);
}
printf("%s: '%s'\n", errorMessage.c_str(), error);
}
}
GLuint Shader::createShader(string text, unsigned int type) {
GLuint shader = glCreateShader(type);
if (shader == 0) {
printf("Error compiling shader type %i\n", type);
}
const GLchar *p[1];
p[0] = text.c_str();
GLint lengths[1];
lengths[0] = text.length();
glShaderSource(shader, 1, p, lengths);
glCompileShader(shader);
checkShaderError(shader, GL_COMPILE_STATUS, false, "Error compiling shader!");
return shader;
}
void Shader::update(Transform *matrix) {
glm::mat4 model = matrix->getModel();
glUniformMatrix4fv(m_uniforms[UNI_TRANSFORM], 1, GL_FALSE, &model[0][0]);
}
void Shader::enable(bool state) {
if (state) {
glUseProgram(m_program);
}
else {
glUseProgram(NULL);
}
}
Mesh class (or, my object class if you rather call it that):
#include "Mesh.h"
Mesh::Mesh() {
initMesh();
}
Mesh::Mesh(ObjectData *obj) {
initMesh();
//Set object to parameter
object = obj;
initVBO();
}
Mesh::~Mesh() {
delete transform;
//Delete buffer
glDeleteBuffers(VBO_COUNT, buffers);
//Delete array
glDeleteVertexArrays(1, &arrayObject);
}
void Mesh::draw() {
if (initialized) {
shader->update(transform);
shader->enable(true);
texture->enable(true);
//Tell OpenGL which array to use
glBindVertexArray(arrayObject);
glDrawArrays(GL_TRIANGLES, 0, object->vertices.size());
glBindVertexArray(NULL);
shader->enable(false);
texture->enable(false);
}
}
void Mesh::initMesh() {
initialized = false;
shader = new Shader(DIR_SHADERS + "BasicShader");
transform = new Transform();
}
void Mesh::initVBO() {
glGenVertexArrays(1, &arrayObject);
//Tell OpenGL which vertex array to use from now
glBindVertexArray(arrayObject);
glGenBuffers(VBO_COUNT, buffers);
//Set buffer data
glBindBuffer(GL_ARRAY_BUFFER, buffers[VBO_VERTEX]);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * object->vertices.size(), &object->vertices.front(), GL_STATIC_DRAW);
//Set shader attribute data
glEnableVertexAttribArray(VBO_VERTEX);
glVertexAttribPointer(VBO_VERTEX, 3, GL_FLOAT, GL_FALSE, NULL, NULL);
//Set buffer data
glBindBuffer(GL_ARRAY_BUFFER, buffers[VBO_COLOR]);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * object->colors.size(), &object->colors.front(), GL_STATIC_DRAW);
//Set shader attribute data
glEnableVertexAttribArray(VBO_COLOR);
glVertexAttribPointer(VBO_COLOR, 3, GL_FLOAT, GL_FALSE, NULL, NULL);
if (object->texCoords.size()) {
//Set buffer data
glBindBuffer(GL_ARRAY_BUFFER, buffers[VBO_TEXCORD]);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec2) * object->texCoords.size(), &object->texCoords.front(), GL_STATIC_DRAW);
//Set shader attribute data
glEnableVertexAttribArray(VBO_TEXCORD);
glVertexAttribPointer(VBO_TEXCORD, 2, GL_FLOAT, GL_FALSE, NULL, NULL);
}
//Unbind vertex array
glBindVertexArray(NULL);
initialized = true;
}
void Mesh::updateVBO() {
//Tell OpenGL which vertex array to use from now
glBindVertexArray(arrayObject);
//Set buffer data
glBindBuffer(GL_ARRAY_BUFFER, buffers[VBO_VERTEX]);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * object->vertices.size(), &object->vertices.front(), GL_STATIC_DRAW);
//Set shader attribute data
glEnableVertexAttribArray(VBO_VERTEX);
glVertexAttribPointer(VBO_VERTEX, 3, GL_FLOAT, GL_FALSE, NULL, NULL);
//Set buffer data
glBindBuffer(GL_ARRAY_BUFFER, buffers[VBO_COLOR]);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * object->colors.size(), &object->colors.front(), GL_STATIC_DRAW);
//Set shader attribute data
glEnableVertexAttribArray(VBO_COLOR);
glVertexAttribPointer(VBO_COLOR, 3, GL_FLOAT, GL_FALSE, NULL, NULL);
if (object->texCoords.size()) {
//Set buffer data
glBindBuffer(GL_ARRAY_BUFFER, buffers[VBO_TEXCORD]);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec2) * object->texCoords.size(), &object->texCoords.front(), GL_STATIC_DRAW);
//Set shader attribute data
glEnableVertexAttribArray(VBO_TEXCORD);
glVertexAttribPointer(VBO_TEXCORD, 2, GL_FLOAT, GL_FALSE, NULL, NULL);
}
//Unbind vertex array
glBindVertexArray(NULL);
}
void Mesh::setShader(string file) {
shader = new Shader(file);
}
void Mesh::setTexture(string file) {
texture = new Texture(file);
}
void Mesh::loadObject(string file) {
//Example object
object = new ObjectData();
object->vertices.push_back(glm::vec3(-0.5, -0.5, 0));
object->vertices.push_back(glm::vec3(0, 0.5, 0));
object->vertices.push_back(glm::vec3(0.5, -0.5, 0));
//object->texCoords.push_back(glm::vec2(0, 0));
//object->texCoords.push_back(glm::vec2(0.5, 1));
//object->texCoords.push_back(glm::vec2(1, 0));
object->colors.push_back(glm::vec3(255, 0, 0));
object->colors.push_back(glm::vec3(255, 0, 0));
object->colors.push_back(glm::vec3(255, 0, 0));
//object->vertices.push_back(glm::vec3(0.5, 0.5, 0));
//object->vertices.push_back(glm::vec3(0.75, 1, 0));
//object->vertices.push_back(glm::vec3(1, 0.5, 0));
//object->texCoords.push_back(glm::vec2(0, 0));
//object->texCoords.push_back(glm::vec2(0.5, 1));
//object->texCoords.push_back(glm::vec2(1, 0));
//object->colors.push_back(glm::vec3(0, 255, 0));
//object->colors.push_back(glm::vec3(0, 255, 0));
//object->colors.push_back(glm::vec3(0, 255, 0));
if (initialized) {
updateVBO();
}
else {
initVBO();
}
}
Transform class:
#include "Transform.h"
Transform::Transform() {
position = glm::vec3();
rotation = glm::vec3();
scale = glm::vec3(1, 1, 1);
}
Transform::~Transform() {
}
void Transform::setPosition(glm::vec3 pos) {
position = pos;
}
void Transform::setRotation(glm::vec3 rot) {
rotation = rot;
}
void Transform::setScale(glm::vec3 sca) {
scale = sca;
}
glm::vec3 Transform::getPosition() {
return position;
}
glm::vec3 Transform::getRotation() {
return rotation;
}
glm::vec3 Transform::getScale() {
return scale;
}
glm::mat4 Transform::getModel() {
glm::mat4 pos = glm::translate(position);
glm::mat4 rotX = glm::rotate(rotation.x, glm::vec3(1, 0, 0));
glm::mat4 rotY = glm::rotate(rotation.y, glm::vec3(0, 1, 0));
glm::mat4 rotZ = glm::rotate(rotation.z, glm::vec3(0, 0, 1));
glm::mat4 sca = glm::scale(scale);
glm::mat4 rot = rotZ * rotY * rotX;
glm::mat4 finalMatrix = pos * rot * sca;
return finalMatrix;
}
From your code:
void Mesh::draw() {
if (initialized) {
shader->update(transform);
shader->enable(true);
GL uniforms are per program state, and setting a uniform will affect the currently bound program object. Since you do not have the program object bound at the time you try to set the uniform, the uniform is left at its default state (all zeros). Just switch these two lines...

BillBoarding Implementation

I am trying to implement soft particles in my projects.
Everything is fine , I implement the texture also. But when the mouse is moved to a certain angle,
the particles get distorted. The particle is generated in view space.
So, I would like to know how could I implement the billboard in my project so that every particles seem uniform.Here is my code:
bool CETSmokeRenderer::InitBuffers()
{
size_t vertexSize = 3 * 4 * m_NumVertex * sizeof(float);
size_t colorSize = 4 * 4 * m_NumVertex * sizeof(float);
size_t texCoordSize = 2 * 4 * m_NumVertex * sizeof(float);
if(!vertexBuffer)
{
glDeleteBuffersARB(1, &vertexBuffer);
glDeleteBuffersARB(1, &colorBuffer);
glDeleteBuffersARB(1, &texCoordBuffer);
}
glGenBuffersARB(1, &vertexBuffer);
glGenBuffersARB(1, &colorBuffer);
glGenBuffersARB(1, &texCoordBuffer);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, vertexBuffer);
glBufferDataARB(GL_ARRAY_BUFFER_ARB, vertexSize, NULL, GL_STREAM_DRAW_ARB);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, colorBuffer);
glBufferDataARB(GL_ARRAY_BUFFER_ARB, colorSize, NULL, GL_STREAM_DRAW_ARB);
// Creates the static texture data
size_t len = 2 * 4 * m_NumVertex;
if(0 > m_NumVertex)
{
return false;
}
else if(0 == m_NumVertex)
{
return true;
}
float *texCoords = new float[len];
{
size_t i = 0;
while(i < len)
{
// u v
texCoords[i++] = 0.0f; texCoords[i++] = 0.0f;
texCoords[i++] = 1.0f; texCoords[i++] = 0.0f;
texCoords[i++] = 1.0f; texCoords[i++] = 1.0f;
texCoords[i++] = 0.0f; texCoords[i++] = 1.0f;
}
}
glBindBufferARB(GL_ARRAY_BUFFER_ARB, texCoordBuffer);
glBufferDataARB(GL_ARRAY_BUFFER_ARB, texCoordSize, (void*)texCoords, GL_STATIC_DRAW_ARB);
delete texCoords;
glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
return 0;
}
void CETSmokeRenderer::Draw(Camera &cam, bool useTex)
{
if(useTex)
glBindTexture(GL_TEXTURE_2D, texID);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
mBaseView->SetupViewingTransform();
size_t len = particleStore.size();
std::vector<SimpleSmokeParticle> toDraw;
for(size_t i = 0; i < len; i++)
{
SimpleSmokeParticle sp;
sp.transP = particleStore[i].p;
sp.index = i;
toDraw.push_back(sp);
}
//std::sort(toDraw.begin(), toDraw.end(), ParticleCmp);
#ifdef USE_VBO
glBindBufferARB(GL_ARRAY_BUFFER_ARB, vertexBuffer);
glBufferDataARB(GL_ARRAY_BUFFER_ARB, 3 * 4 * m_NumVertex * sizeof(float), NULL, GL_STREAM_DRAW_ARB);
float *vertexPtr = (float*)glMapBufferARB(GL_ARRAY_BUFFER_ARB, GL_WRITE_ONLY_ARB);
assert(vertexPtr);
for(size_t i = 0, count = 0; count < len; count++)
{
SmokeParticle &prt = particleStore[ toDraw[count].index ];
Point3f &p = toDraw[count].transP;
float w = prt.w / 0.5f;
float h = prt.h / 1.0f;
vertexPtr[i++] = p.x - w; vertexPtr[i++] = p.y - h; vertexPtr[i++] = p.z;
vertexPtr[i++] = p.x + w; vertexPtr[i++] = p.y - h; vertexPtr[i++] = p.z;
vertexPtr[i++] = p.x + w; vertexPtr[i++] = p.y + h; vertexPtr[i++] = p.z;
vertexPtr[i++] = p.x - w; vertexPtr[i++] = p.y + h; vertexPtr[i++] = p.z;
}
glUnmapBufferARB(GL_ARRAY_BUFFER_ARB);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, colorBuffer);
glBufferDataARB(GL_ARRAY_BUFFER_ARB, 4 * 4 * m_NumVertex * sizeof(float), NULL, GL_STREAM_DRAW_ARB);
float *colorPtr = (float*)glMapBufferARB(GL_ARRAY_BUFFER_ARB, GL_WRITE_ONLY_ARB);
assert(colorBuffer);
for(size_t i = 0, count = 0; count < len; count++)
{
SmokeParticle &prt = particleStore[ toDraw[count].index ];
// r g b a
colorPtr[i++] = prt.r; colorPtr[i++] = prt.g; colorPtr[i++] = prt.b; colorPtr[i++] = prt.alpha;
colorPtr[i++] = prt.r; colorPtr[i++] = prt.g; colorPtr[i++] = prt.b; colorPtr[i++] = prt.alpha;
colorPtr[i++] = prt.r; colorPtr[i++] = prt.g; colorPtr[i++] = prt.b; colorPtr[i++] = prt.alpha;
colorPtr[i++] = prt.r; colorPtr[i++] = prt.g; colorPtr[i++] = prt.b; colorPtr[i++] = prt.alpha;
}
glUnmapBufferARB(GL_ARRAY_BUFFER_ARB);
// Draws buffered data
glBindBufferARB(GL_ARRAY_BUFFER_ARB, vertexBuffer);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, 0);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, colorBuffer);
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(4, GL_FLOAT, 0, 0);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, texCoordBuffer);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, 0, 0);
glDrawArrays(GL_QUADS, 0, (GLsizei)len *4);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
#else
{..}
glPopMatrix();
}
void CETSmokeRenderer::Render()
{
//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Renders depth information
if(useSoftParticles)
{
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);
glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, GL_FALSE);
glClampColorARB(GL_CLAMP_FRAGMENT_COLOR_ARB, GL_FALSE);
glClampColorARB(GL_CLAMP_READ_COLOR_ARB, GL_FALSE);
glClearColor(FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX);
glClear(GL_COLOR_BUFFER_BIT);;
glUseProgramObjectARB(0);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
glClampColorARB(GL_CLAMP_VERTEX_COLOR_ARB, GL_TRUE);
glClampColorARB(GL_CLAMP_FRAGMENT_COLOR_ARB, GL_TRUE);
glClampColorARB(GL_CLAMP_READ_COLOR_ARB, GL_TRUE);
glBindTexture(GL_TEXTURE_2D, 0);
// renders the soft particles
glUseProgramObjectARB(particleShader);
// Sets texture data
GLint texloc = glGetUniformLocationARB(particleShader, "tex");
GLint depthTexloc = glGetUniformLocationARB(particleShader, "depthInfo");
GLint powerloc = glGetUniformLocationARB(particleShader, "power");
glUniform1fARB(powerloc, (float)softParticlePower);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, TextureID());
glUniform1iARB(texloc, 0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, depthTex);
glUniform1iARB(depthTexloc, 1);
Draw(m_pCamera, false);
// Unbinds shader and textures
glBindTexture(GL_TEXTURE_2D, 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, 0);
glUseProgramObjectARB(0);
}
else
{
glUseProgramObjectARB(particleShader);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, TextureID());
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, depthTex);
Draw(m_pCamera, true);
glBindTexture(GL_TEXTURE_2D, 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, 0);
glUseProgramObjectARB(0);
}
}
One way of achieving what you are looking for is to utilise point sprites, I have attached some code below that illustrates this in a simple way, hope this helps:
main.cpp
/*
Simple point-sprite particle demo - renders particles using spheres
Requirements:
GLM maths library
Freeglut
*/
#include <gl/glew.h>
#include <gl/freeglut.h>
#include <iostream>
#include "GLSLShader.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_projection.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <cassert>
#define GL_CHECK_ERRORS assert(glGetError()== GL_NO_ERROR)
using namespace std;
class Screen
{
public:
int width, height;
string title;
unsigned int displayFlags, contextFlags;
Screen(string ititle, int iwidth = 1024, int iheight = 768){
Screen(ititle, (GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA), (GLUT_CORE_PROFILE | GLUT_DEBUG), iwidth, iheight)
}
Screen(string ititle, unsigned int disFlags, unsigned int contFlags, int iwidth = 1024, int iheight = 768){
title = ititle; width = iwidth; height = iheight;
displayFlags = disFlags;
contextFlags = contFlags;
}
};
const int TOTAL= 9;
GLfloat positions[3*TOTAL]={-1,0,-1, 0,0,-1, 1,0,-1,-1,0, 0, 0,0, 0, 1,0, 0,-1,0, 1, 0,0, 1, 1,0,1};
GLuint vboID, vaoID;
GLsizei stride = sizeof(GLfloat)*3;
GLSLShader shader;
int filling=1;
// Absolute rotation values (0-359 degrees) and rotiation increments for each frame
float rotation_x=0, rotation_x_increment=0.1f;
float rotation_y=0, rotation_y_increment=0.05f;
float rotation_z=0, rotation_z_increment=0.03f;
glm::mat4 P; //projection matrix;
bool bRotate=true;
void InitShaders(void)
{
shader.LoadFromFile(GL_VERTEX_SHADER, "shader.vert");
shader.LoadFromFile(GL_FRAGMENT_SHADER, "shader.frag");
shader.CreateAndLinkProgram();
shader.Use();
shader.AddAttribute("vVertex");
shader.AddUniform("Color");
shader.AddUniform("lightDir");
shader.AddUniform("MVP");
glUniform3f(shader("lightDir"), 0,0,1);
glUniform3f(shader("Color"),1,0,0);
shader.UnUse();
GL_CHECK_ERRORS;
}
void InitVAO() {
GL_CHECK_ERRORS;
//Create vao and vbo stuff
glGenVertexArrays(1, &vaoID);
glGenBuffers (1, &vboID);
GL_CHECK_ERRORS;
glBindVertexArray(vaoID);
glBindBuffer (GL_ARRAY_BUFFER, vboID);
glBufferData (GL_ARRAY_BUFFER, sizeof(positions), &positions[0], GL_STATIC_DRAW);
GL_CHECK_ERRORS;
glEnableVertexAttribArray(shader["vVertex"]);
glVertexAttribPointer (shader["vVertex"], 3, GL_FLOAT, GL_FALSE,stride,0);
glBindVertexArray(0);
GL_CHECK_ERRORS;
}
void SetupGLBase() {
glGetError();
GL_CHECK_ERRORS;
glClearColor(0.0f,0.0f,0.2f,0.0f);
GL_CHECK_ERRORS;
InitShaders();
InitVAO();
glEnable(GL_DEPTH_TEST); // We enable the depth test (also called z buffer)
GL_CHECK_ERRORS;
glPointSize(50);
}
void OnRender() {
GL_CHECK_ERRORS;
glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);
//setup matrices
glm::mat4 T = glm::translate(glm::mat4(1.0f),glm::vec3(0.0f, 0.0f, -5));
glm::mat4 Rx = glm::rotate(T, rotation_x, glm::vec3(1.0f, 0.0f, 0.0f));
glm::mat4 Ry = glm::rotate(Rx, rotation_y, glm::vec3(0.0f, 1.0f, 0.0f));
glm::mat4 MV = glm::rotate(Ry, rotation_z, glm::vec3(0.0f, 0.0f, 1.0f));
glm::mat4 MVP = P*MV;
//draw the points
shader.Use();
glUniformMatrix4fv(shader("MVP"), 1, GL_FALSE, glm::value_ptr(MVP));
glBindVertexArray(vaoID);
glDrawArrays(GL_POINTS, 0, TOTAL);
glBindVertexArray(0);
shader.UnUse();
glutSwapBuffers();
}
void OnResize(int w, int h)
{
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
//setup the projection matrix
P = glm::perspective(45.0f, (GLfloat)w/h, 1.f, 1000.f);
}
void OnShutdown() {
glDeleteBuffers(1, &vboID);
glDeleteVertexArrays(1, &vaoID);
}
void OnKey(unsigned char key, int x, int y)
{
switch (key)
{
case ' ': bRotate=!bRotate; break;
case 'r': case 'R':
if (filling==0)
{
glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); // Filled Polygon Mode
filling=1;
}
else
{
glPolygonMode (GL_FRONT_AND_BACK, GL_LINE); // Outline Polygon Mode
filling=0;
}
break;
}
}
void OnSpecialKey(int key, int x, int y)
{
switch (key)
{
case GLUT_KEY_UP: rotation_x_increment = rotation_x_increment +0.005f; break;
case GLUT_KEY_DOWN: rotation_x_increment = rotation_x_increment -0.005f; break;
case GLUT_KEY_LEFT: rotation_y_increment = rotation_y_increment +0.005f; break;
case GLUT_KEY_RIGHT: rotation_y_increment = rotation_y_increment -0.005f; break;
}
}
void OnIdle() {
if(bRotate) {
rotation_x = rotation_x + rotation_x_increment;
rotation_y = rotation_y + rotation_y_increment;
rotation_z = rotation_z + rotation_z_increment;
}
if (rotation_x > 359) rotation_x = 0;
if (rotation_y > 359) rotation_y = 0;
if (rotation_z > 359) rotation_z = 0;
glutPostRedisplay();
}
void glTestAndInfo(GLEnum glewInitResponse)
{
if (GLEW_OK != glewInitResponse) {
cerr<<"Error: "<<glewGetErrorString(glewInitResponse)<<endl;
} else {
if (GLEW_VERSION_3_3)
{
cout<<"Driver supports OpenGL 3.3 or greater.\nDetails:"<<endl;
}
}
cout<<"Using GLEW "<<glewGetString(GLEW_VERSION)<<endl;
cout<<"Vendor: "<<glGetString (GL_VENDOR)<<endl;
cout<<"Renderer: "<<glGetString (GL_RENDERER)<<endl;
cout<<"Version: "<<glGetString (GL_VERSION)<<endl;
cout<<"GLSL: "<<glGetString (GL_SHADING_LANGUAGE_VERSION)<<endl;
}
void main(int argc, char** argv) {
Screen *screen = news Screen("Point sprites as spheres in OpenGL 3.3");
atexit(OnShutdown);
glutInit(&argc, argv);
glutInitDisplayMode(screen->displayFlags);
glutInitContextVersion (3, 3);
glutInitContextFlags (screen->contextFlags);
glutInitWindowSize(screen->width, screen->height);
glutCreateWindow(screen->title);
glewExperimental = GL_TRUE;
glTestAndInfo(glewInit());
SetupGLBase();
glutDisplayFunc(OnRender);
glutReshapeFunc(OnResize);
glutKeyboardFunc(OnKey);
glutSpecialFunc(OnSpecialKey);
glutIdleFunc(OnIdle);
glutMainLoop();
}
GLSLShader.h
#pragma once
#ifndef GLSL_SHADER_H
#define GLSL_SHADER_H
#include <GL/glew.h>
#include <map>
#include <string>
using namespace std;
class GLSLShader
{
public:
GLSLShader(void);
~GLSLShader(void);
void LoadFromString(GLenum whichShader, const string source);
void LoadFromFile(GLenum whichShader, const string filename);
void CreateAndLinkProgram();
void Use();
void UnUse();
void AddAttribute(const string attribute);
void AddUniform(const string uniform);
GLuint operator[](const string attribute);// indexer: returns the location of the named attribute
GLuint operator()(const string uniform);
private:
enum ShaderType {VERTEX_SHADER, FRAGMENT_SHADER, GEOMETRY_SHADER};
GLuint _program;
int _totalShaders;
GLuint _shaders[3];//0 vertexshader, 1 fragmentshader, 2 geometryshader
map<string,GLuint> _attributeList;
map<string,GLuint> _uniformLocationList;
};
#endif
GLSLShader.cpp
/*
Really basic glsl shader class
*/
#include "GLSLShader.h"
#include <iostream>
#include <fstream>
// constructor
GLSLShader::GLSLShader(void)
{
_totalShaders=0;
_shaders[VERTEX_SHADER]=0;
_shaders[FRAGMENT_SHADER]=0;
_shaders[GEOMETRY_SHADER]=0;
_attributeList.clear();
_uniformLocationList.clear();
}
// destructor
GLSLShader::~GLSLShader(void)
{
_attributeList.clear();
_uniformLocationList.clear();
glDeleteProgram(_program);
}
// loader functions
void GLSLShader::LoadFromString(GLenum type, const string source) {
GLuint shader = glCreateShader (type);
const char * ptmp = source.c_str();
glShaderSource (shader, 1, &ptmp, NULL);
//check whether the shader loads fine
GLint status;
glCompileShader (shader);
glGetShaderiv (shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE) {
GLint infoLogLength;
glGetShaderiv (shader, GL_INFO_LOG_LENGTH, &infoLogLength);
GLchar *infoLog= new GLchar[infoLogLength];
glGetShaderInfoLog (shader, infoLogLength, NULL, infoLog);
cerr<<"Compile log: "<<infoLog<<endl;
delete [] infoLog;
}
_shaders[_totalShaders++]=shader;
}
void GLSLShader::LoadFromFile(GLenum whichShader, const string filename){
ifstream fp;
fp.open(filename.c_str(), ios_base::in);
if(fp) {
string line, buffer;
while(getline(fp, line)) {
buffer.append(line);
buffer.append("\r\n");
}
//copy to source
LoadFromString(whichShader, buffer);
} else {
cerr<<"Error loading shader: "<<filename<<endl;
}
}
// utilitarian functions
void GLSLShader::CreateAndLinkProgram() {
_program = glCreateProgram ();
if (_shaders[VERTEX_SHADER] != 0) {
glAttachShader (_program, _shaders[VERTEX_SHADER]);
}
if (_shaders[FRAGMENT_SHADER] != 0) {
glAttachShader (_program, _shaders[FRAGMENT_SHADER]);
}
if (_shaders[GEOMETRY_SHADER] != 0) {
glAttachShader (_program, _shaders[GEOMETRY_SHADER]);
}
//link and check whether the program links fine
GLint status;
glLinkProgram (_program);
glGetProgramiv (_program, GL_LINK_STATUS, &status);
if (status == GL_FALSE) {
GLint infoLogLength;
glGetProgramiv (_program, GL_INFO_LOG_LENGTH, &infoLogLength);
GLchar *infoLog= new GLchar[infoLogLength];
glGetProgramInfoLog (_program, infoLogLength, NULL, infoLog);
cerr<<"Link log: "<<infoLog<<endl;
delete [] infoLog;
}
glDeleteShader(_shaders[VERTEX_SHADER]);
glDeleteShader(_shaders[FRAGMENT_SHADER]);
glDeleteShader(_shaders[GEOMETRY_SHADER]);
}
void GLSLShader::Use() {
glUseProgram(_program);
}
void GLSLShader::UnUse() {
glUseProgram(0);
}
void GLSLShader::AddAttribute(const string attribute) {
_attributeList[attribute]= glGetAttribLocation(_program, attribute.c_str());
}
// indexer: returns the location of the named attribute
GLuint GLSLShader::operator [](const string attribute) {
return _attributeList[attribute];
}
void GLSLShader::AddUniform(const string uniform) {
_uniformLocationList[uniform] = glGetUniformLocation(_program, uniform.c_str());
}
GLuint GLSLShader::operator()(const string uniform){
return _uniformLocationList[uniform];
}
This code is pretty old and I have no way to test rendering here (no distinct GFX card) so if there are any issues let me know and I can fix it once at my GFX dev machine.
Addendum:
Shaders may help too (dont know how I forgot them, old age maybe catching up on me!) so here they are:
Vertex shader (shader.vert)
#version 330 // set this to whatever minimum version you want to support
in vec3 vVertex;
uniform mat4 MVP;
void main()
{
gl_Position = MVP*vec4(vVertex,1);
}
Fragment shader (shader.frag)
#version 330
out vec4 vFragColour;
uniform vec3 Colour;
uniform vec3 lightDirection;
void main(void)
{
// calculate normal from texture coordinates
vec3 N;
N.xy = gl_PointCoord* 2.0 - vec2(1.0);
float mag = dot(N.xy, N.xy);
if (mag > 1.0) discard; // kill pixels outside the circle we want
N.z = sqrt(1.0-mag); // this might be expensive depending on your hardware
float diffuse = max(0.0, dot(lightDirection, N)); // calculate lighting
vFragColour = vec4(Colour,1) * diffuse;
}
Addendum 2:
To add the freeglut libraries to your build and resolve LNK 1104 errors simply go to *Project >> Properties >> VC++ Directories* and add the directories where your freeglut includes, source libraries and dlls are stored, for example for lib files go to
Add the folders as follows:
DLL Directories: add to Executable Directories
.h file Directories(include folder): add to Include Directories
.cpp file Directories: add to Source Directories
.lib file Directories: add to Library Directories
Hope this helps:)

OpenGL Texture Sampling not working

I'm using VC++10 + OpenGL + the Assimp Library to consume and then render some 3D models.
The code is rendering the positions correctly, but for some reason the textures are seriously bugged. My texcoords appear to be loading correctly as are the texture files themselves - however I can't help but feel that the issue must be located with the loaded textures themselves.
www.flickr.com/photos/95269725#N02/8685913640/in/photostream
{ i seem to have a lack of rep to post inline images }
********** EDIT1 : ***********
So, I've been using the awesome GDebugger application to debug and interrogate the OpenGL pipeline in realtime. 2 things stand out really :
1. The biggy here is that the loaded texture is meant to look like this ->
http://www.flickr.com/photos/95269725#N02/8688860034/in/photostream
but actually looks like this when loaded into OpenGL memory :
http://www.flickr.com/photos/95269725#N02/8688860042/in/photostream/
2. Not sure if this is still applicable(as discussed in the comments), however the GL_TEXTURE_2D state variable is always FALSE throughout the game loop.
So I'm going to have to play with the texture loading code to see if I can get any traction there and post another update.
A few big relevant code chunks{sorry!} :
* Vertex Shader *
#version 420
layout(location = 0) in vec3 position;
layout(location = 1) in vec3 normal;
layout(location = 2) in vec2 texCoord;
uniform mat4 cameraToClipMatrix;
uniform mat4 modelToCameraMatrix;
out vec2 oTexCoord;
out vec4 oNormal;
void main()
{
oTexCoord = texCoord;
vec4 cameraPos = modelToCameraMatrix * vec4(position,1.0);
gl_Position = cameraToClipMatrix * cameraPos;
oNormal = normalize(vec4(modelToCameraMatrix * vec4(normal,0.0)));
}
* Fragment Shader *
#version 420
in vec4 Normal;
in vec2 TexCoord;
layout (location = 0) out vec4 FragColor;
uniform sampler2D gSampler;
void main()
{
FragColor = texture(gSampler, TexCoord);
//FragColor = vec4(1.1, 0.0, 1.1, 1.0);
}
* GL Init etc *
void GLSystem::init() {
InitializeProgram();
glClearColor(0.75f, 0.75f, 1.0f, 1.0f);
glFrontFace(GL_CCW);
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glDepthFunc(GL_LEQUAL);
glDepthRange(0.0f, 1.0f);
}
void GLSystem::InitializeProgram()
{
std::vector<GLuint> shaderList;
shaderList.push_back(LoadShader(GL_VERTEX_SHADER, "VertShader1.vert"));
shaderList.push_back(LoadShader(GL_FRAGMENT_SHADER, "FragShader1.frag"));
theProgram = CreateProgram(shaderList);
modelToCameraMatrixUnif = glGetUniformLocation(theProgram, "modelToCameraMatrix"); // view matrix
cameraToClipMatrixUnif = glGetUniformLocation(theProgram, "cameraToClipMatrix"); // projection matrix
m_samplerUnif = glGetUniformLocation(theProgram, "gSampler"); // grab the gSampler uniform location reference in the fragment shader
float fzNear = 1.0f; float fzFar = 45.0f;
cameraToClipMatrix[0].x = fFrustumScale;
cameraToClipMatrix[1].y = fFrustumScale;
cameraToClipMatrix[2].z = (fzFar + fzNear) / (fzNear - fzFar);
cameraToClipMatrix[2].w = -1.0f;
cameraToClipMatrix[3].z = (2 * fzFar * fzNear) / (fzNear - fzFar);
glUseProgram(theProgram);
glUniformMatrix4fv(cameraToClipMatrixUnif, 1, GL_FALSE, glm::value_ptr(cameraToClipMatrix));
glUseProgram(0);
}
* Texture Loading *
bool CTexture::Load() {
m_texObj = 0; // init to zero
std::auto_ptr<glimg::ImageSet> pImgSet;
try {
pImgSet.reset( glimg::loaders::stb::LoadFromFile(m_filename) );
m_texObj = glimg::CreateTexture( &(*pImgSet), 0); // generates a texture and returns the related texture id
//glimg::SingleImage image = pImgSet->GetImage(0, 0, 0);
//glimg::Dimensions dims = image.GetDimensions();
//GLuint targetTexType = glimg::GetTextureType( &(*pImgSet), 0); // not using this yet - but potentially might need to base this objects targetType on this interpreted value.
//glimg::OpenGLPixelTransferParams params = GetUploadFormatType(image.GetFormat(), 0);
//glPixelStorei(GL_UNPACK_ALIGNMENT, image.GetFormat().LineAlign());
//glGenTextures(1, &m_texObj);
//glActiveTexture(GL_TEXTURE0);
//glBindTexture(GL_TEXTURE_2D, m_texObj);
//glTexImage2D(m_targetType, 0, glimg::GetInternalFormat(image.GetFormat(), 0), dims.width, dims.height, 0, params.format, params.type, image.GetImageData());
//glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB8, dims.width, dims.height, 0, GL_RGB, GL_UNSIGNED_BYTE, image.GetImageData() );
/*glTexParameterf(m_targetType, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(m_targetType, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(m_targetType, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(m_targetType, GL_TEXTURE_WRAP_T, GL_REPEAT);*/
}
catch(glimg::loaders::stb::StbLoaderException &e) {
std::cout << "Warning : " << e.what() << " || .Image file loading failed for file : '" << m_filename << std::endl;
return false;
}
glBindTexture(m_targetType, 0); // Bind to default texture
return true;
}
* Mesh Loading *
#include "MeshModel.h"
// ----------------------------------------------------------------------------------------
#include "Texture.h"
#include "GLSystem.h"
#include "Game.h"
// ----------------------------------------------------------------------------------------
#include <assert.h>
// ----------------------------------------------------------------------------------------
MeshItem::MeshItem() {
}
MeshItem::MeshItem(MeshModel& p_meshModel) {
m_pmeshModel = &p_meshModel;
p_delete_object_data = true;
VBO = INVALID_OGL_VALUE;
IBO = INVALID_OGL_VALUE;
NBO = INVALID_OGL_VALUE;
TBO = INVALID_OGL_VALUE;
NumVertices = 0;
NumFaces = 0;
NumIndices = 0;
MaterialIndex = INVALID_MATERIAL;
};
MeshItem::~MeshItem() {
if (VBO != INVALID_OGL_VALUE) {
glDeleteBuffers(1, &VBO);
}
if (IBO != INVALID_OGL_VALUE) {
glDeleteBuffers(1, &IBO);
}
if (NBO != INVALID_OGL_VALUE) {
glDeleteBuffers(1, &NBO);
}
if (TBO != INVALID_OGL_VALUE) {
glDeleteBuffers(1, &TBO);
}
}
void MeshItem::BuildVBO() {
glGenVertexArrays(1, &VAO); /* Generate a vertex array object - container for all vertex attribute arrays */
glBindVertexArray(VAO); /* Bind this VAO as the current Vertex Attribute Array container [ Holds the state for all attributes i.e. not the Vertex and Index data ] */
// Positions
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * NumVertices * 3, &Positions[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); // Positions
// Indices
glGenBuffers(1, &IBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * NumFaces * 3, &Indices[0], GL_STATIC_DRAW);
// Normals
glGenBuffers(1, &NBO);
glBindBuffer(GL_ARRAY_BUFFER, NBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * NumVertices * 3, &Normals[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0); // Normals
// TexCoords
glGenBuffers(1, &TBO);
glBindBuffer(GL_ARRAY_BUFFER, TBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * NumVertices * 2, &TexCoords[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, 0); // TexCoords
glBindVertexArray(0); // Unbind the VAO
glBindBuffer(GL_ARRAY_BUFFER,0); // Unbind the vertices array buffer
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // Unbind the indices array buffer
// Our copy of the data is no longer necessary, it is safe in the graphics card memory
if(p_delete_object_data) {
Positions.erase( Positions.begin(), Positions.end() );
Indices.erase( Indices.begin(), Indices.end() );
Normals.erase( Normals.begin(), Normals.end() );
TexCoords.erase( TexCoords.begin(), TexCoords.end() );
}
}
// ********************* MESHMODEL *********************
MeshModel::MeshModel(GLSystem& p_gls)
: m_pgls(&p_gls)
{
m_texUnit = 0;
m_samplerObj = 0;
}
MeshModel::~MeshModel() {
Clear();
}
GLSystem& MeshModel::getGLSystem() {
return *m_pgls;
}
void MeshModel::Clear() {
//for (unsigned int i = 0 ; i < m_textures.size() ; i++) {
// m_textures[i]);
//}
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
}
bool MeshModel::LoadMesh(const std::string& p_filename) {
Clear(); // Release the previously loaded mesh (if it exists)
bool Ret = false;
Assimp::Importer Importer;
const aiScene* pScene = Importer.ReadFile(p_filename.c_str(), aiProcess_Triangulate | aiProcess_GenSmoothNormals /* | aiProcess_FlipWindingOrder*/ /* | aiProcess_FlipUVs*/ | aiProcess_ValidateDataStructure);
//const aiScene* pScene = aiImportFile(p_filename.c_str(), aiProcessPreset_TargetRealtime_MaxQuality);
if (pScene) {
printf("3D Object File '%s' loaded successfully.\n", p_filename.c_str() );
Ret = InitFromScene(pScene, p_filename);
}
else {
printf("Error parsing '%s': '%s'.\n", p_filename.c_str(), Importer.GetErrorString());
}
return Ret;
}
bool MeshModel::InitFromScene(const aiScene* pScene, const std::string& p_filename) {
//m_meshItems.resize(pScene->mNumMeshes);
m_textures.resize(pScene->mNumMaterials);
InitMaterials(pScene, p_filename); // load materials/textures etc
// Initialize the meshes in the scene one by one
for (unsigned int i = 0 ; i < pScene->mNumMeshes ; i++) {
const aiMesh* paiMesh = pScene->mMeshes[i];
MeshItem mItem(*this);
InitMesh(mItem, paiMesh);
mItem.BuildVBO();
m_meshItems.push_back(mItem);
}
return true;
}
void MeshModel::InitMesh(MeshItem& p_meshItem, const aiMesh* p_paiMesh) {
p_meshItem.MaterialIndex = p_paiMesh->mMaterialIndex;
// Indices
p_meshItem.NumFaces = p_paiMesh->mNumFaces;
p_meshItem.NumIndices = p_meshItem.NumFaces * 3;
p_meshItem.Indices.resize(p_meshItem.NumIndices);
for (unsigned int i = 0 ; i < p_paiMesh->mNumFaces ; ++i) {
const aiFace& face = p_paiMesh->mFaces[i];
assert(face.mNumIndices == 3);
p_meshItem.Indices[i*3+0] = face.mIndices[0];
p_meshItem.Indices[i*3+1] = face.mIndices[1];
p_meshItem.Indices[i*3+2] = face.mIndices[2];
}
p_meshItem.NumVertices = p_paiMesh->mNumVertices;
p_meshItem.Positions.resize(p_meshItem.NumVertices * 3);
p_meshItem.Normals.resize(p_meshItem.NumVertices * 3);
p_meshItem.TexCoords.resize(p_meshItem.NumVertices * 2);
for (unsigned int i = 0 ; i < p_paiMesh->mNumVertices ; ++i) {
// Positions
if( p_paiMesh->HasPositions() ) {
p_meshItem.Positions[i*3+0] = p_paiMesh->mVertices[i].x;
p_meshItem.Positions[i*3+1] = p_paiMesh->mVertices[i].y;
p_meshItem.Positions[i*3+2] = p_paiMesh->mVertices[i].z;
}
// Normals
if( p_paiMesh->HasNormals() ) {
p_meshItem.Normals[i*3+0] = p_paiMesh->mNormals[i].x;
p_meshItem.Normals[i*3+1] = p_paiMesh->mNormals[i].y;
p_meshItem.Normals[i*3+2] = p_paiMesh->mNormals[i].z;
}
// TexCoords
if( p_paiMesh->HasTextureCoords(0) ) {
p_meshItem.TexCoords[i*2+0] = p_paiMesh->mTextureCoords[0][i].x;
p_meshItem.TexCoords[i*2+1] = p_paiMesh->mTextureCoords[0][i].y;
}
}
}
bool MeshModel::InitMaterials(const aiScene* pScene, const std::string& p_filename) {
// Extract the directory part from the file name
std::string::size_type SlashIndex = p_filename.find_last_of("/");
std::string Dir;
if (SlashIndex == std::string::npos) {
Dir = ".";
}
else if (SlashIndex == 0) {
Dir = "/";
}
else {
Dir = p_filename.substr(0, SlashIndex);
}
bool Ret = true;
// Initialize the materials
for (unsigned int i = 0 ; i < pScene->mNumMaterials ; i++) {
const aiMaterial* pMaterial = pScene->mMaterials[i];
m_textures[i] = NULL;
std::string FullPath = "";
if (pMaterial->GetTextureCount(aiTextureType_DIFFUSE) > 0) {
aiString Path;
if (pMaterial->GetTexture(aiTextureType_DIFFUSE, 0, &Path, NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS) {
FullPath = Dir + "/" + Path.data;
m_textures[i] = std::make_shared<CTexture>( GL_TEXTURE_2D, FullPath.c_str() );
if ( !m_textures[i]->Load() ) {
printf("Error loading texture '%s'.\n", FullPath.c_str());
m_textures[i].reset();
m_textures[i] = NULL;
Ret = false;
}
else {
printf("Texture File '%s' loaded successfully\n", FullPath.c_str());
}
}
}
// Load a white texture in case the model does not include its own texture
if (!m_textures[i]) {
m_textures[i] = std::make_shared<CTexture>( GL_TEXTURE_2D, "..//Data/Textures/white.png");
printf("A default Texture File was loaded for '%s'.\n", FullPath.c_str());
Ret = m_textures[i]->Load();
}
}
// Genertate a Sampler object
glGenSamplers(1, &m_samplerObj);
glSamplerParameteri(m_samplerObj, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glSamplerParameteri(m_samplerObj, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glSamplerParameteri(m_samplerObj, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glSamplerParameteri(m_samplerObj, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
return Ret;
}
void MeshModel::DrawMesh() {
for (unsigned int i = 0 ; i < m_meshItems.size() ; i++) {
glUseProgram( getGLSystem().getProgram() ); // Bind to our selected shader program
glBindVertexArray(m_meshItems[i].VAO);
const unsigned int MaterialIndex = m_meshItems[i].MaterialIndex;
// If textures exist then bind them to samplers etc
if (MaterialIndex < m_textures.size() && m_textures[MaterialIndex]) {
glUniform1i(m_pgls->m_samplerUnif, 0);
glActiveTexture(GL_TEXTURE0 + 0);
glBindTexture(GL_TEXTURE_2D, m_textures[MaterialIndex]->m_texObj);
glBindSampler(0, m_samplerObj);
} else {
printf("MeshItem has no material!");
}
// RTS
glutil::MatrixStack currMatrix;
currMatrix.Translate(glm::vec3(0.0f, -3.0f, -10.0f));
currMatrix.Scale(0.1f, 0.1f, 0.1f);
currMatrix.RotateX(-90);
float a = Game::m_tick.asSeconds() /10;
float fAngRad = m_pgls->ComputeAngleRad(a, 2.0);
float fCos = cosf(fAngRad);
float fSin = sinf(fAngRad);
glm::mat3 theMat(1.0f);
theMat[0].x = fCos; theMat[1].x = -fSin;
theMat[0].y = fSin; theMat[1].y = fCos;
currMatrix.ApplyMatrix(glm::mat4(theMat));
glUniformMatrix4fv(m_pgls->modelToCameraMatrixUnif, 1, GL_FALSE, glm::value_ptr(currMatrix.Top()));
glDrawElements(GL_TRIANGLES, m_meshItems[i].NumIndices, GL_UNSIGNED_INT, 0);
glBindVertexArray(0); // Unbind the VAO
glUseProgram(0); // Close the link to the bound shader programs
}
}
I notice your vertex shader declares:
out vec2 oTexCoord;
but your fragment shader declares:
in vec2 TexCoord;
This might leave your texture coordinates undefined.
I think you need to enable textures with glEnable(GL_TEXTURES_2D) in your init section. I get the same look by commenting out that line from my project. Here's the code, if that helps:
EnableGraphics::EnableGraphics()
{
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glOrtho(-1.0, 1.0, -1.0, 1.0, 0.0, 1.0);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // typical alpha transparency
glEnable(GL_TEXTURE_2D);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
}
EDIT:
In case your link dies, I should add that your screenshot shows a 3D model with no textures or shading, although it has colors.

VBO doesn't use UV coordinates

My render method currently looks like this:
void Renderer::render() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
checkGlError("glClear");
EntityCamera* camera = (EntityCamera*) resourceManager_->getResource(GHOST_CAMERA);
mat4 proj;
Matrix::projection3D(proj, 45.0f,
(float) nScreenWidth_ / nScreenHeight_, GHOST_NEAR_DISTANCE, GHOST_FAR_DISTANCE);
mat4 view;
Matrix::multiply(proj, camera_->getMatrix(), view);
camera->extractPlanes(view);
for (vector<Node*>::const_iterator it = renderArray_.begin(); it != renderArray_.end();
it++) {
Node* node = *it;
if (!node->isRenderable()) {
continue;
}
if (node->hasBV() && node->getBV()->isInFrustum(camera, node) == BoundingVolume::OUTSIDE) {
LOGI("Node %s is outside :O", node->getName().c_str());
continue;
}
EntityModel* entity =
static_cast<EntityModel*>(resourceManager_->getResource(
(*it)->getEntity()));
if (entity == 0 || entity->getVertices() == 0 || entity->getVertices()->size() == 0) {
LOGI("Empty entity %s.", node->getName().c_str());
continue;
}
Resource* resource = resourceManager_->getResource(node->getShader());
Shader* shader = static_cast<Shader*>(resource);
Resource* resource2 = resourceManager_->getResource(entity->getTexture());
Image* image = static_cast<Image*>(resource2);
mat4 res;
Matrix::multiply(view, node->getMatrix(), res);
// Select shader program to use.
glUseProgram(shader->getId());
checkGlError("glUseProgram");
int matrix = glGetUniformLocation(shader->getId(), "uWVP");
int texture = glGetUniformLocation(shader->getId(), "texture_0");
checkGlError("glGetUniformLocation");
int textureCoords = glGetAttribLocation(shader->getId(), "attrTexCoords");
int vertices = glGetAttribLocation(shader->getId(), "attrPos");
checkGlError("glGetAttribLocation");
// Specify WVP matrix.
glUniformMatrix4fv(matrix, 1, false, res);
checkGlError("glUniformMatrix4fv");
// Load vertex positions.
if (!entity->isCompiled()) {
//LOGI("Entity %s, not compiled.", entity->getName().c_str());
continue;
}
glEnableVertexAttribArray(vertices);
checkGlError("glEnableVertexAttribArray");
//glVertexAttribPointer(vertices, 3, GL_FLOAT, GL_FALSE, 0,
// &(*entity->getVertices())[0]);
//LOGI("%s vbo id: %d", node->getName().c_str(), entity->getVBO());
glBindBuffer(GL_ARRAY_BUFFER, entity->getVBO());
checkGlError("glBindBuffer");
glVertexAttribPointer(vertices, 3, GL_FLOAT, GL_FALSE, 0, 0);
checkGlError("glVertexAttribPointer");
// Load UV coordinates.
glEnableVertexAttribArray(textureCoords);
checkGlError("glEnableVertexAttribArray");
glVertexAttribPointer(textureCoords, 2, GL_FLOAT, GL_FALSE, 0,
&(*entity->getTextureCoords())[0]);
checkGlError("glVertexAttribPointer");
// Bind the texture.
glActiveTexture(GL_TEXTURE0);
checkGlError("glActiveTexture");
glBindTexture(GL_TEXTURE_2D, image->getId());
checkGlError("glBindTexture");
glUniform1i(texture, 0);
checkGlError("glUniform1i");
if (entity->hasIndices()) {
vector<vector<GLushort>*>* indices = entity->getIndices();
for (unsigned int i = 0; i < indices->size(); i++) {
if (entity->hasBoundingVolumes()) {
BoundingVolume* volume = (*entity->getBoundingVolumes())[i];
if (volume->isInFrustum(camera, node) == BoundingVolume::OUTSIDE) {
continue;
}
}
vector<GLushort>* ind = (*indices)[i];
glDrawElements(GL_TRIANGLES, ind->size(), GL_UNSIGNED_SHORT, &(*ind)[0]);
checkGlError("glDrawElements");
}
}
else {
glDrawArrays(GL_TRIANGLES, 0, entity->getVertices()->size() / 3);
checkGlError("glDrawArrays");
}
glBindBuffer(GL_ARRAY_BUFFER, 0);
checkGlError("glBindBuffer");
}
}
I just recently tried to use VBO, before I was sending vertex data directly and everything worked fine, textures were mapped correctly. Now I changed vertex array with VBO and even though it works, no textures are applied, I could only see black object.
What might be wrong with my textures?
Why when I change glVertexAttribPointer(vertices, 3, GL_FLOAT, GL_FALSE, 0, 0); line order with glBindBuffer(GL_ARRAY_BUFFER, entity->getVBO()); I get disfigured objects? Is this the right call order that I'm using?
You're sending your UV coordinates from plain memory, while you seem to send your vertex coordinates from a VBO. This may not be so efficient, you should have both data sets in VBO to profit of the VBO advantages.
That being said, I think your problem is that you don't unbind your VBO before sending your UV coordinates. Your code should be :
glBindBuffer(GL_ARRAY_BUFFER, 0);
glVertexAttribPointer(textureCoords, 2, GL_FLOAT, GL_FALSE, 0,
&(*entity->getTextureCoords())[0]);
as I suppose your getTextureCoords() does not return an offset in your VBO.