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 \
13 "#extension GL_ARB_shading_language_420pack : require\n"\
14 "#extension GL_ARB_explicit_attrib_location : require\n"\
16 "layout(std140, binding=0) uniform Viewport\n"\
22 "layout(location = 0) in vec2 position;\n"\
23 "layout(location = 1) in vec2 tex_coord;\n"\
25 "out vec2 fp_tex_coord;\n"\
29 "\t// Transform to clip coordinates (-1,1, -1,1).\n"\
30 "\tgl_Position.x = (position.x*2/width) - 1;\n"\
31 "\tgl_Position.y = 1 - (position.y*2/height);\n"\
32 "\tgl_Position.z = 0.0;\n"\
33 "\tgl_Position.w = 1.0;\n"\
34 "\tfp_tex_coord = tex_coord;\n"\
37 #define BASICTEX_FRAG \
40 "in vec2 fp_tex_coord;\n"\
42 "out vec4 output_colour;\n"\
44 "uniform sampler2D tex;\n"\
45 "uniform vec4 colour;\n"\
49 "\toutput_colour = colour;\n"\
50 "\toutput_colour.a = texture(tex, fp_tex_coord).r;\n"\
56 static void opengl_debug_callback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* msg, const void *data)
58 Error("OpenGL Error (%d): %s", id, msg);
64 SDL_Init(SDL_INIT_VIDEO);
65 m_window = SDL_CreateWindow("IPDF", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
66 800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
70 Fatal("Couldn't create window!");
73 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
74 SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
75 SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
76 SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
78 m_gl_context = SDL_GL_CreateContext(m_window);
82 // Why is this so horribly broken?
83 if (ogl_IsVersionGEQ(3,0))
85 Fatal("We require OpenGL 3.1, but you have version %d.%d!",ogl_GetMajorVersion(), ogl_GetMinorVersion());
88 if (!SDL_GL_ExtensionSupported("GL_ARB_shading_language_420pack"))
90 Fatal("Your system does not support the ARB_shading_language_420pack extension, which is required.");
93 if (!SDL_GL_ExtensionSupported("GL_ARB_explicit_attrib_location"))
95 Fatal("Your system does not support the ARB_explicit_attrib_location extension, which is required.");
98 m_frame_begin_time = SDL_GetPerformanceCounter();
99 m_last_frame_time = 0;
100 m_last_frame_gpu_timer = 0;
101 glGenQueries(1, &m_frame_gpu_timer);
102 glBeginQuery(GL_TIME_ELAPSED, m_frame_gpu_timer);
104 glDebugMessageCallback(opengl_debug_callback, 0);
107 glGenVertexArrays(1, &default_vao);
108 glBindVertexArray(default_vao);
110 //TODO: Error checking.
111 m_texture_prog.AttachVertexProgram(BASICTEX_VERT);
112 m_texture_prog.AttachFragmentProgram(BASICTEX_FRAG);
113 m_texture_prog.Link();
114 m_texture_prog.Use();
116 // We always want to use the texture bound to texture unit 0.
117 GLint texture_uniform_location = m_texture_prog.GetUniformLocation("tex");
118 glUniform1i(texture_uniform_location, 0);
120 m_colour_uniform_location = m_texture_prog.GetUniformLocation("colour");
122 m_viewport_ubo.SetUsage(GraphicsBuffer::BufferUsageDynamicDraw);
123 m_viewport_ubo.SetType(GraphicsBuffer::BufferTypeUniform);
125 m_debug_font_atlas = 0;
127 ResizeViewport(800, 600);
137 SDL_GL_DeleteContext(m_gl_context);
138 SDL_DestroyWindow(m_window);
142 void Screen::Clear(float r, float g, float b, float a)
144 glClearColor(r,g,b,a);
145 glClear(GL_COLOR_BUFFER_BIT);
149 void Screen::ResizeViewport(int width, int height)
151 glViewport(0, 0, width, height);
152 m_viewport_width = width;
153 m_viewport_height = height;
154 GLfloat viewportfloats[] = {(float)width, (float)height};
155 m_viewport_ubo.Upload(sizeof(float)*2, viewportfloats);
158 bool Screen::PumpEvents()
161 bool no_quit_requested = true;
162 while (SDL_PollEvent(&evt))
167 no_quit_requested = false;
169 case SDL_WINDOWEVENT:
170 switch (evt.window.event)
172 case SDL_WINDOWEVENT_RESIZED:
173 case SDL_WINDOWEVENT_SIZE_CHANGED:
174 ResizeViewport(evt.window.data1, evt.window.data2);
178 case SDL_MOUSEMOTION:
179 m_last_mouse_x = evt.motion.x;
180 m_last_mouse_y = evt.motion.y;
183 m_mouse_handler(evt.motion.x, evt.motion.y,evt.motion.state, 0);
186 case SDL_MOUSEBUTTONDOWN:
187 case SDL_MOUSEBUTTONUP:
188 m_last_mouse_x = evt.button.x;
189 m_last_mouse_y = evt.button.y;
192 m_mouse_handler(evt.button.x, evt.button.y, evt.button.state?evt.button.button:0, 0);
198 m_mouse_handler(m_last_mouse_x, m_last_mouse_y, 0, evt.wheel.y);
203 Debug("Key %c down", (char)evt.key.keysym.sym);
204 if (isalnum((char)evt.key.keysym.sym))
206 char filename[] = "0.bmp";
207 filename[0] = (char)evt.key.keysym.sym;
208 ScreenShot(filename);
216 return no_quit_requested;
219 void Screen::SetMouseCursor(Screen::MouseCursors cursor)
221 SDL_SystemCursor system_cursor_id = SDL_SYSTEM_CURSOR_ARROW;
224 case CursorArrow: system_cursor_id = SDL_SYSTEM_CURSOR_ARROW; break;
225 case CursorWait: system_cursor_id = SDL_SYSTEM_CURSOR_WAIT; break;
226 case CursorWaitArrow: system_cursor_id = SDL_SYSTEM_CURSOR_WAITARROW; break;
227 case CursorMove: system_cursor_id = SDL_SYSTEM_CURSOR_SIZEALL; break;
228 case CursorHand: system_cursor_id = SDL_SYSTEM_CURSOR_HAND; break;
231 SDL_Cursor *system_cursor = SDL_CreateSystemCursor(system_cursor_id);
232 SDL_SetCursor(system_cursor);
233 //TODO: Check if we need to free the system cursors.
236 void Screen::Present()
238 if (m_debug_font_atlas)
240 m_last_frame_time = SDL_GetPerformanceCounter() - m_frame_begin_time;
241 glEndQuery(GL_TIME_ELAPSED);
242 SDL_GL_SwapWindow(m_window);
243 m_frame_begin_time = SDL_GetPerformanceCounter();
244 if (m_last_frame_gpu_timer)
245 glDeleteQueries(1, &m_last_frame_gpu_timer);
246 m_last_frame_gpu_timer = m_frame_gpu_timer;
247 glGenQueries(1, &m_frame_gpu_timer);
248 glBeginQuery(GL_TIME_ELAPSED, m_frame_gpu_timer);
251 double Screen::GetLastFrameTimeGPU() const
253 if (!m_last_frame_gpu_timer)
255 uint64_t frame_time_ns;
256 glGetQueryObjectui64v(m_last_frame_gpu_timer, GL_QUERY_RESULT, &frame_time_ns);
257 return frame_time_ns/1000000000.0;
260 void Screen::ScreenShot(const char * filename) const
262 Debug("Attempting to save BMP to file %s", filename);
264 int w = ViewportWidth();
265 int h = ViewportHeight();
266 unsigned char * pixels = new unsigned char[w*h*4];
268 Fatal("Failed to allocate %d x %d x 4 = %d pixel array", w, h, w*h*4);
270 for (int y = 0; y < h; ++y)
272 glReadPixels(0,h-y-1,w, 1, GL_RGBA, GL_UNSIGNED_BYTE, &pixels[y*w*4]);
275 #if SDL_BYTEORDER == SDL_LIL_ENDIAN
276 SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(pixels, w, h, 8*4, w*4, 0x000000ff,0x0000ff00,0x00ff0000,0xff000000);
278 SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(pixels, w, h, 8*4, w*4, 0xff000000,0x00ff0000,0x0000ff00,0x000000ff);
281 Fatal("Failed to create SDL_Surface from pixel data - %s", SDL_GetError());
283 GLenum texture_format = (surf->format->Rmask == 0x000000FF) ? GL_RGBA : GL_BGRA;
284 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);
286 if (SDL_SaveBMP(surf, filename) != 0)
287 Fatal("SDL_SaveBMP failed - %s", SDL_GetError());
289 SDL_FreeSurface(surf);
296 * NOT PART OF THE DOCUMENT FORMAT
298 void Screen::RenderBMP(const char * filename) const
300 if (access(filename, R_OK) == -1)
302 Error("No such file \"%s\" - Nothing to render - You might have done this deliberately?", filename);
305 SDL_Surface * bmp = SDL_LoadBMP(filename);
307 Fatal("Failed to load BMP from %s - %s", filename, SDL_GetError());
312 GLenum texture_format = GL_RGBA;
313 switch (bmp->format->BytesPerPixel)
315 case 4: //contains alpha
316 texture_format = (bmp->format->Rmask == 0x000000FF) ? GL_RGBA : GL_BGRA;
318 case 3: //does not contain alpha
319 texture_format = (bmp->format->Rmask == 0x000000FF) ? GL_RGB : GL_BGR;
322 Fatal("Could not understand SDL_Surface format (%d colours)", bmp->format->BytesPerPixel);
326 //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);
328 m_texture_prog.Use();
329 GraphicsBuffer quad_vertex_buffer;
330 quad_vertex_buffer.SetUsage(GraphicsBuffer::BufferUsageStaticDraw);
331 quad_vertex_buffer.SetType(GraphicsBuffer::BufferTypeVertex);
334 1, 0, (float)ViewportWidth(), 0,
335 1, 1, (float)ViewportWidth(), (float)ViewportHeight(),
336 0, 1, 0, (float)ViewportHeight()
338 quad_vertex_buffer.Upload(sizeof(GLfloat) * 16, quad);
339 quad_vertex_buffer.Bind();
340 m_viewport_ubo.Bind();
342 glUniform4f(m_colour_uniform_location, 1.0f, 1.0f, 1.0f, 1.0f);
345 glGenTextures(1, &texID);
346 glBindTexture(GL_TEXTURE_2D, texID);
348 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
349 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
350 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
351 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
353 glTexImage2D(GL_TEXTURE_2D, 0, bmp->format->BytesPerPixel, w, h, 0, texture_format, GL_UNSIGNED_BYTE, bmp->pixels);
355 glEnableVertexAttribArray(0);
356 glEnableVertexAttribArray(1);
357 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), (void*)(2*sizeof(float)));
358 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), 0);
359 glDisableVertexAttribArray(1);
360 glDisableVertexAttribArray(0);
361 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
363 SDL_FreeSurface(bmp);
366 void Screen::DebugFontInit(const char *name, float font_size)
368 unsigned char font_atlas_data[1024*1024];
369 FILE *font_file = fopen(name, "rb");
370 fseek(font_file, 0, SEEK_END);
371 size_t font_file_size = ftell(font_file);
372 fseek(font_file, 0, SEEK_SET);
373 unsigned char *font_file_data = (unsigned char*)malloc(font_file_size);
374 fread(font_file_data, 1, font_file_size, font_file);
376 stbtt_BakeFontBitmap(font_file_data,0, font_size, font_atlas_data,1024,1024, 32,96, m_debug_font_rects);
377 free(font_file_data);
378 glGenTextures(1, &m_debug_font_atlas);
379 glBindTexture(GL_TEXTURE_2D, m_debug_font_atlas);
380 glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 1024,1024, 0, GL_RED, GL_UNSIGNED_BYTE, font_atlas_data);
381 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
382 m_debug_font_size = font_size;
384 m_debug_font_vertices.SetUsage(GraphicsBuffer::BufferUsageStreamDraw);
385 m_debug_font_vertices.SetType(GraphicsBuffer::BufferTypeVertex);
386 m_debug_font_vertices.Upload(8192, nullptr);
387 m_debug_font_vertex_head = 0;
389 m_debug_font_indices.SetUsage(GraphicsBuffer::BufferUsageStreamDraw);
390 m_debug_font_indices.SetType(GraphicsBuffer::BufferTypeIndex);
391 m_debug_font_indices.Resize(500);
392 m_debug_font_index_head = 0;
395 void Screen::DebugFontClear()
397 m_debug_font_x = m_debug_font_y = 0;
398 if (!m_debug_font_atlas) return;
399 DebugFontPrint("\n");
402 void Screen::DebugFontFlush()
407 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
408 glBindTexture(GL_TEXTURE_2D, m_debug_font_atlas);
410 m_texture_prog.Use();
411 m_viewport_ubo.Bind();
412 m_debug_font_vertices.Bind();
413 m_debug_font_indices.Bind();
414 glUniform4f(m_colour_uniform_location, 0,0,0,1);
415 glEnableVertexAttribArray(0);
416 glEnableVertexAttribArray(1);
417 glEnable(GL_PRIMITIVE_RESTART);
418 glPrimitiveRestartIndex(65535);
419 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), 0);
420 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), (void*)(2*sizeof(float)));
421 glDrawElements(GL_TRIANGLE_STRIP, m_debug_font_index_head, GL_UNSIGNED_SHORT, 0);
422 glDisable(GL_PRIMITIVE_RESTART);
423 glDisableVertexAttribArray(1);
424 glDisableVertexAttribArray(0);
428 m_debug_font_vertices.Invalidate();
429 m_debug_font_indices.Invalidate();
430 m_debug_font_vertex_head = 0;
431 m_debug_font_index_head = 0;
434 void Screen::DebugFontPrint(const char* str)
436 if (!m_debug_font_atlas) return;
443 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));
444 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));
446 size_t baseVertex = m_debug_font_vertex_head/4;
448 if (!vertexData.Free(4) || !indexData.Free(5))
450 m_debug_font_indices.UnMap();
451 m_debug_font_vertices.UnMap();
456 if (*str >= 32 && (unsigned char)(*str) < 128) {
457 stbtt_aligned_quad q;
458 stbtt_GetBakedQuad(m_debug_font_rects, 1024,1024, *str-32, &m_debug_font_x,&m_debug_font_y,&q,1);
459 size_t index = vertexData.Add({q.x0, q.y0, q.s0, q.t0});
461 indexData.Add(index);
462 index = vertexData.Add({q.x1, q.y0, q.s1, q.t0});
464 indexData.Add(index);
465 index = vertexData.Add({q.x0, q.y1, q.s0, q.t1});
467 indexData.Add(index);
468 index = vertexData.Add({q.x1, q.y1, q.s1, q.t1});
470 indexData.Add(index);
471 indexData.Add(65535);
473 m_debug_font_vertex_head += 16;
474 m_debug_font_index_head += 5;
477 else if (*str == '\n')
480 m_debug_font_y += m_debug_font_size;
484 m_debug_font_indices.UnMap();
485 m_debug_font_vertices.UnMap();
489 void Screen::DebugFontPrintF(const char *fmt, ...)
494 vsnprintf(buffer, BUFSIZ, fmt,va);
496 DebugFontPrint(buffer);