5 #include <fcntl.h> // for access(2)
6 #include <unistd.h> // for access(2)
8 #include "shaderprogram.h"
10 #define BASICTEX_VERT \
12 "#extension GL_ARB_shading_language_420pack : require\n"\
13 "#extension GL_ARB_explicit_attrib_location : require\n"\
15 "layout(std140, binding=0) uniform Viewport\n"\
21 "layout(location = 0) in vec2 position;\n"\
22 "layout(location = 1) in vec2 tex_coord;\n"\
24 "out vec2 fp_tex_coord;\n"\
28 "\t// Transform to clip coordinates (-1,1, -1,1).\n"\
29 "\tgl_Position.x = (position.x*2/width) - 1;\n"\
30 "\tgl_Position.y = 1 - (position.y*2/height);\n"\
31 "\tgl_Position.z = 0.0;\n"\
32 "\tgl_Position.w = 1.0;\n"\
33 "\tfp_tex_coord = tex_coord;\n"\
36 #define BASICTEX_FRAG \
39 "in vec2 fp_tex_coord;\n"\
41 "out vec4 output_colour;\n"\
43 "uniform sampler2D tex;\n"\
44 "uniform vec4 colour;\n"\
48 "\toutput_colour = colour;\n"\
49 "\toutput_colour.a = texture(tex, fp_tex_coord).r;\n"\
55 static void opengl_debug_callback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* msg, const void *data)
57 Error("OpenGL Error (%d): %s", id, msg);
63 SDL_Init(SDL_INIT_VIDEO);
64 m_window = SDL_CreateWindow("IPDF", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
65 800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
69 Fatal("Couldn't create window!");
72 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
73 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
74 SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
75 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
77 m_gl_context = SDL_GL_CreateContext(m_window);
81 // Why is this so horribly broken?
82 if (ogl_IsVersionGEQ(3,0))
84 Fatal("We require OpenGL 3.1, but you have version %d.%d!",ogl_GetMajorVersion(), ogl_GetMinorVersion());
87 if (!SDL_GL_ExtensionSupported("GL_ARB_shading_language_420pack"))
89 Fatal("Your system does not support the ARB_shading_language_420pack extension, which is required.");
92 if (!SDL_GL_ExtensionSupported("GL_ARB_explicit_attrib_location"))
94 Fatal("Your system does not support the ARB_explicit_attrib_location extension, which is required.");
97 glDebugMessageCallback(opengl_debug_callback, 0);
100 glGenVertexArrays(1, &default_vao);
101 glBindVertexArray(default_vao);
103 //TODO: Error checking.
104 m_texture_prog.AttachVertexProgram(BASICTEX_VERT);
105 m_texture_prog.AttachFragmentProgram(BASICTEX_FRAG);
106 m_texture_prog.Link();
107 m_texture_prog.Use();
109 // We always want to use the texture bound to texture unit 0.
110 GLint texture_uniform_location = m_texture_prog.GetUniformLocation("tex");
111 glUniform1i(texture_uniform_location, 0);
113 m_colour_uniform_location = m_texture_prog.GetUniformLocation("colour");
115 m_viewport_ubo.SetUsage(GraphicsBuffer::BufferUsageDynamicDraw);
116 m_viewport_ubo.SetType(GraphicsBuffer::BufferTypeUniform);
118 m_debug_font_atlas = 0;
120 ResizeViewport(800, 600);
130 SDL_GL_DeleteContext(m_gl_context);
131 SDL_DestroyWindow(m_window);
135 void Screen::Clear(float r, float g, float b, float a)
137 glClearColor(r,g,b,a);
138 glClear(GL_COLOR_BUFFER_BIT);
142 void Screen::ResizeViewport(int width, int height)
144 glViewport(0, 0, width, height);
145 m_viewport_width = width;
146 m_viewport_height = height;
147 GLfloat viewportfloats[] = {(float)width, (float)height};
148 m_viewport_ubo.Upload(sizeof(float)*2, viewportfloats);
151 bool Screen::PumpEvents()
154 bool no_quit_requested = true;
155 while (SDL_PollEvent(&evt))
160 no_quit_requested = false;
162 case SDL_WINDOWEVENT:
163 switch (evt.window.event)
165 case SDL_WINDOWEVENT_RESIZED:
166 case SDL_WINDOWEVENT_SIZE_CHANGED:
167 ResizeViewport(evt.window.data1, evt.window.data2);
171 case SDL_MOUSEMOTION:
172 m_last_mouse_x = evt.motion.x;
173 m_last_mouse_y = evt.motion.y;
176 m_mouse_handler(evt.motion.x, evt.motion.y,evt.motion.state, 0);
179 case SDL_MOUSEBUTTONDOWN:
180 case SDL_MOUSEBUTTONUP:
181 m_last_mouse_x = evt.button.x;
182 m_last_mouse_y = evt.button.y;
185 m_mouse_handler(evt.button.x, evt.button.y, evt.button.state?evt.button.button:0, 0);
191 m_mouse_handler(m_last_mouse_x, m_last_mouse_y, 0, evt.wheel.y);
196 Debug("Key %c down", (char)evt.key.keysym.sym);
197 if (isalnum((char)evt.key.keysym.sym))
199 char filename[] = "0.bmp";
200 filename[0] = (char)evt.key.keysym.sym;
201 ScreenShot(filename);
209 return no_quit_requested;
212 void Screen::SetMouseCursor(Screen::MouseCursors cursor)
214 SDL_SystemCursor system_cursor_id = SDL_SYSTEM_CURSOR_ARROW;
217 case CursorArrow: system_cursor_id = SDL_SYSTEM_CURSOR_ARROW; break;
218 case CursorWait: system_cursor_id = SDL_SYSTEM_CURSOR_WAIT; break;
219 case CursorWaitArrow: system_cursor_id = SDL_SYSTEM_CURSOR_WAITARROW; break;
220 case CursorMove: system_cursor_id = SDL_SYSTEM_CURSOR_SIZEALL; break;
221 case CursorHand: system_cursor_id = SDL_SYSTEM_CURSOR_HAND; break;
224 SDL_Cursor *system_cursor = SDL_CreateSystemCursor(system_cursor_id);
225 SDL_SetCursor(system_cursor);
226 //TODO: Check if we need to free the system cursors.
229 void Screen::Present()
231 if (m_debug_font_atlas)
233 SDL_GL_SwapWindow(m_window);
236 void Screen::ScreenShot(const char * filename) const
238 Debug("Attempting to save BMP to file %s", filename);
240 int w = ViewportWidth();
241 int h = ViewportHeight();
242 unsigned char * pixels = new unsigned char[w*h*4];
244 Fatal("Failed to allocate %d x %d x 4 = %d pixel array", w, h, w*h*4);
246 for (int y = 0; y < h; ++y)
248 glReadPixels(0,h-y-1,w, 1, GL_RGBA, GL_UNSIGNED_BYTE, &pixels[y*w*4]);
251 #if SDL_BYTEORDER == SDL_LIL_ENDIAN
252 SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(pixels, w, h, 8*4, w*4, 0x000000ff,0x0000ff00,0x00ff0000,0xff000000);
254 SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(pixels, w, h, 8*4, w*4, 0xff000000,0x00ff0000,0x0000ff00,0x000000ff);
257 Fatal("Failed to create SDL_Surface from pixel data - %s", SDL_GetError());
259 GLenum texture_format = (surf->format->Rmask == 0x000000FF) ? GL_RGBA : GL_BGRA;
260 Debug("SDL_Surface %d BytesPerPixel, format %d (RGB = %d, BGR = %d, RGBA = %d, BGRA = %d)", surf->format->BytesPerPixel, texture_format, GL_RGB, GL_BGR, GL_RGBA, GL_BGRA);
262 if (SDL_SaveBMP(surf, filename) != 0)
263 Fatal("SDL_SaveBMP failed - %s", SDL_GetError());
265 SDL_FreeSurface(surf);
272 * NOT PART OF THE DOCUMENT FORMAT
274 void Screen::RenderBMP(const char * filename) const
276 if (access(filename, R_OK) == -1)
278 Error("No such file \"%s\" - Nothing to render - You might have done this deliberately?", filename);
281 SDL_Surface * bmp = SDL_LoadBMP(filename);
283 Fatal("Failed to load BMP from %s - %s", filename, SDL_GetError());
288 GLenum texture_format;
289 switch (bmp->format->BytesPerPixel)
291 case 4: //contains alpha
292 texture_format = (bmp->format->Rmask == 0x000000FF) ? GL_RGBA : GL_BGRA;
294 case 3: //does not contain alpha
295 texture_format = (bmp->format->Rmask == 0x000000FF) ? GL_RGB : GL_BGR;
298 Fatal("Could not understand SDL_Surface format (%d colours)", bmp->format->BytesPerPixel);
302 //Debug("SDL_Surface %d BytesPerPixel, format %d (RGB = %d, BGR = %d, RGBA = %d, BGRA = %d)", bmp->format->BytesPerPixel, texture_format, GL_RGB, GL_BGR, GL_RGBA, GL_BGRA);
304 m_texture_prog.Use();
305 GraphicsBuffer quad_vertex_buffer;
306 quad_vertex_buffer.SetUsage(GraphicsBuffer::BufferUsageStaticDraw);
307 quad_vertex_buffer.SetType(GraphicsBuffer::BufferTypeVertex);
310 1, 0, ViewportWidth(), 0,
311 1, 1, ViewportWidth(), ViewportHeight(),
312 0, 1, 0, ViewportHeight()
314 quad_vertex_buffer.Upload(sizeof(GLfloat) * 16, quad);
315 quad_vertex_buffer.Bind();
316 m_viewport_ubo.Bind();
318 glUniform4f(m_colour_uniform_location, 1.0f, 1.0f, 1.0f, 1.0f);
321 glGenTextures(1, &texID);
322 glBindTexture(GL_TEXTURE_2D, texID);
324 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
325 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
326 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
327 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
329 glTexImage2D(GL_TEXTURE_2D, 0, bmp->format->BytesPerPixel, w, h, 0, texture_format, GL_UNSIGNED_BYTE, bmp->pixels);
331 glEnableVertexAttribArray(0);
332 glEnableVertexAttribArray(1);
333 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), (void*)(2*sizeof(float)));
334 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), 0);
335 glDisableVertexAttribArray(1);
336 glDisableVertexAttribArray(0);
337 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
339 SDL_FreeSurface(bmp);
342 void Screen::DebugFontInit(const char *name, float font_size)
344 unsigned char font_atlas_data[1024*1024];
345 FILE *font_file = fopen(name, "rb");
346 fseek(font_file, 0, SEEK_END);
347 size_t font_file_size = ftell(font_file);
348 fseek(font_file, 0, SEEK_SET);
349 unsigned char *font_file_data = (unsigned char*)malloc(font_file_size);
350 fread(font_file_data, 1, font_file_size, font_file);
352 stbtt_BakeFontBitmap(font_file_data,0, font_size, font_atlas_data,1024,1024, 32,96, m_debug_font_rects);
353 free(font_file_data);
354 glGenTextures(1, &m_debug_font_atlas);
355 glBindTexture(GL_TEXTURE_2D, m_debug_font_atlas);
356 glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 1024,1024, 0, GL_RED, GL_UNSIGNED_BYTE, font_atlas_data);
357 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
358 m_debug_font_size = font_size;
360 m_debug_font_vertices.SetUsage(GraphicsBuffer::BufferUsageStreamDraw);
361 m_debug_font_vertices.SetType(GraphicsBuffer::BufferTypeVertex);
362 m_debug_font_vertices.Upload(8192, nullptr);
363 m_debug_font_vertex_head = 0;
365 m_debug_font_indices.SetUsage(GraphicsBuffer::BufferUsageStreamDraw);
366 m_debug_font_indices.SetType(GraphicsBuffer::BufferTypeIndex);
367 m_debug_font_indices.Resize(500);
368 m_debug_font_index_head = 0;
371 void Screen::DebugFontClear()
373 m_debug_font_x = m_debug_font_y = 0;
374 if (!m_debug_font_atlas) return;
375 DebugFontPrint("\n");
378 void Screen::DebugFontFlush()
383 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
384 glBindTexture(GL_TEXTURE_2D, m_debug_font_atlas);
386 m_texture_prog.Use();
387 m_viewport_ubo.Bind();
388 m_debug_font_vertices.Bind();
389 m_debug_font_indices.Bind();
390 glUniform4f(m_colour_uniform_location, 0,0,0,1);
391 glEnableVertexAttribArray(0);
392 glEnableVertexAttribArray(1);
393 glEnable(GL_PRIMITIVE_RESTART);
394 glPrimitiveRestartIndex(65535);
395 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), (void*)(2*sizeof(float)));
396 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), 0);
397 glDrawElements(GL_TRIANGLE_STRIP, m_debug_font_index_head, GL_UNSIGNED_SHORT, 0);
398 glDisable(GL_PRIMITIVE_RESTART);
399 glDisableVertexAttribArray(1);
400 glDisableVertexAttribArray(0);
404 m_debug_font_vertex_head = 0;
405 m_debug_font_index_head = 0;
408 void Screen::DebugFontPrint(const char* str)
410 if (!m_debug_font_atlas) return;
412 float *vertexData = (float*)m_debug_font_vertices.MapRange(m_debug_font_vertex_head*sizeof(float), m_debug_font_vertices.GetSize() - m_debug_font_vertex_head*sizeof(float), false, true, true);
413 uint16_t *indexData = (uint16_t*)m_debug_font_indices.MapRange(m_debug_font_index_head*sizeof(uint16_t), m_debug_font_indices.GetSize() - m_debug_font_index_head*sizeof(uint16_t), false, true, true);
415 if ((m_debug_font_vertex_head*sizeof(float) + 16*sizeof(float) >= m_debug_font_vertices.GetSize() ) ||
416 (m_debug_font_index_head*sizeof(uint16_t) + 5*sizeof(uint16_t) >= m_debug_font_indices.GetSize()))
418 m_debug_font_indices.UnMap();
419 m_debug_font_vertices.UnMap();
424 if (*str >= 32 && *str < 128) {
425 stbtt_aligned_quad q;
426 stbtt_GetBakedQuad(m_debug_font_rects, 1024,1024, *str-32, &m_debug_font_x,&m_debug_font_y,&q,1);
427 *vertexData = q.s0; vertexData++;
428 *vertexData = q.t0; vertexData++;
429 *vertexData = q.x0; vertexData++;
430 *vertexData = q.y0; vertexData++;
431 *vertexData = q.s1; vertexData++;
432 *vertexData = q.t0; vertexData++;
433 *vertexData = q.x1; vertexData++;
434 *vertexData = q.y0; vertexData++;
435 *vertexData = q.s1; vertexData++;
436 *vertexData = q.t1; vertexData++;
437 *vertexData = q.x1; vertexData++;
438 *vertexData = q.y1; vertexData++;
439 *vertexData = q.s0; vertexData++;
440 *vertexData = q.t1; vertexData++;
441 *vertexData = q.x0; vertexData++;
442 *vertexData = q.y1; vertexData++;
444 *indexData = m_debug_font_vertex_head/4; indexData++;
445 *indexData = m_debug_font_vertex_head/4+1; indexData++;
446 *indexData = m_debug_font_vertex_head/4+3; indexData++;
447 *indexData = m_debug_font_vertex_head/4+2; indexData++;
448 *indexData = 65535; indexData++;
450 m_debug_font_vertex_head += 16;
451 m_debug_font_index_head += 5;
454 else if (*str == '\n')
457 m_debug_font_y += m_debug_font_size;
461 m_debug_font_indices.UnMap();
462 m_debug_font_vertices.UnMap();
466 void Screen::DebugFontPrintF(const char *fmt, ...)
471 vsnprintf(buffer, BUFSIZ, fmt,va);
473 DebugFontPrint(buffer);