Home > Net >  c opengl 4.5 doesn't show the object
c opengl 4.5 doesn't show the object

Time:11-22

I writed code which must to show triangle but it doesn't. I really don't know where is problem. I checked everything and don't find out what is the problem. If you can please help me.

Here is code:

#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm.hpp>

int width = 800, height = 600;

int main() {

    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    GLFWwindow* window = glfwCreateWindow(width, height, "engine", NULL, NULL);
    glfwMakeContextCurrent(window);

    gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);

    glViewport(0, 0, width, height);

    const char* VertexShaderData = "#version 450 core\n"
        "layout(location = 0) in vec2 pos;\n"
        "void main(){\n"
        "gl_Position = vec4(pos, 0, 1);\n"
        "}\0";

    GLuint VertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(VertexShader, 1, &VertexShaderData, NULL);
    glCompileShader(VertexShader);

    const char* FragmentShaderData = "#version 450 core\n"
        "out vec4 Color;\n"
        "void main(){\n"
        "Color = vec4(0.25, 0.8, 0.65, 1);\n"
        "}\0";

    GLuint FragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(FragmentShader, 1, &FragmentShaderData, NULL);
    glCompileShader(FragmentShader);

    GLuint ShaderProgram = glCreateProgram();
    glAttachShader(ShaderProgram, VertexShader);
    glAttachShader(ShaderProgram, FragmentShader);
    glLinkProgram(ShaderProgram);

    float Points[] = { -1, -1, 0, 1, 1, -1 };
    
    GLuint VAO, VBO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);

    glBindVertexArray(VAO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);

    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2*sizeof(float), (void*)0);
    glBufferData(GL_ARRAY_BUFFER, 6, Points, GL_STATIC_DRAW);

    glClearColor(0.3, 0.5, 0.7, 1);

    while (!glfwWindowShouldClose(window)) {
        glfwSwapBuffers(window);

        glClear(GL_COLOR_BUFFER_BIT);

        glBindVertexArray(VAO);
        glEnableVertexAttribArray(0);
        glUseProgram(ShaderProgram);

        glDrawArrays(GL_TRIANGLES, 0, 3);
    }
}

Before I was believe what problem is in array, but now i don't think so. Problem is must be in something else.

CodePudding user response:

The 2nd argument to glBufferData is the size of the buffer in bytes:

glBufferData(GL_ARRAY_BUFFER, 6, Points, GL_STATIC_DRAW);

glBufferData(GL_ARRAY_BUFFER, 6*sizeof(float), Points, GL_STATIC_DRAW);
  • Related