ysbaddaden / sdl.cr

SDL2 bindings for Crystal
102 stars 32 forks source link

Allow streaming texture pixel access #47

Closed SleepingInsomniac closed 2 years ago

SleepingInsomniac commented 2 years ago

It appears that the macros which were ported from the SDL headers to define PixelFormatEnum don't work within the enum block (if anyone knows why, I'd love to learn about what is wrong there).

This PR replaces the macro call with the expanded values which are required to when using LibSDL.create_texture, and implements the SDL::Texture#lock method which yields a Slice pointing to the pixels buffer.

SleepingInsomniac commented 2 years ago

Here's a bit of code I wrote to test the streaming texture functionality:

require "./src/sdl"

width = 160
height = 100
scale = 4

begin
  SDL.init(SDL::Init::VIDEO)

  window = SDL::Window.new("test", width * scale, height * scale, flags: SDL::Window::Flags::SHOWN)
  renderer = SDL::Renderer.new(window, flags: SDL::Renderer::Flags::ACCELERATED)
  texture = SDL::Texture.new(renderer, width, height)

  loop do
    case event = SDL::Event.poll
    when SDL::Event::Quit
      break
    end

    texture.lock do |pixels, pitch|
      0.upto(pixels.size - 1) do |n|
        color = rand(0_u32..0xFF_u32) << 24 | rand(0_u32..0xFF_u32) << 16 | rand(0_u32..0xFF_u32) << 8 | 0xFF_u32
        pixels[n] = color
      end
    end

    renderer.copy(texture)
    renderer.present
  end
ensure
  SDL.quit
end
ysbaddaden commented 2 years ago

Thank you!