Reputation: 630
I'm a beginner in both C++ and SDL, and I'm slowly writing a small game following some tutorials to learn some concepts.
I'm having a problem, though: My rendering seems to be really slow. I've used PerformanceCounters to calculate my loops with and without my rendering function. Without it, I get 0~2ish milliseconds per frame; when I add the rendering, it goes up to 65ish ms per frame.
Could someone tell me what is wrong with my rendering function?
SDL_Texture *texture;
...
// gets called by the main loop
void render(int x_offset, int y_offset)
{
if (texture)
{
SDL_DestroyTexture(texture);
}
texture = SDL_CreateTexture(renderer,
SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING,
texture_w,
texture_h);
if (SDL_LockTexture(texture, NULL, &pixel_memory, &pitch) < 0) {
printf("Oops! %s\n", SDL_GetError());
}
Uint32 *pixel;
Uint8 *row = (Uint8 *) pixel_memory;
for (int j = 0; j < texture_h; ++j) {
pixel = (Uint32 *)((Uint8 *) pixel_memory + j * pitch);
for (int i = 0; i < texture_w; ++i) {
Uint8 alpha = 255;
Uint8 red = 172;
Uint8 green = 0;
Uint8 blue = 255;
*pixel++ = ((alpha << 24) | (red << 16) | (green << 8) | (blue));
}
}
SDL_UnlockTexture(texture);
}
Upvotes: 4
Views: 8192
Reputation: 503
The SDL2 is based on hardware rendering. Acessing textures, even with the streaming flag won't be fast since you play ping pong with the GPU.
Instead of creating and destroying a texture each frame, you should consider simply cleaning it before redrawing.
Another option would be to use a surface. You do your stuff with the surface and then draw it as a texture. I'm not sure that the gain would be huge but I think it will still be better than destroying, creating, locking and unlocking a texture each frame.
Looking at your code, I understand it is but a test, though you could try to render to a texture with SDL primitives.
Lastly, keep in mind during your tests that your driver might force the vertical sync, which could lead to fake bad performance.
Upvotes: 6
Reputation: 361
It's likely slow because you're destroying and creating the texture every single frame, locking textures/uploading pixel data isn't super fast, but I doubt it's the bottleneck here. I strongly recommend allocating the texture once before entering your main loop and re-using it during rendering, then destroying it before your program exits.
Upvotes: 5
Reputation: 71899
Probably nothing. Locking textures for direct pixel access is slow. Chances are, you can do a lot of additional stuff in the render function and not see any further decrease in speed.
If you want faster rendering, you need higher-level functions.
Upvotes: 2