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

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