5 #include <fcntl.h> // for access(2)
6 #include <unistd.h> // for access(2)
8 #include "bufferbuilder.h"
9 #include "shaderprogram.h"
11 #define BASICTEX_VERT "shaders/basictex_vert.glsl"
12 #define BASICTEX_FRAG "shaders/basictex_frag.glsl"
17 static void opengl_debug_callback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* msg, const void *data)
19 Error("OpenGL Error (%d): %s", id, msg);
26 SDL_Init(SDL_INIT_VIDEO);
27 m_window = SDL_CreateWindow("IPDF", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
28 800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
32 Fatal("Couldn't create window!");
35 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
36 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
37 SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
38 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
40 m_gl_context = SDL_GL_CreateContext(m_window);
44 // Why is this so horribly broken?
45 if (ogl_IsVersionGEQ(3,0))
47 Fatal("We require OpenGL 3.1, but you have version %d.%d!",ogl_GetMajorVersion(), ogl_GetMinorVersion());
50 if (!SDL_GL_ExtensionSupported("GL_ARB_shading_language_420pack"))
52 Fatal("Your system does not support the ARB_shading_language_420pack extension, which is required.");
55 if (!SDL_GL_ExtensionSupported("GL_ARB_explicit_attrib_location"))
57 Fatal("Your system does not support the ARB_explicit_attrib_location extension, which is required.");
60 m_frame_begin_time = SDL_GetPerformanceCounter();
61 m_last_frame_time = 0;
62 m_last_frame_gpu_timer = 0;
63 glGenQueries(1, &m_frame_gpu_timer);
64 glBeginQuery(GL_TIME_ELAPSED, m_frame_gpu_timer);
66 glDebugMessageCallback(opengl_debug_callback, 0);
69 glGenVertexArrays(1, &default_vao);
70 glBindVertexArray(default_vao);
72 m_texture_prog.InitialiseShaders(BASICTEX_VERT, BASICTEX_FRAG);
75 // We always want to use the texture bound to texture unit 0.
76 GLint texture_uniform_location = m_texture_prog.GetUniformLocation("tex");
77 glUniform1i(texture_uniform_location, 0);
79 m_font_prog.InitialiseShaders(BASICTEX_VERT, "shaders/fonttex_frag.glsl");
82 // We always want to use the texture bound to texture unit 0.
83 GLint font_texture_uniform_location = m_font_prog.GetUniformLocation("tex");
84 glUniform1i(font_texture_uniform_location, 0);
85 m_colour_uniform_location = m_font_prog.GetUniformLocation("colour");
87 m_viewport_ubo.SetUsage(GraphicsBuffer::BufferUsageDynamicDraw);
88 m_viewport_ubo.SetType(GraphicsBuffer::BufferTypeUniform);
90 m_debug_font_atlas = 0;
92 ResizeViewport(800, 600);
102 SDL_GL_DeleteContext(m_gl_context);
103 SDL_DestroyWindow(m_window);
107 void Screen::Clear(float r, float g, float b, float a)
109 glClearColor(r,g,b,a);
110 glClear(GL_COLOR_BUFFER_BIT);
114 void Screen::ResizeViewport(int width, int height)
116 glViewport(0, 0, width, height);
117 m_viewport_width = width;
118 m_viewport_height = height;
119 GLfloat viewportfloats[] = {(float)width, (float)height};
120 m_viewport_ubo.Upload(sizeof(float)*2, viewportfloats);
123 bool Screen::PumpEvents()
126 bool no_quit_requested = true;
127 while (SDL_PollEvent(&evt))
132 no_quit_requested = false;
134 case SDL_WINDOWEVENT:
135 switch (evt.window.event)
137 case SDL_WINDOWEVENT_RESIZED:
138 case SDL_WINDOWEVENT_SIZE_CHANGED:
139 ResizeViewport(evt.window.data1, evt.window.data2);
143 case SDL_MOUSEMOTION:
144 m_last_mouse_x = evt.motion.x;
145 m_last_mouse_y = evt.motion.y;
148 m_mouse_handler(evt.motion.x, evt.motion.y,evt.motion.state, 0);
151 case SDL_MOUSEBUTTONDOWN:
152 case SDL_MOUSEBUTTONUP:
153 m_last_mouse_x = evt.button.x;
154 m_last_mouse_y = evt.button.y;
157 m_mouse_handler(evt.button.x, evt.button.y, evt.button.state?evt.button.button:0, 0);
163 m_mouse_handler(m_last_mouse_x, m_last_mouse_y, 0, evt.wheel.y);
168 Debug("Key %c down", (char)evt.key.keysym.sym);
169 if (isalnum((char)evt.key.keysym.sym))
171 char filename[] = "0.bmp";
172 filename[0] = (char)evt.key.keysym.sym;
173 ScreenShot(filename);
181 return no_quit_requested;
184 void Screen::SetMouseCursor(Screen::MouseCursors cursor)
186 SDL_SystemCursor system_cursor_id = SDL_SYSTEM_CURSOR_ARROW;
189 case CursorArrow: system_cursor_id = SDL_SYSTEM_CURSOR_ARROW; break;
190 case CursorWait: system_cursor_id = SDL_SYSTEM_CURSOR_WAIT; break;
191 case CursorWaitArrow: system_cursor_id = SDL_SYSTEM_CURSOR_WAITARROW; break;
192 case CursorMove: system_cursor_id = SDL_SYSTEM_CURSOR_SIZEALL; break;
193 case CursorHand: system_cursor_id = SDL_SYSTEM_CURSOR_HAND; break;
196 SDL_Cursor *system_cursor = SDL_CreateSystemCursor(system_cursor_id);
197 SDL_SetCursor(system_cursor);
198 //TODO: Check if we need to free the system cursors.
201 void Screen::Present()
203 if (m_debug_font_atlas)
205 m_last_frame_time = SDL_GetPerformanceCounter() - m_frame_begin_time;
206 glEndQuery(GL_TIME_ELAPSED);
207 SDL_GL_SwapWindow(m_window);
208 m_frame_begin_time = SDL_GetPerformanceCounter();
209 if (m_last_frame_gpu_timer)
210 glDeleteQueries(1, &m_last_frame_gpu_timer);
211 m_last_frame_gpu_timer = m_frame_gpu_timer;
212 glGenQueries(1, &m_frame_gpu_timer);
213 glBeginQuery(GL_TIME_ELAPSED, m_frame_gpu_timer);
216 double Screen::GetLastFrameTimeGPU() const
218 if (!m_last_frame_gpu_timer)
220 uint64_t frame_time_ns;
221 glGetQueryObjectui64v(m_last_frame_gpu_timer, GL_QUERY_RESULT, &frame_time_ns);
222 return frame_time_ns/1000000000.0;
225 void Screen::RenderPixels(int x, int y, int w, int h, uint8_t *pixels) const
227 GLenum texture_format = GL_RGBA;
229 m_texture_prog.Use();
230 GraphicsBuffer quad_vertex_buffer;
231 quad_vertex_buffer.SetUsage(GraphicsBuffer::BufferUsageStaticDraw);
232 quad_vertex_buffer.SetType(GraphicsBuffer::BufferTypeVertex);
233 //rectangular texture == 2 triangles
235 0, 0, (float)x, (float)y,
236 1, 0, (float)(x+w), (float)y,
237 0, 1, (float)x, (float)(y+h),
238 1, 1, (float)(x+w), (float)(y+h)
240 quad_vertex_buffer.Upload(sizeof(GLfloat) * 16, quad);
241 quad_vertex_buffer.Bind();
242 m_viewport_ubo.Bind();
244 glUniform4f(m_colour_uniform_location, 1.0f, 1.0f, 1.0f, 1.0f);
247 glGenTextures(1, &texID);
248 glBindTexture(GL_TEXTURE_2D, texID);
250 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
251 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
252 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
253 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
255 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, texture_format, GL_UNSIGNED_BYTE, pixels);
257 glEnableVertexAttribArray(0);
258 glEnableVertexAttribArray(1);
259 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), (void*)(2*sizeof(float)));
260 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), 0);
261 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
262 glDisableVertexAttribArray(1);
263 glDisableVertexAttribArray(0);
267 void Screen::ScreenShot(const char * filename) const
269 Debug("Attempting to save BMP to file %s", filename);
271 int w = ViewportWidth();
272 int h = ViewportHeight();
273 unsigned char * pixels = new unsigned char[w*h*4];
275 Fatal("Failed to allocate %d x %d x 4 = %d pixel array", w, h, w*h*4);
277 for (int y = 0; y < h; ++y)
279 glReadPixels(0,h-y-1,w, 1, GL_RGBA, GL_UNSIGNED_BYTE, &pixels[y*w*4]);
282 #if SDL_BYTEORDER == SDL_LIL_ENDIAN
283 SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(pixels, w, h, 8*4, w*4, 0x000000ff,0x0000ff00,0x00ff0000,0xff000000);
285 SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(pixels, w, h, 8*4, w*4, 0xff000000,0x00ff0000,0x0000ff00,0x000000ff);
288 Fatal("Failed to create SDL_Surface from pixel data - %s", SDL_GetError());
290 GLenum texture_format = (surf->format->Rmask == 0x000000FF) ? GL_RGBA : GL_BGRA;
291 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);
293 if (SDL_SaveBMP(surf, filename) != 0)
294 Fatal("SDL_SaveBMP failed - %s", SDL_GetError());
296 SDL_FreeSurface(surf);
303 * NOT PART OF THE DOCUMENT FORMAT
305 void Screen::RenderBMP(const char * filename) const
307 if (access(filename, R_OK) == -1)
309 Error("No such file \"%s\" - Nothing to render - You might have done this deliberately?", filename);
312 SDL_Surface * bmp = SDL_LoadBMP(filename);
314 Fatal("Failed to load BMP from %s - %s", filename, SDL_GetError());
319 GLenum texture_format = GL_RGBA;
320 switch (bmp->format->BytesPerPixel)
322 case 4: //contains alpha
323 texture_format = (bmp->format->Rmask == 0x000000FF) ? GL_RGBA : GL_BGRA;
325 case 3: //does not contain alpha
326 texture_format = (bmp->format->Rmask == 0x000000FF) ? GL_RGB : GL_BGR;
329 Fatal("Could not understand SDL_Surface format (%d colours)", bmp->format->BytesPerPixel);
333 //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);
335 m_texture_prog.Use();
336 GraphicsBuffer quad_vertex_buffer;
337 quad_vertex_buffer.SetUsage(GraphicsBuffer::BufferUsageStaticDraw);
338 quad_vertex_buffer.SetType(GraphicsBuffer::BufferTypeVertex);
341 1, 0, (float)ViewportWidth(), 0,
342 1, 1, (float)ViewportWidth(), (float)ViewportHeight(),
343 0, 1, 0, (float)ViewportHeight()
345 quad_vertex_buffer.Upload(sizeof(GLfloat) * 16, quad);
346 quad_vertex_buffer.Bind();
347 m_viewport_ubo.Bind();
349 glUniform4f(m_colour_uniform_location, 1.0f, 1.0f, 1.0f, 1.0f);
352 glGenTextures(1, &texID);
353 glBindTexture(GL_TEXTURE_2D, texID);
355 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
356 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
357 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
358 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
360 glTexImage2D(GL_TEXTURE_2D, 0, bmp->format->BytesPerPixel, w, h, 0, texture_format, GL_UNSIGNED_BYTE, bmp->pixels);
362 glEnableVertexAttribArray(0);
363 glEnableVertexAttribArray(1);
364 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), (void*)(2*sizeof(float)));
365 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), 0);
366 glDisableVertexAttribArray(1);
367 glDisableVertexAttribArray(0);
368 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
370 SDL_FreeSurface(bmp);
373 void Screen::DebugFontInit(const char *name, float font_size)
375 unsigned char font_atlas_data[1024*1024];
376 FILE *font_file = fopen(name, "rb");
377 fseek(font_file, 0, SEEK_END);
378 size_t font_file_size = ftell(font_file);
379 fseek(font_file, 0, SEEK_SET);
380 unsigned char *font_file_data = (unsigned char*)malloc(font_file_size);
381 SDL_assert(fread(font_file_data, 1, font_file_size, font_file) == font_file_size);
383 stbtt_BakeFontBitmap(font_file_data,0, font_size, font_atlas_data,1024,1024, 32,96, m_debug_font_rects);
384 free(font_file_data);
385 glGenTextures(1, &m_debug_font_atlas);
386 glBindTexture(GL_TEXTURE_2D, m_debug_font_atlas);
387 glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 1024,1024, 0, GL_RED, GL_UNSIGNED_BYTE, font_atlas_data);
388 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
389 m_debug_font_size = font_size;
391 m_debug_font_vertices.SetUsage(GraphicsBuffer::BufferUsageStreamDraw);
392 m_debug_font_vertices.SetType(GraphicsBuffer::BufferTypeVertex);
393 m_debug_font_vertices.Upload(8192, nullptr);
394 m_debug_font_vertex_head = 0;
396 m_debug_font_indices.SetUsage(GraphicsBuffer::BufferUsageStreamDraw);
397 m_debug_font_indices.SetType(GraphicsBuffer::BufferTypeIndex);
398 m_debug_font_indices.Resize(500);
399 m_debug_font_index_head = 0;
402 void Screen::DebugFontClear()
404 m_debug_font_x = m_debug_font_y = 0;
405 if (!m_debug_font_atlas) return;
406 DebugFontPrint("\n");
409 void Screen::DebugFontFlush()
414 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
415 glBindTexture(GL_TEXTURE_2D, m_debug_font_atlas);
418 m_viewport_ubo.Bind();
419 m_debug_font_vertices.Bind();
420 m_debug_font_indices.Bind();
421 glUniform4f(m_colour_uniform_location, 0,0,0,1);
422 glEnableVertexAttribArray(0);
423 glEnableVertexAttribArray(1);
424 glEnable(GL_PRIMITIVE_RESTART);
425 glPrimitiveRestartIndex(65535);
426 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), 0);
427 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), (void*)(2*sizeof(float)));
428 glDrawElements(GL_TRIANGLE_STRIP, m_debug_font_index_head, GL_UNSIGNED_SHORT, 0);
429 glDisable(GL_PRIMITIVE_RESTART);
430 glDisableVertexAttribArray(1);
431 glDisableVertexAttribArray(0);
435 m_debug_font_vertices.Invalidate();
436 m_debug_font_indices.Invalidate();
437 m_debug_font_vertex_head = 0;
438 m_debug_font_index_head = 0;
441 void Screen::DebugFontPrint(const char* str)
443 if (!m_debug_font_atlas) return;
450 BufferBuilder<fontvertex> vertexData(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), m_debug_font_vertices.GetSize() - m_debug_font_vertex_head*sizeof(float));
451 BufferBuilder<uint16_t> indexData(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), m_debug_font_indices.GetSize() - m_debug_font_index_head*sizeof(uint16_t));
453 size_t baseVertex = m_debug_font_vertex_head/4;
455 if (!vertexData.Free(4) || !indexData.Free(5))
457 m_debug_font_indices.UnMap();
458 m_debug_font_vertices.UnMap();
463 if (*str >= 32 && (unsigned char)(*str) < 128) {
464 stbtt_aligned_quad q;
465 stbtt_GetBakedQuad(m_debug_font_rects, 1024,1024, *str-32, &m_debug_font_x,&m_debug_font_y,&q,1);
466 size_t index = vertexData.Add({q.x0, q.y0, q.s0, q.t0});
468 indexData.Add(index);
469 index = vertexData.Add({q.x1, q.y0, q.s1, q.t0});
471 indexData.Add(index);
472 index = vertexData.Add({q.x0, q.y1, q.s0, q.t1});
474 indexData.Add(index);
475 index = vertexData.Add({q.x1, q.y1, q.s1, q.t1});
477 indexData.Add(index);
478 indexData.Add(65535);
480 m_debug_font_vertex_head += 16;
481 m_debug_font_index_head += 5;
484 else if (*str == '\n')
487 m_debug_font_y += m_debug_font_size;
491 m_debug_font_indices.UnMap();
492 m_debug_font_vertices.UnMap();
496 void Screen::DebugFontPrintF(const char *fmt, ...)
501 vsnprintf(buffer, BUFSIZ, fmt,va);
503 DebugFontPrint(buffer);