Go nuts with Qt
[ipdf/code.git] / src / screen.cpp
1 #include "common.h"
2 #include "screen.h"
3
4 #include "gl_core44.h"
5 #include <fcntl.h> // for access(2)
6 #include <unistd.h> // for access(2)
7
8 #include "bufferbuilder.h"
9 #include "shaderprogram.h"
10
11 #define BASICTEX_VERT "shaders/basictex_vert.glsl"
12 #define BASICTEX_FRAG "shaders/basictex_frag.glsl"
13
14 using namespace IPDF;
15 using namespace std;
16
17 static void opengl_debug_callback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* msg, const void *data)
18 {
19         // Don't print out gl Errors we generated.
20         if (source == GL_DEBUG_SOURCE_APPLICATION) return;
21         //Error("OpenGL Error (%d): %s", id, msg);
22         // Spams this message on fglrx, disabling for now because it's damn annoying.
23         // ERROR: opengl_debug_callback (screen.cpp:21) - OpenGL Error (1011): glObjectLabel failed because (depending on the operation) a referenced binding point is empty; a referenced name is not the name of an object; or the given name is otherwise not valid to this operation (GL_INVALID_VALUE)
24 }
25
26
27 Screen::Screen()
28 {
29
30         SDL_Init(SDL_INIT_VIDEO);
31         m_window = SDL_CreateWindow("IPDF", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
32                         800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
33
34         if (!m_window)
35         {
36                 Fatal("Couldn't create window!");
37         }
38
39         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
40         SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
41         SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
42         SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
43
44         m_gl_context = SDL_GL_CreateContext(m_window);
45
46         ogl_LoadFunctions();
47
48         // Why is this so horribly broken?
49         if (ogl_IsVersionGEQ(3,0))
50         {
51                 Fatal("We require OpenGL 3.1, but you have version %d.%d!",ogl_GetMajorVersion(), ogl_GetMinorVersion());
52         }
53
54         if (!SDL_GL_ExtensionSupported("GL_ARB_shading_language_420pack"))
55         {
56                 Fatal("Your system does not support the ARB_shading_language_420pack extension, which is required.");
57         }
58
59         if (!SDL_GL_ExtensionSupported("GL_ARB_explicit_attrib_location"))
60         {
61                 Fatal("Your system does not support the ARB_explicit_attrib_location extension, which is required.");
62         }
63
64         m_frame_begin_time = SDL_GetPerformanceCounter();
65         m_last_frame_time = 0;
66         m_last_frame_gpu_timer = 0;
67         glGenQueries(1, &m_frame_gpu_timer);
68         glBeginQuery(GL_TIME_ELAPSED, m_frame_gpu_timer);
69
70         glDebugMessageCallback(opengl_debug_callback, 0);
71
72         GLuint default_vao;
73         glGenVertexArrays(1, &default_vao);
74         glBindVertexArray(default_vao);
75
76         m_texture_prog.InitialiseShaders(BASICTEX_VERT, BASICTEX_FRAG);
77         m_texture_prog.Use();
78
79         // We always want to use the texture bound to texture unit 0.
80         GLint texture_uniform_location = m_texture_prog.GetUniformLocation("tex");
81         glUniform1i(texture_uniform_location, 0);
82
83         m_font_prog.InitialiseShaders(BASICTEX_VERT, "shaders/fonttex_frag.glsl");
84         m_font_prog.Use();
85
86         // We always want to use the texture bound to texture unit 0.
87         GLint font_texture_uniform_location = m_font_prog.GetUniformLocation("tex");
88         glUniform1i(font_texture_uniform_location, 0);
89         m_colour_uniform_location = m_font_prog.GetUniformLocation("colour");
90
91         m_viewport_ubo.SetUsage(GraphicsBuffer::BufferUsageDynamicDraw);
92         m_viewport_ubo.SetType(GraphicsBuffer::BufferTypeUniform);
93
94         m_debug_font_atlas = 0;
95         m_no_quit_requested = true;
96         m_show_debug_font = true;
97         m_view = NULL;
98         ResizeViewport(800, 600);
99         
100         
101         
102         Clear();
103         Present();
104         
105
106 }
107
108 Screen::~Screen()
109 {
110         SDL_GL_DeleteContext(m_gl_context);
111         SDL_DestroyWindow(m_window);
112         SDL_Quit();
113 }
114
115 void Screen::Clear(float r, float g, float b, float a)
116 {
117         glClearColor(r,g,b,a);
118         glClear(GL_COLOR_BUFFER_BIT);
119         DebugFontClear();
120 }
121
122 void Screen::ResizeViewport(int width, int height)
123 {
124         glViewport(0, 0, width, height);
125         m_viewport_width = width;
126         m_viewport_height = height;
127         GLfloat viewportfloats[] = {(float)width, (float)height};
128         m_viewport_ubo.Upload(sizeof(float)*2, viewportfloats);
129 }
130
131 bool Screen::PumpEvents()
132 {
133         SDL_Event evt;
134         
135         while (SDL_PollEvent(&evt))
136         {
137                 switch (evt.type)
138                 {
139                 case SDL_QUIT:
140                         m_no_quit_requested = false;
141                         break;
142                 case SDL_WINDOWEVENT:
143                         switch (evt.window.event)
144                         {
145                         case SDL_WINDOWEVENT_RESIZED:
146                         case SDL_WINDOWEVENT_SIZE_CHANGED:
147                                 ResizeViewport(evt.window.data1, evt.window.data2);
148                                 break;
149                         }
150                         break;
151                 case SDL_MOUSEMOTION:
152                         m_last_mouse_x = evt.motion.x;
153                         m_last_mouse_y = evt.motion.y;
154                         if (m_mouse_handler)
155                         {
156                                 m_mouse_handler(evt.motion.x, evt.motion.y,evt.motion.state, 0, this, m_view);
157                         }
158                         break;
159                 case SDL_MOUSEBUTTONDOWN:
160                 case SDL_MOUSEBUTTONUP:
161                         m_last_mouse_x = evt.button.x;
162                         m_last_mouse_y = evt.button.y;
163                         if (m_mouse_handler)
164                         {
165                                 m_mouse_handler(evt.button.x, evt.button.y, evt.button.state?evt.button.button:0, 0, this, m_view);
166                         }
167                         break;
168                 case SDL_MOUSEWHEEL:
169                         if (m_mouse_handler)
170                         {
171                                 m_mouse_handler(m_last_mouse_x, m_last_mouse_y, 0, evt.wheel.y, this, m_view);
172                         }
173                         break;
174                 case SDL_KEYDOWN:
175                 {
176                         Debug("Key %c down", (char)evt.key.keysym.sym);
177                         if (isalnum((char)evt.key.keysym.sym))
178                         {
179                                 char filename[] = "0.bmp";
180                                 filename[0] = (char)evt.key.keysym.sym;
181                                 ScreenShot(filename);
182                         }
183                         break;
184                 }
185                 default:
186                         break;
187                 }
188         }
189         return m_no_quit_requested;
190 }
191
192 void Screen::SetMouseCursor(Screen::MouseCursors cursor)
193 {
194         SDL_SystemCursor system_cursor_id = SDL_SYSTEM_CURSOR_ARROW;
195         switch (cursor)
196         {
197         case CursorArrow: system_cursor_id = SDL_SYSTEM_CURSOR_ARROW; break;
198         case CursorWait: system_cursor_id = SDL_SYSTEM_CURSOR_WAIT; break;
199         case CursorWaitArrow: system_cursor_id = SDL_SYSTEM_CURSOR_WAITARROW; break;
200         case CursorMove: system_cursor_id = SDL_SYSTEM_CURSOR_SIZEALL; break;
201         case CursorHand: system_cursor_id = SDL_SYSTEM_CURSOR_HAND; break;
202         default: break;
203         }
204         SDL_Cursor *system_cursor = SDL_CreateSystemCursor(system_cursor_id);
205         SDL_SetCursor(system_cursor);
206         //TODO: Check if we need to free the system cursors.
207 }
208
209 void Screen::Present()
210 {
211         if (m_debug_font_atlas)
212                 DebugFontFlush();
213         m_last_frame_time = SDL_GetPerformanceCounter() - m_frame_begin_time;
214         glEndQuery(GL_TIME_ELAPSED);
215         SDL_GL_SwapWindow(m_window);
216         m_frame_begin_time = SDL_GetPerformanceCounter();
217         if (m_last_frame_gpu_timer)
218                 glDeleteQueries(1, &m_last_frame_gpu_timer);
219         m_last_frame_gpu_timer = m_frame_gpu_timer;
220         glGenQueries(1, &m_frame_gpu_timer);
221         glBeginQuery(GL_TIME_ELAPSED, m_frame_gpu_timer);
222 }
223
224 double Screen::GetLastFrameTimeGPU() const
225 {
226         if (!m_last_frame_gpu_timer)
227                 return 0;
228         uint64_t frame_time_ns;
229         glGetQueryObjectui64v(m_last_frame_gpu_timer, GL_QUERY_RESULT, &frame_time_ns);
230         return frame_time_ns/1000000000.0;
231 }
232
233 void Screen::RenderPixels(int x, int y, int w, int h, uint8_t *pixels) const
234 {
235         GLenum texture_format = GL_RGBA;
236
237         m_texture_prog.Use();
238         GraphicsBuffer quad_vertex_buffer;
239         quad_vertex_buffer.SetUsage(GraphicsBuffer::BufferUsageStaticDraw);
240         quad_vertex_buffer.SetType(GraphicsBuffer::BufferTypeVertex);
241         //rectangular texture == 2 triangles
242         GLfloat quad[] = { 
243                 0, 0, (float)x, (float)y,
244                 1, 0, (float)(x+w), (float)y,
245                 0, 1, (float)x, (float)(y+h),
246                 1, 1, (float)(x+w), (float)(y+h)
247         };
248         quad_vertex_buffer.Upload(sizeof(GLfloat) * 16, quad);
249         quad_vertex_buffer.Bind();
250         m_viewport_ubo.Bind();
251
252         glUniform4f(m_colour_uniform_location, 1.0f, 1.0f, 1.0f, 1.0f);
253
254         GLuint texID;
255         glGenTextures(1, &texID);
256         glBindTexture(GL_TEXTURE_2D, texID);
257
258         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
259         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
260         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
261         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
262
263         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, texture_format, GL_UNSIGNED_BYTE, pixels);
264
265         glEnableVertexAttribArray(0);
266         glEnableVertexAttribArray(1);
267         glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), (void*)(2*sizeof(float)));
268         glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), 0);
269         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
270         glDisableVertexAttribArray(1);
271         glDisableVertexAttribArray(0);
272
273 }
274
275 void Screen::ScreenShot(const char * filename) const
276 {
277         Debug("Attempting to save BMP to file %s", filename);
278
279         int w = ViewportWidth();
280         int h = ViewportHeight();
281         unsigned char * pixels = new unsigned char[w*h*4];
282         if (pixels == NULL)
283                 Fatal("Failed to allocate %d x %d x 4 = %d pixel array", w, h, w*h*4);
284
285         for (int y = 0; y < h; ++y)
286         {
287                 glReadPixels(0,h-y-1,w, 1, GL_RGBA, GL_UNSIGNED_BYTE, &pixels[y*w*4]);
288         }
289
290 #if SDL_BYTEORDER == SDL_LIL_ENDIAN
291         SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(pixels, w, h, 8*4, w*4, 0x000000ff,0x0000ff00,0x00ff0000,0xff000000);
292 #else
293         SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(pixels, w, h, 8*4, w*4, 0xff000000,0x00ff0000,0x0000ff00,0x000000ff);
294 #endif
295         if (surf == NULL)
296                 Fatal("Failed to create SDL_Surface from pixel data - %s", SDL_GetError());
297
298         GLenum texture_format = (surf->format->Rmask == 0x000000FF) ? GL_RGBA : GL_BGRA;
299         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);
300
301         if (SDL_SaveBMP(surf, filename) != 0)
302                 Fatal("SDL_SaveBMP failed - %s", SDL_GetError());
303         
304         SDL_FreeSurface(surf);
305         delete [] pixels;
306         Debug("Succeeded!");
307 }
308
309 /**
310  * Render a BMP
311  * NOT PART OF THE DOCUMENT FORMAT
312  */
313 void Screen::RenderBMP(const char * filename) const
314 {
315         if (access(filename, R_OK) == -1)
316         {
317                 Error("No such file \"%s\" - Nothing to render - You might have done this deliberately?", filename);
318                 return;
319         }
320         SDL_Surface * bmp = SDL_LoadBMP(filename);
321         if (bmp == NULL)
322                 Fatal("Failed to load BMP from %s - %s", filename, SDL_GetError());
323
324         int w = bmp->w;
325         int h = bmp->h;
326
327         GLenum texture_format = GL_RGBA;
328         switch (bmp->format->BytesPerPixel)
329         {
330                 case 4: //contains alpha
331                         texture_format = (bmp->format->Rmask == 0x000000FF) ? GL_RGBA : GL_BGRA;
332                         break;
333                 case 3: //does not contain alpha
334                         texture_format = (bmp->format->Rmask == 0x000000FF) ? GL_RGB : GL_BGR;  
335                         break;
336                 default:
337                         Fatal("Could not understand SDL_Surface format (%d colours)", bmp->format->BytesPerPixel);
338                         break;  
339         }
340
341         //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);
342
343         m_texture_prog.Use();
344         GraphicsBuffer quad_vertex_buffer;
345         quad_vertex_buffer.SetUsage(GraphicsBuffer::BufferUsageStaticDraw);
346         quad_vertex_buffer.SetType(GraphicsBuffer::BufferTypeVertex);
347         GLfloat quad[] = { 
348                 0, 0, 0, 0,
349                 1, 0, (float)ViewportWidth(), 0,
350                 1, 1, (float)ViewportWidth(), (float)ViewportHeight(),
351                 0, 1, 0, (float)ViewportHeight()
352         };
353         quad_vertex_buffer.Upload(sizeof(GLfloat) * 16, quad);
354         quad_vertex_buffer.Bind();
355         m_viewport_ubo.Bind();
356
357         glUniform4f(m_colour_uniform_location, 1.0f, 1.0f, 1.0f, 1.0f);
358
359         GLuint texID;
360         glGenTextures(1, &texID);
361         glBindTexture(GL_TEXTURE_2D, texID);
362
363         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
364         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
365         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
366         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
367
368         glTexImage2D(GL_TEXTURE_2D, 0, bmp->format->BytesPerPixel, w, h, 0, texture_format, GL_UNSIGNED_BYTE, bmp->pixels);
369
370         glEnableVertexAttribArray(0);
371         glEnableVertexAttribArray(1);
372         glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), (void*)(2*sizeof(float)));
373         glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), 0);
374         glDisableVertexAttribArray(1);
375         glDisableVertexAttribArray(0);
376         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
377
378         SDL_FreeSurface(bmp);   
379 }
380
381 void Screen::DebugFontInit(const char *name, float font_size)
382 {
383         unsigned char font_atlas_data[1024*1024];
384         FILE *font_file = fopen(name, "rb");
385         fseek(font_file, 0, SEEK_END);
386         size_t font_file_size = ftell(font_file);
387         fseek(font_file, 0, SEEK_SET);
388         unsigned char *font_file_data = (unsigned char*)malloc(font_file_size);
389         SDL_assert(fread(font_file_data, 1, font_file_size, font_file) == font_file_size);
390         fclose(font_file);
391         stbtt_BakeFontBitmap(font_file_data,0, font_size, font_atlas_data,1024,1024, 32,96, m_debug_font_rects);
392         free(font_file_data);
393         glGenTextures(1, &m_debug_font_atlas);
394         glBindTexture(GL_TEXTURE_2D, m_debug_font_atlas);
395         glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 1024,1024, 0, GL_RED, GL_UNSIGNED_BYTE, font_atlas_data);
396         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
397         m_debug_font_size = font_size;
398
399         m_debug_font_vertices.SetUsage(GraphicsBuffer::BufferUsageStreamDraw);
400         m_debug_font_vertices.SetType(GraphicsBuffer::BufferTypeVertex);
401         m_debug_font_vertices.SetName("m_debug_font_vertices");
402         m_debug_font_vertices.Upload(8192,NULL);
403         m_debug_font_vertex_head = 0;
404
405         m_debug_font_indices.SetUsage(GraphicsBuffer::BufferUsageStreamDraw);
406         m_debug_font_indices.SetType(GraphicsBuffer::BufferTypeIndex);
407         m_debug_font_indices.SetName("m_debug_font_indices");
408         m_debug_font_indices.Resize(500);
409         m_debug_font_index_head = 0;
410 }
411
412 void Screen::DebugFontClear()
413 {
414         m_debug_font_x = m_debug_font_y = 0;
415         if (!m_debug_font_atlas) return;
416         DebugFontPrint("\n");
417 }
418
419 void Screen::DebugFontFlush()
420 {
421         glPushDebugGroup(GL_DEBUG_SOURCE_APPLICATION, 40, -1, "Screen::DebugFontFlush()");      
422                 
423         glEnable(GL_BLEND);
424         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
425         glBindTexture(GL_TEXTURE_2D, m_debug_font_atlas);
426
427         m_font_prog.Use();
428         m_viewport_ubo.Bind();
429         m_debug_font_vertices.Bind();
430         m_debug_font_indices.Bind();
431         glUniform4f(m_colour_uniform_location, 0,0,0,1);
432         glEnableVertexAttribArray(0);
433         glEnableVertexAttribArray(1);
434         glEnable(GL_PRIMITIVE_RESTART);
435         glPrimitiveRestartIndex(65535);
436         glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), 0);
437         glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), (void*)(2*sizeof(float)));
438         glDrawElements(GL_TRIANGLE_STRIP, m_debug_font_index_head, GL_UNSIGNED_SHORT, 0);
439         glDisable(GL_PRIMITIVE_RESTART);
440         glDisableVertexAttribArray(1);
441         glDisableVertexAttribArray(0);
442
443         glDisable(GL_BLEND);
444
445         m_debug_font_vertices.Invalidate();
446         m_debug_font_indices.Invalidate();
447         m_debug_font_vertex_head = 0;
448         m_debug_font_index_head = 0;
449
450         glPopDebugGroup();
451 }
452
453 struct fontvertex
454 {
455         float x, y, s, t;
456 };
457
458 void Screen::DebugFontPrint(const char* str)
459 {
460         if (!m_debug_font_atlas || !m_show_debug_font) return;
461
462         glPushDebugGroup(GL_DEBUG_SOURCE_APPLICATION, 41, -1, "Screen::DebugFontPrint()");
463
464         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));
465         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));
466
467         size_t baseVertex = m_debug_font_vertex_head/4;
468         while (*str) {
469                 if (!vertexData.Free(4) || !indexData.Free(5))
470                 {
471                         m_debug_font_indices.UnMap();
472                         m_debug_font_vertices.UnMap();
473                         DebugFontFlush();
474                         DebugFontPrint(str);
475                         glPopDebugGroup();
476                         return;
477                 }
478                 if (*str >= 32 && (unsigned char)(*str) < 128) {
479                         stbtt_aligned_quad q;
480                         stbtt_GetBakedQuad(m_debug_font_rects, 1024,1024, *str-32, &m_debug_font_x,&m_debug_font_y,&q,1);
481                         size_t index = vertexData.Add({q.x0, q.y0, q.s0, q.t0});
482                         index += baseVertex;
483                         indexData.Add(index);
484                         index = vertexData.Add({q.x1, q.y0, q.s1, q.t0});
485                         index += baseVertex;
486                         indexData.Add(index);
487                         index = vertexData.Add({q.x0, q.y1, q.s0, q.t1});
488                         index += baseVertex;
489                         indexData.Add(index);
490                         index = vertexData.Add({q.x1, q.y1, q.s1, q.t1});
491                         index += baseVertex;
492                         indexData.Add(index);
493                         indexData.Add(65535);
494
495                         m_debug_font_vertex_head += 16;
496                         m_debug_font_index_head += 5;
497
498                 }
499                 else if (*str == '\n')
500                 {
501                         m_debug_font_x = 0;
502                         m_debug_font_y += m_debug_font_size;
503                 }
504                 ++str;
505         }
506         m_debug_font_indices.UnMap();
507         m_debug_font_vertices.UnMap();
508         glPopDebugGroup();
509         //DebugFontFlush();
510 }
511
512 void Screen::DebugFontPrintF(const char *fmt, ...)
513 {
514         char buffer[BUFSIZ];
515         va_list va;
516         va_start(va, fmt);
517         vsnprintf(buffer, BUFSIZ, fmt,va);
518         va_end(va);
519         DebugFontPrint(buffer);
520 }

UCC git Repository :: git.ucc.asn.au