aeb2e201197e4485ade6d5c383080069f7d1c3b1
[supertux.git] / src / video / font.cpp
1 //  SuperTux
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 //                     Ingo Ruhnke <grumbel@gmail.com>
4 //
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.
9 //
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.
14 //
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/>.
17
18 #include <config.h>
19
20 #include <sstream>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <stdexcept>
24 #include <SDL_image.h>
25 #include <physfs.h>
26
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"
38
39 namespace {
40
41 bool vline_empty(SDL_Surface* surface, int x, int start_y, int end_y, Uint8 threshold)
42 {
43   Uint8* pixels = (Uint8*)surface->pixels;
44
45   for(int y = start_y; y < end_y; ++y)
46   {
47     const Uint8& p = pixels[surface->pitch*y + x*surface->format->BytesPerPixel + 3];
48     if (p > threshold)
49     {
50       return false;
51     }
52   }
53   return true;
54 }
55
56 } // namespace
57
58 Font::Font(GlyphWidth glyph_width_,
59            const std::string& filename,
60            int shadowsize_) :
61   glyph_width(glyph_width_),
62   glyph_surfaces(),
63   shadow_surfaces(),
64   char_height(),
65   shadowsize(shadowsize_),
66   border(0),
67   glyphs(65536)
68 {
69   for(unsigned int i=0; i<65536;i++) glyphs[i].surface_idx = -1;
70
71   const std::string fontdir = FileSystem::dirname(filename);
72   const std::string fontname = FileSystem::basename(filename);
73
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_);
80     }
81   }
82   PHYSFS_freeList(rc);
83 }
84
85 void
86 Font::loadFontFile(const std::string &filename)
87 {
88   lisp::Parser parser;
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");
92
93   if(!config_l) {
94     std::ostringstream msg;
95     msg << "Font file:" << filename << ": is not a supertux-font file";
96     throw std::runtime_error(msg.str());
97   }
98
99   int def_char_width=0;
100
101   if( !config_l->get("glyph-width",def_char_width) ) {
102     log_warning << "Font:"<< filename << ": misses default glyph-width" << std::endl;
103   }
104
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());
109   }
110
111   config_l->get("glyph-border", border);
112
113   lisp::ListIterator iter(config_l);
114   while(iter.next()) {
115     const std::string& token = iter.item();
116     if( token == "surface" ) {
117       const lisp::Lisp * glyphs_val = iter.lisp();
118       int local_char_width;
119       bool monospaced;
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;
126       }
127       if( ! glyphs_val->get("monospace", monospaced ) ) {
128         local_glyph_width = glyph_width;
129       }
130       else {
131         if( monospaced ) local_glyph_width = FIXED;
132         else local_glyph_width = VARIABLE;
133       }
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());
138       }
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());
143       }
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());
148       }
149
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());
154       }
155
156       loadFontSurface(glyph_image, shadow_image, chars,
157                       local_glyph_width, local_char_width);
158     }
159   }
160 }
161
162 void
163 Font::loadFontSurface(
164   const std::string &glyphimage,
165   const std::string &shadowimage,
166   const std::vector<std::string> &chars,
167   GlyphWidth glyph_width_,
168   int char_width
169   )
170 {
171   SurfacePtr glyph_surface  = Surface::create("images/engine/fonts/" + glyphimage);
172   SurfacePtr shadow_surface = Surface::create("images/engine/fonts/" + shadowimage);
173
174   int surface_idx = glyph_surfaces.size();
175   glyph_surfaces.push_back(glyph_surface);
176   shadow_surfaces.push_back(shadow_surface);
177
178   int row=0, col=0;
179   int wrap = glyph_surface->get_width() / char_width;
180
181   SDL_Surface *surface = NULL;
182
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());
191     }
192     SDL_LockSurface(surface);
193   }
194
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;
201
202       Glyph glyph;
203       glyph.surface_idx   = surface_idx;
204
205       if( glyph_width_ == FIXED || isdigit(*chr) )
206       {
207         glyph.rect    = Rectf(x, y, x + char_width, y + char_height);
208         glyph.offset  = Vector(0, 0);
209         glyph.advance = char_width;
210       }
211       else
212       {
213         if (y + char_height > surface->h)
214         {
215           log_warning << "error: font definition contains more letter then the images: " << glyphimage << std::endl;
216           goto abort;
217         }
218
219         int left = x;
220         while (left < x + char_width && vline_empty(surface, left, y, y + char_height, 64))
221           left += 1;
222         int right = x + char_width - 1;
223         while (right > left && vline_empty(surface, right, y, y + char_height, 64))
224           right -= 1;
225
226         if (left <= right)
227         {
228           glyph.offset  = Vector(x-left, 0);
229           glyph.advance = right - left + 1 + 1; // FIXME: might be useful to make spacing configurable
230         }
231         else
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
235         }
236
237         glyph.rect = Rectf(x,  y, x + char_width, y + char_height);
238       }
239
240       glyphs[*chr] = glyph;
241     }
242     if( col>0 && col <= wrap ) {
243       col = 0;
244       row++;
245     }
246   }
247 abort:
248
249   if( surface != NULL ) {
250     SDL_UnlockSurface(surface);
251     SDL_FreeSurface(surface);
252   }
253 }
254
255 Font::~Font()
256 {
257 }
258
259 float
260 Font::get_text_width(const std::string& text) const
261 {
262   float curr_width = 0;
263   float last_width = 0;
264
265   for(UTF8Iterator it(text); !it.done(); ++it)
266   {
267     if (*it == '\n')
268     {
269       last_width = std::max(last_width, curr_width);
270       curr_width = 0;
271     }
272     else
273     {
274       if( glyphs.at(*it).surface_idx != -1 )
275         curr_width += glyphs[*it].advance;
276       else
277         curr_width += glyphs[0x20].advance;
278     }
279   }
280
281   return std::max(curr_width, last_width);
282 }
283
284 float
285 Font::get_text_height(const std::string& text) const
286 {
287   std::string::size_type text_height = char_height;
288
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
293     if (*it == '\n')
294       text_height += char_height + 2;
295   }
296
297   return text_height;
298 }
299
300 float
301 Font::get_height() const
302 {
303   return char_height;
304 }
305
306 std::string
307 Font::wrap_to_chars(const std::string& s, int line_length, std::string* overflow)
308 {
309   // if text is already smaller, return full text
310   if ((int)s.length() <= line_length) {
311     if (overflow) *overflow = "";
312     return s;
313   }
314
315   // if we can find a whitespace character to break at, return text up to this character
316   int i = line_length;
317   while ((i > 0) && (s[i] != ' ')) i--;
318   if (i > 0) {
319     if (overflow) *overflow = s.substr(i+1);
320     return s.substr(0, i);
321   }
322
323   // FIXME: wrap at line_length, taking care of multibyte characters
324   if (overflow) *overflow = "";
325   return s;
326 }
327
328 std::string
329 Font::wrap_to_width(const std::string& s_, float width, std::string* overflow)
330 {
331   std::string s = s_;
332
333   // if text is already smaller, return full text
334   if (get_text_width(s) <= width) {
335     if (overflow) *overflow = "";
336     return s;
337   }
338
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);
346     }
347   }
348
349   // FIXME: hard-wrap at width, taking care of multibyte characters
350   if (overflow) *overflow = "";
351   return s;
352 }
353
354 void
355 Font::draw(Renderer *renderer, const std::string& text, const Vector& pos_,
356            FontAlignment alignment, DrawingEffect drawing_effect, Color color,
357            float alpha) const
358 {
359   float x = pos_.x;
360   float y = pos_.y;
361
362   std::string::size_type last = 0;
363   for(std::string::size_type i = 0;; ++i)
364   {
365     if (text[i] == '\n' || i == text.size())
366     {
367       std::string temp = text.substr(last, i - last);
368
369       // calculate X positions based on the alignment type
370       Vector pos = Vector(x, y);
371
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);
376
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);
380
381       draw_text(renderer, temp, pos, drawing_effect, color, alpha);
382
383       if (i == text.size())
384         break;
385
386       y += char_height + 2;
387       last = i + 1;
388     }
389   }
390 }
391
392 void
393 Font::draw_text(Renderer *renderer, const std::string& text, const Vector& pos,
394                 DrawingEffect drawing_effect, Color color, float alpha) const
395 {
396   if(shadowsize > 0)
397     draw_chars(renderer, false, text,
398                pos + Vector(shadowsize, shadowsize), drawing_effect, Color(1,1,1), alpha);
399
400   draw_chars(renderer, true, text, pos, drawing_effect, color, alpha);
401 }
402
403 void
404 Font::draw_chars(Renderer *renderer, bool notshadow, const std::string& text,
405                  const Vector& pos, DrawingEffect drawing_effect, Color color,
406                  float alpha) const
407 {
408   Vector p = pos;
409
410   for(UTF8Iterator it(text); !it.done(); ++it)
411   {
412     if(*it == '\n')
413     {
414       p.x = pos.x;
415       p.y += char_height + 2;
416     }
417     else if(*it == ' ')
418     {
419       p.x += glyphs[0x20].advance;
420     }
421     else
422     {
423       Glyph glyph;
424       if( glyphs.at(*it).surface_idx != -1 )
425         glyph = glyphs[*it];
426       else
427         glyph = glyphs[0x20];
428
429       DrawingRequest request;
430
431       request.pos = p + glyph.offset;
432       request.drawing_effect = drawing_effect;
433       request.color = color;
434       request.alpha = alpha;
435
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();
440
441       request.request_data = &surfacepartrequest;
442       renderer->draw_surface_part(request);
443
444       p.x += glyph.advance;
445     }
446   }
447 }
448
449 /* EOF */