2 // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 // Ingo Ruhnke <grumbel@gmx.de>
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/>.
23 #include <SDL_image.h>
26 #include "physfs/physfs_sdl.hpp"
28 #include "util/file_system.hpp"
30 #include "lisp/lisp.hpp"
31 #include "lisp/list_iterator.hpp"
32 #include "lisp/parser.hpp"
33 #include "supertux/screen.hpp"
34 #include "util/log.hpp"
35 #include "video/drawing_context.hpp"
36 #include "video/font.hpp"
37 #include "video/renderer.hpp"
40 bool has_multibyte_mark(unsigned char c);
41 uint32_t decode_utf8(const std::string& text, size_t& p);
42 std::string encode_utf8(uint32_t code);
46 const std::string& text;
47 std::string::size_type pos;
50 UTF8Iterator(const std::string& text_) :
56 chr = decode_utf8(text, pos);
57 } catch (std::exception) {
58 log_debug << "Malformed utf-8 sequence beginning with " << *((uint32_t*)(text.c_str() + pos)) << " found " << std::endl;
65 return pos > text.size();
68 UTF8Iterator& operator++() {
70 chr = decode_utf8(text, pos);
71 } catch (std::exception) {
72 log_debug << "Malformed utf-8 sequence beginning with " << *((uint32_t*)(text.c_str() + pos)) << " found " << std::endl;
80 uint32_t operator*() const {
85 bool vline_empty(SDL_Surface* surface, int x, int start_y, int end_y, Uint8 threshold)
87 Uint8* pixels = (Uint8*)surface->pixels;
89 for(int y = start_y; y < end_y; ++y)
91 const Uint8& p = pixels[surface->pitch*y + x*surface->format->BytesPerPixel + 3];
101 Font::Font(GlyphWidth glyph_width_,
102 const std::string& filename,
104 : glyph_width(glyph_width_),
105 shadowsize(shadowsize_),
108 for(unsigned int i=0; i<65536;i++) glyphs[i].surface_idx = -1;
110 const std::string fontdir = FileSystem::dirname(filename);
111 const std::string fontname = FileSystem::basename(filename);
113 // scan for prefix-filename in addons search path
114 char **rc = PHYSFS_enumerateFiles(fontdir.c_str());
115 for (char **i = rc; *i != NULL; i++) {
116 std::string filename(*i);
117 if( filename.rfind(fontname) != std::string::npos ) {
118 loadFontFile(fontdir + filename);
125 Font::loadFontFile(const std::string &filename)
128 log_debug << "Loading font: " << filename << std::endl;
129 const lisp::Lisp* root = parser.parse(filename);
130 const lisp::Lisp* config_l = root->get_lisp("supertux-font");
133 std::ostringstream msg;
134 msg << "Font file:" << filename << ": is not a supertux-font file";
135 throw std::runtime_error(msg.str());
138 int def_char_width=0;
140 if( !config_l->get("glyph-width",def_char_width) ) {
141 log_warning << "Font:"<< filename << ": misses default glyph-width" << std::endl;
144 if( !config_l->get("glyph-height",char_height) ) {
145 std::ostringstream msg;
146 msg << "Font:" << filename << ": misses glyph-height";
147 throw std::runtime_error(msg.str());
150 lisp::ListIterator iter(config_l);
152 const std::string& token = iter.item();
153 if( token == "surface" ) {
154 const lisp::Lisp * glyphs_val = iter.lisp();
155 int local_char_width;
157 GlyphWidth local_glyph_width;
158 std::string glyph_image;
159 std::string shadow_image;
160 std::vector<std::string> chars;
161 if( ! glyphs_val->get("glyph-width", local_char_width) ) {
162 local_char_width = def_char_width;
164 if( ! glyphs_val->get("monospace", monospaced ) ) {
165 local_glyph_width = glyph_width;
168 if( monospaced ) local_glyph_width = FIXED;
169 else local_glyph_width = VARIABLE;
171 if( ! glyphs_val->get("glyphs", glyph_image) ) {
172 std::ostringstream msg;
173 msg << "Font:" << filename << ": missing glyphs image";
174 throw std::runtime_error(msg.str());
176 if( ! glyphs_val->get("shadows", shadow_image) ) {
177 std::ostringstream msg;
178 msg << "Font:" << filename << ": missing shadows image";
179 throw std::runtime_error(msg.str());
181 if( ! glyphs_val->get("chars", chars) || chars.size() == 0) {
182 std::ostringstream msg;
183 msg << "Font:" << filename << ": missing chars definition";
184 throw std::runtime_error(msg.str());
187 if( local_char_width==0 ) {
188 std::ostringstream msg;
189 msg << "Font:" << filename << ": misses glyph-width for some surface";
190 throw std::runtime_error(msg.str());
193 loadFontSurface(glyph_image, shadow_image, chars,
194 local_glyph_width, local_char_width);
200 Font::loadFontSurface(
201 const std::string &glyphimage,
202 const std::string &shadowimage,
203 const std::vector<std::string> &chars,
204 GlyphWidth glyph_width,
208 Surface glyph_surface("images/engine/fonts/" + glyphimage);
209 Surface shadow_surface("images/engine/fonts/" + shadowimage);
211 int surface_idx = glyph_surfaces.size();
212 glyph_surfaces.push_back(glyph_surface);
213 shadow_surfaces.push_back(shadow_surface);
216 int wrap = glyph_surface.get_width() / char_width;
218 SDL_Surface *surface = NULL;
220 if( glyph_width == VARIABLE ) {
221 //this does not work:
222 // surface = ((SDL::Texture *)glyph_surface.get_texture())->get_texture();
223 surface = IMG_Load_RW(get_physfs_SDLRWops("images/engine/fonts/"+glyphimage), 1);
224 if(surface == NULL) {
225 std::ostringstream msg;
226 msg << "Couldn't load image '" << glyphimage << "' :" << SDL_GetError();
227 throw std::runtime_error(msg.str());
229 SDL_LockSurface(surface);
232 for( unsigned int i = 0; i < chars.size(); i++) {
233 for(UTF8Iterator chr(chars[i]); !chr.done(); ++chr) {
234 int y = row * char_height;
235 int x = col * char_width;
236 if( ++col == wrap ) { col=0; row++; }
237 if( *chr == 0x0020 && glyphs[0x20].surface_idx != -1) continue;
240 glyph.surface_idx = surface_idx;
242 if( glyph_width == FIXED ) {
243 glyph.rect = Rect(x, y, x + char_width, y + char_height);
244 glyph.offset = Vector(0, 0);
245 glyph.advance = char_width;
249 while (left < x + char_width && vline_empty(surface, left, y, y + char_height, 64))
251 int right = x + char_width - 1;
252 while (right > left && vline_empty(surface, right, y, y + char_height, 64))
256 glyph.rect = Rect(left, y, right+1, y + char_height);
257 else // glyph is completely transparent
258 glyph.rect = Rect(x, y, x + char_width, y + char_height);
260 glyph.offset = Vector(0, 0);
261 glyph.advance = glyph.rect.get_width() + 1; // FIXME: might be useful to make spacing configurable
264 glyphs[*chr] = glyph;
266 if( col>0 && col <= wrap ) {
272 if( surface != NULL ) {
273 SDL_UnlockSurface(surface);
274 SDL_FreeSurface(surface);
283 Font::get_text_width(const std::string& text) const
285 float curr_width = 0;
286 float last_width = 0;
288 for(UTF8Iterator it(text); !it.done(); ++it)
292 last_width = std::max(last_width, curr_width);
297 if( glyphs.at(*it).surface_idx != -1 )
298 curr_width += glyphs[*it].advance;
300 curr_width += glyphs[0x20].advance;
304 return std::max(curr_width, last_width);
308 Font::get_text_height(const std::string& text) const
310 std::string::size_type text_height = char_height;
312 for(std::string::const_iterator it = text.begin(); it != text.end(); ++it)
313 { // since UTF8 multibyte characters are decoded with values
314 // outside the ASCII range there is no risk of overlapping and
315 // thus we don't need to decode the utf-8 string
317 text_height += char_height + 2;
324 Font::get_height() const
330 Font::wrap_to_chars(const std::string& s, int line_length, std::string* overflow)
332 // if text is already smaller, return full text
333 if ((int)s.length() <= line_length) {
334 if (overflow) *overflow = "";
338 // if we can find a whitespace character to break at, return text up to this character
340 while ((i > 0) && (s[i] != ' ')) i--;
342 if (overflow) *overflow = s.substr(i+1);
343 return s.substr(0, i);
346 // FIXME: wrap at line_length, taking care of multibyte characters
347 if (overflow) *overflow = "";
352 Font::wrap_to_width(const std::string& s_, float width, std::string* overflow)
356 // if text is already smaller, return full text
357 if (get_text_width(s) <= width) {
358 if (overflow) *overflow = "";
362 // if we can find a whitespace character to break at, return text up to this character
363 for (int i = s.length()-1; i >= 0; i--) {
364 std::string s2 = s.substr(0,i);
365 if (s[i] != ' ') continue;
366 if (get_text_width(s2) <= width) {
367 if (overflow) *overflow = s.substr(i+1);
368 return s.substr(0, i);
372 // FIXME: hard-wrap at width, taking care of multibyte characters
373 if (overflow) *overflow = "";
378 Font::draw(Renderer *renderer, const std::string& text, const Vector& pos_,
379 FontAlignment alignment, DrawingEffect drawing_effect, Color color,
385 std::string::size_type last = 0;
386 for(std::string::size_type i = 0;; ++i)
388 if (text[i] == '\n' || i == text.size())
390 std::string temp = text.substr(last, i - last);
392 // calculate X positions based on the alignment type
393 Vector pos = Vector(x, y);
395 if(alignment == ALIGN_CENTER)
396 pos.x -= get_text_width(temp) / 2;
397 else if(alignment == ALIGN_RIGHT)
398 pos.x -= get_text_width(temp);
400 // Cast font position to integer to get a clean drawing result and
401 // no blurring as we would get with subpixel positions
402 pos.x = static_cast<int>(pos.x);
404 draw_text(renderer, temp, pos, drawing_effect, color, alpha);
406 if (i == text.size())
409 y += char_height + 2;
416 Font::draw_text(Renderer *renderer, const std::string& text, const Vector& pos,
417 DrawingEffect drawing_effect, Color color, float alpha) const
420 draw_chars(renderer, false, text,
421 pos + Vector(shadowsize, shadowsize), drawing_effect, Color(1,1,1), alpha);
423 draw_chars(renderer, true, text, pos, drawing_effect, color, alpha);
427 Font::draw_chars(Renderer *renderer, bool notshadow, const std::string& text,
428 const Vector& pos, DrawingEffect drawing_effect, Color color,
433 for(UTF8Iterator it(text); !it.done(); ++it)
438 p.y += char_height + 2;
442 p.x += glyphs[0x20].advance;
447 if( glyphs.at(*it).surface_idx != -1 )
450 glyph = glyphs[0x20];
452 DrawingRequest request;
454 request.pos = p + glyph.offset;
455 request.drawing_effect = drawing_effect;
456 request.color = color;
457 request.alpha = alpha;
459 SurfacePartRequest surfacepartrequest;
460 surfacepartrequest.size = glyph.rect.p2 - glyph.rect.p1;
461 surfacepartrequest.source = glyph.rect.p1;
462 surfacepartrequest.surface = notshadow ? &(glyph_surfaces[glyph.surface_idx]) : &(shadow_surfaces[glyph.surface_idx]);
464 request.request_data = &surfacepartrequest;
465 renderer->draw_surface_part(request);
467 p.x += glyph.advance;
475 * returns true if this byte matches a bitmask of 10xx.xxxx, i.e. it is the 2nd, 3rd or 4th byte of a multibyte utf8 string
477 bool has_multibyte_mark(unsigned char c) {
478 return ((c & 0300) == 0200);
482 * gets unicode character at byte position @a p of UTF-8 encoded @a
483 * text, then advances @a p to the next character.
485 * @throws std::runtime_error if decoding fails.
486 * See unicode standard section 3.10 table 3-5 and 3-6 for details.
488 uint32_t decode_utf8(const std::string& text, size_t& p)
490 uint32_t c1 = (unsigned char) text[p+0];
492 if (has_multibyte_mark(c1)) std::runtime_error("Malformed utf-8 sequence");
494 if ((c1 & 0200) == 0000) {
495 // 0xxx.xxxx: 1 byte sequence
499 else if ((c1 & 0340) == 0300) {
500 // 110x.xxxx: 2 byte sequence
501 if(p+1 >= text.size()) throw std::range_error("Malformed utf-8 sequence");
502 uint32_t c2 = (unsigned char) text[p+1];
503 if (!has_multibyte_mark(c2)) throw std::runtime_error("Malformed utf-8 sequence");
505 return (c1 & 0037) << 6 | (c2 & 0077);
507 else if ((c1 & 0360) == 0340) {
508 // 1110.xxxx: 3 byte sequence
509 if(p+2 >= text.size()) throw std::range_error("Malformed utf-8 sequence");
510 uint32_t c2 = (unsigned char) text[p+1];
511 uint32_t c3 = (unsigned char) text[p+2];
512 if (!has_multibyte_mark(c2)) throw std::runtime_error("Malformed utf-8 sequence");
513 if (!has_multibyte_mark(c3)) throw std::runtime_error("Malformed utf-8 sequence");
515 return (c1 & 0017) << 12 | (c2 & 0077) << 6 | (c3 & 0077);
517 else if ((c1 & 0370) == 0360) {
518 // 1111.0xxx: 4 byte sequence
519 if(p+3 >= text.size()) throw std::range_error("Malformed utf-8 sequence");
520 uint32_t c2 = (unsigned char) text[p+1];
521 uint32_t c3 = (unsigned char) text[p+2];
522 uint32_t c4 = (unsigned char) text[p+4];
523 if (!has_multibyte_mark(c2)) throw std::runtime_error("Malformed utf-8 sequence");
524 if (!has_multibyte_mark(c3)) throw std::runtime_error("Malformed utf-8 sequence");
525 if (!has_multibyte_mark(c4)) throw std::runtime_error("Malformed utf-8 sequence");
527 return (c1 & 0007) << 18 | (c2 & 0077) << 12 | (c3 & 0077) << 6 | (c4 & 0077);
529 throw std::runtime_error("Malformed utf-8 sequence");