1111
1212#include < SDL2/SDL.h>
1313#include < SDL2/SDL_opengl.h>
14+ #include < SDL2/SDL_ttf.h>
1415#include < GL/gl.h>
1516
1617#include " GameBoard.h"
@@ -21,6 +22,60 @@ using std::pair;
2122using std::runtime_error;
2223using std::string;
2324
25+ /* *
26+ * Render some text on screen.
27+ *
28+ * @param fontPath The path to the font ttf
29+ * @param fontSize The size to draw the letters in.
30+ * @param bottomLeft The bottom left screen coordinate of the bounding box to draw to.
31+ * @param topRight The top right screen coordinate of the bounding box to draw to.
32+ * @param text The text to render.
33+ */
34+ void renderText (const std::string& fontPath, int fontSize, const std::pair<float , float > bottomLeft, const std::pair<float , float > topRight, const std::string& text) {
35+ TTF_Font* font = TTF_OpenFont (fontPath.c_str (), fontSize);
36+ if (!font) {
37+ throw runtime_error (" TTF_OpenFont: " + string (TTF_GetError ()));
38+ }
39+
40+ SDL_Color color { 0 , 0 , 0 , 255 };
41+
42+ SDL_Surface* textSurface = TTF_RenderText_Solid (font, text.c_str (), color);
43+ TTF_CloseFont (font);
44+
45+ if (!textSurface) {
46+ throw runtime_error (" TTF_RenderText_Solid: " + string (TTF_GetError ()));
47+ }
48+
49+ SDL_PixelFormat* format = SDL_AllocFormat (SDL_PIXELFORMAT_RGB888);
50+
51+ SDL_Surface* imageSurface = SDL_ConvertSurface (textSurface, format, 0 );
52+
53+ SDL_FreeSurface (textSurface);
54+
55+ GLuint texture;
56+ glGenTextures (1 , &texture);
57+ glBindTexture (GL_TEXTURE_2D, texture);
58+
59+ glTexImage2D (GL_TEXTURE_2D, 0 , GL_RGB, textSurface->w , textSurface->h , 0 , GL_RGBA, GL_UNSIGNED_BYTE, imageSurface->pixels );
60+ glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
61+ glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
62+
63+ SDL_FreeSurface (imageSurface);
64+
65+ glBegin (GL_QUADS);
66+ glTexCoord2f (0 , 1 );
67+ glVertex2f (bottomLeft.first , bottomLeft.second );
68+ glTexCoord2f (0 , 0 );
69+ glVertex2f (bottomLeft.first , topRight.second );
70+ glTexCoord2f (1 , 0 );
71+ glVertex2f (topRight.first , topRight.second );
72+ glTexCoord2f (1 , 1 );
73+ glVertex2f (topRight.first , bottomLeft.second );
74+ glEnd ();
75+
76+ glDeleteTextures (1 , &texture);
77+ }
78+
2479/* *
2580 * Loads an image into an OpenGL texture.
2681 * @param name The file name of the texture to load.
0 commit comments