'argc' has abnormal big value while debug in vc++ - c++

I wrote a code in VC++ 2013, and when debugging it, the 'argc' argument of main function gets an abnormal big value. A value higher than 2,000,000,000 always!! But every time has value different from previous run. I checked the 'Command Arguments' field in project properties, it is empty.
How can i solve the problem?
If any more details is needed tell me.
Thanks.
the code:
#include <stdio.h>
#include <stdlib.h>
//for Windows, we use the static version of GLEW
#ifdef _WIN32
#define GLEW_STATIC
#endif
//GLFW and GLEW libraries
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "shader.h" // functions to load shader
//Global variables
GLFWwindow* window;
int main(int argc, char **argv)
{
//Initialize GLFW
if (!glfwInit()){
fprintf(stderr, "Failed to initialize GLFW\n");
exit(EXIT_FAILURE);
}
//enable anti-aliasing 4x with GLFW
glfwWindowHint(GLFW_SAMPLES, 4);
//specify the client API version that the created context must be compatible with.
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
//make the GLFW forward compatible
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
//use the OpenGL Core (http://www.opengl.org/wiki/Core_And_Compatibility_in_Contexts)
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
//create a GLFW windows object
window = glfwCreateWindow(640, 480, "Chapter 4 - GLSL", NULL, NULL);
if (!window){
fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n");
glfwTerminate();
exit(EXIT_FAILURE);
}
//make the context of the specified window current for the calling thread
glfwMakeContextCurrent(window);
glfwSwapInterval(100);
glewExperimental = true; // Needed for core profile
if (glewInit() != GLEW_OK) {
fprintf(stderr, "Final to Initialize GLEW\n");
glfwTerminate();
exit(EXIT_FAILURE);
}
GLuint program = LoadShaders("simple.vert", "simple.frag");
glBindFragDataLocation(program, 0, "color_out");
glUseProgram(program);
// Create Vertex Array Object
GLuint vertex_array;
glGenVertexArrays(1, &vertex_array);
glBindVertexArray(vertex_array);
// Create a Vertex Buffer Object and copy the vertex data to it
GLuint vertex_buffer;
GLuint color_buffer;
glGenBuffers(1, &vertex_buffer);
glGenBuffers(1, &color_buffer);
const GLfloat vertices[] = {
+1.0f, +0.0f, 0.0f,
+1.0f, -1.0f, 0.0f,
+0.0f, -1.0f, 0.0f,
-1.0f, -0.0f, 0.0f,
+0.0f, +1.0f, 0.0f,
-1.0f, +1.0f, 0.0f,
};
const GLfloat colors[] = {
0.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f,
1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
};
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, color_buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors, GL_STATIC_DRAW);
// Specify the layout of the vertex data
GLint position_attrib = glGetAttribLocation(program, "position");
glEnableVertexAttribArray(position_attrib);
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
glVertexAttribPointer(position_attrib, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
GLint color_attrib = glGetAttribLocation(program, "color_in");
glEnableVertexAttribArray(color_attrib);
glBindBuffer(GL_ARRAY_BUFFER, color_buffer);
glVertexAttribPointer(color_attrib, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
while (!glfwWindowShouldClose(window)){
// Clear the screen to black
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// Draw a rectangle from the 2 triangles using 6 vertices
glDrawArrays(GL_TRIANGLES, 0, 24); //draw the square
glfwSwapBuffers(window);
glfwPollEvents();
}
//clear up the memories
glDisableVertexAttribArray(position_attrib);
glDisableVertexAttribArray(color_attrib);
glDeleteBuffers(1, &vertex_buffer);
glDeleteBuffers(1, &color_buffer);
glDeleteVertexArrays(1, &vertex_array);
glDeleteProgram(program);
// Close OpenGL window and terminate GLFW
glfwDestroyWindow(window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
Edit:
I removed pieces of code till reached the following code. Interestingly, if I remove glewExperimental = true; from code, some link error (error LNK2001) rises!
#include <stdio.h>
#include <stdlib.h>
#ifdef _WIN32
#define GLEW_STATIC
#endif
//GLFW library
#include <GL/glew.h>
int main(int argc, char **argv)
{
glewExperimental = true; // Needed for core profile
exit(EXIT_SUCCESS);
}

Related

How to draw two or more triangles in OpenGL?

Can someone show show me how I can modify my code so I can draw more than one triangle?
I'm hoping to accomplish something like the picture shown here:
// Include standard headers
#include <stdio.h>
#include <stdlib.h>
// Include GLEW
#include <GL/glew.h>
// Include GLFW
#include <GLFW/glfw3.h>
GLFWwindow* window;
// Include GLM
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
using namespace glm;
#include <common/shader.hpp>
int main(void)
{
// Initialise GLFW
if (!glfwInit())
{
fprintf(stderr, "Failed to initialize GLFW\n");
getchar();
return -1;
}
glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// Open a window and create its OpenGL context
window = glfwCreateWindow(1024, 768, "Tutorial 04 - Colored Cube", NULL, NULL);
if (window == NULL) {
fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n");
getchar();
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// Initialize GLEW
glewExperimental = true; // Needed for core profile
if (glewInit() != GLEW_OK) {
fprintf(stderr, "Failed to initialize GLEW\n");
getchar();
glfwTerminate();
return -1;
}
// Ensure we can capture the escape key being pressed below
glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
// Dark blue background
glClearColor(0.0f, 0.0f, 0.4f, 0.0f);
// Enable depth test
glEnable(GL_DEPTH_TEST);
// Accept fragment if it closer to the camera than the former one
glDepthFunc(GL_LESS);
GLuint VertexArrayID;
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
// Create and compile our GLSL program from the shaders
GLuint programID = LoadShaders("TransformVertexShader.vertexshader", "ColorFragmentShader.fragmentshader");
// Get a handle for our "MVP" uniform
GLuint MatrixID = glGetUniformLocation(programID, "MVP");
int verticeCount = 3;
static const GLfloat g_vertex_buffer_data[] = {
-0.5f, 0.5f, 0.0f,
0.5f, 0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
};
static const GLfloat g_color_buffer_data[] = {
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
};
GLuint vertexbuffer;
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);
GLuint colorbuffer;
glGenBuffers(1, &colorbuffer);
glBindBuffer(GL_ARRAY_BUFFER, colorbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(g_color_buffer_data), g_color_buffer_data, GL_STATIC_DRAW);
do {
// Clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Use our shader
glUseProgram(programID);
glm::mat4 MVP = glm::mat4(1.0);
// Send our transformation to the currently bound shader,
// in the "MVP" uniform
glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);
// 1rst attribute buffer : vertices
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(
0, // attribute. No particular reason for 0, but must match the layout in the shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// 2nd attribute buffer : colors
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, colorbuffer);
glVertexAttribPointer(
1, // attribute. No particular reason for 1, but must match the layout in the shader.
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// Draw the triangle !
glDrawArrays(GL_TRIANGLES, 0, verticeCount * 3);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
// Swap buffers
glfwSwapBuffers(window);
glfwPollEvents();
} // Check if the ESC key was pressed or the window was closed
while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS &&
glfwWindowShouldClose(window) == 0);
// Cleanup VBO and shader
glDeleteBuffers(1, &vertexbuffer);
glDeleteBuffers(1, &colorbuffer);
glDeleteProgram(programID);
glDeleteVertexArrays(1, &VertexArrayID);
// Close OpenGL window and terminate GLFW
glfwTerminate();
return 0;
}
It's actually right in front of your nose.
Triangles are defined by 3 vertices.
static const GLfloat g_vertex_buffer_data[] = {
-0.5f, 0.5f, 0.0f,
0.5f, 0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
};
Here, you initialized your vertex data array with 3, 3-dimensional vertices. That's 1 triangle.
Adding more triangles, i.e. 3 sets of 3 vertices, to this array is all you need to do, along with extending the g_color_buffer_data array and changing verticeCount accordingly.
So this:
static const GLfloat g_vertex_buffer_data[] = {
-0.50f, +0.50f, +0.00f,
+0.50f, +0.50f, +0.00f,
+0.50f, -0.50f, +0.00f,
-0.50f, -0.25f, +0.00f,
-0.50f, -0.50f, +0.00f,
-0.25f, -0.50f, +0.00f,
};
static const GLfloat g_color_buffer_data[] = {
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
};
would give you 2 triangles: 1 red, 1 blue.
You could also define verticeCount as:
int verticeCount = sizeof(g_vertex_buffer_data) / (sizeof(g_vertex_buffer_data[0]) * 3);
(Thread on finding the size of a C-style array in C++)
This way you won't manually have to change it.
You can always create a new vertex buffer, but it is usually a good idea to implement vertex and fragment shaders instead. If you choose to use shaders, you can draw the buffer, transform the vertex shader, then draw the buffer again. Fragment shaders also provide a better way of specifying color dynamically. You can read more and see some examples at https://learnopengl.com/Getting-started/Shaders

I have converted The Red Book 9ed ex. 3.7 from old functions to 4.5 functions, but it's not displaying anything

For practice purpose, I have converted OpenGL Red Book 9ed ex. 3.7 from "old" functions to 4.5 functions. I have done it before, and it has worked on my system, but this time, it's not displaying anything, just the glClearBufferfv() color. I tried to follow the example to a tee, and I didn't omit anything. I just converted glBufferData() to glNamedBufferStorage(). And a a few other things. Here's the original code as it appears in the book. But let me copy-paste my own code and shaders:
Main.cpp
#include <iostream>
#include <glad/glad.h>
#include <KHR/khrplatform.h>
#include <GLFW/glfw3.h>
#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <SOIL2/SOIL2.h>
#include <Shader.h>
#include <Camera.h>
enum VAO_IDs { Triangles, NumVAOs, ID3 };
enum Buffer_IDs { ArrayBuffer1, ArrayBuffer2, EBOBuffer, NumBuffers
};
enum Attrib_IDs { vPosition = 0, cPosition = 1 };
GLuint VAOs[NumVAOs];
GLuint Buffers[NumBuffers];
const GLuint NumVertices = 6;
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
void init()
{
GLfloat cube_positions[] = {
-1.0f, -1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, 1.0f, 1.0f,
1.0f, -1.0f, -1.0f, 1.0f,
1.0f, -1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f
};
GLfloat cube_colors[] = {
1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 0.0f, 1.0f,
1.0f, 0.0f, 1.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f
};
GLushort cube_indices[] = {
0, 1, 2, 3, 6, 7, 4, 5,
0xFFFF,
2, 6, 0, 4, 1, 5, 3, 7
};
glCreateVertexArrays(NumVAOs, VAOs);
glCreateBuffers(NumBuffers, Buffers);
glNamedBufferStorage(Buffers[ArrayBuffer1], sizeof(cube_positions), cube_positions, GL_ARRAY_BUFFER);
glNamedBufferStorage(Buffers[ArrayBuffer2], sizeof(cube_colors), cube_colors, GL_ARRAY_BUFFER);
glNamedBufferStorage(Buffers[EBOBuffer], sizeof(cube_indices), cube_indices, GL_ELEMENT_ARRAY_BUFFER);
Shader myShader("TirangleVert.glsl", "TriangleFrag.glsl");
myShader.Use();
glBindVertexArray(VAOs[Triangles]);
glBindBuffer(GL_ARRAY_BUFFER, Buffers[ArrayBuffer1]);
glBindBuffer(GL_ARRAY_BUFFER, Buffers[ArrayBuffer2]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Buffers[EBOBuffer]);
glVertexAttribPointer(vPosition, 4, GL_FLOAT, GL_FALSE, 0, 0);
glVertexAttribPointer(cPosition, 4, GL_FLOAT, GL_FALSE, 0, (const GLvoid *) sizeof(cube_positions));
glEnableVertexAttribArray(vPosition);
glEnableVertexAttribArray(cPosition);
}
void display()
{
GLfloat black[] = { 0.2f, 0.5f, 0.6f };
glClearBufferfv(GL_COLOR, 0, black);
glBindVertexArray(VAOs[Triangles]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Buffers[EBOBuffer]);
glLineWidth(20);
glPointSize(20);
glEnable(GL_PRIMITIVE_RESTART);
glPrimitiveRestartIndex(0xFFFF);
glDrawElements(GL_TRIANGLE_STRIP, 17, GL_UNSIGNED_SHORT, NULL);
//glDrawElements(GL_TRIANGLE_STRIP, 8, GL_UNSIGNED_SHORT, NULL);
//glDrawElements(GL_TRIANGLE_STRIP, 8, GL_UNSIGNED_SHORT,
// (const GLvoid *)(9 * sizeof(GLushort)));
}
void dealloc()
{
glDeleteVertexArrays(NumVAOs, VAOs);
glDeleteBuffers(NumBuffers, Buffers);
}
int main()
{
// glfw: initialize and configure
// ------------------------------
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// glfw window creation
// --------------------
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
// glad: load all OpenGL function pointers
// ---------------------------------------
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
init();
// render loop
// -----------
while (!glfwWindowShouldClose(window))
{
// input
// -----
processInput(window);
// render
// ------
display();
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
glfwSwapBuffers(window);
glfwPollEvents();
}
dealloc();
// glfw: terminate, clearing all previously allocated GLFW resources.
// ------------------------------------------------------------------
glfwTerminate();
return 0;
}
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
}
TirangleVert.glsl:
#version 450 core
layout (location = 0) in vec4 cube_pos;
layout (location = 1) in vec4 colors;
out vec4 myColor;
void main()
{
gl_Position = cube_pos;
myColor = colors;
}
TriangleFrag.glsl:
#version 450 core
layout (location = 0) in vec4 myColor;
out vec4 color;
void main()
{
color = myColor;
}
PS: I realize that there's a typo in the name of the vertex shader, but it's all accounted for. Also, there's no problem with Shader.h, as I have used it before with no issues.
Many thanks.
The last parameter of the glNamedBufferStorage is the bitfield, which specifies the intended usage of the buffer's data store, rather than GL_ARRAY_BUFFERor GL_ELEMENT_ARRAY_BUFFER. This will cause a GL_INVALID_VALUE error:
GLbitfield flags = GL_DYNAMIC_STORAGE_BIT | GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT;
glNamedBufferStorage(Buffers[ArrayBuffer1], sizeof(cube_positions), cube_positions, flags);
glNamedBufferStorage(Buffers[ArrayBuffer2], sizeof(cube_colors), cube_colors, flags);
glNamedBufferStorage(Buffers[EBOBuffer], sizeof(cube_indices), cube_indices, flags);
glVertexAttribPointer specifies a vertex array which is refers to the array buffer which is currently bound.
The proper buffer has to be bound by glBindBuffer before glVertexAttribPointer is called. Note, there is only 1 buffer which can be currently bound.
If a buffer is bound, then the last parameter (pointer) is treated as a byte offset into the buffer object's data store. In your case this parameter has to be 0. Note, in a core profile context you have to use an array buffer, a directly addressed memory is not valid.
glBindVertexArray(VAOs[Triangles]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Buffers[EBOBuffer]);
glBindBuffer(GL_ARRAY_BUFFER, Buffers[ArrayBuffer1]);
glVertexAttribPointer(vPosition, 4, GL_FLOAT, GL_FALSE, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, Buffers[ArrayBuffer2]);
glVertexAttribPointer(cPosition, 4, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(vPosition);
glEnableVertexAttribArray(cPosition);

OpenGL - nanogui panel overlay 3d scene

I want to use nanogui in my current project with c++ OpenGL. So I do all the build and linking and get it successfully running. However, It covered over my 3d scene.
My 3D scene is just a quad cover the whole screen, and using fragment shader to do all sort of SDF rendering. Now I want to overlay nanogui on top of the 3d scene.
Below is my code:
int main ()
{
GLFWwindow* window = NULL;
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);
glfwMakeContextCurrent (window);
///nanogui
#if defined(NANOGUI_GLAD)
if (!gladLoadGLLoader((GLADloadproc) glfwGetProcAddress))
throw std::runtime_error("Could not initialize GLAD!");
glGetError();
#endif
glClearColor(0.2f, 0.25f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// Create a nanogui screen and pass the glfw pointer to initialize
screen = new Screen();
screen->initialize(window, true);
glewExperimental = GL_TRUE;
glewInit ();
glViewport(0, 0, screenWidth*2, screenHeight*2);
// Create nanogui gui
bool enabled = true;
FormHelper *gui = new FormHelper(screen);
ref<Window> nanoguiWindow = gui->addWindow(Eigen::Vector2i(10, 10), "Form helper example");
gui->addGroup("Basic types");
gui->addVariable("bool", bvar)->setTooltip("Test tooltip.");
gui->addVariable("string", strval);
... //all the nanogui setup code
gui->addButton("A button", []() { std::cout << "Button pressed." << std::endl; })->setTooltip("Testing a much longer tooltip, that will wrap around to new lines multiple times.");;
screen->setVisible(true);
screen->performLayout();
nanoguiWindow->center();
glfwSetKeyCallback(window, key_callback);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetScrollCallback(window, scroll_callback);
glEnable (GL_DEPTH_TEST);
glDepthFunc (GL_LESS);
Shader ourShader("vertex_shader.glsl", "fragment_shader.glsl");
GLint positionLocation = glGetAttribLocation(ourShader.Program, "a_position");
GLint resolutionloc = glGetUniformLocation(ourShader.Program, "resolution");
ourShader.Use();
glUniform2f(resolutionloc, (GLfloat)screenWidth*2, (GLfloat)screenHeight*2);
GLint mouseLocation = glGetUniformLocation(ourShader.Program, "mouse");
// glUniform2f(mouseLocation,firstMouse.);
GLfloat vertices[] = {
-1.0f, -1.0f,
1.0f, -1.0f,
-1.0f, 1.0f,
-1.0f, 1.0f,
1.0f, -1.0f,
1.0f, 1.0f // Top Left
};
GLuint VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
// Game loop
while (!glfwWindowShouldClose(window))
{
glfwPollEvents();
// Clear the colorbuffer
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 6);
glBindVertexArray(0);
screen->drawContents();
screen->drawWidgets();
glfwSwapBuffers(window);
}
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glfwTerminate();
return 0;
}
With this, I only see the nanogui overlay with background. I am not sure how to render both of them together.
How can I resolve this? I am rather new to OpenGL so I am not sure what happen here. But I suspect is something to do with frame buffer or something like that.

C++ OpenGL Color at each Vertex not drawn

I'm very new to OpenGL and at the moment I'm trying to understand VAO and VBO.
The VAO is simply a collection of VBO.
Each VBO is an attribute of an object, coordinates of vertices of the object, color at each object's vertex, etc.
In the code below, the Vertex struct define 2 properties of a vertex, which is position and color of the vertex. Therefore, 2 VBOs are needed to store these information.
My problem is: I'm able to draw the triangle on the screen, but the color at each vertex doesn't seem to be drawn. Why does this happen?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
// create vertex buffer
GLuint vertexbuffer;
struct Vertex{
GLdouble position[3];
GLfloat color[3];
};
static const GLfloat vertex_data[] = {
-0.7f, -0.7f, 0.0f,
0.7f, -0.7f, 0.0f,
0.0f, 1.0f, 0.0f
};
void SetupGeometry(){
const struct Vertex triangle[3] = {
{{-0.7, -0.7, 0.0}, {1.0f, 0.0f, 0.0f}},
{{0.7, -0.7, 0.0}, {0.0f, 1.0f, 0.0f}},
{{0.0, 1.0, 0.0}, {0.0f, 0.0f, 1.0f}}
};
//GLuint VertexArrayID;
//glGenVertexArrays(1, &VertexArrayID);
//glBindVertexArray(VertexArrayID);
//generate 1 buffer, put the resulting identifier in vertex buffer
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
// give our vertices to OpenGL
glBufferData(GL_ARRAY_BUFFER, 3*sizeof(struct Vertex), triangle, GL_STATIC_DRAW);
// GLuint index, GLuint size, GLenum type, GLboolean normalized, GLsizei stride, const void *offset
glVertexAttribPointer(0, 3, GL_DOUBLE, GL_FALSE, sizeof(struct Vertex), (void*) offsetof(struct Vertex, position));
// any newly created VAO disables array access for all attributes
// array access is enabled by binding the VAO in SetupGeometry and calling:
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(struct Vertex), (void*) offsetof(struct Vertex, color));
glEnableVertexAttribArray(1);
}
void SetupShaders(void){
}
void Render(int i){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDrawArrays(GL_LINE_LOOP, 0, 3);
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods){
if((key == GLFW_KEY_ESCAPE || key == GLFW_KEY_Q) && action != GLFW_PRESS){
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
int main( void ) {
/* Create a windowed mode window and its OpenGL context */
GLFWwindow* window;
if( !glfwInit() ) {
printf("Failed to start GLFW\n");
exit( EXIT_FAILURE );
}
window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
if (!window) {
glfwTerminate();
printf("GLFW Failed to start\n");
return -1;
}
/* Make the window's context current */
glfwMakeContextCurrent(window); // IMPORTANT: Must be done so glew recognises OpenGL
glfwWindowHint(GLFW_SAMPLES, 4);
int err = glewInit();
if (glewInit() != GLEW_OK) {
/* Problem: glewInit failed, something is seriously wrong. */
fprintf(stderr, "Error initializing GLEW: %s\n", glewGetErrorString(err));
}
fprintf(stderr, "Glew done\n");
fprintf(stderr, "GL VERSION INFO %s\n", glGetString(GL_VERSION));
glfwSetKeyCallback(window, key_callback);
SetupGeometry();
while(!glfwWindowShouldClose(window)){
Render(0);
glfwSwapBuffers(window);
glfwPollEvents();
}
}
You don't seem to have included any shaders. You'll need to use a fragment shader to set the colour values for the triangle. This link should help you.

openGL Unhandled exception on glDrawArrays(GL_TRIANGLES, 0, model.indicesCount); call

So I'm trying to write a simple 3D rendering engine using GLFW and GLEW in C++. However the program crashes on glDrawArrays(GL_TRIANGLES, 0, model.indicesCount); call. I'm pretty sure I'm doing something wrong but I can't figure out where or what needs to be changed/altered. I'm actually rewriting a perfectly working engine from Java.
My code:
common.h:
#ifndef _COMMON
#define _COMMON
// standard stuff
#include <iostream>
#include <list>
// openGL stuff
#include "GL\glew.h"
#include "GLFW\glfw3.h"
// my stuff
#include "DisplayManager.h"
#include "RawModel.h"
#include "Loader.h"
#include "Renderer.h"
#endif
DisplayManager.h:
#pragma once
#include "common.h"
class DisplayManager{
private:
GLFWwindow* window;
public:
void create(int width = 1280, int height = 720, std::string title = "Untitled"){
if(!glfwInit()){
std::cerr << "GLFW init failed\n";
system("pause");
exit(EXIT_FAILURE);
}
glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
window = glfwCreateWindow(width, height, title.c_str(), NULL, NULL);
glfwMakeContextCurrent(window);
if(!window){
std::cerr << "Failed to create a window\n";
system("pause");
exit(EXIT_FAILURE);
}
glewExperimental = GL_TRUE;
if(glewInit() != GLEW_OK){
std::cerr << "GLEW init failed\n";
system("pause");
glfwTerminate();
exit(EXIT_FAILURE);
}
}
void update(){
glfwSwapBuffers(window);
glfwPollEvents();
}
int isCloseRequested(){
return glfwWindowShouldClose(window);
}
void close(){
glfwDestroyWindow(window);
glfwTerminate();
}
};
RawModel.h:
#pragma once
struct RawModel{
public:
GLuint vaoID;
GLuint indicesCount;
RawModel(GLuint vaoID, GLuint indicesCount){
this->vaoID = vaoID;
this->indicesCount = indicesCount;
}
};
Loader.h:
#pragma once
#include "common.h"
#define VERTEX_ATTRIB_INDEX 0
#define VERTEX_SIZE 3
class Loader{
public:
// functions
RawModel loadModel(const GLfloat vertices[], GLuint verticesCount){
GLuint vaoID = createAndBindVao();
storeFloatDataInVAO(VERTEX_ATTRIB_INDEX, vertices, verticesCount, VERTEX_SIZE);
unbindVAO();
return RawModel(vaoID, verticesCount);
}
void cleanUp(){
std::list<GLuint>::iterator vao_it = vaos.begin();
for(; vao_it != vaos.end(); ++vao_it){
const GLuint vao = *vao_it;
glDeleteVertexArrays(1, &vao);
}
std::list<GLuint>::iterator vbo_it = vbos.begin();
for(; vbo_it != vbos.end(); ++vbo_it){
const GLuint vbo = *vbo_it;
glDeleteBuffers(1, &vbo);
}
}
private:
// variables
std::list<GLuint> vaos;
std::list<GLuint> vbos;
// functions
GLuint createAndBindVao(){
GLuint vaoID;
glGenVertexArrays(1, &vaoID);
vaos.push_back(vaoID);
glBindVertexArray(vaoID);
return vaoID;
}
void storeFloatDataInVAO(const GLuint attributeIndex, const GLfloat data[], const GLuint dataLength, const GLuint chunkSize){
GLuint vboID;
glGenBuffers(1, &vboID);
vbos.push_back(vboID);
glBindBuffer(GL_VERTEX_ARRAY, vboID);
glBufferData(GL_VERTEX_ARRAY, sizeof(GLfloat) * dataLength * chunkSize, data, GL_STATIC_DRAW);
glVertexAttribPointer(attributeIndex, chunkSize, GL_FLOAT, GL_FALSE, 0, (void*)0);
glBindBuffer(GL_VERTEX_ARRAY, 0);
}
void unbindVAO(){
glBindVertexArray(0);
}
};
Renderer.h:
#pragma once
#include "common.h"
#define BLACK 0.0f, 0.0f, 0.0f, 1.0f
#define WHITE 1.0f, 1.0f, 1.0f, 1.0f
#define RED 1.0f, 0.0f, 0.0f, 1.0f
#define GREEN 0.0f, 1.0f, 0.0f, 1.0f
#define BLUE 0.0f, 0.0f, 1.0f, 1.0f
#define YELLOW 1.0f, 1.0f, 0.0f, 1.0f
class Renderer{
public:
void prepare(){
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(YELLOW);
};
void render(RawModel model){
glBindVertexArray(model.vaoID);
glEnableVertexAttribArray(VERTEX_ATTRIB_INDEX);
glDrawArrays(GL_TRIANGLES, 0, model.indicesCount);
glDisableVertexAttribArray(VERTEX_ATTRIB_INDEX);
glBindVertexArray(0);
}
};
and the Source.cpp with the main function:
#include "common.h"
static const GLfloat VERTICES[] = {
// X Y Z
-0.5f, 0.5f, 0,
-0.5f, -0.5f, 0,
0.5f, 0.5f, 0
};
int main(){
DisplayManager display;
display.create();
Loader loader;
RawModel model = loader.loadModel(VERTICES, 3);
Renderer renderer;
// main loop
while(!display.isCloseRequested()){
renderer.prepare();
renderer.render(model);
display.update();
}
loader.cleanUp();
display.close();
return EXIT_SUCCESS;
}
If I comment out the glDrawArrays(GL_TRIANGLES, 0, model.indicesCount); it seams to be working and I get a green window.
The error is here:
glBindBuffer(GL_VERTEX_ARRAY, vboID);
glBufferData(GL_VERTEX_ARRAY, sizeof(GLfloat) * dataLength * chunkSize, data, GL_STATIC_DRAW);
glVertexAttribPointer(attributeIndex, chunkSize, GL_FLOAT, GL_FALSE, 0, (void*)0);
glBindBuffer(GL_VERTEX_ARRAY, 0);
GL_VERTEX_ARRAY is not a valid buffer target in OpenGL, the correct one is GL_ARRAY_BUFFER. As a consequence, these commands all should generate a GL error. The attrib pointer function will should generate GL_INVALID_OPERATION, since no GL_ARRAY_BUFFER is bound at the time of the call, the others should just generate GL_INVALID_ENUM. Now you have basically an uninitialized vertex attribute pointer, you later enable that attribute array and try to draw from it, resulting in the crash.
Another thing: I don't see any shaders in your code. Shaders are mandatory in the core profile, which you use. Now glDrawElements() actually should fail, although some implementors ignore that and use some trivial shaders in that scenario.