Sign in to follow this  

OpenGL Why the efficiency a simple 2D program is so low?

This topic is 2125 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

I'm a totally new beginner to OpenGL and I'm learning it by online resource http://www.arcsynthesis.org/gltut/.

It is a 2D example that is a simply 2D spinning triangle around one point. A attach its main code below.

My problem is why a simple program run so slow. It does not run very smooth and I can a few obvious lags. This is much more frequent when I open v-sync (CPU 100% on a laptop is annoying). I also try to sleep sometime before call another glutPostRedisplay. This seems even lagger than v-sync.

My question is how to make this program run more smooth? I can never feel such lag when I play some games written in OpenGL. Also is there a convenient way to limit the FPS?

[code]
#define ARRAY_COUNT( array ) (sizeof( array ) / (sizeof( array[0] ) * (sizeof( array ) != sizeof(void*) || sizeof( array[0] ) <= sizeof(void*))))

GLuint theProgram;

void InitializeProgram()
{
std::vector<GLuint> shaderList;

shaderList.push_back(Framework::LoadShader(GL_VERTEX_SHADER, "standard.vert"));
shaderList.push_back(Framework::LoadShader(GL_FRAGMENT_SHADER, "standard.frag"));

theProgram = Framework::CreateProgram(shaderList);
}

const float vertexPositions[] = {
0.25f, 0.25f, 0.0f, 1.0f,
0.25f, -0.25f, 0.0f, 1.0f,
-0.25f, -0.25f, 0.0f, 1.0f,
};

GLuint positionBufferObject;
GLuint vao;


void InitializeVertexBuffer()
{
glGenBuffers(1, &positionBufferObject);

glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexPositions), vertexPositions, GL_STREAM_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}

//Called after the window and OpenGL are initialized. Called exactly once, before the main loop.
void init()
{
InitializeProgram();
InitializeVertexBuffer();

glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
}


void ComputePositionOffsets(float &fXOffset, float &fYOffset)
{
const float fLoopDuration = 1.0f;
const float fScale = 3.14159f * 2.0f / fLoopDuration;

float fElapsedTime = glutGet(GLUT_ELAPSED_TIME) / 1000.0f;

float fCurrTimeThroughLoop = fmodf(fElapsedTime, fLoopDuration);

fXOffset = cosf(fCurrTimeThroughLoop * fScale) * 0.5f;
fYOffset = sinf(fCurrTimeThroughLoop * fScale) * 0.5f;
}

void AdjustVertexData(float fXOffset, float fYOffset)
{
std::vector<float> fNewData(ARRAY_COUNT(vertexPositions));
memcpy(&fNewData[0], vertexPositions, sizeof(vertexPositions));

for(int iVertex = 0; iVertex < ARRAY_COUNT(vertexPositions); iVertex += 4)
{
fNewData[iVertex] += fXOffset;
fNewData[iVertex + 1] += fYOffset;
}

glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertexPositions), &fNewData[0]);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}

void display()
{
float fXOffset = 0.0f, fYOffset = 0.0f;
ComputePositionOffsets(fXOffset, fYOffset);
AdjustVertexData(fXOffset, fYOffset);

glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);

glUseProgram(theProgram);

glBindBuffer(GL_ARRAY_BUFFER, positionBufferObject);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);

glDrawArrays(GL_TRIANGLES, 0, 3);

glDisableVertexAttribArray(0);
glUseProgram(0);

glutSwapBuffers();
glutPostRedisplay();
}
[/code]

Standard.vert
[code]
#version 330

layout(location = 0) in vec4 position;

void main()
{
gl_Position = position;
}
[/code]

Standard.frag
[code]
#version 330

out vec4 outputColor;

void main()
{
outputColor = vec4(1.0f, 1.0f, 1.0f, 1.0f);
}

[/code]

BTW, Is http://www.arcsynthesis.org/gltut/ a good choice for beginner to learn opengl?

Share this post


Link to post
Share on other sites
You are doing all of your calculations on the CPU (slow), using std::vector (also somewhat slow) for a static array (unnecessary) and then moving your vertex data across your system bus (from the CPU to the GPU) each frame (very slow).

If your array isn't dynamic, skip std::vector and use a standard array. Send you vertex data to the GPU once and then either transform it in the vertex shader or use glRotate each frame.

Share this post


Link to post
Share on other sites
Hidden
[quote name='MarkS' timestamp='1332414551' post='4924266']
You are doing all of your calculations on the CPU (slow), using std::vector (also somewhat slow) for a static array (unnecessary) and then moving your vertex data across your system bus (from the CPU to the GPU) each frame (very slow).

If your array isn't dynamic, skip std::vector and use a standard array. Send you vertex data to the GPU once and then either transform it in the vertex shader or use glRotate each frame.
[/quote]

It's not enough data for this to be an issue.
Are you sure it's not your call to glutPostRedisplay..? It seems a bit fishy to call it in your display function! In GLUT, you should probably call it in the Idle callback.

Share this post


Link to post
For 3 verts in a single triangle, doing things on the CPU should be effectively "free" - or at the very least have overhead so low that it's not even measurable. For sure you should move them to the GPU (put them in your vertex shader) but in this case they're not going to be the cause of the symptoms you describe.

Can you post your main function? And in particular elaborate a little on your sleep call - sleep calls are a very bad way of limiting framerate and are not suitable for this kind of use case. They are suitable for reducing battery usage, but you need a fairly light touch with them.

Share this post


Link to post
Share on other sites
[quote name='mhagain' timestamp='1332427952' post='4924332']
For 3 verts in a single triangle, doing things on the CPU should be effectively "free" - or at the very least have overhead so low that it's not even measurable. For sure you should move them to the GPU (put them in your vertex shader) but in this case they're not going to be the cause of the symptoms you describe.
[/quote]

I agree. Since he is learning I felt it was best to steer him away from this practice. It may be free now, but it wont be with a much higher vertex model.

I didn't look at the book he linked to, but if that code is straight from that book, it should raise flags.

Share this post


Link to post
Share on other sites
[quote name='MarkS' timestamp='1332456453' post='4924457']
I agree. Since he is learning I felt it was best to steer him away from this practice. It may be free now, but it wont be with a much higher vertex model.
[/quote]

Good point, I definitely agree there.

Share this post


Link to post
Share on other sites
[quote name='MarkS' timestamp='1332456453' post='4924457']
[quote name='mhagain' timestamp='1332427952' post='4924332']
For 3 verts in a single triangle, doing things on the CPU should be effectively "free" - or at the very least have overhead so low that it's not even measurable. For sure you should move them to the GPU (put them in your vertex shader) but in this case they're not going to be the cause of the symptoms you describe.
[/quote]

I agree. Since he is learning I felt it was best to steer him away from this practice. It may be free now, but it wont be with a much higher vertex model.

I didn't look at the book he linked to, but if that code is straight from that book, it should raise flags.
[/quote]

It is straight from that site, it goes over the proper way to do things later on, i think it is using that method in order to keep the vertex shader simple for the initial example to prevent pushing too much information on the reader at once, I havn't actually looked through it all properly though so i can't vouch for its quality and it does seem a bit odd to start off by showing a retarded way to do things.

Share this post


Link to post
Share on other sites
Thanks for everyone. :)

I understand that the way moving the triangle directly in the CPU is not a good way. But the strange thing is that I can't reprocedure the efficiency problem on the same computer again. I can only believe that this is just my illusion.(Maybe I'm running my computer on powersaving mode?)

Another problem is that when I run two OpenGL applications and enable v-sync, the FPS will drop to 30 and application becomes a little lag. Is there a solution to this problem?

Share this post


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

  • Similar Content

    • By _OskaR
      Hi,
      I have an OpenGL application but without possibility to wite own shaders.
      I need to perform small VS modification - is possible to do it in an alternative way? Do we have apps or driver modifictions which will catch the shader sent to GPU and override it?
    • By xhcao
      Does sync be needed to read texture content after access texture image in compute shader?
      My simple code is as below,
      glUseProgram(program.get());
      glBindImageTexture(0, texture[0], 0, GL_FALSE, 3, GL_READ_ONLY, GL_R32UI);
      glBindImageTexture(1, texture[1], 0, GL_FALSE, 4, GL_WRITE_ONLY, GL_R32UI);
      glDispatchCompute(1, 1, 1);
      // Does sync be needed here?
      glUseProgram(0);
      glBindFramebuffer(GL_READ_FRAMEBUFFER, framebuffer);
      glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                                     GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, texture[1], 0);
      glReadPixels(0, 0, kWidth, kHeight, GL_RED_INTEGER, GL_UNSIGNED_INT, outputValues);
       
      Compute shader is very simple, imageLoad content from texture[0], and imageStore content to texture[1]. Does need to sync after dispatchCompute?
    • By Jonathan2006
      My question: is it possible to transform multiple angular velocities so that they can be reinserted as one? My research is below:
      // This works quat quaternion1 = GEQuaternionFromAngleRadians(angleRadiansVector1); quat quaternion2 = GEMultiplyQuaternions(quaternion1, GEQuaternionFromAngleRadians(angleRadiansVector2)); quat quaternion3 = GEMultiplyQuaternions(quaternion2, GEQuaternionFromAngleRadians(angleRadiansVector3)); glMultMatrixf(GEMat4FromQuaternion(quaternion3).array); // The first two work fine but not the third. Why? quat quaternion1 = GEQuaternionFromAngleRadians(angleRadiansVector1); vec3 vector1 = GETransformQuaternionAndVector(quaternion1, angularVelocity1); quat quaternion2 = GEQuaternionFromAngleRadians(angleRadiansVector2); vec3 vector2 = GETransformQuaternionAndVector(quaternion2, angularVelocity2); // This doesn't work //quat quaternion3 = GEQuaternionFromAngleRadians(angleRadiansVector3); //vec3 vector3 = GETransformQuaternionAndVector(quaternion3, angularVelocity3); vec3 angleVelocity = GEAddVectors(vector1, vector2); // Does not work: vec3 angleVelocity = GEAddVectors(vector1, GEAddVectors(vector2, vector3)); static vec3 angleRadiansVector; vec3 angularAcceleration = GESetVector(0.0, 0.0, 0.0); // Sending it through one angular velocity later in my motion engine angleVelocity = GEAddVectors(angleVelocity, GEMultiplyVectorAndScalar(angularAcceleration, timeStep)); angleRadiansVector = GEAddVectors(angleRadiansVector, GEMultiplyVectorAndScalar(angleVelocity, timeStep)); glMultMatrixf(GEMat4FromEulerAngle(angleRadiansVector).array); Also how do I combine multiple angularAcceleration variables? Is there an easier way to transform the angular values?
    • By dpadam450
      I have this code below in both my vertex and fragment shader, however when I request glGetUniformLocation("Lights[0].diffuse") or "Lights[0].attenuation", it returns -1. It will only give me a valid uniform location if I actually use the diffuse/attenuation variables in the VERTEX shader. Because I use position in the vertex shader, it always returns a valid uniform location. I've read that I can share uniforms across both vertex and fragment, but I'm confused what this is even compiling to if this is the case.
       
      #define NUM_LIGHTS 2
      struct Light
      {
          vec3 position;
          vec3 diffuse;
          float attenuation;
      };
      uniform Light Lights[NUM_LIGHTS];
       
       
    • By pr033r
      Hello,
      I have a Bachelor project on topic "Implenet 3D Boid's algorithm in OpenGL". All OpenGL issues works fine for me, all rendering etc. But when I started implement the boid's algorithm it was getting worse and worse. I read article (http://natureofcode.com/book/chapter-6-autonomous-agents/) inspirate from another code (here: https://github.com/jyanar/Boids/tree/master/src) but it still doesn't work like in tutorials and videos. For example the main problem: when I apply Cohesion (one of three main laws of boids) it makes some "cycling knot". Second, when some flock touch to another it scary change the coordination or respawn in origin (x: 0, y:0. z:0). Just some streng things. 
      I followed many tutorials, change a try everything but it isn't so smooth, without lags like in another videos. I really need your help. 
      My code (optimalizing branch): https://github.com/pr033r/BachelorProject/tree/Optimalizing
      Exe file (if you want to look) and models folder (for those who will download the sources):
      http://leteckaposta.cz/367190436
      Thanks for any help...

  • Popular Now