Browse Source

Split the field background class and fixed the first scroll limits

- The tiles of each blending mode are in a tile buffer, which replaces the three copies of the buffer, material and layer data. The scroll and the shake are in their own classes.
- The backgrounds and the text areas write their vertices with the same code.
- Broke up the adding of tiles and the update of the animations.
- The scroll limits of a field were calculated with the screen proportion before it was calculated.
- Added tests for the vertices, the layers, the shake and the scroll.
Iñigo Valentin 4 days ago
parent
commit
73ed05b90c

+ 150 - 632
src/engine/graphics/Background2D.cpp

@@ -13,12 +13,9 @@
  * GNU General Public License for more details.
  * GNU General Public License for more details.
  */
  */
 
 
-#include <OgreHardwareBufferManager.h>
 #include <OgreLogManager.h>
 #include <OgreLogManager.h>
-#include <OgreMaterialManager.h>
 #include <OgreException.h>
 #include <OgreException.h>
 #include <OgreViewport.h>
 #include <OgreViewport.h>
-#include <OgreTechnique.h>
 #include <OgreTextureManager.h>
 #include <OgreTextureManager.h>
 #include <OgreHardwarePixelBuffer.h>
 #include <OgreHardwarePixelBuffer.h>
 #include <algorithm>
 #include <algorithm>
@@ -35,85 +32,27 @@ ConfigVar cv_show_background2d("show_background2d", "Draw background", "true");
 ConfigVar cv_background2d_manual("background2d_manual", "Manual 2d background scrolling", "false");
 ConfigVar cv_background2d_manual("background2d_manual", "Manual 2d background scrolling", "false");
 
 
 Background2D::Background2D():
 Background2D::Background2D():
-  alpha_max_vertex_count_(0),
-  add_max_vertex_count_(0),
-  subtract_max_vertex_count_(0),
-  scroll_entity_(nullptr),
-  scroll_position_start_(Ogre::Vector2::ZERO),
-  scroll_position_end_(Ogre::Vector2::ZERO),
-  scroll_type_(Background2D::NONE),
-  scroll_seconds_(0),
-  scroll_current_seconds_(0),
-  scroll_target_entity_(nullptr),
-  scroll_follow_target_(false),
-  free_scroll_(false),
-  position_(Ogre::Vector2::ZERO),
-  position_real_(Ogre::Vector2::ZERO),
+  alpha_tiles_(VGears::B_ALPHA, "Background2DAlpha", MAX_TILES),
+  add_tiles_(VGears::B_ADD, "Background2DAdd", MAX_TILES),
+  subtract_tiles_(VGears::B_SUBTRACT, "Background2DSubtract", MAX_SUBTRACT_TILES),
+  scroll_([](const ScriptId& script){
+      ScriptManager::getSingleton().ContinueScriptExecution(script);
+  }),
   offset_(Ogre::Vector2::ZERO),
   offset_(Ogre::Vector2::ZERO),
-  range_(Ogre::AxisAlignedBox::BOX_INFINITE),
+  position_real_(Ogre::Vector2::ZERO),
+  screen_scale_(1),
+  screen_proportion_(1, 1),
   virtual_screen_size_(320, 240) // FFVII original resolution
   virtual_screen_size_(320, 240) // FFVII original resolution
 {
 {
     scene_manager_ = Ogre::Root::getSingleton().getSceneManager("Scene");
     scene_manager_ = Ogre::Root::getSingleton().getSceneManager("Scene");
     render_system_ = Ogre::Root::getSingletonPtr()->getRenderSystem();
     render_system_ = Ogre::Root::getSingletonPtr()->getRenderSystem();
-    CreateVertexBuffers();
-    alpha_material_ = Ogre::MaterialManager::getSingleton().create("Background2DAlpha", "FIELDS");
-    Ogre::Pass* pass = alpha_material_->getTechnique(0)->getPass(0);
-    pass->setVertexColourTracking(Ogre::TVC_AMBIENT);
-    pass->setCullingMode(Ogre::CULL_NONE);
-    pass->setDepthCheckEnabled(true);
-    pass->setDepthWriteEnabled(true);
-    pass->setLightingEnabled(false);
-    pass->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
-    pass->setAlphaRejectFunction(Ogre::CMPF_GREATER);
-    pass->setAlphaRejectValue(0);
-    Ogre::TextureUnitState* tex = pass->createTextureUnitState();
-    tex->setTextureName("system/blank.png");
-    tex->setNumMipmaps(-1);
-    tex->setTextureFiltering(Ogre::TFO_NONE);
-    add_material = Ogre::MaterialManager::getSingleton().create("Background2DAdd", "FIELDS");
-    pass = add_material->getTechnique(0)->getPass(0);
-    pass->setVertexColourTracking(Ogre::TVC_AMBIENT);
-    pass->setCullingMode(Ogre::CULL_NONE);
-    pass->setDepthCheckEnabled(true);
-    pass->setDepthWriteEnabled(true);
-    pass->setLightingEnabled(false);
-    // Additive tiles blend with what is behind. They don't write depth, or a tile in front (such as
-    // the light beams, at depth 0) would hide the additive tiles behind it, like the waterfall of
-    // eals_1.
-    pass->setDepthWriteEnabled(false);
-    pass->setSceneBlending(Ogre::SBT_ADD);
-    pass->setAlphaRejectFunction(Ogre::CMPF_GREATER);
-    pass->setAlphaRejectValue(0);
-    tex = pass->createTextureUnitState();
-    tex->setTextureName("system/blank.png");
-    tex->setNumMipmaps(-1);
-    tex->setTextureFiltering(Ogre::TFO_NONE);
-    subtract_material_ = Ogre::MaterialManager::getSingleton().create(
-      "Background2DSubtract", "FIELDS"
-    );
-    pass = subtract_material_->getTechnique(0)->getPass(0);
-    pass->setVertexColourTracking(Ogre::TVC_AMBIENT);
-    pass->setCullingMode(Ogre::CULL_NONE);
-    pass->setDepthCheckEnabled(true);
-    pass->setDepthWriteEnabled(true);
-    pass->setLightingEnabled(false);
-    pass->setSceneBlending(Ogre::SBT_ADD);
-    // Like the additive tiles, they don't write depth.
-    pass->setDepthWriteEnabled(false);
-    pass->setSceneBlendingOperation(Ogre::SBO_SUBTRACT);
-    pass->setAlphaRejectFunction(Ogre::CMPF_LESS);
-    pass->setAlphaRejectValue(0);
-    tex = pass->createTextureUnitState();
-    tex->setTextureName("system/blank.png");
-    tex->setNumMipmaps(-1);
-    tex->setTextureFiltering(Ogre::TFO_NONE);
+    ResetLayers();
     scene_manager_->addRenderQueueListener(this);
     scene_manager_->addRenderQueueListener(this);
 }
 }
 
 
 Background2D::~Background2D(){
 Background2D::~Background2D(){
     scene_manager_->removeRenderQueueListener(this);
     scene_manager_->removeRenderQueueListener(this);
     for (unsigned int i = 0; i < animations_.size(); ++ i) delete animations_[i];
     for (unsigned int i = 0; i < animations_.size(); ++ i) delete animations_[i];
-    DestroyVertexBuffers();
 }
 }
 
 
 void Background2D::InputDebug(const VGears::Event& event){
 void Background2D::InputDebug(const VGears::Event& event){
@@ -131,53 +70,47 @@ void Background2D::Hide(){scene_manager_->removeRenderQueueListener(this);}
 void Background2D::Show(){scene_manager_->addRenderQueueListener(this);}
 void Background2D::Show(){scene_manager_->addRenderQueueListener(this);}
 
 
 void Background2D::Update(){
 void Background2D::Update(){
-    if (has_pending_scroll_){
-        has_pending_scroll_ = false;
-        SetScroll(pending_scroll_);
-    }
+    if (scroll_.ApplyPending()) applyScroll();
     UpdatePalette();
     UpdatePalette();
-    UpdateShake(Timer::getSingleton().GetGameTimeDelta());
+    const float delta = Timer::getSingleton().GetGameTimeDelta();
+    UpdateShake(delta);
     // The layers that scroll by themselves.
     // The layers that scroll by themselves.
     for (int layer = 0; layer < LAYER_COUNT; ++ layer){
     for (int layer = 0; layer < LAYER_COUNT; ++ layer){
-        layer_scroll_offset_[layer][0] += layer_scroll_speed_[layer][0] * Timer::getSingleton().GetGameTimeDelta();
-        layer_scroll_offset_[layer][1] += layer_scroll_speed_[layer][1] * Timer::getSingleton().GetGameTimeDelta();
-    }
-    for (unsigned int i = 0; i < animation_played_.size(); ++ i){
-        for (unsigned int j = 0; j < animations_.size(); ++ j){
-            if (animations_[j]->GetName() == animation_played_[i].name){
-                float delta_time = Timer::getSingleton().GetGameTimeDelta();
-                float time = animations_[j]->GetTime();
-                float end_time = animations_[j]->GetLength();
-
-                // If animation ended
-                if (time + delta_time >= end_time){
-                    // Set to last frame of animation.
-                    if (time != end_time) animations_[j]->SetTime(end_time);
-
-                    if (animation_played_[i].state == Background2DAnimation::ONCE){
-                        for (unsigned int k = 0; k < animation_played_[i].sync.size(); ++k){
-                            ScriptManager::getSingleton().ContinueScriptExecution(
-                              animation_played_[i].sync[k]
-                            );
-                        }
-                        animation_played_[i].sync.clear();
-                        // Mark to delete this way:
-                        animation_played_[i].name = "";
-                    }
-                    // In case of looped, sync with end:
-                    else animations_[j]->SetTime(time + delta_time - end_time);
+        layer_scroll_offset_[layer][0] += layer_scroll_speed_[layer][0] * delta;
+        layer_scroll_offset_[layer][1] += layer_scroll_speed_[layer][1] * delta;
+    }
+    UpdateAnimations(delta);
+}
+
+void Background2D::UpdateAnimations(const float delta){
+    for (AnimationPlayed& played : animation_played_){
+        for (Background2DAnimation* animation : animations_){
+            if (animation->GetName() != played.name) continue;
+            const float time = animation->GetTime();
+            const float end_time = animation->GetLength();
+            if (time + delta < end_time) animation->AddTime(delta);
+            else{
+                // Set to last frame of animation.
+                if (time != end_time) animation->SetTime(end_time);
+                if (played.state == Background2DAnimation::ONCE){
+                    for (const ScriptId& script : played.sync)
+                        ScriptManager::getSingleton().ContinueScriptExecution(script);
+                    played.sync.clear();
+                    // Mark to delete this way:
+                    played.name = "";
                 }
                 }
-                else animations_[j]->AddTime(delta_time);
+                // In case of looped, sync with end:
+                else animation->SetTime(time + delta - end_time);
             }
             }
         }
         }
     }
     }
-
     // Remove stopped animations.
     // Remove stopped animations.
-    std::vector<AnimationPlayed>::iterator i = animation_played_.begin();
-    for(; i != animation_played_.end();){
-        if ((*i).name == "") i = animation_played_.erase(i);
-        else ++ i;
-    }
+    animation_played_.erase(
+      std::remove_if(
+        animation_played_.begin(), animation_played_.end(),
+        [](const AnimationPlayed& played){return played.name == "";}
+      ), animation_played_.end()
+    );
 }
 }
 
 
 void Background2D::UpdateDebug(){
 void Background2D::UpdateDebug(){
@@ -215,52 +148,29 @@ void Background2D::OnResize(){
 }
 }
 
 
 void Background2D::WriteTilePosition(const Tile& tile){
 void Background2D::WriteTilePosition(const Tile& tile){
-    Ogre::Vector2 top_left(static_cast<Ogre::Real>(tile.x), static_cast<Ogre::Real>(- tile.y));
-    Ogre::Vector2 top_right(
-      static_cast<Ogre::Real>(tile.x + tile.width), static_cast<Ogre::Real>(top_left.y)
-    );
-    Ogre::Vector2 bottom_right(
-      static_cast<Ogre::Real>(top_right.x), static_cast<Ogre::Real>(-(tile.y + tile.height))
-    );
-    Ogre::Vector2 bottom_left(
-      static_cast<Ogre::Real>(top_left.x), static_cast<Ogre::Real>(bottom_right.y)
-    );
-    virtualScreenToWorldSpace(top_left);
-    virtualScreenToWorldSpace(top_right);
-    virtualScreenToWorldSpace(bottom_right);
-    virtualScreenToWorldSpace(bottom_left);
+    BackgroundTileBuffer* buffer = BufferFor(tile.blending);
+    if (buffer == nullptr) return;
+    QuadWriter::Corners corners = TileCorners(tile);
     // A tile that is not drawn has all its corners in the same point.
     // A tile that is not drawn has all its corners in the same point.
-    if (!tile.visible){
-        top_right = top_left;
-        bottom_right = top_left;
-        bottom_left = top_left;
-    }
-    Ogre::HardwareVertexBufferSharedPtr vertex_buffer;
-    if (tile.blending == VGears::B_ALPHA) vertex_buffer = alpha_vertex_buffer_;
-    else if (tile.blending == VGears::B_ADD) vertex_buffer = add_vertex_buffer_;
-    else if (tile.blending == VGears::B_SUBTRACT) vertex_buffer = subtract_vertex_buffer_;
-    else return;
-    float* write_iterator
-      = static_cast<float*>(vertex_buffer->lock(Ogre::HardwareBuffer::HBL_NORMAL));
-    write_iterator += tile.start_vertex_index * TILE_VERTEX_INDEX_SIZE;
-    *write_iterator ++ = top_left.x;
-    *write_iterator ++ = top_left.y;
-    write_iterator += 7;
-    *write_iterator ++ = top_right.x;
-    *write_iterator ++ = top_right.y;
-    write_iterator += 7;
-    *write_iterator ++ = bottom_right.x;
-    *write_iterator ++ = bottom_right.y;
-    write_iterator += 7;
-    *write_iterator ++ = top_left.x;
-    *write_iterator ++ = top_left.y;
-    write_iterator += 7;
-    *write_iterator ++ = bottom_right.x;
-    *write_iterator ++ = bottom_right.y;
-    write_iterator += 7;
-    *write_iterator ++ = bottom_left.x;
-    *write_iterator ++ = bottom_left.y;
-    vertex_buffer->unlock();
+    if (!tile.visible) corners.fill(corners[0]);
+    buffer->SetPositions(tile.start_vertex_index, corners);
+}
+
+QuadWriter::Corners Background2D::TileCorners(const Tile& tile) const{
+    const Ogre::Real left = static_cast<Ogre::Real>(tile.x);
+    const Ogre::Real top = static_cast<Ogre::Real>(-tile.y);
+    const Ogre::Real right = static_cast<Ogre::Real>(tile.x + tile.width);
+    const Ogre::Real bottom = static_cast<Ogre::Real>(-(tile.y + tile.height));
+    QuadWriter::Corners corners{{{left, top}, {right, top}, {right, bottom}, {left, bottom}}};
+    for (Ogre::Vector2& corner : corners) virtualScreenToWorldSpace(corner);
+    return corners;
+}
+
+BackgroundTileBuffer* Background2D::BufferFor(const Blending blending){
+    if (blending == VGears::B_ALPHA) return &alpha_tiles_;
+    if (blending == VGears::B_ADD) return &add_tiles_;
+    if (blending == VGears::B_SUBTRACT) return &subtract_tiles_;
+    return nullptr;
 }
 }
 
 
 bool Background2D::IsAreaStateOn(const int area, const int layers) const{
 bool Background2D::IsAreaStateOn(const int area, const int layers) const{
@@ -303,81 +213,10 @@ void Background2D::ScriptAreaOff(const int area, const int layer){
     RefreshArea(area);
     RefreshArea(area);
 }
 }
 
 
-namespace{
-    // Random factors the original game applies to each bounce of a shake.
-    const float SHAKE_FACTORS[] = {
-      -1.0f, 1.14f, -1.34f, 0.61f, -0.49f, 0.64f, -0.25f, 0.47f, -1.20f, -0.01f, 1.14f, -0.86f,
-      0.81f, -0.58f, 0.68f, -1.31f, 0.44f, -0.91f, 0.03f, -0.97f, 1.25f, -0.76f, 0.48f, -0.99f,
-      1.34f, -0.85f, 0.55f, -0.65f, 0.07f, -0.83f
-    };
-    const size_t SHAKE_FACTOR_COUNT = sizeof(SHAKE_FACTORS) / sizeof(SHAKE_FACTORS[0]);
-
-    // Frames per second the shake times are given in.
-    const float SHAKE_FRAMES_PER_SECOND = 30.0f;
-
-    // Pixels of the original screen.
-    const float ORIGINAL_SCREEN_WIDTH = 320.0f;
-
-    // Quadratic in and out easing.
-    float ShakeEase(const float t){return t < 0.5f ? 2 * t * t : 1 - 2 * (1 - t) * (1 - t);}
-}
-
-void Background2D::ShakeAxis::Configure(const float new_amplitude, const float new_seconds){
-    amplitude = new_amplitude;
-    seconds = std::max(new_seconds, 1.0f / SHAKE_FRAMES_PER_SECOND);
-    stopping = false;
-    if (!running){
-        running = true;
-        StartBounce();
-    }
-}
-
-void Background2D::ShakeAxis::Stop(const float seconds_to_center){
-    if (!running) return;
-    stopping = true;
-    stop_seconds = std::max(seconds_to_center, 1.0f / SHAKE_FRAMES_PER_SECOND);
-}
-
-void Background2D::ShakeAxis::StartBounce(){
-    from = value;
-    elapsed = 0;
-    if (stopping){
-        to = 0;
-        duration = stop_seconds;
-    }
-    else{
-        // Half the amplitude, times the random factor, is the distance in pixels.
-        to = amplitude / 2 * SHAKE_FACTORS[step % SHAKE_FACTOR_COUNT];
-        ++ step;
-        duration = seconds;
-    }
-}
-
-bool Background2D::ShakeAxis::Advance(const float delta){
-    if (!running) return false;
-    const float old_value = value;
-    elapsed += delta;
-    while (elapsed >= duration){
-        elapsed -= duration;
-        value = to;
-        if (stopping && to == 0){
-            // Back in the center: the shake is over.
-            *this = ShakeAxis();
-            return old_value != 0;
-        }
-        StartBounce();
-    }
-    value = from + (to - from) * ShakeEase(elapsed / duration);
-    return value != old_value;
-}
-
 void Background2D::UpdateShake(const float delta){
 void Background2D::UpdateShake(const float delta){
-    if (!shake_x_.running && !shake_y_.running) return;
-    const bool x_changed = shake_x_.Advance(delta);
-    const bool y_changed = shake_y_.Advance(delta);
-    if (!x_changed && !y_changed) return;
-    const float scale = virtual_screen_size_.x / ORIGINAL_SCREEN_WIDTH;
-    shake_offset_ = Ogre::Vector2(shake_x_.value * scale, shake_y_.value * scale);
+    if (!shake_.Update(delta)) return;
+    // The shake is in pixels of the original screen.
+    shake_offset_ = shake_.Offset() * (virtual_screen_size_.x / 320.0f);
     applyScroll();
     applyScroll();
 }
 }
 
 
@@ -386,24 +225,8 @@ void Background2D::ScriptShake(
   const int y_frames
   const int y_frames
 ){
 ){
     LOG_TRIVIAL("Background2d shake type " + std::to_string(type) + ".");
     LOG_TRIVIAL("Background2d shake type " + std::to_string(type) + ".");
-    const float x_seconds = x_frames / SHAKE_FRAMES_PER_SECOND;
-    const float y_seconds = y_frames / SHAKE_FRAMES_PER_SECOND;
-    switch (type){
-        case 0:
-            {
-                const float seconds = std::max(x_seconds, y_seconds);
-                shake_x_.Stop(seconds);
-                shake_y_.Stop(seconds);
-            }
-            break;
-        case 1: shake_x_.Configure(static_cast<float>(x_amplitude), x_seconds); break;
-        case 2: shake_y_.Configure(static_cast<float>(y_amplitude), y_seconds); break;
-        case 3:
-            shake_x_.Configure(static_cast<float>(x_amplitude), x_seconds);
-            shake_y_.Configure(static_cast<float>(y_amplitude), y_seconds);
-            break;
-        default: LOG_WARNING("Background2d shake type " + std::to_string(type) + " is unknown.");
-    }
+    if (!shake_.Set(type, x_amplitude, x_frames, y_amplitude, y_frames))
+        LOG_WARNING("Background2d shake type " + std::to_string(type) + " is unknown.");
 }
 }
 
 
 void Background2D::ScriptAreaClear(const int area){
 void Background2D::ScriptAreaClear(const int area){
@@ -471,57 +294,41 @@ void Background2D::UpdatePalette(){
 }
 }
 
 
 void Background2D::Clear(){
 void Background2D::Clear(){
-    scroll_entity_ = nullptr;
-    scroll_position_start_ = Ogre::Vector2::ZERO;
-    scroll_position_end_ = Ogre::Vector2::ZERO;
-    scroll_seconds_ = 0;
-    scroll_current_seconds_ = 0;
-    scroll_target_entity_ = nullptr;
-    scroll_follow_target_ = false;
-    free_scroll_ = false;
-    has_pending_scroll_ = false;
-    position_ = Ogre::Vector2::ZERO;
+    scroll_.Clear();
     position_real_ = Ogre::Vector2::ZERO;
     position_real_ = Ogre::Vector2::ZERO;
     offset_ = Ogre::Vector2::ZERO;
     offset_ = Ogre::Vector2::ZERO;
-    range_ = Ogre::AxisAlignedBox::BOX_INFINITE;
-    UnsetScroll();
-    for(unsigned int i = 0; i < animations_.size(); ++i) delete animations_[i];
+    for (Background2DAnimation* animation : animations_) delete animation;
     animations_.clear();
     animations_.clear();
-    for(unsigned int i = 0; i < animation_played_.size(); ++ i)
-        for(unsigned int j = 0; j < animation_played_[i].sync.size(); ++j)
-            ScriptManager::getSingleton().ContinueScriptExecution(animation_played_[i].sync[j]);
+    for (const AnimationPlayed& played : animation_played_){
+        for (const ScriptId& script : played.sync)
+            ScriptManager::getSingleton().ContinueScriptExecution(script);
+    }
     animation_played_.clear();
     animation_played_.clear();
     tiles_.clear();
     tiles_.clear();
     area_states_on_.clear();
     area_states_on_.clear();
     palette_.Clear();
     palette_.Clear();
     palette_image_loaded_ = false;
     palette_image_loaded_ = false;
-    shake_x_ = ShakeAxis();
-    shake_y_ = ShakeAxis();
+    shake_ = BackgroundShake();
     shake_offset_ = Ogre::Vector2::ZERO;
     shake_offset_ = Ogre::Vector2::ZERO;
-    DestroyVertexBuffers();
-    CreateVertexBuffers();
+    alpha_tiles_.Clear();
+    add_tiles_.Clear();
+    subtract_tiles_.Clear();
+    ResetLayers();
 }
 }
 
 
-void Background2D::ScriptAutoScrollToEntity(Entity* entity){
-    scroll_entity_ = entity;
-    free_scroll_ = false;
-}
+void Background2D::ScriptAutoScrollToEntity(Entity* entity){scroll_.Follow(entity);}
 
 
-Entity* Background2D::GetAutoScrollEntity() const{return scroll_entity_;}
+Entity* Background2D::GetAutoScrollEntity() const{return scroll_.FollowedEntity();}
 
 
-bool Background2D::HasScrollControl() const{
-    return scroll_entity_ != nullptr || scroll_target_entity_ != nullptr || free_scroll_
-      || has_pending_scroll_;
-}
+bool Background2D::HasScrollControl() const{return scroll_.HasControl();}
 
 
 void Background2D::ScriptScrollToPlayer(const SCROLL_TYPE type, const float seconds){
 void Background2D::ScriptScrollToPlayer(const SCROLL_TYPE type, const float seconds){
     Entity* player = EntityManager::getSingleton().ScriptGetPlayerEntity();
     Entity* player = EntityManager::getSingleton().ScriptGetPlayerEntity();
     if (player == nullptr) return;
     if (player == nullptr) return;
-    scroll_entity_ = nullptr;
     // The camera follows the player when the scroll ends, whatever the transition: scenes end with
     // The camera follows the player when the scroll ends, whatever the transition: scenes end with
     // SCRLC (scroll to the player) and give the control back without any other camera opcode, as
     // SCRLC (scroll to the player) and give the control back without any other camera opcode, as
     // the first visit of mrkt2 does.
     // the first visit of mrkt2 does.
-    StartScroll(GetEntityScroll(player), type, seconds, player, true);
+    if (scroll_.ToEntity(player, GetEntityScroll(player), type, seconds)) applyScroll();
 }
 }
 
 
 void Background2D::ScriptScrollToEntity(
 void Background2D::ScriptScrollToEntity(
@@ -531,13 +338,12 @@ void Background2D::ScriptScrollToEntity(
         LOG_WARNING("Background2d can't scroll to an entity that doesn't exist.");
         LOG_WARNING("Background2d can't scroll to an entity that doesn't exist.");
         return;
         return;
     }
     }
-    scroll_entity_ = nullptr;
-    StartScroll(GetEntityScroll(entity), type, seconds, entity, true);
+    if (scroll_.ToEntity(entity, GetEntityScroll(entity), type, seconds)) applyScroll();
 }
 }
 
 
 void Background2D::UpdateScrollTarget(){
 void Background2D::UpdateScrollTarget(){
-    if (scroll_target_entity_ != nullptr)
-        scroll_position_end_ = ClampToRange(GetEntityScroll(scroll_target_entity_));
+    if (scroll_.TargetEntity() != nullptr)
+        scroll_.SetTargetPosition(GetEntityScroll(scroll_.TargetEntity()));
 }
 }
 
 
 const Ogre::Vector2 Background2D::GetEntityScroll(const Entity* entity) const{
 const Ogre::Vector2 Background2D::GetEntityScroll(const Entity* entity) const{
@@ -552,32 +358,6 @@ const Ogre::Vector2 Background2D::GetEntityScroll(const Entity* entity) const{
     ) / screen_scale_;
     ) / screen_scale_;
 }
 }
 
 
-void Background2D::StartScroll(
-  const Ogre::Vector2& position, const SCROLL_TYPE type, const float seconds,
-  Entity* target_entity, const bool follow_target
-){
-    // A newer scroll replaces an instant one that has not been applied yet.
-    has_pending_scroll_ = false;
-    // Finish the previous scroll first, without following its target.
-    scroll_target_entity_ = nullptr;
-    scroll_follow_target_ = false;
-    UnsetScroll();
-    scroll_target_entity_ = target_entity;
-    scroll_follow_target_ = follow_target;
-    if (type == Background2D::NONE || seconds <= 0){
-        // The camera that goes to an entity is limited to the background.
-        if (target_entity != nullptr) free_scroll_ = false;
-        SetScroll(position);
-        UnsetScroll();
-        return;
-    }
-    scroll_position_start_ = position_;
-    scroll_position_end_ = (target_entity != nullptr) ? ClampToRange(position) : ClampScroll(position);
-    scroll_type_ = type;
-    scroll_seconds_ = seconds;
-    scroll_current_seconds_ = 0;
-}
-
 void Background2D::ScriptScrollToPosition(
 void Background2D::ScriptScrollToPosition(
   const float x, const float y, const SCROLL_TYPE type, const float seconds
   const float x, const float y, const SCROLL_TYPE type, const float seconds
 ){
 ){
@@ -585,34 +365,18 @@ void Background2D::ScriptScrollToPosition(
       "Background2d set scroll to position '"
       "Background2d set scroll to position '"
       + Ogre::StringConverter::toString(Ogre::Vector2(x, y)) + "'."
       + Ogre::StringConverter::toString(Ogre::Vector2(x, y)) + "'."
     );
     );
-    scroll_entity_ = nullptr;
-    free_scroll_ = true;
-    if (type == Background2D::NONE || seconds <= 0){
-        // The scripts set a position and then scroll from it to another one, in the same frame.
-        // The camera is only moved at the end of the frame, so if another scroll comes first the
-        // movement starts from where the camera was, and there is no jump.
-        // TODO: Some scenes still show a small camera jump (mds7pb_1, when the NPCs go down the
-        // pinball machine and when Marlene says "Papa"), and the camera stays fixed after them
-        // until the script scrolls to the player. How the original game handles it is not known.
-        scroll_target_entity_ = nullptr;
-        scroll_follow_target_ = false;
-        UnsetScroll();
-        pending_scroll_ = Ogre::Vector2(x, y);
-        has_pending_scroll_ = true;
-        return;
-    }
-    StartScroll(Ogre::Vector2(x, y), type, seconds, nullptr, false);
+    scroll_.ToPosition(Ogre::Vector2(x, y), type, seconds);
 }
 }
 
 
 int Background2D::ScriptScrollSync(){
 int Background2D::ScriptScrollSync(){
     // Nothing would ever wake the script up if there is no scroll to wait for.
     // Nothing would ever wake the script up if there is no scroll to wait for.
-    if (scroll_type_ == Background2D::NONE) return 1;
+    if (scroll_.Type() == NONE) return 1;
     ScriptId script = ScriptManager::getSingleton().GetCurrentScriptId();
     ScriptId script = ScriptManager::getSingleton().GetCurrentScriptId();
     LOG_TRIVIAL(
     LOG_TRIVIAL(
       "Wait Background2d scroll for function '"
       "Wait Background2d scroll for function '"
       + script.function + "' in script entity '" + script.entity + "'."
       + script.function + "' in script entity '" + script.entity + "'."
     );
     );
-    scroll_sync_.push_back(script);
+    scroll_.Wait(script);
     return -1;
     return -1;
 }
 }
 
 
@@ -627,54 +391,27 @@ void Background2D::ScriptOffset(const float x, const float y){
     CameraManager::getSingleton().Set2DScroll(position_real_);
     CameraManager::getSingleton().Set2DScroll(position_real_);
 }
 }
 
 
-void Background2D::UnsetScroll(){
-    scroll_type_ = Background2D::NONE;
-    if (scroll_follow_target_){
-        scroll_entity_ = scroll_target_entity_;
-        free_scroll_ = false;
-    }
-    scroll_target_entity_ = nullptr;
-    scroll_follow_target_ = false;
-    for(unsigned int i = 0; i < scroll_sync_.size(); ++ i)
-        ScriptManager::getSingleton().ContinueScriptExecution(scroll_sync_[i]);
-    scroll_sync_.clear();
-}
+void Background2D::UnsetScroll(){scroll_.Stop();}
 
 
-const Ogre::Vector2& Background2D::GetScrollPositionStart() const{return scroll_position_start_;}
+const Ogre::Vector2& Background2D::GetScrollPositionStart() const{return scroll_.Start();}
 
 
-const Ogre::Vector2& Background2D::GetScrollPositionEnd() const{return scroll_position_end_;}
+const Ogre::Vector2& Background2D::GetScrollPositionEnd() const{return scroll_.End();}
 
 
-Background2D::SCROLL_TYPE Background2D::GetScrollType() const{return scroll_type_;}
+Background2D::SCROLL_TYPE Background2D::GetScrollType() const{return scroll_.Type();}
 
 
-float Background2D::GetScrollSeconds() const{return scroll_seconds_;}
+float Background2D::GetScrollSeconds() const{return scroll_.Seconds();}
 
 
-void Background2D::SetScrollCurrentSeconds(const float seconds){scroll_current_seconds_ = seconds;}
+void Background2D::SetScrollCurrentSeconds(const float seconds){
+    scroll_.SetCurrentSeconds(seconds);
+}
 
 
-float Background2D::GetScrollCurrentSeconds() const{return scroll_current_seconds_;}
+float Background2D::GetScrollCurrentSeconds() const{return scroll_.CurrentSeconds();}
 
 
 void Background2D::SetScroll(const Ogre::Vector2& position){
 void Background2D::SetScroll(const Ogre::Vector2& position){
-    position_ = ClampScroll(position);
+    scroll_.SetPosition(position);
     applyScroll();
     applyScroll();
 }
 }
 
 
-const Ogre::Vector2 Background2D::ClampScroll(const Ogre::Vector2& position) const{
-    return free_scroll_ ? position : ClampToRange(position);
-}
-
-const Ogre::Vector2 Background2D::ClampToRange(const Ogre::Vector2& position) const{
-    Ogre::Vector2 clamped = position;
-    Ogre::Vector3 pos_3d(position.x, position.y, 0);
-    if (!range_.contains(pos_3d)){
-        Ogre::Vector3 max_3d(range_.getMaximum());
-        Ogre::Vector3 min_3d(range_.getMinimum());
-        Ogre::Vector2 max(max_3d.x, max_3d.y);
-        Ogre::Vector2 min(min_3d.x, min_3d.y);
-        clamped.makeCeil(min);
-        clamped.makeFloor(max);
-    }
-    return clamped;
-}
-
 void Background2D::applyScroll(){
 void Background2D::applyScroll(){
     if(cv_background2d_manual.GetB() != true){
     if(cv_background2d_manual.GetB() != true){
         position_real_ = (GetScroll() + shake_offset_) * screen_scale_;
         position_real_ = (GetScroll() + shake_offset_) * screen_scale_;
@@ -684,7 +421,7 @@ void Background2D::applyScroll(){
     }
     }
 }
 }
 
 
-const Ogre::Vector2& Background2D::GetScroll() const{return position_;}
+const Ogre::Vector2& Background2D::GetScroll() const{return scroll_.Position();}
 
 
 const Ogre::Vector2 Background2D::GetScreenScroll() const{return GetScroll() * screen_scale_;}
 const Ogre::Vector2 Background2D::GetScreenScroll() const{return GetScroll() * screen_scale_;}
 
 
@@ -692,15 +429,9 @@ void Background2D::SetImage(const Ogre::String& image){
     Ogre::LogManager::getSingleton().stream() << "Background2D::SetImage " << image;
     Ogre::LogManager::getSingleton().stream() << "Background2D::SetImage " << image;
     image_name_ = image;
     image_name_ = image;
     palette_image_loaded_ = false;
     palette_image_loaded_ = false;
-    Ogre::Pass* pass = alpha_material_->getTechnique(0)->getPass(0);
-    Ogre::TextureUnitState* tex = pass->getTextureUnitState(0);
-    tex->setTextureName(image);
-    pass = add_material->getTechnique(0)->getPass(0);
-    tex = pass->getTextureUnitState(0);
-    tex->setTextureName(image);
-    pass = subtract_material_->getTechnique(0)->getPass(0);
-    tex = pass->getTextureUnitState(0);
-    tex->setTextureName(image);
+    alpha_tiles_.SetImage(image);
+    add_tiles_.SetImage(image);
+    subtract_tiles_.SetImage(image);
 }
 }
 
 
 void Background2D::SetRange(const Ogre::Vector4& range){
 void Background2D::SetRange(const Ogre::Vector4& range){
@@ -710,20 +441,23 @@ void Background2D::SetRange(const Ogre::Vector4& range){
 void Background2D::SetRange(const int min_x, const int min_y, const int max_x, const int max_y){
 void Background2D::SetRange(const int min_x, const int min_y, const int max_x, const int max_y){
     Ogre::LogManager::getSingleton().stream()
     Ogre::LogManager::getSingleton().stream()
       << "Background2D::SetRange " << min_x << " " << min_y << " " << max_x << " " << max_y;
       << "Background2D::SetRange " << min_x << " " << min_y << " " << max_x << " " << max_y;
+    // The proportion of the screen is needed for the limits.
+    calculateScreenScale();
     Ogre::Vector2 half_virtual_screen_size(virtual_screen_size_ / 2);
     Ogre::Vector2 half_virtual_screen_size(virtual_screen_size_ / 2);
     half_virtual_screen_size /= screen_proportion_;
     half_virtual_screen_size /= screen_proportion_;
     // The scroll is the opposite of the position of the center of the camera (the scripts give it
     // The scroll is the opposite of the position of the center of the camera (the scripts give it
     // like that, and the scene is moved, not the camera), so the limits of the camera are the
     // like that, and the scene is moved, not the camera), so the limits of the camera are the
     // opposite ones. It only shows in the fields whose range is not centered (nivl_b1): the
     // opposite ones. It only shows in the fields whose range is not centered (nivl_b1): the
     // camera went beyond the background.
     // camera went beyond the background.
-    range_.setMaximum(
+    Ogre::AxisAlignedBox range;
+    range.setMaximum(
       -(min_x + half_virtual_screen_size.x), -(min_y + half_virtual_screen_size.y), 1
       -(min_x + half_virtual_screen_size.x), -(min_y + half_virtual_screen_size.y), 1
     );
     );
-    range_.setMinimum(
+    range.setMinimum(
       -(max_x - half_virtual_screen_size.x), -(max_y - half_virtual_screen_size.y), 0
       -(max_x - half_virtual_screen_size.x), -(max_y - half_virtual_screen_size.y), 0
     );
     );
-    Ogre::LogManager::getSingleton().stream() << "Background2D::SetRange " << range_;
-    calculateScreenScale();
+    scroll_.SetRange(range);
+    Ogre::LogManager::getSingleton().stream() << "Background2D::SetRange " << range;
 }
 }
 
 
 float Background2D::TileDepthToBuffer(const float depth, const Ogre::Matrix4& projection){
 float Background2D::TileDepthToBuffer(const float depth, const Ogre::Matrix4& projection){
@@ -791,140 +525,33 @@ void Background2D::AddTile(
   const float v1, const float u2, const float v2, const Blending blending, const int area,
   const float v1, const float u2, const float v2, const Blending blending, const int area,
   const int state, const int layer, const float intensity
   const int state, const int layer, const float intensity
 ){
 ){
-    Ogre::RenderOperation render_op;
-    Ogre::HardwareVertexBufferSharedPtr vertex_buffer;
-    unsigned int max_vertex_count;
-    if (blending == VGears::B_ALPHA){
-        render_op = alpha_render_op_;
-        vertex_buffer = alpha_vertex_buffer_;
-        max_vertex_count = alpha_max_vertex_count_;
-    }
-    else if (blending == VGears::B_ADD){
-        render_op = add_render_op_;
-        vertex_buffer = add_vertex_buffer_;
-        max_vertex_count = add_max_vertex_count_;
-    }
-    else if (blending == VGears::B_SUBTRACT){
-        render_op = subtract_render_op_;
-        vertex_buffer = subtract_vertex_buffer_;
-        max_vertex_count = subtract_max_vertex_count_;
-    }
-    else{
+    BackgroundTileBuffer* buffer = BufferFor(blending);
+    if (buffer == nullptr){
         LOG_ERROR("Unknown blending type.");
         LOG_ERROR("Unknown blending type.");
         return;
         return;
     }
     }
-    if (render_op.vertexData->vertexCount + TILE_VERTEX_COUNT > max_vertex_count){
+    if (buffer->IsFull()){
         LOG_ERROR(
         LOG_ERROR(
           "Max number of tiles reached. Can't create more than "
           "Max number of tiles reached. Can't create more than "
-          + Ogre::StringConverter::toString(max_vertex_count / TILE_VERTEX_COUNT) + " tiles."
+          + Ogre::StringConverter::toString(buffer->MaxTiles()) + " tiles."
         );
         );
         return;
         return;
     }
     }
-    // Keep where the tiles of each layer are in the buffer.
-    {
-        const int buffer = (blending == VGears::B_ALPHA) ? 0 : ((blending == VGears::B_ADD) ? 1 : 2);
-        const int clamped = (layer < 0) ? 0 : ((layer >= LAYER_COUNT) ? LAYER_COUNT - 1 : layer);
-        if (last_layer_[buffer] > clamped) layers_contiguous_[buffer] = false;
-        if (clamped > last_layer_[buffer]) last_layer_[buffer] = clamped;
-        LayerRange& range = layer_ranges_[buffer][clamped];
-        if (range.count == 0) range.first = render_op.vertexData->vertexCount;
-        range.count += TILE_VERTEX_COUNT;
-    }
     Tile tile;
     Tile tile;
     tile.x = x;
     tile.x = x;
     tile.y = y;
     tile.y = y;
     tile.width = width;
     tile.width = width;
     tile.height = height;
     tile.height = height;
-    tile.start_vertex_index = render_op.vertexData->vertexCount;
     tile.blending = blending;
     tile.blending = blending;
     tile.area = area;
     tile.area = area;
     tile.state = state;
     tile.state = state;
     tile.visible = (area == 0) || IsAreaStateOn(area, state);
     tile.visible = (area == 0) || IsAreaStateOn(area, state);
-    //size_t index(tiles_.size());
-    tiles_.push_back(tile);
-    Ogre::Vector2 top_left(static_cast<Ogre::Real>(x), static_cast<Ogre::Real>(-y));
-    Ogre::Vector2 top_right(
-      static_cast<Ogre::Real>(x + width), static_cast<Ogre::Real>(top_left.y)
+    tile.start_vertex_index = buffer->Add(
+      TileCorners(tile), {u1, v1, u2, v2}, depth, intensity, layer
     );
     );
-    Ogre::Vector2 bottom_right(
-      static_cast<Ogre::Real>(top_right.x), static_cast<Ogre::Real>(-(y + height))
-    );
-    Ogre::Vector2 bottom_left(top_left.x, bottom_right.y);
-    virtualScreenToWorldSpace(top_left);
-    virtualScreenToWorldSpace(top_right);
-    virtualScreenToWorldSpace(bottom_right);
-    virtualScreenToWorldSpace(bottom_left);
-    float new_x1 = top_left.x;
-    float new_y1 = top_left.y;
-    float new_x2 = top_right.x;
-    float new_y2 = top_right.y;
-    float new_x3 = bottom_right.x;
-    float new_y3 = bottom_right.y;
-    float new_x4 = bottom_left.x;
-    float new_y4 = bottom_left.y;
-    float* write_iterator
-      = static_cast<float*>(vertex_buffer->lock(Ogre::HardwareBuffer::HBL_NORMAL));
-    write_iterator += render_op.vertexData->vertexCount * TILE_VERTEX_INDEX_SIZE;
-
-    // TODO: Can use WriteGlyph
-    *write_iterator ++ = new_x1;
-    *write_iterator ++ = new_y1;
-    *write_iterator ++ = depth;
-    *write_iterator ++ = intensity;
-    *write_iterator ++ = intensity;
-    *write_iterator ++ = intensity;
-    *write_iterator ++ = 1;
-    *write_iterator ++ = u1;
-    *write_iterator ++ = v1;
-    *write_iterator ++ = new_x2;
-    *write_iterator ++ = new_y2;
-    *write_iterator ++ = depth;
-    *write_iterator ++ = intensity;
-    *write_iterator ++ = intensity;
-    *write_iterator ++ = intensity;
-    *write_iterator ++ = 1;
-    *write_iterator ++ = u2;
-    *write_iterator ++ = v1;
-    *write_iterator ++ = new_x3;
-    *write_iterator ++ = new_y3;
-    *write_iterator ++ = depth;
-    *write_iterator ++ = intensity;
-    *write_iterator ++ = intensity;
-    *write_iterator ++ = intensity;
-    *write_iterator ++ = 1;
-    *write_iterator ++ = u2;
-    *write_iterator ++ = v2;
-    *write_iterator ++ = new_x1;
-    *write_iterator ++ = new_y1;
-    *write_iterator ++ = depth;
-    *write_iterator ++ = intensity;
-    *write_iterator ++ = intensity;
-    *write_iterator ++ = intensity;
-    *write_iterator ++ = 1;
-    *write_iterator ++ = u1;
-    *write_iterator ++ = v1;
-    *write_iterator ++ = new_x3;
-    *write_iterator ++ = new_y3;
-    *write_iterator ++ = depth;
-    *write_iterator ++ = intensity;
-    *write_iterator ++ = intensity;
-    *write_iterator ++ = intensity;
-    *write_iterator ++ = 1;
-    *write_iterator ++ = u2;
-    *write_iterator ++ = v2;
-    *write_iterator ++ = new_x4;
-    *write_iterator ++ = new_y4;
-    *write_iterator ++ = depth;
-    *write_iterator ++ = intensity;
-    *write_iterator ++ = intensity;
-    *write_iterator ++ = intensity;
-    *write_iterator ++ = 1;
-    *write_iterator ++ = u1;
-    *write_iterator ++ = v2;
-    render_op.vertexData->vertexCount += TILE_VERTEX_COUNT;
-    vertex_buffer->unlock();
+    tiles_.push_back(tile);
     // Tiles of an area that is off are written at their position, and then collapsed.
     // Tiles of an area that is off are written at their position, and then collapsed.
-    if (!tiles_.back().visible) WriteTilePosition(tiles_.back());
+    if (!tile.visible) WriteTilePosition(tile);
 }
 }
 
 
 void Background2D::UpdateTileUV(
 void Background2D::UpdateTileUV(
@@ -934,32 +561,8 @@ void Background2D::UpdateTileUV(
         LOG_ERROR("Tile with id " + Ogre::StringConverter::toString( tile_id ) + " doesn't exist.");
         LOG_ERROR("Tile with id " + Ogre::StringConverter::toString( tile_id ) + " doesn't exist.");
         return;
         return;
     }
     }
-    Ogre::HardwareVertexBufferSharedPtr vertex_buffer;
-    if (tiles_[tile_id].blending == VGears::B_ALPHA) vertex_buffer = alpha_vertex_buffer_;
-    else if (tiles_[tile_id].blending == VGears::B_ADD) vertex_buffer = add_vertex_buffer_;
-    else if(tiles_[tile_id].blending == VGears::B_SUBTRACT) vertex_buffer = subtract_vertex_buffer_;
-    float* write_iterator
-      = static_cast<float*>(vertex_buffer->lock(Ogre::HardwareBuffer::HBL_NORMAL));
-    write_iterator += tiles_[tile_id].start_vertex_index * TILE_VERTEX_INDEX_SIZE;
-    write_iterator += 7;
-    *write_iterator ++ = u1;
-    *write_iterator ++ = v1;
-    write_iterator += 7;
-    *write_iterator ++ = u2;
-    *write_iterator ++ = v1;
-    write_iterator += 7;
-    *write_iterator ++ = u2;
-    *write_iterator ++ = v2;
-    write_iterator += 7;
-    *write_iterator ++ = u1;
-    *write_iterator ++ = v1;
-    write_iterator += 7;
-    *write_iterator ++ = u2;
-    *write_iterator ++ = v2;
-    write_iterator += 7;
-    *write_iterator ++ = u1;
-    *write_iterator ++ = v2;
-    vertex_buffer->unlock();
+    const Tile& tile = tiles_[tile_id];
+    BufferFor(tile.blending)->SetTexture(tile.start_vertex_index, {u1, v1, u2, v2});
 }
 }
 
 
 void Background2D::AddAnimation(Background2DAnimation* animation){animations_.push_back(animation);}
 void Background2D::AddAnimation(Background2DAnimation* animation){animations_.push_back(animation);}
@@ -1027,24 +630,14 @@ void Background2D::renderQueueEnded(
         Ogre::Viewport *viewport(CameraManager::getSingleton().getViewport());
         Ogre::Viewport *viewport(CameraManager::getSingleton().getViewport());
         float width = static_cast<float>(viewport->getActualWidth());
         float width = static_cast<float>(viewport->getActualWidth());
         float height = static_cast<float>(viewport->getActualHeight());
         float height = static_cast<float>(viewport->getActualHeight());
-        Ogre::Matrix4 view;
-        view.makeTrans(Ogre::Vector3(position_real_.x / width, -position_real_.y / height, 0));
-        // TODO This is deprecated, but if not done , the background image disappears.
-        render_system_->_setViewMatrix(view);
-        rs_params->setConstant(Ogre::GpuProgramParameters::ACT_VIEW_MATRIX, view);
-        render_system_->applyFixedFunctionParams(rs_params, Ogre::GPV_GLOBAL);
-        RenderBuffer(0, alpha_render_op_, alpha_material_, rs_params, width, height);
-        RenderBuffer(1, add_render_op_, add_material, rs_params, width, height);
-        RenderBuffer(2, subtract_render_op_, subtract_material_, rs_params, width, height);
+        SetView(position_real_, rs_params, width, height);
+        RenderBuffer(alpha_tiles_, rs_params, width, height);
+        RenderBuffer(add_tiles_, rs_params, width, height);
+        RenderBuffer(subtract_tiles_, rs_params, width, height);
     }
     }
 }
 }
 
 
 void Background2D::ResetLayers(){
 void Background2D::ResetLayers(){
-    for (int buffer = 0; buffer < 3; ++ buffer){
-        for (int layer = 0; layer < LAYER_COUNT; ++ layer) layer_ranges_[buffer][layer] = LayerRange();
-        last_layer_[buffer] = -1;
-        layers_contiguous_[buffer] = true;
-    }
     for (int layer = 0; layer < LAYER_COUNT; ++ layer){
     for (int layer = 0; layer < LAYER_COUNT; ++ layer){
         layer_parallax_[layer][0] = layer_parallax_[layer][1] = 1.0f;
         layer_parallax_[layer][0] = layer_parallax_[layer][1] = 1.0f;
         layer_scroll_speed_[layer][0] = layer_scroll_speed_[layer][1] = 0.0f;
         layer_scroll_speed_[layer][0] = layer_scroll_speed_[layer][1] = 0.0f;
@@ -1079,25 +672,18 @@ void Background2D::ScriptSetLayerScroll(const int layer, const int x, const int
 }
 }
 
 
 void Background2D::RenderBuffer(
 void Background2D::RenderBuffer(
-  const int buffer, Ogre::RenderOperation& render_op, const Ogre::MaterialPtr& material,
-  Ogre::GpuProgramParametersPtr& rs_params, const float width, const float height
+  BackgroundTileBuffer& buffer, Ogre::GpuProgramParametersPtr& rs_params, const float width,
+  const float height
 ){
 ){
-    if (render_op.vertexData->vertexCount == 0) return;
-    const unsigned int total = render_op.vertexData->vertexCount;
-    const bool by_layer = layers_contiguous_[buffer] && HasLayerScroll();
-    if (!by_layer){
+    if (buffer.IsEmpty()) return;
+    if (!buffer.Layers().AreContiguous() || !HasLayerScroll()){
         // The view the layers of other buffers could have left.
         // The view the layers of other buffers could have left.
-        Ogre::Matrix4 view;
-        view.makeTrans(Ogre::Vector3(position_real_.x / width, -position_real_.y / height, 0));
-        render_system_->_setViewMatrix(view);
-        rs_params->setConstant(Ogre::GpuProgramParameters::ACT_VIEW_MATRIX, view);
-        render_system_->applyFixedFunctionParams(rs_params, Ogre::GPV_GLOBAL);
-        scene_manager_->_setPass(material->getTechnique(0)->getPass(0), true, false);
-        render_system_->_render(render_op);
+        SetView(position_real_, rs_params, width, height);
+        buffer.Draw(*scene_manager_, *render_system_);
         return;
         return;
     }
     }
     for (int layer = 0; layer < LAYER_COUNT; ++ layer){
     for (int layer = 0; layer < LAYER_COUNT; ++ layer){
-        const LayerRange& range = layer_ranges_[buffer][layer];
+        const BackgroundLayerRanges::Range& range = buffer.Layers().Of(layer);
         if (range.count == 0) continue;
         if (range.count == 0) continue;
         // The scroll of the background, changed by the parallax of the layer, plus the one it has
         // The scroll of the background, changed by the parallax of the layer, plus the one it has
         // by itself. The scroll by itself is in pixels of the virtual screen.
         // by itself. The scroll by itself is in pixels of the virtual screen.
@@ -1105,94 +691,26 @@ void Background2D::RenderBuffer(
           layer_scroll_offset_[layer][0] * screen_scale_,
           layer_scroll_offset_[layer][0] * screen_scale_,
           layer_scroll_offset_[layer][1] * screen_scale_
           layer_scroll_offset_[layer][1] * screen_scale_
         );
         );
-        Ogre::Matrix4 view;
-        view.makeTrans(Ogre::Vector3(
-          (position_real_.x * layer_parallax_[layer][0] + by_itself.x) / width,
-          -(position_real_.y * layer_parallax_[layer][1] + by_itself.y) / height, 0
-        ));
-        // TODO This is deprecated, but if not done , the background image disappears.
-        render_system_->_setViewMatrix(view);
-        rs_params->setConstant(Ogre::GpuProgramParameters::ACT_VIEW_MATRIX, view);
-        render_system_->applyFixedFunctionParams(rs_params, Ogre::GPV_GLOBAL);
-        scene_manager_->_setPass(material->getTechnique(0)->getPass(0), true, false);
-        render_op.vertexData->vertexStart = range.first;
-        render_op.vertexData->vertexCount = range.count;
-        render_system_->_render(render_op);
-        render_op.vertexData->vertexStart = 0;
-        render_op.vertexData->vertexCount = total;
+        SetView(
+          Ogre::Vector2(
+            position_real_.x * layer_parallax_[layer][0] + by_itself.x,
+            position_real_.y * layer_parallax_[layer][1] + by_itself.y
+          ), rs_params, width, height
+        );
+        buffer.Draw(*scene_manager_, *render_system_, range);
     }
     }
 }
 }
 
 
-void Background2D::CreateVertexBuffers(){
-    ResetLayers();
-    // Some fields have more than 1600 tiles that add their colour (the fire and the light of las0_2,
-    // clsin2_1 and ujunon4), and more than 2500 tiles in all.
-    alpha_max_vertex_count_ = 4096 * TILE_VERTEX_COUNT;
-    alpha_render_op_.vertexData = new Ogre::VertexData;
-    alpha_render_op_.vertexData->vertexStart = 0;
-    Ogre::VertexDeclaration* vertex_declaration = alpha_render_op_.vertexData->vertexDeclaration;
-    size_t offset = 0;
-    vertex_declaration->addElement(0, 0, Ogre::VET_FLOAT3, Ogre::VES_POSITION);
-    offset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT3);
-    vertex_declaration->addElement(0, offset, Ogre::VET_FLOAT4, Ogre::VES_DIFFUSE);
-    offset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT4);
-    vertex_declaration->addElement(0, offset, Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES);
-    alpha_vertex_buffer_ = Ogre::HardwareBufferManager::getSingletonPtr()->createVertexBuffer(
-      vertex_declaration->getVertexSize(0), alpha_max_vertex_count_,
-      Ogre::HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY, false
-    );
-    alpha_render_op_.vertexData->vertexBufferBinding->setBinding(0, alpha_vertex_buffer_);
-    alpha_render_op_.operationType = Ogre::RenderOperation::OT_TRIANGLE_LIST;
-    alpha_render_op_.useIndexes = false;
-    add_max_vertex_count_ = 4096 * TILE_VERTEX_COUNT;
-    add_render_op_.vertexData = new Ogre::VertexData;
-    add_render_op_.vertexData->vertexStart = 0;
-    vertex_declaration = add_render_op_.vertexData->vertexDeclaration;
-    offset = 0;
-    vertex_declaration->addElement(0, 0, Ogre::VET_FLOAT3, Ogre::VES_POSITION);
-    offset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT3);
-    vertex_declaration->addElement(0, offset, Ogre::VET_FLOAT4, Ogre::VES_DIFFUSE);
-    offset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT4);
-    vertex_declaration->addElement(0, offset, Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES);
-    add_vertex_buffer_ = Ogre::HardwareBufferManager::getSingletonPtr()->createVertexBuffer(
-      vertex_declaration->getVertexSize(0), add_max_vertex_count_,
-      Ogre::HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY, false
-    );
-    add_render_op_.vertexData->vertexBufferBinding->setBinding(0, add_vertex_buffer_);
-    add_render_op_.operationType = Ogre::RenderOperation::OT_TRIANGLE_LIST;
-    add_render_op_.useIndexes = false;
-    subtract_max_vertex_count_ = 2048 * TILE_VERTEX_COUNT;
-    subtract_render_op_.vertexData = new Ogre::VertexData;
-    subtract_render_op_.vertexData->vertexStart = 0;
-    vertex_declaration = subtract_render_op_.vertexData->vertexDeclaration;
-    offset = 0;
-    vertex_declaration->addElement(0, 0, Ogre::VET_FLOAT3, Ogre::VES_POSITION);
-    offset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT3);
-    vertex_declaration->addElement(0, offset, Ogre::VET_FLOAT4, Ogre::VES_DIFFUSE);
-    offset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT4);
-    vertex_declaration->addElement(0, offset, Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES);
-    subtract_vertex_buffer_ = Ogre::HardwareBufferManager::getSingletonPtr()->createVertexBuffer(
-      vertex_declaration->getVertexSize(0), subtract_max_vertex_count_,
-      Ogre::HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY, false
-    );
-    subtract_render_op_.vertexData->vertexBufferBinding->setBinding(0, subtract_vertex_buffer_);
-    subtract_render_op_.operationType = Ogre::RenderOperation::OT_TRIANGLE_LIST;
-    subtract_render_op_.useIndexes = false;
-}
-
-void Background2D::DestroyVertexBuffers(){
-    delete alpha_render_op_.vertexData;
-    alpha_render_op_.vertexData = 0;
-    alpha_vertex_buffer_.reset();
-    alpha_max_vertex_count_ = 0;
-    delete add_render_op_.vertexData;
-    add_render_op_.vertexData = 0;
-    add_vertex_buffer_.reset();
-    add_max_vertex_count_ = 0;
-    delete subtract_render_op_.vertexData;
-    subtract_render_op_.vertexData = 0;
-    subtract_vertex_buffer_.reset();
-    subtract_max_vertex_count_ = 0;
+void Background2D::SetView(
+  const Ogre::Vector2& position, Ogre::GpuProgramParametersPtr& rs_params, const float width,
+  const float height
+){
+    Ogre::Matrix4 view;
+    view.makeTrans(Ogre::Vector3(position.x / width, -position.y / height, 0));
+    // TODO This is deprecated, but if not done , the background image disappears.
+    render_system_->_setViewMatrix(view);
+    rs_params->setConstant(Ogre::GpuProgramParameters::ACT_VIEW_MATRIX, view);
+    render_system_->applyFixedFunctionParams(rs_params, Ogre::GPV_GLOBAL);
 }
 }
 
 
 void Background2D::load(const VGears::Background2DFilePtr& background){
 void Background2D::load(const VGears::Background2DFilePtr& background){

+ 80 - 340
src/engine/graphics/Background2D.h

@@ -17,49 +17,26 @@
 
 
 #include <map>
 #include <map>
 #include <set>
 #include <set>
-#include <OgreHardwareVertexBuffer.h>
 #include <OgreRenderQueueListener.h>
 #include <OgreRenderQueueListener.h>
 #include <OgreRoot.h>
 #include <OgreRoot.h>
 #include "formats/field/Background2DFile.h"
 #include "formats/field/Background2DFile.h"
 #include "Background2DAnimation.h"
 #include "Background2DAnimation.h"
 #include "BackgroundPalette.h"
 #include "BackgroundPalette.h"
+#include "BackgroundScroll.h"
+#include "BackgroundShake.h"
+#include "BackgroundTileBuffer.h"
 #include "engine/entity/Entity.h"
 #include "engine/entity/Entity.h"
 #include "engine/script/ScriptManager.h"
 #include "engine/script/ScriptManager.h"
 
 
 /**
 /**
  * A field background
  * A field background
  */
  */
-class Background2D : public Ogre::RenderQueueListener{
+class Background2D : public Ogre::RenderQueueListener, public BackgroundScrollTypes{
 
 
     public:
     public:
 
 
         typedef VGears::Blending  Blending;
         typedef VGears::Blending  Blending;
 
 
-        /**
-         * How to scroll the background.
-         */
-        enum SCROLL_TYPE{
-
-            /**
-             * Don't scroll the background.
-             */
-            NONE,
-
-            /**
-             * Linearly scroll.
-             *
-             * May seem unnatural in scripted sequences, but it's OK for
-             * character tracking.
-             */
-            LINEAR,
-            /**
-             * Smooth (soft in, soft out) scroll.
-             *
-             * Best for scripted sequences.
-             */
-            SMOOTH
-        };
-
         /**
         /**
          * Constructor.
          * Constructor.
          */
          */
@@ -589,89 +566,6 @@ class Background2D : public Ogre::RenderQueueListener{
          */
          */
         bool IsAreaStateOn(const int area, const int layers) const;
         bool IsAreaStateOn(const int area, const int layers) const;
 
 
-        /**
-         * A chain of random bounces in one axis of the view.
-         */
-        struct ShakeAxis{
-
-            /**
-             * Amplitude of the next bounces, in original screen pixels.
-             */
-            float amplitude = 0;
-
-            /**
-             * Duration of the next bounces, in seconds.
-             */
-            float seconds = 0;
-
-            /**
-             * Whether the axis is moving.
-             */
-            bool running = false;
-
-            /**
-             * Whether the axis is going back to the center to stop.
-             */
-            bool stopping = false;
-
-            /**
-             * Duration of the movement back to the center, in seconds.
-             */
-            float stop_seconds = 0;
-
-            /**
-             * Position at the start of the current bounce.
-             */
-            float from = 0;
-
-            /**
-             * Position at the end of the current bounce.
-             */
-            float to = 0;
-
-            /**
-             * Duration of the current bounce, in seconds.
-             */
-            float duration = 0;
-
-            /**
-             * Time since the start of the current bounce, in seconds.
-             */
-            float elapsed = 0;
-
-            /**
-             * Index of the next random factor.
-             */
-            size_t step = 0;
-
-            /**
-             * Current position, in original screen pixels.
-             */
-            float value = 0;
-
-            /**
-             * Changes the bounces of the axis, and starts it if it is stopped.
-             */
-            void Configure(const float new_amplitude, const float new_seconds);
-
-            /**
-             * Makes the axis go back to the center and stop after the current bounce.
-             */
-            void Stop(const float seconds_to_center);
-
-            /**
-             * Moves the axis forward in time.
-             *
-             * @return True if the position changed.
-             */
-            bool Advance(const float delta);
-
-            /**
-             * Starts the next bounce.
-             */
-            void StartBounce();
-        };
-
         /**
         /**
          * Moves the shake forward in time, and applies it to the view if it changed.
          * Moves the shake forward in time, and applies it to the view if it changed.
          *
          *
@@ -724,35 +618,6 @@ class Background2D : public Ogre::RenderQueueListener{
          */
          */
         virtual void applyScroll();
         virtual void applyScroll();
 
 
-        /**
-         * Starts a scroll, replacing the current one if there is any.
-         *
-         * A scroll without type or duration is applied immediately.
-         *
-         * @param[in] position Position to scroll to.
-         * @param[in] type Scroll type.
-         * @param[in] seconds Scroll duration.
-         * @param[in] target_entity Entity the scroll moves towards, or nullptr.
-         * @param[in] follow_target Keep following target_entity when the scroll ends.
-         */
-        void StartScroll(
-          const Ogre::Vector2& position, const SCROLL_TYPE type, const float seconds,
-          Entity* target_entity, const bool follow_target
-        );
-
-        /**
-         * Limits a scroll position to the background range.
-         *
-         * @param[in] position Position to limit.
-         * @return The position, inside the background range.
-         */
-        const Ogre::Vector2 ClampScroll(const Ogre::Vector2& position) const;
-
-        /**
-         * Limits a scroll position to the background range, always.
-         */
-        const Ogre::Vector2 ClampToRange(const Ogre::Vector2& position) const;
-
         /**
         /**
          * Calculates the screen scale.
          * Calculates the screen scale.
          *
          *
@@ -770,296 +635,176 @@ class Background2D : public Ogre::RenderQueueListener{
          */
          */
         virtual void virtualScreenToWorldSpace(Ogre::Vector2 &pos) const;
         virtual void virtualScreenToWorldSpace(Ogre::Vector2 &pos) const;
 
 
-        /**
-         * Tile vertex properties.
-         */
-        enum{
-
-            /**
-             * Tile vertex count.
-             *
-             * @todo Understand and document.
-             */
-            TILE_VERTEX_COUNT = 6,
-
-            /**
-             * Tile vertex index size.
-             */
-            TILE_VERTEX_INDEX_SIZE = TILE_VERTEX_COUNT + 3
-        };
-
     private:
     private:
 
 
         /**
         /**
-         * Creates all vertex buffers.
-         */
-        void CreateVertexBuffers();
-
-        /**
-         * Destroys all vertex buffers.
-         */
-        void DestroyVertexBuffers();
-
-        /**
-         * The scene manager.
-         */
-        Ogre::SceneManager* scene_manager_;
-
-        /**
-         * The render system.
-         */
-        Ogre::RenderSystem* render_system_;
-
-        /**
-         * The list of tiles in the background.
-         */
-        TileList tiles_;
-
-        /**
-         * The layers that are on for each scripted area, as a bit mask.
-         */
-        std::map<int, unsigned int> area_states_on_;
-
-        /**
-         * Painting again of the tiles of the palettes the scripts animate.
-         */
-        void UpdatePalette();
-
-        /**
-         * The palettes the scripts animate.
-         */
-        BackgroundPalette palette_;
-
-        /**
-         * Name of the image of the background.
-         */
-        Ogre::String image_name_;
-
-        /**
-         * A copy of the image of the background, where the animated tiles are painted.
-         */
-        Ogre::Image palette_image_;
-
-        /**
-         * True if palette_image_ has the image.
-         */
-        bool palette_image_loaded_ = false;
-
-        /**
-         * The shake of the view in the X axis.
-         */
-        ShakeAxis shake_x_;
-
-        /**
-         * The shake of the view in the Y axis.
-         */
-        ShakeAxis shake_y_;
-
-        /**
-         * The shake being applied to the scroll, in virtual screen units.
+         * The number of layers of a background.
          */
          */
-        Ogre::Vector2 shake_offset_ = Ogre::Vector2::ZERO;
+        static const int LAYER_COUNT = BackgroundLayerRanges::LAYER_COUNT;
 
 
         /**
         /**
-         * Alpha blending render operation.
-         */
-        /**
-         * The number of layers of a background.
+         * Number of alpha and of add tiles that fit. Some fields have more than 1600 tiles that add
+         * their colour (the fire and the light of las0_2, clsin2_1 and ujunon4), and more than 2500
+         * tiles in all.
          */
          */
-        static const int LAYER_COUNT = 4;
+        static const unsigned int MAX_TILES = 4096;
 
 
         /**
         /**
-         * Part of a vertex buffer that has the tiles of a layer.
+         * Number of subtract tiles that fit.
          */
          */
-        struct LayerRange{
-            LayerRange(): first(0), count(0){}
-            unsigned int first;
-            unsigned int count;
-        };
+        static const unsigned int MAX_SUBTRACT_TILES = 2048;
 
 
         /**
         /**
-         * The tiles of each layer in the buffers of alpha, add and subtract tiles. They are only
-         * used if the tiles of a layer are together, which is how the installer writes them.
+         * The alpha blended tiles.
          */
          */
-        LayerRange layer_ranges_[3][LAYER_COUNT];
+        BackgroundTileBuffer alpha_tiles_;
 
 
         /**
         /**
-         * The last layer a tile has been added to for each buffer.
+         * The tiles that add their colour.
          */
          */
-        int last_layer_[3];
+        BackgroundTileBuffer add_tiles_;
 
 
         /**
         /**
-         * If the tiles of the layers of each buffer are together, one layer after the other.
+         * The tiles that subtract their colour.
          */
          */
-        bool layers_contiguous_[3];
+        BackgroundTileBuffer subtract_tiles_;
 
 
         /**
         /**
-         * Scroll of each layer relative to the one of the background.
+         * The scroll of the view.
          */
          */
-        float layer_parallax_[LAYER_COUNT][2];
+        BackgroundScroll scroll_;
 
 
         /**
         /**
-         * Speed at which each layer scrolls by itself, in pixels of the virtual screen per second.
+         * The shake of the view.
          */
          */
-        float layer_scroll_speed_[LAYER_COUNT][2];
+        BackgroundShake shake_;
 
 
         /**
         /**
-         * Distance each layer has scrolled by itself, in pixels of the virtual screen.
+         * Retrieves the buffer of the tiles with a blending mode.
+         *
+         * @param[in] blending The blending mode.
+         * @return The buffer, or null if the mode is unknown.
          */
          */
-        float layer_scroll_offset_[LAYER_COUNT][2];
+        BackgroundTileBuffer* BufferFor(const Blending blending);
 
 
         /**
         /**
-         * Sets the layers to the state they have when a background is loaded.
+         * Calculates where the corners of a tile are.
+         *
+         * @param[in] tile The tile.
+         * @return The corners, in world space.
          */
          */
-        void ResetLayers();
+        QuadWriter::Corners TileCorners(const Tile& tile) const;
 
 
         /**
         /**
-         * If any layer is not scrolled as the background is.
+         * Moves forward the animations that are playing.
+         *
+         * @param[in] delta Seconds since the last frame.
          */
          */
-        bool HasLayerScroll() const;
+        void UpdateAnimations(const float delta);
 
 
         /**
         /**
          * Draws the tiles of a buffer, each layer scrolled as it has to be.
          * Draws the tiles of a buffer, each layer scrolled as it has to be.
          *
          *
-         * @param[in] buffer Buffer to draw: 0 for alpha, 1 for add and 2 for subtract.
-         * @param[in,out] render_op What to draw.
-         * @param[in] material Material to draw it with.
+         * @param[in,out] buffer Buffer to draw.
          * @param[in] rs_params Parameters of the render system.
          * @param[in] rs_params Parameters of the render system.
          * @param[in] width Width of the viewport.
          * @param[in] width Width of the viewport.
          * @param[in] height Height of the viewport.
          * @param[in] height Height of the viewport.
          */
          */
         void RenderBuffer(
         void RenderBuffer(
-          const int buffer, Ogre::RenderOperation& render_op, const Ogre::MaterialPtr& material,
-          Ogre::GpuProgramParametersPtr& rs_params, const float width, const float height
+          BackgroundTileBuffer& buffer, Ogre::GpuProgramParametersPtr& rs_params, const float width,
+          const float height
         );
         );
 
 
-        Ogre::RenderOperation alpha_render_op_;
-
         /**
         /**
-         * Alpha blending vertex buffer.
-         */
-        Ogre::HardwareVertexBufferSharedPtr alpha_vertex_buffer_;
-
-        /**
-         * Alpha blending max vertex count.
-         */
-        unsigned int alpha_max_vertex_count_;
-
-        /**
-         * Alpha blending material.
-         */
-        Ogre::MaterialPtr alpha_material_;
-
-        /**
-         * Add blending render operation.
-         */
-        Ogre::RenderOperation add_render_op_;
-
-        /**
-         * Add blending vertex buffer.
-         */
-        Ogre::HardwareVertexBufferSharedPtr add_vertex_buffer_;
-
-        /**
-         * Add blending max vertex count.
-         */
-        unsigned int add_max_vertex_count_;
-
-        /**
-         * Add blending material.
-         */
-        Ogre::MaterialPtr add_material;
-
-        /**
-         * Substract blending render operation.
+         * Moves the view the tiles are drawn with.
+         *
+         * @param[in] position Scroll of the view, in pixels of the screen.
+         * @param[in] rs_params Parameters of the render system.
+         * @param[in] width Width of the viewport.
+         * @param[in] height Height of the viewport.
          */
          */
-        Ogre::RenderOperation subtract_render_op_;
+        void SetView(
+          const Ogre::Vector2& position, Ogre::GpuProgramParametersPtr& rs_params, const float width,
+          const float height
+        );
 
 
         /**
         /**
-         * Substract blending vertex buffer.
+         * The scene manager.
          */
          */
-        Ogre::HardwareVertexBufferSharedPtr subtract_vertex_buffer_;
+        Ogre::SceneManager* scene_manager_;
 
 
         /**
         /**
-         * Substract blending max vertex count.
+         * The render system.
          */
          */
-        unsigned int subtract_max_vertex_count_;
+        Ogre::RenderSystem* render_system_;
 
 
         /**
         /**
-         * Substract blending material.
+         * The list of tiles in the background.
          */
          */
-        Ogre::MaterialPtr subtract_material_;
+        TileList tiles_;
 
 
         /**
         /**
-         * The entity to keep track of with the scroll.
+         * The layers that are on for each scripted area, as a bit mask.
          */
          */
-        Entity* scroll_entity_;
+        std::map<int, unsigned int> area_states_on_;
 
 
         /**
         /**
-         * Starting position of the current scroll action.
+         * Painting again of the tiles of the palettes the scripts animate.
          */
          */
-        Ogre::Vector2 scroll_position_start_;
+        void UpdatePalette();
 
 
         /**
         /**
-         * Final position of the current scroll action.
+         * The palettes the scripts animate.
          */
          */
-        Ogre::Vector2 scroll_position_end_;
+        BackgroundPalette palette_;
 
 
         /**
         /**
-         * Type of the current scroll action.
+         * Name of the image of the background.
          */
          */
-        SCROLL_TYPE scroll_type_;
+        Ogre::String image_name_;
 
 
         /**
         /**
-         * Total duration of the current scroll action, in seconds
+         * A copy of the image of the background, where the animated tiles are painted.
          */
          */
-        float scroll_seconds_;
+        Ogre::Image palette_image_;
 
 
         /**
         /**
-         * Secund the currens scroll action has taken so far.
+         * True if palette_image_ has the image.
          */
          */
-        float scroll_current_seconds_;
+        bool palette_image_loaded_ = false;
 
 
         /**
         /**
-         * Entity the current scroll action moves towards, or nullptr.
+         * The shake being applied to the scroll, in virtual screen units.
          */
          */
-        Entity* scroll_target_entity_;
+        Ogre::Vector2 shake_offset_ = Ogre::Vector2::ZERO;
 
 
         /**
         /**
-         * Whether to keep following the target entity when the current scroll action ends.
+         * Alpha blending render operation.
          */
          */
-        bool scroll_follow_target_;
-
         /**
         /**
-         * True while a script has moved the camera to a position. The original game doesn't limit
-         * those scrolls to the background, so a scene can show the empty space around it (the
-         * models of ealin_12 are moved there while the camera is away). The camera that follows
-         * an entity is always limited.
+         * Scroll of each layer relative to the one of the background.
          */
          */
-        bool free_scroll_;
+        float layer_parallax_[LAYER_COUNT][2];
 
 
         /**
         /**
-         * Position of an instant scroll that waits for the end of the frame.
-         *
-         * A script that sets a position and scrolls to another one in the same frame must see the
-         * scroll start where the camera was, not at the first position. See ScriptScrollToPosition.
+         * Speed at which each layer scrolls by itself, in pixels of the virtual screen per second.
          */
          */
-        Ogre::Vector2 pending_scroll_;
+        float layer_scroll_speed_[LAYER_COUNT][2];
 
 
         /**
         /**
-         * Whether there is an instant scroll waiting for the end of the frame.
+         * Distance each layer has scrolled by itself, in pixels of the virtual screen.
          */
          */
-        bool has_pending_scroll_ = false;
+        float layer_scroll_offset_[LAYER_COUNT][2];
 
 
         /**
         /**
-         * @todo Document.
+         * Sets the layers to the state they have when a background is loaded.
          */
          */
-        std::vector<ScriptId> scroll_sync_;
+        void ResetLayers();
 
 
         /**
         /**
-         * The current scroll position, virtual screen size.
+         * If any layer is not scrolled as the background is.
          */
          */
-        Ogre::Vector2 position_;
+        bool HasLayerScroll() const;
 
 
         /**
         /**
          * The current background offset, virtual screen size.
          * The current background offset, virtual screen size.
@@ -1088,11 +833,6 @@ class Background2D : public Ogre::RenderQueueListener{
          */
          */
         Ogre::Vector2 virtual_screen_size_;
         Ogre::Vector2 virtual_screen_size_;
 
 
-        /**
-         * @todo Document.
-         */
-        Ogre::AxisAlignedBox range_;
-
         /**
         /**
          * State of an animation.
          * State of an animation.
          */
          */

+ 139 - 0
src/engine/graphics/BackgroundScroll.cpp

@@ -0,0 +1,139 @@
+/*
+ * 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 "BackgroundScroll.h"
+
+BackgroundScroll::BackgroundScroll(const Resume& resume):
+  resume_(resume), position_(Ogre::Vector2::ZERO), range_(Ogre::AxisAlignedBox::BOX_INFINITE),
+  followed_entity_(nullptr), target_entity_(nullptr), start_(Ogre::Vector2::ZERO),
+  end_(Ogre::Vector2::ZERO), type_(NONE), seconds_(0), current_seconds_(0), free_(false),
+  pending_position_(Ogre::Vector2::ZERO), has_pending_(false)
+{}
+
+void BackgroundScroll::SetPosition(const Ogre::Vector2& position){position_ = Clamp(position);}
+
+Ogre::Vector2 BackgroundScroll::Clamp(const Ogre::Vector2& position) const{
+    return free_ ? position : ClampToRange(position);
+}
+
+Ogre::Vector2 BackgroundScroll::ClampToRange(const Ogre::Vector2& position) const{
+    Ogre::Vector2 clamped = position;
+    if (!range_.contains(Ogre::Vector3(position.x, position.y, 0))){
+        const Ogre::Vector3 maximum = range_.getMaximum();
+        const Ogre::Vector3 minimum = range_.getMinimum();
+        clamped.makeCeil(Ogre::Vector2(minimum.x, minimum.y));
+        clamped.makeFloor(Ogre::Vector2(maximum.x, maximum.y));
+    }
+    return clamped;
+}
+
+void BackgroundScroll::Follow(Entity* entity){
+    followed_entity_ = entity;
+    free_ = false;
+}
+
+bool BackgroundScroll::HasControl() const{
+    return followed_entity_ != nullptr || target_entity_ != nullptr || free_ || has_pending_;
+}
+
+bool BackgroundScroll::ToEntity(
+  Entity* entity, const Ogre::Vector2& position, const SCROLL_TYPE type, const float seconds
+){
+    followed_entity_ = nullptr;
+    return Begin(position, type, seconds, entity);
+}
+
+void BackgroundScroll::ToPosition(
+  const Ogre::Vector2& position, const SCROLL_TYPE type, const float seconds
+){
+    followed_entity_ = nullptr;
+    free_ = true;
+    if (type == NONE || seconds <= 0){
+        // The scripts set a position and then scroll from it to another one, in the same frame.
+        // The camera is only moved at the end of the frame, so if another scroll comes first the
+        // movement starts from where the camera was, and there is no jump.
+        // TODO: Some scenes still show a small camera jump (mds7pb_1, when the NPCs go down the
+        // pinball machine and when Marlene says "Papa"), and the camera stays fixed after them
+        // until the script scrolls to the player. How the original game handles it is not known.
+        Abandon();
+        pending_position_ = position;
+        has_pending_ = true;
+        return;
+    }
+    Begin(position, type, seconds, nullptr);
+}
+
+bool BackgroundScroll::ApplyPending(){
+    if (!has_pending_) return false;
+    has_pending_ = false;
+    SetPosition(pending_position_);
+    return true;
+}
+
+bool BackgroundScroll::Wait(const ScriptId& script){
+    if (type_ == NONE) return false;
+    waiting_.push_back(script);
+    return true;
+}
+
+void BackgroundScroll::Stop(){
+    type_ = NONE;
+    if (target_entity_ != nullptr) Follow(target_entity_);
+    target_entity_ = nullptr;
+    for (const ScriptId& script : waiting_) resume_(script);
+    waiting_.clear();
+}
+
+void BackgroundScroll::Clear(){
+    target_entity_ = nullptr;
+    Stop();
+    position_ = Ogre::Vector2::ZERO;
+    range_ = Ogre::AxisAlignedBox::BOX_INFINITE;
+    followed_entity_ = nullptr;
+    start_ = Ogre::Vector2::ZERO;
+    end_ = Ogre::Vector2::ZERO;
+    seconds_ = 0;
+    current_seconds_ = 0;
+    free_ = false;
+    has_pending_ = false;
+}
+
+bool BackgroundScroll::Begin(
+  const Ogre::Vector2& position, const SCROLL_TYPE type, const float seconds, Entity* target
+){
+    // A newer scroll replaces an instant one that has not been applied yet, and finishes the
+    // previous one.
+    has_pending_ = false;
+    Abandon();
+    target_entity_ = target;
+    if (type == NONE || seconds <= 0){
+        // The camera that goes to an entity is limited to the background.
+        if (target != nullptr) free_ = false;
+        SetPosition(position);
+        Stop();
+        return true;
+    }
+    start_ = position_;
+    end_ = (target != nullptr) ? ClampToRange(position) : Clamp(position);
+    type_ = type;
+    seconds_ = seconds;
+    current_seconds_ = 0;
+    return false;
+}
+
+void BackgroundScroll::Abandon(){
+    target_entity_ = nullptr;
+    Stop();
+}

+ 281 - 0
src/engine/graphics/BackgroundScroll.h

@@ -0,0 +1,281 @@
+/*
+ * 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 <vector>
+#include <OgreAxisAlignedBox.h>
+#include <OgreVector2.h>
+#include "engine/script/ScriptManager.h"
+
+class Entity;
+
+/**
+ * The kinds of scroll of a field.
+ */
+struct BackgroundScrollTypes{
+
+    /**
+     * Types of scroll.
+     */
+    enum SCROLL_TYPE{
+
+        /**
+         * No scroll.
+         */
+        NONE,
+
+        /**
+         * Linear, smooth scroll.
+         */
+        LINEAR,
+
+        /**
+         * Accelerated scroll.
+         */
+        SMOOTH
+    };
+};
+
+/**
+ * The scroll of a field: where the view is, where it is going, what entity it follows, and the
+ * scripts that wait for it.
+ *
+ * The movement of a scroll is done by the caller, which sets the position as time passes.
+ */
+class BackgroundScroll : public BackgroundScrollTypes{
+
+    public:
+
+        /**
+         * Function that lets a script that was waiting go on.
+         */
+        typedef std::function<void(const ScriptId&)> Resume;
+
+        /**
+         * Constructor.
+         *
+         * @param[in] resume Called for each waiting script when a scroll ends.
+         */
+        explicit BackgroundScroll(const Resume& resume);
+
+        /**
+         * Retrieves the position of the view.
+         */
+        const Ogre::Vector2& Position() const{return position_;}
+
+        /**
+         * Moves the view, within the limits unless the scroll is free.
+         *
+         * @param[in] position The new position.
+         */
+        void SetPosition(const Ogre::Vector2& position);
+
+        /**
+         * Sets the limits of the view.
+         *
+         * @param[in] range The limits.
+         */
+        void SetRange(const Ogre::AxisAlignedBox& range){range_ = range;}
+
+        /**
+         * Limits a position, unless the scroll is free.
+         *
+         * @param[in] position The position.
+         * @return The position within the limits.
+         */
+        Ogre::Vector2 Clamp(const Ogre::Vector2& position) const;
+
+        /**
+         * Limits a position.
+         *
+         * @param[in] position The position.
+         * @return The position within the limits.
+         */
+        Ogre::Vector2 ClampToRange(const Ogre::Vector2& position) const;
+
+        /**
+         * Makes the view follow an entity.
+         *
+         * @param[in] entity The entity.
+         */
+        void Follow(Entity* entity);
+
+        /**
+         * Retrieves the entity the view follows, or null.
+         */
+        Entity* FollowedEntity() const{return followed_entity_;}
+
+        /**
+         * Checks if something controls the view: an entity or a scroll of a script.
+         */
+        bool HasControl() const;
+
+        /**
+         * Scrolls to an entity, and follows it when the scroll ends.
+         *
+         * @param[in] entity The entity.
+         * @param[in] position Position of the view that shows the entity.
+         * @param[in] type Type of scroll.
+         * @param[in] seconds Duration of the scroll.
+         * @return True if the view has already moved: it was an instant scroll.
+         */
+        bool ToEntity(
+          Entity* entity, const Ogre::Vector2& position, const SCROLL_TYPE type,
+          const float seconds
+        );
+
+        /**
+         * Scrolls to a position, which is not limited. The view follows nothing after it.
+         *
+         * An instant scroll is done in the next {@see ApplyPending}.
+         *
+         * @param[in] position The position.
+         * @param[in] type Type of scroll.
+         * @param[in] seconds Duration of the scroll.
+         */
+        void ToPosition(const Ogre::Vector2& position, const SCROLL_TYPE type, const float seconds);
+
+        /**
+         * Does the instant scroll to a position that is waiting, if there is one.
+         *
+         * @return True if the view moved.
+         */
+        bool ApplyPending();
+
+        /**
+         * Retrieves the entity the current scroll goes to, or null.
+         */
+        Entity* TargetEntity() const{return target_entity_;}
+
+        /**
+         * Changes where the current scroll ends, for scrolls to an entity that moves.
+         *
+         * @param[in] position The new end, which is limited.
+         */
+        void SetTargetPosition(const Ogre::Vector2& position){end_ = ClampToRange(position);}
+
+        /**
+         * Makes a script wait for the current scroll to end.
+         *
+         * @param[in] script The script.
+         * @return False if there is no scroll to wait for.
+         */
+        bool Wait(const ScriptId& script);
+
+        /**
+         * Ends the current scroll: the view follows its target, and the waiting scripts go on.
+         */
+        void Stop();
+
+        /**
+         * Ends the current scroll and forgets everything.
+         */
+        void Clear();
+
+        /**
+         * Retrieves where the current scroll started.
+         */
+        const Ogre::Vector2& Start() const{return start_;}
+
+        /**
+         * Retrieves where the current scroll ends.
+         */
+        const Ogre::Vector2& End() const{return end_;}
+
+        /**
+         * Retrieves the type of the current scroll, NONE if there is none.
+         */
+        SCROLL_TYPE Type() const{return type_;}
+
+        /**
+         * Retrieves the duration of the current scroll.
+         */
+        float Seconds() const{return seconds_;}
+
+        /**
+         * Retrieves how long the current scroll has been going on.
+         */
+        float CurrentSeconds() const{return current_seconds_;}
+
+        /**
+         * Sets how long the current scroll has been going on.
+         */
+        void SetCurrentSeconds(const float seconds){current_seconds_ = seconds;}
+
+    private:
+
+        /**
+         * Starts a scroll.
+         *
+         * @param[in] position Where it ends.
+         * @param[in] type Type of scroll.
+         * @param[in] seconds Duration.
+         * @param[in] target Entity the view follows when the scroll ends, or null.
+         * @return True if the view has already moved: it was an instant scroll.
+         */
+        bool Begin(
+          const Ogre::Vector2& position, const SCROLL_TYPE type, const float seconds,
+          Entity* target
+        );
+
+        /**
+         * Ends the current scroll without following its target.
+         */
+        void Abandon();
+
+        /** Lets the waiting scripts go on. */
+        Resume resume_;
+
+        /** The position of the view. */
+        Ogre::Vector2 position_;
+
+        /** The limits of the view. */
+        Ogre::AxisAlignedBox range_;
+
+        /** The entity the view follows. */
+        Entity* followed_entity_;
+
+        /** The entity the current scroll goes to. */
+        Entity* target_entity_;
+
+        /** Where the current scroll started. */
+        Ogre::Vector2 start_;
+
+        /** Where the current scroll ends. */
+        Ogre::Vector2 end_;
+
+        /** Type of the current scroll. */
+        SCROLL_TYPE type_;
+
+        /** Duration of the current scroll. */
+        float seconds_;
+
+        /** How long the current scroll has been going on. */
+        float current_seconds_;
+
+        /** True if a script moved the view to a position, which is not limited. */
+        bool free_;
+
+        /** Position of the instant scroll that is waiting. */
+        Ogre::Vector2 pending_position_;
+
+        /** True if there is an instant scroll waiting. */
+        bool has_pending_;
+
+        /** The scripts waiting for the current scroll. */
+        std::vector<ScriptId> waiting_;
+};

+ 108 - 0
src/engine/graphics/BackgroundShake.cpp

@@ -0,0 +1,108 @@
+/*
+ * 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 "BackgroundShake.h"
+
+namespace{
+    // Random factors the original game applies to each bounce of a shake.
+    const float SHAKE_FACTORS[] = {
+      -1.0f, 1.14f, -1.34f, 0.61f, -0.49f, 0.64f, -0.25f, 0.47f, -1.20f, -0.01f, 1.14f, -0.86f,
+      0.81f, -0.58f, 0.68f, -1.31f, 0.44f, -0.91f, 0.03f, -0.97f, 1.25f, -0.76f, 0.48f, -0.99f,
+      1.34f, -0.85f, 0.55f, -0.65f, 0.07f, -0.83f
+    };
+    const size_t SHAKE_FACTOR_COUNT = sizeof(SHAKE_FACTORS) / sizeof(SHAKE_FACTORS[0]);
+
+    // Frames per second the shake times are given in.
+    const float SHAKE_FRAMES_PER_SECOND = 30.0f;
+
+    // Quadratic in and out easing.
+    float ShakeEase(const float t){return t < 0.5f ? 2 * t * t : 1 - 2 * (1 - t) * (1 - t);}
+}
+
+void BackgroundShake::Axis::Configure(const float new_amplitude, const float new_seconds){
+    amplitude = new_amplitude;
+    seconds = std::max(new_seconds, 1.0f / SHAKE_FRAMES_PER_SECOND);
+    stopping = false;
+    if (!running){
+        running = true;
+        StartBounce();
+    }
+}
+
+void BackgroundShake::Axis::Stop(const float seconds_to_center){
+    if (!running) return;
+    stopping = true;
+    stop_seconds = std::max(seconds_to_center, 1.0f / SHAKE_FRAMES_PER_SECOND);
+}
+
+void BackgroundShake::Axis::StartBounce(){
+    from = value;
+    elapsed = 0;
+    if (stopping){
+        to = 0;
+        duration = stop_seconds;
+    }
+    else{
+        // Half the amplitude, times the random factor, is the distance in pixels.
+        to = amplitude / 2 * SHAKE_FACTORS[step % SHAKE_FACTOR_COUNT];
+        ++ step;
+        duration = seconds;
+    }
+}
+
+bool BackgroundShake::Axis::Advance(const float delta){
+    if (!running) return false;
+    const float old_value = value;
+    elapsed += delta;
+    while (elapsed >= duration){
+        elapsed -= duration;
+        value = to;
+        if (stopping && to == 0){
+            // Back in the center: the shake is over.
+            *this = Axis();
+            return old_value != 0;
+        }
+        StartBounce();
+    }
+    value = from + (to - from) * ShakeEase(elapsed / duration);
+    return value != old_value;
+}
+
+bool BackgroundShake::Set(
+  const int type, const int x_amplitude, const int x_frames, const int y_amplitude,
+  const int y_frames
+){
+    const float x_seconds = x_frames / SHAKE_FRAMES_PER_SECOND;
+    const float y_seconds = y_frames / SHAKE_FRAMES_PER_SECOND;
+    if (type == 0){
+        const float seconds = std::max(x_seconds, y_seconds);
+        x_.Stop(seconds);
+        y_.Stop(seconds);
+        return true;
+    }
+    if (type < 0 || type > 3) return false;
+    // The bits of the type are the axes.
+    if (type & 1) x_.Configure(static_cast<float>(x_amplitude), x_seconds);
+    if (type & 2) y_.Configure(static_cast<float>(y_amplitude), y_seconds);
+    return true;
+}
+
+bool BackgroundShake::Update(const float delta){
+    if (!IsRunning()) return false;
+    const bool x_changed = x_.Advance(delta);
+    const bool y_changed = y_.Advance(delta);
+    return x_changed || y_changed;
+}

+ 135 - 0
src/engine/graphics/BackgroundShake.h

@@ -0,0 +1,135 @@
+/*
+ * 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 <cstddef>
+#include <OgreVector2.h>
+
+/**
+ * The shake of the view of a field: a chain of random bounces in each axis.
+ */
+class BackgroundShake{
+
+    public:
+
+        /**
+         * Starts, changes or stops the shake, as the scripts ask.
+         *
+         * @param[in] type 0 to stop, 1 to shake horizontally, 2 vertically and 3 both.
+         * @param[in] x_amplitude Horizontal amplitude, in original screen pixels.
+         * @param[in] x_frames Duration of the horizontal bounces, at 30 frames per second.
+         * @param[in] y_amplitude Vertical amplitude, in original screen pixels.
+         * @param[in] y_frames Duration of the vertical bounces, at 30 frames per second.
+         * @return False if the type is unknown.
+         */
+        bool Set(
+          const int type, const int x_amplitude, const int x_frames, const int y_amplitude,
+          const int y_frames
+        );
+
+        /**
+         * Moves the shake forward in time.
+         *
+         * @param[in] delta Seconds since the last frame.
+         * @return True if the position changed.
+         */
+        bool Update(const float delta);
+
+        /**
+         * Retrieves the position of the view.
+         *
+         * @return The displacement from the center, in original screen pixels.
+         */
+        Ogre::Vector2 Offset() const{return Ogre::Vector2(x_.value, y_.value);}
+
+        /**
+         * Checks if the view is moving in any axis.
+         */
+        bool IsRunning() const{return x_.running || y_.running;}
+
+    private:
+
+        /**
+         * A chain of random bounces in one axis of the view.
+         */
+        struct Axis{
+
+            /** Amplitude of the next bounces, in original screen pixels. */
+            float amplitude = 0;
+
+            /** Duration of the next bounces, in seconds. */
+            float seconds = 0;
+
+            /** Whether the axis is moving. */
+            bool running = false;
+
+            /** Whether the axis is going back to the center to stop. */
+            bool stopping = false;
+
+            /** Duration of the movement back to the center, in seconds. */
+            float stop_seconds = 0;
+
+            /** Position at the start of the current bounce. */
+            float from = 0;
+
+            /** Position at the end of the current bounce. */
+            float to = 0;
+
+            /** Duration of the current bounce, in seconds. */
+            float duration = 0;
+
+            /** Time since the start of the current bounce, in seconds. */
+            float elapsed = 0;
+
+            /** Index of the next random factor. */
+            size_t step = 0;
+
+            /** Current position, in original screen pixels. */
+            float value = 0;
+
+            /**
+             * Changes the bounces of the axis, and starts it if it is stopped.
+             */
+            void Configure(const float new_amplitude, const float new_seconds);
+
+            /**
+             * Makes the axis go back to the center and stop after the current bounce.
+             */
+            void Stop(const float seconds_to_center);
+
+            /**
+             * Moves the axis forward in time.
+             *
+             * @return True if the position changed.
+             */
+            bool Advance(const float delta);
+
+            /**
+             * Starts the next bounce.
+             */
+            void StartBounce();
+        };
+
+        /**
+         * The horizontal axis.
+         */
+        Axis x_;
+
+        /**
+         * The vertical axis.
+         */
+        Axis y_;
+};

+ 151 - 0
src/engine/graphics/BackgroundTileBuffer.cpp

@@ -0,0 +1,151 @@
+/*
+ * 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 <OgreMaterialManager.h>
+#include <OgrePass.h>
+#include <OgreTechnique.h>
+#include <OgreTextureUnitState.h>
+#include <OgreVertexIndexData.h>
+#include "BackgroundTileBuffer.h"
+
+void BackgroundLayerRanges::Clear(){
+    for (Range& range : ranges_) range = Range();
+    last_layer_ = -1;
+    contiguous_ = true;
+}
+
+void BackgroundLayerRanges::Add(
+  const int layer, const unsigned int first, const unsigned int count
+){
+    const int clamped = (layer < 0) ? 0 : ((layer >= LAYER_COUNT) ? LAYER_COUNT - 1 : layer);
+    if (last_layer_ > clamped) contiguous_ = false;
+    if (clamped > last_layer_) last_layer_ = clamped;
+    Range& range = ranges_[clamped];
+    if (range.count == 0) range.first = first;
+    range.count += count;
+}
+
+BackgroundTileBuffer::BackgroundTileBuffer(
+  const VGears::Blending blending, const Ogre::String& material_name,
+  const unsigned int max_tiles
+):
+  max_tiles_(max_tiles)
+{
+    CreateBuffer();
+    material_ = Ogre::MaterialManager::getSingleton().create(material_name, "FIELDS");
+    Ogre::Pass* pass = material_->getTechnique(0)->getPass(0);
+    pass->setVertexColourTracking(Ogre::TVC_AMBIENT);
+    pass->setCullingMode(Ogre::CULL_NONE);
+    pass->setDepthCheckEnabled(true);
+    pass->setLightingEnabled(false);
+    // The tiles that add or subtract their colour blend with what is behind. They don't write
+    // depth, or a tile in front (such as the light beams, at depth 0) would hide the ones behind
+    // it, like the waterfall of eals_1.
+    pass->setDepthWriteEnabled(blending == VGears::B_ALPHA);
+    if (blending == VGears::B_ALPHA) pass->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
+    else pass->setSceneBlending(Ogre::SBT_ADD);
+    if (blending == VGears::B_SUBTRACT) pass->setSceneBlendingOperation(Ogre::SBO_SUBTRACT);
+    pass->setAlphaRejectFunction(
+      blending == VGears::B_SUBTRACT ? Ogre::CMPF_LESS : Ogre::CMPF_GREATER
+    );
+    pass->setAlphaRejectValue(0);
+    Ogre::TextureUnitState* texture = pass->createTextureUnitState();
+    texture->setTextureName("system/blank.png");
+    texture->setNumMipmaps(-1);
+    texture->setTextureFiltering(Ogre::TFO_NONE);
+}
+
+BackgroundTileBuffer::~BackgroundTileBuffer(){DestroyBuffer();}
+
+void BackgroundTileBuffer::Clear(){
+    DestroyBuffer();
+    CreateBuffer();
+    layers_.Clear();
+}
+
+void BackgroundTileBuffer::SetImage(const Ogre::String& image){
+    material_->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setTextureName(image);
+}
+
+bool BackgroundTileBuffer::IsFull() const{
+    return operation_.vertexData->vertexCount + QuadWriter::VERTEX_COUNT
+      > max_tiles_ * QuadWriter::VERTEX_COUNT;
+}
+
+unsigned int BackgroundTileBuffer::Add(
+  const QuadWriter::Corners& corners, const QuadWriter::Rectangle& texture, const float depth,
+  const float intensity, const int layer
+){
+    const unsigned int first = operation_.vertexData->vertexCount;
+    layers_.Add(layer, first, QuadWriter::VERTEX_COUNT);
+    float* vertices = Lock(first);
+    QuadWriter::Write(
+      vertices, corners, texture, depth, Ogre::ColourValue(intensity, intensity, intensity, 1)
+    );
+    buffer_->unlock();
+    operation_.vertexData->vertexCount += QuadWriter::VERTEX_COUNT;
+    return first;
+}
+
+void BackgroundTileBuffer::SetPositions(
+  const unsigned int first_vertex, const QuadWriter::Corners& corners
+){
+    QuadWriter::SetPositions(Lock(first_vertex), corners);
+    buffer_->unlock();
+}
+
+void BackgroundTileBuffer::SetTexture(
+  const unsigned int first_vertex, const QuadWriter::Rectangle& texture
+){
+    QuadWriter::SetTexture(Lock(first_vertex), texture);
+    buffer_->unlock();
+}
+
+bool BackgroundTileBuffer::IsEmpty() const{return operation_.vertexData->vertexCount == 0;}
+
+void BackgroundTileBuffer::Draw(
+  Ogre::SceneManager& scene_manager, Ogre::RenderSystem& render_system
+){
+    scene_manager._setPass(material_->getTechnique(0)->getPass(0), true, false);
+    render_system._render(operation_);
+}
+
+void BackgroundTileBuffer::Draw(
+  Ogre::SceneManager& scene_manager, Ogre::RenderSystem& render_system,
+  const BackgroundLayerRanges::Range& range
+){
+    const size_t total = operation_.vertexData->vertexCount;
+    operation_.vertexData->vertexStart = range.first;
+    operation_.vertexData->vertexCount = range.count;
+    Draw(scene_manager, render_system);
+    operation_.vertexData->vertexStart = 0;
+    operation_.vertexData->vertexCount = total;
+}
+
+void BackgroundTileBuffer::CreateBuffer(){
+    buffer_ = QuadWriter::CreateBuffer(operation_, max_tiles_ * QuadWriter::VERTEX_COUNT);
+    operation_.vertexData->vertexCount = 0;
+}
+
+void BackgroundTileBuffer::DestroyBuffer(){
+    delete operation_.vertexData;
+    operation_.vertexData = nullptr;
+    buffer_.reset();
+}
+
+float* BackgroundTileBuffer::Lock(const unsigned int first_vertex){
+    return static_cast<float*>(buffer_->lock(Ogre::HardwareBuffer::HBL_NORMAL))
+      + first_vertex * QuadWriter::VERTEX_SIZE;
+}

+ 232 - 0
src/engine/graphics/BackgroundTileBuffer.h

@@ -0,0 +1,232 @@
+/*
+ * 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 <OgreHardwareVertexBuffer.h>
+#include <OgreMaterial.h>
+#include <OgreRenderOperation.h>
+#include <OgreRenderSystem.h>
+#include <OgreSceneManager.h>
+#include "formats/field/Background2DFile.h"
+#include "QuadWriter.h"
+
+/**
+ * Where the tiles of each layer are in a vertex buffer.
+ *
+ * It's only useful if the tiles of a layer are together, one layer after the other, which is how
+ * the installer writes them.
+ */
+class BackgroundLayerRanges{
+
+    public:
+
+        /**
+         * The number of layers of a background.
+         */
+        static const int LAYER_COUNT = 4;
+
+        /**
+         * Part of a vertex buffer that has the tiles of a layer.
+         */
+        struct Range{
+
+            /** First vertex. */
+            unsigned int first = 0;
+
+            /** Number of vertices. */
+            unsigned int count = 0;
+        };
+
+        /**
+         * Constructor.
+         */
+        BackgroundLayerRanges(){Clear();}
+
+        /**
+         * Forgets all the tiles.
+         */
+        void Clear();
+
+        /**
+         * Records the vertices of a tile.
+         *
+         * @param[in] layer Layer of the tile. Out of range layers count as the nearest one.
+         * @param[in] first First vertex of the tile.
+         * @param[in] count Number of vertices of the tile.
+         */
+        void Add(const int layer, const unsigned int first, const unsigned int count);
+
+        /**
+         * Checks if the tiles of the layers are together.
+         */
+        bool AreContiguous() const{return contiguous_;}
+
+        /**
+         * Retrieves the vertices of a layer.
+         *
+         * @param[in] layer The layer, from 0 to LAYER_COUNT - 1.
+         */
+        const Range& Of(const int layer) const{return ranges_[layer];}
+
+    private:
+
+        /** The vertices of each layer. */
+        Range ranges_[LAYER_COUNT];
+
+        /** The last layer a tile has been added to. */
+        int last_layer_;
+
+        /** If the tiles of the layers are together. */
+        bool contiguous_;
+};
+
+/**
+ * The tiles of a field background that are blended in the same way: their vertex buffer and the
+ * material they are drawn with.
+ */
+class BackgroundTileBuffer{
+
+    public:
+
+        /**
+         * Constructor. Creates the material and the vertex buffer.
+         *
+         * @param[in] blending How the tiles are blended.
+         * @param[in] material_name Name of the material.
+         * @param[in] max_tiles Number of tiles that fit in the buffer.
+         */
+        BackgroundTileBuffer(
+          const VGears::Blending blending, const Ogre::String& material_name,
+          const unsigned int max_tiles
+        );
+
+        /**
+         * Destructor.
+         */
+        ~BackgroundTileBuffer();
+
+        /**
+         * Removes all the tiles.
+         */
+        void Clear();
+
+        /**
+         * Sets the image of the tiles.
+         *
+         * @param[in] image Name of the image.
+         */
+        void SetImage(const Ogre::String& image);
+
+        /**
+         * Checks if no more tiles fit.
+         */
+        bool IsFull() const;
+
+        /**
+         * Retrieves the number of tiles that fit in the buffer.
+         */
+        unsigned int MaxTiles() const{return max_tiles_;}
+
+        /**
+         * Adds a tile. The buffer must not be full.
+         *
+         * @param[in] corners Corners of the tile.
+         * @param[in] texture Part of the image of the tile.
+         * @param[in] depth Depth of the tile.
+         * @param[in] intensity Part of the colour of the image that is used.
+         * @param[in] layer Layer of the tile.
+         * @return The first vertex of the tile.
+         */
+        unsigned int Add(
+          const QuadWriter::Corners& corners, const QuadWriter::Rectangle& texture,
+          const float depth, const float intensity, const int layer
+        );
+
+        /**
+         * Moves a tile.
+         *
+         * @param[in] first_vertex First vertex of the tile.
+         * @param[in] corners The new corners.
+         */
+        void SetPositions(const unsigned int first_vertex, const QuadWriter::Corners& corners);
+
+        /**
+         * Changes the part of the image of a tile.
+         *
+         * @param[in] first_vertex First vertex of the tile.
+         * @param[in] texture The new part of the image.
+         */
+        void SetTexture(const unsigned int first_vertex, const QuadWriter::Rectangle& texture);
+
+        /**
+         * Checks if there are no tiles.
+         */
+        bool IsEmpty() const;
+
+        /**
+         * Retrieves where the tiles of each layer are.
+         */
+        const BackgroundLayerRanges& Layers() const{return layers_;}
+
+        /**
+         * Draws all the tiles.
+         */
+        void Draw(Ogre::SceneManager& scene_manager, Ogre::RenderSystem& render_system);
+
+        /**
+         * Draws some of the tiles.
+         *
+         * @param[in] range The vertices to draw.
+         */
+        void Draw(
+          Ogre::SceneManager& scene_manager, Ogre::RenderSystem& render_system,
+          const BackgroundLayerRanges::Range& range
+        );
+
+    private:
+
+        /**
+         * Creates the vertex buffer.
+         */
+        void CreateBuffer();
+
+        /**
+         * Frees the vertex buffer.
+         */
+        void DestroyBuffer();
+
+        /**
+         * Retrieves the vertices of the buffer, which has to be unlocked afterwards.
+         *
+         * @param[in] first_vertex First vertex wanted.
+         */
+        float* Lock(const unsigned int first_vertex);
+
+        /** Number of tiles that fit in the buffer. */
+        unsigned int max_tiles_;
+
+        /** What is drawn. */
+        Ogre::RenderOperation operation_;
+
+        /** The vertex buffer. */
+        Ogre::HardwareVertexBufferSharedPtr buffer_;
+
+        /** The material. */
+        Ogre::MaterialPtr material_;
+
+        /** Where the tiles of each layer are. */
+        BackgroundLayerRanges layers_;
+};

+ 4 - 0
src/engine/graphics/CMakeLists.txt

@@ -3,11 +3,15 @@ vgears_sources(
     Background2D.cpp
     Background2D.cpp
     Background2DAnimation.cpp
     Background2DAnimation.cpp
     BackgroundPalette.cpp
     BackgroundPalette.cpp
+    BackgroundScroll.cpp
+    BackgroundShake.cpp
+    BackgroundTileBuffer.cpp
     CameraManager.cpp
     CameraManager.cpp
     DebugDraw.cpp
     DebugDraw.cpp
     MovieCameraFrame.cpp
     MovieCameraFrame.cpp
     MoviePlayer.cpp
     MoviePlayer.cpp
     MovieState.cpp
     MovieState.cpp
+    QuadWriter.cpp
     ScreenFade.cpp
     ScreenFade.cpp
     ScreenFadeState.cpp
     ScreenFadeState.cpp
 )
 )

+ 97 - 0
src/engine/graphics/QuadWriter.cpp

@@ -0,0 +1,97 @@
+/*
+ * 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 <OgreHardwareBufferManager.h>
+#include <OgreVertexIndexData.h>
+#include "QuadWriter.h"
+
+namespace{
+
+    /**
+     * The corner of each vertex of the two triangles.
+     */
+    const int CORNERS[QuadWriter::VERTEX_COUNT] = {0, 1, 2, 0, 2, 3};
+
+    /**
+     * Position of the texture coordinates in a vertex.
+     */
+    const int TEXTURE_OFFSET = 7;
+
+    /**
+     * The texture coordinates of each corner.
+     */
+    QuadWriter::Corners TextureCorners(const QuadWriter::Rectangle& texture){
+        return {{
+          {texture.left, texture.top}, {texture.right, texture.top},
+          {texture.right, texture.bottom}, {texture.left, texture.bottom}
+        }};
+    }
+}
+
+namespace QuadWriter{
+
+    Ogre::HardwareVertexBufferSharedPtr CreateBuffer(
+      Ogre::RenderOperation& operation, const unsigned int vertex_count
+    ){
+        operation.vertexData = new Ogre::VertexData;
+        operation.vertexData->vertexStart = 0;
+        Ogre::VertexDeclaration* declaration = operation.vertexData->vertexDeclaration;
+        size_t offset = 0;
+        declaration->addElement(0, offset, Ogre::VET_FLOAT3, Ogre::VES_POSITION);
+        offset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT3);
+        declaration->addElement(0, offset, Ogre::VET_FLOAT4, Ogre::VES_DIFFUSE);
+        offset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT4);
+        declaration->addElement(0, offset, Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES);
+        Ogre::HardwareVertexBufferSharedPtr buffer
+          = Ogre::HardwareBufferManager::getSingletonPtr()->createVertexBuffer(
+            declaration->getVertexSize(0), vertex_count,
+            Ogre::HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY, false
+          );
+        operation.vertexData->vertexBufferBinding->setBinding(0, buffer);
+        operation.operationType = Ogre::RenderOperation::OT_TRIANGLE_LIST;
+        operation.useIndexes = false;
+        return buffer;
+    }
+
+    void Write(
+      float*& vertices, const Corners& corners, const Rectangle& texture, const float depth,
+      const Ogre::ColourValue& colour
+    ){
+        const Corners coordinates = TextureCorners(texture);
+        for (const int corner : CORNERS){
+            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;
+        }
+    }
+
+    void SetPositions(float* vertices, const Corners& corners){
+        for (const int corner : CORNERS){
+            vertices[0] = corners[corner].x;
+            vertices[1] = corners[corner].y;
+            vertices += VERTEX_SIZE;
+        }
+    }
+
+    void SetTexture(float* vertices, const Rectangle& texture){
+        const Corners coordinates = TextureCorners(texture);
+        for (const int corner : CORNERS){
+            vertices[TEXTURE_OFFSET] = coordinates[corner].x;
+            vertices[TEXTURE_OFFSET + 1] = coordinates[corner].y;
+            vertices += VERTEX_SIZE;
+        }
+    }
+}

+ 104 - 0
src/engine/graphics/QuadWriter.h

@@ -0,0 +1,104 @@
+/*
+ * 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 <OgreColourValue.h>
+#include <OgreHardwareVertexBuffer.h>
+#include <OgreRenderOperation.h>
+#include <OgreVector2.h>
+
+/**
+ * Writes textured rectangles into vertex buffers, as two triangles each.
+ *
+ * A vertex has a position (3 values), a colour (4) and texture coordinates (2).
+ */
+namespace QuadWriter{
+
+    /**
+     * Number of values of a vertex.
+     */
+    const int VERTEX_SIZE = 9;
+
+    /**
+     * Number of vertices of a rectangle.
+     */
+    const int VERTEX_COUNT = 6;
+
+    /**
+     * A rectangle with horizontal and vertical sides.
+     */
+    struct Rectangle{
+
+        /** Left side. */
+        float left;
+
+        /** Top side. */
+        float top;
+
+        /** Right side. */
+        float right;
+
+        /** Bottom side. */
+        float bottom;
+    };
+
+    /**
+     * The top left, top right, bottom right and bottom left corners of a rectangle.
+     */
+    typedef std::array<Ogre::Vector2, 4> Corners;
+
+    /**
+     * Creates the vertex buffer of a render operation that draws rectangles.
+     *
+     * @param[out] operation The render operation. Its vertex data is created, with no vertices.
+     * @param[in] vertex_count Number of vertices that fit in the buffer.
+     * @return The buffer.
+     */
+    Ogre::HardwareVertexBufferSharedPtr CreateBuffer(
+      Ogre::RenderOperation& operation, const unsigned int vertex_count
+    );
+
+    /**
+     * Writes the vertices of a rectangle.
+     *
+     * @param[in,out] vertices Where to write them. It's moved past them.
+     * @param[in] corners Corners of the rectangle.
+     * @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.
+     */
+    void Write(
+      float*& vertices, const Corners& corners, const Rectangle& texture, const float depth,
+      const Ogre::ColourValue& colour
+    );
+
+    /**
+     * Changes the positions of the vertices of a rectangle, but not their depth.
+     *
+     * @param[in,out] vertices The first vertex of the rectangle.
+     * @param[in] corners The new corners.
+     */
+    void SetPositions(float* vertices, const Corners& corners);
+
+    /**
+     * Changes the part of the texture of a rectangle.
+     *
+     * @param[in,out] vertices The first vertex of the rectangle.
+     * @param[in] texture The new part of the texture.
+     */
+    void SetTexture(float* vertices, const Rectangle& texture);
+}

+ 5 - 18
src/engine/ui/UiTextArea.cpp

@@ -540,11 +540,11 @@ void UiTextArea::WriteCharacter(
       static_cast<float>(data.x + data.width) / width,
       static_cast<float>(data.x + data.width) / width,
       static_cast<float>(data.y + data.height) / height
       static_cast<float>(data.y + data.height) / height
     };
     };
-    const std::array<Ogre::Vector2, 4> corners = UiTextLayout::ScreenCorners(
+    const QuadWriter::Corners corners = UiTextLayout::ScreenCorners(
       box, final_translate_, final_rotation_, Ogre::Vector2(screen_width_, screen_height_)
       box, final_translate_, final_rotation_, Ogre::Vector2(screen_width_, screen_height_)
     );
     );
-    UiTextLayout::WriteQuad(vertices, corners, texture, final_z_, colour);
-    render_operation_.vertexData->vertexCount += 6;
+    QuadWriter::Write(vertices, corners, texture, final_z_, colour);
+    render_operation_.vertexData->vertexCount += QuadWriter::VERTEX_COUNT;
 }
 }
 
 
 void UiTextArea::GrowVertexBuffer(const unsigned int letters){
 void UiTextArea::GrowVertexBuffer(const unsigned int letters){
@@ -558,22 +558,9 @@ void UiTextArea::GrowVertexBuffer(const unsigned int letters){
 
 
 void UiTextArea::CreateVertexBuffer(const unsigned int letters){
 void UiTextArea::CreateVertexBuffer(const unsigned int letters){
     max_letters_ = letters;
     max_letters_ = letters;
-    render_operation_.vertexData = new Ogre::VertexData;
-    render_operation_.vertexData->vertexStart = 0;
-    Ogre::VertexDeclaration* vertex_declaration = render_operation_.vertexData->vertexDeclaration;
-    size_t offset = 0;
-    vertex_declaration->addElement(0, 0, Ogre::VET_FLOAT3, Ogre::VES_POSITION);
-    offset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT3);
-    vertex_declaration->addElement(0, offset, Ogre::VET_FLOAT4, Ogre::VES_DIFFUSE);
-    offset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT4);
-    vertex_declaration->addElement(0, offset, Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES);
-    vertex_buffer_ = Ogre::HardwareBufferManager::getSingletonPtr()->createVertexBuffer(
-      vertex_declaration->getVertexSize(0), max_letters_ * 6,
-      Ogre::HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY, false
+    vertex_buffer_ = QuadWriter::CreateBuffer(
+      render_operation_, max_letters_ * QuadWriter::VERTEX_COUNT
     );
     );
-    render_operation_.vertexData->vertexBufferBinding->setBinding(0, vertex_buffer_);
-    render_operation_.operationType = Ogre::RenderOperation::OT_TRIANGLE_LIST;
-    render_operation_.useIndexes = false;
 }
 }
 
 
 void UiTextArea::DestroyVertexBuffer(){
 void UiTextArea::DestroyVertexBuffer(){

+ 2 - 18
src/engine/ui/UiTextLayout.cpp

@@ -78,11 +78,11 @@ float UiTextLayout::TextWidth(
     return std::max(longest, width);
     return std::max(longest, width);
 }
 }
 
 
-std::array<Ogre::Vector2, 4> UiTextLayout::ScreenCorners(
+QuadWriter::Corners UiTextLayout::ScreenCorners(
   const Box& box, const Ogre::Vector2& translate, const float rotation,
   const Box& box, const Ogre::Vector2& translate, const float rotation,
   const Ogre::Vector2& screen
   const Ogre::Vector2& screen
 ){
 ){
-    std::array<Ogre::Vector2, 4> corners{{
+    QuadWriter::Corners corners{{
       {box.left, box.top}, {box.right, box.top}, {box.right, box.bottom}, {box.left, box.bottom}
       {box.left, box.top}, {box.right, box.top}, {box.right, box.bottom}, {box.left, box.bottom}
     }};
     }};
     float cos = 1;
     float cos = 1;
@@ -101,22 +101,6 @@ std::array<Ogre::Vector2, 4> UiTextLayout::ScreenCorners(
     return corners;
     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{
 float UiTextLayout::ScaleX(const float size) const{
     return size * area_.scale.x * area_.screen_height / REFERENCE_HEIGHT;
     return size * area_.scale.x * area_.screen_height / REFERENCE_HEIGHT;
 }
 }

+ 4 - 37
src/engine/ui/UiTextLayout.h

@@ -15,16 +15,15 @@
 
 
 #pragma once
 #pragma once
 
 
-#include <array>
 #include <functional>
 #include <functional>
 #include <vector>
 #include <vector>
-#include <OgreColourValue.h>
 #include <OgreVector2.h>
 #include <OgreVector2.h>
+#include "engine/graphics/QuadWriter.h"
 #include "UiFont.h"
 #include "UiFont.h"
 #include "UiTextChar.h"
 #include "UiTextChar.h"
 
 
 /**
 /**
- * Decides where the characters of a text area go, and writes their vertices.
+ * Decides where the characters of a text area go.
  *
  *
  * Positions are relative to the position of the text area, in pixels of the screen. Sizes of the
  * 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.
  * fonts, paddings and images are for a screen 720 pixels high, and are scaled to the real one.
@@ -33,11 +32,6 @@ class UiTextLayout{
 
 
     public:
     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.
          * Where a text area is, and its sizes.
          */
          */
@@ -71,20 +65,7 @@ class UiTextLayout{
         /**
         /**
          * The rectangle of a character.
          * The rectangle of a character.
          */
          */
-        struct Box{
-
-            /** Left side. */
-            float left;
-
-            /** Top side. */
-            float top;
-
-            /** Right side. */
-            float right;
-
-            /** Bottom side. */
-            float bottom;
-        };
+        typedef QuadWriter::Rectangle Box;
 
 
         /**
         /**
          * Constructor. The first character goes at the beginning of the first line.
          * Constructor. The first character goes at the beginning of the first line.
@@ -143,25 +124,11 @@ class UiTextLayout{
          * @param[in] screen Size of the screen.
          * @param[in] screen Size of the screen.
          * @return The top left, top right, bottom right and bottom left corners.
          * @return The top left, top right, bottom right and bottom left corners.
          */
          */
-        static std::array<Ogre::Vector2, 4> ScreenCorners(
+        static QuadWriter::Corners ScreenCorners(
           const Box& box, const Ogre::Vector2& translate, const float rotation,
           const Box& box, const Ogre::Vector2& translate, const float rotation,
           const Ogre::Vector2& screen
           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:
     private:
 
 
         /**
         /**

+ 148 - 0
test/engine/graphics/Background2D.cpp

@@ -0,0 +1,148 @@
+/*
+ * 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 "engine/graphics/BackgroundScroll.h"
+#include "engine/graphics/BackgroundShake.h"
+#include "engine/graphics/BackgroundTileBuffer.h"
+#include "engine/graphics/QuadWriter.h"
+
+namespace{
+
+    /**
+     * An entity pointer. The scroll only stores it.
+     */
+    Entity* FakeEntity(){
+        static int entity;
+        return reinterpret_cast<Entity*>(&entity);
+    }
+
+    Ogre::AxisAlignedBox Limits(){return Ogre::AxisAlignedBox(-10, -20, 0, 10, 20, 1);}
+}
+
+BOOST_AUTO_TEST_CASE(TestQuadWriter){
+    std::vector<float> vertices(QuadWriter::VERTEX_COUNT * QuadWriter::VERTEX_SIZE);
+    float* end = vertices.data();
+    const QuadWriter::Corners corners{{{1, 2}, {3, 4}, {5, 6}, {7, 8}}};
+    QuadWriter::Write(end, corners, {0, 0.25f, 0.5f, 0.75f}, 9, Ogre::ColourValue(1, 0, 0, 1));
+    BOOST_CHECK(end == vertices.data() + vertices.size());
+    // The vertices are the corners 0, 1, 2, 0, 2 and 3.
+    const auto vertex = [&vertices](int index){return &vertices[index * QuadWriter::VERTEX_SIZE];};
+    const float expected[] = {5, 6, 9, 1, 0, 0, 1, 0.5f, 0.75f};
+    BOOST_CHECK_EQUAL_COLLECTIONS(vertex(2), vertex(3), expected, expected + 9);
+    BOOST_CHECK_EQUAL(vertex(5)[0], 7);
+    BOOST_CHECK_EQUAL(vertex(5)[7], 0);
+    QuadWriter::SetPositions(vertices.data(), {{{10, 11}, {12, 13}, {14, 15}, {16, 17}}});
+    QuadWriter::SetTexture(vertices.data(), {1, 2, 3, 4});
+    BOOST_CHECK_EQUAL(vertex(4)[0], 14);
+    BOOST_CHECK_EQUAL(vertex(4)[2], 9);
+    BOOST_CHECK_EQUAL(vertex(4)[7], 3);
+    BOOST_CHECK_EQUAL(vertex(5)[8], 4);
+}
+
+BOOST_AUTO_TEST_CASE(TestBackgroundLayerRanges){
+    BackgroundLayerRanges ranges;
+    ranges.Add(0, 0, 6);
+    ranges.Add(0, 6, 6);
+    ranges.Add(2, 12, 6);
+    // Out of range layers count as the nearest one.
+    ranges.Add(9, 18, 6);
+    BOOST_CHECK(ranges.AreContiguous());
+    BOOST_CHECK_EQUAL(ranges.Of(0).count, 12u);
+    BOOST_CHECK_EQUAL(ranges.Of(2).first, 12u);
+    BOOST_CHECK_EQUAL(ranges.Of(3).first, 18u);
+    ranges.Add(1, 24, 6);
+    BOOST_CHECK(!ranges.AreContiguous());
+    ranges.Clear();
+    BOOST_CHECK(ranges.AreContiguous());
+    BOOST_CHECK_EQUAL(ranges.Of(0).count, 0u);
+}
+
+BOOST_AUTO_TEST_CASE(TestBackgroundShake){
+    BackgroundShake shake;
+    BOOST_CHECK(!shake.Update(0.1f));
+    BOOST_CHECK(!shake.Set(7, 1, 1, 1, 1));
+    // Horizontal, 20 pixels, bounces of one second.
+    BOOST_CHECK(shake.Set(1, 20, 30, 0, 0));
+    BOOST_CHECK(shake.Update(1.0f));
+    // The first bounce goes to half the amplitude times the first factor, -1.
+    BOOST_CHECK_CLOSE(shake.Offset().x, -10.0f, 0.001f);
+    BOOST_CHECK_EQUAL(shake.Offset().y, 0);
+    // To stop, it ends the bounce, goes back to the center and stays there.
+    BOOST_CHECK(shake.Set(0, 0, 30, 0, 30));
+    shake.Update(1.0f);
+    shake.Update(1.0f);
+    BOOST_CHECK_EQUAL(shake.Offset().x, 0);
+    BOOST_CHECK(!shake.IsRunning());
+}
+
+BOOST_AUTO_TEST_CASE(TestBackgroundScrollLimits){
+    BackgroundScroll scroll([](const ScriptId&){});
+    scroll.SetRange(Limits());
+    scroll.SetPosition({100, -100});
+    BOOST_CHECK(scroll.Position() == Ogre::Vector2(10, -20));
+    BOOST_CHECK(!scroll.HasControl());
+    // A scroll of a script to a position is not limited, and an instant one waits.
+    scroll.ToPosition({100, -100}, BackgroundScroll::NONE, 0);
+    BOOST_CHECK(scroll.HasControl());
+    BOOST_CHECK(scroll.Position() == Ogre::Vector2(10, -20));
+    BOOST_CHECK(scroll.ApplyPending());
+    BOOST_CHECK(scroll.Position() == Ogre::Vector2(100, -100));
+    BOOST_CHECK(!scroll.ApplyPending());
+    // Following an entity limits it again.
+    scroll.Follow(FakeEntity());
+    scroll.SetPosition({100, 0});
+    BOOST_CHECK(scroll.Position() == Ogre::Vector2(10, 0));
+}
+
+BOOST_AUTO_TEST_CASE(TestBackgroundScrollToAnEntity){
+    std::vector<std::string> resumed;
+    BackgroundScroll scroll([&resumed](const ScriptId& script){resumed.push_back(script.entity);});
+    scroll.SetRange(Limits());
+    BOOST_CHECK(!scroll.Wait(ScriptId()));
+    BOOST_CHECK(!scroll.ToEntity(FakeEntity(), {50, 5}, BackgroundScroll::LINEAR, 2));
+    BOOST_CHECK(scroll.End() == Ogre::Vector2(10, 5));
+    BOOST_CHECK(scroll.TargetEntity() == FakeEntity());
+    BOOST_CHECK(scroll.FollowedEntity() == nullptr);
+    ScriptId script;
+    script.entity = "cloud";
+    BOOST_CHECK(scroll.Wait(script));
+    scroll.Stop();
+    BOOST_CHECK(scroll.FollowedEntity() == FakeEntity());
+    BOOST_CHECK_EQUAL(scroll.Type(), BackgroundScroll::NONE);
+    BOOST_REQUIRE_EQUAL(resumed.size(), 1u);
+    BOOST_CHECK_EQUAL(resumed[0], "cloud");
+    // An instant scroll moves at once and follows the entity.
+    BOOST_CHECK(scroll.ToEntity(FakeEntity(), {-50, 0}, BackgroundScroll::NONE, 0));
+    BOOST_CHECK(scroll.Position() == Ogre::Vector2(-10, 0));
+    BOOST_CHECK(scroll.FollowedEntity() == FakeEntity());
+}
+
+BOOST_AUTO_TEST_CASE(TestBackgroundScrollReplacedAndCleared){
+    int resumed = 0;
+    BackgroundScroll scroll([&resumed](const ScriptId&){++ resumed;});
+    scroll.ToEntity(FakeEntity(), {5, 5}, BackgroundScroll::SMOOTH, 1);
+    scroll.Wait(ScriptId());
+    // A new scroll ends the previous one without following its entity.
+    scroll.ToPosition({1, 1}, BackgroundScroll::LINEAR, 1);
+    BOOST_CHECK_EQUAL(resumed, 1);
+    BOOST_CHECK(scroll.FollowedEntity() == nullptr);
+    BOOST_CHECK(scroll.TargetEntity() == nullptr);
+    scroll.Wait(ScriptId());
+    scroll.Clear();
+    BOOST_CHECK_EQUAL(resumed, 2);
+    BOOST_CHECK(!scroll.HasControl());
+    BOOST_CHECK(scroll.Position() == Ogre::Vector2::ZERO);
+}

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

@@ -1,5 +1,6 @@
 # Tests of this folder (see vgears_tests and vgears_installer_tests in test/CMakeLists.txt).
 # Tests of this folder (see vgears_tests and vgears_installer_tests in test/CMakeLists.txt).
 vgears_tests(
 vgears_tests(
+    Background2D.cpp
     MovieCameraFrame.cpp
     MovieCameraFrame.cpp
     MovieState.cpp
     MovieState.cpp
     ScreenFadeState.cpp
     ScreenFadeState.cpp

+ 1 - 11
test/engine/ui/UiText.cpp

@@ -139,7 +139,7 @@ BOOST_AUTO_TEST_CASE(TestUiTextLayoutWrapsAndStopsAtTheBottom){
     BOOST_CHECK(!layout.Place(Glyph('d'), box));
     BOOST_CHECK(!layout.Place(Glyph('d'), box));
 }
 }
 
 
-BOOST_AUTO_TEST_CASE(TestUiTextLayoutWidthAndVertices){
+BOOST_AUTO_TEST_CASE(TestUiTextLayoutWidthAndCorners){
     const std::vector<TextChar> text = Parse("ab\nabc");
     const std::vector<TextChar> text = Parse("ab\nabc");
     BOOST_CHECK_EQUAL(UiTextLayout::TextWidth(text, Glyph), 30);
     BOOST_CHECK_EQUAL(UiTextLayout::TextWidth(text, Glyph), 30);
     const auto corners = UiTextLayout::ScreenCorners(
     const auto corners = UiTextLayout::ScreenCorners(
@@ -148,14 +148,4 @@ BOOST_AUTO_TEST_CASE(TestUiTextLayoutWidthAndVertices){
     BOOST_CHECK_CLOSE(corners[0].x, -0.8f, 0.001f);
     BOOST_CHECK_CLOSE(corners[0].x, -0.8f, 0.001f);
     BOOST_CHECK_CLOSE(corners[0].y, 0.6f, 0.001f);
     BOOST_CHECK_CLOSE(corners[0].y, 0.6f, 0.001f);
     BOOST_CHECK_CLOSE(corners[2].x, -0.4f, 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);
 }
 }