简体   繁体   中英

How to draw a grid of pixels fast with sdl2?

I have the following function which draws a grid of pixels on the window, I'm using sdl.

The problem is that is very slow, It makes my program to run at 10fps. so I think Im must be doing something wrong.

This is the code I'm using

void rayTracing(SDL &sdl) {
  int nx = 1440;
  int ny = 810;

  for (int x = 0; x < nx; x++) {
    for (int y = 0; y < ny; y++) {
      float r = float(x) / float(nx);
      float g = float(y) / float(ny);
      float b = 0.2;
      int ir = int(255.99 * r);
      int ig = int(255.99 * g);
      int ib = int(255.99 * b);

      SDL_SetRenderDrawColor(sdl.renderer.get(), ir, ig, ib, 255);
      SDL_RenderDrawPoint(sdl.renderer.get(), x, ny - y);
    }
  }

  SDL_SetRenderDrawColor(sdl.renderer.get(), 0, 0, 0, 0);
}

Maybe the problem is the way I use SDL_RenderDrawPoint?

Your best bet may be to create a separate render texture that you can access directly through a pointer. You make your changes and when you are done, you call an SDL texture update once and it will transfer your in-memory texture to the display.

This is how you create the SDL texture

theTexture = SDL_CreateTexture( theRenderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, nx, ny );

You would then also create an in-memory buffer to draw to

uint32_t *textureBuffer = new uint32_t[ nx * ny ];

At this point, drawing a pixel really just comes down to writing the respective RGB8888 color value to the textureBuffer array, kind of like this

textureBuffer[(yPos*nx) + xPos] = 0xFF000000 | (ir<<16) | (ib<<8) | ig;

After drawing to it, you can then update the entire texture in one swoop like this

SDL_UpdateTexture( theTexture , NULL, textureBuffer, nx * sizeof (uint32_t));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM