Hello :), This is a really noob question, I just started learning opengl yesterday. I was just trying to create a basic shape, the program compiles but gives some windows error in runtime. I have no clue whats wrong in the program, please check it out and tell me whats wrong and how to fix it? Is something wrong with my shaders?
#include <GL\glew.h>
#include <GLFW\glfw3.h>
#include <iostream>
#include <cstdio>
int main()
{
if (!glfwInit())
throw std::runtime_error("Cannot Initialize GLFW3");
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
GLFWwindow *window = glfwCreateWindow(800, 600, "OpenGL", NULL, NULL);
if (!window)
throw std::runtime_error("Cannot create Window.");
glfwMakeContextCurrent(window);
glewExperimental = GL_TRUE;
glewInit();
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
float verts[] =
{
0.0f, 0.3f, 0.0f,
0.3f, -0.3f, 0.0f,
-0.3f, -0.3f, 0.0f
};
GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(verts), &verts, GL_STATIC_DRAW);
GLuint vao;
glGenBuffers(1, &vao);
glBindVertexArray(vao);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vbo); //Use vertex buffer as the second argument, not vertex array obj.
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
const char *vs =
"#version 400"
"in vec3 vp;"
"void main() {"
"gl_Position = vec4(vp, 1.0);"
"}";
const char *fs =
"#version 400"
"out vec4 outColor;"
"void main() {"
"outColor = vec4(0.5, 0.0, 0.4, 1.0);"
"}";
GLint stat;
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vs, NULL);
glCompileShader(vertexShader);
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &stat);
if (!stat)
throw std::runtime_error("Vertex shader compile failed.");
GLuint fragShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragShader, 1, &fs, NULL);
glCompileShader(vertexShader);
glGetShaderiv(fragShader, GL_COMPILE_STATUS, &stat);
if (!stat)
throw std::runtime_error("Frag Shader compile failed.");
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragShader);
glLinkProgram(shaderProgram);
while (!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(shaderProgram);
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES, 0, 3);
glfwPollEvents();
glfwSwapBuffers(window);
}
glfwTerminate();
return 0;
}
EDIT: The program is working when used printf function instead of throw std::runtime_error(), but there is no color in the triangle, any ideas why??
EDIT2: I’m also getting the Vertex Shader and Fragment Shader compile messages, but there is a White triangle visible in the window. What is wrong in my shaders or code ???