A 2D tile-based sandbox game.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Window.cc 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include "Window.h"
  2. #include <SDL.h>
  3. #include <iostream>
  4. #include "gl.h"
  5. #include "util.h"
  6. namespace Cygnet {
  7. struct WindowState {
  8. SDL_Window *window;
  9. SDL_GLContext glctx;
  10. };
  11. Window::Window(const char *name, int w, int h):
  12. state_(std::make_unique<WindowState>()) {
  13. SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);
  14. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
  15. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
  16. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  17. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
  18. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
  19. SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 8);
  20. SDL_GL_SetSwapInterval(1);
  21. state_->window = SDL_CreateWindow(name,
  22. SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, w, h,
  23. SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE |
  24. SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_OPENGL);
  25. sdlCheck(state_->window != NULL);
  26. state_->glctx = SDL_GL_CreateContext(state_->window);
  27. glCheck();
  28. makeCurrent();
  29. glewInit();
  30. std::cerr << "OpenGL Version: " << glGetString(GL_VERSION) << '\n';
  31. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  32. glEnable(GL_BLEND);
  33. glCheck();
  34. SDL_GetWindowSize(state_->window, &w, &h);
  35. onResize(w, h);
  36. }
  37. Window::~Window() {
  38. SDL_DestroyWindow(state_->window);
  39. }
  40. void Window::makeCurrent() {
  41. SDL_GL_MakeCurrent(state_->window, state_->glctx);
  42. glCheck();
  43. }
  44. void Window::clear(Color color) {
  45. glClearColor(color.r, color.g, color.b, color.a);
  46. glClear(GL_COLOR_BUFFER_BIT);
  47. glCheck();
  48. }
  49. void Window::flip() {
  50. SDL_GL_SwapWindow(state_->window);
  51. glCheck();
  52. }
  53. void Window::onResize(int w, int h) {
  54. int dw, dh;
  55. SDL_GL_GetDrawableSize(state_->window, &dw, &dh);
  56. glViewport(0, 0, dw, dh);
  57. glCheck();
  58. size_ = {dw, dh};
  59. ratio_ = (double)dw / (double)w;
  60. }
  61. SDL_Window *Window::sdlWindow() {
  62. return state_->window;
  63. }
  64. }