Reputation: 702
I'm having a problem with rendering a texture using SDL2. In my program, there are a bunch of pixels which move around the screen, however they visibly flicker. Here is my code:
Source.cpp
frameStart = SDL_GetTicks();
screen.update();
// Makes the screen black
for (int x = 0; x < Screen::SCREEN_WIDTH; x++)
{
for (int y = 0; y < Screen::SCREEN_HEIGHT; y++) {
screen.setPixel(x, y, 0, 0, 0);
}
}
// Draw + Update people (Code should be separated and moved)
for (Person &p : people) {
if (p.isAlive == true) {
p.Update(p);
cout << p.x << ", " << p.y << endl;
screen.setPixel(p.x, p.y, 255, 0, 0);
}
else {
screen.setPixel(p.x, p.y, 0, 0, 0);
}
}
// Manage events
if (screen.processEvents() == false) {
break;
}
frameTime = SDL_GetTicks() - frameStart;
if (frameDelay > frameTime) {
SDL_Delay(frameDelay - frameTime);
}
}
Screen.update points here:
void Screen::update() {
SDL_UpdateTexture(m_texture, NULL, m_buffer, SCREEN_WIDTH * sizeof(Uint32) );
SDL_RenderCopy(m_renderer, m_texture, NULL, NULL);
SDL_RenderPresent(m_renderer);
SDL_RenderClear(m_renderer);
}
And my renderer and texture setup are as follows:
m_renderer = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_PRESENTVSYNC);
m_texture = SDL_CreateTexture(m_renderer, SDL_PIXELFORMAT_RGBA8888,
SDL_TEXTUREACCESS_STATIC, SCREEN_WIDTH, SCREEN_HEIGHT);
I've messed around alot with the flags for both the renderer and texture but have not found a solution that stops the flickering. Any help would be really appreciated.
Upvotes: 0
Views: 6860
Reputation: 41
The sequence you should follow is:
What you are doing is basically, Render and clear right the way. If you make this way might work just fine
frameStart = SDL_GetTicks();
SDL_RenderClear(m_renderer);
/* Do you rendering */
/*Manage your events*/
SDL_RenderPresent(m_renderer);
frameTime = SDL_GetTicks() - frameStart;
if (frameDelay > frameTime) {
SDL_Delay(frameDelay - frameTime);
}
Also about rendering pixels, when clearing the texture, you should use memset wich is faster. But your way still works
memset(pixels,0,h*pitch);
Upvotes: 4