0

I've been primarily developing on Linux (Mint) and Windows using SDL2 and OpenGL 3.3, with few issues in regards to drawing objects. CPU usage never really spiking past ~40%.

That was, until I tried porting what I had to OSX (Sierra). Utilizing the exact same shader and code that runs on Linux and Windows just fine, spikes the cpu usage on OSX to ~99% consistently.

At first, I thought it was a batching issue, so I batched my draw calls together to minimize the number of calls to glDrawElements, and that didn't work.

Then, I thought it was an issue involving not using attributes in the vertex/fragment shader (like: OpenGL core profile incredible slowdown on OS X)

Also, I maintain the framerate at 60 fps.

After sorting that out, no luck. Tried logging everything I could, nothing from glGetError() nor from shader logs.

So I removed bits and pieces from my vertex/fragment shaders to see what in particular was slowing down my draw calls. I managed to reduce it down to this: Any call in either my vertex/fragment shaders to the texture() function will run the cpu to high usage.

Texture loading code:

// Texture loading
void PCShaderSurface::AddTexturePairing(HashString const &aName)
{
  GLint minFilter = GL_LINEAR;
  GLint magFilter = GL_LINEAR;
  GLint wrapS = GL_REPEAT;
  GLint wrapT = GL_REPEAT;
  if(Constants::GetString("OpenGLMinFilter") == "GL_NEAREST")
  {
    minFilter = GL_NEAREST;
  }
  if(Constants::GetString("OpenGLMagFilter") == "GL_NEAREST")
  {
    magFilter = GL_NEAREST;
  }
  if(Constants::GetString("OpenGLWrapModeS") == "GL_CLAMP_TO_EDGE")
  {
    wrapS = GL_CLAMP_TO_EDGE;
  }
  if(Constants::GetString("OpenGLWrapModeT") == "GL_CLAMP_TO_EDGE")
  {
    wrapT = GL_CLAMP_TO_EDGE;
  }

  glGenTextures(1, &mTextureID);
  glBindTexture(GL_TEXTURE_2D, mTextureID);

  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, mSurface->w, mSurface->h, 0, mTextureFormat, GL_UNSIGNED_BYTE, mSurface->pixels);

  GetManager()->AddTexturePairing(aName, TextureData(mTextureID, mSurface->w, mSurface->h));
}

Draw Code:

// I batch objects that use the same program and texture id to draw in the same call.
glUseProgram(program);
int activeTexture = texture % mMaxTextures;
int vertexPosLocation = glGetAttribLocation(program, "vertexPos");
int texCoordPosLocation = glGetAttribLocation(program, "texCoord");
int objectPosLocation = glGetAttribLocation(program, "objectPos");
int colorPosLocation = glGetAttribLocation(program, "primaryColor");

// Calculate matrices and push vertex, color, position, texCoord data
// ...

// Enable textures and set uniforms.
glBindVertexArray(mVertexArrayObjectID);
glActiveTexture(GL_TEXTURE0 + activeTexture);
glBindTexture(GL_TEXTURE_2D, texture);
glUniform1i(glGetUniformLocation(program, "textureUnit"), activeTexture);
glUniform3f(glGetUniformLocation(program, "cameraDiff"), cameraTranslation.x, cameraTranslation.y, cameraTranslation.z);
glUniform3f(glGetUniformLocation(program, "cameraSize"), cameraSize.x, cameraSize.y, cameraSize.z);
glUniformMatrix3fv(glGetUniformLocation(program, "cameraTransform"), 1, GL_TRUE, cameraMatrix);

// Set shader properties. Due to batching, done on a per surface / shader basis.
// Shader uniforms are reset upon relinking.
SetShaderProperties(surface, true);

// Set VBO and buffer data.
glBindVertexArray(mVertexArrayObjectID);
BindAttributeV3(GL_ARRAY_BUFFER, mVertexBufferID, vertexPosLocation, vertexData);
BindAttributeV3(GL_ARRAY_BUFFER, mTextureBufferID, texCoordPosLocation, textureData);
BindAttributeV3(GL_ARRAY_BUFFER, mPositionBufferID, objectPosLocation, positionData);
BindAttributeV4(GL_ARRAY_BUFFER, mColorBufferID, colorPosLocation, colorData);

// Set index data
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBufferID);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * indices.size(), &indices[0], GL_DYNAMIC_DRAW);

// Draw and disable
glDrawElements(GL_TRIANGLES, static_cast<unsigned>(vertexData.size()), GL_UNSIGNED_INT, 0);
DisableVertexAttribArray(vertexPosLocation);
DisableVertexAttribArray(texCoordPosLocation);
DisableVertexAttribArray(objectPosLocation);
DisableVertexAttribArray(colorPosLocation);

// Reset shader property values.
SetShaderProperties(surface, false);

// Reset to default texture
glBindTexture(GL_TEXTURE_2D, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
glUseProgram(0);

Example binding code:

void PCShaderScreen::BindAttributeV3(GLenum aTarget, int const aBufferID, int const aAttributeLocation, std::vector<Vector3> &aData)
{
  if(aAttributeLocation != -1)
  {
    glEnableVertexAttribArray(aAttributeLocation);
    glBindBuffer(aTarget, aBufferID);
    glBufferData(aTarget, sizeof(Vector3) * aData.size(), &aData[0], GL_DYNAMIC_DRAW);
    glVertexAttribPointer(aAttributeLocation, 3, GL_FLOAT, GL_FALSE, sizeof(Vector3), 0);
    glBindBuffer(aTarget, 0);
  }
}

VS code:

#version 330

in vec4 vertexPos;
in vec4 texCoord;
in vec4 objectPos;
in vec4 primaryColor;

uniform vec3 cameraDiff;
uniform vec3 cameraSize;
uniform mat3 cameraTransform;

out vec2 texValues;
out vec4 texColor;

void main()
{
  texColor = primaryColor;
  texValues = texCoord.xy;

  vec3 vertex = vertexPos.xyz + objectPos.xyz;
  vertex = (cameraTransform * vertex) - cameraDiff;
  vertex.x /= cameraSize.x;
  vertex.y /= -cameraSize.y;
  vertex.y += 1.0;
  vertex.x -= 1.0;
  gl_Position.xyz = vertex;
  gl_Position.w = 1.0;
}

FS code:

#version 330

uniform sampler2D textureUnit;
in vec2 texValues;
in vec4 texColor;
out vec4 fragColor;

void main()
{
  // Slow, 99% CPU usage on OSX only
  fragColor = texture(textureUnit, texValues) * texColor;
  // Fine on everything
  fragColor = vec4(1,1,1,1);
}

I'm really out of ideas here, I even followed Apple's best practices (https://developer.apple.com/library/content/documentation/GraphicsImaging/Conceptual/OpenGL-MacProgGuide/opengl_texturedata/opengl_texturedata.html) as best as I could, with no luck.

Are the Windows and Linux drivers I'm using just offering me some form of forgiveness that I'm not aware of? Is the OSX driver really that sensitive? I must be missing something. Any help and insight would be appreciated. Thanks for reading my long winded speech.

14
  • First, use Instruments and the Time Profiler template to analyze what is using CPU time in your program. Even if it's not in your code, exactly, it will probably provide a clue. Second, my guess is that your texture format is not ideal and requires swizzling. From the Apple doc you linked: "The combination GL_RGBA and GL_UNSIGNED_BYTE needs to be swizzled by many cards when the data is loaded, so it's not recommended." Removing the texture() call allows the GL to detect that the texture isn't actually used, so it can skip the swizzle. Feb 15, 2017 at 4:54
  • Thanks for the insight, I changed the glTexImage call to glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, mSurface->w, mSurface->h, 0, mTextureFormat, GL_UNSIGNED_INT_8_8_8_8_REV, mSurface->pixels);, with no luck, sadly. I made sure that the image was loaded in as GL_BGRA for good measure. imgur.com/a/GDqba I ran my code through Instruments, and it appears as if my problem occurs within the glDrawElements call. Feb 15, 2017 at 8:03
  • Interestingly, I see this call to SCCompileShader, not sure exactly what that is. Feb 15, 2017 at 8:12
  • @JimmySpencer what about your activeTexture calculation, why is it not always 0? Does it stay the same or changes with different draws? I suppose constantly changing texture slot number might force driver to recompile shader each time.
    – keltar
    Feb 15, 2017 at 14:07
  • Well, the time spent in SCCompileShader suggests that something you're doing with your pipeline state is causing the GL driver to recompile your shader for every draw. What does SetShaderProperties() do? Feb 15, 2017 at 15:58

2 Answers 2

1

All credit to @keltar for finding this, but my problem was in the glActiveTexture call.

I changed the call from glActiveTexture(GL_TEXTURE0 + activeTexture) to just glActiveTexture(GL_TEXTURE0).

To paraphrase @keltar: "Constantly changing the texture slot number might force driver to recompile shader each time. I don't think it matters which exact value it would be, as long as it doesn't change (and within GL limits). I suppose hardware that you use can't effectively (or at all) sample texture from any slot specified by uniform variable - but GL implies so. On some hardware e.g. fetching vertex attributes is internally part of shader too. When state changes, driver attempts to patch shader, but if change is too big (or driver don't know how to patch) - it falls to recompilation. Sadly OSX graphics drivers aren't known to be good, to my knowledge."

0

You do a lot of gl-calls in your draw code: binding buffers, uploading data to buffers, etc. Most of them would be better done when preparing or uploading data.

I prefer to do in the draw code just:

  1. glUseProgram(program);
  2. Enable de VAO by glBindVertexArray
  3. Pass uniforms
  4. Active texture units by glActiveTexture
  5. glDrawXXX commands
  6. glUseProgram(0);
  7. Disable de VAO
2
  • Would using so many calls cause a call to "texture()" in the fragment shader to make the cpu go as crazy as it does? I'm not really seeing the correlation. Feb 15, 2017 at 0:59
  • Taking out the call to "texture()" in the fs has my cpu running at about 8-9% smoothly, putting it back in: 95-99% Feb 15, 2017 at 1:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.