Pergunta

OpenGL has functions such as BufferData(int array[]) where array must be of the format x-y-z x-y-z ....

It is simply a sequence of integers where each consecutive 3-tuple is interpreted as a vertex.

Is it safe to represent this as an std::vector, where vertex is declared as:

struct vertex
{
  int x, y, z;
};

This would make it semantically more clear what is happening, in my opinion. However, is it possible to guarantee that this would work?

If it is not, is there any other way to provide a more semantic representation of the data?

Foi útil?

Solução

It may work but it will not be reliable - there could be unnamed padding between the structure members so you cannot guarantee that they are aligned correctly

What is wrong with just using std::vector - this memory is guaranteed by the standard to be correct aligned and sequential.

For example you can use:

std::vector<int> cord(3,0);
BufferData(&cord[0]);

[Edit] Mooing Duck pointer out it takes more than 1 set of 3, - so in that case just extend the vector

3 tuples of 3 ints

std::vector<int> cord(9,0);
BufferData(&cord[0]);

Outras dicas

The struct memory can be packed using compile instruction

#pragma pack(push,1)
struct vertex
{
int x,y,z;
};
#pragma pack(pop,1)

The vector stores the data continuously, which can be verified using the following simple program:

#include <iostream>
#include <vector>

using namespace std;
#pragma pack(push,1)
struct vtx
{
    int x,y,z;
};
#pragma pack(pop,1)

main()
{
    vector<vtx> v(3);
    v[0].x=v[0].y=v[0].z=1;
    v[1].x=v[1].y=v[1].z=2;
    v[2].x=v[2].y=v[2].z=3;
    int *p=&v[0].x;
    for(int i=0;i<9;i++) cout<<*p++<<endl;
}

The output would be: 1 1 1 2 2 2 3 3 3

So the answer is yes.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top