ysbaddaden / sdl.cr

SDL2 bindings for Crystal
102 stars 32 forks source link

Question - SDL_GetKeyboardState #34

Open AlesLulak opened 4 years ago

AlesLulak commented 4 years ago

Is it possible to use SDL_GetKeyboardState?

I tried to get it work by LibSDL.get_keyboard_state(nil) but I was unsuccessful.

ysbaddaden commented 4 years ago

I don't know.

Erquint commented 3 years ago

@AlesLulak Here I tried to reimplement the example code from your link as close as I could:

State = LibSDL.get_keyboard_state(nil)
loop do # You're gonna need a loop anyway. But want to avoid reassignments to a constant.
  if State[LibSDL::Scancode::RETURN.value] > 0
    puts "<RETURN> is pressed.\n"
  end
  if State[LibSDL::Scancode::RIGHT.value] > 0 &&
    State[LibSDL::Scancode::UP.value] > 0
    puts "Right and Up Keys Pressed.\n"
  end
# Omitting boilerplate event polling for termination and window updates.
end

And this seems to work like a charm pretty much how it would in C.

But you'd probably want to rewrite it with Crystal-specific approach to avoid unsafe pointer access or maybe just use the sdl.cr's own safer methods as shown in samples.

Erquint commented 3 years ago

@ysbaddaden Looking at keyboard.cr, you might wanna consider using LibC types for better platform-based integration and future-proofing.

I don't know enough about this myself to advice, but here are some references to ponder upon:

ysbaddaden commented 3 years ago

@Erquint The C bindings are very old. Now, they could be automatically generated by leveraging c2cr in the clang.cr shard, be declared on LibC, and we don't need lowercase function names anymore, so they could start with the SDL_ prefix.

ysbaddaden commented 3 years ago

For example the clang bindings are automatically generated.

Erquint commented 3 years ago

Sounds interesting but I have my doubts about portability. Would that work on non-POSIX systems?

Still, my expertise is no good at this specific level. I know very little about compilation of C.

ysbaddaden commented 3 years ago

@Erquint Generating bindings from headers automatically can only help with portability: they'd always be adapted to the actual headers on the target, which is much nicer than static headers generated from a single set of headers (x86_64-linux-gnu).

Erquint commented 3 years ago

I just wonder why SDL won't store that array of effectively boolean UInt8s as a BitArray instead to vacuum that 7-bit padding…