Currently I am doing my rendering by using a 3D array window_width x window_height x rgb as a buffer, then looping through the buffer and plotting pixels on screen using SDL2 (SDL_RenderDrawPoint). I know this is horrible and stupidly slow but I am not well experienced in graphics techniques. What is the better way to do this?

  • \$\begingroup\$ Why not use a 1D array of SDL_Textures that you render using SDL_RenderCopy? Why do you need a buffer of these anyway? \$\endgroup\$ Jun 16 '15 at 4:54
  • \$\begingroup\$ I'm building a ray tracer and my render algorithm puts each calculated pixel into the array, which I then render to screen. Can I put the pixel data into a texture, then copy it using RenderCopy? \$\endgroup\$
    – Corydon
    Jun 16 '15 at 5:06

You can use SDL_LockTexture and SDL_UnlockTexture for write only access to a texture created with the SDL_TEXTUREACCESS_STREAMING flag. Lock, write, unlock, then use SDL_RenderCopy to blit to the screen.

Create the buffer with SDL_CreateTexture (modify to you liking):

SDL_Texture* buffer = SDL_CreateTexture(renderer,

Lock with SDL_LockTexture:

                NULL,      // NULL means the *whole texture* here.

Where pixels is a int * and pitch is the width of a row of pixels in bytes.

Write your pixel data to pixels. You won't have any of the convenient SDL functions to do this. Just plonk the data in, one pixel after the other until you have done them all. Make sure you write with the correct PIXELFORMAT, otherwise the colours will come out wonky. (In SDL_PIXELFORMAT_BGRA8888, the first byte is blue, second is green, third is red and fourth is alpha. Leave alpha at 255 unless you want transparency)

Clean up with SDL_UnlockTexture:


Then you can RenderCopy this texture as normal:

SDL_RenderCopy(renderer, buffer, NULL, NULL);

This assumes the buffer is the same size as your window.

Note you will have to modify this for your own use case.

  • \$\begingroup\$ Do you know around what point it becomes beneficial to write to pixels pixel by pixel instead of SDL_RenderCopy? It seems like a 32x32 px section is relatively slow to use SDL_RenderCopy on, what is the limit where it no longer makes sense to write data pixel by pixel? \$\endgroup\$
    – jrh
    Aug 26 '20 at 22:34

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.