Browse Source

Split the text area and fixed the reading of plain texts

- The reading of the markup and the layout of the characters are in their own classes. The two copies of the markup reader are one.
- Broke up the update, the drawing of the characters and the creation of the images.
- Setting a plain text, as the scripts do, only read the first element at each level, so the text after a tag was lost.
- Elements with a missing or invalid attribute and invalid plain texts crashed the game.
- The scroll time had no initial value.
- Added tests for the markup reader and the layout.
Iñigo Valentin 4 days ago
parent
commit
aadb6b71c1

+ 2 - 0
src/engine/ui/CMakeLists.txt

@@ -8,5 +8,7 @@ vgears_sources(
     UiManager.cpp
     UiSprite.cpp
     UiTextArea.cpp
+    UiTextLayout.cpp
+    UiTextParser.cpp
     UiWidget.cpp
 )

+ 209 - 617
src/engine/ui/UiTextArea.cpp

@@ -26,6 +26,7 @@
 #include "common/Logger.h"
 #include "engine/ui/UiManager.h"
 #include "engine/ui/UiTextArea.h"
+#include "engine/ui/UiTextParser.h"
 #include "engine/Timer.h"
 #include "engine/ui/UiSprite.h"
 #include "common/Utilities.h"
@@ -49,6 +50,7 @@ void UiTextArea::Initialise(){
     text_print_speed_ = -1; // -1 instant
     text_print_speed_mod_ = 1;
     text_state_ = TS_DONE;
+    text_scroll_time_ = 0;
     text_y_offset_ = 0;
     text_y_offset_target_ = 0;
     pause_time_ = 0;
@@ -62,7 +64,7 @@ void UiTextArea::Initialise(){
     timer_ = false;
     timer_time_ = 0;
     TextVariable var;
-    var.name = "UITextAreaTimer";
+    var.name = UiTextParser::TIMER_VARIABLE;
     var.value = "00:00";
     text_variable_.push_back(var);
     scene_manager_ = Ogre::Root::getSingleton().getSceneManager("Scene");
@@ -72,84 +74,15 @@ void UiTextArea::Initialise(){
 
 void UiTextArea::Update(){
     if (visible_ == true){
-        if (timer_ == true){
-            int time = Timer::getSingleton().GetGameTimer();
-            if (time > 5999) time = 5999; // 99:59
-
-            if (time != timer_time_){
-                timer_time_ = time;
-                Ogre::String time_string = "";
-                time_string += Ogre::StringUtil::format("%2d", timer_time_ / 60);
-                time_string += (timer_time_ & 1) ? ":" : ";";
-                time_string += Ogre::StringUtil::format("%2d", timer_time_ % 60);
-                SetVariable("UITextAreaTimer", time_string);
-            }
-        }
+        if (timer_ == true) UpdateTimer();
         switch(text_state_){
-            case TS_SHOW_TEXT:
-                if (text_print_speed_ == -1) text_limit_ = max_letters_;
-                else{
-                    float time = Timer::getSingleton().GetGameTimeDelta() * 30;
-                    float addition;
-                    float limit;
-                    if (next_pressed_ == true || next_repeated_ == true)
-                        text_print_speed_mod_ += (text_print_speed_mod_ >= 128) ? 0 : 1.0f * time;
-                    else text_print_speed_mod_ -= (text_print_speed_mod_ <= 1) ? 0 : 1.0f * time;
-                    if (text_print_speed_ < 128){
-                        addition = ((128 - text_print_speed_) / 32) + 2;
-                        limit = 1;
-                    }
-                    else{
-                        addition = 2;
-                        limit = ((text_print_speed_ - 128) / 32) + 1;
-                    }
-                    float char_to_add = (limit * text_print_speed_mod_ / 16 + addition) / limit;
-                    text_limit_ += time * char_to_add;
-                }
-                update_transformation_ = true;
-                break;
-            case TS_SCROLL_TEXT:
-                text_y_offset_
-                  -= font_->GetHeight()
-                  * Timer::getSingleton().GetGameTimeDelta()
-                  / text_scroll_time_;
-                if (text_y_offset_ <= text_y_offset_target_){
-                    text_y_offset_ = text_y_offset_target_;
-                    text_print_speed_mod_ = 1;
-                    text_state_ = TS_SHOW_TEXT;
-                }
-                update_transformation_ = true;
-                break;
-            case TS_PAUSE_OK:
-                if (next_pressed_ == true){
-                    text_print_speed_mod_ = 1;
-                    text_state_ = TS_SHOW_TEXT;
-                }
-                break;
-            case TS_PAUSE_TIME:
-                pause_time_ -= Timer::getSingleton().GetGameTimeDelta();
-                if (pause_time_ <= 0){
-                    text_print_speed_mod_ = 1;
-                    text_state_ = TS_SHOW_TEXT;
-                }
-                break;
-            case TS_OVERFLOW:
-                if (next_pressed_ == true){
-                    text_y_offset_target_ = text_y_offset_ - font_->GetHeight();
-                    text_state_ = TS_SCROLL_TEXT;
-                }
-                break;
-            case TS_NEXT_PAGE:
-                if (next_pressed_ == true){
-                    RemoveSpritesFromText(next_page_start_);
-                    text_.erase(text_.begin(), text_.begin() + next_page_start_);
-                    text_limit_ = 0;
-                    text_print_speed_mod_ = 1;
-                    text_y_offset_ = 0;
-                    text_y_offset_target_ = 0;
-                    text_state_ = TS_SHOW_TEXT;
-                }
-                break;
+            case TS_SHOW_TEXT: UpdateShowText(); break;
+            case TS_SCROLL_TEXT: UpdateScrollText(); break;
+            case TS_PAUSE_OK: if (next_pressed_) ContinueText(); break;
+            case TS_PAUSE_TIME: UpdatePauseTime(); break;
+            case TS_OVERFLOW: if (next_pressed_) ScrollOneLine(); break;
+            case TS_NEXT_PAGE: if (next_pressed_) ShowNextPage(); break;
+            case TS_DONE: break;
         }
     }
     next_pressed_ = false;
@@ -157,6 +90,75 @@ void UiTextArea::Update(){
     UiWidget::Update();
 }
 
+void UiTextArea::UpdateTimer(){
+    int time = Timer::getSingleton().GetGameTimer();
+    if (time > 5999) time = 5999; // 99:59
+    if (time == timer_time_) return;
+    timer_time_ = time;
+    Ogre::String time_string = Ogre::StringUtil::format("%2d", timer_time_ / 60);
+    time_string += (timer_time_ & 1) ? ":" : ";";
+    time_string += Ogre::StringUtil::format("%2d", timer_time_ % 60);
+    SetVariable(UiTextParser::TIMER_VARIABLE, time_string);
+}
+
+void UiTextArea::UpdateShowText(){
+    if (text_print_speed_ == -1) text_limit_ = max_letters_;
+    else{
+        // Holding the button makes the text print faster.
+        const float time = Timer::getSingleton().GetGameTimeDelta() * 30;
+        if (next_pressed_ == true || next_repeated_ == true)
+            text_print_speed_mod_ += (text_print_speed_mod_ >= 128) ? 0 : 1.0f * time;
+        else text_print_speed_mod_ -= (text_print_speed_mod_ <= 1) ? 0 : 1.0f * time;
+        float addition;
+        float limit;
+        if (text_print_speed_ < 128){
+            addition = ((128 - text_print_speed_) / 32) + 2;
+            limit = 1;
+        }
+        else{
+            addition = 2;
+            limit = ((text_print_speed_ - 128) / 32) + 1;
+        }
+        const float characters = (limit * text_print_speed_mod_ / 16 + addition) / limit;
+        text_limit_ += time * characters;
+    }
+    update_transformation_ = true;
+}
+
+void UiTextArea::UpdateScrollText(){
+    text_y_offset_
+      -= font_->GetHeight() * Timer::getSingleton().GetGameTimeDelta() / text_scroll_time_;
+    if (text_y_offset_ <= text_y_offset_target_){
+        text_y_offset_ = text_y_offset_target_;
+        ContinueText();
+    }
+    update_transformation_ = true;
+}
+
+void UiTextArea::UpdatePauseTime(){
+    pause_time_ -= Timer::getSingleton().GetGameTimeDelta();
+    if (pause_time_ <= 0) ContinueText();
+}
+
+void UiTextArea::ContinueText(){
+    text_print_speed_mod_ = 1;
+    text_state_ = TS_SHOW_TEXT;
+}
+
+void UiTextArea::ScrollOneLine(){
+    text_y_offset_target_ = text_y_offset_ - font_->GetHeight();
+    text_state_ = TS_SCROLL_TEXT;
+}
+
+void UiTextArea::ShowNextPage(){
+    RemoveSpritesFromText(next_page_start_);
+    text_.erase(text_.begin(), text_.begin() + next_page_start_);
+    text_limit_ = 0;
+    text_y_offset_ = 0;
+    text_y_offset_target_ = 0;
+    ContinueText();
+}
+
 void UiTextArea::Render(){
     // Scripts that run after the widgets update (like the battle) can change the text or the
     // position of a widget in the same frame it is drawn, so the geometry is refreshed here.
@@ -232,26 +234,19 @@ void UiTextArea::PutNumber(const std::string& number, const int digits){
 }
 
 void UiTextArea::SetText(const char* text){
-    // Don't call PrepareTextFromNode from here!
-    // Use the non-recursive SetTextFromNode.
-    Ogre::UTFString str_text = Ogre::UTFString(text);
+    // Unlike the other ways of setting the text, the one already shown is not cleared: what has
+    // been printed is not printed again.
     text_.clear();
     TiXmlDocument doc;
-    Ogre::UTFString xml_text = "<container>" + str_text + "</container>";
+    const Ogre::UTFString xml_text = "<container>" + Ogre::UTFString(text) + "</container>";
     doc.Parse(xml_text.asUTF8_c_str(), 0, TIXML_ENCODING_UTF8);
-    SetTextFromNode(doc.RootElement(), colour_1_);
-    text_state_ = TS_SHOW_TEXT;
-    update_transformation_ = true;
-    GrowVertexBuffer(text_.size());
-    if (text_.size() > max_letters_){
-        text_.clear();
+    if (doc.Error()){
         LOG_ERROR(
-          "Max number of text reached in '" + path_name_ + "'. Can't render text from node. "
-          + "Max number of letters is " + Ogre::StringConverter::toString(max_letters_) + "."
+          "Can't parse text '" + Ogre::String(text) + "'. TinyXml Error: " + doc.ErrorDesc()
         );
     }
-    text_state_ = TS_SHOW_TEXT;
-    update_transformation_ = true;
+    // What could be read of an invalid text is shown.
+    ShowText(doc.RootElement());
 }
 
 void UiTextArea::SetText(const Ogre::UTFString& text){
@@ -266,19 +261,34 @@ void UiTextArea::SetText(const Ogre::UTFString& text){
 }
 
 void UiTextArea::SetText(TiXmlNode* text){
-    if (text == NULL){
+    if (text == nullptr){
         LOG_ERROR("Text pointer is NULL.");
         return;
     }
     // Reload font if language was changed.
-    if (font_ != NULL){
-        Ogre::String language = font_->GetLanguage();
-        if (language != "")
-            if (TextHandler::getSingleton().GetLanguage() != language) SetFont(font_->GetName());
+    if (font_ != nullptr){
+        const Ogre::String language = font_->GetLanguage();
+        if (language != "" && TextHandler::getSingleton().GetLanguage() != language)
+            SetFont(font_->GetName());
     }
-
     TextClear();
-    PrepareTextFromNode(text, colour_1_);
+    ShowText(text);
+}
+
+void UiTextArea::ShowText(TiXmlNode* node){
+    UiTextParser::Sources sources;
+    sources.variable = [this](const Ogre::String& name){return GetVariable(name);};
+    sources.character_name = [](int id){return TextHandler::getSingleton().GetCharacterName(id);};
+    sources.party_name = [](int position){
+        return TextHandler::getSingleton().GetPartyCharacterName(position);
+    };
+    sources.text = [](const Ogre::String& name){return TextHandler::getSingleton().GetText(name);};
+    sources.image = [this](const Ogre::String& name, TextChar& character){
+        return CreateImage(name, character);
+    };
+    UiTextParser parser(sources, text_);
+    parser.Parse(node, colour_1_);
+    if (parser.UsesTimer()) timer_ = true;
     text_state_ = TS_SHOW_TEXT;
     update_transformation_ = true;
     GrowVertexBuffer(text_.size());
@@ -291,6 +301,44 @@ void UiTextArea::SetText(TiXmlNode* text){
     }
 }
 
+bool UiTextArea::CreateImage(const Ogre::String& name, TextChar& character){
+    TiXmlNode* prototype = UiManager::getSingleton().GetPrototype("TextAreaSprite");
+    if (prototype == nullptr) return false;
+    for (TiXmlNode* node = prototype->FirstChild(); node != nullptr; node = node->NextSibling()){
+        if (
+          node->Type() != TiXmlNode::TINYXML_ELEMENT || node->ValueStr() != "sprite"
+          || GetString(node, "name") != name
+        ) continue;
+        UiSprite* sprite = new UiSprite(name, name_ + "." + name, this);
+        const Ogre::String image = GetString(node, "image");
+        if (image != "") sprite->SetImage(image);
+        const Ogre::String y = GetString(node, "y");
+        if (y != ""){
+            float percent = 0;
+            ParsePercent(percent, character.sprite_y, y);
+        }
+        const Ogre::String width = GetString(node, "width");
+        if (width != ""){
+            float percent = 0;
+            float pixels = 0;
+            ParsePercent(percent, pixels, width);
+            sprite->SetWidth(0, pixels);
+        }
+        const Ogre::String height = GetString(node, "height");
+        if (height != ""){
+            float percent = 0;
+            float pixels = 0;
+            ParsePercent(percent, pixels, height);
+            sprite->SetHeight(percent, pixels);
+        }
+        sprite->SetVisible(false);
+        AddChild(sprite);
+        character.sprite = sprite;
+        return true;
+    }
+    return false;
+}
+
 void UiTextArea::TextClear(){
     RemoveSpritesFromText(text_.size());
     text_.clear();
@@ -407,552 +455,96 @@ unsigned int UiTextArea::GetTextSize() const{return text_.size();}
 float UiTextArea::GetPauseTime() const{return pause_time_;}
 
 void UiTextArea::UpdateGeometry(){
-    if (font_ == NULL){
+    if (font_ == nullptr){
         LOG_ERROR("Font for '" + path_name_ + "' if not set.");
         return;
     }
-    float width = 0;
+    float align_width = 0;
     if (text_align_ != LEFT){
-        width = GetTextWidth();
-        if (text_align_ == CENTER) width /= 2;
+        align_width = UiTextLayout::TextWidth(
+          text_, [this](int code){return font_->GetCharData(code);}
+        );
+        if (text_align_ == CENTER) align_width /= 2;
     }
-    float* write_iterator
-      = static_cast<float*>(vertex_buffer_->lock(Ogre::HardwareBuffer::HBL_NORMAL));
+    const UiTextLayout::Area area{
+      final_origin_, final_size_, final_scale_, screen_height_,
+      padding_top_, padding_right_, padding_bottom_, padding_left_
+    };
+    UiTextLayout layout(area, align_width, text_y_offset_, font_->GetHeight());
+    float* vertices = static_cast<float*>(vertex_buffer_->lock(Ogre::HardwareBuffer::HBL_NORMAL));
     render_operation_.vertexData->vertexCount = 0;
-    float local_x_start
-      = -final_origin_.x - (width - padding_left_) * final_scale_.x * screen_height_ / 720.0f;
-    float local_x1 = local_x_start;
-    float local_y1 = -final_origin_.y + ((text_y_offset_ + padding_top_)
-      * final_scale_.y * screen_height_ / 720.0f);
-    float local_x2;
-    float local_y2;
-    float x = final_translate_.x;
-    float y = final_translate_.y;
     unsigned int i = 0;
     for (; (i < text_limit_) && (i < text_.size()); ++ i){
-        if (text_[i].skip == true) continue;
-        else if (text_[i].pause_ok == true){
-            text_[i].skip = true;
-            text_state_ = TS_PAUSE_OK;
-            break;
-        }
-        else if (text_[i].pause_time != 0){
-            text_[i].skip = true;
-            pause_time_ = text_[i].pause_time;
-            text_state_ = TS_PAUSE_TIME;
-            break;
-        }
-        else if (text_[i].next_page == true){
-            text_[i].skip = true;
-            next_page_start_ = i + 1;
-            text_state_ = TS_NEXT_PAGE;
-            break;
-        }
-        else if (text_[i].sprite != NULL){
-            float width_percent = 0;
-            float img_width = 0;
-            text_[i].sprite->GetWidth(width_percent, img_width);
-            text_[i].sprite->SetX(0, local_x1 / (final_scale_.x * screen_height_ / 720.0f));
-            local_x1 += img_width * final_scale_.x * screen_height_ / 720.0f;
-            float height_percent = 0;
-            float img_height = 0;
-            text_[i].sprite->GetHeight(height_percent, img_height);
-            text_[i].sprite->SetY(
-              0, text_[i].sprite_y + (local_y1 / (final_scale_.y * screen_height_ / 720.0f))
-            );
-            text_[i].sprite->SetVisible(true);
-            text_[i].sprite->UpdateGeometry();
+        TextChar& character = text_[i];
+        if (character.skip) continue;
+        if (StopAtCommand(i)) break;
+        if (character.sprite != nullptr){
+            PlaceSprite(character, layout);
             continue;
         }
-        UiCharData char_data = font_->GetCharData(text_[i].char_code);
-        Ogre::ColourValue colour = text_[i].colour;
-        if (char_data.char_code == 10){ // LF (line feed): \n
-            local_x1 = local_x_start;
-            local_y1 += font_->GetHeight() * final_scale_.y * screen_height_ / 720.0f;
+        const UiCharData data = font_->GetCharData(character.char_code);
+        if (data.char_code == 10){ // LF (line feed): \n
+            layout.NewLine();
             continue;
         }
-        local_x1 += char_data.pre * final_scale_.x * screen_height_ / 720.0f;
-        local_x2 = local_x1 + char_data.width * final_scale_.x * screen_height_ / 720.0f;
-        local_y2 = local_y1 + char_data.height * final_scale_.y * screen_height_ / 720.0f;
-        if (
-          local_x2 + char_data.post * final_scale_.x * screen_height_ / 720.0f
-          > final_size_.x - padding_right_ * final_scale_.x * screen_height_ / 720.0f
-        ){
-            local_x1 = local_x_start;
-            local_x2 = local_x1 + char_data.width * final_scale_.x * screen_height_ / 720.0f;
-            local_y1 += font_->GetHeight() * final_scale_.y * screen_height_ / 720.0f;
-            local_y2 = local_y1 + char_data.height * final_scale_.y * screen_height_ / 720.0f;
-        }
-
-        // If the lower border of the textarea is crossed:
-        // generate event and stop rendering
-        if (local_y2 > final_size_.y - padding_bottom_ * final_scale_.y * screen_height_ / 720.0f){
+        UiTextLayout::Box box;
+        // The text goes below the area: the rest is not drawn.
+        if (!layout.Place(data, box)){
             if (text_state_ != TS_SCROLL_TEXT) text_state_ = TS_OVERFLOW;
             break;
         }
-        int x1, y1, x2, y2, x3, y3, x4, y4;
-        if (final_rotation_ != 0){
-            float cos = Ogre::Math::Cos(Ogre::Radian(Ogre::Degree(final_rotation_)));
-            float sin = Ogre::Math::Sin(Ogre::Radian(Ogre::Degree(final_rotation_)));
-            x1 = local_x1 * cos - local_y1 * sin + x;
-            y1 = local_x1 * sin + local_y1 * cos + y;
-            x2 = local_x2 * cos - local_y1 * sin + x;
-            y2 = local_x2 * sin + local_y1 * cos + y;
-            x3 = local_x2 * cos - local_y2 * sin + x;
-            y3 = local_x2 * sin + local_y2 * cos + y;
-            x4 = local_x1 * cos - local_y2 * sin + x;
-            y4 = local_x1 * sin + local_y2 * cos + y;
-        }
-        else{
-            x1 = local_x1 + x;
-            y1 = local_y1 + y;
-            x2 = local_x2 + x;
-            y2 = local_y1 + y;
-            x3 = local_x2 + x;
-            y3 = local_y2 + y;
-            x4 = local_x1 + x;
-            y4 = local_y2 + y;
-        }
-        float new_x1 = (x1 / screen_width_) * 2 - 1;
-        float new_y1 = -((y1 / screen_height_) * 2 - 1);
-        float new_x2 = (x2 / screen_width_) * 2 - 1;
-        float new_y2 = -((y2 / screen_height_) * 2 - 1);
-        float new_x3 = (x3 / screen_width_) * 2 - 1;
-        float new_y3 = -((y3 / screen_height_) * 2 - 1);
-        float new_x4 = (x4 / screen_width_) * 2 - 1;
-        float new_y4 = -((y4 / screen_height_) * 2 - 1);
-        local_x1 += (char_data.width + char_data.post) * final_scale_.x * screen_height_ / 720.0f;
-        float img_width = font_->GetImageWidth();
-        float img_height = font_->GetImageHeight();
-        float left = (float)char_data.x / img_width;
-        float right = (float)(char_data.x + char_data.width) / img_width;
-        float top = (float)char_data.y / img_height;
-        float bottom = (float)(char_data.y + char_data.height) / img_height;
-
-        *write_iterator ++ = new_x1;
-        *write_iterator ++ = new_y1;
-        *write_iterator ++ = final_z_;
-        *write_iterator ++ = colour.r;
-        *write_iterator ++ = colour.g;
-        *write_iterator ++ = colour.b;
-        *write_iterator ++ = colour.a;
-        *write_iterator ++ = left;
-        *write_iterator ++ = top;
-
-        *write_iterator ++ = new_x2;
-        *write_iterator ++ = new_y2;
-        *write_iterator ++ = final_z_;
-        *write_iterator ++ = colour.r;
-        *write_iterator ++ = colour.g;
-        *write_iterator ++ = colour.b;
-        *write_iterator ++ = colour.a;
-        *write_iterator ++ = right;
-        *write_iterator ++ = top;
-
-        *write_iterator ++ = new_x3;
-        *write_iterator ++ = new_y3;
-        *write_iterator ++ = final_z_;
-        *write_iterator ++ = colour.r;
-        *write_iterator ++ = colour.g;
-        *write_iterator ++ = colour.b;
-        *write_iterator ++ = colour.a;
-        *write_iterator ++ = right;
-        *write_iterator ++ = bottom;
-
-        *write_iterator ++ = new_x1;
-        *write_iterator ++ = new_y1;
-        *write_iterator ++ = final_z_;
-        *write_iterator ++ = colour.r;
-        *write_iterator ++ = colour.g;
-        *write_iterator ++ = colour.b;
-        *write_iterator ++ = colour.a;
-        *write_iterator ++ = left;
-        *write_iterator ++ = top;
-
-        *write_iterator ++ = new_x3;
-        *write_iterator ++ = new_y3;
-        *write_iterator ++ = final_z_;
-        *write_iterator ++ = colour.r;
-        *write_iterator ++ = colour.g;
-        *write_iterator ++ = colour.b;
-        *write_iterator ++ = colour.a;
-        *write_iterator ++ = right;
-        *write_iterator ++ = bottom;
-
-        *write_iterator ++ = new_x4;
-        *write_iterator ++ = new_y4;
-        *write_iterator ++ = final_z_;
-        *write_iterator ++ = colour.r;
-        *write_iterator ++ = colour.g;
-        *write_iterator ++ = colour.b;
-        *write_iterator ++ = colour.a;
-        *write_iterator ++ = left;
-        *write_iterator ++ = bottom;
-
-        render_operation_.vertexData->vertexCount += 6;
+        WriteCharacter(vertices, box, data, character.colour);
     }
     vertex_buffer_->unlock();
     if (i == text_.size()) text_state_ = TS_DONE;
 }
 
-float UiTextArea::GetTextWidth() const{
-    float width = 0;
-    float width_max = 0;
-    for (unsigned int i = 0; i < text_.size(); ++ i){
-        UiCharData char_data = font_->GetCharData(text_[i].char_code);
-        // If newline, store previous row max width
-        if (char_data.char_code == 10){
-            width_max = (width > width_max) ? width : width_max;
-            width = 0;
-        }
-        else width += char_data.pre + char_data.width + char_data.post;
+bool UiTextArea::StopAtCommand(const unsigned int index){
+    TextChar& character = text_[index];
+    if (character.pause_ok) text_state_ = TS_PAUSE_OK;
+    else if (character.pause_time != 0){
+        pause_time_ = character.pause_time;
+        text_state_ = TS_PAUSE_TIME;
     }
-    return (width > width_max) ? width : width_max;
-}
-
-void UiTextArea::PrepareTextFromNode(TiXmlNode* node, const Ogre::ColourValue& colour){
-
-    while (node != NULL){
-        switch(node->Type()){
-            case TiXmlNode::TINYXML_TEXT:
-                {
-                    TiXmlText* childText = node->ToText();
-                    if (childText) PrepareTextFromText(childText->Value(), colour);
-                }
-                break;
-            case TiXmlNode::TINYXML_ELEMENT:
-                {
-                    Ogre::ColourValue colour_child = colour;
-                    Ogre::String name = node->ValueStr();
-                    if (name == "colour"){
-                        colour_child = Ogre::StringConverter::parseColourValue(
-                          node->ToElement()->Attribute("value")
-                        );
-                    }
-                    else if (name == "pause_ok"){
-                        TextChar new_char;
-                        new_char.pause_ok = true;
-                        text_.push_back(new_char);
-                    }
-                    else if (name == "pause"){
-                        const std::string* string
-                          = node->ToElement()->Attribute(Ogre::String("time"));
-                        if (string != NULL){
-                            TextChar new_char;
-                            // The time of the pause is in frames of the game (30 per second), as in the original game.
-                            new_char.pause_time = Ogre::StringConverter::parseReal(*string) / 30.0f;
-                            text_.push_back(new_char);
-                        }
-                    }
-                    else if (name == "next_page"){
-                        TextChar new_char;
-                        new_char.next_page = true;
-                        text_.push_back(new_char);
-                    }
-                    else if (name == "timer"){
-                        timer_ = true;
-                        TextChar new_char;
-                        new_char.skip = true;
-                        new_char.variable = "UITextAreaTimer";
-                        new_char.colour = colour;
-                        Ogre::UTFString var = GetVariable("UITextAreaTimer");
-                        new_char.variable_len = var.size();
-                        text_.push_back(new_char);
-                        for (unsigned int i = 0; i < var.size(); ++ i){
-                            TextChar text_char;
-                            text_char.char_code = var[i];
-                            text_char.colour = colour;
-                            text_.push_back(text_char);
-                        }
-                    }
-                    else if (name == "variable"){
-                        const std::string* string
-                          = node->ToElement()->Attribute(Ogre::String("name"));
-                        if (string != NULL){
-                            TextChar new_char;
-                            new_char.skip = true;
-                            new_char.variable = *string;
-                            new_char.colour = colour;
-                            Ogre::UTFString var = GetVariable(*string);
-                            new_char.variable_len = var.size();
-                            text_.push_back(new_char);
-                            for (unsigned int i = 0; i < var.size(); ++ i){
-                                TextChar text_char;
-                                text_char.char_code = var[i];
-                                text_char.colour = colour;
-                                text_.push_back(text_char);
-                            }
-                        }
-                    }
-                    else if (name == "character"){
-                        const std::string* id = node->ToElement()->Attribute(Ogre::String("id"));
-                        const std::string char_name = TextHandler::getSingleton().GetCharacterName(
-                          std::stoi(*id)
-                        );
-                        for (unsigned int i = 0; i < char_name.length(); ++ i){
-                            TextChar text_char;
-                            text_char.char_code = char_name.at(i);
-                            text_char.colour = colour;
-                            text_.push_back(text_char);
-                        }
-                    }
-                    else if (name == "party"){
-                        const std::string* pos = node->ToElement()->Attribute(Ogre::String("pos"));
-                        const std::string char_name
-                          = TextHandler::getSingleton().GetPartyCharacterName(std::stoi(*pos));
-                        for (unsigned int i = 0; i < char_name.length(); ++ i){
-                            TextChar text_char;
-                            text_char.char_code = char_name.at(i);
-                            text_char.colour = colour;
-                            text_.push_back(text_char);
-                        }
-                    }
-                    else if (name == "include"){
-                        const std::string* text_name = node->ToElement()->Attribute(
-                          Ogre::String("name")
-                        );
-                        if (text_name != NULL){
-                            TiXmlNode* text = TextHandler::getSingleton().GetText(*text_name);
-                            if (text != NULL) PrepareTextFromNode(text, colour_child);
-                        }
-                    }
-                    else if (name == "image"){
-                        Ogre::String name1 = GetString(node, "sprite");
-                        if (name1 != ""){
-                            TiXmlNode* sprites = UiManager::getSingleton().GetPrototype(
-                              "TextAreaSprite"
-                            );
-                            if (sprites != NULL){
-                                sprites = sprites->FirstChild();
-                                while (sprites != NULL){
-                                    if (
-                                      sprites->Type() == TiXmlNode::TINYXML_ELEMENT
-                                      && sprites->ValueStr() == "sprite"
-                                    ){
-                                        Ogre::String name2 = GetString(sprites, "name");
-                                        if (name1 == name2){
-                                            TextChar new_char;
-                                            UiSprite* sprite = new UiSprite(
-                                              name1, name_ + "." + name1, this
-                                            );
-                                            Ogre::String image = GetString(sprites, "image");
-                                            if (image != "") sprite->SetImage(image);
-                                            Ogre::String y_str = GetString(sprites, "y");
-                                            if (y_str != ""){
-                                                float y_percent = 0;
-                                                float y = 0;
-                                                ParsePercent(y_percent, y, y_str);
-                                                new_char.sprite_y = y;
-                                            }
-                                            Ogre::String width_str = GetString(sprites, "width");
-                                            if (width_str != ""){
-                                                float width_percent = 0;
-                                                float width = 0;
-                                                ParsePercent(width_percent, width, width_str);
-                                                sprite->SetWidth(0, width);
-                                            }
-                                            Ogre::String height_str = GetString(sprites, "height");
-                                            if (height_str != ""){
-                                                float height_percent = 0;
-                                                float height = 0;
-                                                ParsePercent(height_percent, height, height_str);
-                                                sprite->SetHeight(height_percent, height);
-                                            }
-                                            sprite->SetVisible(false);
-                                            AddChild(sprite);
-                                            new_char.sprite = sprite;
-                                            text_.push_back(new_char);
-                                            break;
-                                        }
-                                    }
-                                    sprites = sprites->NextSibling();
-                                }
-                            }
-                        }
-                    }
-                    TiXmlNode* node_child = node->FirstChild();
-                    if (node_child != NULL) PrepareTextFromNode(node_child, colour_child);
-                }
-            break;
-        }
-        node = node->NextSibling();
+    else if (character.next_page){
+        next_page_start_ = index + 1;
+        text_state_ = TS_NEXT_PAGE;
     }
+    else return false;
+    // The command is done only once.
+    character.skip = true;
+    return true;
 }
 
-void UiTextArea::SetTextFromNode(TiXmlNode* node, const Ogre::ColourValue& colour){
-    switch(node->Type()){
-        case TiXmlNode::TINYXML_TEXT:
-            {
-                TiXmlText* childText = node->ToText();
-                if (childText) PrepareTextFromText(childText->Value(), colour);
-            }
-            break;
-        case TiXmlNode::TINYXML_ELEMENT:
-            {
-                Ogre::ColourValue colour_child = colour;
-                Ogre::String name = node->ValueStr();
-                if (name == "colour"){
-                    colour_child = Ogre::StringConverter::parseColourValue(
-                      node->ToElement()->Attribute("value")
-                    );
-                }
-                else if (name == "pause_ok"){
-                    TextChar new_char;
-                    new_char.pause_ok = true;
-                    text_.push_back(new_char);
-                }
-                else if (name == "pause"){
-                    const std::string* string
-                      = node->ToElement()->Attribute(Ogre::String("time"));
-                    if (string != NULL){
-                        TextChar new_char;
-                        // The time of the pause is in frames of the game (30 per second), as in the original game.
-                        new_char.pause_time = Ogre::StringConverter::parseReal(*string) / 30.0f;
-                        text_.push_back(new_char);
-                    }
-                }
-                else if (name == "next_page"){
-                    TextChar new_char;
-                    new_char.next_page = true;
-                    text_.push_back(new_char);
-                }
-                else if (name == "timer"){
-                    timer_ = true;
-                    TextChar new_char;
-                    new_char.skip = true;
-                    new_char.variable = "UITextAreaTimer";
-                    new_char.colour = colour;
-                    Ogre::UTFString var = GetVariable("UITextAreaTimer");
-                    new_char.variable_len = var.size();
-                    text_.push_back(new_char);
-                    for (unsigned int i = 0; i < var.size(); ++ i){
-                        TextChar text_char;
-                        text_char.char_code = var[i];
-                        text_char.colour = colour;
-                        text_.push_back(text_char);
-                    }
-                }
-                else if (name == "variable"){
-                    const std::string* string
-                      = node->ToElement()->Attribute(Ogre::String("name"));
-                    if (string != NULL){
-                        TextChar new_char;
-                        new_char.skip = true;
-                        new_char.variable = *string;
-                        new_char.colour = colour;
-                        Ogre::UTFString var = GetVariable(*string);
-                        new_char.variable_len = var.size();
-                        text_.push_back(new_char);
-                        for (unsigned int i = 0; i < var.size(); ++ i){
-                            TextChar text_char;
-                            text_char.char_code = var[i];
-                            text_char.colour = colour;
-                            text_.push_back(text_char);
-                        }
-                    }
-                }
-                else if (name == "character"){
-                    const std::string* id = node->ToElement()->Attribute(Ogre::String("id"));
-                    const std::string char_name = TextHandler::getSingleton().GetCharacterName(
-                      std::stoi(*id)
-                    );
-                    for (unsigned int i = 0; i < char_name.length(); ++ i){
-                        TextChar text_char;
-                        text_char.char_code = char_name.at(i);
-                        text_char.colour = colour;
-                        text_.push_back(text_char);
-                    }
-                }
-                else if (name == "party"){
-                    const std::string* pos = node->ToElement()->Attribute(Ogre::String("pos"));
-                    const std::string char_name
-                      = TextHandler::getSingleton().GetPartyCharacterName(std::stoi(*pos));
-                    for (unsigned int i = 0; i < char_name.length(); ++ i){
-                        TextChar text_char;
-                        text_char.char_code = char_name.at(i);
-                        text_char.colour = colour;
-                        text_.push_back(text_char);
-                    }
-                }
-                else if (name == "include"){
-                    const std::string* text_name = node->ToElement()->Attribute(
-                      Ogre::String("name")
-                    );
-                    if (text_name != NULL){
-                        TiXmlNode* text = TextHandler::getSingleton().GetText(*text_name);
-                        if (text != NULL) SetTextFromNode(text, colour_child);
-                    }
-                }
-                else if (name == "image"){
-                    Ogre::String name1 = GetString(node, "sprite");
-                    if (name1 != ""){
-                        TiXmlNode* sprites = UiManager::getSingleton().GetPrototype(
-                          "TextAreaSprite"
-                        );
-                        if (sprites != NULL){
-                            sprites = sprites->FirstChild();
-                            while (sprites != NULL){
-                                if (
-                                  sprites->Type() == TiXmlNode::TINYXML_ELEMENT
-                                  && sprites->ValueStr() == "sprite"
-                                ){
-                                    Ogre::String name2 = GetString(sprites, "name");
-                                    if (name1 == name2){
-                                        TextChar new_char;
-                                        UiSprite* sprite = new UiSprite(
-                                          name1, name_ + "." + name1, this
-                                        );
-                                        Ogre::String image = GetString(sprites, "image");
-                                        if (image != "") sprite->SetImage(image);
-                                        Ogre::String y_str = GetString(sprites, "y");
-                                        if (y_str != ""){
-                                            float y_percent = 0;
-                                            float y = 0;
-                                            ParsePercent(y_percent, y, y_str);
-                                            new_char.sprite_y = y;
-                                        }
-                                        Ogre::String width_str = GetString(sprites, "width");
-                                        if (width_str != ""){
-                                            float width_percent = 0;
-                                            float width = 0;
-                                            ParsePercent(width_percent, width, width_str);
-                                            sprite->SetWidth(0, width);
-                                        }
-                                        Ogre::String height_str = GetString(sprites, "height");
-                                        if (height_str != ""){
-                                            float height_percent = 0;
-                                            float height = 0;
-                                            ParsePercent(height_percent, height, height_str);
-                                            sprite->SetHeight(height_percent, height);
-                                        }
-                                        sprite->SetVisible(false);
-                                        AddChild(sprite);
-                                        new_char.sprite = sprite;
-                                        text_.push_back(new_char);
-                                        break;
-                                    }
-                                }
-                                sprites = sprites->NextSibling();
-                            }
-                        }
-                    }
-                }
-                TiXmlNode* node_child = node->FirstChild();
-                if (node_child != NULL) SetTextFromNode(node_child, colour_child);
-            }
-        break;
-    }
+void UiTextArea::PlaceSprite(const TextChar& character, UiTextLayout& layout){
+    float percent = 0;
+    float width = 0;
+    character.sprite->GetWidth(percent, width);
+    float x = 0;
+    float y = 0;
+    layout.PlaceImage(width, x, y);
+    character.sprite->SetX(0, x);
+    character.sprite->SetY(0, character.sprite_y + y);
+    character.sprite->SetVisible(true);
+    character.sprite->UpdateGeometry();
 }
 
-void UiTextArea::PrepareTextFromText(
-  const Ogre::UTFString& text, const Ogre::ColourValue& colour_child
+void UiTextArea::WriteCharacter(
+  float*& vertices, const UiTextLayout::Box& box, const UiCharData& data,
+  const Ogre::ColourValue& colour
 ){
-    for (unsigned int i = 0; i < text.size(); ++ i){
-        TextChar new_char;
-        new_char.char_code = text[i];
-        new_char.colour = colour_child;
-        text_.push_back(new_char);
+    const float width = font_->GetImageWidth();
+    const float height = font_->GetImageHeight();
+    const UiTextLayout::Box texture{
+      static_cast<float>(data.x) / width, static_cast<float>(data.y) / height,
+      static_cast<float>(data.x + data.width) / width,
+      static_cast<float>(data.y + data.height) / height
     };
+    const std::array<Ogre::Vector2, 4> corners = UiTextLayout::ScreenCorners(
+      box, final_translate_, final_rotation_, Ogre::Vector2(screen_width_, screen_height_)
+    );
+    UiTextLayout::WriteQuad(vertices, corners, texture, final_z_, colour);
+    render_operation_.vertexData->vertexCount += 6;
 }
 
 void UiTextArea::GrowVertexBuffer(const unsigned int letters){

+ 66 - 93
src/engine/ui/UiTextArea.h

@@ -22,10 +22,10 @@
 #include <tinyxml.h>
 
 #include "UiFont.h"
+#include "UiTextChar.h"
+#include "UiTextLayout.h"
 #include "UiWidget.h"
 
-class UiSprite;
-
 /**
  * The textarea state.
  */
@@ -67,76 +67,6 @@ enum TextState{
     TS_NEXT_PAGE,
 };
 
-/**
- * A character in a text.
- */
-struct TextChar{
-    TextChar():
-      char_code(0),
-      colour(Ogre::ColourValue::White),
-      skip(false),
-      variable(""),
-      variable_len(0),
-      pause_ok(false),
-      pause_time(0.0f),
-      next_page(false),
-      sprite(NULL),
-      sprite_y(0)
-    {}
-
-    /**
-     * The character code.
-     *
-     * Normal character code, no FF7 code tables.
-     */
-    int char_code;
-
-    /**
-     * Color for the character.
-     */
-    Ogre::ColourValue colour;
-
-    /**
-     * Indicates if the character is to be actually printed.
-     */
-    bool skip;
-
-    /**
-     * If the character is a variable, the variable name.
-     */
-    Ogre::String variable;
-
-    /**
-     * If the character is a variable, the variable length.
-     */
-    unsigned int variable_len;
-
-    /**
-     * Indicates if the OK button has been pressed during a text pause.
-     */
-    bool pause_ok;
-
-    /**
-     * For pause characters, the time.
-     */
-    float pause_time;
-
-    /**
-     * Indicates if the character is a new page character.
-     */
-    bool next_page;
-
-    /**
-     * If the character is a symbol or an image, this is the sprite.
-     */
-    UiSprite* sprite;
-
-    /**
-     * If the character is a symbol or an image, this is the Y position.
-     */
-    float sprite_y;
-};
-
 /**
  * A variable displayed in a text.
  */
@@ -383,41 +313,84 @@ class UiTextArea : public UiWidget{
     private:
 
         /**
-         * Retrieves the text width.
-         *
-         * @return The text width, in pixels.
+         * Writes the time of the game timer in its variable, if it changed.
          */
-        float GetTextWidth() const;
+        void UpdateTimer();
 
         /**
-         * Prepares text from a XML node.
-         *
-         * Not to be used to set text dinamically from scripts repatedly (i.e. for menus). It can
-         * produce memory leaks, and it's slower. Use {@see SetTextFromNode} for that.
+         * Prints more of the text.
+         */
+        void UpdateShowText();
+
+        /**
+         * Scrolls the text.
+         */
+        void UpdateScrollText();
+
+        /**
+         * Waits the time of a pause.
+         */
+        void UpdatePauseTime();
+
+        /**
+         * Goes on printing the text after a pause or a scroll.
+         */
+        void ContinueText();
+
+        /**
+         * Starts scrolling a line, to show the text that did not fit.
+         */
+        void ScrollOneLine();
+
+        /**
+         * Removes the current page and starts printing the next one.
+         */
+        void ShowNextPage();
+
+        /**
+         * Reads the markup of a text, adds its characters and starts showing it.
          *
-         * @param[in] node The XML node to get the text from.
-         * @param[in] colour The text colour.
+         * @param[in] node The text.
          */
-        void PrepareTextFromNode(TiXmlNode* node, const Ogre::ColourValue& colour);
+        void ShowText(TiXmlNode* node);
 
         /**
-         * Prepares text from a XML node.
+         * Creates the sprite of an image of a text.
          *
-         * Use this when setting text dinamically from scripts, instead of
-         * {@see PrepareTextFromNode}.
+         * @param[in] name Name of the image, from the "TextAreaSprite" prototype.
+         * @param[out] character The sprite and its position are set in it.
+         * @return False if there is no such image.
+         */
+        bool CreateImage(const Ogre::String& name, TextChar& character);
+
+        /**
+         * Stops the printing of the text at a pause or a page break.
          *
-         * @param[in] node The XML node to get the text from.
-         * @param[in] colour The text colour.
+         * @param[in] index Index of a character of the text.
+         * @return True if the character is one of those.
          */
-        void SetTextFromNode(TiXmlNode* node, const Ogre::ColourValue& colour);
+        bool StopAtCommand(const unsigned int index);
 
         /**
-         * Prepares text from a string.
+         * Puts the sprite of a character in its place and shows it.
          *
-         * @param[in] text The text to prepare.
-         * @param[in] colour The text colour.
+         * @param[in] character The character.
+         * @param[in,out] layout Layout of the text.
          */
-        void PrepareTextFromText(const Ogre::UTFString& text, const Ogre::ColourValue& colour);
+        void PlaceSprite(const TextChar& character, UiTextLayout& layout);
+
+        /**
+         * Writes the vertices of a character.
+         *
+         * @param[in,out] vertices Where to write them. It is moved past them.
+         * @param[in] box Where the character goes.
+         * @param[in] data The character in the font.
+         * @param[in] colour Colour of the character.
+         */
+        void WriteCharacter(
+          float*& vertices, const UiTextLayout::Box& box, const UiCharData& data,
+          const Ogre::ColourValue& colour
+        );
 
         /**
          * Constructor.

+ 91 - 0
src/engine/ui/UiTextChar.h

@@ -0,0 +1,91 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <OgreColourValue.h>
+#include <OgrePrerequisites.h>
+
+class UiSprite;
+
+/**
+ * A character in a text.
+ */
+struct TextChar{
+    TextChar():
+      char_code(0),
+      colour(Ogre::ColourValue::White),
+      skip(false),
+      variable(""),
+      variable_len(0),
+      pause_ok(false),
+      pause_time(0.0f),
+      next_page(false),
+      sprite(nullptr),
+      sprite_y(0)
+    {}
+
+    /**
+     * The character code.
+     *
+     * Normal character code, no FF7 code tables.
+     */
+    int char_code;
+
+    /**
+     * Color for the character.
+     */
+    Ogre::ColourValue colour;
+
+    /**
+     * Indicates if the character is to be actually printed.
+     */
+    bool skip;
+
+    /**
+     * If the character is a variable, the variable name.
+     */
+    Ogre::String variable;
+
+    /**
+     * If the character is a variable, the variable length.
+     */
+    unsigned int variable_len;
+
+    /**
+     * Indicates if the OK button has been pressed during a text pause.
+     */
+    bool pause_ok;
+
+    /**
+     * For pause characters, the time.
+     */
+    float pause_time;
+
+    /**
+     * Indicates if the character is a new page character.
+     */
+    bool next_page;
+
+    /**
+     * If the character is a symbol or an image, this is the sprite.
+     */
+    UiSprite* sprite;
+
+    /**
+     * If the character is a symbol or an image, this is the Y position.
+     */
+    float sprite_y;
+};

+ 126 - 0
src/engine/ui/UiTextLayout.cpp

@@ -0,0 +1,126 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <algorithm>
+#include <OgreMath.h>
+#include "UiTextLayout.h"
+
+namespace{
+
+    /**
+     * Height of the screen the sizes are for.
+     */
+    const float REFERENCE_HEIGHT = 720.0f;
+}
+
+UiTextLayout::UiTextLayout(
+  const Area& area, const float align_width, const float scroll, const int line_height
+):
+  area_(area), line_height_(line_height)
+{
+    line_start_ = -area_.origin.x - ScaleX(align_width - area_.padding_left);
+    x_ = line_start_;
+    y_ = -area_.origin.y + ScaleY(scroll + area_.padding_top);
+}
+
+void UiTextLayout::NewLine(){
+    x_ = line_start_;
+    y_ += ScaleY(line_height_);
+}
+
+bool UiTextLayout::Place(const UiCharData& character, Box& box){
+    x_ += ScaleX(character.pre);
+    if (
+      x_ + ScaleX(character.width) + ScaleX(character.post)
+      > area_.size.x - ScaleX(area_.padding_right)
+    ) NewLine();
+    box.left = x_;
+    box.top = y_;
+    box.right = x_ + ScaleX(character.width);
+    box.bottom = y_ + ScaleY(character.height);
+    if (box.bottom > area_.size.y - ScaleY(area_.padding_bottom)) return false;
+    x_ += ScaleX(character.width + character.post);
+    return true;
+}
+
+void UiTextLayout::PlaceImage(const float width, float& x, float& y){
+    x = x_ / (area_.scale.x * area_.screen_height / REFERENCE_HEIGHT);
+    y = y_ / (area_.scale.y * area_.screen_height / REFERENCE_HEIGHT);
+    x_ += ScaleX(width);
+}
+
+float UiTextLayout::TextWidth(
+  const std::vector<TextChar>& text, const std::function<UiCharData(int)>& character_data
+){
+    float width = 0;
+    float longest = 0;
+    for (const TextChar& character : text){
+        const UiCharData data = character_data(character.char_code);
+        // Line feed.
+        if (data.char_code == 10){
+            longest = std::max(longest, width);
+            width = 0;
+        }
+        else width += data.pre + data.width + data.post;
+    }
+    return std::max(longest, width);
+}
+
+std::array<Ogre::Vector2, 4> UiTextLayout::ScreenCorners(
+  const Box& box, const Ogre::Vector2& translate, const float rotation,
+  const Ogre::Vector2& screen
+){
+    std::array<Ogre::Vector2, 4> corners{{
+      {box.left, box.top}, {box.right, box.top}, {box.right, box.bottom}, {box.left, box.bottom}
+    }};
+    float cos = 1;
+    float sin = 0;
+    if (rotation != 0){
+        cos = Ogre::Math::Cos(Ogre::Radian(Ogre::Degree(rotation)));
+        sin = Ogre::Math::Sin(Ogre::Radian(Ogre::Degree(rotation)));
+    }
+    for (Ogre::Vector2& corner : corners){
+        // The corners are on whole pixels.
+        const int x = corner.x * cos - corner.y * sin + translate.x;
+        const int y = corner.x * sin + corner.y * cos + translate.y;
+        corner.x = (x / screen.x) * 2 - 1;
+        corner.y = -((y / screen.y) * 2 - 1);
+    }
+    return corners;
+}
+
+void UiTextLayout::WriteQuad(
+  float*& vertices, const std::array<Ogre::Vector2, 4>& corners, const Box& texture,
+  const float depth, const Ogre::ColourValue& colour
+){
+    const std::array<Ogre::Vector2, 4> coordinates{{
+      {texture.left, texture.top}, {texture.right, texture.top},
+      {texture.right, texture.bottom}, {texture.left, texture.bottom}
+    }};
+    for (const int corner : {0, 1, 2, 0, 2, 3}){
+        for (const float value : {
+          corners[corner].x, corners[corner].y, depth, colour.r, colour.g, colour.b, colour.a,
+          coordinates[corner].x, coordinates[corner].y
+        }) *vertices ++ = value;
+    }
+}
+
+float UiTextLayout::ScaleX(const float size) const{
+    return size * area_.scale.x * area_.screen_height / REFERENCE_HEIGHT;
+}
+
+float UiTextLayout::ScaleY(const float size) const{
+    return size * area_.scale.y * area_.screen_height / REFERENCE_HEIGHT;
+}

+ 201 - 0
src/engine/ui/UiTextLayout.h

@@ -0,0 +1,201 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <array>
+#include <functional>
+#include <vector>
+#include <OgreColourValue.h>
+#include <OgreVector2.h>
+#include "UiFont.h"
+#include "UiTextChar.h"
+
+/**
+ * Decides where the characters of a text area go, and writes their vertices.
+ *
+ * Positions are relative to the position of the text area, in pixels of the screen. Sizes of the
+ * fonts, paddings and images are for a screen 720 pixels high, and are scaled to the real one.
+ */
+class UiTextLayout{
+
+    public:
+
+        /**
+         * Number of values of a vertex: position (3), colour (4) and texture coordinates (2).
+         */
+        static const int VERTEX_SIZE = 9;
+
+        /**
+         * Where a text area is, and its sizes.
+         */
+        struct Area{
+
+            /** Origin of the area. */
+            Ogre::Vector2 origin;
+
+            /** Size of the area, in pixels. */
+            Ogre::Vector2 size;
+
+            /** Scale of the area. */
+            Ogre::Vector2 scale;
+
+            /** Height of the screen. */
+            float screen_height;
+
+            /** Padding at the top. */
+            float padding_top;
+
+            /** Padding at the right. */
+            float padding_right;
+
+            /** Padding at the bottom. */
+            float padding_bottom;
+
+            /** Padding at the left. */
+            float padding_left;
+        };
+
+        /**
+         * The rectangle of a character.
+         */
+        struct Box{
+
+            /** Left side. */
+            float left;
+
+            /** Top side. */
+            float top;
+
+            /** Right side. */
+            float right;
+
+            /** Bottom side. */
+            float bottom;
+        };
+
+        /**
+         * Constructor. The first character goes at the beginning of the first line.
+         *
+         * @param[in] area The text area.
+         * @param[in] align_width Width of the text to the left of the starting position: 0 for text
+         * aligned to the left, the width of the text for the right, half of it to center it.
+         * @param[in] scroll Vertical offset of the text.
+         * @param[in] line_height Height of the lines of the font.
+         */
+        UiTextLayout(
+          const Area& area, const float align_width, const float scroll, const int line_height
+        );
+
+        /**
+         * Moves to the beginning of the next line.
+         */
+        void NewLine();
+
+        /**
+         * Places a character, in the next line if it doesn't fit in the current one.
+         *
+         * @param[in] character Sizes of the character.
+         * @param[out] box Where the character goes.
+         * @return False if the character goes below the area. It must not be drawn.
+         */
+        bool Place(const UiCharData& character, Box& box);
+
+        /**
+         * Places an image.
+         *
+         * @param[in] width Width of the image.
+         * @param[out] x Horizontal position of the image, in the units of the sizes.
+         * @param[out] y Vertical position of the line, in the units of the sizes.
+         */
+        void PlaceImage(const float width, float& x, float& y);
+
+        /**
+         * Calculates the width of a text: the width of its longest line.
+         *
+         * @param[in] text The text.
+         * @param[in] character_data Retrieves the sizes of a character.
+         * @return The width.
+         */
+        static float TextWidth(
+          const std::vector<TextChar>& text,
+          const std::function<UiCharData(int)>& character_data
+        );
+
+        /**
+         * Calculates the corners of a rectangle on the screen, in the -1 to 1 range.
+         *
+         * @param[in] box The rectangle.
+         * @param[in] translate Position of the text area.
+         * @param[in] rotation Rotation of the text area, in degrees.
+         * @param[in] screen Size of the screen.
+         * @return The top left, top right, bottom right and bottom left corners.
+         */
+        static std::array<Ogre::Vector2, 4> ScreenCorners(
+          const Box& box, const Ogre::Vector2& translate, const float rotation,
+          const Ogre::Vector2& screen
+        );
+
+        /**
+         * Writes the two triangles of a rectangle with a part of a texture.
+         *
+         * @param[in,out] vertices Where to write 6 vertices. It's moved past them.
+         * @param[in] corners Corners of the rectangle, as returned by {@see ScreenCorners}.
+         * @param[in] texture The part of the texture, in the 0 to 1 range.
+         * @param[in] depth Depth of the vertices.
+         * @param[in] colour Colour of the vertices.
+         */
+        static void WriteQuad(
+          float*& vertices, const std::array<Ogre::Vector2, 4>& corners, const Box& texture,
+          const float depth, const Ogre::ColourValue& colour
+        );
+
+    private:
+
+        /**
+         * Converts a horizontal size to pixels of the screen.
+         */
+        float ScaleX(const float size) const;
+
+        /**
+         * Converts a vertical size to pixels of the screen.
+         */
+        float ScaleY(const float size) const;
+
+        /**
+         * The text area.
+         */
+        Area area_;
+
+        /**
+         * Height of the lines.
+         */
+        int line_height_;
+
+        /**
+         * Where the lines begin.
+         */
+        float line_start_;
+
+        /**
+         * Horizontal position of the next character.
+         */
+        float x_;
+
+        /**
+         * Vertical position of the current line.
+         */
+        float y_;
+};

+ 121 - 0
src/engine/ui/UiTextParser.cpp

@@ -0,0 +1,121 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <OgreStringConverter.h>
+#include "UiTextParser.h"
+
+const char* const UiTextParser::TIMER_VARIABLE = "UITextAreaTimer";
+
+UiTextParser::UiTextParser(const Sources& sources, std::vector<TextChar>& text):
+  sources_(sources), text_(text), uses_timer_(false)
+{}
+
+void UiTextParser::Parse(TiXmlNode* node, const Ogre::ColourValue& colour){
+    for (; node != nullptr; node = node->NextSibling()){
+        if (node->ToText() != nullptr) AddString(node->ToText()->Value(), colour);
+        else if (node->ToElement() != nullptr){
+            const Ogre::ColourValue content_colour = ParseElement(*node->ToElement(), colour);
+            Parse(node->FirstChild(), content_colour);
+        }
+    }
+}
+
+Ogre::ColourValue UiTextParser::ParseElement(
+  const TiXmlElement& element, const Ogre::ColourValue& colour
+){
+    const std::string& name = element.ValueStr();
+    if (name == "colour"){
+        const char* value = element.Attribute("value");
+        if (value != nullptr) return Ogre::StringConverter::parseColourValue(value);
+    }
+    else if (name == "pause_ok"){
+        TextChar character;
+        character.pause_ok = true;
+        text_.push_back(character);
+    }
+    else if (name == "pause"){
+        const char* time = element.Attribute("time");
+        if (time != nullptr){
+            TextChar character;
+            // The time of the pause is in frames of the game (30 per second), as in the original
+            // game.
+            character.pause_time = Ogre::StringConverter::parseReal(time) / 30.0f;
+            text_.push_back(character);
+        }
+    }
+    else if (name == "next_page"){
+        TextChar character;
+        character.next_page = true;
+        text_.push_back(character);
+    }
+    else if (name == "timer"){
+        uses_timer_ = true;
+        AddVariable(TIMER_VARIABLE, colour);
+    }
+    else if (name == "variable"){
+        const char* variable = element.Attribute("name");
+        if (variable != nullptr) AddVariable(variable, colour);
+    }
+    else if (name == "character"){
+        int id = 0;
+        if (element.QueryIntAttribute("id", &id) == TIXML_SUCCESS)
+            AddName(sources_.character_name(id), colour);
+    }
+    else if (name == "party"){
+        int position = 0;
+        if (element.QueryIntAttribute("pos", &position) == TIXML_SUCCESS)
+            AddName(sources_.party_name(position), colour);
+    }
+    else if (name == "include"){
+        const char* text = element.Attribute("name");
+        if (text != nullptr) Parse(sources_.text(text), colour);
+    }
+    else if (name == "image"){
+        const char* sprite = element.Attribute("sprite");
+        TextChar character;
+        if (sprite != nullptr && *sprite != '\0' && sources_.image(sprite, character))
+            text_.push_back(character);
+    }
+    return colour;
+}
+
+void UiTextParser::AddVariable(const Ogre::String& name, const Ogre::ColourValue& colour){
+    const Ogre::UTFString value = sources_.variable(name);
+    TextChar mark;
+    mark.skip = true;
+    mark.variable = name;
+    mark.variable_len = value.size();
+    mark.colour = colour;
+    text_.push_back(mark);
+    AddString(value, colour);
+}
+
+void UiTextParser::AddName(const std::string& name, const Ogre::ColourValue& colour){
+    for (const char letter : name){
+        TextChar character;
+        character.char_code = letter;
+        character.colour = colour;
+        text_.push_back(character);
+    }
+}
+
+void UiTextParser::AddString(const Ogre::UTFString& string, const Ogre::ColourValue& colour){
+    for (size_t i = 0; i < string.size(); ++ i){
+        TextChar character;
+        character.char_code = string[i];
+        character.colour = colour;
+        text_.push_back(character);
+    }
+}

+ 134 - 0
src/engine/ui/UiTextParser.h

@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <functional>
+#include <string>
+#include <vector>
+#include <Overlay/OgreUTFString.h>
+#include <tinyxml.h>
+#include "UiTextChar.h"
+
+/**
+ * Reads the markup of a text into the list of its characters.
+ *
+ * The elements it knows are: colour (value), pause_ok, pause (time, in frames of the game),
+ * next_page, timer, variable (name), character (id), party (pos), include (name) and image
+ * (sprite). The contents of the elements are read too.
+ */
+class UiTextParser{
+
+    public:
+
+        /**
+         * Name of the variable with the time of the timer.
+         */
+        static const char* const TIMER_VARIABLE;
+
+        /**
+         * What the parser needs to know to expand the elements of a text. All must be set.
+         */
+        struct Sources{
+
+            /**
+             * Retrieves the value of a variable.
+             */
+            std::function<Ogre::UTFString(const Ogre::String&)> variable;
+
+            /**
+             * Retrieves the name of a character, by ID.
+             */
+            std::function<std::string(int)> character_name;
+
+            /**
+             * Retrieves the name of a party member, by position.
+             */
+            std::function<std::string(int)> party_name;
+
+            /**
+             * Retrieves a text to include, by name. Null if there is none.
+             */
+            std::function<TiXmlNode*(const Ogre::String&)> text;
+
+            /**
+             * Creates the sprite of an image, and sets it and its position in the character.
+             * Returns false if there is no such image.
+             */
+            std::function<bool(const Ogre::String&, TextChar&)> image;
+        };
+
+        /**
+         * Constructor.
+         *
+         * @param[in] sources Where the contents of the elements come from.
+         * @param[out] text The characters are added at the end of this list.
+         */
+        UiTextParser(const Sources& sources, std::vector<TextChar>& text);
+
+        /**
+         * Reads a node, its contents and the nodes that follow it.
+         *
+         * @param[in] node The first node. Nothing is read if it's null.
+         * @param[in] colour Colour of the characters.
+         */
+        void Parse(TiXmlNode* node, const Ogre::ColourValue& colour);
+
+        /**
+         * Checks if any of the parsed text shows the timer.
+         */
+        bool UsesTimer() const{return uses_timer_;}
+
+    private:
+
+        /**
+         * Adds the characters of an element, not including its contents.
+         *
+         * @param[in] element The element.
+         * @param[in] colour Colour of the characters.
+         * @return The colour of the contents of the element.
+         */
+        Ogre::ColourValue ParseElement(const TiXmlElement& element, const Ogre::ColourValue& colour);
+
+        /**
+         * Adds a variable: a character that marks where it is, followed by its value.
+         */
+        void AddVariable(const Ogre::String& name, const Ogre::ColourValue& colour);
+
+        /**
+         * Adds the characters of a name.
+         */
+        void AddName(const std::string& name, const Ogre::ColourValue& colour);
+
+        /**
+         * Adds the characters of a string.
+         */
+        void AddString(const Ogre::UTFString& string, const Ogre::ColourValue& colour);
+
+        /**
+         * Where the contents of the elements come from.
+         */
+        const Sources& sources_;
+
+        /**
+         * The list of characters.
+         */
+        std::vector<TextChar>& text_;
+
+        /**
+         * True if any text shows the timer.
+         */
+        bool uses_timer_;
+};

+ 1 - 0
test/engine/ui/CMakeLists.txt

@@ -1,4 +1,5 @@
 # Tests of this folder (see vgears_tests and vgears_installer_tests in test/CMakeLists.txt).
 vgears_tests(
     TextHandler.cpp
+    UiText.cpp
 )

+ 161 - 0
test/engine/ui/UiText.cpp

@@ -0,0 +1,161 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <boost/test/unit_test.hpp>
+#include <tinyxml.h>
+#include "engine/ui/UiTextLayout.h"
+#include "engine/ui/UiTextParser.h"
+
+namespace{
+
+    /**
+     * Sources with fixed names, a variable "money" and an included text "greeting".
+     */
+    struct TestSources{
+        TiXmlDocument included;
+        UiTextParser::Sources sources;
+        TestSources(){
+            // As in the game, where the XML files set it: spaces and line feeds are kept.
+            TiXmlBase::SetCondenseWhiteSpace(false);
+            included.Parse("<text>Hi <colour value=\"1 0 0\">you</colour>!</text>");
+            sources.variable = [](const Ogre::String& name){
+                return Ogre::UTFString(name == "money" ? "150" : "");
+            };
+            sources.character_name = [](int id){return "Name" + std::to_string(id);};
+            sources.party_name = [](int position){return "Party" + std::to_string(position);};
+            sources.text = [this](const Ogre::String& name){
+                return name == "greeting" ? included.RootElement() : nullptr;
+            };
+            sources.image = [](const Ogre::String& name, TextChar& character){
+                character.sprite_y = 7;
+                return name == "circle";
+            };
+        }
+    };
+
+    std::vector<TextChar> Parse(const std::string& markup, bool* timer = nullptr){
+        TestSources test;
+        TiXmlDocument document;
+        document.Parse(("<container>" + markup + "</container>").c_str());
+        std::vector<TextChar> text;
+        UiTextParser parser(test.sources, text);
+        parser.Parse(document.RootElement(), Ogre::ColourValue::White);
+        if (timer != nullptr) *timer = parser.UsesTimer();
+        return text;
+    }
+
+    /**
+     * The visible letters of a text.
+     */
+    std::string Letters(const std::vector<TextChar>& text){
+        std::string letters;
+        for (const TextChar& character : text){
+            if (character.char_code != 0) letters += static_cast<char>(character.char_code);
+        }
+        return letters;
+    }
+
+    UiCharData Glyph(const int code){
+        UiCharData data = {};
+        data.char_code = code;
+        data.width = 8;
+        data.height = 10;
+        data.pre = 1;
+        data.post = 1;
+        return data;
+    }
+}
+
+BOOST_AUTO_TEST_CASE(TestUiTextReadsEveryElement){
+    // All the text is read, not only the first element of each level.
+    const auto text = Parse("HP <colour value=\"1 0 0\">-5</colour> of <include name=\"greeting\" />.");
+    BOOST_CHECK_EQUAL(Letters(text), "HP -5 of Hi you!.");
+    BOOST_CHECK(text[0].colour == Ogre::ColourValue::White);
+    BOOST_CHECK(text[3].colour == Ogre::ColourValue(1, 0, 0));
+    BOOST_CHECK(text[5].colour == Ogre::ColourValue::White);
+}
+
+BOOST_AUTO_TEST_CASE(TestUiTextNamesAndVariables){
+    BOOST_CHECK_EQUAL(Letters(Parse("<character id=\"2\"/>,<party pos=\"1\"/>")), "Name2,Party1");
+    const auto text = Parse("<variable name=\"money\"/>G");
+    BOOST_REQUIRE_EQUAL(text.size(), 5u);
+    BOOST_CHECK(text[0].skip);
+    BOOST_CHECK_EQUAL(text[0].variable, "money");
+    BOOST_CHECK_EQUAL(text[0].variable_len, 3u);
+    BOOST_CHECK_EQUAL(Letters(text), "150G");
+    bool timer = false;
+    BOOST_CHECK_EQUAL(Parse("<timer/>", &timer)[0].variable, UiTextParser::TIMER_VARIABLE);
+    BOOST_CHECK(timer);
+}
+
+BOOST_AUTO_TEST_CASE(TestUiTextCommands){
+    const auto text = Parse("a<pause_ok/><pause time=\"60\"/><next_page/><image sprite=\"circle\"/>");
+    BOOST_REQUIRE_EQUAL(text.size(), 5u);
+    BOOST_CHECK(text[1].pause_ok);
+    BOOST_CHECK_EQUAL(text[2].pause_time, 2.0f);
+    BOOST_CHECK(text[3].next_page);
+    BOOST_CHECK_EQUAL(text[4].sprite_y, 7.0f);
+}
+
+BOOST_AUTO_TEST_CASE(TestUiTextIgnoresIncompleteElements){
+    // These crashed the game.
+    BOOST_CHECK_EQUAL(
+      Letters(Parse(
+        "<colour>a</colour><character/><party pos=\"x\"/><variable/><pause/><include/><image/>b"
+      )), "ab"
+    );
+    BOOST_CHECK(Parse("<include name=\"nothing\"/><image sprite=\"square\"/>").empty());
+}
+
+BOOST_AUTO_TEST_CASE(TestUiTextLayoutWrapsAndStopsAtTheBottom){
+    // An area of 25 x 20 on a screen of the reference height: two letters per line, two lines.
+    const UiTextLayout::Area area{{0, 0}, {25, 20}, {1, 1}, 720, 0, 0, 0, 0};
+    UiTextLayout layout(area, 0, 0, 10);
+    UiTextLayout::Box box;
+    BOOST_REQUIRE(layout.Place(Glyph('a'), box));
+    BOOST_CHECK_EQUAL(box.left, 1);
+    BOOST_CHECK_EQUAL(box.right, 9);
+    BOOST_REQUIRE(layout.Place(Glyph('b'), box));
+    BOOST_CHECK_EQUAL(box.left, 11);
+    BOOST_CHECK_EQUAL(box.top, 0);
+    // The third letter doesn't fit: it goes to the next line. The space before it is not
+    // repeated there.
+    BOOST_REQUIRE(layout.Place(Glyph('c'), box));
+    BOOST_CHECK_EQUAL(box.left, 0);
+    BOOST_CHECK_EQUAL(box.top, 10);
+    layout.NewLine();
+    BOOST_CHECK(!layout.Place(Glyph('d'), box));
+}
+
+BOOST_AUTO_TEST_CASE(TestUiTextLayoutWidthAndVertices){
+    const std::vector<TextChar> text = Parse("ab\nabc");
+    BOOST_CHECK_EQUAL(UiTextLayout::TextWidth(text, Glyph), 30);
+    const auto corners = UiTextLayout::ScreenCorners(
+      {10, 20, 30, 40}, {0, 0}, 0, {100, 100}
+    );
+    BOOST_CHECK_CLOSE(corners[0].x, -0.8f, 0.001f);
+    BOOST_CHECK_CLOSE(corners[0].y, 0.6f, 0.001f);
+    BOOST_CHECK_CLOSE(corners[2].x, -0.4f, 0.001f);
+    std::vector<float> vertices(6 * UiTextLayout::VERTEX_SIZE);
+    float* end = vertices.data();
+    UiTextLayout::WriteQuad(end, corners, {0, 0.25f, 0.5f, 0.75f}, 3, Ogre::ColourValue(1, 0, 0));
+    BOOST_CHECK(end == vertices.data() + vertices.size());
+    // The last vertex is the bottom left one.
+    const float* last = &vertices[5 * UiTextLayout::VERTEX_SIZE];
+    BOOST_CHECK_EQUAL(last[0], corners[3].x);
+    BOOST_CHECK_EQUAL(last[2], 3);
+    BOOST_CHECK_EQUAL(last[7], 0);
+    BOOST_CHECK_EQUAL(last[8], 0.75f);
+}