im learning about OpenGL and i wrote the following code in C++ using this guide and this video.
Also i am using GLFW for context creation and GLEW for GL functions
Most of the Shader class is copied from the video up linked,
The problem is that using glDrawElements() to render inside the main loop gets me a segmentation fault:
Segmentation fault
------------------
(program exited with code: 139)
Press return to continue
while with glDrawArrays() i can draw with no problems.
Does anyone know what this could be caused by?
I think the error might depend on the implementation of the Shader class, because i used glDrawArrays() in other programs that did not used this class and that cared about shaders in the main function.
program.cpp
//INCLUDE AND DECLARATIONS
#include <iostream>
#include <fstream>
// GLEW
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
#include "Shader.h"
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
unsigned long getFileLength(std::ifstream& file);
int loadshader(char* filename, GLchar** ShaderSource, unsigned long* len);
const GLuint WIDTH = 800, HEIGHT = 600;
//VERTEX DATA
float data[] = {
// X Y R G B
-0.5f, 0.5f, 1.0f, 0.0f, 0.0f, // Top-left
0.5f, 0.5f, 0.0f, 1.0f, 0.0f, // Top-right
0.5f, -0.5f, 0.0f, 0.0f, 1.0f, // Bottom-right
-0.5f, -0.5f, 1.0f, 1.0f, 1.0f // Bottom-left
};
GLuint elements[] = {
0, 1, 2,
2, 3, 0
};
//main
int main()
{ //INIT GLFW AND WINDOW
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, key_callback);
glewExperimental = GL_TRUE;
glewInit();
glViewport(0, 0, WIDTH, HEIGHT);
//ALLOCATE BUFFERS
//VERTEX ARRAY BUFFER
GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(data), data, GL_STATIC_DRAW);
//ELEMENT ARRAY BUFFER
GLuint ebo;
glGenBuffers(1, &ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);
//CREATE SHADER
Shader shader("./shaders/basicShader");
// main loop
while (!glfwWindowShouldClose(window))
{
shader.Bind();
glfwPollEvents(); //window events
glClearColor(1.0f, 0.0f, 0.5f, 0.5f); //background
glClear(GL_COLOR_BUFFER_BIT);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glfwSwapBuffers(window); //update window
}
glDeleteBuffers(1, &vbo);
glDeleteBuffers(1, &ebo);
glfwTerminate();
return 0;
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
}
Shader.h
#include <iostream>
#include <fstream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
class Shader
{
public:
Shader(const std::string& filepath);
~Shader();
void Bind();
private:
static const GLuint NUM_SHADERS = 2;
GLuint program;
GLuint shaders[NUM_SHADERS];
std::string LoadShader(const std::string& fileName);
void CheckShaderError(GLuint shader, GLuint flag, bool isProgram, const std::string& errorMessage);
GLuint CreateShader(const std::string& text, unsigned int type);
};
Shader.cpp
#include "Shader.h"
Shader::Shader(const std::string& filepath)
{
program = glCreateProgram();
shaders[0] = CreateShader(LoadShader(filepath + ".vs"), GL_VERTEX_SHADER);
shaders[1] = CreateShader(LoadShader(filepath + ".fs"), GL_FRAGMENT_SHADER);
for(unsigned int i = 0; i < NUM_SHADERS; i++)
{
glAttachShader(program, shaders[i]);
}
glBindAttribLocation(program, 0, "position");
glBindFragDataLocation(program, 0, "outColor");
glLinkProgram(program);
CheckShaderError(program, GL_LINK_STATUS, true, "Error linking shader program");
glValidateProgram(program);
CheckShaderError(program, GL_LINK_STATUS, true, "Invalid shader program");
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
GLint posAttrib = glGetAttribLocation(program, "position");
glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 5*sizeof(float), 0);
glEnableVertexAttribArray(posAttrib);
GLint AttribColor = glGetAttribLocation(program, "color");
glVertexAttribPointer(AttribColor, 3, GL_FLOAT, GL_FALSE, 5*sizeof(float), (void*)(2*sizeof(float)));
glEnableVertexAttribArray(AttribColor);
}
Shader::~Shader()
{
for(unsigned int i = 0; i < NUM_SHADERS; i++)
{
glDetachShader(program, shaders[i]);
glDeleteShader(shaders[i]);
}
glDeleteProgram(program);
}
void Shader::Bind()
{
glUseProgram(program);
}
//loads shaders from files
std::string Shader::LoadShader(const std::string& fileName)
{
std::ifstream file;
file.open((fileName).c_str());
std::string output;
std::string line;
if(file.is_open())
{
while(file.good())
{
getline(file, line);
output.append(line + "\n");
}
}
else
{
std::cerr << "Unable to load shader: " << fileName << std::endl;
}
return output;
}
//Checks for eventual errors in shaders
void Shader::CheckShaderError(GLuint shader, GLuint flag, bool isProgram, const std::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);
std::cerr << errorMessage << ": '" << error << "'" << std::endl;
}
}
GLuint Shader::CreateShader(const std::string& text, unsigned int type)
{
GLuint shader = glCreateShader(type);
if(shader == 0)
std::cerr << "error allocating shader" << std:: endl;
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;
}
The problem is with your index buffer binding. The index buffer (GL_ELEMENT_ARRAY_BUFFER) binding is part of the VAO state. Skipping the unrelated calls, you have the following overall sequence:
...
glGenBuffers(1, &ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);
...
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
...
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
Since the GL_ELEMENT_ARRAY_BUFFER binding is part of the VAO state, the current index buffer binding is replaced with the index buffer binding in the VAO state when you call:
glBindVertexArray(vao);
Since you never bind an index buffer while the VAO is bound, this means that the index buffer binding in the VAO state is 0. As a result, you don't have an index buffer bound after this call.
What happens next is that you make the glDrawElements() call with the last argument 0. Without an index buffer bound, the last argument is interpreted as a pointer to CPU memory. So OpenGL tries to read index data at address 0, which causes the crash.
To fix this, you simply have to bind the index buffer while the VAO is bound. You can either do that by changing the order of your calls, and create/bind the VAO before you set up the index buffer. Or you can bind it again when you set up the vertex attribute state. For example, at the very end of the Shader constructor, after the glVertexAttribPointer() and related calls, you add this call:
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 months ago.
Improve this question
I just started learning OpenGL by following https://learnopengl.com/Getting-started/Hello-Triangle, following the tutorial I wrote the code as per my understanding which compiles and does give me an output but instead of an orangish triangle it shows a white one. If I replace the shaderProgram() with the code from https://learnopengl.com/code_viewer_gh.php?code=src/1.getting_started/2.1.hello_triangle/hello_triangle.cpp it works (shows the orange triangle), so I think I narrowed the problem to shader program compilation, I just couldn't find what's wrong with it, following is my code.
// Local Headers
#include "glitter.hpp"
// System Headers
#include <glad/glad.h>
#include <GLFW/glfw3.h>
// Standard Headers
#include <cstdio>
#include <cstdlib>
#include <stdexcept>
#include <iostream>
#include <memory>
void _delete_shader(const GLuint *shader)
{
if (!shader) return;
glDeleteShader(*shader);
delete shader;
}
using shader_t = std::unique_ptr<GLuint, decltype(&_delete_shader)>;
// window resize callback
void framebuffer_size_callback(GLFWwindow* , int width, int height)
{
glViewport(0, 0, width, height);
}
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, true);
}
}
shader_t compileShader(const char *source, GLenum shaderType)
{
auto shader = glCreateShader(shaderType);
glShaderSource(shader, 1, &source, nullptr);
glCompileShader(shader);
int success;
char log[512];
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(shader, sizeof(log), nullptr, log);
throw std::runtime_error(log);
}
return shader_t(new GLuint {shader}, &_delete_shader);
}
shader_t vertexshader() try
{
static const char *source = R"(
#version 330 core
layout (location = 0) in vec3 aPos;
void main()
{
gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);
}
)";
return compileShader(source, GL_VERTEX_SHADER);
}
catch(const std::exception& e)
{
printf("error in vertex shader, %s\n", e.what());
exit(-1);
}
shader_t fragmentShader() try
{
static const char *source = R"(
#version 330 core
out vec4 FragColor;
void main()
{
FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);
}
)";
return compileShader(source, GL_FRAGMENT_SHADER);
}
catch(const std::exception &e)
{
printf("error in fragment shader, %s\n", e.what());
exit(-1);
}
uint32_t shaderProgram() try
{
uint32_t program = glCreateProgram();
const auto vertexShader = ::vertexshader();
glAttachShader(program, *vertexShader);
const auto fragmentShader = ::fragmentShader();
glAttachShader(program, *fragmentShader);
glLinkProgram(program);
int success;
glGetProgramiv(program, GL_LINK_STATUS, &success);
if (!success)
{
char log[512];
glGetProgramInfoLog(program, 512, nullptr, log);
throw std::runtime_error(log);
}
}
catch(const std::exception &e)
{
printf("error in shader program, %s\n", e.what());
exit(-1);
}
int main(int , char * [])
{
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", nullptr, nullptr);
if (window == nullptr)
{
printf("Failed to create window\n");
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
puts("Failed to initialize GLAD\n");
glfwTerminate();
return -1;
}
glViewport(0, 0, 800, 600);
float vertices[] =
{
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
0.0f, 0.5f, 0.0f
};
const auto shaderProgram = ::shaderProgram();
unsigned int VAO, VBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
glBindVertexArray(VAO);
// copy vertices into gpu memory
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// how data should be interpreted
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void *)0);
glEnableVertexAttribArray(0);
// note that this is allowed, the call to glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind
glBindBuffer(GL_ARRAY_BUFFER, 0);
// You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other
// VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary.
glBindVertexArray(0);
while (!glfwWindowShouldClose(window))
{
// inputs
processInput(window);
// paint color
glClearColor(.2f, .3f, .3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// draw triangle
glUseProgram(shaderProgram);
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 3);
// final rendering step
glfwSwapBuffers(window);
// check for events
glfwPollEvents();
}
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteProgram(shaderProgram);
glfwTerminate();
return 0;
}
shaderProgram() never returns anything, so the name of your GL program object is just lost, and your shaderProgram local variable contains just some undefined value, hence you never use that program.
Note that such mistakes will be spotted by almost every decent compiler, just enable (and read) the warnings...
I used openGL, GLEW and GLFW3. In openGl 3.0 mesa, the default shader was used and a white triangle was drawn. In 4.2, the screen was left black. No error messages were generated.
The issue is not due to mislabeling of a fragment shader as a vertex shader or vice versa.
The program contains 3 functions:
(1) compileShader, which is supposed to take in shader type and source code as std::string and return a shader ID with compiled code.
(2) createProgram, takes in the source code of a vertex shader and a fragment shader and returns a program ID with the shaders compiled and attached.
(3) And main, where both shader source codes are defined as strings.
Sorry and Thank you.
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <string>
static unsigned int compileShader(unsigned int type, std::string const& sourceCode){
unsigned int shaderId = glCreateShader(type);
const char* source = sourceCode.c_str();
glShaderSource(shaderId, 1, &source, nullptr);
glCompileShader(shaderId);
int result;
glGetShaderiv(shaderId, GL_COMPILE_STATUS, &result);
if (result == GL_FALSE){
if (type == GL_FRAGMENT_SHADER) std::cout<<"Fragment\n";
else std::cout<<"Vertex";
std::cout<<"SHADER COMPILATION FAILED!"<<std::endl;
int logLength;
glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &logLength);
char* infoLog = new char[logLength];
glGetShaderInfoLog(shaderId, logLength, NULL, infoLog);
std::cout<<infoLog<<std::endl;
delete[] infoLog;
glDeleteShader(shaderId);
return 0;
}
return shaderId;
}
static unsigned int createProgram(std::string const& vertexCode, std::string const& fragmentCode){
unsigned int vsId = compileShader(GL_VERTEX_SHADER, vertexCode);
unsigned int fsId = compileShader(GL_FRAGMENT_SHADER, fragmentCode);
unsigned int programId = glCreateProgram();
glAttachShader(programId, vsId);
glAttachShader(programId, fsId);
glLinkProgram(programId);
glValidateProgram(programId);
glDeleteShader(vsId);
glDeleteShader(fsId);
return programId;
}
int main()
{
GLFWwindow* window;
if (!glfwInit())
{
std::cout<<"GLFW initialization failed";
return -1;
}
///switches to opengl 4.2!
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
/* Create a windowed mode window and its OpenGL context */
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window);
glewInit();
std::cout << "OpenGL " << glGetString(GL_VERSION) << "\n" << std::endl;
float positions[6] = {
0.5f, 0.5f,
-0.5f, 0.5f,
0.0f, 0.0f
};
unsigned int buffer = 1;
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(float), positions, GL_STATIC_DRAW);
glEnableVertexAttribArray(0); //enables the xy attrib of position
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), 0); //specifies layout of xy attrib
std::string vertexSource = R"(
#version 330 core
layout(location=0) in vec4 position;
void main(){
gl_Position = position;
}
)";
std::string fragmentSource = R"(
#version 330 core
layout(location=0) out vec4 color;
void main(){
color = vec4(1.0, 0.0, 0.0, 1.0);
}
)";
unsigned int programId = createProgram(vertexSource, fragmentSource);
glUseProgram(programId);
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
/* Render here */
glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(GL_TRIANGLES, 0, 3);
/* Swap front and back buffers */
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
glfwTerminate();
return 0;
}
The issue is not the shader program, but you are using a core profile OpenGL Context (GLFW_OPENGL_CORE_PROFILE). Thus you have to create a named Vertex Array Object. The default VAO (0) is not valid in a core profile context.
Generate vertex array object name by glGenVertexArrays and create and bind the object by glBindVertexArray:
unsigned int vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
unsigned int buffer;
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(float), positions, GL_STATIC_DRAW);
glEnableVertexAttribArray(0); //enables the xy attrib of position
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), 0); //specifies layout of xy attrib
i try to paint simple triangle but i somehow can see the triangle
Here is my files
the window do created but no triangals in it dont know why
#include <iostream>
#include "GLFWManager.h"
#include <stdio.h>
#include <stdlib.h>
int main()
{
std::cout << "Hello World!\n";
GLFWManager gLFWManager;
gLFWManager.Init();
GLuint vbo;
GLuint vao;
GLfloat vertices[] = {
0.0f, 0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
-0.5f, -0.5f, 0.0f,
// second triangle
0.0f, -0.5f, 0.0f, // left
0.9f, -0.5f, 0.0f, // right
0.45f, 0.5f, 0.0f // top
};
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// note that this is allowed, the call to glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind
// glBindBuffer(GL_ARRAY_BUFFER, 0);
// You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other
// VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary.
// glBindVertexArray(0);
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
int shaderProgram = gLFWManager.createShader();
// Set the clear color
glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
while (!glfwWindowShouldClose(gLFWManager.window))
{
glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
// draw our first triangle
glUseProgram(shaderProgram);
glBindVertexArray(vao); // seeing as we only have a single VAO there's no need to bind it every time, but we'll do so to keep things a bit more organized
glDrawArrays(GL_TRIANGLES, 0,6); // set the count to 3 since we're drawing 3 vertices
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
glfwSwapBuffers(gLFWManager.window);
glfwPollEvents();
}
// optional: de-allocate all resources once they've outlived their purpose:
// ------------------------------------------------------------------------
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(1, &vbo);
// glfw: terminate, clearing all previously allocated GLFW resources.
// ------------------------------------------------------------------
}
and this one :
#include "GLFWManager.h"
#include "stdio.h"
#include "stdlib.h"
int GLFWManager::windowHight = 300;
int GLFWManager::windowWidth = 300;
void GLFWManager::errorCallback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
void GLFWManager::windowSizeCallbackcallback(GLFWwindow* window, int width, int height)
{
if (width > 0 && height > 0) {
windowHight = height;
windowWidth = width;
}
}
static void KeyCallback(GLFWwindow* window, int key, int, int action, int mods)
{
switch (key)
{
case GLFW_KEY_ESCAPE:
{
if (action == GLFW_RELEASE)
{
glfwSetWindowShouldClose(window, GLFW_PRESS);
}
}
}
}
GLFWManager::GLFWManager()
{
window = nullptr;
}
GLFWManager::~GLFWManager()
{
}
void GLFWManager::Init()
{
glfwSetErrorCallback(GLFWManager::errorCallback);
if (!glfwInit())
{
exit(EXIT_FAILURE);
}
setWindowsHints();
createWindow();
glfwSetKeyCallback(window, KeyCallback);
glfwSetWindowSizeCallback(window, GLFWManager::windowSizeCallbackcallback);
const GLFWvidmode *vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
glfwSetWindowPos(window, (vidmode->width - windowWidth) /2 , (vidmode->height - windowHight) /2);
glfwGetFramebufferSize(window, &windowWidth, &windowHight);
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
glfwShowWindow(window);
loadGlad();
}
void GLFWManager::setWindowsHints()
{
glfwDefaultWindowHints();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); // the window will stay hidden after creation
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); // the window will be resizable
}
void GLFWManager::createWindow()
{
window = glfwCreateWindow(windowWidth,windowHight, "Test", NULL, NULL);
if (!window)
{
exit(EXIT_FAILURE);
}
}
void GLFWManager::loadGlad()
{
// glad: load all OpenGL function pointers
// ---------------------------------------
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
fprintf(stderr, "Failed to initialize GLAD");
exit(EXIT_FAILURE);
}
// 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);
}
int GLFWManager::createShader()
{
const char* vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 aPos;\n"
"void main()\n"
"{\n"
" gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
"}\0";
const char* fragmentShaderSource = "#version 330 core\n"
"out vec4 FragColor;\n"
"void main()\n"
"{\n"
" FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}\n\0";
// build and compile our shader program
// ------------------------------------
// vertex shader
int vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
// check for shader compile errors
int success;
char infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
printf("ERROR::SHADER::VERTEX::COMPILATION_FAILED\n %s\n ",infoLog);
}
// fragment shader
int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
// check for shader compile errors
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
printf("ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n %s \n",infoLog);
}
// link shaders
int shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
// check for linking errors
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
printf("ERROR::SHADER::PROGRAM::LINKING_FAILED\n %s \n",infoLog);
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
return shaderProgram;
}
glVertexAttribPointer and glEnableVertexAttribArray specify and enable an array of vertex attribute data and sets states in the state vector of the currently bound Vertex Array Object.
You have to bind the vertex array object (glBindVertexArray) before you can specify the vertex arrays:
// Create vertex buffer object
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// Create Vertex array object
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
// specify array of generic vertex array data
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
Note, before you call glVertexAttribPointer, the Vertex Array Object and the Vertex Buffer Object have to be bound, because glVertexAttribPointer associates the buffer which is currently bound to the ARRAY_BUFFER target, to the attribute with the specified index, in the state vector of the currently bound VAO.
I have issue in that the window is displaying the clear color i.e. (Orange) I tried all answers on the web but they didn't seem to help me. I'm using GLFW 3.3 precompiled binaries. I'm using GLAD for OpenGL functions.
The code does not give any errors or warnings and also glGetError() returns 0 at all points of the code.
I've already tried changing the order and gDEBugger gives me error (that is, PRIV_INSTRUCTION) and the VAO and VBO tabs are empty.
Here's my code
#define GLFW_DLL
#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
using namespace std;
static const char* vshSrc = "#version 330 core \n layout (location = 0) in vec3 tPos; void main(){gl_Position = tPos.x, tPos.y, tPos.z;} \0";
static const char* fshSrc = "#version 330 core \n layout (location = 0) out vec4 FragOut; void main(){FragOut = vec4(1.0f,0.4f,0.3f,1.0f);} \0";
/** Processes the input.
*Edit the fuction to add more features. */
void getInput( GLFWwindow *win ){
if(glfwGetKey(win,GLFW_KEY_ESCAPE) == GLFW_PRESS){
glfwSetWindowShouldClose(win,true);
}
}
int main( int argc, char **argv )
{
//Initialization
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,3);
glfwWindowHint(GLFW_OPENGL_PROFILE,GLFW_OPENGL_CORE_PROFILE);
//Make compatible for MacOSX
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT,GL_TRUE);
#endif // __APPLE__
//Window creation
GLFWwindow* window = glfwCreateWindow(640,480,"Illuminati",NULL,NULL);
if (window == NULL)
{
cout << "Window creation failed" << endl;
return -1;
}
//GLAD
glfwMakeContextCurrent(window);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
cout << "GLAD load error." << endl;
return -1;
}
//glViewport( 0, 0, 640, 480);
//==============================================================//
//Shader programs
//Vertex Shader
unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vshSrc, NULL);
glCompileShader(vertexShader);
//Check for compile errors
int compilationSuccesful;
char InfoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &compilationSuccesful);
if ( !compilationSuccesful ){
glGetShaderInfoLog(vertexShader, 512, NULL, InfoLog);
cout << "Vertex Shader compilation Failed. ERROR. \n \n" << InfoLog << endl;
}
//Fragment Shader
unsigned int fragmentShader;
fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fshSrc, NULL);
glCompileShader(fragmentShader);
//error checking for fragment shader
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &compilationSuccesful);
if ( !compilationSuccesful ){
glGetShaderInfoLog(fragmentShader, 512, NULL, InfoLog);
cout << "Fragment Shader compilation Failed. ERROR. \n \n" << InfoLog << endl;
}
//Shader Program
unsigned int shaderProgram;
shaderProgram = glCreateProgram();
//Shader attachments
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
//Checking for link errors
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &compilationSuccesful);
if ( !compilationSuccesful ){
glGetProgramInfoLog(shaderProgram, 512, NULL, InfoLog);
cout << "The program refused to link. ERROR. \n \n" << InfoLog << endl;
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
//----------------------------------------------------------------------------------------------------------//
//Vertex data and elements
float rect[ ] {
/* 0 bottom left*/ -0.5f, -0.5f, 0.0f,
/* 1 top left*/ -0.5, 0.5f, 0.0f,
/* 2 bottom right*/ 0.5f, -0.5f, 0.0f,
/* 3 top right*/ 0.5f, 0.5f, 0.0f
};
unsigned int indices[] {
0,1,2, //first triangle
1,3,2 //second triangle
};
//==============================================================//
//Buffers and VAO
//VAO
unsigned int VAO;
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
//VBO
unsigned int VBO;
glGenBuffers(1,&VBO);
//EBO
unsigned int EBO;
glGenBuffers(1, &EBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(rect), rect, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
//================================================================//
//Vertex Attributes
//glBindVertexArray(0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
//for safety
//glBindBuffer(GL_ARRAY_BUFFER, 0);
//glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
//A useless variable
//unsigned int ui;
//===============================================================//
//Render Loop
while ( !glfwWindowShouldClose(window) )
{
//Clear the buffer
glClearColor(0.9f,0.7f,0.2f,1.0f);
glClear(GL_COLOR_BUFFER_BIT);
////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////DRAWING//////////////////////////////////////////
glBindVertexArray(VAO);
glUseProgram(shaderProgram);
//glDrawArrays(GL_TRIANGLES, 0, 4);
glDrawElements(GL_TRIANGLES,6,GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
//////////////////////////////////////////////END/////////////////////////////////////////////
getInput(window);
glfwSwapBuffers(window);
glfwPollEvents();
}
//Exit and destructors
glfwTerminate();
return 0;
}
//End
/*
__
<( . )____
/_______/
~~~~~~~~~
~~~~~~~~~
*/
In your shader this expression will try to assign the value of tPos.z and only tPos.z to gl_Position
gl_Position = tPos.x, tPos.y, tPos.z;
The reason for that is the semantics of the Comma operator, where all expressions delimited by , are evaluated, but only the result of the very last one is used as the whole expression's R-value.
You probably just want to swizzle it, also you must assign .w:
gl_Position = vec4(tPos.xyz, 1);
I've been following this tutorial in a bid to learn OpenGL. I have something that works, but only if I use global variables:
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
// float vertices[] = {
// -0.5f, -0.5f, 0.0f,
// 0.5f, -0.5f, 0.0f,
// 0.0f, 0.5f, 0.0f
// };
float rectVertices[] = {
0.5f, 0.5f, 0.0f, // Top Right
0.5f, -0.5f, 0.0f, // Bottom Right
-0.5f, -0.5f, 0.0f, // Bottom Left
-0.5f, 0.5f, 0.0f // Top Left
};
uint rectIndices[] = {
0, 1, 3, // First Triangle
1, 2, 3 // Second Triangle
};
const GLchar* vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 position;\n"
"void main() {\n"
"gl_Position = vec4(position.x, position.y, position.z, 1.0);\n"
"}\n";
const GLchar* fragmentShaderSource = "#version 330 core\n"
"out vec4 color;\n"
"void main() {\n"
"color = vec4(1.0, 0.5, 0.2, 1.0);\n"
"}\n";
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) {
if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
}
void finalize() {
glfwTerminate();
}
void programExit(int code) {
finalize();
exit(code);
}
void enforce(int success, const char* msg, const char* info) {
if (!success) {
std::cerr << msg << info << std::endl;
exit(-1);
}
}
// Initialise
// GLFW and OpenGL
void initialiseGLFW(int vMajor, int vMinor) {
// Initialising GLFW
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, vMajor);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, vMinor);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
}
// Window Creation
GLFWwindow* createWindow(int width, int height, const char* title) {
GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", nullptr, nullptr);
enforce(window != nullptr, "Failed to create GLFW window", nullptr);
return window;
}
void initialiseGLEW(bool experimental) {
glewExperimental = experimental;
enforce(glewInit() == GLEW_OK, "Failed to initialise GLEW", nullptr);
}
GLFWwindow* initialise(int width, int height, const char* title) {
initialiseGLFW(3, 3);
// Creating GLFW Window
GLFWwindow* window = createWindow(width, height, title);
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, key_callback);
// Initialising GLEW
initialiseGLEW(true);
glViewport(0, 0, 800, 600);
return window;
}
// Creating Shaders
void checkCompilationError(uint shader) {
int success;
char infoLog[512];
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
glGetShaderInfoLog(shader, 512, nullptr, infoLog);
enforce(success, "Shader compilation error: ", infoLog);
}
void checkLinkingError(uint program) {
int success;
char infoLog[512];
glGetProgramiv(program, GL_LINK_STATUS, &success);
glGetProgramInfoLog(program, 512, nullptr, infoLog);
enforce(success, "Program linking error: ", infoLog);
}
uint compileShader(GLenum type, const char* source, ushort count, int* lengths) {
uint shader = glCreateShader(type);
glShaderSource(shader, count, &source, lengths);
glCompileShader(shader);
checkCompilationError(shader);
return shader;
}
uint createProgram(uint vShader, uint fShader) {
uint program = glCreateProgram();
glAttachShader(program, vShader);
glAttachShader(program, fShader);
glLinkProgram(program);
checkLinkingError(program);
return program;
}
// Subprocedure specific to this program
uint initialiseShaders(const char* vsSource, const char* fsSource) {
// Initialising shaders
uint vShader = compileShader(GL_VERTEX_SHADER, vsSource, 1, nullptr);
uint fShader = compileShader(GL_FRAGMENT_SHADER, fsSource, 1, nullptr);
// Link program
GLuint shaderProgram = createProgram(vShader, fShader);
// clean up
glDeleteShader(vShader);
glDeleteShader(fShader);
return shaderProgram;
}
void configureVBO(float* vertices) {
for (int i = 0; i < 12; i++) std::cout << vertices[i] << std::endl;
glBufferData(
GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW
);
// Tell OpenGL how to interpret the vertices
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*) 0);
glEnableVertexAttribArray(0);
}
void configureEBO(uint* indices) {
for (int i = 0; i < 6; i++) std::cout << indices[i] << std::endl;
glBufferData(
GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW
);
}
uint intialiseVAO(float* vertices, uint* indices) {
uint VAO, VBO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
configureVBO(vertices);
if (indices != nullptr) {
glGenBuffers(1, &EBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
configureEBO(indices);
}
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
return VAO;
}
void execGameLoop(GLFWwindow* window, uint shaderProgram, uint VAO) {
while(!glfwWindowShouldClose(window)) {
glfwPollEvents();
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// Set the program to be used
glUseProgram(shaderProgram);
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
glfwSwapBuffers(window);
}
}
int main() {
// Config
int width = 800, height = 800;
const char* title = "Learn OpenGL";
// Initialise GLFW and GLEW
GLFWwindow* window = initialise(width, height, title);
// Initialise Shader program
uint shaderProgram = initialiseShaders(vertexShaderSource, fragmentShaderSource);
// Configuring VAO, VBO and EBO
uint VAO = intialiseVAO(rectVertices, rectIndices);
execGameLoop(window, shaderProgram, VAO);
finalize();
return 0;
}
My problem is specifically to do with:
void configureVBO(float* vertices) {
for (int i = 0; i < 12; i++) std::cout << vertices[i] << std::endl;
glBufferData(
GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW
);
// Tell OpenGL how to interpret the vertices
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*) 0);
glEnableVertexAttribArray(0);
}
void configureEBO(uint* indices) {
for (int i = 0; i < 6; i++) std::cout << indices[i] << std::endl;
glBufferData(
GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW
);
}
which works as expected when using the rectVertices/Indices global variables, but don't work when they're passed as parameters. The for-loops in each method prints the array, and they contain the values I expect them to. Why does OpenGL draw the rectangle when I use the global variables, but not when I use local parameters?
void configureVBO(float* vertices) {
for (int i = 0; i < 12; i++) std::cout << vertices[i] << std::endl;
glBufferData(
GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW
);
// Tell OpenGL how to interpret the vertices
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*) 0);
glEnableVertexAttribArray(0);
}
The problem here is that sizeof(vertices) is not doing what you think it does. It doesn't tell you how many vertices are in the array -- rather, it's telling you how many bytes a variable of type vertices occupies. Since vertices is a pointer, that number is likely to be either 4 or 8 depending on your system -- but importantly, it has nothing to do with how many vertices you're actually intending to upload.
Instead, what you need to do is tell OpenGL how big you want the buffer to be, in bytes. You calculate that by number of vertices * sizeof(vertex_type). So in your case that would be 12 * sizeof(float).
In general, you'll either need to include a second parameter to the function which includes the number of vertices, or use a std::vector<float> to hold your vertex data instead. For example, with a vector this would become:
void configureVBO(const std::vector<float>& vertices) {
for (auto v : vertices) std::cout << v << "\n";
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(float),
vertices.data(), GL_STATIC_DRAW);
// etc...
}
The reason the code worked when you used a global variable is to do with the way C++ passes arrays to functions (which in turn, it inherited from C). When you pass an array, what the function receives is just a pointer to the start of the array -- the information about the length of the array has been lost, so sizeof(vertices) can't tell you how long the array actually is. However, if you use a global variable, then the compiler can see the definition float vertices[12] even within the configureVBO function, so in that case sizeof() will do what you expect.
This is a very common mix-up for people getting started with C and C++. I'd really recommend using std::vector instead (for many reasons, of which this is just one), but it's also worth reading up on how arrays and pointers work in C and C++.