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