Search code examples
c++openglglm-mathwavefront

Calculate indices from a vector of vec3 objects by finding duplicate vertices


I am trying to build an .obj file importer that renders said model to the screen. At present I have imported the vertices and they are stored in a

std::vector<vec3> vertices;

My renderer class quite large so I'll link github instead of posting it here.

https://github.com/rob-DEV/OpenGL-Model-Viewer/blob/master/OpenGL-Model-Viewer/src/graphics/renderer/renderer.cpp

So at line 41 in renderer.cpp. I submit these vertexs to the renderer. Originally I just drew triangles, but I would like to take advantage of GL_ELEMENTS

My question is how (if possible) can I calculate these indices from a list of vertices? I have tried to find duplicates and do so when the model is loaded but i don't know how to map them.


Solution

  • Using mapped buffers (by glMapBuffer) does not work in your case.

    For example, if you want to know if a vertex has been already mapped (a duplicate) you should read all of currently mapped vertices, which is slow.
    If you want to use a sorted array (so fast binary search can be used) then many portions of that mapped buffer must be re-written during the sorting/storing process. Slow too.

    A better option is to build your sorted vertices array on your own, on normal RAM. Be adviced of searching issues due to numerical matters when comparing two floats.

    On a second pass each index is just the position of the current vertex. Same advice for numerical issues.

    Data can be sent to the GPU by two simple glBufferSubData, one for vertices (and their colors and normals and etc) and another one for the indices.

    If the object moves (and you prefer to update coordinates instead of use a translation matrix) then it's right to use a mapped buffer with new coordinates (as you currently do). Indices don't change, so they don't need to be updated.