0
\$\begingroup\$

Instead of using a vector of floats, i want to use a struct, so that it can store different types and is easier.

struct QuadVertex
{
    glm::vec3 Position;
    glm::vec4 Color;
    glm::vec2 TexCoord;
    int TexIndex;
};

But if i use this structure in a vertex buffer, c++ could use padding or alignment in the structure and openl wouldnt get the expected data. How can i safely use this structure to store vertices, and how should i modify the vertex attributes correctly?

\$\endgroup\$
3
  • \$\begingroup\$ If that was Delphi I would say to use "packed" records. C++ must have something like that too. \$\endgroup\$ Commented Jan 22, 2023 at 10:41
  • 2
    \$\begingroup\$ What about this? learn.microsoft.com/en-us/cpp/cpp/… \$\endgroup\$ Commented Jan 22, 2023 at 11:34
  • 1
    \$\begingroup\$ The other option would be to tell opengl the correct stride. \$\endgroup\$ Commented Jan 22, 2023 at 17:18

1 Answer 1

2
\$\begingroup\$

Use sizeof and offsetof.

Specifically, when setting up your vertex format and pointers in code, using sizeof for the stride in your glVertexAttribPointer calls will cause OpenGL to correctly set things up such that each vertex properly begins at the start of each new struct in your array.

Similarly, using offsetof for the position of each attribute will cause OpenGL to correctly retrieve each attribute from it's correct location in the struct.

This will work irrespective of padding or alignment, and will be portable across different architectures and compilers where these might differ. (Loading the data correctly into the structs is another issue, of course.)

\$\endgroup\$
2
  • \$\begingroup\$ But i have an abstracted class VertexLayout which i use like vb.setlayout({vec3, vec3}). i \$\endgroup\$ Commented Jan 24, 2023 at 14:13
  • \$\begingroup\$ @ihsan - that seems like a "you problem" more than anything else. The API has been designed to be used a particular way. Use it that way. If you can't or won't, that's not the API's fault. \$\endgroup\$ Commented Jan 24, 2023 at 23:58

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.