• Advertisement
Sign in to follow this  

OpenGL Efficient data packing

This topic is 1639 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi everyone I just had a few questions about OpenGL and performance.

 

I made a very simple 2D particle system, all the particles get attracted to a fixed point using gravitational attraction equations, so nothing too intensive.

 

For my data I used structs and packed it into a single buffer.

 typedef struct particle
    {
        GLfloat age;
        GLfloat pos[2];
        GLfloat vel[2];
        GLfloat col[3];

        void setPosition(float x, float y)
        {
            pos[0] = x;
            pos[1] = y;
        }

        void setColour(GLfloat r, GLfloat g, GLfloat b)
        {
            col[0] = r;
            col[1] = g;
            col[2] = b;
        }

        void setVelocity(GLfloat x, GLfloat y)
        {
            vel[0] = x;
            vel[1] = y;
        }

    }particle;

 I store the particles in a vector

 m_particles.resize(n);
 std::vector<particle>::iterator it;
    for(it = m_particles.begin(); it < m_particles.end(); ++it)
    {
       /// set position etc..

    }

Then the usual generating, binding and drawing vertex arrays code. All the calculations are done on CPU and I could get about 250,000 particles with good framerate.

 

 

Now to clean up the code and add more functionality, I decided to make a particle class.

class particle
{
public:

    particle(glm::vec3 _pos, glm::vec3 _vel, glm::vec3 _col, float _mass);
    ~particle();

    glm::vec3 getPosition()
    {
        return m_position;
    }

    glm::vec3 getVelocity()
    {
        return m_velocity;
    }

    void setColour(float _r,float  _g, float _b)
    {
        m_colour.x = _r;
        m_colour.y = _g;
        m_colour.z = _b;
    }


private:

    glm::vec3 m_position;
    glm::vec3 m_velocity;
    glm::vec3 m_colour;
    glm::vec3 m_force;
    glm::vec3 m_acceleration;

    float m_mass;
 

};

Then storing particles in a vector

 m_particles.reserve(n); ////////resize crashed the program so used reserve instead

    for(int i=0; i<n; ++i)
    {
        ///setting random values for each param
        particle p = particle(pos,vel,col, mass);
        m_particles.push_back(p);
    }

All the other code stays the same and I only needed to change the pointers to point to the correct offset in the buffer etc...

 

glVertexAttribPointer(col, 3, GL_FLOAT, GL_TRUE, sizeof(particle), (GLvoid *)NULL + (6*4)); //colour data

 

With this system I could only get about 80,000 particles with similar framerate and I kinda confused why.

 

There is extra private members in the class like force and acceleration that get passed into the single buffer but I removed them and still no difference. But is it ok if I leave that data in the buffer even if I never use it on the gpu side?

 

Should I always use structs for passing data to opengl?

 

My vector container holds the object:

std::vector<particle> m_particles;

 

I tried making it a pointer to the object but then I couldn't correctly pass the data to opengl. It would draw garbage, would making it a pointer even help in performance?

std::vector<particle *> m_particles;

 

Also I am using one buffer, is it better to split the buffers up so like a separate buffer for position,velocity,colour etc... 

 

Sorry for lots of questions I have tried researching but my problem is not a common error.

 

Thanks for your time.

 

Share this post


Link to post
Share on other sites
Advertisement
The change from
struct particle
to
class particle
doesn't make any difference. Making the data members into classes
glm::vec3 m_position;
would take some more storage space. And when you have all your data interleaved like this, iterating over the lot takes longer when there is more space between them since
sizeof(particle)
is larger.

You could probably increase performance by storing the positions separately from the other stuff, then drawing them would be more cache-friendly (look up 'data oriented design'). But the code would be less clear. Tradeoff time - maybe time to assess what parts are most critical for your program.

Share this post


Link to post
Share on other sites
One candidate for the slowdown is all that copying around of vector classes you are doing. Consider passing all those glm::vec3 by const reference (i.e. const glm::vec3 &v).

Another potential for slowdown is that the size of your class has grown significantly, since you started with 4 floats to represent position/velocity, and ended with 12 floats to represent position/velocity/acceleration/force. That takes you from 32 bytes per particle to 64 bytes - you've basically doubled the pressure on your cache.

Share this post


Link to post
Share on other sites

The change from

struct particle
to
class particle
doesn't make any difference. Making the data members into classes
glm::vec3 m_position;
would take some more storage space. And when you have all your data interleaved like this, iterating over the lot takes longer when there is more space between them since
sizeof(particle)
is larger.

You could probably increase performance by storing the positions separately from the other stuff, then drawing them would be more cache-friendly (look up 'data oriented design'). But the code would be less clear. Tradeoff time - maybe time to assess what parts are most critical for your program.

 

 

I'll try splitting the buffer and see what happens, but just curious about something.

Every single example/tutorial I have seen always stores the object in a vector but never a pointer to that object, why is that?

std::vector<particle *> /////////<--------------------------- would this make no performance difference.

 

 

One candidate for the slowdown is all that copying around of vector classes you are doing. Consider passing all those glm::vec3 by const reference (i.e. const glm::vec3 &v).

Another potential for slowdown is that the size of your class has grown significantly, since you started with 4 floats to represent position/velocity, and ended with 12 floats to represent position/velocity/acceleration/force. That takes you from 32 bytes per particle to 64 bytes - you've basically doubled the pressure on your cache.

 

Thanks for that, I am now passing all glm::vec3 by const reference and even did it for the floats. It managed to get like 3 frames per second more, nothing major but still better than nothing lol.

Share this post


Link to post
Share on other sites

I'll try splitting the buffer and see what happens, but just curious about something.
Every single example/tutorial I have seen always stores the object in a vector but never a pointer to that object, why is that?
std::vector<particle *> /////////<--------------------------- would this make no performance difference.

That might be more convenient if you want to have multiple lists of different particles (i.e. render all the 'fire' particles together in one way, all the 'water' ones together in a different way, but still simulate them all together in the same way). However, then they aren't necessarily consecutive in memory and you can't do your call to
glVertexAttribPointer(col, 3, GL_FLOAT, GL_TRUE, sizeof(particle), (GLvoid *)NULL + (6*4));
which incidentally looks dubious to me - the value of 6*4 might not work if a compiler does struct member packing differently, or you change the code later on.

If it's really performance-critical, I'd split out the positions into a float array, so it can be passed to GL in a simple, reliable way and store a pointer to the relevant index into this array within each instance of the particle class. All the other stuff I'd leave nice and tidy, wrapped up in particle.

Share this post


Link to post
Share on other sites

I tried making it a pointer to the object but then I couldn't correctly pass the data to opengl. It would draw garbage, would making it a pointer even help in performance?
std::vector<particle *> m_particles;


As you say doing this won't work as you want it to because all you are passing to OpenGL (if you pass this data) is a list of address values which OpenGL can't do anything with thus the garbage.

This would also slow down the simulation aspect as, instead of nice cache friendly (well, reasonably friendly, but I'll come to that) data for the CPU to chew on you instead require the CPU to fetch data from another location before working on it and do so for every single particle. This is likely to cause masses of cache misses and destroy your performance in the process.

Also I am using one buffer, is it better to split the buffers up so like a separate buffer for position,velocity,colour etc...


As long as your algorithm takes advantage of it, yes, this would be a much better solution.

The key to this is making best use of the cache; every time you fetch a value from memory you don't fetch a single value but the whole cache line it sits in; this means if you then access the value next to it the CPU can pull it from cache instead of having to take a trip back to main memory to fetch it (aka a cache miss which is VERY slow). CPUs tend to have another trick to help this as they will pre-fetch the next cache line of data they guess you will need next (forward and backwards walking of memory tends to get best results) so that you won't stall when you get to it.

Now, this works with the current setup you have but this is why I said 'reasonably friendly' when talking about the data.

Currently, assuming 'glm::vec3' really is a 3 component vector and not 4 under the hood (which in SSE land makes sense for alignment) your particle class takes up (4*3)*5 bytes or 60 bytes. I'm currently using an Ivy Bridge CPU and a single cache line on that is 64bytes in size which means your particle class only just fits in. (If vec3 is really 4 floats under the hood then it's 80 bytes long and you've blown two cache lines. Not that cache lines are wasted of course; in the 60byte example the next 4bytes would be the first 4 bytes of the next particle structure.

By thinking about the data you can split up the components into sections of memory and then read only what you need for each stage; so instead of doing each particle in turn's calculations (force -> velocity -> position for example) you do ALL the changes in velocity for the particles and then work out all the changes in position.

This ends up moving the same amount of data around but means you can do more ALU ops per cache line as each cache line can fit 4 particles worth of information on it; well assuming simple 'position', 'velocity', 'force' split - you could split it down further so that all the 'x' live together, all the 'y' lives together and so on (as the equation for moving them is, generally, completely independent for each component which means with the correct alignment (16byte memory address alignment) and usage of SSE you can calculate 4 particles worth of 'x' changes in one instruction, effectively 3 instructions for position(x,y,z) for 4 particles instead of (best case) 3 instructions per particle.

But that's taking it to the extreme end of things and brings with it the problem of how do you get the separate 'x','y' and 'z' streams efficiently back into a GPU ready format to render later.

Share this post


Link to post
Share on other sites

<snip>

 

 

Sorry for the late reply. Just got a chance to work on this project.  Thanks for all the info it was a great read and highly informative. 

I just tried a quick solution of splitting the data. So made a separate structure to hold particle position and colour only and passing that to the GPU. This turned out to be worse performance haha (probably due copying data from the class).

 

Anyway I think im just gonna leave this like it is and attempt to move all the calculations on GPU instead that should definitely boost performance.

 

Thanks again.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Advertisement
  • Popular Now

  • Similar Content

    • By LifeArtist
      Good Evening,
      I want to make a 2D game which involves displaying some debug information. Especially for collision, enemy sights and so on ...
      First of I was thinking about all those shapes which I need will need for debugging purposes: circles, rectangles, lines, polygons.
      I am really stucked right now because of the fundamental question:
      Where do I store my vertices positions for each line (object)? Currently I am not using a model matrix because I am using orthographic projection and set the final position within the VBO. That means that if I add a new line I would have to expand the "points" array and re-upload (recall glBufferData) it every time. The other method would be to use a model matrix and a fixed vbo for a line but it would be also messy to exactly create a line from (0,0) to (100,20) calculating the rotation and scale to make it fit.
      If I proceed with option 1 "updating the array each frame" I was thinking of having 4 draw calls every frame for the lines vao, polygons vao and so on. 
      In addition to that I am planning to use some sort of ECS based architecture. So the other question would be:
      Should I treat those debug objects as entities/components?
      For me it would make sense to treat them as entities but that's creates a new issue with the previous array approach because it would have for example a transform and render component. A special render component for debug objects (no texture etc) ... For me the transform component is also just a matrix but how would I then define a line?
      Treating them as components would'nt be a good idea in my eyes because then I would always need an entity. Well entity is just an id !? So maybe its a component?
      Regards,
      LifeArtist
    • By QQemka
      Hello. I am coding a small thingy in my spare time. All i want to achieve is to load a heightmap (as the lowest possible walking terrain), some static meshes (elements of the environment) and a dynamic character (meaning i can move, collide with heightmap/static meshes and hold a varying item in a hand ). Got a bunch of questions, or rather problems i can't find solution to myself. Nearly all are deal with graphics/gpu, not the coding part. My c++ is on high enough level.
      Let's go:
      Heightmap - i obviously want it to be textured, size is hardcoded to 256x256 squares. I can't have one huge texture stretched over entire terrain cause every pixel would be enormous. Thats why i decided to use 2 specified textures. First will be a tileset consisting of 16 square tiles (u v range from 0 to 0.25 for first tile and so on) and second a 256x256 buffer with 0-15 value representing index of the tile from tileset for every heigtmap square. Problem is, how do i blend the edges nicely and make some computationally cheap changes so its not obvious there are only 16 tiles? Is it possible to generate such terrain with some existing program?
      Collisions - i want to use bounding sphere and aabb. But should i store them for a model or entity instance? Meaning i have 20 same trees spawned using the same tree model, but every entity got its own transformation (position, scale etc). Storing collision component per instance grats faster access + is precalculated and transformed (takes additional memory, but who cares?), so i stick with this, right? What should i do if object is dynamically rotated? The aabb is no longer aligned and calculating per vertex min/max everytime object rotates/scales is pretty expensive, right?
      Drawing aabb - problem similar to above (storing aabb data per instance or model). This time in my opinion per model is enough since every instance also does not have own vertex buffer but uses the shared one (so 20 trees share reference to one tree model). So rendering aabb is about taking the model's aabb, transforming with instance matrix and voila. What about aabb vertex buffer (this is more of a cosmetic question, just curious, bumped onto it in time of writing this). Is it better to make it as 8 points and index buffer (12 lines), or only 2 vertices with min/max x/y/z and having the shaders dynamically generate 6 other vertices and draw the box? Or maybe there should be just ONE 1x1x1 cube box template moved/scaled per entity?
      What if one model got a diffuse texture and a normal map, and other has only diffuse? Should i pass some bool flag to shader with that info, or just assume that my game supports only diffuse maps without fancy stuff?
      There were several more but i forgot/solved them at time of writing
      Thanks in advance
    • By RenanRR
      Hi All,
      I'm reading the tutorials from learnOpengl site (nice site) and I'm having a question on the camera (https://learnopengl.com/Getting-started/Camera).
      I always saw the camera being manipulated with the lookat, but in tutorial I saw the camera being changed through the MVP arrays, which do not seem to be camera, but rather the scene that changes:
      Vertex Shader:
      #version 330 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec2 aTexCoord; out vec2 TexCoord; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { gl_Position = projection * view * model * vec4(aPos, 1.0f); TexCoord = vec2(aTexCoord.x, aTexCoord.y); } then, the matrix manipulated:
      ..... glm::mat4 projection = glm::perspective(glm::radians(fov), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); ourShader.setMat4("projection", projection); .... glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); ourShader.setMat4("view", view); .... model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ourShader.setMat4("model", model);  
      So, some doubts:
      - Why use it like that?
      - Is it okay to manipulate the camera that way?
      -in this way, are not the vertex's positions that changes instead of the camera?
      - I need to pass MVP to all shaders of object in my scenes ?
       
      What it seems, is that the camera stands still and the scenery that changes...
      it's right?
       
       
      Thank you
       
    • By dpadam450
      Sampling a floating point texture where the alpha channel holds 4-bytes of packed data into the float. I don't know how to cast the raw memory to treat it as an integer so I can perform bit-shifting operations.

      int rgbValue = int(textureSample.w);//4 bytes of data packed as color
      // algorithm might not be correct and endianness might need switching.
      vec3 extractedData = vec3(  rgbValue & 0xFF000000,  (rgbValue << 8) & 0xFF000000, (rgbValue << 16) & 0xFF000000);
      extractedData /= 255.0f;
    • By Devashish Khandelwal
      While writing a simple renderer using OpenGL, I faced an issue with the glGetUniformLocation function. For some reason, the location is coming to be -1.
      Anyone has any idea .. what should I do?
  • Advertisement