Fix (lots of) memory leaks in Game.cpp
[numtypysics.git] / Font.cpp
blobf71c94914b304c46cec4dad15ed15fd143a63f95
1 /*
2 * This file is part of NumptyPhysics
3 * Copyright (C) 2008 Tim Edmonds
4 *
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License as
7 * published by the Free Software Foundation; either version 3 of the
8 * License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
16 #include "Font.h"
17 #include "Canvas.h"
18 #include "Config.h"
19 #include <SDL/SDL_ttf.h>
21 #define FONT(fONTpTR) ((TTF_Font*)((fONTpTR)->m_state))
23 struct FontCanvas : public Canvas
25 FontCanvas( SDL_Surface* s )
26 : Canvas( s )
31 Font::Font( const std::string& file, int ptsize )
33 TTF_Init();
34 std::string fname = Config::findFile(file);
35 m_state = TTF_OpenFont( fname.c_str(), ptsize );
39 Vec2 Font::metrics( const std::string& text ) const
41 Vec2 m;
42 TTF_SizeText( FONT(this), text.c_str(), &m.x, &m.y );
43 return m;
47 void Font::drawLeft( Canvas* canvas, Vec2 pt,
48 const std::string& text, int colour ) const
50 SDL_Surface *surf;
51 SDL_Color bg = { 0xff,0xff,0xff };
52 FontCanvas temp( TTF_RenderText_Blended( FONT(this),
53 text.c_str(),
54 SDL_Color() ) );
55 canvas->drawImage( &temp, pt.x, pt.y );
58 void Font::drawCenter( Canvas* canvas, Vec2 pt,
59 const std::string& text, int colour ) const
61 drawLeft( canvas, pt - metrics(text)/2, text, colour );
64 void Font::drawWrap( Canvas* canvas, Rect area,
65 const std::string& text, int colour ) const
67 Vec2 pos = area.tl;
68 size_t i = 0, e=0;
69 while ( i < text.length() ) {
70 e = text.find_first_of(" \n\r\t",i);
71 if ( i == e ) {
72 i++;
73 } else {
74 std::string word = text.substr(i,i+e);
75 Vec2 wm = metrics( word );
76 if ( pos.x + wm.x > area.br.x ) {
77 pos.x = area.tl.x;
78 pos.y += wm.y;
80 drawLeft( canvas, pos, word, colour );
81 i = e + 1;
84 drawLeft( canvas, pos, text.substr(i), colour );
88 const Font* Font::titleFont()
90 static Font* f = new Font("femkeklaver.ttf",36);
91 return f;
94 const Font* Font::headingFont()
96 static Font* f = new Font("femkeklaver.ttf",24);
97 return f;
100 const Font* Font::blurbFont()
102 static Font* f = new Font("femkeklaver.ttf",16);
103 return f;