简体   繁体   English

如何使用 sdl2 快速绘制像素网格?

[英]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.我有以下 function 在 window 上绘制像素网格,我使用的是 sdl。

The problem is that is very slow, It makes my program to run at 10fps.问题是它非常慢,它使我的程序以 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?也许问题是我使用 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.您进行更改,完成后,您调用一次 SDL 纹理更新,它会将您的内存中纹理传输到显示器。

This is how you create the SDL texture这就是创建 SDL 纹理的方式

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此时,绘制一个像素实际上只是将各自的 RGB8888 颜色值写入到 textureBuffer 数组中,有点像这样

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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