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

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