2 // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 // Ingo Ruhnke <grumbel@gmail.com>
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include <SDL_image.h>
27 #include "lisp/list_iterator.hpp"
28 #include "lisp/parser.hpp"
29 #include "physfs/physfs_sdl.hpp"
30 #include "supertux/screen.hpp"
31 #include "util/file_system.hpp"
32 #include "util/log.hpp"
33 #include "util/utf8_iterator.hpp"
34 #include "video/drawing_context.hpp"
35 #include "video/drawing_request.hpp"
36 #include "video/font.hpp"
37 #include "video/renderer.hpp"
41 bool vline_empty(SDL_Surface* surface, int x, int start_y, int end_y, Uint8 threshold)
43 Uint8* pixels = (Uint8*)surface->pixels;
45 for(int y = start_y; y < end_y; ++y)
47 const Uint8& p = pixels[surface->pitch*y + x*surface->format->BytesPerPixel + 3];
58 Font::Font(GlyphWidth glyph_width_,
59 const std::string& filename,
61 glyph_width(glyph_width_),
65 shadowsize(shadowsize_),
69 for(unsigned int i=0; i<65536;i++) glyphs[i].surface_idx = -1;
71 const std::string fontdir = FileSystem::dirname(filename);
72 const std::string fontname = FileSystem::basename(filename);
74 // scan for prefix-filename in addons search path
75 char **rc = PHYSFS_enumerateFiles(fontdir.c_str());
76 for (char **i = rc; *i != NULL; i++) {
77 std::string filename_(*i);
78 if( filename_.rfind(fontname) != std::string::npos ) {
79 loadFontFile(fontdir + filename_);
86 Font::loadFontFile(const std::string &filename)
89 log_debug << "Loading font: " << filename << std::endl;
90 const lisp::Lisp* root = parser.parse(filename);
91 const lisp::Lisp* config_l = root->get_lisp("supertux-font");
94 std::ostringstream msg;
95 msg << "Font file:" << filename << ": is not a supertux-font file";
96 throw std::runtime_error(msg.str());
101 if( !config_l->get("glyph-width",def_char_width) ) {
102 log_warning << "Font:"<< filename << ": misses default glyph-width" << std::endl;
105 if( !config_l->get("glyph-height",char_height) ) {
106 std::ostringstream msg;
107 msg << "Font:" << filename << ": misses glyph-height";
108 throw std::runtime_error(msg.str());
111 config_l->get("glyph-border", border);
113 lisp::ListIterator iter(config_l);
115 const std::string& token = iter.item();
116 if( token == "surface" ) {
117 const lisp::Lisp * glyphs_val = iter.lisp();
118 int local_char_width;
120 GlyphWidth local_glyph_width;
121 std::string glyph_image;
122 std::string shadow_image;
123 std::vector<std::string> chars;
124 if( ! glyphs_val->get("glyph-width", local_char_width) ) {
125 local_char_width = def_char_width;
127 if( ! glyphs_val->get("monospace", monospaced ) ) {
128 local_glyph_width = glyph_width;
131 if( monospaced ) local_glyph_width = FIXED;
132 else local_glyph_width = VARIABLE;
134 if( ! glyphs_val->get("glyphs", glyph_image) ) {
135 std::ostringstream msg;
136 msg << "Font:" << filename << ": missing glyphs image";
137 throw std::runtime_error(msg.str());
139 if( ! glyphs_val->get("shadows", shadow_image) ) {
140 std::ostringstream msg;
141 msg << "Font:" << filename << ": missing shadows image";
142 throw std::runtime_error(msg.str());
144 if( ! glyphs_val->get("chars", chars) || chars.size() == 0) {
145 std::ostringstream msg;
146 msg << "Font:" << filename << ": missing chars definition";
147 throw std::runtime_error(msg.str());
150 if( local_char_width==0 ) {
151 std::ostringstream msg;
152 msg << "Font:" << filename << ": misses glyph-width for some surface";
153 throw std::runtime_error(msg.str());
156 loadFontSurface(glyph_image, shadow_image, chars,
157 local_glyph_width, local_char_width);
163 Font::loadFontSurface(
164 const std::string &glyphimage,
165 const std::string &shadowimage,
166 const std::vector<std::string> &chars,
167 GlyphWidth glyph_width_,
171 SurfacePtr glyph_surface = Surface::create("images/engine/fonts/" + glyphimage);
172 SurfacePtr shadow_surface = Surface::create("images/engine/fonts/" + shadowimage);
174 int surface_idx = glyph_surfaces.size();
175 glyph_surfaces.push_back(glyph_surface);
176 shadow_surfaces.push_back(shadow_surface);
179 int wrap = glyph_surface->get_width() / char_width;
181 SDL_Surface *surface = NULL;
183 if( glyph_width_ == VARIABLE ) {
184 //this does not work:
185 // surface = ((SDL::Texture *)glyph_surface.get_texture())->get_texture();
186 surface = IMG_Load_RW(get_physfs_SDLRWops("images/engine/fonts/"+glyphimage), 1);
187 if(surface == NULL) {
188 std::ostringstream msg;
189 msg << "Couldn't load image '" << glyphimage << "' :" << SDL_GetError();
190 throw std::runtime_error(msg.str());
192 SDL_LockSurface(surface);
195 for( unsigned int i = 0; i < chars.size(); i++) {
196 for(UTF8Iterator chr(chars[i]); !chr.done(); ++chr) {
197 int y = row * (char_height + 2*border) + border;
198 int x = col * (char_width + 2*border) + border;
199 if( ++col == wrap ) { col=0; row++; }
200 if( *chr == 0x0020 && glyphs[0x20].surface_idx != -1) continue;
203 glyph.surface_idx = surface_idx;
205 if( glyph_width_ == FIXED || isdigit(*chr) )
207 glyph.rect = Rectf(x, y, x + char_width, y + char_height);
208 glyph.offset = Vector(0, 0);
209 glyph.advance = char_width;
213 if (y + char_height > surface->h)
215 log_warning << "error: font definition contains more letter then the images: " << glyphimage << std::endl;
220 while (left < x + char_width && vline_empty(surface, left, y, y + char_height, 64))
222 int right = x + char_width - 1;
223 while (right > left && vline_empty(surface, right, y, y + char_height, 64))
228 glyph.offset = Vector(x-left, 0);
229 glyph.advance = right - left + 1 + 1; // FIXME: might be useful to make spacing configurable
232 { // glyph is completly transparent
233 glyph.offset = Vector(0, 0);
234 glyph.advance = char_width + 1; // FIXME: might be useful to make spacing configurable
237 glyph.rect = Rectf(x, y, x + char_width, y + char_height);
240 glyphs[*chr] = glyph;
242 if( col>0 && col <= wrap ) {
249 if( surface != NULL ) {
250 SDL_UnlockSurface(surface);
251 SDL_FreeSurface(surface);
260 Font::get_text_width(const std::string& text) const
262 float curr_width = 0;
263 float last_width = 0;
265 for(UTF8Iterator it(text); !it.done(); ++it)
269 last_width = std::max(last_width, curr_width);
274 if( glyphs.at(*it).surface_idx != -1 )
275 curr_width += glyphs[*it].advance;
277 curr_width += glyphs[0x20].advance;
281 return std::max(curr_width, last_width);
285 Font::get_text_height(const std::string& text) const
287 std::string::size_type text_height = char_height;
289 for(std::string::const_iterator it = text.begin(); it != text.end(); ++it)
290 { // since UTF8 multibyte characters are decoded with values
291 // outside the ASCII range there is no risk of overlapping and
292 // thus we don't need to decode the utf-8 string
294 text_height += char_height + 2;
301 Font::get_height() const
307 Font::wrap_to_chars(const std::string& s, int line_length, std::string* overflow)
309 // if text is already smaller, return full text
310 if ((int)s.length() <= line_length) {
311 if (overflow) *overflow = "";
315 // if we can find a whitespace character to break at, return text up to this character
317 while ((i > 0) && (s[i] != ' ')) i--;
319 if (overflow) *overflow = s.substr(i+1);
320 return s.substr(0, i);
323 // FIXME: wrap at line_length, taking care of multibyte characters
324 if (overflow) *overflow = "";
329 Font::wrap_to_width(const std::string& s_, float width, std::string* overflow)
333 // if text is already smaller, return full text
334 if (get_text_width(s) <= width) {
335 if (overflow) *overflow = "";
339 // if we can find a whitespace character to break at, return text up to this character
340 for (int i = s.length()-1; i >= 0; i--) {
341 std::string s2 = s.substr(0,i);
342 if (s[i] != ' ') continue;
343 if (get_text_width(s2) <= width) {
344 if (overflow) *overflow = s.substr(i+1);
345 return s.substr(0, i);
349 // FIXME: hard-wrap at width, taking care of multibyte characters
350 if (overflow) *overflow = "";
355 Font::draw(Renderer *renderer, const std::string& text, const Vector& pos_,
356 FontAlignment alignment, DrawingEffect drawing_effect, Color color,
362 std::string::size_type last = 0;
363 for(std::string::size_type i = 0;; ++i)
365 if (text[i] == '\n' || i == text.size())
367 std::string temp = text.substr(last, i - last);
369 // calculate X positions based on the alignment type
370 Vector pos = Vector(x, y);
372 if(alignment == ALIGN_CENTER)
373 pos.x -= get_text_width(temp) / 2;
374 else if(alignment == ALIGN_RIGHT)
375 pos.x -= get_text_width(temp);
377 // Cast font position to integer to get a clean drawing result and
378 // no blurring as we would get with subpixel positions
379 pos.x = static_cast<int>(pos.x);
381 draw_text(renderer, temp, pos, drawing_effect, color, alpha);
383 if (i == text.size())
386 y += char_height + 2;
393 Font::draw_text(Renderer *renderer, const std::string& text, const Vector& pos,
394 DrawingEffect drawing_effect, Color color, float alpha) const
397 draw_chars(renderer, false, text,
398 pos + Vector(shadowsize, shadowsize), drawing_effect, Color(1,1,1), alpha);
400 draw_chars(renderer, true, text, pos, drawing_effect, color, alpha);
404 Font::draw_chars(Renderer *renderer, bool notshadow, const std::string& text,
405 const Vector& pos, DrawingEffect drawing_effect, Color color,
410 for(UTF8Iterator it(text); !it.done(); ++it)
415 p.y += char_height + 2;
419 p.x += glyphs[0x20].advance;
424 if( glyphs.at(*it).surface_idx != -1 )
427 glyph = glyphs[0x20];
429 DrawingRequest request;
431 request.pos = p + glyph.offset;
432 request.drawing_effect = drawing_effect;
433 request.color = color;
434 request.alpha = alpha;
436 SurfacePartRequest surfacepartrequest;
437 surfacepartrequest.srcrect = glyph.rect;
438 surfacepartrequest.dstsize = glyph.rect.get_size();
439 surfacepartrequest.surface = notshadow ? glyph_surfaces[glyph.surface_idx].get() : shadow_surfaces[glyph.surface_idx].get();
441 request.request_data = &surfacepartrequest;
442 renderer->draw_surface_part(request);
444 p.x += glyph.advance;