support for centered text in scripts
[supertux.git] / src / object / text_object.cpp
1 #include <config.h>
2
3 #include "text_object.hpp"
4 #include "resources.hpp"
5 #include "video/drawing_context.hpp"
6
7 TextObject::TextObject()
8   : fading(0), fadetime(0), visible(false)
9 {
10   font = blue_text;
11   centered = false;
12 }
13
14 TextObject::~TextObject()
15 {
16 }
17
18 void
19 TextObject::set_font(const std::string& name)
20 {
21   if(name == "gold") {
22     font = gold_text;
23   } else if(name == "white") {
24     font = white_text;
25   } else if(name == "blue") {
26     font = blue_text;
27   } else if(name == "gray") {
28     font = gray_text;
29   } else if(name == "big") {
30     font = white_big_text;
31   } else if(name == "small") {
32     font = white_small_text;
33   } else {
34     std::cerr << "Unknown font '" << name << "'.\n";
35   }
36 }
37
38 void
39 TextObject::set_text(const std::string& text)
40 {
41   this->text = text;
42 }
43
44 void
45 TextObject::fade_in(float fadetime)
46 {
47   this->fadetime = fadetime;
48   fading = fadetime;
49 }
50
51 void
52 TextObject::fade_out(float fadetime)
53 {
54   this->fadetime = fadetime;
55   fading = -fadetime;
56 }
57
58 void
59 TextObject::set_visible(bool visible)
60 {
61   this->visible = visible;
62   fading = 0;
63 }
64
65 void
66 TextObject::set_centered(bool centered)
67 {
68   this->centered = centered;
69 }
70
71 void
72 TextObject::draw(DrawingContext& context)
73 {
74   context.push_transform();
75   context.set_translation(Vector(0, 0));
76   if(fading > 0) {
77     context.set_alpha(static_cast<uint8_t> 
78         ((fadetime-fading) * 255.0 / fadetime));
79   } else if(fading < 0) {
80     context.set_alpha(static_cast<uint8_t> (-fading * 255.0 / fadetime));
81   } else if(!visible) {
82     context.pop_transform();
83     return;
84   }
85
86   context.draw_filled_rect(Vector(125, 50), Vector(550, 120),
87       Color(150, 180, 200, 125), LAYER_GUI-50);
88   if (centered) {
89     context.draw_center_text(font, text, Vector(0, 50+35), LAYER_GUI-40);
90   }
91   else context.draw_text(font, text, Vector(125+35, 50+35), LEFT_ALLIGN, LAYER_GUI-40);
92
93   context.pop_transform();
94 }
95
96 void
97 TextObject::update(float elapsed_time)
98 {
99   if(fading > 0) {
100     fading -= elapsed_time;
101     if(fading <= 0) {
102       fading = 0;
103       visible = true;
104     }
105   } else if(fading < 0) {
106     fading += elapsed_time;
107     if(fading >= 0) {
108       fading = 0;
109       visible = false;
110     }
111   }
112 }
113