More use of SurfacePtr
[supertux.git] / src / video / font.cpp
1 //  SuperTux
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 //                     Ingo Ruhnke <grumbel@gmx.de>
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 <stdlib.h>
21 #include <string.h>
22 #include <stdexcept>
23 #include <SDL_image.h>
24 #include <physfs.h>
25
26 #include "lisp/list_iterator.hpp"
27 #include "lisp/parser.hpp"
28 #include "physfs/physfs_sdl.hpp"
29 #include "supertux/screen.hpp"
30 #include "util/file_system.hpp"
31 #include "util/log.hpp"
32 #include "util/utf8_iterator.hpp"
33 #include "video/drawing_context.hpp"
34 #include "video/font.hpp"
35 #include "video/renderer.hpp"
36
37 namespace {
38
39 bool vline_empty(SDL_Surface* surface, int x, int start_y, int end_y, Uint8 threshold)
40 {
41   Uint8* pixels = (Uint8*)surface->pixels;
42
43   for(int y = start_y; y < end_y; ++y)
44   {
45     const Uint8& p = pixels[surface->pitch*y + x*surface->format->BytesPerPixel + 3];
46     if (p > threshold)
47     {
48       return false;
49     }
50   }
51   return true;
52 }
53
54 } // namespace
55
56 Font::Font(GlyphWidth glyph_width_,
57            const std::string& filename,
58            int shadowsize_) :
59   glyph_width(glyph_width_),
60   glyph_surfaces(),
61   shadow_surfaces(),
62   char_height(),
63   shadowsize(shadowsize_),
64   glyphs(65536)
65 {
66   for(unsigned int i=0; i<65536;i++) glyphs[i].surface_idx = -1;
67
68   const std::string fontdir = FileSystem::dirname(filename);
69   const std::string fontname = FileSystem::basename(filename);
70
71   // scan for prefix-filename in addons search path
72   char **rc = PHYSFS_enumerateFiles(fontdir.c_str());
73   for (char **i = rc; *i != NULL; i++) {
74     std::string filename(*i);
75     if( filename.rfind(fontname) != std::string::npos ) {
76       loadFontFile(fontdir + filename);
77     }
78   }
79   PHYSFS_freeList(rc);
80 }
81
82 void 
83 Font::loadFontFile(const std::string &filename)
84 {
85   lisp::Parser parser;
86   log_debug << "Loading font: " << filename << std::endl;
87   const lisp::Lisp* root = parser.parse(filename);
88   const lisp::Lisp* config_l = root->get_lisp("supertux-font");
89
90   if(!config_l) {
91     std::ostringstream msg;
92     msg << "Font file:" << filename << ": is not a supertux-font file";
93     throw std::runtime_error(msg.str());
94   }
95
96   int def_char_width=0;
97
98   if( !config_l->get("glyph-width",def_char_width) ) {
99     log_warning << "Font:"<< filename << ": misses default glyph-width" << std::endl;
100   }
101   
102   if( !config_l->get("glyph-height",char_height) ) {
103     std::ostringstream msg;
104     msg << "Font:" << filename << ": misses glyph-height";
105     throw std::runtime_error(msg.str());
106   }
107
108   lisp::ListIterator iter(config_l);
109   while(iter.next()) {
110     const std::string& token = iter.item();
111     if( token == "surface" ) {
112       const lisp::Lisp * glyphs_val = iter.lisp();
113       int local_char_width;
114       bool monospaced;
115       GlyphWidth local_glyph_width;
116       std::string glyph_image;
117       std::string shadow_image;
118       std::vector<std::string> chars;
119       if( ! glyphs_val->get("glyph-width", local_char_width) ) {
120         local_char_width = def_char_width;
121       }
122       if( ! glyphs_val->get("monospace", monospaced ) ) {
123         local_glyph_width = glyph_width;
124       }
125       else {
126         if( monospaced ) local_glyph_width = FIXED;
127         else local_glyph_width = VARIABLE;
128       }
129       if( ! glyphs_val->get("glyphs", glyph_image) ) {
130         std::ostringstream msg;
131         msg << "Font:" << filename << ": missing glyphs image";
132         throw std::runtime_error(msg.str());
133       }
134       if( ! glyphs_val->get("shadows", shadow_image) ) {
135         std::ostringstream msg;
136         msg << "Font:" << filename << ": missing shadows image";
137         throw std::runtime_error(msg.str());
138       }
139       if( ! glyphs_val->get("chars", chars) || chars.size() == 0) {
140         std::ostringstream msg;
141         msg << "Font:" << filename << ": missing chars definition";
142         throw std::runtime_error(msg.str());
143       }
144
145       if( local_char_width==0 ) {
146         std::ostringstream msg;
147         msg << "Font:" << filename << ": misses glyph-width for some surface";
148         throw std::runtime_error(msg.str());
149       }
150
151       loadFontSurface(glyph_image, shadow_image, chars,
152                       local_glyph_width, local_char_width);
153     }
154   }
155 }
156
157 void 
158 Font::loadFontSurface(
159   const std::string &glyphimage,
160   const std::string &shadowimage,
161   const std::vector<std::string> &chars,
162   GlyphWidth glyph_width,
163   int char_width
164   )
165 {
166   SurfacePtr glyph_surface  = Surface::create("images/engine/fonts/" + glyphimage);
167   SurfacePtr shadow_surface = Surface::create("images/engine/fonts/" + shadowimage);
168
169   int surface_idx = glyph_surfaces.size();
170   glyph_surfaces.push_back(glyph_surface);
171   shadow_surfaces.push_back(shadow_surface);
172
173   int row=0, col=0;
174   int wrap = glyph_surface->get_width() / char_width;
175  
176   SDL_Surface *surface = NULL;
177   
178   if( glyph_width == VARIABLE ) {
179     //this does not work:
180     // surface = ((SDL::Texture *)glyph_surface.get_texture())->get_texture();
181     surface = IMG_Load_RW(get_physfs_SDLRWops("images/engine/fonts/"+glyphimage), 1);
182     if(surface == NULL) {
183       std::ostringstream msg;
184       msg << "Couldn't load image '" << glyphimage << "' :" << SDL_GetError();
185       throw std::runtime_error(msg.str());
186     }
187     SDL_LockSurface(surface);
188   }
189
190   for( unsigned int i = 0; i < chars.size(); i++) {
191     for(UTF8Iterator chr(chars[i]); !chr.done(); ++chr) {
192       int y = row * char_height;
193       int x = col * char_width;
194       if( ++col == wrap ) { col=0; row++; }
195       if( *chr == 0x0020 && glyphs[0x20].surface_idx != -1) continue;
196         
197       Glyph glyph;
198       glyph.surface_idx   = surface_idx;
199       
200       if( glyph_width == FIXED ) 
201       {
202         glyph.rect    = Rectf(x, y, x + char_width, y + char_height);
203         glyph.offset  = Vector(0, 0);
204         glyph.advance = char_width;
205       }
206       else 
207       {
208         int left = x;
209         while (left < x + char_width && vline_empty(surface, left, y, y + char_height, 64))
210           left += 1;
211         int right = x + char_width - 1;
212         while (right > left && vline_empty(surface, right, y, y + char_height, 64))
213           right -= 1;
214           
215         if (left <= right) 
216         {
217           glyph.offset  = Vector(x-left, 0);
218           glyph.advance = right - left + 1 + 1; // FIXME: might be useful to make spacing configurable
219         } 
220         else 
221         { // glyph is completly transparent
222           glyph.offset  = Vector(0, 0);
223           glyph.advance = char_width + 1; // FIXME: might be useful to make spacing configurable
224         }
225
226         glyph.rect = Rectf(x,  y, x + char_width, y + char_height);
227       }
228
229       glyphs[*chr] = glyph;
230     }
231     if( col>0 && col <= wrap ) { 
232       col = 0;
233       row++;
234     }
235   }
236   
237   if( surface != NULL ) {
238     SDL_UnlockSurface(surface);
239     SDL_FreeSurface(surface);
240   }
241 }
242
243 Font::~Font()
244 {
245 }
246
247 float
248 Font::get_text_width(const std::string& text) const
249 {
250   float curr_width = 0;
251   float last_width = 0;
252
253   for(UTF8Iterator it(text); !it.done(); ++it)
254   {
255     if (*it == '\n')
256     {
257       last_width = std::max(last_width, curr_width);
258       curr_width = 0;
259     }
260     else
261     {
262       if( glyphs.at(*it).surface_idx != -1 )
263         curr_width += glyphs[*it].advance;
264       else 
265         curr_width += glyphs[0x20].advance;
266     }
267   }
268
269   return std::max(curr_width, last_width);
270 }
271
272 float
273 Font::get_text_height(const std::string& text) const
274 {
275   std::string::size_type text_height = char_height;
276
277   for(std::string::const_iterator it = text.begin(); it != text.end(); ++it)
278   { // since UTF8 multibyte characters are decoded with values
279     // outside the ASCII range there is no risk of overlapping and
280     // thus we don't need to decode the utf-8 string
281     if (*it == '\n')
282       text_height += char_height + 2;
283   }
284
285   return text_height;
286 }
287
288 float
289 Font::get_height() const
290 {
291   return char_height;
292 }
293
294 std::string
295 Font::wrap_to_chars(const std::string& s, int line_length, std::string* overflow)
296 {
297   // if text is already smaller, return full text
298   if ((int)s.length() <= line_length) {
299     if (overflow) *overflow = "";
300     return s;
301   }
302
303   // if we can find a whitespace character to break at, return text up to this character
304   int i = line_length;
305   while ((i > 0) && (s[i] != ' ')) i--;
306   if (i > 0) {
307     if (overflow) *overflow = s.substr(i+1);
308     return s.substr(0, i);
309   }
310
311   // FIXME: wrap at line_length, taking care of multibyte characters
312   if (overflow) *overflow = "";
313   return s;
314 }
315
316 std::string
317 Font::wrap_to_width(const std::string& s_, float width, std::string* overflow)
318 {
319   std::string s = s_;
320
321   // if text is already smaller, return full text
322   if (get_text_width(s) <= width) {
323     if (overflow) *overflow = "";
324     return s;
325   }
326
327   // if we can find a whitespace character to break at, return text up to this character
328   for (int i = s.length()-1; i >= 0; i--) {
329     std::string s2 = s.substr(0,i);
330     if (s[i] != ' ') continue;
331     if (get_text_width(s2) <= width) {
332       if (overflow) *overflow = s.substr(i+1);
333       return s.substr(0, i);
334     }
335   }
336   
337   // FIXME: hard-wrap at width, taking care of multibyte characters
338   if (overflow) *overflow = "";
339   return s;
340 }
341
342 void
343 Font::draw(Renderer *renderer, const std::string& text, const Vector& pos_,
344            FontAlignment alignment, DrawingEffect drawing_effect, Color color,
345            float alpha) const
346 {
347   float x = pos_.x;
348   float y = pos_.y;
349
350   std::string::size_type last = 0;
351   for(std::string::size_type i = 0;; ++i)
352   {
353     if (text[i] == '\n' || i == text.size())
354     {
355       std::string temp = text.substr(last, i - last);
356
357       // calculate X positions based on the alignment type
358       Vector pos = Vector(x, y);
359
360       if(alignment == ALIGN_CENTER)
361         pos.x -= get_text_width(temp) / 2;
362       else if(alignment == ALIGN_RIGHT)
363         pos.x -= get_text_width(temp);
364
365       // Cast font position to integer to get a clean drawing result and
366       // no blurring as we would get with subpixel positions
367       pos.x = static_cast<int>(pos.x);
368
369       draw_text(renderer, temp, pos, drawing_effect, color, alpha);
370
371       if (i == text.size())
372         break;
373
374       y += char_height + 2;
375       last = i + 1;
376     }
377   }
378 }
379
380 void
381 Font::draw_text(Renderer *renderer, const std::string& text, const Vector& pos,
382                 DrawingEffect drawing_effect, Color color, float alpha) const
383 {
384   if(shadowsize > 0)
385     draw_chars(renderer, false, text, 
386                pos + Vector(shadowsize, shadowsize), drawing_effect, Color(1,1,1), alpha);
387
388   draw_chars(renderer, true, text, pos, drawing_effect, color, alpha);
389 }
390
391 void
392 Font::draw_chars(Renderer *renderer, bool notshadow, const std::string& text,
393                  const Vector& pos, DrawingEffect drawing_effect, Color color,
394                  float alpha) const
395 {
396   Vector p = pos;
397
398   for(UTF8Iterator it(text); !it.done(); ++it)
399   {
400     if(*it == '\n')
401     {
402       p.x = pos.x;
403       p.y += char_height + 2;
404     }
405     else if(*it == ' ')
406     {
407       p.x += glyphs[0x20].advance;
408     }
409     else
410     {
411       Glyph glyph;
412       if( glyphs.at(*it).surface_idx != -1 )
413         glyph = glyphs[*it];
414       else 
415         glyph = glyphs[0x20];
416
417       DrawingRequest request;
418
419       request.pos = p + glyph.offset;
420       request.drawing_effect = drawing_effect;
421       request.color = color;
422       request.alpha = alpha;
423
424       SurfacePartRequest surfacepartrequest;
425       surfacepartrequest.size = glyph.rect.p2 - glyph.rect.p1;
426       surfacepartrequest.source = glyph.rect.p1;
427       surfacepartrequest.surface = notshadow ? glyph_surfaces[glyph.surface_idx].get() : shadow_surfaces[glyph.surface_idx].get();
428
429       request.request_data = &surfacepartrequest;
430       renderer->draw_surface_part(request);
431
432       p.x += glyph.advance;
433     }
434   }
435 }
436
437 /* EOF */