- renamed LEFT_ALLIGN to ALIGN_LEFT
[supertux.git] / src / video / font.cpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //                     Ingo Ruhnke <grumbel@gmx.de>
6 //
7 //  This program is free software; you can redistribute it and/or
8 //  modify it under the terms of the GNU General Public License
9 //  as published by the Free Software Foundation; either version 2
10 //  of the License, or (at your option) any later version.
11 //
12 //  This program is distributed in the hope that it will be useful,
13 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
14 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 //  GNU General Public License for more details.
16 //
17 //  You should have received a copy of the GNU General Public License
18 //  along with this program; if not, write to the Free Software
19 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20
21 #include <config.h>
22
23 #include <cstdlib>
24 #include <cstring>
25 #include <stdexcept>
26
27 #include <SDL_image.h>
28 #include "physfs/physfs_sdl.hpp"
29
30 #include "lisp/parser.hpp"
31 #include "lisp/lisp.hpp"
32 #include "screen.hpp"
33 #include "font.hpp"
34 #include "drawing_context.hpp"
35 #include "log.hpp"
36
37 namespace {
38 bool     has_multibyte_mark(unsigned char c);
39 uint32_t decode_utf8(const std::string& text, size_t& p);
40
41 struct UTF8Iterator
42 {
43   const std::string&     text;
44   std::string::size_type pos;
45   uint32_t chr;
46
47   UTF8Iterator(const std::string& text_)
48     : text(text_),
49       pos(0)
50   {
51     chr = decode_utf8(text, pos);
52   }
53
54   bool done() const
55   {
56     return pos > text.size();
57   }
58
59   UTF8Iterator& operator++() {
60     try {
61       chr = decode_utf8(text, pos);
62     } catch (std::runtime_error) {
63       log_debug << "Malformed utf-8 sequence beginning with " << *((uint32_t*)(text.c_str() + pos)) << " found " << std::endl;
64       chr = 0;
65       ++pos;
66     }
67
68     return *this;
69   }
70
71   uint32_t operator*() const {
72     return chr;
73   }
74 };
75
76 bool vline_empty(SDL_Surface* surface, int x, int start_y, int end_y, Uint8 threshold)
77 {
78   Uint8* pixels = (Uint8*)surface->pixels;
79
80   for(int y = start_y; y < end_y; ++y)
81     {
82       const Uint8& p = pixels[surface->pitch*y + x*surface->format->BytesPerPixel + 3];
83       if (p > threshold)
84         {
85           return false;
86         }
87     }
88   return true;
89 }
90 } // namespace
91
92 Font::Font(GlyphWidth glyph_width_, 
93            const std::string& file, const std::string& shadowfile,
94            int char_width, int char_height_, int shadowsize)
95   : glyph_width(glyph_width_),
96     glyph_surface(0), shadow_chars(0),
97     char_height(char_height_), 
98     shadowsize(shadowsize)
99 {
100   glyph_surface = new Surface(file);
101   shadow_chars  = new Surface(shadowfile);
102
103   first_char = 32;
104   char_count = ((int) glyph_surface->get_height() / char_height) * 16;
105
106   for(uint32_t i = 0; i < char_count; ++i)
107     {
108       float x = (i % 16) * char_width;
109       float y = (i / 16) * char_height;
110       glyphs.push_back(Rect(x, y,
111                             x + char_width, y + char_height));
112     }
113 }
114
115 Font::Font(GlyphWidth glyph_width_, const std::string& filename, int char_width, int char_height_)
116   : glyph_width(glyph_width_),
117     glyph_surface(0), shadow_chars(0), 
118     char_height(char_height_), 
119     shadowsize(0)
120 {
121   glyph_surface = new Surface(filename);
122
123   first_char = 32;
124   char_count = ((int) glyph_surface->get_height() / char_height) * 16;
125
126   // Load the surface into RAM and scan the pixel data for characters
127   SDL_Surface* surface = IMG_Load_RW(get_physfs_SDLRWops(filename), 1);
128   if(surface == NULL) {
129     std::ostringstream msg;
130     msg << "Couldn't load image '" << filename << "' :" << SDL_GetError();
131     throw std::runtime_error(msg.str());
132   }
133
134   SDL_LockSurface(surface);
135
136   for(uint32_t i = 0; i < char_count; ++i)
137     {
138       int x = (i % 16) * char_width;
139       int y = (i / 16) * char_height;
140
141       int left = x;
142       while (left < x + char_width &&
143              vline_empty(surface, left, y, y + char_height, 0))
144         left += 1;
145
146       int right = x + char_width - 1;
147       while (right > left && 
148              vline_empty(surface, right, y, y + char_height, 0))
149         right -= 1;
150
151       if (left <= right)
152         glyphs.push_back(Rect(left,  y,
153                               right+1, y + char_height));
154       else // glyph is completly transparent
155         glyphs.push_back(Rect(x,  y,
156                               x + char_width, y + char_height));
157
158     }
159   
160   SDL_UnlockSurface(surface);
161
162   SDL_FreeSurface(surface);
163 }
164
165 Font::~Font()
166 {
167   delete glyph_surface;
168   delete shadow_chars;
169 }
170
171 float
172 Font::get_text_width(const std::string& text) const
173 {
174   float curr_width = 0;
175   float last_width = 0;
176
177   for(UTF8Iterator it(text); !it.done(); ++it)
178     {
179       if (*it == '\n')
180         {
181           last_width = std::max(last_width, curr_width);
182           curr_width = 0;
183         }
184       else
185         {
186           int idx = chr2glyph(*it);
187           curr_width += glyphs[idx].get_width();
188         }
189     }
190
191   return std::max(curr_width, last_width);
192 }
193
194 float
195 Font::get_text_height(const std::string& text) const
196 {
197   std::string::size_type text_height = char_height;
198   
199   for(std::string::const_iterator it = text.begin(); it != text.end(); ++it)
200     { // since UTF8 multibyte characters are decoded with values
201       // outside the ASCII range there is no risk of overlapping and
202       // thus we don't need to decode the utf-8 string
203       if (*it == '\n')
204         text_height += char_height + 2;
205     }
206
207   return text_height;
208 }
209
210 float
211 Font::get_height() const
212 {
213   return char_height; 
214 }
215
216 std::string
217 Font::wrap_to_chars(const std::string& s, int line_length, std::string* overflow)
218 {
219   // if text is already smaller, return full text
220   if ((int)s.length() <= line_length) {
221     if (overflow) *overflow = "";
222     return s;
223   }
224
225   // if we can find a whitespace character to break at, return text up to this character
226   int i = line_length;
227   while ((i > 0) && (s[i] != ' ')) i--;
228   if (i > 0) {
229     if (overflow) *overflow = s.substr(i+1);
230     return s.substr(0, i);
231   }
232
233   // FIXME: wrap at line_length, taking care of multibyte characters
234   if (overflow) *overflow = "";
235   return s;
236 }
237
238 void
239 Font::draw(const std::string& text, const Vector& pos_, FontAlignment alignment,
240            DrawingEffect drawing_effect, float alpha) const
241 {
242   float x = pos_.x;
243   float y = pos_.y;
244
245   std::string::size_type last = 0;
246   for(std::string::size_type i = 0;; ++i)
247     {
248       if (text[i] == '\n' || i == text.size())
249         {
250           std::string temp = text.substr(last, i - last);
251
252           // calculate X positions based on the alignment type
253           Vector pos = Vector(x, y);
254           
255           if(alignment == ALIGN_CENTER)
256             pos.x -= get_text_width(temp) / 2;
257           else if(alignment == ALIGN_RIGHT)
258             pos.x -= get_text_width(temp);
259           
260           draw_text(temp, pos, drawing_effect, alpha);
261
262           if (i == text.size())
263             break;
264
265           y += char_height + 2;      
266           last = i + 1;
267         }
268     }
269 }
270
271 void
272 Font::draw_text(const std::string& text, const Vector& pos,
273                 DrawingEffect drawing_effect, float alpha) const
274 {
275   if(shadowsize > 0)
276     draw_chars(shadow_chars, text, pos + Vector(shadowsize, shadowsize),
277                drawing_effect, alpha);
278
279   draw_chars(glyph_surface, text, pos, drawing_effect, alpha);
280 }
281
282 int
283 Font::chr2glyph(uint32_t chr) const
284 {
285   int glyph_index = chr - first_char;
286   
287   // we don't have the control chars 0x80-0xa0 in the font
288   if (chr >= 0x80) { // non-ascii character
289     glyph_index -= 32;
290     if(chr <= 0xa0) {
291       log_debug << "Unsupported utf-8 character '" << chr << "' found" << std::endl;
292       glyph_index = 0;
293     }
294   }
295
296   if(glyph_index < 0 || glyph_index >= (int) char_count) {
297     log_debug << "Unsupported utf-8 character found" << std::endl;
298     glyph_index = 0;
299   }
300   
301   return glyph_index;
302 }
303
304 void
305 Font::draw_chars(Surface* pchars, const std::string& text, const Vector& pos,
306                  DrawingEffect drawing_effect, float alpha) const
307 {
308   Vector p = pos;
309   for(UTF8Iterator it(text); !it.done(); ++it)
310     {
311       int font_index = chr2glyph(*it);
312
313       if(*it == '\n') 
314         { 
315           p.x = pos.x;
316           p.y += char_height + 2;
317         }
318       else if(*it == ' ') 
319         {
320           p.x += glyphs[font_index].get_width();
321         } 
322       else 
323         {
324           const Rect& glyph = glyphs[font_index];
325           pchars->draw_part(glyph.get_left(), glyph.get_top(),
326                             p.x, p.y,
327                             glyph.get_width(), glyph.get_height(),
328                             alpha, drawing_effect);
329           p.x += glyphs[font_index].get_width();
330         }
331     }
332 }
333
334
335 namespace {
336
337 /**
338  * 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
339  */
340 bool has_multibyte_mark(unsigned char c) {
341   return ((c & 0300) == 0200);
342 }
343
344 /**
345  * gets unicode character at byte position @a p of UTF-8 encoded @a
346  * text, then advances @a p to the next character.
347  *
348  * @throws std::runtime_error if decoding fails.
349  * See unicode standard section 3.10 table 3-5 and 3-6 for details.
350  */
351 uint32_t decode_utf8(const std::string& text, size_t& p)
352 {
353   uint32_t c1 = (unsigned char) text[p+0];
354
355   if (has_multibyte_mark(c1)) std::runtime_error("Malformed utf-8 sequence");
356
357   if ((c1 & 0200) == 0000) {
358     // 0xxx.xxxx: 1 byte sequence
359     p+=1;
360     return c1;
361   }
362   else if ((c1 & 0340) == 0300) {
363     // 110x.xxxx: 2 byte sequence
364     if(p+1 >= text.size()) throw std::range_error("Malformed utf-8 sequence");
365     uint32_t c2 = (unsigned char) text[p+1];
366     if (!has_multibyte_mark(c2)) throw std::runtime_error("Malformed utf-8 sequence");
367     p+=2;
368     return (c1 & 0037) << 6 | (c2 & 0077);
369   }
370   else if ((c1 & 0360) == 0340) {
371     // 1110.xxxx: 3 byte sequence
372     if(p+2 >= text.size()) throw std::range_error("Malformed utf-8 sequence");
373     uint32_t c2 = (unsigned char) text[p+1];
374     uint32_t c3 = (unsigned char) text[p+2];
375     if (!has_multibyte_mark(c2)) throw std::runtime_error("Malformed utf-8 sequence");
376     if (!has_multibyte_mark(c3)) throw std::runtime_error("Malformed utf-8 sequence");
377     p+=3;
378     return (c1 & 0017) << 12 | (c2 & 0077) << 6 | (c3 & 0077);
379   }
380   else if ((c1 & 0370) == 0360) {
381     // 1111.0xxx: 4 byte sequence
382     if(p+3 >= text.size()) throw std::range_error("Malformed utf-8 sequence");
383     uint32_t c2 = (unsigned char) text[p+1];
384     uint32_t c3 = (unsigned char) text[p+2];
385     uint32_t c4 = (unsigned char) text[p+4];
386     if (!has_multibyte_mark(c2)) throw std::runtime_error("Malformed utf-8 sequence");
387     if (!has_multibyte_mark(c3)) throw std::runtime_error("Malformed utf-8 sequence");
388     if (!has_multibyte_mark(c4)) throw std::runtime_error("Malformed utf-8 sequence");
389     p+=4;
390     return (c1 & 0007) << 18 | (c2 & 0077) << 12 | (c3 & 0077) << 6 | (c4 & 0077);
391   }
392   throw std::runtime_error("Malformed utf-8 sequence");
393 }
394
395 } // namespace