简体   繁体   中英

OpenGL Drawing with VBO

Iam trying to write a small Opengl program to draw a single triangle using only Vertex Buffer Objects (without using VAO)s but whenever i want to compile it, it only shows a blue screen

Here is my code

#include <iostream>
#include <GLUT/glut.h>
#include <OpenGL/gl3.h>

GLuint VBO;
GLuint VAO;

void display();

float vertex[] = {-1.0, 0.0 , 0.0,
                   0.0 , 1.0 , 0.0 ,
                   1.0 , 0.0 , 0.0 };

int main (int argc, char *argv[])

{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE);
glutInitWindowSize(1000, 400);
glutInitWindowPosition(100, 100);
glutCreateWindow("My First GLUT/OpenGL Window");
glutDisplayFunc(display);
glutMainLoop();
return 0;
}

 void display()

{
glClearColor(0, 0, 1,1);
glClear(GL_COLOR_BUFFER_BIT);

glGenBuffers(1,&VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER,9 *sizeof(vertex),vertex, GL_STATIC_DRAW);

glEnableVertexAttribArray(0);

glVertexAttribPointer(0, 3,GL_FLOAT, GL_TRUE, 0, 0);


glDrawArrays(GL_TRIANGLES, 0, 3);

glDisableVertexAttribArray(0);

glutSwapBuffers();
};

Three problems:

  • Your code misses setting the viewport (if the window happens to be created with a size of 0×0 and gets resized only later the initial viewport size will be 0×0).

  • Your use of the sizeof operator is wrong. vertex is a statically allocated array, and so the sizeof operator will return the total size of the vertex array, nout just the size of a single element. So in that particular case just sizeof(vertex) without multiplying it with 9 would suffice.

And last but not least, and the true cause of your problem:

  • Where are your shaders? Using generic vertex attributes, and of course mandatory by OpenGL-3 you must supply a valid combination of a vertex and fragment shader. Without those, nothing will render.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM