iosswiftopengl-esvertexvertex-array

OpenGL ES: Do vertex structs need x, y, AND z?


This is probably a stupid question, but I've been wondering it - do vertex structs in OpenGL NEED to have x, y and z? I'm drawing in 2D, yet all the tutorials I've seen seem to have a z variable in their struct even though it's always 0. Doesn't this slow down rendering or something?

Also, they always seem to have r, g, b and a for the color variables, but I don't require the alpha since it'll always be 1 for my project. Do I really need to say it's 1 every single time?

I'm just wondering since glVertexAttribPointer lets you set the second parameter to be anything, and I tried setting it to 2 since I'm only using x and y, and it worked.


Solution

  • From the spec section 2.8:

    If size is one then the x component of the attribute is specified by the array; the y, z, and w components are implicitly set to zero, zero, and one, respectively. If size is two then the x and y components of the attribute are specified by the array; the z , and w components are implicitly set to zero, and one, respectively. If size is three then x, y, and z are specified, and w is implicitly set to one. If size is four then all components are specified.

    So if you don't define z or w for your 2D vertices. The vertex assembler automatically fills them with z=0,w=1. Your code is safe and correct.

    RGBA is the same as XYZW, so you don't have to specify alpha for colour components either assuming you want alpha to be 1.

    Performance-wise you should generally expect a win by using smaller vertex components because less data has to be moved around and copied to the GPU. I would expect any performance gain to be tiny and probably unmeasurable.

    One exception is that if you shave a few bytes off a vertex and reduce it say from a nice cache friendly 16-bytes per vertex to 12-bytes per vertex, you might reduce performance slightly because 8, 16, 32 byte sizes are a bit of a magic number as far as memory accesses go. Again, any performance loss here will be minute, so I wouldn't let it trouble you.