I exported the Blender Box as a Collada file, I am loading it with Assimp, yet it does not draw properly.
Here is how it looks:
I have tried using .fbx and .obj without success.
is this an error in my code, or is the vertex data not correct?
I checked the normals, they all point in the proper direction,
whats leads me to believe that the orientation of the faces is correct.
Here is my Code:
#include<assimp/Importer.hpp>
#include<assimp/postprocess.h>
#include<assimp/scene.h>
#include<vector>
#include<iostream>
#include<GL/glew.h>
#include<glm/glm.hpp>
#include<glm/gtx/quaternion.hpp>
#include<glm/gtc/quaternion.hpp>
#include<glm/gtc/matrix_transform.hpp>
#include<SFML/Window.hpp>
#include<SFML/OpenGL.hpp>
#include<SFML/Graphics.hpp>
#include"Shader.h"
#include"vertex.h"
#include"Cam.h"
#include"obj.h"
int main() {
glewExperimental = GL_TRUE;
if (!glewInit()) {
std::cout << "Glew Failed to initialize" << std::endl;
return -5;
}
glEnable(GL_DEPTH_TEST);
////////////////////////////// WINDOW SHADER CAMERA ///////////////////////////
sf::Window window(sf::VideoMode(800, 600), "OpenGL");
window.setActive(true);
Shader Shader1("vss_min.glsl", "fss_min.glsl");
Cam camera(window);
glm::mat4 modelMatrix(1.0);
modelMatrix = glm::scale(modelMatrix, glm::vec3(0.2, 0.2f, 0.2f));
///////////////////////////// MESH /////////////////////////////////////////
std::vector<vertex> vertices;
std::vector<std::uint32_t> indices;
Assimp::Importer importer;
const aiScene* s = importer.ReadFile("c:/meshes/ext/buntekiste.fbx",aiProcess_Debone);
aiMesh* mesh = s->mMeshes[0];
for (std::uint32_t it = 0; it < mesh->mNumVertices;it++) {
vertex v;
if (mesh->HasPositions())v.pos = vec3(mesh->mVertices[it]);
if (mesh->HasNormals())v.normal = vec3(mesh->mNormals[it]);
if (mesh->HasVertexColors(0))v.color = vec4(mesh->mColors[0][it]);
if (mesh->HasTextureCoords(0))v.uv = vec2(mesh->mTextureCoords[0][it]);
vertices.push_back(v);
}
for (std::uint32_t it = 0; it < mesh->mNumFaces; it++) {
indices.push_back(mesh->mFaces[it].mIndices[0]);
indices.push_back(mesh->mFaces[it].mIndices[1]);
indices.push_back(mesh->mFaces[it].mIndices[2]);
}
std::uint32_t VAO, VBO, IBO, TID;
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER,VBO);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(vertex), vertices.data(), GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 12 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 12 * sizeof(float), (void*)(3*sizeof(float)));
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 12 * sizeof(float), (void*)(6*sizeof(float)));
glEnableVertexAttribArray(2);
glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, 12 * sizeof(float), (void*)(10*sizeof(float)));
glEnableVertexAttribArray(3);
glGenBuffers(1, &IBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(std::uint32_t), indices.data(), GL_STATIC_DRAW);
/////////////////////////////// TEXTURE //////////////////////////////////////////////////////
sf::Image img;
img.loadFromFile("c:/textures/buntekiste.png");
glGenTextures(1, &TID);
glBindTexture(GL_TEXTURE_2D, TID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
if (img.getPixelsPtr()) {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img.getSize().x, img.getSize().y, 0, GL_RGBA, GL_UNSIGNED_BYTE, img.getPixelsPtr());
glGenerateMipmap(GL_TEXTURE_2D);
}
else {
std::cout << "Failed to load texture" << std::endl;
return -3;
}
////////////////////////////// MAINLOOP ///////////////////////////////////////////////////////
bool running = true;
while (running)
{
// handle events
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
// end the program
running = false;
}
else if (event.type == sf::Event::Resized)
{
// adjust the viewport when the window is resized
glViewport(0, 0, event.size.width, event.size.height);
}
}
///////////////////// DRAWSTUFF /////////////////////////////////////////
camera.update(),
glClearColor(0.3f, 0.0f, 0.8f,0.7f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glm::mat4 mvp = modelMatrix;
Shader1.set4x4("Model", modelMatrix);
Shader1.set4x4("View", camera.getView());
Shader1.set4x4("Projection", camera.getProjection());
glBindVertexArray(VAO);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, TID);
Shader1.use();
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0);
window.display();
}
return 0;
}
FragmentShader:
#version 440
out vec4 FragColor;
in vec4 vertexColor;
in vec3 FragPos;
in vec3 normal;
in vec2 uv;
uniform int textureSwitch;
uniform vec3 lightPos;
uniform sampler2D myTexture;
void main(){
FragColor = texture(myTexture,uv);
}
VertexShader:
#version 440
layout(location =0) in vec3 Pos;
layout(location =1) in vec3 Normal;
layout(location =2) in vec4 Color;
layout(location =3) in vec2 TexCoord;
uniform mat4 Model;
uniform mat4 View;
uniform mat4 Projection;
out vec4 vertexColor;
out vec3 normal;
out vec3 FragPos;
out vec2 uv;
void main(){
mat4 mvp = Projection *View*Model;
gl_Position = mvp * vec4(Pos,1.0f);
normal = Normal;
uv = TexCoord;
vertexColor = Color;
}
I had the same problem and this works for me: add glEnable(GL_DEPTH_TEST);//enable depth buffer glCullFace(GL_FRONT);//for keep front faces and glDisable(GL_CULL_FACE); - if you have enabled GL_CULL_FACE
I did call glEnable(GL_DEPTH_TEST)
before creating the OpenGL Context.
Calling it afterwards solves it.
Ahh finally:
Related
I am attempting to draw a png file using OpenGL and seem to have a problem with how I am setting up the textures.
Main.cpp:
float positions[] = {
-1.0f, -1.0f,
0.0f, 1.0f,
1.0f, 1.0f,
};
float texCoords[] = {
-1.0f, -1.0f,
-1.0f, 1.0f,
1.0f, 1.0f,
};
unsigned int buffer;
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(positions), positions, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
unsigned int texBuffer;
glGenBuffers(1, &texBuffer);
glBindBuffer(GL_ARRAY_BUFFER, texBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(texCoords), texCoords, GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
int w;
int h;
int comp;
unsigned char* image = stbi_load("res/images/background_level.png", &w, &h, &comp, STBI_rgb_alpha);
if (image == nullptr)
throw(std::string("Failed to load texture"));
//std::cout << image << std::endl;
unsigned int m_texture;
glGenTextures(1, &m_texture);
glBindTexture(GL_TEXTURE_2D, m_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
if (comp == 3)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
else if (comp == 4)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);
glBindTexture(GL_TEXTURE_2D, 0);
stbi_image_free(image);
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
/* Render here */
glClearColor(1.0, 1.0, 1.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
// draw our first triangle
glUseProgram(programID);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, 0);
int uniformLoc = glGetUniformLocation(programID, "tex");
glUniform1i(uniformLoc, 0);
glDrawArrays(GL_TRIANGLES, 0, 3);
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
vertex.shader:
#shader VERTEX
#version 330 core
layout (location=0) in vec2 vert;
layout (location=1) in vec2 vertTexCoord;
out vec2 fragTexCoord;
void main() {
// Pass the tex coord straight through to the fragment shader
fragTexCoord = vertTexCoord;
gl_Position = vec4(vert, 0, 1);
}
fragment.shader:
#shader FRAGMENT
#version 330 core
uniform sampler2D tex; //this is the texture
in vec2 fragTexCoord; //this is the texture coord
out vec4 finalColor; //this is the output color of the pixel
void main() {
//finalColor = vec4(1.0, 1.0, 1.0, 1.0);
finalColor = texture(tex, fragTexCoord);
}
If I swap the line commented out in the fragment shader, I get an all white triangle rendered. However with the line attempting to use the texture, the triangle comes out all black. I am just beginning with OpenGL so I don't necessarily have all of the beginning concepts down pat. Textures may be ahead of my skill level but I figured it couldn't hurt to try and ask here as someone may be able to show me where I have things confused.
You are calling glBindTexture(GL_TEXTURE_2D, 0) instead of glBindTexture(GL_TEXTURE_2D, m_texture) inside the renderloop. With this command, a texture is bound to the currently active texture unit.
I tried to load the same model(modeled in 3Ds max) in opengl, but with different textures. The problem is, that when I try to bind the Texture with glBindTexture after I have acitvated the texture, then it disappears. Before I changed the textures in 3Ds max, it always has show me the model in black color (just in opengl). But I haven´t even assign black color to my model. My image "model-image.png" also contains all textures, that I have assign to my object. So am I missing something?
Thanks for your help in advance.
void initDrawing()
{
glEnable(GL_DEPTH_TEST);
program = glCreateProgram();
std::string shaderV = Utilities::loadFile("shader.vert");
std::string shaderF = Utilities::loadFile("shader.frag");
program = Utilities::compileShader(shaderV, shaderF);
Utilities::loadObj("model.obj", obj);
Utilities::loadPNG("model-image.png", diffuse);
glEnable(GL_TEXTURE_2D);
glGenVertexArrays(1, &vertexArrayObject);
glBindVertexArray(vertexArrayObject);
glGenBuffers(1, &vPosition);
glBindBuffer(GL_ARRAY_BUFFER, vPosition);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec4)*obj.vertices.size(), &obj.vertices[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vPosition);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
GLuint vCoordinates;
glGenBuffers(1, &vCoordinates);
glBindBuffer(GL_ARRAY_BUFFER, vCoordinates);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec2)*obj.textureCoordinates.size(), &obj.textureCoordinates[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, vCoordinates);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, NULL);
glGenTextures(2, &texture);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, diffuse.width, diffuse.height, 0, GL_RGBA, GL_UNSIGNED_BYTE,
&diffuse.colors[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glUseProgram(program);
ModelView = glGetUniformLocation(program, "ModelView");
Projection = glGetUniformLocation(program, "Projection");
Diffuse = glGetUniformLocation(program, "Diffuse");
}
void display()
{
// background color
const GLfloat color[] = { 0.5, 0.5, 0.5, 1 };
glClear(GL_DEPTH_BUFFER_BIT);
glClearBufferfv(GL_COLOR, 0, color);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
modelView = view * model;
glUniformMatrix4fv(ModelView, 1, GL_FALSE, glm::value_ptr(modelView));
glUniformMatrix4fv(Projection, 1, GL_FALSE, glm::value_ptr(projection));
glUniform1i(Diffuse, 0);
glDrawArrays(GL_TRIANGLES, 0, obj.vertices.size());
glutSwapBuffers();
}
My Shader:
fragment shader:
uniform sampler2D Diffuse;
in vec2 fUV;
out vec3 color;
//main for the color
void main(void)
{
color = texture(Diffuse, fUV).rgb;
}
vertex Shader:
layout (location = 0) in vec4 vPosition;
layout (location = 2) in vec2 vCoordinates;
uniform mat4 ModelView;
uniform mat4 Projection;
out vec2 fUV;
void main(void)
{
gl_Position = Projection * ModelView * vPosition;
fUV = vCoordinates;
}
My guess is that when you say
layout(location = 2) in vec2 vCoordinates;
you really mean to say
layout(location = 1) in vec2 vCoordinates;
considering you never enable vertex attribute 2.
Beforehand, sorry for a lot of posted code. I will try to be as straightforward as possible.
My texture is 4x4 texture image in bmp format (if someone interested here it is ->). And as a result of mapping i get color of top leftpixel (0.0, 1.0) (i checked it, it is always color of top left pixel) and my triangle color results in color of that pixel, which is white.
I tried changing GL_NEARESTtoGL_LINEAR in GL_TEXTURE_MAG_FILTER
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
and i get bottom right pixel (1.0, 0.0), which is some kind of green:
I am loading texture using stb_image. So in my Texture.cpp:
Texture::Texture(const std::string& fileName)
{
int width, height, numComponents;
unsigned char* imageData = stbi_load(fileName.c_str(), &width, &height, &numComponents, 4);
if (imageData == NULL)
{
std::cerr << "Error: Texture load failed for texture: " << fileName << std::endl;
}
glEnable(GL_TEXTURE_2D);
glGenTextures(1, &_texture);
glBindTexture(GL_TEXTURE_2D, _texture);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);
stbi_image_free(imageData);
}
Texture::~Texture(void)
{
glDeleteTextures(1, &_texture);
}
void Texture::Bind(unsigned int unit)
{
assert(unit >= 0 && unit <= 31);
glActiveTexture(GL_TEXTURE0 + unit);
glBindTexture(GL_TEXTURE_2D, _texture);
}
In my vertex shader:
#version 150
in vec3 position;
in vec2 texCoord;
out vec2 texCoord0;
void main(void)
{
texCoord0 = texCoord;
gl_Position = vec4(position, 1.0);
}
In my fragment shader:
#version 150
in vec2 textCoord0;
uniform sampler2D texture;
void main(void)
{
gl_FragColor = texture2D(texture, textCoord0);
}
In my main.cpp
#include <iostream>
#include <GL/glew.h>
#include "Display.h"
#include "Shader.h"
#include "Mesh.h"
#include "Texture.h"
int main(int argc, char** argv)
{
Display display(800, 600, " ");
display.Clear(0.0f, 0.15f, 0.3f, 1.0f);
Vertex vertices[] = {
Vertex(glm::vec3(-1.0f, -1.0f, 0.0f), glm::vec2(0.0f, 0.0f)),
Vertex(glm::vec3( 0.0f, 1.0f, 0.0f), glm::vec2(0.5f, 1.0f)),
Vertex(glm::vec3( 1.0f, -1.0f, 0.0f), glm::vec2(1.0f, 0.0f))
};
Texture texture("./res/a.bmp");
Shader shader("./res/testShader");
Mesh mesh(vertices, sizeof(vertices) / sizeof(vertices[0]));
while (display.IsClosed() != true)
{
shader.Bind();
texture.Bind(0);
mesh.Draw();
display.Update();
}
return 0;
}
In Mesh.cpp i am splitting Vertices attributes (glm::vec3 _position and glm::vec2 _texture) into 2 stl vectors and using 2 buffers ("0" - for position of vertex and "1" - for texture) :
Mesh::Mesh(Vertex* vertices, unsigned int numVertices, GLenum usage)
{
_drawCount = numVertices;
glGenVertexArrays(1, &_vertexArrayObject);
glBindVertexArray(_vertexArrayObject);
std::vector<glm::vec3> positions;
std::vector<glm::vec2> texCoords;
positions.reserve(numVertices);
texCoords.reserve(numVertices);
for (unsigned int i = 0; i < numVertices; ++i)
{
positions.push_back(*vertices[i].Position());
texCoords.push_back(*vertices[i].TexCoord());
}
glGenBuffers(NUM_BUFFERS, _vertexArrayBuffers);
glBindBuffer(GL_ARRAY_BUFFER, _vertexArrayBuffers[POSITION_VB]);
glBufferData(GL_ARRAY_BUFFER, numVertices * sizeof(positions[0]), positions.data(), usage);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, _vertexArrayBuffers[TEXCOORD_VB]);
glBufferData(GL_ARRAY_BUFFER, numVertices * sizeof(texCoords[0]), texCoords.data(), usage);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);
glBindVertexArray(0);
}
Mesh::~Mesh(void)
{
glDeleteVertexArrays(1, &_vertexArrayObject);
}
void Mesh::Draw(GLenum mode)
{
glBindVertexArray(_vertexArrayObject);
glDrawArrays(mode, 0, _drawCount);
glBindVertexArray(0);
}
In Shader.cpp i binded atributes like this:
glBindAttribLocation(_program, 0, "position");
glBindAttribLocation(_program, 1, "texCoord");
----------------------------EDIT---------------------------------
After changing vertex shader to:
#version 330 core
layout (location = 0) in vec3 position;
layout (location = 1) in vec2 texCoord;
out vec2 TexCoord;
void main()
{
gl_Position = vec4(position, 1.0f);
TexCoord = texCoord;
}
and fragment shader to:
#version 330 core
in vec2 TexCoord;
out vec4 color;
uniform sampler2D ourTexture;
void main()
{
color = texture(ourTexture, TexCoord);
}
texture is mapped correctly.
But i still want to know why my first solution doesn't work.
But i still want to know why my first solution doesn't work.
Because you're using
#version 330 core
and texture2D is deprecated since version 130
The shader compiler should've warned or errored about that. Check your shader logs via glGetShaderInfoLog and glGetProgramInfoLog.
I am trying to map a texture to objects using GLSL version 330
Here is some code that my help you understanding my problem
Fragment Shader:
#version 330
layout(location = 0) in vec3 vertex;
layout(location = 1) in vec3 vertex_normal;
layout(location = 2) in vec2 texCoord;
out vec2 tCoord;
uniform mat4 modelview;
uniform mat4 projection;
void main() {
gl_Position = projection * modelview * vec4(vertex, 1.0);
tCoord = texCoord;
}
Vertex Shader
#version 330
in vec2 tCoord;
uniform sampler2D texture;
out vec4 color;
void main() {
if(tCoord == vec2(0,0))
color = vec4(1.0,0.0,0.0,1.0);
else
color = vec4(0.0,1.0,0.0,1.0);
}
Loading the Mesh and texture to OpenGL
texture coordinates will be boudn using vertexAttribPointer to position 2 (0 is position and 1 is normal)
Creating the MeshObj
void MeshObj::setData(const MeshData &meshData) {
mIndexCount = meshData.indices.size();
// TODO: extend this method to upload texture coordinates as another VBO //
// - texture coordinates are at location 2 within the shader code
// create local storage arrays for vertices, normals and indices //
unsigned int vertexDataSize = meshData.vertex_position.size();
unsigned int vertexNormalSize = meshData.vertex_normal.size();
unsigned int vertexTexcoordSize = meshData.vertex_texcoord.size();
GLfloat *vertex_position = new GLfloat[vertexDataSize]();
std::copy(meshData.vertex_position.begin(), meshData.vertex_position.end(), vertex_position);
GLfloat *vertex_normal = NULL;
if (vertexNormalSize > 0) {
vertex_normal = new GLfloat[vertexNormalSize]();
std::copy(meshData.vertex_normal.begin(), meshData.vertex_normal.end(), vertex_normal);
}
GLfloat *vertex_texcoord = NULL;
if (vertexTexcoordSize > 0) {
vertex_texcoord = new GLfloat[vertexTexcoordSize]();
std::copy(meshData.vertex_texcoord.begin(), meshData.vertex_texcoord.end(), vertex_texcoord);
}
GLuint *indices = new GLuint[mIndexCount]();
std::copy(meshData.indices.begin(), meshData.indices.end(), indices);
// create VAO //
if (mVAO == 0) {
glGenVertexArrays(1, &mVAO);
}
glBindVertexArray(mVAO);
// create and bind VBOs and upload data (one VBO per available vertex attribute -> position, normal) //
if (mVBO_position == 0) {
glGenBuffers(1, &mVBO_position);
}
glBindBuffer(GL_ARRAY_BUFFER, mVBO_position);
glBufferData(GL_ARRAY_BUFFER, vertexDataSize * sizeof(GLfloat), &vertex_position[0], GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(0);
if (vertexNormalSize > 0) {
if (mVBO_normal == 0) {
glGenBuffers(1, &mVBO_normal);
}
glBindBuffer(GL_ARRAY_BUFFER, mVBO_normal);
glBufferData(GL_ARRAY_BUFFER, vertexNormalSize * sizeof(GLfloat), &vertex_normal[0], GL_STATIC_DRAW);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(1);
}
if (vertexTexcoordSize > 0) {
if (mVBO_texcoord == 0) {
glGenBuffers(1, &mVBO_texcoord);
}
std::cout << "Texture stuff set" << std::endl;
glBindBuffer(GL_ARRAY_BUFFER, mVBO_texcoord);
glBufferData(GL_ARRAY_BUFFER, vertexTexcoordSize * sizeof(GLfloat), &vertex_texcoord[0], GL_STATIC_DRAW);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(2);
}
// init and bind a IBO //
if (mIBO == 0) {
glGenBuffers(1, &mIBO);
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, mIndexCount * sizeof(GLuint), &indices[0], GL_STATIC_DRAW);
// unbind buffers //
glBindVertexArray(0);
// make sure to clean up temporarily allocated data, if neccessary //
delete[] vertex_position;
if (vertexNormalSize > 0) {
delete[] vertex_normal;
}
if (vertexTexcoordSize > 0) {
delete[] vertex_texcoord;
}
delete[] indices;
}
Render the Scene
glm_ModelViewMatrix.push(glm_ModelViewMatrix.top());
glActiveTexture(GL_TEXTURE0);
glm_ModelViewMatrix.top() = glm::translate(glm_ModelViewMatrix.top(),0.0f,-13.0f,-10.0f);
glUniformMatrix4fv(uniformLocations["modelview"], 1, false, glm::value_ptr(glm_ModelViewMatrix.top()));
glBindTexture(GL_TEXTURE_2D, objLoader->getMeshObj("trashbin")->getTexttureID());
glUniform1i(glGetUniformLocation(shaderProgram,"texture"), objLoader->getMeshObj("trashbin")->getTexttureID());
objLoader->getMeshObj("trashbin")->render();
glm_ModelViewMatrix.top() = glm::translate(glm_ModelViewMatrix.top(),-9.0f,-13.0f,-10.0f);
glm_ModelViewMatrix.top() = glm::scale(glm_ModelViewMatrix.top(), 1.5f,1.5f,1.5f);
glUniformMatrix4fv(uniformLocations["modelview"], 1, false, glm::value_ptr(glm_ModelViewMatrix.top()));
glBindTexture(GL_TEXTURE_2D, objLoader->getMeshObj("ball")->getTexttureID());
glUniform1i(glGetUniformLocation(shaderProgram,"texture"), objLoader->getMeshObj("ball")->getTexttureID());
objLoader->getMeshObj("ball")->render();
// restore scene graph to previous state //
glm_ModelViewMatrix.pop();
Render the mesh
void MeshObj::render(void) {
// render your VAO //
if (mVAO != 0) {
glBindVertexArray(mVAO);
glDrawElements(GL_TRIANGLES, mIndexCount, GL_UNSIGNED_INT, (void*)0);
glBindVertexArray(0);
}
}
After all this code, now a short description of my problem:
In my shaders I am currently checking if the texCoord is passed correctly to the shader, but it always stays (0,0).
Where is the problem when uploading the texture coordinates? The same technique is working fine for the vertexPosition and the vertex normal...
glUniform1i(glGetUniformLocation(shaderProgram,"texture"), objLoader->getMeshObj("trashbin")->getTexttureID());
Try passing in the texture unit index (texUnit) instead of the texture object ID (texObj, from a glGenTextures() call).
Generally:
unsigned int texUnit = 0;
glActiveTexture( GL_TEXTURE0 + texUnit );
glBindTexture( GL_TEXTURE_2D, texObj );
glUniform1i( ..., texUnit );
In your case:
glActiveTexture( GL_TEXTURE0 );
...
glBindTexture( GL_TEXTURE_2D, objLoader->getMeshObj("trashbin")->getTexttureID() );
glUniform1i( glGetUniformLocation( shaderProgram, "texture" ), 0 );
You don't give the image to OpenGL at any point with glTexImage2D
Add this below your bind texture in order to give OpenGL your texture
//example parameters, substitute with your own.
glTexImage2D(GL_TEXTURE_2D, 0,GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data);
//just parameters for texture(optional)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
Reference to glTexImage2D:
http://www.opengl.org/sdk/docs/man/xhtml/glTexImage2D.xml
I'm trying out my hand at graphics, following a tutorial at http://en.wikibooks.org/wiki/OpenGL_Programming/Modern_OpenGL_Tutorial_06
Problem: When I try to texture my cube, my sample is black.
Screenshot: http://puu.sh/2JP1H.jpg (note: I set blue = uv.x to test my UVs)
I looked at the threads OpenGL textures appear just black, and
Texture is all black, but it seemed they had different problems.
First I load my texture using SOIL image loading library:
int w, h;
unsigned char* img = SOIL_load_image("resources/images/4x4window.jpg",&w,&h,0,0);
ErrorIf(!img, "%s", SOIL_last_result());
glGenTextures(1, &texture_id);
glBindTexture(GL_TEXTURE, texture_id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,w,h,0,GL_RGB,GL_UNSIGNED_BYTE,img);
My render function where I pass my texture to the shader program:
void onDisplay()
{
glClearColor(1.0, 1.0, 1.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(program);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture_id);
glUniform1i(uniform_myTexture, /*GL_TEXTURE*/0);
glEnableVertexAttribArray(attribute_coord3d); // open shader var
glBindBuffer(GL_ARRAY_BUFFER, vbo_cube_verts); // put stuff in buffer
glVertexAttribPointer(attribute_coord3d, 3, GL_FLOAT, GL_FALSE, 0, 0); //send
glEnableVertexAttribArray(attribute_texcoord);
glBindBuffer(GL_ARRAY_BUFFER, vbo_cube_texcoords);
glVertexAttribPointer(attribute_texcoord, 2, GL_FLOAT, GL_FALSE, 0, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_cube_elements);
int size;
glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &size);
glDrawElements(GL_TRIANGLES, size / sizeof(GLushort), GL_UNSIGNED_SHORT, 0);
glDisableVertexAttribArray(attribute_coord3d);
glDisableVertexAttribArray(attribute_texcoord);
glutSwapBuffers();
}
Vertex Shader:
attribute vec3 coord3d;
attribute vec2 texcoord;
varying vec2 f_texcoord;
uniform mat4 mvp;
void main(void)
{
gl_Position = mvp * vec4(coord3d, 1.0);
f_texcoord = texcoord;
}
Fragment Shader:
varying vec2 f_texcoord;
uniform sampler2D mytexture;
void main(void)
{
vec4 result = texture2D(mytexture, f_texcoord);
result.z = f_texcoord.x;
result.w = 1;
gl_FragColor = result;
}
The line where the the texture is bound is:
glBindTexture(GL_TEXTURE, texture_id);
that should be:
glBindTexture(GL_TEXTURE_2D, texture_id);