简体   繁体   English

OpenGL顶点数组初始化

[英]OpenGL vertices array initialisation

I have a question about OpenGL 3.0, why am I unable to draw anything when my array of vertices in initialized as 我有一个关于OpenGL 3.0的问题,当我的顶点数组初始化为时,为什么为什么我无法绘制任何内容?

float * vertices;
int size = 100; // size of the vertices array
float * vertices = (float *) malloc (size*sizeof(float));

I have allocated memory, and initialized all the values in the array to 0.0, but it looks like my vertex buffer reads only the first element of the vertices array. 我已经分配了内存,并将数组中的所有值初始化为0.0,但是看来我的顶点缓冲区仅读取了顶点数组的第一个元素。 Whereas when I initialize the array like this : 而当我像这样初始化数组时:

float vertices[size];

all the vertices are read and rendered as expected. 所有顶点均按预期方式读取并渲染。

Here is how I specify my vertex buffer, and pass data to the buffer : 这是我指定顶点缓冲区并将数据传递到缓冲区的方法:

unsigned int VBO;
glGenBuffers(1, &VBO);

glBindBuffer(GL_ARRAY_BUFFER, VBO);

glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STREAM_DRAW);

GLint posAttrib = glGetAttribLocation(ourShader.ID, "aPos");

// iterpreting data from buffer 
glVertexAttribPointer(posAttrib, 3, GL_FLOAT, GL_FALSE, 3* sizeof(float), (void*)0);
glEnableVertexAttribArray(0);

sizeof doesn't do what you expect it to do. sizeof不执行您期望的操作。 sizeof(x) returns the size of the data type of the variable x . sizeof(x)返回变量x的数据类型的大小。

In case of int size = 100; 如果int size = 100; float vertices[size]; the data type of vertices is float[100] and sizeof(vertices) returns the same as sizeof(float)*100 . vertices的数据类型为float[100]sizeof(vertices)返回的sizeof(float)*100sizeof(float)*100

In case of float * vertices; float * vertices;情况下float * vertices; , the data type of vertices is float* and sizeof(vertices) returns the size of the pointer data type, which points to the dynamically allocated array, but it does not return the size of the dynamic memory or even the number of elements of the allocated array. vertices的数据类型为float*sizeof(vertices)返回指针数据类型的大小,该指针数据类型指向动态分配的数组,但返回动态内存的大小,甚至返回数组的元素数分配的数组。 The size of the pointer depends on the hardware and is the same as sizeof(void*) (usually it is 4 or 8). 指针的大小取决于硬件,并且与sizeof(void*) (通常为4或8)。

sizeof(float) * size would work in both of the cases of the question: sizeof(float) * size在以下两种情况下均有效:

glBufferData(GL_ARRAY_BUFFER, sizeof(float)*size, vertices, GL_STREAM_DRAW);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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