module window; import derelict.sdl2.sdl; import glad.gl.all; /** * Converts an integer representing a colour, for example 0x428bca into a 4 element * int array for passing to OpenGL. */ GLfloat[4] to(T : GLfloat[4])(int color, ubyte alpha = 255) nothrow @nogc pure { GLfloat[4] gl_color = [ //mask out r, g, b components from int cast(float)cast(ubyte)(color>>16)/255, cast(float)cast(ubyte)(color>>8)/255, cast(float)cast(ubyte)(color)/255, cast(float)cast(ubyte)(alpha)/255 ]; return gl_color; } // to!GLfloat[4] struct Window { import core.stdc.stdio; import core.stdc.stdlib; SDL_Window* window; SDL_GLContext context; void create_window(int w, int h, const char* title = "Chipd8 Emu") { assert(w > 0, "window width must be > 0"); assert(h > 0, "window height must be > 0"); // minimum OpenGL 3.3 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 32); SDL_Window* new_win = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, w, h, SDL_WINDOW_OPENGL); if (new_win == null) { printf("SDL2 - Window could not be created: %s\n", SDL_GetError()); return; } SDL_GLContext new_con = SDL_GL_CreateContext(new_win); if (new_con == null) { printf("SDL2 - failed creating OpenGL 3.3 context: %s\n", SDL_GetError()); return; } // assign em yes window = new_win; context = new_con; atexit(SDL_Quit); } // create_window void handle_event(ref SDL_Event ev) { } void render_clear(int colour) { auto col = to!GLColor(color, 255); glClearColor(col[0], col[1], col[2], col[3]); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void render_present() { SDL_GL_SwapWindow(window); } @property nothrow @nogc { int[2] window_size() { int w, h; SDL_GetWindowSize(window, &w, &h); return [w, h]; } int[2] framebuffer_size() { int w, h; SDL_GL_GetDrawableSize(window, &w, &h); return [w, h]; } } } // Window