os_sdl2.odin 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. //+build !js
  2. package vendor_wgpu_example_triangle
  3. import "core:c"
  4. import "core:fmt"
  5. import "vendor:sdl2"
  6. import "vendor:wgpu"
  7. import "vendor:wgpu/sdl2glue"
  8. OS :: struct {
  9. window: ^sdl2.Window,
  10. }
  11. os_init :: proc(os: ^OS) {
  12. sdl_flags := sdl2.InitFlags{.VIDEO, .JOYSTICK, .GAMECONTROLLER, .EVENTS}
  13. if res := sdl2.Init(sdl_flags); res != 0 {
  14. fmt.eprintfln("ERROR: Failed to initialize SDL: [%s]", sdl2.GetError())
  15. return
  16. }
  17. window_flags: sdl2.WindowFlags = {.SHOWN, .ALLOW_HIGHDPI, .RESIZABLE}
  18. os.window = sdl2.CreateWindow(
  19. "WGPU Native Triangle",
  20. sdl2.WINDOWPOS_CENTERED,
  21. sdl2.WINDOWPOS_CENTERED,
  22. 960,
  23. 540,
  24. window_flags,
  25. )
  26. if os.window == nil {
  27. fmt.eprintfln("ERROR: Failed to create the SDL Window: [%s]", sdl2.GetError())
  28. return
  29. }
  30. sdl2.AddEventWatch(size_callback, nil)
  31. }
  32. os_run :: proc(os: ^OS) {
  33. now := sdl2.GetPerformanceCounter()
  34. last : u64
  35. dt: f32
  36. main_loop: for {
  37. last = now
  38. now = sdl2.GetPerformanceCounter()
  39. dt = f32((now - last) * 1000) / f32(sdl2.GetPerformanceFrequency())
  40. e: sdl2.Event
  41. for sdl2.PollEvent(&e) {
  42. #partial switch (e.type) {
  43. case .QUIT:
  44. break main_loop
  45. }
  46. }
  47. frame(dt)
  48. }
  49. sdl2.DestroyWindow(os.window)
  50. sdl2.Quit()
  51. finish()
  52. }
  53. os_get_render_bounds :: proc(os: ^OS) -> (width, height: u32) {
  54. iw, ih: c.int
  55. sdl2.GetWindowSize(os.window, &iw, &ih)
  56. return u32(iw), u32(ih)
  57. }
  58. os_get_surface :: proc(os: ^OS, instance: wgpu.Instance) -> wgpu.Surface {
  59. return sdl2glue.GetSurface(instance, os.window)
  60. }
  61. @(private="file")
  62. size_callback :: proc "c" (userdata: rawptr, event: ^sdl2.Event) -> c.int {
  63. if event.type == .WINDOWEVENT {
  64. if event.window.event == .SIZE_CHANGED || event.window.event == .RESIZED {
  65. resize()
  66. }
  67. }
  68. return 0
  69. }