My code is giving me this error:
Exception thrown at 0x00007FFCF428A6CF (nvoglv64.dll) in program.exe:
0xC0000005: Access violation reading location 0x000001D6B603F000.
In the debug output window of Visual Studio I also see pdb not loaded for the nvoglv64.dll file.
since i've added this code to my openGL app:
data = stbi_load("src/pickaxe.png", &width, &height, &nrChannels, 0);
if (!data) {
std::cout << "swords image loaded incorrectly " << std::endl;
}
else {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
Is it caused because of loading the image or by function GLTEXIMAGE_2D ?
Here is my full code:
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
// global variables
int p_WIDTH = 1280;
int p_HEIGHT = 960;
int succes;
char info[512];
// buffers
// shader sources
const char* vertexShaderSource =
"#version 330 core\n"
"layout(location = 0)in vec3 _verts;\n"
"layout(location = 1)in vec2 _texCoords;\n"
"out vec2 texCoords;\n"
"void main(){\n"
"gl_Position = vec4(_verts, 1.0f);\n"
"texCoords = _texCoords;\n"
"};\0"
;
const char* fragmentShaderSource =
"#version 330 core\n"
"in vec2 texCoords;\n"
"out vec4 fragColor;\n"
"uniform sampler2D _texture1;\n"
"uniform sampler2D _texture2;\n"
"void main(){\n"
"fragColor = mix(texture(_texture1, texCoords), texture(_texture2, texCoords), 0.5f);\n"
"};\0"
;
// functions
void window_resize_callback(GLFWwindow* window, int width, int height) {
glViewport(0, 0, width, height);
}
int main() {
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_ANY_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GLFWwindow* window = glfwCreateWindow(p_WIDTH, p_HEIGHT, "getting_started_completed", NULL, NULL);
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, window_resize_callback);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
// shaders
GLuint vertexShader, fragmentShader;
vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &succes);
if (!succes) {
glGetShaderInfoLog(vertexShader, 512, NULL, info);
std::cout << "VERTEX_SHADER_COMP_ERROR: " << info << std::endl;
}
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &succes);
if (!succes) {
glGetShaderInfoLog(fragmentShader, 512, NULL, info);
std::cout << "FRAGMENT_SHADER_COMP_ERROR: " << info << std::endl;
}
GLuint program = glCreateProgram();
glAttachShader(program, vertexShader);
glAttachShader(program, fragmentShader);
glLinkProgram(program);
glGetProgramiv(program, GL_COMPILE_STATUS, &succes);
if (!succes) {
glGetProgramInfoLog(program, 512, NULL, info);
std::cout << "PROGRAM_LINK_ERROR: " << info << std::endl;
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
// vertices
float vertices[] = {
-0.5f, -0.5f, 0.f, 0,0, // 0
0.5f, -0.5f, 0.f, 1,0, // 1
0.5f, 0.5f, 0.f, 1,1, // 2
-0.5f, 0.5f, 0.f, 0,1 // 3
};
unsigned int indices[] = {
0,1,2,
0,2,3
};
// buffers etc.
GLuint vbo, vao, ebo;
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
glGenBuffers(1, &ebo);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5*sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
// textures
unsigned int texture1, texture2;
glGenTextures(1, &texture1);
glBindTexture(GL_TEXTURE_2D, texture1);
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_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
int width, height, nrChannels;
stbi_set_flip_vertically_on_load(true);
unsigned char* data = stbi_load("src/dirt.jpg", &width, &height, &nrChannels, 0);
if (!data) {
std::cout << "dirt image loaded incorectly " << std::endl;
}
else {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
stbi_image_free(data);
glGenTextures(1, &texture2);
glBindTexture(GL_TEXTURE_2D, texture2);
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_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
data = stbi_load("src/pickaxe.png", &width, &height, &nrChannels, 0);
if (!data) {
std::cout << "swords image loaded incorrectly " << std::endl;
}
else {
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
glUseProgram(program);
glUniform1i(glGetUniformLocation(program, "_texture1"), 0);
glUniform1i(glGetUniformLocation(program, "_texture2"), 1);
while (!glfwWindowShouldClose(window)) {
glClearColor(0.f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture1);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture2);
glUseProgram(program);
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glfwPollEvents();
glfwSwapBuffers(window);
}
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(1, &vbo);
glDeleteBuffers(1, &ebo);
glfwTerminate();
//std::cin.get();
return 0;
}
You want to load and image with 4 channels (GL_RGBA). There is no guarantee that the STB library generates an image with 4 channels. The actual number of channels is returned by the 4th argument of stbi_load. If the image doesn't have 4 channels, the subsequent call of glTexImage2D expects a larger buffer than you actually provide. That causes the access violation.
To solve the problem, you can force stbi_load to generate an image with 4 color channels by explicitly passing 4 as the last parameter:
data = stbi_load("src/pickaxe.png", &width, &height, &nrChannels, 4);
Related
I'm trying to display RGB images in a GtkGLArea using a gtk/epoxy stack in C(/C++) langage brought by vcpkg.
I have no errors but the widget stay white.
Can someone teel me what I'm missing ?
here are the shaders:
#include <gtk/gtk.h>
#include <epoxy/gl.h>
const char* vertexShaderCode =
"#version 330 core\n"
"in vec3 a_position;"
"void main() {"
" gl_Position = vec4(a_position,1.0);"
"}";
const char* fragmentShaderCode =
"#version 330 core\n"
"uniform sampler2D u_texture;"
"in vec2 tex_pos;"
"out vec3 color;"
"void main() {"
" vec3 texel = texture2D(u_texture, tex_pos).rgb;"
" color = texel;"
"}";
used variables (class members):
guint width, height;
guint vao;
guint texture;
guint program;
void* pixels; // image content
some Triangle coordinates:
GLfloat vertices[12] = {
-1, -1, 0,
1, -1, 0,
-1, 1, 0,
1, 1, 0
};
GLfloat textureVertices[8] = {
0, 1,
1, 1,
0, 0,
1, 0
};
Init:
glViewport(0, 0, width, height);
glClearColor(1.0f, 1.0f, 1.0f, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// shaders
guint vshader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vshader, 1, &vertexShaderCode, NULL);
glCompileShader(vshader);
guint fshader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fshader, 1, &fragmentShaderCode, NULL);
glCompileShader(fshader);
//program
program = glCreateProgram();
glAttachShader(program, vshader);
glAttachShader(program, fshader);
glLinkProgram(program);
glUseProgram(program);
glDisable(GL_BLEND);
glDisable(GL_DITHER);
glDisable(GL_DEPTH_TEST);
glDeleteShader(vshader);
glDeleteShader(fshader);
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
GLuint buffers[2];
glGenBuffers(2, &buffers[0]);
glBindBuffer(GL_ARRAY_BUFFER, buffers[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, buffers[1]);
glBufferData(GL_ARRAY_BUFFER, sizeof(textureVertices), textureVertices, GL_STATIC_DRAW);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), 0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, 0);
int textureHandle = glGetUniformLocation(program, "u_texture");
glUniform1i(textureHandle, 0);
glBindAttribLocation(program, 0, "a_position");
glBindAttribLocation(program, 1, "tex_pos");
// textures
glActiveTexture(GL_TEXTURE0);
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);// OR LINEAR
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glTexImage2D(
GL_TEXTURE_2D, 0,
GL_RGB,
width, height, 0,
GL_RGB,
GL_UNSIGNED_BYTE, NULL);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glDisableVertexAttribArray(0);
glBindTexture(GL_TEXTURE_2D, 0);
glBindVertexArray(0);
glDeleteBuffers(2, &buffers[0]);
update drawing:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glBindTexture(GL_TEXTURE_2D, texture);
// Bind the VAO
glViewport(0, 0, areaWidth, areHeight);
glUseProgram(program);
glBindVertexArray(vao);
glBindTexture(GL_TEXTURE_2D, texture);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glBindTexture(GL_TEXTURE_2D, 0);
each time needed data is copied to pixels pointer and rendering is requested:
gtk_gl_area_queue_render(GTK_GL_AREA(widget));
but the image is never rendered
All vertex attributes are inputs to the vertex shader. You need to pass the texture coordinates from the vertex shader to the fragment shader:
#version 330 core
in vec3 a_position;
in vec2 a_tex_pos;
out vec2 tex_pos;
void main() {
tex_pos = a_tex_pos;
gl_Position = vec4(a_position,1.0);
}
glBindAttribLocation(program, 1, "tex_pos");
glBindAttribLocation(program, 1, "a_tex_pos");
Note that the vertex shader runs per vertex, but the fragment shader runs per fragment. The vertex shader outputs are interpolated along the fragments between the vertices. The interpolated outputs are the inputs to the fragment shader. With the interpolated texture coordinates, a different pixel of the image can be looked up for each fragment of the primitive.
I fixed it, there was several mistakes:
mainly:
draw strips without an bound vertice buffer
working example:
here are the shaders:
#include <gtk/gtk.h>
#include <epoxy/gl.h>
const char* vertexShaderCode =
"#version 330 core\n"
"layout(location = 0) in vec3 a_position;"
"in vec2 a_tex_pos;"
"out vec2 tex_pos;"
"void main() {"
" tex_pos = a_tex_pos;"
" gl_Position = vec4(a_position,1.0);"
"}";
const char* fragmentShaderCode =
"#version 330 core\n"
"uniform sampler2D u_texture;"
"in vec2 tex_pos;"
"layout(location = 0) out vec4 color;"
"void main() {"
" vec4 texel = texture2D(u_texture, tex_pos);"
" color = texel;"
"}";
used variables (class members):
guint width, height;
guint vao;
guint texture;
guint program;
guint buffers[2];
void* pixels; // image content
some Triangle coordinates:
GLfloat vertices[12] = {
-1, -1, 0,
1, -1, 0,
-1, 1, 0,
1, 1, 0
};
GLfloat textureVertices[8] = {
0, 1,
1, 1,
0, 0,
1, 0
};
Init:
glViewport(0, 0, width, height);
glClearColor(1.0f, 1.0f, 1.0f, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// shaders
guint vshader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vshader, 1, &vertexShaderCode, NULL);
glCompileShader(vshader);
guint fshader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fshader, 1, &fragmentShaderCode, NULL);
glCompileShader(fshader);
//program
program = glCreateProgram();
glAttachShader(program, vshader);
glAttachShader(program, fshader);
glLinkProgram(program);
glUseProgram(program);
//glDisable(GL_BLEND);
glDisable(GL_DITHER);
//glDisable(GL_DEPTH_TEST);
glDeleteShader(vshader);
glDeleteShader(fshader);
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
fbo = 0;
glGenFramebuffers(1, &fbo);
GLuint buffers[2];
glGenBuffers(2, &buffers[0]);
// I swap buffers order
glBindBuffer(GL_ARRAY_BUFFER, buffers[1]);
glBufferData(GL_ARRAY_BUFFER, sizeof(textureVertices), textureVertices, GL_STATIC_DRAW);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), 0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, buffers[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), 0);
glEnableVertexAttribArray(0);
//glBindBuffer(GL_ARRAY_BUFFER, 0); not yet !
int textureHandle = glGetUniformLocation(program, "u_texture");
glUniform1i(textureHandle, 0);
glBindAttribLocation(program, 0, "a_position");
glBindAttribLocation(program, 1, "a_tex_pos");
// textures
glActiveTexture(GL_TEXTURE0);
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);// OR LINEAR
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glTexImage2D(
GL_TEXTURE_2D, 0,
GL_RGB,
width, height, 0,
GL_RGBA,
GL_UNSIGNED_BYTE, NULL);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // it is effective now
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
GLenum DrawBuffers[1] = { GL_COLOR_ATTACHMENT0 };
glDrawBuffers(1, DrawBuffers);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0); // unbind now
glDisableVertexAttribArray(0);
glBindTexture(GL_TEXTURE_2D, 0);
glBindVertexArray(0);
//glDeleteBuffers(2, &buffers[0]); no !
update drawing:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glBindTexture(GL_TEXTURE_2D, texture);
// Bind the VAO
glViewport(0, 0, areaWidth, areHeight);
glUseProgram(program);
glBindVertexArray(vao);
glBindTexture(GL_TEXTURE_2D, texture);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels);
// rebind vertices
glBindBuffer(GL_ARRAY_BUFFER, buffers[0]);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glBindTexture(GL_TEXTURE_2D, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
each time needed data is copied to pixels pointer and rendering is requested:
gtk_gl_area_queue_render(GTK_GL_AREA(widget));
I am trying to display a texture, but for some reason it's not shown correctly it's distorted.
This is my source code:
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
void processInput(GLFWwindow *window)
{
if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
int main(void)
{
int success;
char infoLog[512];
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
glViewport(0, 0, 800, 600);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
const char *vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 aPos;\n"
"layout (location = 1) in vec2 aTexCoord;\n"
"out vec2 TexCoord;\n"
"void main()\n"
"{\n"
" gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
"TexCoord = aTexCoord;"
"}\0";
unsigned int vertexShader;
vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if(!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}
const char* fragmentShaderSource = "#version 330 core\n"
"out vec4 FragColor;\n"
"in vec2 TexCoord;\n"
"uniform sampler2D ourTexture;\n"
"void main()\n"
"{\n"
"FragColor = texture(ourTexture, TexCoord);\n"
"}\0";
unsigned int fragmentShader;
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if(!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}
unsigned int shaderProgram;
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if(!success) {
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
}
float vertices[] = {
//positions //texture coords
1.0f, 1.0f, 0.0f, 1.0f, 1.0f,// top right
1.0f, -1.0f, 0.0f, 1.0f, 0.0f,// bottom right
-1.0f, -1.0f, 0.0f, 0.0f, 0.0f,// bottom left
-1.0f, 1.0f, 0.0f, 0.0f, 1.0f// top left
};
unsigned int indices[] = {
0, 1, 3, // first triangle
1, 2, 3 // second triangle
};
unsigned int VBO;
unsigned int EBO;
unsigned int VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &EBO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
unsigned int texture;
glGenTextures(1, &texture);
//glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_TEXTURE_WRAP_S);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_TEXTURE_WRAP_T);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
int width, height, nrChannels;
stbi_set_flip_vertically_on_load(1);
unsigned char *data = stbi_load("../asd.jpg", &width, &height,&nrChannels, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else
{
if(stbi_failure_reason())
std::cout << stbi_failure_reason();
}
while(!glfwWindowShouldClose(window))
{
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glBindTexture(GL_TEXTURE_2D, texture);
glUseProgram(shaderProgram);
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
processInput(window);
glfwSwapBuffers(window);
glfwPollEvents();
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
glfwTerminate();
return 0;
}
Result:
Expected result:
I checked all coordinates and positions and everything looks correct. I have no idea why the texture is not shown correctly.
The vertex and fragment shaders also seems to be correct.
By default OpenGL assumes that the start of each row of an image is aligned to 4 bytes. This is because the GL_UNPACK_ALIGNMENT parameter by default is 4. Since the image has 3 color channels (GL_RGB), and is tightly packed the size of a row of the image may not be aligned to 4 bytes.
When a RGB image with 3 color channels is loaded to a texture object and 3*width is not divisible by 4, GL_UNPACK_ALIGNMENT has to be set to 1, before specifying the texture image with glTexImage2D:
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
This is an error that appears when trying to load the texture:
This is my working directory:
Down below is the location of my texture images
I tried adding a texture to a triangle however something seems to go wrong. When trying to run debug there is no error and no warning however it shows an grey window with no triangle and no texture whatsoever. Here is a part of my code, what is wrong?
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#define GLEW_STATIC
#include "GL/glew.h"
#include "GLFW/glfw3.h"
#include "SOIL2/SOIL2.h"
int glWindowWidth = 640;
int glWindowHeight = 480;
int retina_width, retina_height;
GLFWwindow* glWindow = NULL;
GLfloat vertexCoordinates[] = {
//position //color //texture
0.5f,0.5f,0.0f, 1.0f,0.0f,0.0f, 1.0f ,1.0f,
0.5f,-0.5f,0.0f, 1.0f,1.0f,1.0f, 1.0f,0.0f
-0.5f,-0.5f,0.0f, 1.0f,0.0f,0.0f, 0.0f ,0.0f,
-0.5f,0.5f,0.0f, 1.0f,0.0f,1.0f, 0.0f ,1.0f,
};
GLuint indices[] =
{
0,1,2,
1,2,3
};
GLuint verticesVBO;
GLuint triangleVAO;
GLuint EBO;
GLuint triangleVAO2;
GLuint verticesVBO2;
GLuint shaderProgram;
GLuint shaderProgram2;
void windowResizeCallback(GLFWwindow* window, int width, int height)
{
fprintf(stdout, "window resized to width: %d , and height: %d\n", width, height);
//TODO
}
void initObjects()
{
//genereaza un ID unic pentru verticesVBO
glGenBuffers(1, &verticesVBO);
glGenBuffers(1, &EBO);
glGenVertexArrays(1, &triangleVAO);
glBindBuffer(GL_ARRAY_BUFFER, verticesVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexCoordinates), vertexCoordinates, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
//genereaza un ID unic, care corespunde obiectului triangleVAO
glBindVertexArray(triangleVAO);
glBindBuffer(GL_ARRAY_BUFFER, verticesVBO);
//seteaza pointer-ul atributelor de varf
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8*sizeof(GLfloat), (GLvoid *)0);
glEnableVertexAttribArray(0);
//color attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3*sizeof(GLfloat)));
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
glEnableVertexAttribArray(2);
//de-selecteaza obiectul triangleVAO
glBindVertexArray(0);
}
bool initOpenGLWindow()
{
if (!glfwInit()) {
fprintf(stderr, "ERROR: could not start GLFW3\n");
return false;
}
//for Mac OS X
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE,GL_FALSE);
glWindow = glfwCreateWindow(glWindowWidth, glWindowHeight, "OpenGL Shader Example", NULL, NULL);
if (!glWindow) {
fprintf(stderr, "ERROR: could not open window with GLFW3\n");
glfwTerminate();
return false;
}
glfwSetWindowSizeCallback(glWindow, windowResizeCallback);
glfwMakeContextCurrent(glWindow);
glfwWindowHint(GLFW_SAMPLES, 4);
// start GLEW extension handler
glewExperimental = GL_TRUE;
glewInit();
// get version info
const GLubyte* renderer = glGetString(GL_RENDERER); // get renderer string
const GLubyte* version = glGetString(GL_VERSION); // version as a string
printf("Renderer: %s\n", renderer);
printf("OpenGL version supported %s\n", version);
//for RETINA display
glfwGetFramebufferSize(glWindow, &retina_width, &retina_height);
return true;
}
void renderScene()
{
//initializeaza buffer-ele de culoare si adancime inainte de a rasteriza cadrul curent
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//defineste culoarea de fundal
glClearColor(0.8, 0.8, 0.8, 1.0);
//specifica locatia si dimensiunea ferestrei
glViewport(0, 0, retina_width, retina_height);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
if (glfwGetKey(glWindow, GLFW_KEY_D)) {
//TODO
}
//activeaza program shader-ul; apeluri ulterioare de rasterizare vor utiliza acest program
glUseProgram(shaderProgram); /**/
//activeaza VAO
glBindVertexArray(triangleVAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
//specifica tipul primitiei, indicele de inceput si numarul de indici utilizati pentru rasterizare
//glDrawArrays(GL_TRIANGLES, 0, 3);
//glDrawArrays(GL_TRIANGLES, 0, 3); /**/
}
std::string readShaderFile(std::string fileName)
{
std::ifstream shaderFile;
std::string shaderString;
//open shader file
shaderFile.open(fileName);
std::stringstream shaderStringStream;
//read shader content into stream
shaderStringStream << shaderFile.rdbuf();
//close shader file
shaderFile.close();
//convert stream into GLchar array
shaderString = shaderStringStream.str();
return shaderString;
}
void shaderCompileLog(GLuint shaderId)
{
GLint success;
GLchar infoLog[512];
//check compilation info
glGetShaderiv(shaderId, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(shaderId, 512, NULL, infoLog);
std::cout << "Shader compilation error\n" << infoLog << std::endl;
}
}
void shaderLinkLog(GLuint shaderProgramId)
{
GLint success;
GLchar infoLog[512];
//check linking info
glGetProgramiv(shaderProgramId, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
std::cout << "Shader linking error\n" << infoLog << std::endl;
}
}
GLuint initBasicShader(std::string vertexShaderFileName, std::string fragmentShaderFileName, GLuint shaderProgram)
{
//read, parse and compile the vertex shader
std::string v = readShaderFile(vertexShaderFileName);
const GLchar* vertexShaderString = v.c_str();
GLuint vertexShader;
vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderString, NULL);
glCompileShader(vertexShader);
//check compilation status
shaderCompileLog(vertexShader);
//read, parse and compile the vertex shader
std::string f = readShaderFile(fragmentShaderFileName);
const GLchar* fragmentShaderString = f.c_str();
GLuint fragmentShader;
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderString, NULL);
glCompileShader(fragmentShader);
//check compilation status
shaderCompileLog(fragmentShader);
//attach and link the shader programs
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
//check linking info
shaderLinkLog(shaderProgram);
return shaderProgram;
}
int main(int argc, const char * argv[]) {
initOpenGLWindow();
initObjects();
shaderProgram = initBasicShader("shaders/shader.vert", "shaders/shader.frag",shaderProgram);
shaderProgram2 = initBasicShader("shaders/shader2.vert", "shaders/shader2.frag",shaderProgram2);
int width, height;
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
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);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
unsigned char* image = SOIL_load_image("res/images/image1.jpg", &width, &height, 0, SOIL_LOAD_RGBA);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);
glGenerateMipmap(GL_TEXTURE_2D);
SOIL_free_image_data(image);
glBindTexture(GL_TEXTURE_2D, 0);
while (!glfwWindowShouldClose(glWindow)) {
glActiveTexture(GL_TEXTURE0);
glfwPollEvents();
renderScene();
glBindTexture(GL_TEXTURE_2D, texture);
glUniform1i(glGetUniformLocation(shaderProgram, "diffuseTexture"), 0);
glBindVertexArray(triangleVAO);
glfwSwapBuffers(glWindow);
}
//close GL context and any other GLFW resources
glfwTerminate();
return 0;
}
This is the fragment shader
#version 400
in vec3 colour;
in vec2 passTexture;
out vec4 fragmentColour;
uniform sampler2D dif;
void main() {
fragmentColour = texture(dif, passTexture);
}
This is the vertex shader:
#version 400
layout(location = 0) in vec3 vertexPosition;
layout(location = 1) in vec3 vertexNormal;
layout(location = 2) in vec2 textcoord;
out vec3 colour;
out vec2 passTexture;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main() {
colour = vertexNormal;
passTexture = textcoord;
gl_Position = projection * view * model * vec4(vertexPosition, 1.0);
}
By default all fields of the matrices in the vertex are shader are initialized by 0.0.
To make the code run you've to skip the matrices:
gl_Position = vec4(vertexPosition, 1.0);
Or initialize them by the Identity matrix in renderScene:
GLint model_loc = glGetUniformLocation(shaderProgram, "model");
GLint view_loc = glGetUniformLocation(shaderProgram, "view");
GLint proj_loc = glGetUniformLocation(shaderProgram, "projection");
GLint tex_loc = glGetUniformLocation(shaderProgram, "diffuseTexture");
float identity_matrix[] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
Note, uniforms have to be set, after the program is installed by glUseProgram.
glUseProgram(shaderProgram);
glUniformMatrix4fv(model_loc, 1, GL_FALSE, identity_matrix);
glUniformMatrix4fv(view_loc, 1, GL_FALSE, identity_matrix);
glUniformMatrix4fv(proj_loc, 1, GL_FALSE, identity_matrix);
glUniform1i(tex_loc, 0); // unnecessary, because 0 is default.
Since the Index buffers is stated in the Vertex Array Object, the VAO has to be bound, before the index buffer can be bound:
glGenVertexArrays(1, &triangleVAO);
glBindVertexArray(triangleVAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
Set all the necessary states, and bind the necessary objects, before you do the draw call.
The viewport rectangle and the clear color should be set before glClear.
The texture should be bound before the mesh is drawn.
while (!glfwWindowShouldClose(glWindow)) {
glfwPollEvents();
renderScene();
glfwSwapBuffers(glWindow);
}
void renderScene()
{
glViewport(0, 0, retina_width, retina_height);
glClearColor(0.8, 0.8, 0.8, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glBindVertexArray(triangleVAO);
glUseProgram(shaderProgram);
// set the uniforms as described above
// [...]
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
}
Furthermore there is missing a comma (,) int the 2nd row of the array of vertex array attributes and the indices do not form a quad. Change it:
GLfloat vertexCoordinates[] = {
//position //color //texture
0.5f, 0.5f,0.0f, 1.0f,0.0f,0.0f, 1.0f ,1.0f,
0.5f,-0.5f,0.0f, 1.0f,1.0f,1.0f, 1.0f ,0.0f,
-0.5f,-0.5f,0.0f, 1.0f,0.0f,0.0f, 0.0f ,0.0f,
-0.5f, 0.5f,0.0f, 1.0f,0.0f,1.0f, 0.0f ,1.0f,
};
GLuint indices[] = { 0,1,2, 0,2,3 };
Finally, if you want to use mipmaping, then the texture minification filter has to be one of GL_NEAREST_MIPMAP_NEAREST, GL_LINEAR_MIPMAP_NEAREST, GL_NEAREST_MIPMAP_LINEAR or GL_LINEAR_MIPMAP_LINEAR.
Full code:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#define GLEW_STATIC
#include "GL/glew.h"
#include "GLFW/glfw3.h"
#include "SOIL2/SOIL2.h"
int glWindowWidth = 640;
int glWindowHeight = 480;
int retina_width, retina_height;
GLFWwindow* glWindow = NULL;
GLfloat vertexCoordinates[] = {
//position //color //texture
0.5f, 0.5f,0.0f, 1.0f,0.0f,0.0f, 1.0f ,1.0f,
0.5f,-0.5f,0.0f, 1.0f,1.0f,1.0f, 1.0f ,0.0f,
-0.5f,-0.5f,0.0f, 1.0f,0.0f,0.0f, 0.0f ,0.0f,
-0.5f, 0.5f,0.0f, 1.0f,0.0f,1.0f, 0.0f ,1.0f,
};
GLuint indices[] = { 0,1,2, 0,2,3 };
GLuint verticesVBO;
GLuint triangleVAO;
GLuint EBO;
GLuint triangleVAO2;
GLuint verticesVBO2;
GLuint shaderProgram;
GLuint shaderProgram2;
GLuint texture;
GLint model_loc, view_loc, proj_loc, tex_loc;
float identity_matrix[] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
void windowResizeCallback(GLFWwindow* window, int width, int height)
{
fprintf(stdout, "window resized to width: %d , and height: %d\n", width, height);
//TODO
}
void initObjects()
{
//genereaza un ID unic pentru verticesVBO
glGenBuffers(1, &verticesVBO);
glGenBuffers(1, &EBO);
glGenVertexArrays(1, &triangleVAO);
glBindVertexArray(triangleVAO);
glBindBuffer(GL_ARRAY_BUFFER, verticesVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexCoordinates), vertexCoordinates, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
//genereaza un ID unic, care corespunde obiectului triangleVAO
glBindBuffer(GL_ARRAY_BUFFER, verticesVBO);
//seteaza pointer-ul atributelor de varf
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8*sizeof(GLfloat), (GLvoid *)0);
glEnableVertexAttribArray(0);
//color attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3*sizeof(GLfloat)));
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
glEnableVertexAttribArray(2);
//de-selecteaza obiectul triangleVAO
glBindVertexArray(0);
}
bool initOpenGLWindow()
{
if (!glfwInit()) {
fprintf(stderr, "ERROR: could not start GLFW3\n");
return false;
}
//for Mac OS X
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE,GL_FALSE);
glWindow = glfwCreateWindow(glWindowWidth, glWindowHeight, "OpenGL Shader Example", NULL, NULL);
if (!glWindow) {
fprintf(stderr, "ERROR: could not open window with GLFW3\n");
glfwTerminate();
return false;
}
glfwSetWindowSizeCallback(glWindow, windowResizeCallback);
glfwMakeContextCurrent(glWindow);
glfwWindowHint(GLFW_SAMPLES, 4);
// start GLEW extension handler
glewExperimental = GL_TRUE;
glewInit();
// get version info
const GLubyte* renderer = glGetString(GL_RENDERER); // get renderer string
const GLubyte* version = glGetString(GL_VERSION); // version as a string
printf("Renderer: %s\n", renderer);
printf("OpenGL version supported %s\n", version);
//for RETINA display
glfwGetFramebufferSize(glWindow, &retina_width, &retina_height);
return true;
}
void renderScene()
{
glViewport(0, 0, retina_width, retina_height);
glClearColor(0.8, 0.8, 0.8, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glBindVertexArray(triangleVAO);
if (glfwGetKey(glWindow, GLFW_KEY_D)) {
//TODO
}
glUseProgram(shaderProgram);
glUniformMatrix4fv(model_loc, 1, GL_FALSE, identity_matrix);
glUniformMatrix4fv(view_loc, 1, GL_FALSE, identity_matrix);
glUniformMatrix4fv(proj_loc, 1, GL_FALSE, identity_matrix);
glUniform1i(tex_loc, 0); // unnecessary, because 0 is default.
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
}
std::string readShaderFile(std::string fileName)
{
std::ifstream shaderFile;
std::string shaderString;
//open shader file
shaderFile.open(fileName);
std::stringstream shaderStringStream;
//read shader content into stream
shaderStringStream << shaderFile.rdbuf();
//close shader file
shaderFile.close();
//convert stream into GLchar array
shaderString = shaderStringStream.str();
return shaderString;
}
void shaderCompileLog(GLuint shaderId)
{
GLint success;
GLchar infoLog[512];
//check compilation info
glGetShaderiv(shaderId, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(shaderId, 512, NULL, infoLog);
std::cout << "Shader compilation error\n" << infoLog << std::endl;
}
}
void shaderLinkLog(GLuint shaderProgramId)
{
GLint success;
GLchar infoLog[512];
//check linking info
glGetProgramiv(shaderProgramId, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
std::cout << "Shader linking error\n" << infoLog << std::endl;
}
}
GLuint initBasicShader(std::string vertexShaderFileName, std::string fragmentShaderFileName, GLuint shaderProgram)
{
//read, parse and compile the vertex shader
std::string v = readShaderFile( vertexShaderFileName );
const GLchar* vertexShaderString = v.c_str();
GLuint vertexShader;
vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderString, NULL);
glCompileShader(vertexShader);
//check compilation status
shaderCompileLog(vertexShader);
//read, parse and compile the vertex shader
std::string f = readShaderFile( fragmentShaderFileName );
const GLchar* fragmentShaderString = f.c_str();
GLuint fragmentShader;
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderString, NULL);
glCompileShader(fragmentShader);
//check compilation status
shaderCompileLog(fragmentShader);
//attach and link the shader programs
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
//check linking info
shaderLinkLog(shaderProgram);
return shaderProgram;
}
int main(int argc, const char * argv[]) {
initOpenGLWindow();
initObjects();
shaderProgram = initBasicShader("shaders/shader.vert", "shaders/shader.frag",shaderProgram);
model_loc = glGetUniformLocation(shaderProgram, "model");
view_loc = glGetUniformLocation(shaderProgram, "view");
proj_loc = glGetUniformLocation(shaderProgram, "projection");
tex_loc = glGetUniformLocation(shaderProgram, "diffuseTexture");
shaderProgram2 = initBasicShader("shaders/shader2.vert", "shaders/shader2.frag",shaderProgram2);
int width, height;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
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);
unsigned char* image = SOIL_load_image("SOIL2/res/images/image1.jpg", &width, &height, 0, SOIL_LOAD_RGBA);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);
glGenerateMipmap(GL_TEXTURE_2D);
SOIL_free_image_data(image);
glBindTexture(GL_TEXTURE_2D, 0);
while (!glfwWindowShouldClose(glWindow)) {
glfwPollEvents();
renderScene();
glfwSwapBuffers(glWindow);
}
//close GL context and any other GLFW resources
glfwTerminate();
return 0;
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
//genereaza un ID unic, care corespunde obiectului triangleVAO
glBindVertexArray(triangleVAO);
You need to bind the vertex array object before you bind the index buffer, so you need to swap this around.
Edit: The vertex array bind needs to go above
glBindBuffer(GL_ARRAY_BUFFER, verticesVBO);
as well.
I have two uniform in my shader and i am updating these uniform in my window loop but the window do no get updated with loop instead i have to use my mouse to update the window..
I have upload a vedio to showcase this problem https://youtu.be/jWABZ50HhCE
This is my code::
#define GLEW_STATIC
#include<gl\glew.h>
#include<GLFW\glfw3.h>
#include<iostream>
#include<SOIL.h>
#include<glm/glm.hpp>
#include<glm/gtc/matrix_transform.hpp>
#include<glm/gtc/type_ptr.hpp>
//////////////////////////////////////
static const char* vertexShaderSource = "\n\
#version 150 core\n\
in vec2 position;\n\
in vec3 inColor;\n\
uniform mat4 trans;\n\ ////////////Uniform1/////////////
in vec2 texcoord;\n\
out vec2 Texcoord;\n\
out vec3 Color;\n\
void main(){\n\
Color=inColor;\n\
Texcoord=texcoord;\n\
gl_Position=trans*vec4(position,0,1);\n\
}\n";
static const char* fragmentShaderSource = "\n\
#version 150 core\n\
in vec3 Color;\n\
in vec2 Texcoord;\n\
uniform sampler2D te0;\n\
uniform sampler2D tex1;\n\
out vec4 color;\n\
uniform float mixvalue;\n\ ////////////Uniform2/////////////
void main(){\n\
vec4 color1=texture(te0,Texcoord);\n\
vec4 color2=texture(tex1,Texcoord);\n\
color=mix(color1,color2,mixvalue);\n\
}\n\
";
//////////////////////////////////////
int main() {
if (!glfwInit())
return -1;
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
GLFWwindow* window = glfwCreateWindow(1024, 620, "Window", nullptr, nullptr);
glfwMakeContextCurrent(window);
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
return -1;
GLfloat triangleVertices[] = {
0.5f,0.5f,1,0,0,1,0,
0.5f,-0.5f,0,1,0,1,1,
-0.5f,-0.5f,0,0,1,0,1,
-0.5f,0.5f,0,0,0,0,0
};
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(triangleVertices), triangleVertices, GL_STATIC_DRAW);
GLuint elements[] = { 0,1,2 ,3,0,2};
GLuint ebo;
glGenBuffers(1, &ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);
////////////////////////////////////////////////////////
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, nullptr);
glCompileShader(vertexShader);
GLint statusVertex;
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &statusVertex);
if (!statusVertex) {
char buffer[1024];
glGetShaderInfoLog(vertexShader, 1024, NULL, buffer);
std::cout << "Error Compiling vertexShader:" << buffer << std::endl;
}
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, nullptr);
glCompileShader(fragmentShader);
GLint statusFrag;
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &statusFrag);
if (!statusFrag) {
char buffer[1024];
glGetShaderInfoLog(fragmentShader, 1024, NULL, buffer);
std::cout << "Error Compiling fragmentShader:" << buffer << std::endl;
}
GLuint program = glCreateProgram();
glAttachShader(program, vertexShader);
glAttachShader(program, fragmentShader);
glBindFragDataLocation(program, 0, "color");
glLinkProgram(program);
glUseProgram(program);
//////////////////////////////////////////////////////////
GLint positionAttrib = glGetAttribLocation(program, "position");
glVertexAttribPointer(positionAttrib, 2, GL_FLOAT, GL_FALSE, 7 * sizeof(GL_FLOAT), nullptr);
glEnableVertexAttribArray(positionAttrib);
GLint colorAttrib = glGetAttribLocation(program, "inColor");
glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(GL_FLOAT), (void*)(2 * sizeof(GL_FLOAT)));
glEnableVertexAttribArray(colorAttrib);
GLint texAttrib = glGetAttribLocation(program, "texcoord");
glVertexAttribPointer(texAttrib, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(GL_FLOAT), (void*)(5 * sizeof(GL_FLOAT)));
glEnableVertexAttribArray(texAttrib);
GLuint textures[2];
glGenTextures(2, textures);
int width, height;
unsigned char* image;
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textures[0]);
image = SOIL_load_image("1.png", &width, &height, 0, SOIL_LOAD_RGBA);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);
glGenerateMipmap(GL_TEXTURE_2D);
glUniform1i(glGetUniformLocation(program, "te0"), 0);
SOIL_free_image_data(image);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, textures[1]);
image = SOIL_load_image("2.png", &width, &height, 0, SOIL_LOAD_RGBA);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);
glGenerateMipmap(GL_TEXTURE_2D);
glUniform1i(glGetUniformLocation(program, "tex1"), 1);
SOIL_free_image_data(image);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
GLuint mixvalue = glGetUniformLocation(program, "mixvalue");
GLint uniTrans = glGetUniformLocation(program, "trans");
//////These Two uniform/////////////////////
////////////////////////////////////////////
glm::mat4 trans = glm::mat4(1.0f);
float a=0,b=0;
/////////////////////////////////////////////////////////////
while (!glfwWindowShouldClose(window)) {
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
b += 3;
trans = glm::rotate(trans, glm::radians(b), glm::vec3(0, 0, 1));
glUniformMatrix4fv(uniTrans, 1, GL_FALSE, glm::value_ptr(trans));
if (glfwGetKey(window, GLFW_KEY_E)) {
break;
}
if (a >= 1) a = 0;
a += 0.1f;
glUniform1f(mixvalue, a);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
What is wrong here.Is there something that i am doing wrong or is it because of some driver error.
GlfwVersion 3.3.0 32 bit
This question already has an answer here:
OpenGL texture tilted
(1 answer)
Closed 1 year ago.
I'm trying to upload a texture in OpenGL but the texture is crooked.
#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <SOIL/SOIL.h>
#define GLSL(version, shader) "#version " #version "\n" #shader
const char * vertShader = GLSL(430,
in vec2 position;
in vec2 texcoord;
out vec2 coordinates;
void main() {
coordinates = texcoord;
gl_Position = vec4(position, 0.0, 1.0);
}
);
const char * fragShader = GLSL(430,
in vec2 coordinates;
out vec4 color;
uniform sampler2D texture;
void main() {
color = texture(texture, coordinates);
}
);
int main(int argc, char ** argv)
{
if (not glfwInit())
{
std::cerr << "Failed to initialize GLFW" << std::endl;
return -1;
}
GLFWwindow *window;
window = glfwCreateWindow(720, 480, "Textures", 0, 0);
if (not window)
{
std::cerr << "Failed to open GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glewExperimental = true;
if (glewInit() != GLEW_OK)
{
std::cerr << "Failed to initialize GLEW" << std::endl;
return -1;
}
glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
GLuint vbo;
glGenBuffers(1, &vbo);
GLfloat vertices[] = {
-1.0f, +1.0f, 0.0f, 0.0f,
+1.0f, +1.0f, 1.0f, 0.0f,
+1.0f, -1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 0.0f, 1.0f,
};
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
GLuint ebo;
glGenBuffers(1, &ebo);
GLuint elements[] = {
0, 1, 2,
2, 3, 0
};
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertShader, 0);
glCompileShader(vertexShader);
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragShader, NULL);
glCompileShader(fragmentShader);
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glUseProgram(shaderProgram);
GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
GLint texAttrib = glGetAttribLocation(shaderProgram, "texcoord");
glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), 0);
glEnableVertexAttribArray(posAttrib);
glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void *)(2 * sizeof(float)));
glEnableVertexAttribArray(texAttrib);
GLuint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
int width, height;
unsigned char * image = SOIL_load_image("happyface.png", &width, &height, 0, SOIL_LOAD_RGB);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
SOIL_free_image_data(image);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
do {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glfwPollEvents();
glfwSwapBuffers(window);
} while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS
&& glfwWindowShouldClose(window) == 0);
glDeleteTextures(1, &tex);
glDeleteProgram(shaderProgram);
glDeleteShader(fragmentShader);
glDeleteShader(vertexShader);
glDeleteBuffers(1, &ebo);
glDeleteBuffers(1, &vbo);
glDeleteVertexArrays(1, &vao);
glfwTerminate();
return 0;
}
What am I doing wrong? As you can see the texture is crooked and repeating, but the texture is just one smiley face.
That is the result:
And that is the texture:
I'm no OpenGL guru, but some graphics systems require textures that are multiples of 2 or 4 pixels wide.
Your texture is 479 wide - add another column of pixels and I think you'll be fine.