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 // 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)
27 Screen::Screen(bool visible)
30 SDL_Init(SDL_INIT_VIDEO);
31 uint32_t flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE;
33 flags |= SDL_WINDOW_HIDDEN;
35 m_window = SDL_CreateWindow("IPDF", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
40 Fatal("Couldn't create window!");
43 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
44 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
45 SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
46 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
48 m_gl_context = SDL_GL_CreateContext(m_window);
52 // Why is this so horribly broken?
53 if (ogl_IsVersionGEQ(3,0))
55 Error("We require OpenGL 3.1, but you have version %d.%d!",ogl_GetMajorVersion(), ogl_GetMinorVersion());
58 if (!SDL_GL_ExtensionSupported("GL_ARB_shading_language_420pack"))
60 Error("Your system does not support the ARB_shading_language_420pack extension, which is required.");
63 if (!SDL_GL_ExtensionSupported("GL_ARB_explicit_attrib_location"))
65 Error("Your system does not support the ARB_explicit_attrib_location extension, which is required.");
68 m_frame_begin_time = SDL_GetPerformanceCounter();
69 m_last_frame_time = 0;
70 m_last_frame_gpu_timer = 0;
71 glGenQueries(1, &m_frame_gpu_timer);
72 glBeginQuery(GL_TIME_ELAPSED, m_frame_gpu_timer);
74 glDebugMessageCallback(opengl_debug_callback, 0);
77 glGenVertexArrays(1, &default_vao);
78 glBindVertexArray(default_vao);
80 m_texture_prog.InitialiseShaders(BASICTEX_VERT, BASICTEX_FRAG);
83 // We always want to use the texture bound to texture unit 0.
84 GLint texture_uniform_location = m_texture_prog.GetUniformLocation("tex");
85 glUniform1i(texture_uniform_location, 0);
87 m_font_prog.InitialiseShaders(BASICTEX_VERT, "shaders/fonttex_frag.glsl");
90 // We always want to use the texture bound to texture unit 0.
91 GLint font_texture_uniform_location = m_font_prog.GetUniformLocation("tex");
92 glUniform1i(font_texture_uniform_location, 0);
93 m_colour_uniform_location = m_font_prog.GetUniformLocation("colour");
95 m_viewport_ubo.SetUsage(GraphicsBuffer::BufferUsageDynamicDraw);
96 m_viewport_ubo.SetType(GraphicsBuffer::BufferTypeUniform);
98 m_debug_font_atlas = 0;
99 m_no_quit_requested = true;
100 m_show_debug_font = true;
102 ResizeViewport(800, 600);
114 SDL_GL_DeleteContext(m_gl_context);
115 SDL_DestroyWindow(m_window);
119 void Screen::Clear(float r, float g, float b, float a)
121 glClearColor(r,g,b,a);
122 glClear(GL_COLOR_BUFFER_BIT);
126 void Screen::ResizeViewport(int width, int height)
128 glViewport(0, 0, width, height);
129 m_viewport_width = width;
130 m_viewport_height = height;
131 GLfloat viewportfloats[] = {(float)width, (float)height};
132 m_viewport_ubo.Upload(sizeof(float)*2, viewportfloats);
135 bool Screen::PumpEvents()
139 while (SDL_PollEvent(&evt))
144 m_no_quit_requested = false;
146 case SDL_WINDOWEVENT:
147 switch (evt.window.event)
149 case SDL_WINDOWEVENT_RESIZED:
150 case SDL_WINDOWEVENT_SIZE_CHANGED:
151 ResizeViewport(evt.window.data1, evt.window.data2);
155 case SDL_MOUSEMOTION:
156 m_last_mouse_x = evt.motion.x;
157 m_last_mouse_y = evt.motion.y;
160 m_mouse_handler(evt.motion.x, evt.motion.y,evt.motion.state, 0, this, m_view);
163 case SDL_MOUSEBUTTONDOWN:
164 case SDL_MOUSEBUTTONUP:
165 m_last_mouse_x = evt.button.x;
166 m_last_mouse_y = evt.button.y;
169 m_mouse_handler(evt.button.x, evt.button.y, evt.button.state?evt.button.button:0, 0, this, m_view);
175 m_mouse_handler(m_last_mouse_x, m_last_mouse_y, 0, evt.wheel.y, this, m_view);
180 Debug("Key %c down", (char)evt.key.keysym.sym);
181 if (isalnum((char)evt.key.keysym.sym))
183 char filename[] = "0.bmp";
184 filename[0] = (char)evt.key.keysym.sym;
185 ScreenShot(filename);
193 return m_no_quit_requested;
196 void Screen::SetMouseCursor(Screen::MouseCursors cursor)
198 SDL_SystemCursor system_cursor_id = SDL_SYSTEM_CURSOR_ARROW;
201 case CursorArrow: system_cursor_id = SDL_SYSTEM_CURSOR_ARROW; break;
202 case CursorWait: system_cursor_id = SDL_SYSTEM_CURSOR_WAIT; break;
203 case CursorWaitArrow: system_cursor_id = SDL_SYSTEM_CURSOR_WAITARROW; break;
204 case CursorMove: system_cursor_id = SDL_SYSTEM_CURSOR_SIZEALL; break;
205 case CursorHand: system_cursor_id = SDL_SYSTEM_CURSOR_HAND; break;
208 SDL_Cursor *system_cursor = SDL_CreateSystemCursor(system_cursor_id);
209 SDL_SetCursor(system_cursor);
210 //TODO: Check if we need to free the system cursors.
213 void Screen::Present()
215 if (m_debug_font_atlas)
217 m_last_frame_time = SDL_GetPerformanceCounter() - m_frame_begin_time;
218 glEndQuery(GL_TIME_ELAPSED);
219 SDL_GL_SwapWindow(m_window);
220 m_frame_begin_time = SDL_GetPerformanceCounter();
221 if (m_last_frame_gpu_timer)
222 glDeleteQueries(1, &m_last_frame_gpu_timer);
223 m_last_frame_gpu_timer = m_frame_gpu_timer;
224 glGenQueries(1, &m_frame_gpu_timer);
225 glBeginQuery(GL_TIME_ELAPSED, m_frame_gpu_timer);
228 double Screen::GetLastFrameTimeGPU() const
230 if (!m_last_frame_gpu_timer)
232 uint64_t frame_time_ns;
233 glGetQueryObjectui64v(m_last_frame_gpu_timer, GL_QUERY_RESULT, &frame_time_ns);
234 return frame_time_ns/1000000000.0;
237 void Screen::RenderPixels(int x, int y, int w, int h, uint8_t *pixels) const
239 GLenum texture_format = GL_RGBA;
241 m_texture_prog.Use();
242 GraphicsBuffer quad_vertex_buffer;
243 quad_vertex_buffer.SetUsage(GraphicsBuffer::BufferUsageStaticDraw);
244 quad_vertex_buffer.SetType(GraphicsBuffer::BufferTypeVertex);
245 //rectangular texture == 2 triangles
247 0, 0, (float)x, (float)y,
248 1, 0, (float)(x+w), (float)y,
249 0, 1, (float)x, (float)(y+h),
250 1, 1, (float)(x+w), (float)(y+h)
252 quad_vertex_buffer.Upload(sizeof(GLfloat) * 16, quad);
253 quad_vertex_buffer.Bind();
254 m_viewport_ubo.Bind();
256 glUniform4f(m_colour_uniform_location, 1.0f, 1.0f, 1.0f, 1.0f);
259 glGenTextures(1, &texID);
260 glBindTexture(GL_TEXTURE_2D, texID);
262 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
263 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
264 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
265 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
267 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, texture_format, GL_UNSIGNED_BYTE, pixels);
269 glEnableVertexAttribArray(0);
270 glEnableVertexAttribArray(1);
271 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), (void*)(2*sizeof(float)));
272 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), 0);
273 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
274 glDisableVertexAttribArray(1);
275 glDisableVertexAttribArray(0);
279 void Screen::ScreenShot(const char * filename) const
281 Debug("Attempting to save BMP to file %s", filename);
283 int w = ViewportWidth();
284 int h = ViewportHeight();
285 unsigned char * pixels = new unsigned char[w*h*4];
287 Fatal("Failed to allocate %d x %d x 4 = %d pixel array", w, h, w*h*4);
289 for (int y = 0; y < h; ++y)
291 glReadPixels(0,h-y-1,w, 1, GL_RGBA, GL_UNSIGNED_BYTE, &pixels[y*w*4]);
294 #if SDL_BYTEORDER == SDL_LIL_ENDIAN
295 SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(pixels, w, h, 8*4, w*4, 0x000000ff,0x0000ff00,0x00ff0000,0xff000000);
297 SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(pixels, w, h, 8*4, w*4, 0xff000000,0x00ff0000,0x0000ff00,0x000000ff);
300 Fatal("Failed to create SDL_Surface from pixel data - %s", SDL_GetError());
302 GLenum texture_format = (surf->format->Rmask == 0x000000FF) ? GL_RGBA : GL_BGRA;
303 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);
305 if (SDL_SaveBMP(surf, filename) != 0)
306 Fatal("SDL_SaveBMP failed - %s", SDL_GetError());
308 SDL_FreeSurface(surf);
315 * NOT PART OF THE DOCUMENT FORMAT
317 void Screen::RenderBMP(const char * filename) const
319 if (access(filename, R_OK) == -1)
321 Error("No such file \"%s\" - Nothing to render - You might have done this deliberately?", filename);
324 SDL_Surface * bmp = SDL_LoadBMP(filename);
326 Fatal("Failed to load BMP from %s - %s", filename, SDL_GetError());
331 GLenum texture_format = GL_RGBA;
332 switch (bmp->format->BytesPerPixel)
334 case 4: //contains alpha
335 texture_format = (bmp->format->Rmask == 0x000000FF) ? GL_RGBA : GL_BGRA;
337 case 3: //does not contain alpha
338 texture_format = (bmp->format->Rmask == 0x000000FF) ? GL_RGB : GL_BGR;
341 Fatal("Could not understand SDL_Surface format (%d colours)", bmp->format->BytesPerPixel);
345 //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);
347 m_texture_prog.Use();
348 GraphicsBuffer quad_vertex_buffer;
349 quad_vertex_buffer.SetUsage(GraphicsBuffer::BufferUsageStaticDraw);
350 quad_vertex_buffer.SetType(GraphicsBuffer::BufferTypeVertex);
353 1, 0, (float)ViewportWidth(), 0,
354 1, 1, (float)ViewportWidth(), (float)ViewportHeight(),
355 0, 1, 0, (float)ViewportHeight()
357 quad_vertex_buffer.Upload(sizeof(GLfloat) * 16, quad);
358 quad_vertex_buffer.Bind();
359 m_viewport_ubo.Bind();
361 glUniform4f(m_colour_uniform_location, 1.0f, 1.0f, 1.0f, 1.0f);
364 glGenTextures(1, &texID);
365 glBindTexture(GL_TEXTURE_2D, texID);
367 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
368 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
369 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
370 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
372 glTexImage2D(GL_TEXTURE_2D, 0, bmp->format->BytesPerPixel, w, h, 0, texture_format, GL_UNSIGNED_BYTE, bmp->pixels);
374 glEnableVertexAttribArray(0);
375 glEnableVertexAttribArray(1);
376 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), (void*)(2*sizeof(float)));
377 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), 0);
378 glDisableVertexAttribArray(1);
379 glDisableVertexAttribArray(0);
380 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
382 SDL_FreeSurface(bmp);
385 void Screen::DebugFontInit(const char *name, float font_size)
387 unsigned char font_atlas_data[1024*1024];
388 FILE *font_file = fopen(name, "rb");
389 fseek(font_file, 0, SEEK_END);
390 size_t font_file_size = ftell(font_file);
391 fseek(font_file, 0, SEEK_SET);
392 unsigned char *font_file_data = (unsigned char*)malloc(font_file_size);
393 SDL_assert(fread(font_file_data, 1, font_file_size, font_file) == font_file_size);
395 stbtt_BakeFontBitmap(font_file_data,0, font_size, font_atlas_data,1024,1024, 32,96, m_debug_font_rects);
396 free(font_file_data);
397 glGenTextures(1, &m_debug_font_atlas);
398 glBindTexture(GL_TEXTURE_2D, m_debug_font_atlas);
399 glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 1024,1024, 0, GL_RED, GL_UNSIGNED_BYTE, font_atlas_data);
400 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
401 m_debug_font_size = font_size;
403 m_debug_font_vertices.SetUsage(GraphicsBuffer::BufferUsageStreamDraw);
404 m_debug_font_vertices.SetType(GraphicsBuffer::BufferTypeVertex);
405 m_debug_font_vertices.SetName("m_debug_font_vertices");
406 m_debug_font_vertices.Upload(8192,NULL);
407 m_debug_font_vertex_head = 0;
409 m_debug_font_indices.SetUsage(GraphicsBuffer::BufferUsageStreamDraw);
410 m_debug_font_indices.SetType(GraphicsBuffer::BufferTypeIndex);
411 m_debug_font_indices.SetName("m_debug_font_indices");
412 m_debug_font_indices.Resize(500);
413 m_debug_font_index_head = 0;
416 void Screen::DebugFontClear()
418 m_debug_font_x = m_debug_font_y = 0;
419 if (!m_debug_font_atlas) return;
420 DebugFontPrint("\n");
423 void Screen::DebugFontFlush()
425 glPushDebugGroup(GL_DEBUG_SOURCE_APPLICATION, 40, -1, "Screen::DebugFontFlush()");
428 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
429 glBindTexture(GL_TEXTURE_2D, m_debug_font_atlas);
432 m_viewport_ubo.Bind();
433 m_debug_font_vertices.Bind();
434 m_debug_font_indices.Bind();
435 glUniform4f(m_colour_uniform_location, 0,0,0,1);
436 glEnableVertexAttribArray(0);
437 glEnableVertexAttribArray(1);
438 glEnable(GL_PRIMITIVE_RESTART);
439 glPrimitiveRestartIndex(65535);
440 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), 0);
441 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), (void*)(2*sizeof(float)));
442 glDrawElements(GL_TRIANGLE_STRIP, m_debug_font_index_head, GL_UNSIGNED_SHORT, 0);
443 glDisable(GL_PRIMITIVE_RESTART);
444 glDisableVertexAttribArray(1);
445 glDisableVertexAttribArray(0);
449 m_debug_font_vertices.Invalidate();
450 m_debug_font_indices.Invalidate();
451 m_debug_font_vertex_head = 0;
452 m_debug_font_index_head = 0;
462 void Screen::DebugFontPrint(const char* str)
464 if (!m_debug_font_atlas || !m_show_debug_font) return;
466 glPushDebugGroup(GL_DEBUG_SOURCE_APPLICATION, 41, -1, "Screen::DebugFontPrint()");
468 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));
469 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));
471 size_t baseVertex = m_debug_font_vertex_head/4;
473 if (!vertexData.Free(4) || !indexData.Free(5))
475 m_debug_font_indices.UnMap();
476 m_debug_font_vertices.UnMap();
482 if (*str >= 32 && (unsigned char)(*str) < 128) {
483 stbtt_aligned_quad q;
484 stbtt_GetBakedQuad(m_debug_font_rects, 1024,1024, *str-32, &m_debug_font_x,&m_debug_font_y,&q,1);
485 size_t index = vertexData.Add({q.x0, q.y0, q.s0, q.t0});
487 indexData.Add(index);
488 index = vertexData.Add({q.x1, q.y0, q.s1, q.t0});
490 indexData.Add(index);
491 index = vertexData.Add({q.x0, q.y1, q.s0, q.t1});
493 indexData.Add(index);
494 index = vertexData.Add({q.x1, q.y1, q.s1, q.t1});
496 indexData.Add(index);
497 indexData.Add(65535);
499 m_debug_font_vertex_head += 16;
500 m_debug_font_index_head += 5;
503 else if (*str == '\n')
506 m_debug_font_y += m_debug_font_size;
510 m_debug_font_indices.UnMap();
511 m_debug_font_vertices.UnMap();
516 void Screen::DebugFontPrintF(const char *fmt, ...)
521 vsnprintf(buffer, BUFSIZ, fmt,va);
523 DebugFontPrint(buffer);