Przeglądaj źródła

Improve field module: decompiler fixes, camera, fades, dialogs and party requests

Decompiler / installer
- Handle model-less entities (Director, AD, MES) so model opcodes are harmless, skipping names that aren't valid Lua identifiers.
- Fix LSTMP: store Data.PreviousFieldId (set from each script header) and guard against a bank-0 destination
- Detect scripts that fall through into the next one and emit an explicit call to it
- Add PREQ/PRQSW/PRQEW (party_request) and CKITM (key item check)
- Director: use the entity named "cloud" for place_player_at_map_entry and autoscroll
- Fix text colour tags left open at the end of a dialog

Engine
- Background2D: scripted scrolls are unclamped, entity-following scrolls clamp to the range; add BackgroundPalette
- Set player entity: move autoscroll to the new player and copy the previous player's position when the new one has none
- Entity: hold single-frame animations and cancel a running offset on AT_NONE
- ScreenFade: fix additive fade type 6
- Dialogs: timer window rendering and padding
- AudioManager: skip movies that have no sound file quietly
- play_sounds binding takes optional arguments

Lua
- field.lua: nil guard in place_player_at_map_entry, party_request helper, fix the map-change race where a request made on a field's first frame was erased
- system.lua: NullEntity, and Timer updates the dialog
Iñigo Valentin 6 godzin temu
rodzic
commit
9f4521de9b
61 zmienionych plików z 1878 dodań i 179 usunięć
  1. 76 8
      data/data/scripts/field.lua
  2. 50 0
      data/data/scripts/system.lua
  3. 2 0
      doc/INSTALL_DATA.md
  4. 55 0
      doc/TODO.md
  5. 1 0
      src/CMakeLists.txt
  6. 17 0
      src/core/AudioManager.cpp
  7. 16 0
      src/core/AudioManager.h
  8. 95 5
      src/core/Background2D.cpp
  9. 59 0
      src/core/Background2D.h
  10. 247 0
      src/core/BackgroundPalette.cpp
  11. 167 0
      src/core/BackgroundPalette.h
  12. 4 2
      src/core/DebugDraw.cpp
  13. 15 0
      src/core/DebugDraw.h
  14. 27 11
      src/core/DialogsManager.cpp
  15. 3 0
      src/core/DialogsManager.h
  16. 13 7
      src/core/Entity.cpp
  17. 25 0
      src/core/Entity.h
  18. 62 8
      src/core/EntityManager.cpp
  19. 26 0
      src/core/EntityManager.h
  20. 5 0
      src/core/EntityModel.cpp
  21. 4 1
      src/core/ScreenFadeState.cpp
  22. 17 1
      src/core/ScriptManager.cpp
  23. 17 1
      src/core/ScriptManagerBinds.h
  24. 3 0
      src/core/XmlBackground2DFile.cpp
  25. 34 2
      src/data/VGearsBackgroundFile.cpp
  26. 46 0
      src/data/VGearsBackgroundFile.h
  27. 8 0
      src/data/VGearsTriggersFile.h
  28. 71 45
      src/installer/ExternalTools.cpp
  29. 14 0
      src/installer/ExternalTools.h
  30. 199 18
      src/installer/FieldDataInstaller.cpp
  31. 1 1
      src/installer/FieldDataInstaller.h
  32. 12 1
      src/installer/FieldTextWriter.cpp
  33. 41 3
      src/installer/decompiler/field/FieldCodeGenerator.cpp
  34. 9 0
      src/installer/decompiler/field/FieldCodeGenerator.h
  35. 2 0
      src/installer/decompiler/field/FieldDecompiler.cpp
  36. 17 0
      src/installer/decompiler/field/FieldDecompiler.h
  37. 20 0
      src/installer/decompiler/field/FieldDisassembler.cpp
  38. 5 0
      src/installer/decompiler/field/FieldDisassembler.h
  39. 23 0
      src/installer/decompiler/field/FieldEngine.cpp
  40. 60 0
      src/installer/decompiler/field/FieldEngine.h
  41. 68 26
      src/installer/decompiler/field/instruction/FieldBackgroundInstruction.cpp
  42. 2 1
      src/installer/decompiler/field/instruction/FieldBackgroundInstruction.h
  43. 17 3
      src/installer/decompiler/field/instruction/FieldControlFlowInstruction.cpp
  44. 1 0
      src/installer/decompiler/field/instruction/FieldControlFlowInstruction.h
  45. 35 12
      src/installer/decompiler/field/instruction/FieldMathInstruction.cpp
  46. 2 0
      src/installer/decompiler/field/instruction/FieldMathInstruction.h
  47. 24 2
      src/installer/decompiler/field/instruction/FieldMediaInstruction.cpp
  48. 4 0
      src/installer/decompiler/field/instruction/FieldMediaInstruction.h
  49. 56 10
      src/installer/decompiler/field/instruction/FieldModelInstruction.cpp
  50. 2 0
      src/installer/decompiler/field/instruction/FieldModelInstruction.h
  51. 18 1
      src/installer/decompiler/field/instruction/FieldModuleInstruction.cpp
  52. 1 0
      src/installer/decompiler/field/instruction/FieldModuleInstruction.h
  53. 8 2
      src/installer/decompiler/field/instruction/FieldPartyInstruction.cpp
  54. 7 1
      src/installer/decompiler/field/instruction/FieldWalkmeshInstruction.cpp
  55. 17 2
      src/installer/decompiler/field/instruction/FieldWindowInstruction.cpp
  56. 2 0
      src/installer/decompiler/field/instruction/FieldWindowInstruction.h
  57. 5 0
      src/map/VGearsBackground2DFile.cpp
  58. 19 0
      src/map/VGearsBackground2DFile.h
  59. 3 0
      src/map/VGearsBackground2DFileXMLSerializer.cpp
  60. 5 5
      test/core/ScreenFadeState.cpp
  61. 14 0
      test/installer/ExternalTools.cpp

+ 76 - 8
data/data/scripts/field.lua

@@ -66,10 +66,14 @@ place_player_at_map_entry = function(entity_name)
             local x, y, z = point:get_position()
             local rotation = point:get_rotation()
             local player = entity_manager:get_entity(entity_name)
-            player:set_position(x, y, z)
-            player:set_rotation(rotation)
-            player:set_solid(true)
-            player:set_visible(true)
+            if player ~= nil then
+                player:set_position(x, y, z)
+                player:set_rotation(rotation)
+                player:set_solid(true)
+                player:set_visible(true)
+            else
+                print("place_player_at_map_entry: there is no entity '" .. entity_name .. "'.")
+            end
         end
     end
 
@@ -93,6 +97,20 @@ set_entity_to_character = function(entity_name, character_id)
         place_player_at_map_entry(entity_name)
     end
     entity_manager:set_entity_to_character(entity_name, character_id)
+    -- The model of a playable character is shown only if it is the leader of the party. The other
+    -- members are not drawn following the leader (join_party hides them too), and the scenes show
+    -- their models when they need them. Models are visible by default, so the ones of the
+    -- characters that are not the leader, such as Cid in mds6_1 or Aerith in mrkt2 after the
+    -- first scene, have to be hidden here. With no party at all (a new game that has not set it
+    -- yet) nothing is hidden.
+    if character_id ~= Party[1] and entity_name ~= "" and Party[1] ~= nil then
+        local entity = entity_manager:get_entity(entity_name)
+        if entity ~= nil then
+            entity:set_visible(false)
+            entity:set_solid(false)
+            entity:set_talkable(false)
+        end
+    end
 end
 
 --- Joins the party members in the field.
@@ -317,6 +335,29 @@ play_map_music = function(id)
     end
 end
 
+--- Changes the music of the field to one of its tracks (CMUSC).
+--
+-- The original opcode can fade the current music out and the new one in. Here the change is at once:
+-- a track that is changed without fades (the usual jingle of an inn) is played once, so the script
+-- that waits for the music to end (CHMST) goes on; one with fades is played looped.
+-- TODO: Implement the fades.
+--
+-- @param id ID of the track in the field.
+-- @param fade_out Fade out parameter of the original opcode (20 means no fade).
+-- @param fade_in Fade in parameter of the original opcode (0 means no fade).
+change_map_music = function(id, fade_out, fade_in)
+    local track_id = audio_manager:get_track_id(id)
+    if track_id == -1 then
+        print("Requested non-existent music track ID " .. tostring(id))
+        return
+    end
+    if fade_in == 0 then
+        audio_manager:play_music_once(tostring(track_id))
+    else
+        audio_manager:play_music(tostring(track_id))
+    end
+end
+
 --- Sets the map name
 --
 -- It's not set from a literal text, but from a dialog identifier.
@@ -364,18 +405,21 @@ System["MapChanger"] = {
     --- Jumps to a new map.
     ffvii_field = function(self)
         if self.map_name ~= "" then
+            local target = self.map_name
             player_lock(true) -- disable menu and pc movement while load map
             script:request_end_sync(Script.UI, "Fade", "fade_out", 0)
             -- The fields go to the world map as "wm<n>", n being the FIELD.TBL record of the exit.
-            local world_record = tonumber(string.match(self.map_name, "^wm(%d+)$"))
+            local world_record = tonumber(string.match(target, "^wm(%d+)$"))
             if world_record then
                 enter_world_map(world_record, self.point_name)
             else
-                map(self.map_name)
+                map(target)
             end
             player_lock(false) -- enable menu and pc movement after load map
-            self.current_map_name = self.map_name
-            self.map_name = ""
+            self.current_map_name = target
+            -- A field can ask for another change as soon as it starts (blin60_1 goes on to
+            -- blin60_2 at once). That request must not be erased here.
+            if self.map_name == target then self.map_name = "" end
             script:request_end_sync(Script.UI, "Fade", "fade_in", 0)
         end
         return 0
@@ -400,3 +444,27 @@ System["MapChanger"] = {
         return 0
     end,
 }
+
+
+--- Runs a script of the entity of a character (the PREQ, PRQSW and PRQEW opcodes).
+--
+-- @param character ID of the character, the one that the entity was given with the PC opcode.
+-- @param script_name Name of the script function.
+-- @param priority Priority of the script.
+-- @param mode "request" does not wait, "start_sync" waits for the script to start and "end_sync" for
+-- it to end.
+party_request = function(character, script_name, priority, mode)
+    local entity = entity_manager:get_entity_from_character_id(character)
+    if entity == nil then
+        print("party_request: there is no entity for the character " .. tostring(character) .. ".")
+        return
+    end
+    local name = entity:get_name()
+    if mode == "start_sync" then
+        script:request_start_sync(Script.ENTITY, name, script_name, priority)
+    elseif mode == "end_sync" then
+        script:request_end_sync(Script.ENTITY, name, script_name, priority)
+    else
+        script:request(Script.ENTITY, name, script_name, priority)
+    end
+end

+ 50 - 0
data/data/scripts/system.lua

@@ -45,6 +45,10 @@ System = {
     end
 }
 
+--- Stands for the model of the script entities that have none: the opcodes that move or hide a
+-- model are run by them in the original game and do nothing. Any method called on it is ignored.
+NullEntity = setmetatable({}, {__index = function() return function() end end})
+
 Timer = {
     -- TODO When the game clock is implemented, dont use FPS, call this every second.
     FPS = 250,
@@ -69,6 +73,7 @@ Timer = {
     set = function(time)
         Timer.time = tonumber(time)
         Timer.frames = Timer.FPS
+        dialog:update_timer(Timer.time)
         Banks[1][20]--[[timer_hours]] = math.floor(Timer.time / 3600)
         Banks[1][21]--[[timer_minutes]] = math.floor(Timer.time / 60) % 60
         Banks[1][22]--[[timer_seconds]] = Timer.time % 60
@@ -111,6 +116,20 @@ export_party_members = function()
     text_manager:set_party(c1, c2, c3)
 end
 
+--- Restores the HP and MP of every character, also the ones that are not in the party, and clears
+-- their status (MHMMX).
+restore_all_characters = function()
+    for id, character in pairs(Characters) do
+        if type(id) == "number" and type(character) == "table" and character.stats ~= nil
+          and character.stats.hp ~= nil and character.stats.mp ~= nil then
+            Characters.recalculate_stats(id)
+            character.stats.hp.current = character.stats.hp.max
+            character.stats.mp.current = character.stats.mp.max
+            character.status = {}
+        end
+    end
+end
+
 --- Sets the current party.
 --
 -- @param character1 The first member character ID, the party leader.
@@ -238,6 +257,27 @@ get_character_enable = function(character)
     return Characters[character].enabled;
 end
 
+--- Checks if a character is in the current party (IFPRTYQ).
+--
+-- @param character ID of the character to check.
+-- @return True if the character is in one of the party slots.
+IFPRTYQ = function(character)
+    for i = 1, 3 do
+        if Party[i] == character then return true end
+    end
+    return false
+end
+
+--- Checks if a character is available as a party member (IFMEMBQ).
+--
+-- A character is available when it is enabled in the PHS, whether it is in the party or not.
+--
+-- @param character ID of the character to check.
+-- @return True if the character is enabled.
+IFMEMBQ = function(character)
+    return Characters[character] ~= nil and Characters[character].enabled == true
+end
+
 --- Adds items to the inventory.
 --
 -- Inventory quantities will be capped at 99.
@@ -781,6 +821,16 @@ Party.steal_materia = function()
     -- TODO: How is this reversed?
 end
 
+--- Integer division of the field scripts (DIV, DIV2).
+--
+-- @param a Dividend.
+-- @param b Divisor. The result is the dividend if it is zero.
+-- @return The integer part of a / b.
+function math_div(a, b)
+    if b == 0 then return a end
+    return math.floor(a / b)
+end
+
 --- Implementation of OR bit operation.
 --
 -- @param a First operand.

+ 2 - 0
doc/INSTALL_DATA.md

@@ -13,6 +13,8 @@ The installer converts the sound effects, the music and the videos with two exte
 - [FFmpeg](https://ffmpeg.org/download.html "FFmpeg") converts the sound effects, encodes the music and converts the videos.
 - [TiMidity](https://timidity.sourceforge.net/#download "TiMidity") plays the original MIDI music so FFmpeg can encode it. Only the music needs it.
 
+The silence at the end of each music track (the reverberation that TiMidity renders after the last note) is removed when the music is encoded. The scripts that wait for a track to end, such as the jingle of the inns, would wait for it otherwise, and the files are smaller.
+
 You don't have to configure anything if they are installed. The installer looks for them, in this order:
 
 1. The program you chose with **Locate…**. The choice is remembered.

+ 55 - 0
doc/TODO.md

@@ -46,3 +46,58 @@ texture), so the frustum culling skips the ones that are out of view, and measur
 afterwards, because it can grow. Loading and unloading blocks around the player is the next step after
 that, but the whole map fits in memory, so it should only be for the load time. The 6 alternate blocks of
 WM0 (story shapes) are not loaded now and would have to be handled.
+
+## Field: black corners of diagonal backgrounds (mds5_3)
+
+In mds5_3 the top-right (and bottom-left) corner of the screen can show black when the player walks
+near the edge. The data is the same as in the original: layer 0 has 777 sprites in a diagonal band of
+816x432 pixels, layer 1 has 531 sprites, layers 2 and 3 are disabled, and the installed `bg.xml` keeps all
+of them. The camera range (from the trigger data) is the full rectangle around the art, so the camera can
+reach the unpainted corners.
+
+Not known: whether the original game shows the same black corner. It was left as it is. If it needs a fix,
+shrink the camera range of such fields so the screen never shows the empty tiles, but that would differ
+from the original camera. Other fields with diagonal art may be affected too.
+
+## Field: palette animations that are not implemented
+
+The palette opcodes that fields use for waterfalls, lights and fades are implemented (`STPAL`, `LDPAL`,
+`CPPAL`, `ADPAL`, `MPPAL`, `MPPAL2`): the installer writes `palette.bin` for the fields whose script loads
+colors into a palette (`LDPAL`), and the engine paints the tiles of those palettes again (see
+`BackgroundPalette`). These are still comments in the generated scripts: `STPLS` and `LDPLS` (partial
+palettes, 5 uses), `CPPAL2` (8), `ADPAL2` (22), `RTPAL` (1) and `RTPAL2` (0). Their handlers are in
+ff7.exe next to the others (0x61a9b8, 0x61ab52, 0x61ad32, 0x61b3e9, 0x61ae43, 0x61af9c).
+
+Not checked in the game for every field: the opcode arithmetic comes from the exe, but only the
+waterfall of eals_1 was used as a test. The first palette page may not be the "VRAM palette id" in
+every field (it is assumed that the id is the index of the page in the field palette file).
+
+## Field: opcodes that are still not complete
+
+- `KAWAI` (eyes, transparency, light, shine...) and `KAWIW`: none of the `KAWAI` operations is implemented (for example `EYETX`, which closes and opens the eyes of the models in ealin_2), so `KAWIW` has nothing to wait for. The converted models may not even keep the eye textures.
+- `CMUSC` changes the music at once. The original fades the current music out and the new one in (the fade parameters are in the call, see `change_map_music`). A change without fades is played once so the `CHMST` loops that wait for it end, which is what the inns need, but a change that should stay would be played once too.
+- `SLIP` is implemented for the player only, as "do not slide along the wall when the move is blocked".
+- Scripts that read the Cancel button (key 64) also see it pressed while the "run" key is held (see `EntityManager::IsKeyOn`).
+
+## Field: dialog text codes that are not converted
+
+The variable code (`FE DE`, a number given by `MPARA` or `MPRA2`) is implemented. These codes still show as
+`[MISSING 0xFE xx]` in the converted dialogs: `E1` (about 30 uses, it looks like a tab or spacing, as in
+"Current GP[E1] GP"), `E2` (7 uses, button icons, followed by characters such as `@#&`) and `E9` (32 uses,
+it looks like a spacer, as in "1BET [E9]100[E9]gil"). Their meaning has not been checked. No documentation
+for them was found.
+
+## Field: colne_3, the guards can trap the player
+
+After the cutscene the guards (ZAKOB, ZAKOc, ZAKOD, ZAKOE) chase the player with the original loop (move
+to the player, repeat) until the scene ends, which is intended: the way out is to talk to three of them
+and then to SOTCH. Their speed was measured (about 0.22 units/s against 0.7 of the player walking), so
+they should not catch a moving player, but the player has been trapped a couple of times in the game
+(probably surrounded by solid models). Left as is. If it is looked at again: check how the player
+collides with several solid NPCs that stop around it (`CheckSolidCollisions`).
+
+## Field: pillar_3, Ren not visible (to test)
+
+The model of Ren was invisible. The probable cause (an instant `OFST` did not cancel a running smooth
+offset, so Ren stayed 4 units away) was fixed in `Entity::ScriptOffsetToPosition`, but it has not been
+tested in the game. Check the helicopter intro of pillar_3 and that Ren appears and jumps down.

+ 1 - 0
src/CMakeLists.txt

@@ -602,6 +602,7 @@ set(VGEARS_SOURCE_FILES
     core/AudioManager.cpp
     core/Background2DAnimation.cpp
     core/Background2D.cpp
+    core/BackgroundPalette.cpp
     core/ScreenFade.cpp
     core/MovieCameraFrame.cpp
     core/MoviePlayer.cpp

+ 17 - 0
src/core/AudioManager.cpp

@@ -13,6 +13,7 @@
  * GNU General Public License for more details.
  */
 
+#include <boost/filesystem.hpp>
 #include <algorithm>
 #include <iostream>
 #include <list>
@@ -172,6 +173,12 @@ void AudioManager::ScriptPlayMusicOnce(const char* name){
     }
 }
 
+bool AudioManager::ScriptIsMusicPlaying(){
+    if (!initialized_) return false;
+    boost::recursive_mutex::scoped_lock lock(update_mutex_);
+    return (module_ == Module::BATTLE ? battle_music_ : music_).IsPlaying();
+}
+
 void AudioManager::EndBattleMusic(){
     if (!initialized_) return;
     boost::recursive_mutex::scoped_lock lock(update_mutex_);
@@ -195,6 +202,11 @@ void AudioManager::SoundPlay(const Ogre::String& name){
 void AudioManager::MoviePlay(const Ogre::String& file){
     if (!initialized_) return;
     boost::recursive_mutex::scoped_lock lock(update_mutex_);
+    // Some movies have no sound: nothing to play, and it is not an error.
+    if (!boost::filesystem::exists(file.c_str())){
+        LOG_TRIVIAL("The movie \"" + file + "\" has no sound.");
+        return;
+    }
     movie_.SetLoop(-1);
     movie_.Play(file);
 }
@@ -523,6 +535,11 @@ ALsizei AudioManager::Player::FillBuffer(){
     return read;
 }
 
+bool AudioManager::Player::IsPlaying(){
+    boost::recursive_mutex::scoped_lock lock(*update_mutex_);
+    return !file_.empty();
+}
+
 float AudioManager::Player::GetPosition(){
     boost::recursive_mutex::scoped_lock lock(*update_mutex_);
     int play_offset = 0;

+ 16 - 0
src/core/AudioManager.h

@@ -304,6 +304,15 @@ class AudioManager : public Manager, public Ogre::Singleton<AudioManager>{
          */
         void ScriptPlayMusicOnce(const char* name);
 
+        /**
+         * Checks if the music of the current module is playing.
+         *
+         * It is false when there is no music, or when a track that was played once has ended.
+         *
+         * @return True if music is playing.
+         */
+        bool ScriptIsMusicPlaying();
+
         /**
          * Sets the volume of the music (field, battle and world tracks) and of the audio of the
          * movies.
@@ -407,6 +416,13 @@ class AudioManager : public Manager, public Ogre::Singleton<AudioManager>{
                  */
                 float GetPosition();
 
+                /**
+                 * Checks if the player has a track that has not ended.
+                 *
+                 * @return True if it is playing (or paused).
+                 */
+                bool IsPlaying();
+
             private:
 
                 /**

+ 95 - 5
src/core/Background2D.cpp

@@ -19,6 +19,8 @@
 #include <OgreException.h>
 #include <OgreViewport.h>
 #include <OgreTechnique.h>
+#include <OgreTextureManager.h>
+#include <OgreHardwarePixelBuffer.h>
 #include <algorithm>
 #include "core/Background2D.h"
 #include "core/CameraManager.h"
@@ -44,6 +46,7 @@ Background2D::Background2D():
   scroll_current_seconds_(0),
   scroll_target_entity_(nullptr),
   scroll_follow_target_(false),
+  free_scroll_(false),
   position_(Ogre::Vector2::ZERO),
   position_real_(Ogre::Vector2::ZERO),
   offset_(Ogre::Vector2::ZERO),
@@ -74,6 +77,10 @@ Background2D::Background2D():
     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);
@@ -91,6 +98,8 @@ Background2D::Background2D():
     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);
@@ -126,6 +135,7 @@ void Background2D::Update(){
         has_pending_scroll_ = false;
         SetScroll(pending_scroll_);
     }
+    UpdatePalette();
     UpdateShake(Timer::getSingleton().GetGameTimeDelta());
     // The layers that scroll by themselves.
     for (int layer = 0; layer < LAYER_COUNT; ++ layer){
@@ -402,6 +412,64 @@ void Background2D::ScriptAreaClear(const int area){
     RefreshArea(area);
 }
 
+void Background2D::SetPalette(const Ogre::String& name){
+    if (palette_.Load(name)){
+        palette_image_loaded_ = false;
+        Ogre::LogManager::getSingleton().stream() << "Background2D: palette file loaded " << name;
+    }
+}
+
+void Background2D::ScriptPaletteStore(int page, int slot, int count){
+    palette_.Store(page, slot, count);
+}
+
+void Background2D::ScriptPaletteLoad(int slot, int page, int count){
+    palette_.Load(slot, page, count);
+}
+
+void Background2D::ScriptPaletteCopy(int source, int destination, int count){
+    palette_.Copy(source, destination, count);
+}
+
+void Background2D::ScriptPaletteMultiply(
+  int source, int destination, int start, int count, int red, int green, int blue
+){
+    palette_.Multiply(source, destination, start, count, red, green, blue);
+}
+
+void Background2D::ScriptPaletteAdd(
+  int source, int destination, int red, int green, int blue, int count
+){
+    palette_.Add(source, destination, red, green, blue, count);
+}
+
+void Background2D::UpdatePalette(){
+    if (palette_.IsEmpty() || image_name_.empty()) return;
+    if (!palette_image_loaded_){
+        try{
+            palette_image_.load(
+              image_name_, Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME
+            );
+        }
+        catch (const Ogre::Exception& e){
+            LOG_ERROR("Background palette: can't load image '" + image_name_ + "': " + e.what());
+            palette_.Clear();
+            return;
+        }
+        palette_image_loaded_ = true;
+    }
+    if (!palette_.Paint(palette_image_)) return;
+    Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(image_name_);
+    if (!texture){
+        texture = Ogre::TextureManager::getSingleton().load(
+          image_name_, Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME
+        );
+    }
+    if (texture){
+        texture->getBuffer()->blitFromMemory(palette_image_.getPixelBox());
+    }
+}
+
 void Background2D::Clear(){
     scroll_entity_ = nullptr;
     scroll_position_start_ = Ogre::Vector2::ZERO;
@@ -410,6 +478,7 @@ void Background2D::Clear(){
     scroll_current_seconds_ = 0;
     scroll_target_entity_ = nullptr;
     scroll_follow_target_ = false;
+    free_scroll_ = false;
     has_pending_scroll_ = false;
     position_ = Ogre::Vector2::ZERO;
     position_real_ = Ogre::Vector2::ZERO;
@@ -424,6 +493,8 @@ void Background2D::Clear(){
     animation_played_.clear();
     tiles_.clear();
     area_states_on_.clear();
+    palette_.Clear();
+    palette_image_loaded_ = false;
     shake_x_ = ShakeAxis();
     shake_y_ = ShakeAxis();
     shake_offset_ = Ogre::Vector2::ZERO;
@@ -431,7 +502,10 @@ void Background2D::Clear(){
     CreateVertexBuffers();
 }
 
-void Background2D::ScriptAutoScrollToEntity(Entity* entity){scroll_entity_ = entity;}
+void Background2D::ScriptAutoScrollToEntity(Entity* entity){
+    scroll_entity_ = entity;
+    free_scroll_ = false;
+}
 
 Entity* Background2D::GetAutoScrollEntity() const{return scroll_entity_;}
 
@@ -439,7 +513,10 @@ void Background2D::ScriptScrollToPlayer(const SCROLL_TYPE type, const float seco
     Entity* player = EntityManager::getSingleton().ScriptGetPlayerEntity();
     if (player == nullptr) return;
     scroll_entity_ = nullptr;
-    StartScroll(GetEntityScroll(player), type, seconds, player, type == Background2D::NONE);
+    // 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
+    // the first visit of mrkt2 does.
+    StartScroll(GetEntityScroll(player), type, seconds, player, true);
 }
 
 void Background2D::ScriptScrollToEntity(
@@ -455,7 +532,7 @@ void Background2D::ScriptScrollToEntity(
 
 void Background2D::UpdateScrollTarget(){
     if (scroll_target_entity_ != nullptr)
-        scroll_position_end_ = ClampScroll(GetEntityScroll(scroll_target_entity_));
+        scroll_position_end_ = ClampToRange(GetEntityScroll(scroll_target_entity_));
 }
 
 const Ogre::Vector2 Background2D::GetEntityScroll(const Entity* entity) const{
@@ -483,12 +560,14 @@ void Background2D::StartScroll(
     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_ = ClampScroll(position);
+    scroll_position_end_ = (target_entity != nullptr) ? ClampToRange(position) : ClampScroll(position);
     scroll_type_ = type;
     scroll_seconds_ = seconds;
     scroll_current_seconds_ = 0;
@@ -502,6 +581,7 @@ void Background2D::ScriptScrollToPosition(
       + 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
@@ -544,7 +624,10 @@ void Background2D::ScriptOffset(const float x, const float y){
 
 void Background2D::UnsetScroll(){
     scroll_type_ = Background2D::NONE;
-    if (scroll_follow_target_) scroll_entity_ = scroll_target_entity_;
+    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)
@@ -574,6 +657,10 @@ void Background2D::SetScroll(const Ogre::Vector2& position){
 }
 
 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)){
@@ -602,6 +689,8 @@ const Ogre::Vector2 Background2D::GetScreenScroll() const{return GetScroll() * s
 
 void Background2D::SetImage(const Ogre::String& image){
     Ogre::LogManager::getSingleton().stream() << "Background2D::SetImage " << image;
+    image_name_ = image;
+    palette_image_loaded_ = false;
     Ogre::Pass* pass = alpha_material_->getTechnique(0)->getPass(0);
     Ogre::TextureUnitState* tex = pass->getTextureUnitState(0);
     tex->setTextureName(image);
@@ -1096,6 +1185,7 @@ void Background2D::load(const VGears::Background2DFilePtr& background){
     assert(background != nullptr);
     background->load();
     SetImage(background->GetTextureName());
+    if (!background->GetPaletteName().empty()) SetPalette(background->GetPaletteName());
     virtual_screen_size_ = background->GetClip();
     SetRange(background->GetRange());
     const Ogre::Vector3& position(background->GetPosition());

+ 59 - 0
src/core/Background2D.h

@@ -22,6 +22,7 @@
 #include <OgreRoot.h>
 #include "map/VGearsBackground2DFile.h"
 #include "Background2DAnimation.h"
+#include "BackgroundPalette.h"
 #include "Entity.h"
 #include "ScriptManager.h"
 
@@ -347,6 +348,26 @@ class Background2D : public Ogre::RenderQueueListener{
          */
         void SetImage( const Ogre::String& image );
 
+        /**
+         * Loads the palettes of the image, if a script animates them.
+         *
+         * @param[in] name Resource name of the palette file (palette.bin of the field).
+         */
+        void SetPalette(const Ogre::String& name);
+
+        /**
+         * Palette opcodes of the scripts, see BackgroundPalette.
+         */
+        void ScriptPaletteStore(int page, int slot, int count);
+        void ScriptPaletteLoad(int slot, int page, int count);
+        void ScriptPaletteCopy(int source, int destination, int count);
+        void ScriptPaletteMultiply(
+          int source, int destination, int start, int count, int red, int green, int blue
+        );
+        void ScriptPaletteAdd(
+          int source, int destination, int red, int green, int blue, int count
+        );
+
         /**
          * Set the background scrolling range.
          *
@@ -722,6 +743,11 @@ class Background2D : public Ogre::RenderQueueListener{
          */
         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.
          *
@@ -789,6 +815,31 @@ class Background2D : public Ogre::RenderQueueListener{
          */
         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.
          */
@@ -974,6 +1025,14 @@ class Background2D : public Ogre::RenderQueueListener{
          */
         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.
+         */
+        bool free_scroll_;
+
         /**
          * Position of an instant scroll that waits for the end of the frame.
          *

+ 247 - 0
src/core/BackgroundPalette.cpp

@@ -0,0 +1,247 @@
+/*
+ * 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 <OgreResourceGroupManager.h>
+#include "core/BackgroundPalette.h"
+#include "core/Logger.h"
+
+namespace{
+    /**
+     * Reads little endian values from a buffer.
+     */
+    class Reader{
+        public:
+            Reader(const char* data, size_t size): data_(data), size_(size), pos_(0), ok_(true){}
+            uint16_t U16(){
+                if (pos_ + 2 > size_){ok_ = false; return 0;}
+                const uint16_t v = static_cast<uint8_t>(data_[pos_])
+                  | (static_cast<uint8_t>(data_[pos_ + 1]) << 8);
+                pos_ += 2;
+                return v;
+            }
+            uint8_t U8(){
+                if (pos_ + 1 > size_){ok_ = false; return 0;}
+                return static_cast<uint8_t>(data_[pos_ ++]);
+            }
+            bool Read(void* dest, size_t size){
+                if (pos_ + size > size_){ok_ = false; return false;}
+                std::copy(data_ + pos_, data_ + pos_ + size, static_cast<char*>(dest));
+                pos_ += size;
+                return true;
+            }
+            bool Ok() const{return ok_;}
+        private:
+            const char* data_;
+            size_t size_;
+            size_t pos_;
+            bool ok_;
+    };
+
+    /**
+     * Value of a byte parameter as signed.
+     */
+    int SignedByte(int value){
+        value &= 0xFF;
+        return (value & 0x80) ? value - 256 : value;
+    }
+}
+
+bool BackgroundPalette::Load(const Ogre::String& name){
+    Clear();
+    Ogre::DataStreamPtr stream;
+    try{
+        stream = Ogre::ResourceGroupManager::getSingleton().openResource(name);
+    }
+    catch (const Ogre::Exception&){
+        LOG_ERROR("Background palette: can't open '" + name + "'.");
+        return false;
+    }
+    std::vector<char> data(stream->size());
+    if (!data.empty()) stream->read(data.data(), data.size());
+    Reader reader(data.data(), data.size());
+    char magic[4] = {0, 0, 0, 0};
+    reader.Read(magic, 4);
+    if (!reader.Ok() || std::string(magic, 4) != "VGPL"){
+        LOG_ERROR("Background palette: '" + name + "' is not a palette file.");
+        return false;
+    }
+    const int page_count = reader.U16();
+    const int colors = reader.U16();
+    pages_.assign(page_count, std::vector<uint16_t>(colors, 0));
+    for (auto& page : pages_){
+        for (auto& color : page) color = reader.U16();
+    }
+    const uint32_t tile_count = reader.U16() | (static_cast<uint32_t>(reader.U16()) << 16);
+    for (uint32_t i = 0; i < tile_count && reader.Ok(); ++ i){
+        Tile tile;
+        tile.x = reader.U16();
+        tile.y = reader.U16();
+        tile.width = reader.U16();
+        tile.height = reader.U16();
+        tile.page = reader.U16();
+        tile.first_hidden = reader.U8() != 0;
+        tile.indexes.resize(static_cast<size_t>(tile.width) * tile.height);
+        reader.Read(tile.indexes.data(), tile.indexes.size());
+        tiles_.push_back(std::move(tile));
+    }
+    if (!reader.Ok()){
+        LOG_ERROR("Background palette: '" + name + "' is truncated.");
+        Clear();
+        return false;
+    }
+    dirty_.assign(pages_.size(), false);
+    return true;
+}
+
+void BackgroundPalette::Clear(){
+    pages_.clear();
+    tiles_.clear();
+    dirty_.clear();
+    std::fill(array_.begin(), array_.end(), 0);
+}
+
+bool BackgroundPalette::IsEmpty() const{return tiles_.empty();}
+
+void BackgroundPalette::Store(int page, int slot, int count){
+    if (page < 0 || page >= static_cast<int>(pages_.size())) return;
+    const int first = slot * SLOT_COLORS;
+    for (int i = 0; i < count; ++ i){
+        if (first + i < 0 || first + i >= ARRAY_SIZE) break;
+        if (i >= static_cast<int>(pages_[page].size())) break;
+        array_[first + i] = pages_[page][i];
+    }
+}
+
+void BackgroundPalette::Load(int slot, int page, int count){
+    if (page < 0 || page >= static_cast<int>(pages_.size())) return;
+    const int first = slot * SLOT_COLORS;
+    for (int i = 0; i < count; ++ i){
+        if (first + i < 0 || first + i >= ARRAY_SIZE) break;
+        if (i >= static_cast<int>(pages_[page].size())) break;
+        pages_[page][i] = array_[first + i];
+    }
+    dirty_[page] = true;
+}
+
+void BackgroundPalette::Copy(int source, int destination, int count){
+    const int from = source * SLOT_COLORS;
+    const int to = destination * SLOT_COLORS;
+    for (int i = 0; i < count; ++ i){
+        if (from + i < 0 || from + i >= ARRAY_SIZE || to + i < 0 || to + i >= ARRAY_SIZE) break;
+        array_[to + i] = array_[from + i];
+    }
+}
+
+uint16_t BackgroundPalette::MultiplyColor(uint16_t color, int red, int green, int blue){
+    // The original game doubles the 5 bit channels and multiplies, so the multiplier 64 keeps the
+    // channel. The green and blue channels take one bit of the channel under them, as it does.
+    int r = (((color << 1) & 0x3F) * (red & 0xFF)) >> 7;
+    int g = (((color >> 4) & 0x3F) * (green & 0xFF)) >> 7;
+    int b = (((color >> 9) & 0x3F) * (blue & 0xFF)) >> 7;
+    r = std::min(r, 31);
+    g = std::min(g, 31);
+    b = std::min(b, 31);
+    uint16_t result = static_cast<uint16_t>((b << 10) | (g << 5) | r | (color & 0x8000));
+    // Black stays opaque black, not an empty color.
+    if (result == 0) result = 0x8000;
+    return result;
+}
+
+uint16_t BackgroundPalette::AddToColor(uint16_t color, int red, int green, int blue){
+    const int r = std::max(0, std::min(31, (color & 0x1F) + red));
+    const int g = std::max(0, std::min(31, ((color >> 5) & 0x1F) + green));
+    const int b = std::max(0, std::min(31, ((color >> 10) & 0x1F) + blue));
+    uint16_t result = static_cast<uint16_t>((b << 10) | (g << 5) | r | (color & 0x8000));
+    if (result == 0 && color != 0) result = 0x8000;
+    return result;
+}
+
+void BackgroundPalette::Multiply(
+  int source, int destination, int start, int count, int red, int green, int blue
+){
+    const int from = source * SLOT_COLORS;
+    const int to = destination * SLOT_COLORS;
+    for (int i = start; i < start + count; ++ i){
+        if (from + i < 0 || from + i >= ARRAY_SIZE || to + i < 0 || to + i >= ARRAY_SIZE) break;
+        const uint16_t color = array_[from + i];
+        // Empty colors are not changed.
+        if (color == 0) continue;
+        array_[to + i] = MultiplyColor(color, red, green, blue);
+    }
+}
+
+void BackgroundPalette::Add(int source, int destination, int red, int green, int blue, int count){
+    const int from = source * SLOT_COLORS;
+    const int to = destination * SLOT_COLORS;
+    red = SignedByte(red);
+    green = SignedByte(green);
+    blue = SignedByte(blue);
+    for (int i = 0; i < count; ++ i){
+        if (from + i < 0 || from + i >= ARRAY_SIZE || to + i < 0 || to + i >= ARRAY_SIZE) break;
+        array_[to + i] = AddToColor(array_[from + i], red, green, blue);
+    }
+}
+
+bool BackgroundPalette::IsBrightFirstColor(uint16_t first){
+    // A channel of 24 or more out of 31 (see the installer).
+    return (first & 0x1F) >= 24 || ((first >> 5) & 0x1F) >= 24 || ((first >> 10) & 0x1F) >= 24;
+}
+
+void BackgroundPalette::ToRgba(
+  uint16_t color, uint16_t first, int index, bool first_hidden, uint8_t* rgba
+){
+    // Strange PC version behavior, as in the installer: empty colors are replaced by the first
+    // color, and the first color is hidden by a flag.
+    const bool empty = (color == 0);
+    if (color == 0) color = first;
+    const int r = color & 0x1F;
+    const int g = (color >> 5) & 0x1F;
+    const int b = (color >> 10) & 0x1F;
+    rgba[0] = static_cast<uint8_t>(r / 31.0f * 255.0f);
+    rgba[1] = static_cast<uint8_t>(g / 31.0f * 255.0f);
+    rgba[2] = static_cast<uint8_t>(b / 31.0f * 255.0f);
+    // The empty entries that took a visible first color are hidden too (see the installer).
+    if (index == 0 && first_hidden) rgba[3] = 0;
+    else if (empty && first_hidden && IsBrightFirstColor(first)) rgba[3] = 0;
+    else if ((color & 0x8000) && (r != 0 || g != 0 || b != 0)) rgba[3] = 127;
+    else rgba[3] = 255;
+}
+
+bool BackgroundPalette::Paint(Ogre::Image& image){
+    if (std::none_of(dirty_.begin(), dirty_.end(), [](bool d){return d;})) return false;
+    uint8_t* data = image.getData();
+    const size_t width = image.getWidth();
+    const size_t height = image.getHeight();
+    if (data == nullptr || image.getFormat() != Ogre::PF_BYTE_RGBA) return false;
+    for (const Tile& tile : tiles_){
+        if (tile.page >= pages_.size() || !dirty_[tile.page]) continue;
+        if (static_cast<size_t>(tile.x) + tile.width > width) continue;
+        if (static_cast<size_t>(tile.y) + tile.height > height) continue;
+        const std::vector<uint16_t>& colors = pages_[tile.page];
+        const uint16_t first = colors.empty() ? 0 : colors[0];
+        for (int y = 0; y < tile.height; ++ y){
+            for (int x = 0; x < tile.width; ++ x){
+                const int index = tile.indexes[static_cast<size_t>(y) * tile.width + x];
+                const uint16_t color = index < static_cast<int>(colors.size()) ? colors[index] : 0;
+                uint8_t* pixel = data + ((tile.y + y) * width + tile.x + x) * 4;
+                ToRgba(color, first, index, tile.first_hidden, pixel);
+            }
+        }
+    }
+    std::fill(dirty_.begin(), dirty_.end(), false);
+    return true;
+}

+ 167 - 0
src/core/BackgroundPalette.h

@@ -0,0 +1,167 @@
+/*
+ * 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 <cstdint>
+#include <vector>
+#include <OgreImage.h>
+#include <OgreString.h>
+#include <OgreTexture.h>
+
+/**
+ * Palette animations of a 2D background.
+ *
+ * The backgrounds of the original game use 8 bit tiles with palettes, and the scripts change the
+ * palettes while the field runs (waterfalls, lights, fades). The tiles of the image of a field are
+ * already painted with their palette, so for the palettes a script changes the installer saves the
+ * palettes and the indexes of the tiles (palette.bin), and this class paints them again when the
+ * script changes a palette.
+ *
+ * The scripts work like in the original game: an array of palettes in memory (the "slots", 16
+ * colors each) and the palettes of the background (the "pages"). Colors are the 16 bit values of
+ * the original game: 5 bits per channel (red in the lowest bits) and the flag 0x8000.
+ */
+class BackgroundPalette{
+    public:
+
+        /**
+         * Loads the palette data of a field.
+         *
+         * @param[in] name Resource name of the palette file.
+         * @return True if it was loaded.
+         */
+        bool Load(const Ogre::String& name);
+
+        /**
+         * Removes all data.
+         */
+        void Clear();
+
+        /**
+         * Checks if there is palette data.
+         */
+        bool IsEmpty() const;
+
+        /**
+         * Stores colors of a page in the array of palettes (STPAL).
+         */
+        void Store(int page, int slot, int count);
+
+        /**
+         * Loads colors of a page from the array of palettes (LDPAL).
+         */
+        void Load(int slot, int page, int count);
+
+        /**
+         * Copies colors inside the array of palettes (CPPAL).
+         */
+        void Copy(int source, int destination, int count);
+
+        /**
+         * Multiplies the channels of colors in the array of palettes (MPPAL, MPPAL2). 64 is 1.0.
+         */
+        void Multiply(
+          int source, int destination, int start, int count, int red, int green, int blue
+        );
+
+        /**
+         * Adds signed values to the channels of colors in the array of palettes (ADPAL).
+         */
+        void Add(int source, int destination, int red, int green, int blue, int count);
+
+        /**
+         * Paints the tiles of the pages that changed in the image.
+         *
+         * @param[in,out] image The image of the whole background, which is changed.
+         * @return True if the image changed.
+         */
+        bool Paint(Ogre::Image& image);
+
+        /**
+         * The color of a palette entry as it is shown, like the installer does it.
+         *
+         * @param[in] color Color of the original game (5 bits per channel and the flag 0x8000).
+         * @param[in] first Color 0 of the same page, used for the empty colors.
+         * @param[in] index Index of the color in the page.
+         * @param[in] first_hidden True if the first color of the page is transparent.
+         * @param[out] rgba The 4 bytes to write: red, green, blue, alpha.
+         */
+        static void ToRgba(
+          uint16_t color, uint16_t first, int index, bool first_hidden, uint8_t* rgba
+        );
+
+        /**
+         * Checks if the first color of a page is a bright marker color, whose empty entries are
+         * hidden (see ToRgba).
+         */
+        static bool IsBrightFirstColor(uint16_t first);
+
+        /**
+         * Multiplies a color (see Multiply).
+         */
+        static uint16_t MultiplyColor(uint16_t color, int red, int green, int blue);
+
+        /**
+         * Adds a value to the channels of a color (see Add).
+         */
+        static uint16_t AddToColor(uint16_t color, int red, int green, int blue);
+
+    private:
+
+        /**
+         * A tile that has to be painted again when its page changes.
+         */
+        struct Tile{
+            uint16_t x;
+            uint16_t y;
+            uint16_t width;
+            uint16_t height;
+            uint16_t page;
+            bool first_hidden;
+            std::vector<uint8_t> indexes;
+        };
+
+        /**
+         * Number of colors that a slot of the array has.
+         */
+        static const int SLOT_COLORS = 16;
+
+        /**
+         * Size of the array of palettes, in colors (256 slots).
+         */
+        static const int ARRAY_SIZE = 256 * SLOT_COLORS;
+
+        /**
+         * The palette pages.
+         */
+        std::vector<std::vector<uint16_t>> pages_;
+
+        /**
+         * The array of palettes.
+         */
+        std::vector<uint16_t> array_ = std::vector<uint16_t>(ARRAY_SIZE, 0);
+
+        /**
+         * The tiles.
+         */
+        std::vector<Tile> tiles_;
+
+        /**
+         * The pages that changed since the last call to Paint.
+         */
+        std::vector<bool> dirty_;
+};

+ 4 - 2
src/core/DebugDraw.cpp

@@ -103,6 +103,8 @@ void DebugDraw::SetFadeDistance(const float fade_s, const float fade_e){
     fade_end_square_ = fade_e * fade_e;
 }
 
+void DebugDraw::SetFadeEnabled(const bool enabled){fade_enabled_ = enabled;}
+
 void DebugDraw::SetTextAlignment(TextAlignment alignment){text_alignment_ = alignment;}
 
 void DebugDraw::Line(const float x1, const float y1, const float x2, const float y2){
@@ -401,9 +403,9 @@ void DebugDraw::Text(
         //  ->getRootSceneNode()->get->getPosition()
         //);
         //std::cout << "[DEBUG TEXT MODI]: " << dist_sq << "\n";
-        if (dist_sq < fade_end_square_){
+        if (!fade_enabled_ || dist_sq < fade_end_square_){
             float a
-              = (dist_sq > fade_start_square_)
+              = (fade_enabled_ && dist_sq > fade_start_square_)
                 ? (1.0f - (dist_sq - fade_start_square_) / (fade_end_square_ - fade_start_square_))
                 : 1.0f;
             Ogre::ColourValue colour = colour_;

+ 15 - 0
src/core/DebugDraw.h

@@ -65,6 +65,16 @@ class DebugDraw : public Ogre::RenderQueueListener, public Ogre::Singleton<Debug
          */
         void SetFadeDistance(const float fade_s, const float fade_e);
 
+        /**
+         * Enables or disables the fading of the text with the distance to the camera.
+         *
+         * The fade distances are fixed, but the camera of a field can be far from everything (the
+         * Wall Market maps are 60 to 90 units from it), so the text would never be seen there.
+         *
+         * @param[in] enabled True to fade the text, false to always draw it.
+         */
+        void SetFadeEnabled(const bool enabled);
+
         /**
          * Text alignment modes.
          */
@@ -388,6 +398,11 @@ class DebugDraw : public Ogre::RenderQueueListener, public Ogre::Singleton<Debug
          * For text fading. The text fully fades at this distance.
          */
         float fade_end_square_;
+
+        /**
+         * If the text fades with the distance, see SetFadeEnabled.
+         */
+        bool fade_enabled_ = true;
 };
 
 /**

+ 27 - 11
src/core/DialogsManager.cpp

@@ -178,6 +178,8 @@ void DialogsManager::SetText(const char* d_name, const char* text){
         ShowMessage(id, data->x, data->y, data->w, data->h);
         messages_[id]->text_area->SetText(std::string("[ERROR string not found:] ") + text);
     }
+    // The text of a timer window is the time, not the text of the message.
+    if (static_cast<int>(id) == timer_window_id_) RenderTimer();
 }
 
 bool DialogsManager::ShowScriptMessage(const char* text){
@@ -212,6 +214,9 @@ void DialogsManager::SetNumeric(const char* d_name, const bool numeric, const bo
     }
     if (numeric){
         messages_[id]->text_area->SetFont("FFVIITimerFont");
+        // The digits are taller than the area left by the usual padding of a small window, and the
+        // text would overflow and not be shown.
+        messages_[id]->text_area->SetPadding(0, 0, 0, 0);
         if (timer){
             messages_[id]->numeric = false;
             messages_[id]->timer = true;
@@ -224,6 +229,7 @@ void DialogsManager::SetNumeric(const char* d_name, const bool numeric, const bo
     }
     else{
         messages_[id]->text_area->SetFont("FFVIIFont");
+        messages_[id]->text_area->SetPadding(3, 5, 3, 5);
         messages_[id]->numeric = false;
         messages_[id]->timer = false;
         timer_window_id_ = -1;
@@ -231,15 +237,17 @@ void DialogsManager::SetNumeric(const char* d_name, const bool numeric, const bo
 }
 
 void DialogsManager::UpdateTimer(const unsigned int seconds){
-    if (
-      timer_window_id_ != - 1 && timer_window_id_ < messages_.size() && seconds != timer_seconds_
-    ){
-        std::string m = std::to_string(seconds / 60);
-        while (m.size() < 2) m = "0" + m;
-        std::string s = std::to_string(seconds % 60);
-        while (s.size() < 2) s = "0" + s;
-        messages_[timer_window_id_]->text_area->SetText(m + ":" + s);
-    }
+    timer_seconds_ = seconds;
+    RenderTimer();
+}
+
+void DialogsManager::RenderTimer(){
+    if (timer_window_id_ == -1 || timer_window_id_ >= static_cast<int>(messages_.size())) return;
+    std::string m = std::to_string(timer_seconds_ / 60);
+    while (m.size() < 2) m = "0" + m;
+    std::string s = std::to_string(timer_seconds_ % 60);
+    while (s.size() < 2) s = "0" + s;
+    messages_[timer_window_id_]->text_area->SetText(m + ":" + s);
 }
 
 void DialogsManager::SetMode(const char* d_name, const int bg, const bool closeable){
@@ -349,15 +357,23 @@ void DialogsManager::ShowMessage(
 ){
     // Add 5 pixels, to compensate character width operation roundowns.
     int extra_width = width + 5;
-    // Handle error when dialog window cross border of limit area
+    // Handle error when dialog window cross border of limit area. The vertical check uses the
+    // height of the area (it used its width, so windows that went past the bottom were not moved
+    // back unless they were beyond 320).
     float la_percent_width, la_width;
     limit_area_->GetWidth(la_percent_width, la_width);
     float move_back_x = 0;
     if (x + extra_width > la_width) move_back_x = x + extra_width - la_width;
     float la_percent_height, la_height;
-    limit_area_->GetWidth(la_percent_height, la_height);
+    limit_area_->GetHeight(la_percent_height, la_height);
     float move_back_y = 0;
     if (y + height > la_height) move_back_y = y + height - la_height;
+    LOG_TRIVIAL(
+      "dialog window " + std::to_string(id) + ": requested (" + std::to_string(x) + ","
+      + std::to_string(y) + "," + std::to_string(width) + "," + std::to_string(height)
+      + "), shown at (" + std::to_string(x - move_back_x) + "," + std::to_string(y - move_back_y)
+      + ") in a limit area of " + std::to_string(la_width) + "x" + std::to_string(la_height)
+    );
     messages_[id]->widget->SetX(0, x - move_back_x);
     messages_[id]->widget->SetY(0, y - move_back_y);
     messages_[id]->widget->SetWidth(0, extra_width);

+ 3 - 0
src/core/DialogsManager.h

@@ -343,6 +343,9 @@ class DialogsManager : public Manager, public Ogre::Singleton<DialogsManager>{
          */
         void UpdateTimer(const unsigned int seconds);
 
+        /// Writes the time of the timer in its window.
+        void RenderTimer();
+
         /**
          * Sets the window mode.
          *

+ 13 - 7
src/core/Entity.cpp

@@ -236,10 +236,9 @@ void Entity::SetPosition(const Ogre::Vector3& position){scene_node_->setPosition
 void Entity::ScriptSetPosition(const float x, const float y, const float z){
     SetPosition(Ogre::Vector3(x, y, z));
 
-    // Make the entity solid, visible and talkable. TODO: Check if neccessary.
-    SetVisible(true);
-    SetSolid(true);
-    SetTalkable(true);
+    // The position doesn't change if the entity is visible, solid or talkable: the scripts hide an
+    // entity (VISI) and place it (XYZI) in any order, and the second one that shows it again would
+    // make, for example, the stand-in models (dea, dcl) of the scenes visible from the start.
 
     // If set from a script:
     // Reset walkmesh triangle to reattach entity to walkmesh again if needed.
@@ -517,8 +516,12 @@ void Entity::ScriptJumpToPosition(
   const float x, const float y, const float z, const float seconds, const int dest_triangle
 ){
     float new_z = z;
-    // If z not specified (-1), asume same Z.
-    if (z < 0) new_z = GetPosition().z;
+    // If z is not specified (-1) it is the height of the destination triangle, so the entity
+    // lands on the floor of the destination (jumping down a step, for example), and not at the
+    // height it jumps from.
+    if (z < 0) new_z = EntityManager::getSingleton().GetTriangleHeight(
+      dest_triangle, x, y, GetPosition().z
+    );
     Ogre::Vector3 jump_to(x, y, new_z);
     SetJump(jump_to, seconds, dest_triangle);
     LOG_TRIVIAL(
@@ -580,6 +583,9 @@ void Entity::ScriptOffsetToPosition(
     );
     Ogre::Vector3 position = Ogre::Vector3(x, y, z);
     if (type == AT_NONE){
+        // An instant offset replaces the one that is running, which must not go on moving the
+        // model afterwards (script_3 of ren in pillar_3 ends this way).
+        if (offset_type_ != AT_NONE) UnsetOffset();
         this->SetOffset(position);
         return;
     }
@@ -804,6 +810,6 @@ Ogre::Degree Entity::GetDirectionToEntity(Entity* entity) const{
     Ogre::Vector2 up(0.0f, -1.0f);
     Ogre::Vector2 dir(direction_point.x - current_point.x, direction_point.y - current_point.y);
     // Angle between vectors
-    Ogre::Degree angle(Ogre::Radian(acosf(dir.dotProduct(up) / (dir.length() * up.length()))));
+    Ogre::Degree angle(Ogre::Radian(SafeAcos(dir.dotProduct(up), dir.length() * up.length())));
     return (dir.x < 0) ? Ogre::Degree(360) - angle : angle;
 }

+ 25 - 0
src/core/Entity.h

@@ -15,6 +15,8 @@
 
 #pragma once
 
+#include <algorithm>
+#include <cmath>
 #include <tuple>
 #include <OgreString.h>
 #include "EntityCollision.h"
@@ -99,6 +101,21 @@ enum LinearMovement{
 /**
  * Any entity in a field.
  */
+/**
+ * Arc cosine of a ratio, in radians, that never gives NaN.
+ *
+ * The cosine of the angle between two vectors can end up a bit over 1 or under -1 because of float
+ * rounding (for example when moving exactly along an axis), and acosf gives NaN then. A NaN
+ * rotation breaks the bounding box of the entity and Ogre asserts. A zero length vector gives 0.
+ *
+ * @param[in] dot The dot product of the vectors.
+ * @param[in] length_product The product of the lengths of the vectors.
+ */
+inline float SafeAcos(const float dot, const float length_product){
+    if (!(length_product > 0.0f)) return 0.0f;
+    return std::acos(std::max(-1.0f, std::min(1.0f, dot / length_product)));
+}
+
 class Entity{
 
     public:
@@ -1568,6 +1585,14 @@ class Entity{
          */
         float animation_end_time_;
 
+        /**
+         * Seconds left that the animation has to wait before it can end. A range of one frame
+         * (start and end equal) lasts a frame of the original game (1/30 s), not an update of the
+         * engine, so the scripts that play an animation frame by frame are not faster at a high
+         * frame rate.
+         */
+        float animation_hold_ = 0.0f;
+
         /**
          * Indicates if an automation must be played automatically.
          */

+ 62 - 8
src/core/EntityManager.cpp

@@ -75,6 +75,16 @@ const unsigned int EntityManager::BATTLE_BACKGROUND_ID = 1000;
 
 const unsigned int EntityManager::WORLD_MAP_BACKGROUND_ID = 1001;
 
+float EntityManager::GetTriangleHeight(int triangle, float x, float y, float fallback) const{
+    if (IsBattleModule() || triangle < 0 || triangle >= walkmesh_.GetNumberOfTriangles())
+        return fallback;
+    const float height = PointElevation(
+      Ogre::Vector2(x, y), walkmesh_.GetA(triangle), walkmesh_.GetB(triangle),
+      walkmesh_.GetC(triangle)
+    );
+    return std::isfinite(height) ? height : fallback;
+}
+
 float EntityManager::PointElevation(
   const Ogre::Vector2& point, const Ogre::Vector3& a, const Ogre::Vector3& b, const Ogre::Vector3& c
 ){
@@ -128,7 +138,7 @@ Ogre::Degree EntityManager::GetDirectionToPoint(
     Ogre::Vector2 up(0.0f, -1.0f);
     Ogre::Vector2 dir(direction_point.x - current_point.x, direction_point.y - current_point.y);
     // Angle between vectors
-    Ogre::Degree angle(Ogre::Radian(acosf(dir.dotProduct(up) / (dir.length() * up.length()))));
+    Ogre::Degree angle(Ogre::Radian(SafeAcos(dir.dotProduct(up), dir.length() * up.length())));
     return (dir.x < 0) ? Ogre::Degree(360) - angle : angle;
 }
 
@@ -406,6 +416,12 @@ void EntityManager::AddFieldOrWorldMapEntity(
     entity->setScale(scale);
     entity->SetIndex(index);
     entity->setRootOrientation(root_orientation);
+    // The models of a field are visible, solid and talkable until a script changes it (VISI 0,
+    // SOLID 1, TLKON 1). Many entities, such as the doors of mds6_2 or the people of mrkt2, are
+    // never turned on by a script. Setting a position doesn't turn them on.
+    entity->SetVisible(true);
+    entity->SetSolid(true);
+    entity->SetTalkable(true);
     entity_.push_back(entity);
     ScriptManager::getSingleton().AddEntity(ScriptManager::ENTITY, entity->GetName(), entity);
 }
@@ -539,6 +555,8 @@ void EntityManager::SetBackground3D(const Ogre::String& name, const Ogre::String
 }
 
 void EntityManager::UpdateDebug(){
+    // Only the world map fades the debug text with the distance to the camera.
+    DEBUG_DRAW.SetFadeEnabled(module_ == Module::WORLD);
     grid_->setVisible(cv_debug_grid.GetB());
     axis_->setVisible(cv_debug_axis.GetB());
     if (module_ == Module::BATTLE){
@@ -563,6 +581,7 @@ void EntityManager::ClearField(){
     walkmesh_.Clear();
     background_2d_.Clear();
     screen_fade_.Clear();
+    player_slip_ = true;
     DialogsManager::getSingleton().Clear();
     for (unsigned int i = 0; i < entity_.size(); ++ i){
         ScriptManager::getSingleton().RemoveEntity(ScriptManager::ENTITY, entity_[i]->GetName());
@@ -792,8 +811,22 @@ void EntityManager::ScriptSetPlayerEntity(const char* name){
             // A script can read the walkmesh triangle of the player right after this, so if it was
             // placed by position the triangle has to be known. Done before it's the player entity
             // so that the entity not being on the walkmesh yet isn't logged as an error.
+            if (entity_[i]->GetMoveTriangleId() == -1 && entity_[i]->GetPosition().isZeroLength()){
+                // A model that has no position of its own (the fields put the dressed Cloud away
+                // until a script makes it the player) takes the place of the previous player,
+                // which is where the field entry put the party, as in the original game.
+                if (player_entity_ != nullptr && player_entity_ != entity_[i]){
+                    entity_[i]->SetPosition(player_entity_->GetPosition());
+                    entity_[i]->SetRotation(player_entity_->GetRotation());
+                }
+            }
             if (entity_[i]->GetMoveTriangleId() == -1) SetEntityOnWalkmesh(entity_[i]);
             LOG_TRIVIAL("Player entity set to '" + std::string(name) + "'.");
+            // The camera that follows the player keeps following it when another entity takes over
+            // (Cloud and the dressed Cloud, for example); a camera that follows some other entity
+            // is left as it is.
+            if (player_entity_ != nullptr && background_2d_.GetAutoScrollEntity() == player_entity_)
+                background_2d_.ScriptAutoScrollToEntity(entity_[i]);
             player_entity_ = entity_[i];
             // Also, make it non-talkable. Visibility and solidity are left to the scripts, as in
             // the original game: some fields use hidden helper entities (like the 'camera') as
@@ -839,6 +872,8 @@ void EntityManager::ScriptUnsetPlayerEntity(){
     player_entity_ = nullptr;
 }
 
+void EntityManager::ScriptSetPlayerSlip(const bool slip){player_slip_ = slip;}
+
 void EntityManager::ScriptPlayerLock(const bool lock){
     if (IsBattleModule()){
         LOG_WARNING("Tried to set player lock but the EntityManager is in battle mode.");
@@ -1008,6 +1043,12 @@ bool EntityManager::IsKeyOn(unsigned int key_code){
     for (const auto& entry : BUTTONS)
         if ((key_code & entry.mask) && InputManager::getSingleton().IsGameEventPressed(entry.event))
             return true;
+    // TODO: In the original game the button that makes the player run is the Cancel button (64),
+    // so scripts that check Cancel are checking if the player runs (the sneak out of ealin_2, for
+    // example). Here running has its own game event, "run", so it counts as Cancel too. Scripts
+    // that really want the Cancel button would see it pressed while running. Check which scripts
+    // need which, and maybe split them.
+    if ((key_code & 64) && InputManager::getSingleton().IsGameEventPressed("run")) return true;
     return false;
 }
 
@@ -1171,8 +1212,8 @@ bool EntityManager::PerformWalkmeshMove(Entity* entity, const float speed, const
     if (entity->GetMoveAutoRotation() == true){
         Ogre::Vector2 up(0.0f, -1.0f);
         // Angle between vectors
-        Ogre::Degree angle(Ogre::Radian(acosf(
-          direction.dotProduct(up) / (direction.length() * up.length())
+        Ogre::Degree angle(Ogre::Radian(SafeAcos(
+          direction.dotProduct(up), direction.length() * up.length()
         )));
         angle = (direction.x < 0) ? Ogre::Degree(360) - angle : angle;
         entity->SetRotation(Ogre::Degree(angle));
@@ -1330,6 +1371,8 @@ bool EntityManager::PerformWalkmeshMove(Entity* entity, const float speed, const
                 ){
                     // If not both left and right check failed
                     if (first_triangle_check == false || second_triangle_check == false){
+                        // With SLIP off the move is not turned along the wall: it stays blocked.
+                        if (!player_slip_) break;
                         if (first_triangle_check != false && second_triangle_check == false){
                             q1.FromAngleAxis(
                               Ogre::Radian(Ogre::Degree(-11.25f)), Ogre::Vector3::UNIT_Z
@@ -1684,8 +1727,8 @@ void EntityManager::SetNextOffsetStep(Entity* entity){
     current = (current > total) ? total : current;
     Ogre::Vector3 start = entity->GetOffsetPositionStart();
     Ogre::Vector3 end = entity->GetOffsetPositionEnd();
-    // TODO: Prevent division by 0:
-    float x = current / total;
+    // An offset of zero seconds is done at once. Dividing would give NaN.
+    float x = (total > 0.0f) ? current / total : 1.0f;
     if (std::isnan(x)) x = 0.0f;
     float smooth_modifier = (type == AT_SMOOTH) ? -2 * x * x * x + 3 * x * x : x;
     Ogre::Vector3 offset = start + (end - start) * smooth_modifier;
@@ -1703,8 +1746,9 @@ void EntityManager::SetNextTurnStep(Entity* entity){
     current = (current > total) ? total : current;
     Ogre::Degree start = entity->GetTurnDirectionStart();
     Ogre::Degree end = entity->GetTurnDirectionEnd();
-    // TODO: Prevent division by 0:
-    float x = current / total;
+    // A turn of zero seconds is done at once. Dividing would give NaN, and a NaN rotation breaks
+    // the bounding box of the entity.
+    float x = (total > 0.0f) ? current / total : 1.0f;
     float smooth_modifier = (type == AT_SMOOTH) ? -2 * x * x * x + 3 * x * x : x;
     Ogre::Degree rotation = start + (end - start) * smooth_modifier;
     entity->SetRotation(rotation);
@@ -1815,6 +1859,8 @@ void EntityManager::SetNextJumpStep(Entity* entity){
     float total = entity->GetJumpSeconds();
     float current = entity->GetJumpCurrentSeconds();
     current += Timer::getSingleton().GetGameTimeDelta();
+    // A jump of zero seconds lands at once, without dividing by zero.
+    if (total <= 0.0f) total = 0.0001f;
     current = (current > total) ? total : current;
     Ogre::Vector3 start_position = entity->GetJumpStart();
     Ogre::Vector3 end_position   = entity->GetJumpEnd();
@@ -1828,6 +1874,14 @@ void EntityManager::SetNextJumpStep(Entity* entity){
         entity->UnsetJump();
         entity->SetMoveTriangleId(entity->GetJumpDestTriangle());
         SetEntityOnWalkmesh(entity);
+        // The scripts set the animation of the jump as the default one (DFANM) and don't set it
+        // back, but the player stands normally after landing in the original game (the scene of
+        // mds6_2 where Cloud jumps down, for example). The scripts that do set it, do it after
+        // the jump, so they aren't affected.
+        if (entity == player_entity_){
+            entity->ScriptSetDefaultAnimation("Idle");
+            entity->PlayAnimationContinue("Idle");
+        }
     }
     else entity->SetJumpCurrentSeconds(current);
 }
@@ -1842,7 +1896,7 @@ void EntityManager::SetNextScrollStep(){
     current = (current > total) ? total : current;
     Ogre::Vector2 start = background_2d_.GetScrollPositionStart();
     Ogre::Vector2 end = background_2d_.GetScrollPositionEnd();
-    float x = current / total;
+    float x = (total > 0.0f) ? current / total : 1.0f;
     float smooth_modifier = (type == Background2D::SMOOTH) ? -2 * x * x * x + 3 * x * x : x;
     Ogre::Vector2 scroll = start + (end - start) * smooth_modifier;
     background_2d_.SetScroll(scroll);

+ 26 - 0
src/core/EntityManager.h

@@ -396,6 +396,27 @@ class EntityManager : public Manager, public Ogre::Singleton<EntityManager>{
          */
         void ScriptPlayerLock(const bool lock);
 
+        /**
+         * Sets if the player can slide along the walls (SLIP in the field scripts).
+         *
+         * When it is off, a move of the player that is blocked by a wall is not turned into a
+         * move along the wall. It is on by default and when a field is loaded.
+         *
+         * @param[in] slip True to let the player slide.
+         */
+        void ScriptSetPlayerSlip(const bool slip);
+
+        /**
+         * Retrieves the height of a point of a walkmesh triangle.
+         *
+         * @param[in] triangle The triangle.
+         * @param[in] x X coordinate of the point.
+         * @param[in] y Y coordinate of the point.
+         * @param[in] fallback Value returned if there is no such triangle.
+         * @return The height of the triangle at the point.
+         */
+        float GetTriangleHeight(int triangle, float x, float y, float fallback) const;
+
         /**
          * Sets if the player moves running by default.
          *
@@ -863,6 +884,11 @@ class EntityManager : public Manager, public Ogre::Singleton<EntityManager>{
          */
         bool player_lock_;
 
+        /**
+         * Indicates if the player slides along the walls (see ScriptSetPlayerSlip).
+         */
+        bool player_slip_ = true;
+
         /**
          * Indicates if the playable is being moved by running.
          *

+ 5 - 0
src/core/EntityModel.cpp

@@ -312,6 +312,7 @@ void EntityModel::PlayAnimation(
           (start == -1) ? animation_current_->getLength() : start
         );
         animation_end_time_ = (end == -1) ? animation_current_->getLength() : end;
+        animation_hold_ = (start != -1 && start == end) ? 1.0f / 30.0f : 0.0f;
         animation_state_ = state;
         animation_play_type_ = play_type;
     }
@@ -371,6 +372,10 @@ bool EntityModel::HasAnimation(const Ogre::String& animation) const{
 
 void EntityModel::UpdateAnimation(const float delta){
     if (animation_current_ != nullptr){
+        if (animation_hold_ > 0.0f){
+            animation_hold_ -= delta;
+            if (animation_hold_ > 0.0f) return;
+        }
         float delta_mod = delta * animation_speed_;
         bool stop_check
           = (animation_current_->hasEnded() == true)

+ 4 - 1
src/core/ScreenFadeState.cpp

@@ -95,7 +95,10 @@ bool ScreenFadeState::StartFade(
             Begin(BLEND_ADD, Standard(r, g, b), Black(), 1, 1, seconds, false);
             return true;
         case 6:
-            Begin(BLEND_NORMAL, Standard(r, g, b), Standard(r, g, b), 0, 1, seconds, true);
+            // The pair of type 5: the colour is added to the field little by little and kept. The
+            // scripts use the pair for flashes (5 after 6 with the same colour) and for the tint
+            // of the scenes that are told (a dark blue added to the field, not a screen of it).
+            Begin(BLEND_ADD, Black(), Standard(r, g, b), 1, 1, seconds, true);
             return true;
         case 7:
             Begin(BLEND_SUBTRACT, Inverse1(r, g, b), Inverse1(r, g, b), 1, 1, seconds, false);

+ 17 - 1
src/core/ScriptManager.cpp

@@ -349,7 +349,23 @@ void ScriptManager::Update(const ScriptManager::Type type){
                         script_entity_[i].queue[script_index].wait = false;
                 }
             
-                if (!yielded) break;
+                if (!yielded){
+                    // The scripts of an entity don't wait for each other in the original game. If
+                    // the first one is waiting (for another script to end, for example) and a
+                    // script that someone waits to start (request_start_sync) is queued behind
+                    // it, that script has to start, or the two would wait for each other forever
+                    // (the lines of mrkt3 do this with Aerith).
+                    bool start_waited_script = false;
+                    for (size_t next = script_index + 1; next < script_entity_[i].queue.size(); ++ next){
+                        const QueueScript& queued = script_entity_[i].queue[next];
+                        if (!queued.yield && !queued.wait && !queued.paused_scripts_start.empty()){
+                            script_index = next - 1;
+                            start_waited_script = true;
+                            break;
+                        }
+                    }
+                    if (!start_waited_script) break;
+                }
             }
         }
     }

+ 17 - 1
src/core/ScriptManagerBinds.h

@@ -222,6 +222,7 @@ void ScriptManager::InitBinds(){
       "get_player_entity", &EntityManager::ScriptGetPlayerEntity,
       "unset_player_entity", &EntityManager::ScriptUnsetPlayerEntity,
       "player_lock", &EntityManager::ScriptPlayerLock,
+      "set_player_slip", &EntityManager::ScriptSetPlayerSlip,
       "is_player_locked", &EntityManager::IsPlayerLocked,
       "set_player_default_run", &EntityManager::SetPlayerDefaultRun,
       "random_encounters_on", &EntityManager::SetRandomEncounters,
@@ -368,11 +369,21 @@ void ScriptManager::InitBinds(){
         sol::resolve<void(const char*)>(&AudioManager::ScriptPlaySound),
         sol::resolve<void(const char*, const int)>(&AudioManager::ScriptPlaySound)
       ),
-      "play_sounds", &AudioManager::ScriptPlaySounds,
+      // The scripts pass nil for the sounds the opcode doesn't use.
+      "play_sounds", [](
+        AudioManager& audio, sol::optional<std::string> name1, sol::optional<std::string> name2,
+        sol::optional<std::string> name3, sol::optional<std::string> name4
+      ){
+          if (name1) audio.ScriptPlaySounds(
+            name1->c_str(), name2 ? name2->c_str() : "", name3 ? name3->c_str() : "",
+            name4 ? name4->c_str() : ""
+          );
+      },
       "get_track_id", &AudioManager::ScriptGetTrack,
       "get_battle_track_id", &AudioManager::ScriptGetBattleTrack,
       "set_battle_track_id", &AudioManager::ScriptSetBattleTrack,
       "play_music_once", &AudioManager::ScriptPlayMusicOnce,
+      "is_music_playing", &AudioManager::ScriptIsMusicPlaying,
       "set_music_volume", &AudioManager::ScriptSetMusicVolume,
       "set_sound_volume", &AudioManager::ScriptSetSoundVolume
     );
@@ -491,6 +502,11 @@ void ScriptManager::InitBinds(){
       "area_on", &Background2D::ScriptAreaOn,
       "area_off", &Background2D::ScriptAreaOff,
       "area_clear", &Background2D::ScriptAreaClear,
+      "palette_store", &Background2D::ScriptPaletteStore,
+      "palette_load", &Background2D::ScriptPaletteLoad,
+      "palette_copy", &Background2D::ScriptPaletteCopy,
+      "palette_multiply", &Background2D::ScriptPaletteMultiply,
+      "palette_add", &Background2D::ScriptPaletteAdd,
       "shake", &Background2D::ScriptShake,
       "set_layer_parallax", &Background2D::ScriptSetLayerParallax,
       "set_layer_scroll", &Background2D::ScriptSetLayerScroll,

+ 3 - 0
src/core/XmlBackground2DFile.cpp

@@ -37,6 +37,9 @@ void XmlBackground2DFile::Load(){
     Ogre::String image = GetString(node, "image", "");
     if (image != ""){
         background->SetImage(image);
+        // The palettes that the scripts animate.
+        const Ogre::String palette = GetString(node, "palette", "");
+        if (palette != "") background->SetPalette(palette);
         Ogre::Quaternion range = GetQuaternion(
           node, "range", Ogre::Quaternion(-100000, -100000, 100000, 100000)
         );

+ 34 - 2
src/data/VGearsBackgroundFile.cpp

@@ -102,6 +102,7 @@ namespace VGears{
     Ogre::Image* BackgroundFile::CreateImage(const PaletteFilePtr &palette){
         assert(palette != nullptr);
         SpritePtrList sprites;
+        palette_tiles_.clear();
         AddAllSprites(sprites);
         size_t width(1024);
         size_t row_pitch(width);
@@ -220,6 +221,17 @@ namespace VGears{
                 if (sprite.palette_page < PALETTE_ENTRY_COUNT){
                     first_color_hidden = palette_[sprite.palette_page] > 0;
                 }
+                // Remember the tile, for the palette animations.
+                PaletteTile palette_tile;
+                palette_tile.x = dst_x;
+                palette_tile.y = dst_y;
+                palette_tile.width = sprite.width;
+                palette_tile.height = sprite.height;
+                palette_tile.palette_page = sprite.palette_page;
+                palette_tile.first_color_hidden = first_color_hidden;
+                palette_tile.indexes.assign(
+                  static_cast<size_t>(sprite.width) * sprite.height, 0
+                );
                 for (uint16 y(sprite.height); y --;){
                     for (uint16 x(sprite.width); x --;){
                         size_t data_index(
@@ -231,6 +243,9 @@ namespace VGears{
                               << data_index;
                         }
                         uint8 index(data_page.data.at(data_index));
+                        palette_tile.indexes[
+                          static_cast<size_t>(y) * sprite.width + x
+                        ] = index;
                         if (index >= palette_page.size()){
                             Ogre::LogManager::getSingleton().stream()
                               << "Error: palette page Index out of Bounds "
@@ -247,8 +262,22 @@ namespace VGears{
                         // Strange PC version behavior: empty colors are
                         // replaced by the first color and the first color is
                         // hidden by a flag.
-                        if (colour == Color::ZERO) colour = palette_page[0];
-                        if (index == 0 && first_color_hidden) colour.a = 0;
+                        const bool empty_color = (colour == Color::ZERO);
+                        if (empty_color) colour = palette_page[0];
+                        // A page whose first color is a bright marker (the yellow of mds6_2, the green
+                        // of mds5_1) uses it as the key of the hidden color: the empty entries that
+                        // took it are hidden too, or they would be painted with that color. When
+                        // the first color is a dark one, the empty entries are painted with it,
+                        // as the dithering of the ground of mds6_2 needs.
+                        const float marker_level = 24.0f / 31.0f;
+                        const bool bright_first_color = (
+                          palette_page[0].r >= marker_level || palette_page[0].g >= marker_level
+                          || palette_page[0].b >= marker_level
+                        );
+                        if (
+                          (index == 0 && first_color_hidden)
+                          || (empty_color && first_color_hidden && bright_first_color)
+                        ) colour.a = 0;
                         else if (
                           colour.a
                           && (colour.r != 0 || colour.g != 0 || colour.b != 0)
@@ -259,6 +288,9 @@ namespace VGears{
                         color[data_index] = colour.getAsARGB();
                     }
                 }
+                if (sprite.palette_page < palette->GetPages().size()){
+                    palette_tiles_.push_back(std::move(palette_tile));
+                }
             }
             // Source in the texture atlas is where it's just copied to.
             sprite.src.x = dst_x;

+ 46 - 0
src/data/VGearsBackgroundFile.h

@@ -353,6 +353,47 @@ namespace VGears{
              */
             Ogre::Image* CreateImage(const PaletteFilePtr &palette);
 
+            /**
+             * A tile of the image that uses an 8 bit palette, with its indexes, so it can be
+             * painted again when a script changes the palette (palette animations).
+             *
+             * Filled by CreateImage.
+             */
+            struct PaletteTile{
+
+                /**
+                 * Position of the tile in the image.
+                 */
+                uint16 x;
+                uint16 y;
+
+                /**
+                 * Size of the tile.
+                 */
+                uint16 width;
+                uint16 height;
+
+                /**
+                 * Palette page the tile uses.
+                 */
+                uint16 palette_page;
+
+                /**
+                 * True if the first color of the page is transparent.
+                 */
+                bool first_color_hidden;
+
+                /**
+                 * Palette indexes of the pixels, row by row.
+                 */
+                std::vector<uint8> indexes;
+            };
+
+            /**
+             * Retrieves the tiles that use palettes, as of the last call to CreateImage.
+             */
+            const std::vector<PaletteTile>& GetPaletteTiles() const{return palette_tiles_;}
+
             /**
              * Adds all sprites to the background.
              *
@@ -409,6 +450,11 @@ namespace VGears{
              */
             std::array<uint8, PALETTE_ENTRY_COUNT> palette_;
 
+            /**
+             * Tiles that use palettes, see GetPaletteTiles.
+             */
+            std::vector<PaletteTile> palette_tiles_;
+
             /**
              * The background pages.
              */

+ 8 - 0
src/data/VGearsTriggersFile.h

@@ -406,6 +406,14 @@ namespace VGears{
              */
             const std::array<Gateway, 12>& GetGateways() const{return trigger_data_->doors;}
 
+            /**
+             * Retrieves the list of background triggers (the lines that turn a background area on
+             * or off, such as the doors).
+             */
+            const std::array<Trigger, 12>& GetBackgroundTriggers() const{
+                return trigger_data_->triggers;
+            }
+
         protected:
 
             /**

+ 71 - 45
src/installer/ExternalTools.cpp

@@ -258,6 +258,16 @@ namespace ExternalTools{
         return FfmpegArguments("-", output);
     }
 
+    std::vector<std::string> FfmpegMidiArguments(const std::string& output){
+        // Below -50 dB is silence, and 0.3 seconds of it are kept so the end doesn't sound cut.
+        return {
+          "-hide_banner", "-loglevel", "panic", "-y", "-i", "-", "-af",
+          "areverse,silenceremove=start_periods=1:start_duration=0:start_threshold=-50dB"
+          ":start_silence=0.3:detection=peak,areverse",
+          output
+        };
+    }
+
     std::vector<std::string> TimidityArguments(const std::string& midi){
         return {"--quiet=3", midi, "-Ow", "-o", "-"};
     }
@@ -323,55 +333,71 @@ namespace ExternalTools{
         return true;
     }
 
+    namespace{
+        /**
+         * Renders a MIDI with TiMidity and encodes it with ffmpeg, without a shell.
+         */
+        bool RenderMidi(
+          const std::string& timidity, const std::string& ffmpeg,
+          const std::vector<std::string>& ffmpeg_arguments, const std::string& midi,
+          const std::string& output, std::string* error
+        ){
+            QProcess render;
+            QProcess encode;
+            // render | encode, without a shell.
+            render.setStandardOutputProcess(&encode);
+            render.setStandardErrorFile(QProcess::nullDevice());
+            encode.setStandardOutputFile(QProcess::nullDevice());
+            encode.setStandardErrorFile(QProcess::nullDevice());
+            const auto to_list = [](const std::vector<std::string>& arguments){
+                QStringList list;
+                for (const std::string& argument : arguments) list << QString::fromStdString(argument);
+                return list;
+            };
+            // The source is started first, as Qt documents for piped processes.
+            render.start(QString::fromStdString(timidity), to_list(TimidityArguments(midi)));
+            encode.start(QString::fromStdString(ffmpeg), to_list(ffmpeg_arguments));
+            const bool render_started = render.waitForStarted(10000);
+            const bool encode_started = encode.waitForStarted(10000);
+            bool ok = false;
+            std::string reason;
+            if (!render_started || !encode_started){
+                render.kill();
+                encode.kill();
+                render.waitForFinished(2000);
+                encode.waitForFinished(2000);
+                reason = std::string("could not start ") + (!render_started ? "timidity" : "ffmpeg");
+            }
+            else{
+                render.waitForFinished(-1);
+                encode.waitForFinished(-1);
+                if (render.exitStatus() != QProcess::NormalExit || render.exitCode() != 0)
+                    reason = "timidity failed with exit code " + std::to_string(render.exitCode());
+                else if (encode.exitStatus() != QProcess::NormalExit || encode.exitCode() != 0)
+                    reason = "ffmpeg failed with exit code " + std::to_string(encode.exitCode());
+                else ok = true;
+            }
+            boost::system::error_code ec;
+            if (ok && !(fs::file_size(output, ec) > 0 && !ec)){
+                ok = false;
+                reason = "no audio was produced";
+            }
+            if (!ok){
+                fs::remove(output, ec);
+                if (error) *error = reason;
+            }
+            return ok;
+        }
+    }
+
     bool ConvertMidiToOgg(
       const std::string& timidity, const std::string& ffmpeg, const std::string& midi, const std::string& output,
       std::string* error
     ){
-        QProcess render;
-        QProcess encode;
-        // render | encode, without a shell.
-        render.setStandardOutputProcess(&encode);
-        render.setStandardErrorFile(QProcess::nullDevice());
-        encode.setStandardOutputFile(QProcess::nullDevice());
-        encode.setStandardErrorFile(QProcess::nullDevice());
-        const auto to_list = [](const std::vector<std::string>& arguments){
-            QStringList list;
-            for (const std::string& argument : arguments) list << QString::fromStdString(argument);
-            return list;
-        };
-        // The source is started first, as Qt documents for piped processes.
-        render.start(QString::fromStdString(timidity), to_list(TimidityArguments(midi)));
-        encode.start(QString::fromStdString(ffmpeg), to_list(FfmpegStdinArguments(output)));
-        const bool render_started = render.waitForStarted(10000);
-        const bool encode_started = encode.waitForStarted(10000);
-        bool ok = false;
-        std::string reason;
-        if (!render_started || !encode_started){
-            render.kill();
-            encode.kill();
-            render.waitForFinished(2000);
-            encode.waitForFinished(2000);
-            reason = std::string("could not start ") + (!render_started ? "timidity" : "ffmpeg");
-        }
-        else{
-            render.waitForFinished(-1);
-            encode.waitForFinished(-1);
-            if (render.exitStatus() != QProcess::NormalExit || render.exitCode() != 0)
-                reason = "timidity failed with exit code " + std::to_string(render.exitCode());
-            else if (encode.exitStatus() != QProcess::NormalExit || encode.exitCode() != 0)
-                reason = "ffmpeg failed with exit code " + std::to_string(encode.exitCode());
-            else ok = true;
-        }
-        boost::system::error_code ec;
-        if (ok && !(fs::file_size(output, ec) > 0 && !ec)){
-            ok = false;
-            reason = "no audio was produced";
-        }
-        if (!ok){
-            fs::remove(output, ec);
-            if (error) *error = reason;
-        }
-        return ok;
+        // The silence at the end is removed. If that leaves nothing (a track that is all silence)
+        // the track is encoded as it is.
+        if (RenderMidi(timidity, ffmpeg, FfmpegMidiArguments(output), midi, output, error)) return true;
+        return RenderMidi(timidity, ffmpeg, FfmpegStdinArguments(output), midi, output, error);
     }
 
 }

+ 14 - 0
src/installer/ExternalTools.h

@@ -185,6 +185,20 @@ namespace ExternalTools{
      */
     std::vector<std::string> FfmpegStdinArguments(const std::string& output);
 
+    /**
+     * Arguments of ffmpeg to encode the audio of a rendered MIDI (from the standard input) and
+     * remove the silence at its end.
+     *
+     * TiMidity renders the reverberation tail of the last notes, and the track would end in several
+     * seconds of near silence. The scripts that wait for a track to end (the jingle of the inns)
+     * would wait for all of it. The silence is removed by reversing the audio, removing the
+     * silence at its start, and reversing it again.
+     *
+     * @param[in] output Path of the file to write.
+     * @return The arguments.
+     */
+    std::vector<std::string> FfmpegMidiArguments(const std::string& output);
+
     /**
      * Arguments to render a MIDI file with TiMidity to a wav file written to the standard output.
      */

+ 199 - 18
src/installer/FieldDataInstaller.cpp

@@ -13,6 +13,8 @@
  * GNU General Public License for more details.
  */
 
+#include <cmath>
+#include <set>
 #include <string>
 #include <fstream>
 #include <algorithm>
@@ -39,8 +41,17 @@ int FieldDataInstaller::INACTIVE_GATEWAY_ID(32767);
 
 const std::vector<int> FieldDataInstaller::TEMPORARY_BANKS{5};
 
-std::string FieldDataInstaller::FieldScriptHeader(){
+std::string FieldDataInstaller::FieldScriptHeader(const int field_id){
     std::string header = "EntityContainer = {}\n\n";
+    if (field_id >= 0){
+        // LSTMP reads the ID of the field the player comes from. The field being left is the
+        // previous one, unless the field was just reloaded (after a battle, for example).
+        header += "-- The IDs of this field and of the previous one, for LSTMP.\n"
+          "if Data.FieldId ~= " + std::to_string(field_id) + " then\n"
+          "    Data.PreviousFieldId = Data.FieldId or 0\n"
+          "    Data.FieldId = " + std::to_string(field_id) + "\n"
+          "end\n\n";
+    }
     for (const int bank : TEMPORARY_BANKS){
         header += "-- Temporary variables start at zero in every field.\n"
           "for address = 0, Banks.SIZE do\n"
@@ -66,7 +77,7 @@ std::string FieldDataInstaller::CreateGateWayScript(
       "        return 0\n"
       "    end,\n\n"
       "    on_near = function(self, entity)\n"
-      "        if entity == \"Cloud\" then\n"
+      "        if entity ~= nil then\n"
       "            if not Data.DisableGateways then\n"
       "                load_field_map_request(\"" + target_map_name + "\", \"" + source_spawn_point_name + "\")\n"
       "            end\n"
@@ -79,6 +90,120 @@ std::string FieldDataInstaller::CreateGateWayScript(
       "}\n\n";
 }
 
+namespace{
+    /**
+     * Checks if a background trigger is in use. Unused ones are all zeroes.
+     */
+    bool IsBackgroundTriggerUsed(const VGears::TriggersFile::Trigger& t){
+        for (const auto& v : t.trigger_line){
+            if (v.x != 0 || v.y != 0 || v.z != 0) return true;
+        }
+        return false;
+    }
+
+    /**
+     * Creates the script of the entity of a background trigger.
+     *
+     * Behaviors: 0 on, 1 off, 2 on and off when away, 3 off and on when away, 4 and 5 the same as
+     * 2 and 3 (the original only reverts when the player leaves by the plus side of the line; here
+     * it is when the player leaves the line on any side).
+     */
+    std::string CreateBackgroundTriggerScript(
+      const std::string& name, const VGears::TriggersFile::Trigger& t
+    ){
+        const std::string area = std::to_string(t.background_parameter);
+        const std::string state = std::to_string(t.background_state);
+        const std::string on = "background2d:area_on(" + area + ", " + state + ")";
+        const std::string off = "background2d:area_off(" + area + ", " + state + ")";
+        std::string enter, leave;
+        switch (t.behavior){
+            case 0: enter = on; break;
+            case 1: enter = off; break;
+            case 2: case 4: enter = on; leave = off; break;
+            case 3: case 5: enter = off; leave = on; break;
+            default: break;
+        }
+        return
+          "\nEntityContainer[ \"" + name + "\" ] = {\n\n"
+          "    on_start = function(self)\n"
+          "        return 0\n"
+          "    end,\n\n"
+          "    on_approach = function(self, entity)\n"
+          "        if entity ~= nil then " + enter + " end\n"
+          "        return 0\n"
+          "    end,\n\n"
+          "    on_cross = function(self, entity)\n"
+          "        return 0\n"
+          "    end,\n\n"
+          "    on_near = function(self, entity)\n"
+          "        return 0\n"
+          "    end,\n\n"
+          "    on_leave = function(self, entity)\n"
+          "        if entity ~= nil then " + leave + " end\n"
+          "        return 0\n"
+          "    end,\n"
+          "}\n\n";
+    }
+}
+
+namespace{
+    /**
+     * Writes the data the engine needs to animate the palettes of a background.
+     *
+     * Format (little endian): "VGPL", u16 number of pages, u16 colors per page, the colors of the
+     * pages as the u16 values of the original game (5 bits per channel and the 0x8000 flag), u32
+     * number of tiles, and for each tile: u16 x, y, width, height in the image, u16 page, u8 first
+     * color hidden, and one byte per pixel with the palette index.
+     *
+     * @return True if the file was written. It is not when no tile uses an animated palette.
+     */
+    bool WritePaletteFile(
+      const std::string& path, const VGears::PaletteFilePtr& palette,
+      const std::vector<VGears::BackgroundFile::PaletteTile>& tiles,
+      const std::set<int>& pages, bool all_pages
+    ){
+        std::vector<const VGears::BackgroundFile::PaletteTile*> used;
+        for (const auto& tile : tiles){
+            if (all_pages || pages.count(tile.palette_page) > 0) used.push_back(&tile);
+        }
+        if (used.empty() || palette.isNull() || palette->GetPages().empty()) return false;
+        std::ofstream file(path, std::ios::binary);
+        if (!file.is_open()) return false;
+        auto write16 = [&file](uint16_t v){
+            const char bytes[2] = {static_cast<char>(v & 0xFF), static_cast<char>(v >> 8)};
+            file.write(bytes, 2);
+        };
+        const auto& palette_pages = palette->GetPages();
+        file.write("VGPL", 4);
+        write16(static_cast<uint16_t>(palette_pages.size()));
+        write16(static_cast<uint16_t>(palette_pages[0].size()));
+        for (const auto& page : palette_pages){
+            for (const auto& color : page){
+                const int r = static_cast<int>(std::lround(color.r * 31.0f));
+                const int g = static_cast<int>(std::lround(color.g * 31.0f));
+                const int b = static_cast<int>(std::lround(color.b * 31.0f));
+                write16(static_cast<uint16_t>(r | (g << 5) | (b << 10) | (color.a > 0.0f ? 0x8000 : 0)));
+            }
+        }
+        const uint32_t count = static_cast<uint32_t>(used.size());
+        write16(static_cast<uint16_t>(count & 0xFFFF));
+        write16(static_cast<uint16_t>(count >> 16));
+        for (const auto* tile : used){
+            write16(tile->x);
+            write16(tile->y);
+            write16(tile->width);
+            write16(tile->height);
+            write16(tile->palette_page);
+            file.put(tile->first_color_hidden ? 1 : 0);
+            file.write(
+              reinterpret_cast<const char*>(tile->indexes.data()),
+              static_cast<std::streamsize>(tile->indexes.size())
+            );
+        }
+        return true;
+    }
+}
+
 size_t FieldDataInstaller::GetFieldId(
   const std::string& name, const std::vector<std::string>& field_id_to_name_lookup
 ){
@@ -578,6 +703,14 @@ void FieldDataInstaller::PcFieldToVGearsField(VGears::FLevelFilePtr& field){
             );
         }
     }
+    const auto& bg_triggers = triggers->GetBackgroundTriggers();
+    for (size_t i = 0; i < bg_triggers.size(); i ++){
+        if (IsBackgroundTriggerUsed(bg_triggers[i])){
+            gateway_script_data += CreateBackgroundTriggerScript(
+              "BgTrigger" + std::to_string(i), bg_triggers[i]
+            );
+        }
+    }
     const VGears::ModelListFilePtr& models = field->GetModelList();
     FieldDecompiler::DecompiledScript decompiled;
     FF7FieldScriptFormatter formatter(field->getName(), models, map_list_, spawn_points_);
@@ -587,7 +720,8 @@ void FieldDataInstaller::PcFieldToVGearsField(VGears::FLevelFilePtr& field){
 
         // Decompile to LUA.
         decompiled = FieldDecompiler::Decompile(
-          field->getName(), raw_field_data, formatter, gateway_script_data, FieldScriptHeader()
+          field->getName(), raw_field_data, formatter, gateway_script_data,
+          FieldScriptHeader(static_cast<int>(GetFieldId(field->getName(), map_list_)))
         );
         std::ofstream script_file(data_dir_ + "/" + FIELD_MAPS_DIR + "/" + field->getName() + "/script.lua");
         if (script_file.is_open()){
@@ -731,6 +865,10 @@ void FieldDataInstaller::PcFieldToVGearsField(VGears::FLevelFilePtr& field){
             }
         }
 
+        // The entities (lines, scripts and models) must be in the order of the original field:
+        // the engine starts their scripts in that order, and some scripts depend on it (a script
+        // that clears the background areas has to start before the doors that set them).
+        std::vector<std::pair<uint, std::unique_ptr<TiXmlElement>>> ordered_entities;
         // Get lines. Add them to a list, so they aren't processed later as regular entities.
         std::vector<std::string> line_entities;
         const float line_scale = LINE_SCALE_FACTOR / GetFieldScaleFactor(this_field_id);
@@ -752,7 +890,7 @@ void FieldDataInstaller::PcFieldToVGearsField(VGears::FLevelFilePtr& field){
                 + " " + std::to_string(line.point_b[2] * line_scale)
             );
             xml_entity_trigger->SetAttribute("enabled", "true");
-            element->LinkEndChild(xml_entity_trigger.release());
+            ordered_entities.emplace_back(line.index, std::move(xml_entity_trigger));
         }
 
         // Get entities.
@@ -792,14 +930,19 @@ void FieldDataInstaller::PcFieldToVGearsField(VGears::FLevelFilePtr& field){
                 // translation seems to be inverted?
                 xml_entity_script->SetAttribute("scale", "0.03125 0.03125 0.03125");
                 xml_entity_script->SetAttribute("root_orientation", "0.7071067811865476 0.7071067811865476 0 0");
-                element->LinkEndChild(xml_entity_script.release());
+                ordered_entities.emplace_back(entity.index, std::move(xml_entity_script));
             }
             else{
                 std::unique_ptr<TiXmlElement> xml_entity_script(new TiXmlElement("entity_script"));
                 xml_entity_script->SetAttribute("name", entity.name);//it.first);
-                element->LinkEndChild(xml_entity_script.release());
+                ordered_entities.emplace_back(entity.index, std::move(xml_entity_script));
             }
         }
+        std::stable_sort(
+          ordered_entities.begin(), ordered_entities.end(),
+          [](const auto& a, const auto& b){return a.first < b.first;}
+        );
+        for (auto& ordered : ordered_entities) element->LinkEndChild(ordered.second.release());
         const float downscaler_this = 128.0f * GetFieldScaleFactor(this_field_id);
         for (size_t i = 0; i < gateways.size(); i ++){
             const VGears::TriggersFile::Gateway& gateway = gateways[i];
@@ -827,6 +970,31 @@ void FieldDataInstaller::PcFieldToVGearsField(VGears::FLevelFilePtr& field){
             }
         }
 
+        // Background triggers (doors and similar that change tiles).
+        const auto& bg_triggers_xml = triggers->GetBackgroundTriggers();
+        for (size_t i = 0; i < bg_triggers_xml.size(); i ++){
+            const VGears::TriggersFile::Trigger& bg_trigger = bg_triggers_xml[i];
+            if (!IsBackgroundTriggerUsed(bg_trigger)) continue;
+            std::unique_ptr<TiXmlElement> xml_entity_trigger(new TiXmlElement("entity_trigger"));
+            xml_entity_trigger->SetAttribute("name", "BgTrigger" + std::to_string(i));
+            xml_entity_trigger->SetAttribute(
+              "point1",
+              Ogre::StringConverter::toString(Ogre::Vector3(
+                bg_trigger.trigger_line[0].x, bg_trigger.trigger_line[0].y,
+                bg_trigger.trigger_line[0].z
+              ) / downscaler_this)
+            );
+            xml_entity_trigger->SetAttribute(
+              "point2",
+              Ogre::StringConverter::toString(Ogre::Vector3(
+                bg_trigger.trigger_line[1].x, bg_trigger.trigger_line[1].y,
+                bg_trigger.trigger_line[1].z
+              ) / downscaler_this)
+            );
+            xml_entity_trigger->SetAttribute("enabled", "true");
+            element->LinkEndChild(xml_entity_trigger.release());
+        }
+
         // Get music tracks
         std::vector<int> tracks = ExtractMusicTrackIds(field);
         std::unique_ptr<TiXmlElement> xml_tracks(new TiXmlElement("tracks"));
@@ -878,6 +1046,19 @@ void FieldDataInstaller::PcFieldToVGearsField(VGears::FLevelFilePtr& field){
               std::to_string(BG_PSX_SCREEN_WIDTH * BG_SCALE_UP_FACTOR) + " "
               + std::to_string(BG_PSX_SCREEN_HEIGHT * BG_SCALE_UP_FACTOR)
             );
+            // The palette animations: the tiles of the palettes a script changes are painted again
+            // by the engine.
+            if (
+              !decompiled.palette_pages.empty() || decompiled.palette_pages_dynamic
+            ){
+                const std::string palette_name = field->getName() + "/palette.bin";
+                if (WritePaletteFile(
+                  data_dir_ + "/" + FIELD_MAPS_DIR + "/" + palette_name, pal, bg->GetPaletteTiles(),
+                  decompiled.palette_pages, decompiled.palette_pages_dynamic
+                )){
+                    bg_element->SetAttribute("palette", palette_name);
+                }
+            }
             // Write out the *_BG.XML data.
             auto& layers = bg->GetLayers();
             int layer_index = -1;
@@ -911,9 +1092,12 @@ void FieldDataInstaller::PcFieldToVGearsField(VGears::FLevelFilePtr& field){
                       + Ogre::StringConverter::toString(u1) + " " + Ogre::StringConverter::toString(v1)
                     );
                     // TODO: It works (on FFVII PC), but why this number?
-                    xml_element->SetAttribute(
-                      "depth", Ogre::StringConverter::toString(static_cast<float>(sprite.depth) * (0.03125f))
-                    );
+                    // The depth is a distance from the camera, so it has the scale of the field
+                    // like the position of the camera does. The far depths (the backgrounds, from
+                    // 127 on) are only an order and are kept.
+                    float tile_depth = static_cast<float>(sprite.depth) * (0.03125f);
+                    if (tile_depth < 127.0f) tile_depth /= GetFieldScaleFactor(this_field_id);
+                    xml_element->SetAttribute("depth", Ogre::StringConverter::toString(tile_depth));
                     // TODO: Copied from DatFile::AddTile.
                     // Add to common method.
                     Ogre::String blending_str = "";
@@ -926,15 +1110,12 @@ void FieldDataInstaller::PcFieldToVGearsField(VGears::FLevelFilePtr& field){
                     xml_element->SetAttribute("blending", blending_str);
                     // The layer is needed by the scripts that scroll them at their own speed.
                     xml_element->SetAttribute("layer", layer_index);
-                    // Sprites in an area the script controls (BGON, BGOFF, BGCLR) are drawn only
-                    // while it turns on one of their layers. The rest are always drawn.
-                    if (
-                      sprite.animation_id != 0
-                      && (
-                        decompiled.background_areas_dynamic
-                        || decompiled.background_areas.count(sprite.animation_id) > 0
-                      )
-                    ){
+                    // The sprites that belong to a group (animation_id) are drawn only while a
+                    // script (BGON) or a background trigger turns on one of their states. The
+                    // original game clears the state of every group when it loads a field, so a
+                    // group that nothing turns on is never drawn (the debris behind the doors of
+                    // mds6_2, for example).
+                    if (sprite.animation_id != 0){
                         xml_element->SetAttribute("area", static_cast<int>(sprite.animation_id));
                         xml_element->SetAttribute("state", static_cast<int>(sprite.animation_frame));
                     }

+ 1 - 1
src/installer/FieldDataInstaller.h

@@ -466,7 +466,7 @@ class FieldDataInstaller{
          *
          * @return Lua code to put at the beginning of a field script.
          */
-        static std::string FieldScriptHeader();
+        static std::string FieldScriptHeader(const int field_id = -1);
 
     private:
 

+ 12 - 1
src/installer/FieldTextWriter.cpp

@@ -89,6 +89,8 @@ void FieldTextWriter::Write(const std::vector<u8>& script_section_buffer, std::s
         // Some maps have unclosed color tags.
         // Use this counter to close them at the end.
         int colour_opened = 0;
+        // Number of the next variable code of the dialog (see MPARA and MPRA2 in the scripts).
+        int variable_count = 0;
         for (unsigned char temp = 0x00;; ++ offset){
             temp = GetU8(offset);
             if (temp == 0xFF) break;
@@ -283,6 +285,13 @@ void FieldTextWriter::Write(const std::vector<u8>& script_section_buffer, std::s
                     AddText(dialog);
                     logger_->Log("<pause_ok />");
                 }
+                else if (temp2 == 0xDE){
+                    // A variable: a number that the script gives to the window (MPARA, MPRA2).
+                    // The codes of a dialog are numbered from zero, in the order they appear.
+                    AddText(dialog);
+                    logger_->Log("<variable name=\"var" + IntToString(variable_count) + "\" />");
+                    variable_count ++;
+                }
                 else if (temp2 == 0xDD){
                     u16 wait = GetU16LE(offset + 1);
                     ++ offset;
@@ -315,9 +324,11 @@ void FieldTextWriter::Write(const std::vector<u8>& script_section_buffer, std::s
                 }
             }
         }
+        // The text that was read last is still waiting to be written: it goes inside the colour
+        // that is open, so the closing tags come after it.
+        AddText(dialog);
         // Close unclosed color tags;
         for (; colour_opened > 0; colour_opened --) logger_->Log("</colour>");
-        AddText(dialog);
         logger_->Log("</dialog>\n\n");
         tag_open_ = false;
     }

+ 41 - 3
src/installer/decompiler/field/FieldCodeGenerator.cpp

@@ -13,6 +13,7 @@
  * GNU General Public License for more details.
  */
 
+#include <cctype>
 #include <boost/algorithm/string/predicate.hpp>
 #include <algorithm>
 #include <stdexcept>
@@ -224,7 +225,17 @@ void FieldCodeGenerator::Generate(InstVec& insts, const Graph& graph){
         // Add missing return:
         if ("return 0" != lines_.at(lines_.size() - 1).line && "do return 0 end" != lines_.at(lines_.size() - 1).line){
             if ("on_update" == function->first.name) AddOutputLine(ON_UPDATE_FINISHED_STATEMENT);
-            AddOutputLine("do return 0 end", false, false);
+            // A function with no return goes on in the code of the next script.
+            FunctionMetaData fall_meta(function->first.metadata);
+            const std::string next = static_cast<FieldEngine*>(engine_)->GetFunctionFallThrough(
+              fall_meta.GetEntityName(), function->first.name
+            );
+            if (!next.empty())
+                AddOutputLine(
+                  "return EntityContainer[\"" + fall_meta.GetEntityName() + "\"]."
+                  + formatter_.GetFriendlyFunctionName(fall_meta.GetEntityName(), next) + "(self)"
+                );
+            else AddOutputLine("do return 0 end", false, false);
         }
         // A goto to a label that isn't in the function can't be compiled, and the whole script
         // would fail to load. It can't continue where it was told to, so it ends the script.
@@ -256,11 +267,24 @@ void FieldCodeGenerator::AddOutputLine(std::string line, bool unindent_before, b
 
 float FieldCodeGenerator::GetScaleFactor() const{return static_cast<FieldEngine*>(engine_)->GetScaleFactor();}
 
+// A name can be a field of a table written as "name = value" only if it is an identifier of Lua. The
+// entities of some fields have names such as "60f_1".
+static bool IsLuaIdentifier(const std::string& name){
+    if (name.empty() || std::isdigit(static_cast<unsigned char>(name[0]))) return false;
+    for (const char c : name)
+        if (!std::isalnum(static_cast<unsigned char>(c)) && c != '_') return false;
+    return true;
+}
+
 void FieldCodeGenerator::OnBeforeStartFunction(const Function& function){
     FunctionMetaData meta_data(function.metadata);
     if (meta_data.IsStart()){
         AddOutputLine("EntityContainer[\"" + meta_data.GetEntityName() + "\"] = {", false, true);
         if (meta_data.GetCharacterId() != -1) AddOutputLine(meta_data.GetEntityName() + " = nil,\n");
+        // Entities without a model (the Director and other helper scripts) still run the opcodes
+        // that move or hide a model, and they do nothing. Give them an object that ignores them.
+        else if (IsLuaIdentifier(meta_data.GetEntityName()))
+            AddOutputLine(meta_data.GetEntityName() + " = NullEntity,\n");
     }
     const auto comment = formatter_.GetFunctionComment(meta_data.GetEntityName(), function.name);
     if (!comment.empty()) AddOutputLine("-- " + comment);
@@ -271,9 +295,23 @@ void FieldCodeGenerator::OnStartFunction(const Function& func){
     FunctionMetaData meta_data(func.metadata);
     if (meta_data.GetEntityName() == "Director" && func.name == "on_start"){
         // TODO: Don't hardcode Cloud, Use the one from the previous level,
+        // The entity of Cloud is called "Cloud" in most fields, but not in all of them (md0 and
+        // sinbil_1 call it "CLOUD", for example).
+        std::string player_name = "Cloud";
+        for (auto& other : static_cast<FieldEngine*>(engine_)->functions){
+            FunctionMetaData other_meta(other.second.metadata);
+            std::string lower = other_meta.GetEntityName();
+            std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
+            if (lower == "cloud"){
+                player_name = other_meta.GetEntityName();
+                break;
+            }
+        }
         AddOutputLine("-- HACK: Set default playable entity an ensure the camera follows it.");
-        AddOutputLine("place_player_at_map_entry(\"Cloud\")");
-        AddOutputLine("background2d:autoscroll_to_entity(entity_manager:get_entity(\"Cloud\"))\n");
+        AddOutputLine("place_player_at_map_entry(\"" + player_name + "\")");
+        AddOutputLine(
+          "background2d:autoscroll_to_entity(entity_manager:get_entity(\"" + player_name + "\"))\n"
+        );
     }
     // Don't run on_update again once it has reached its end.
     if (func.name == "on_update"){

+ 9 - 0
src/installer/decompiler/field/FieldCodeGenerator.h

@@ -267,6 +267,15 @@ class FieldCodeGenerator : public CodeGenerator{
           FieldScriptFormatter& formatter, uint32 bank, TValue value_or_address,
           ValueType type = ValueType::Integer, float scale = 1.0f
         ){
+            // The variables hold the values in the units of the original game, like the values
+            // written in the opcodes, so a float one has to be scaled the same way.
+            if (bank != 0 && type == ValueType::Float && scale != 1.0f){
+                return (
+                  boost::format("(%1% / %2%)")
+                  % FormatValueOrVariable(formatter, bank, value_or_address, ValueType::Integer)
+                  % scale
+                ).str();
+            }
             switch (bank){
                 case 0:
                     switch (type){

+ 2 - 0
src/installer/decompiler/field/FieldDecompiler.cpp

@@ -55,5 +55,7 @@ FieldDecompiler::DecompiledScript FieldDecompiler::Decompile(
     for (auto line : engine.GetLineList()) ds.lines.push_back(line);
     ds.background_areas = engine.GetBackgroundAreas();
     ds.background_areas_dynamic = engine.BackgroundAreasAreDynamic();
+    ds.palette_pages = engine.GetPalettePages();
+    ds.palette_pages_dynamic = engine.PalettePagesAreDynamic();
     return ds;
 }

+ 17 - 0
src/installer/decompiler/field/FieldDecompiler.h

@@ -40,6 +40,11 @@ class FieldDecompiler: public Decompiler{
              */
             std::string name;
 
+            /**
+             * Index of the line entity in the field.
+             */
+            uint index = 0;
+
             /**
              * First point of the line.
              */
@@ -107,6 +112,18 @@ class FieldDecompiler: public Decompiler{
              * If so, it is not known which areas it controls, and any of them might be.
              */
             bool background_areas_dynamic = false;
+
+            /**
+             * Palette pages the script changes (palette animations).
+             */
+            std::set<int> palette_pages;
+
+            /**
+             * Whether the script picks palette pages from variables.
+             *
+             * If so, it is not known which palettes it changes, and any of them might be.
+             */
+            bool palette_pages_dynamic = false;
         };
 
         /**

+ 20 - 0
src/installer/decompiler/field/FieldDisassembler.cpp

@@ -243,6 +243,25 @@ void FieldDisassembler::AddFunc(
         while (stream_->GetPosition() != next_script_entry_point + section_pointers_size_)
             is_line = ReadOpCodesToPositionOrReturn(next_script_entry_point + section_pointers_size_, point_a, point_b);
     }
+    // A script that doesn't end with a return runs into the code of the script that starts where it
+    // ends (the question of ealin_2 is asked by a script that goes on in the one that handles the
+    // answer).
+    if (script_index > 0 && !to_return_only && !engine_->EntityIsLine(entity_index)){
+        const bool ends = last_opcode_ == OPCODES::RET || last_opcode_ == OPCODES::JMPF
+          || last_opcode_ == OPCODES::JMPFL || last_opcode_ == OPCODES::JMPB
+          || last_opcode_ == OPCODES::JMPBL;
+        if (!ends){
+            const auto& entries = header_.entity_scripts[entity_index];
+            for (size_t i = 1; i < entries.size(); ++ i){
+                if (entries[i] != next_script_entry_point || i == script_index) continue;
+                const std::string target = (i == 1) ? "on_interact" : "script_" + std::to_string(i);
+                engine_->AddFunctionFallThrough(
+                  entity_name, func_name.empty() ? func->name : func_name, target
+                );
+                break;
+            }
+        }
+    }
     // Read metadata, mark start and/or end.
     std::string meta_data;
     if (is_start && is_end) meta_data = "start_end_";
@@ -352,6 +371,7 @@ bool FieldDisassembler::ReadOpCodesToPositionOrReturn(
     while (stream_->GetPosition() < end_pos){
 
         uint8 opcode = stream_->ReadU8();
+        last_opcode_ = opcode;
         uint32 full_opcode = 0;
         full_opcode = (full_opcode << 8) + opcode;
         switch (opcode){

+ 5 - 0
src/installer/decompiler/field/FieldDisassembler.h

@@ -756,6 +756,11 @@ class FieldDisassembler : public Disassembler{
          */
         int16 section_pointers_size_;
 
+        /**
+         * The last opcode read by ReadOpCodesToPositionOrReturn.
+         */
+        uint8 last_opcode_ = 0xFF;
+
         /**
          * The field header.
          */

+ 23 - 0
src/installer/decompiler/field/FieldEngine.cpp

@@ -184,6 +184,7 @@ std::vector<FieldDecompiler::Line> FieldEngine::GetLineList() const{
         if (entity.second.IsLine() == true){
             FieldDecompiler::Line line;
             line.name = entity.second.GetName();
+            line.index = entity.second.GetIndex();
             line.point_a = entity.second.GetLinePointA();
             line.point_b = entity.second.GetLinePointB();
             lines.push_back(line);
@@ -201,6 +202,15 @@ const std::set<int>& FieldEngine::GetBackgroundAreas() const{return background_a
 
 bool FieldEngine::BackgroundAreasAreDynamic() const{return background_areas_dynamic_;}
 
+void FieldEngine::AddPalettePage(int page){
+    if (page < 0) palette_pages_dynamic_ = true;
+    else palette_pages_.insert(page);
+}
+
+const std::set<int>& FieldEngine::GetPalettePages() const{return palette_pages_;}
+
+bool FieldEngine::PalettePagesAreDynamic() const{return palette_pages_dynamic_;}
+
 void FieldEngine::AddEntityFunction(
   const std::string& entity_name, size_t entity_index, const std::string& func_name, size_t func_index
 ){
@@ -219,6 +229,19 @@ void FieldEngine::AddFunctionAlias(
     function_aliases_.push_back(FunctionAlias{entity_name, alias, target});
 }
 
+void FieldEngine::AddFunctionFallThrough(
+  const std::string& entity_name, const std::string& function, const std::string& target
+){
+    function_fall_through_[entity_name + "/" + function] = target;
+}
+
+std::string FieldEngine::GetFunctionFallThrough(
+  const std::string& entity_name, const std::string& function
+) const{
+    const auto it = function_fall_through_.find(entity_name + "/" + function);
+    return it == function_fall_through_.end() ? "" : it->second;
+}
+
 void FieldEngine::MarkEntityAsLine(
   size_t entity_index, bool line, std::vector<float> point_a, std::vector<float> point_b
 ){

+ 60 - 0
src/installer/decompiler/field/FieldEngine.h

@@ -20,6 +20,7 @@
 
 #include <set>
 #include <string>
+#include <map>
 #include <vector>
 
 #include "FieldScriptFormatter.h"
@@ -290,6 +291,27 @@ class FieldEngine : public Engine{
          */
         bool BackgroundAreasAreDynamic() const;
 
+        /**
+         * Adds a palette the script changes (it loads colors into it).
+         *
+         * @param[in] page The palette page, or -1 if it is picked from a variable.
+         */
+        void AddPalettePage(int page);
+
+        /**
+         * Retrieves the palette pages the script changes.
+         *
+         * @return The page IDs.
+         */
+        const std::set<int>& GetPalettePages() const;
+
+        /**
+         * Checks if the script picks any palette page from a variable.
+         *
+         * @return True if it does.
+         */
+        bool PalettePagesAreDynamic() const;
+
         /**
          * Retrieves all entities in the map.
          *
@@ -333,6 +355,29 @@ class FieldEngine : public Engine{
           const std::string& entity_name, const std::string& alias, const std::string& target
         );
 
+        /**
+         * Records that a function has no return and goes on in the code of another function of
+         * the same entity (the code of one script runs into the entry point of the next).
+         *
+         * @param[in] entity_name Name of the entity.
+         * @param[in] function Name of the function that doesn't end.
+         * @param[in] target Name of the function it goes on in.
+         */
+        void AddFunctionFallThrough(
+          const std::string& entity_name, const std::string& function, const std::string& target
+        );
+
+        /**
+         * Retrieves the name of the function a function goes on in, if it doesn't end.
+         *
+         * @param[in] entity_name Name of the entity.
+         * @param[in] function Name of the function.
+         * @return The name of the function it goes on in, empty if it ends.
+         */
+        std::string GetFunctionFallThrough(
+          const std::string& entity_name, const std::string& function
+        ) const;
+
         /**
          * Retrieves the functions that are another name for other function.
          *
@@ -438,6 +483,11 @@ class FieldEngine : public Engine{
          */
         std::vector<FunctionAlias> function_aliases_;
 
+        /**
+         * Functions that go on in another one, by "entity/function".
+         */
+        std::map<std::string, std::string> function_fall_through_;
+
         /**
          * The map scale factor.
          */
@@ -453,6 +503,16 @@ class FieldEngine : public Engine{
          */
         bool background_areas_dynamic_ = false;
 
+        /**
+         * Palette pages the script changes.
+         */
+        std::set<int> palette_pages_;
+
+        /**
+         * Whether the script picks any palette page from a variable.
+         */
+        bool palette_pages_dynamic_ = false;
+
         /**
          * The script name.
          */

+ 68 - 26
src/installer/decompiler/field/instruction/FieldBackgroundInstruction.cpp

@@ -33,14 +33,14 @@ void FieldBackgroundInstruction::ProcessInst(
     switch (opcode_){
         case OPCODES::BGPDH: ProcessBGPDH(code_gen); break;
         case OPCODES::BGSCR: ProcessBGSCR(code_gen); break;
-        case OPCODES::MPPAL: code_gen->WriteTodo(md.GetEntityName(), "MPPAL"); break;
+        case OPCODES::MPPAL: ProcessMPPAL(code_gen); break;
         case OPCODES::BGON: ProcessBGON(code_gen, static_cast<FieldEngine&>(*engine)); break;
         case OPCODES::BGOFF: ProcessBGOFF(code_gen, static_cast<FieldEngine&>(*engine)); break;
         case OPCODES::BGROL: code_gen->WriteTodo(md.GetEntityName(), "BGROL"); break;
         case OPCODES::BGROL2: code_gen->WriteTodo(md.GetEntityName(), "BGROL2"); break;
         case OPCODES::BGCLR: ProcessBGCLR(code_gen, static_cast<FieldEngine&>(*engine)); break;
         case OPCODES::STPAL: ProcessSTPAL(code_gen); break;
-        case OPCODES::LDPAL: ProcessLDPAL(code_gen); break;
+        case OPCODES::LDPAL: ProcessLDPAL(code_gen, static_cast<FieldEngine&>(*engine)); break;
         case OPCODES::CPPAL: ProcessCPPAL(code_gen); break;
         case OPCODES::RTPAL: code_gen->WriteTodo(md.GetEntityName(), "RTPAL"); break;
         case OPCODES::ADPAL: ProcessADPAL(code_gen); break;
@@ -131,33 +131,52 @@ void FieldBackgroundInstruction::ProcessBGCLR(CodeGenerator* code_gen, FieldEngi
     );
 }
 
+namespace{
+    /**
+     * Formats the number of colors of a palette opcode: the byte is the number minus one.
+     */
+    std::string PaletteCount(
+      FieldCodeGenerator* cg, uint32 bank, uint32 value
+    ){
+        if (bank == 0) return std::to_string(value + 1);
+        return "(" + FieldCodeGenerator::FormatValueOrVariable(cg->GetFormatter(), bank, value)
+          + " + 1)";
+    }
+}
+
+// The palette opcodes work on an array of palettes in memory (the "slots", 16 colors each) and on
+// the palettes of the background (the "pages"). They are implemented by the palette of the 2D
+// background, see BackgroundPalette. The meaning of the parameters and the arithmetic come from the
+// opcode handlers of ff7.exe.
+
 void FieldBackgroundInstruction::ProcessSTPAL(CodeGenerator* code_gen){
     FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
-    const auto& source = FieldCodeGenerator::FormatValueOrVariable(
+    const auto& page = FieldCodeGenerator::FormatValueOrVariable(
       cg->GetFormatter(), params_[0]->GetUnsigned(), params_[2]->GetUnsigned()
     );
-    const auto& destination = FieldCodeGenerator::FormatValueOrVariable(
+    const auto& slot = FieldCodeGenerator::FormatValueOrVariable(
       cg->GetFormatter(), params_[1]->GetUnsigned(), params_[3]->GetUnsigned()
     );
-    auto num_entries = params_[4]->GetUnsigned() + 1;
+    const auto count = params_[4]->GetUnsigned() + 1;
+    // Stores the first colors of a palette page in the array of palettes.
     code_gen->AddOutputLine((
-      boost::format("-- store palette %1% to position %2%, start CLUT index 0, %3% entries")
-      % source % destination % num_entries
+      boost::format("background2d:palette_store(%1%, %2%, %3%)") % page % slot % count
     ).str());
 }
 
-void FieldBackgroundInstruction::ProcessLDPAL(CodeGenerator* code_gen){
+void FieldBackgroundInstruction::ProcessLDPAL(CodeGenerator* code_gen, FieldEngine& engine){
     FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
-    const auto& source = FieldCodeGenerator::FormatValueOrVariable(
+    const auto& slot = FieldCodeGenerator::FormatValueOrVariable(
       cg->GetFormatter(), params_[0]->GetUnsigned(), params_[2]->GetUnsigned()
     );
-    const auto& destination = FieldCodeGenerator::FormatValueOrVariable(
+    const auto& page = FieldCodeGenerator::FormatValueOrVariable(
       cg->GetFormatter(), params_[1]->GetUnsigned(), params_[3]->GetUnsigned()
     );
-    auto num_entries = params_[4]->GetUnsigned() + 1;
+    engine.AddPalettePage(params_[1]->GetUnsigned() == 0 ? params_[3]->GetUnsigned() : -1);
+    const auto count = params_[4]->GetUnsigned() + 1;
+    // Loads the first colors of a palette page from the array of palettes.
     code_gen->AddOutputLine((
-      boost::format("-- load palette %2% from position %1%, start CLUT index 0, %3% entries")
-      % source % destination % num_entries
+      boost::format("background2d:palette_load(%1%, %2%, %3%)") % slot % page % count
     ).str());
 }
 
@@ -169,10 +188,9 @@ void FieldBackgroundInstruction::ProcessCPPAL(CodeGenerator* code_gen){
     const auto& destination = FieldCodeGenerator::FormatValueOrVariable(
       cg->GetFormatter(), params_[1]->GetUnsigned(), params_[3]->GetUnsigned()
     );
-    auto num_entries = params_[4]->GetUnsigned() + 1;
+    const auto count = params_[4]->GetUnsigned() + 1;
     code_gen->AddOutputLine((
-      boost::format("-- copy palette %1% to palette %2%, %3% entries")
-      % source % destination % num_entries
+      boost::format("background2d:palette_copy(%1%, %2%, %3%)") % source % destination % count
     ).str());
 }
 
@@ -193,12 +211,11 @@ void FieldBackgroundInstruction::ProcessADPAL(CodeGenerator* code_gen){
     const auto& b = FieldCodeGenerator::FormatValueOrVariable(
       cg->GetFormatter(), params_[2]->GetUnsigned(), params_[8]->GetUnsigned()
     );
-    auto num_entries = params_[11]->GetUnsigned() + 1;
+    const auto count = params_[11]->GetUnsigned() + 1;
+    // Adds a signed value to each 5 bit channel of the colors of a palette in the array.
     code_gen->AddOutputLine((
-      boost::format(
-        "-- add RGB(%3%, %4%, %5%) to %6% entries of palette stored at position %1%, "
-        "storing result in position %2%"
-      ) % source % destination % r % g % b % num_entries
+      boost::format("background2d:palette_add(%1%, %2%, %3%, %4%, %5%, %6%)")
+      % source % destination % r % g % b % count
     ).str());
 }
 
@@ -219,12 +236,37 @@ void FieldBackgroundInstruction::ProcessMPPAL2(CodeGenerator* code_gen){
     const auto& b = FieldCodeGenerator::FormatValueOrVariable(
       cg->GetFormatter(), params_[2]->GetUnsigned(), params_[8]->GetUnsigned()
     );
-    auto num_entries = params_[11]->GetUnsigned() + 1;
+    const auto count = params_[11]->GetUnsigned() + 1;
+    // Multiplies each channel of the colors of a palette in the array (64 is 1.0).
     code_gen->AddOutputLine((
-      boost::format(
-        "-- multiply RGB(%3%, %4%, %5%) by %6% entries of palette stored at position %1%, "
-        "storing result in position %2%"
-      ) % source % destination % r % g % b % num_entries).str());
+      boost::format("background2d:palette_multiply(%1%, %2%, 0, %6%, %3%, %4%, %5%)")
+      % source % destination % r % g % b % count
+    ).str());
+}
+
+void FieldBackgroundInstruction::ProcessMPPAL(CodeGenerator* code_gen){
+    // Like MPPAL2, but only from a start color. The banks are: start color, blue, green, red and
+    // the number of colors. The palettes in the array are always values.
+    FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
+    const auto source = params_[6]->GetUnsigned();
+    const auto destination = params_[7]->GetUnsigned();
+    const auto& start = FieldCodeGenerator::FormatValueOrVariable(
+      cg->GetFormatter(), params_[0]->GetUnsigned(), params_[8]->GetUnsigned()
+    );
+    const auto& b = FieldCodeGenerator::FormatValueOrVariable(
+      cg->GetFormatter(), params_[1]->GetUnsigned(), params_[9]->GetUnsigned()
+    );
+    const auto& g = FieldCodeGenerator::FormatValueOrVariable(
+      cg->GetFormatter(), params_[2]->GetUnsigned(), params_[10]->GetUnsigned()
+    );
+    const auto& r = FieldCodeGenerator::FormatValueOrVariable(
+      cg->GetFormatter(), params_[3]->GetUnsigned(), params_[11]->GetUnsigned()
+    );
+    const auto count = PaletteCount(cg, params_[5]->GetUnsigned(), params_[12]->GetUnsigned());
+    code_gen->AddOutputLine((
+      boost::format("background2d:palette_multiply(%1%, %2%, %3%, %4%, %5%, %6%, %7%)")
+      % source % destination % start % count % r % g % b
+    ).str());
 }
 
 void FieldBackgroundInstruction::ProcessSTPLS(CodeGenerator* code_gen){

+ 2 - 1
src/installer/decompiler/field/instruction/FieldBackgroundInstruction.h

@@ -49,9 +49,10 @@ class FieldBackgroundInstruction : public KernelCallInstruction{
         void ProcessBGOFF(CodeGenerator* code_gen, FieldEngine& engine);
         void ProcessBGCLR(CodeGenerator* code_gen, FieldEngine& engine);
         void ProcessSTPAL(CodeGenerator* code_gen);
-        void ProcessLDPAL(CodeGenerator* code_gen);
+        void ProcessLDPAL(CodeGenerator* code_gen, FieldEngine& engine);
         void ProcessCPPAL(CodeGenerator* code_gen);
         void ProcessADPAL(CodeGenerator* code_gen);
+        void ProcessMPPAL(CodeGenerator* code_gen);
         void ProcessMPPAL2(CodeGenerator* code_gen);
         void ProcessSTPLS(CodeGenerator* code_gen);
         void ProcessLDPLS(CodeGenerator* code_gen);

+ 17 - 3
src/installer/decompiler/field/instruction/FieldControlFlowInstruction.cpp

@@ -50,9 +50,9 @@ void FieldControlFlowInstruction::ProcessInst(
         case OPCODES::REQ: ProcessREQ(code_gen, eng); break;
         case OPCODES::REQSW: ProcessREQSW(code_gen, eng); break;
         case OPCODES::REQEW: ProcessREQEW(code_gen, eng); break;
-        case OPCODES::PREQ: code_gen->WriteTodo(md.GetEntityName(), "PREQ"); break;
-        case OPCODES::PRQSW: code_gen->WriteTodo(md.GetEntityName(), "PRQSW"); break;
-        case OPCODES::PRQEW: code_gen->WriteTodo(md.GetEntityName(), "PRQEW"); break;
+        case OPCODES::PREQ: ProcessPartyRequest(code_gen, "request"); break;
+        case OPCODES::PRQSW: ProcessPartyRequest(code_gen, "start_sync"); break;
+        case OPCODES::PRQEW: ProcessPartyRequest(code_gen, "end_sync"); break;
         case OPCODES::RETTO: ProcessRETTO(code_gen); break;
         case OPCODES::WAIT: ProcessWAIT(code_gen); break;
         default:
@@ -62,6 +62,20 @@ void FieldControlFlowInstruction::ProcessInst(
     }
 }
 
+void FieldControlFlowInstruction::ProcessPartyRequest(
+  CodeGenerator* code_gen, const std::string& mode
+){
+    // Operands: the character (the one given to the PC opcode of the entity), the priority and the
+    // index of the script. The entity is the one of that character, which is known when running.
+    const auto script_index = params_[2]->GetUnsigned();
+    const std::string script_name
+      = (script_index == 1) ? "on_interact" : "script_" + std::to_string(script_index);
+    code_gen->AddOutputLine((
+      boost::format("party_request(%1%, \"%2%\", %3%, \"%4%\")")
+      % params_[0]->GetSigned() % script_name % params_[1]->GetUnsigned() % mode
+    ).str());
+}
+
 void FieldControlFlowInstruction::ProcessREQ(
   CodeGenerator* code_gen, const FieldEngine& engine
 ){

+ 1 - 0
src/installer/decompiler/field/instruction/FieldControlFlowInstruction.h

@@ -75,6 +75,7 @@ class FieldControlFlowInstruction : public KernelCallInstruction{
          * @param[in,out] code_gen Code generator to append lines.
          * @param[in] engine The engine.
          */
+        void ProcessPartyRequest(CodeGenerator* code_gen, const std::string& mode);
         void ProcessREQ(CodeGenerator* code_gen, const FieldEngine& engine);
 
         /**

+ 35 - 12
src/installer/decompiler/field/instruction/FieldMathInstruction.cpp

@@ -55,10 +55,14 @@ void FieldMathInstruction::ProcessInst(
         case OPCODES::MINUS2:
             ProcessPLUSx_MINUSx(code_gen, "-");
             break;
-        case OPCODES::MUL: code_gen->WriteTodo(md.GetEntityName(), "MUL"); break;
-        case OPCODES::MUL2: code_gen->WriteTodo(md.GetEntityName(), "MUL2"); break;
-        case OPCODES::DIV: code_gen->WriteTodo(md.GetEntityName(), "DIV"); break;
-        case OPCODES::DIV2: code_gen->WriteTodo(md.GetEntityName(), "DIV2"); break;
+        case OPCODES::MUL:
+        case OPCODES::MUL2:
+            ProcessPLUSx_MINUSx(code_gen, "*");
+            break;
+        case OPCODES::DIV:
+        case OPCODES::DIV2:
+            ProcessFunctionOfTwo(code_gen, "math_div");
+            break;
         case OPCODES::MOD:
             {
                 const uint32 source_bank = params_[0]->GetUnsigned();
@@ -76,13 +80,19 @@ void FieldMathInstruction::ProcessInst(
                 );
             }
         break;
-        case OPCODES::MOD2: code_gen->WriteTodo(md.GetEntityName(), "MOD2"); break;
-        case OPCODES::AND: code_gen->WriteTodo(md.GetEntityName(), "AND"); break;
-        case OPCODES::AND2: code_gen->WriteTodo(md.GetEntityName(), "AND2"); break;
-        case OPCODES::OR: code_gen->WriteTodo(md.GetEntityName(), "OR"); break;
-        case OPCODES::OR2: code_gen->WriteTodo(md.GetEntityName(), "OR2"); break;
-        case OPCODES::XOR: code_gen->WriteTodo(md.GetEntityName(), "XOR"); break;
-        case OPCODES::XOR2: code_gen->WriteTodo(md.GetEntityName(), "XOR2"); break;
+        case OPCODES::MOD2: ProcessPLUSx_MINUSx(code_gen, "%"); break;
+        case OPCODES::AND:
+        case OPCODES::AND2:
+            ProcessFunctionOfTwo(code_gen, "bit_and");
+            break;
+        case OPCODES::OR:
+        case OPCODES::OR2:
+            ProcessFunctionOfTwo(code_gen, "bit_or");
+            break;
+        case OPCODES::XOR:
+        case OPCODES::XOR2:
+            ProcessFunctionOfTwo(code_gen, "bit_xor");
+            break;
         case OPCODES::INC:
         case OPCODES::INC2:
             ProcessINCx_DECx(code_gen, "+");
@@ -207,7 +217,7 @@ void FieldMathInstruction::ProcessSaturatedDEC2(CodeGenerator* code_gen){
 void FieldMathInstruction::ProcessRDMSD(CodeGenerator* code_gen){
     // TODO: we don't have os.time...
     // TODO: RNG emulation?
-    code_gen->AddOutputLine("math.randomseed(os.time())");
+    code_gen->AddOutputLine("-- RDMSD: the random generator is seeded by the engine");
 }
 
 void FieldMathInstruction::ProcessSETBYTE_SETWORD(CodeGenerator* code_gen){
@@ -248,6 +258,19 @@ void FieldMathInstruction::ProcessPLUSx_MINUSx(CodeGenerator* code_gen, const st
     code_gen->AddOutputLine((boost::format("%1% = %1% %2% %3%") % lhs % op % rhs).str());
 }
 
+void FieldMathInstruction::ProcessFunctionOfTwo(CodeGenerator* code_gen, const std::string& function){
+    // The variable gets the result of a function (a bit operation, or a division) of its value and
+    // the value or variable of the second operand, as PLUS does with the sum.
+    FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
+    const auto& lhs = FieldCodeGenerator::FormatValueOrVariable(
+      cg->GetFormatter(), params_[0]->GetUnsigned(), params_[2]->GetUnsigned()
+    );
+    const auto& rhs = FieldCodeGenerator::FormatValueOrVariable(
+      cg->GetFormatter(), params_[1]->GetUnsigned(), params_[3]->GetUnsigned()
+    );
+    code_gen->AddOutputLine((boost::format("%1% = %2%(%1%, %3%)") % lhs % function % rhs).str());
+}
+
 void FieldMathInstruction::ProcessINCx_DECx(CodeGenerator* code_gen, const std::string& op){
     FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
     // TODO: Check for assignment to value.

+ 2 - 0
src/installer/decompiler/field/instruction/FieldMathInstruction.h

@@ -115,6 +115,8 @@ class FieldMathInstruction : public StoreInstruction{
 
         void ProcessPLUSx_MINUSx(CodeGenerator* code_gen, const std::string& op);
 
+        void ProcessFunctionOfTwo(CodeGenerator* code_gen, const std::string& function);
+
         void ProcessINCx_DECx(CodeGenerator* code_gen, const std::string& op);
 
         void ProcessRANDOM(CodeGenerator* code_gen);

+ 24 - 2
src/installer/decompiler/field/instruction/FieldMediaInstruction.cpp

@@ -44,8 +44,8 @@ void FieldMediaInstruction::ProcessInst(
         case OPCODES::MOVIE: ProcessMOVIE(code_gen); break;
         case OPCODES::MVIEF: ProcessMVIEF(code_gen); break;
         case OPCODES::FMUSC: code_gen->WriteTodo(md.GetEntityName(), "FMUSC"); break;
-        case OPCODES::CMUSC: code_gen->WriteTodo(md.GetEntityName(), "CMUSC"); break;
-        case OPCODES::CHMST: code_gen->WriteTodo(md.GetEntityName(), "CHMST"); break;
+        case OPCODES::CMUSC: ProcessCMUSC(code_gen); break;
+        case OPCODES::CHMST: ProcessCHMST(code_gen); break;
         default:
             code_gen->AddOutputLine(FieldCodeGenerator::FormatInstructionNotImplemented(
               md.GetEntityName(), address_, opcode_
@@ -84,6 +84,28 @@ void FieldMediaInstruction::ProcessBMUSC(CodeGenerator* code_gen){
     );
 }
 
+void FieldMediaInstruction::ProcessCMUSC(CodeGenerator* code_gen){
+    // Changes the music to one of the tracks of the field. The parameters are the track, one that
+    // is always 0, the fade out, the fade in and three that are always 0.
+    code_gen->AddOutputLine((
+      boost::format("change_map_music(%1%, %2%, %3%)")
+      % params_[0]->GetUnsigned() % params_[2]->GetUnsigned() % params_[3]->GetUnsigned()
+    ).str());
+}
+
+void FieldMediaInstruction::ProcessCHMST(CodeGenerator* code_gen){
+    // Stores in a variable if there is music playing. The first parameter is the bank, in the
+    // two nibbles of the first byte, and the second one the address.
+    FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
+    const auto& destination = FieldCodeGenerator::FormatValueOrVariable(
+      cg->GetFormatter(), params_[0]->GetUnsigned() * 16 + params_[1]->GetUnsigned(),
+      params_[2]->GetUnsigned()
+    );
+    code_gen->AddOutputLine((
+      boost::format("%1% = audio_manager:is_music_playing() and 1 or 0") % destination
+    ).str());
+}
+
 void FieldMediaInstruction::ProcessMUSIC(CodeGenerator* code_gen){
     code_gen->AddOutputLine(
       (boost::format("play_map_music(%1%)") % params_[0]->GetUnsigned()).str()

+ 4 - 0
src/installer/decompiler/field/instruction/FieldMediaInstruction.h

@@ -45,6 +45,10 @@ class FieldMediaInstruction : public KernelCallInstruction{
 
         void ProcessBMUSC(CodeGenerator* code_gen);
 
+        void ProcessCMUSC(CodeGenerator* code_gen);
+
+        void ProcessCHMST(CodeGenerator* code_gen);
+
         void ProcessMUSIC(CodeGenerator* code_gen);
 
         void ProcessSOUND(CodeGenerator* code_gen);

+ 56 - 10
src/installer/decompiler/field/instruction/FieldModelInstruction.cpp

@@ -94,7 +94,11 @@ void FieldModelInstruction::ProcessInst(
         case (OPCODES::KAWAI << 8) | OPCODES_KAWAI::RESET:
             code_gen->WriteTodo(md.GetEntityName(), "RESET");
             break;
-        case OPCODES::KAWIW: code_gen->WriteTodo(md.GetEntityName(), "KAWIW"); break;
+        case OPCODES::KAWIW:
+            // Waits for the last KAWAI operation (eyes, light, transparency...) to end. Those
+            // operations are not implemented, so there is nothing to wait for.
+            code_gen->AddOutputLine("-- KAWIW: no KAWAI operation to wait for");
+            break;
         case OPCODES::PMOVA: code_gen->WriteTodo(md.GetEntityName(), "PMOVA"); break;
         case OPCODES::PDIRA: code_gen->WriteTodo(md.GetEntityName(), "PDIRA"); break;
         case OPCODES::PTURA: code_gen->WriteTodo(md.GetEntityName(), "PTURA"); break;
@@ -114,9 +118,9 @@ void FieldModelInstruction::ProcessInst(
         case OPCODES::VISI: ProcessVISI(code_gen, md.GetEntityName()); break;
         case OPCODES::XYZI: ProcessXYZI(code_gen, md.GetEntityName()); break;
         case OPCODES::XYI: ProcessXYI(code_gen, md.GetEntityName()); break;
-        case OPCODES::XYZ: code_gen->WriteTodo(md.GetEntityName(), "XYZ"); break;
+        case OPCODES::XYZ: ProcessXYZ(code_gen, md.GetEntityName()); break;
         case OPCODES::MOVE: ProcessMOVE(code_gen, md.GetEntityName()); break;
-        case OPCODES::CMOVE: code_gen->WriteTodo(md.GetEntityName(), "CMOVE"); break;
+        case OPCODES::CMOVE: ProcessCMOVE(code_gen, md.GetEntityName()); break;
         case OPCODES::MOVA: ProcessMOVA(code_gen, md.GetEntityName(), eng); break;
         case OPCODES::TURA: ProcessTURA(code_gen, md.GetEntityName(), eng); break;
         case OPCODES::ANIMW: ProcessANIMW(code_gen, md.GetEntityName()); break;
@@ -327,9 +331,9 @@ void FieldModelInstruction::ProcessTALKR(CodeGenerator* code_gen, const std::str
         );
     }
     else{
-        // A variable: the scale is not applied yet.
+        // A variable: FormatValueOrVariable already scales it.
         code_gen->AddOutputLine(
-          "self." + entity + ":set_talk_radius((" + range_value + ") / " + std::to_string(scale) + ")"
+          "self." + entity + ":set_talk_radius(" + range_value + ")"
         );
     }
 }
@@ -459,17 +463,36 @@ void FieldModelInstruction::ProcessXYZI(CodeGenerator* code_gen, const std::stri
     ).str());
 }
 
+void FieldModelInstruction::ProcessXYZ(CodeGenerator* code_gen, const std::string& entity){
+    // Like XYZI, but without a triangle: the entity is placed on the walkmesh when it moves.
+    FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
+    const float scale = 128.0f * cg->GetScaleFactor();
+    const auto& x = FieldCodeGenerator::FormatValueOrVariable(
+      cg->GetFormatter(), params_[0]->GetUnsigned(), params_[4]->GetSigned(),
+      FieldCodeGenerator::ValueType::Float, scale
+    );
+    const auto& y = FieldCodeGenerator::FormatValueOrVariable(
+      cg->GetFormatter(), params_[1]->GetUnsigned(), params_[5]->GetSigned(),
+      FieldCodeGenerator::ValueType::Float, scale
+    );
+    const auto& z = FieldCodeGenerator::FormatValueOrVariable(
+      cg->GetFormatter(), params_[2]->GetUnsigned(), params_[6]->GetSigned(),
+      FieldCodeGenerator::ValueType::Float, scale
+    );
+    code_gen->AddOutputLine((
+      boost::format("self.%1%:set_position(%2%, %3%, %4%)") % entity % x % y % z
+    ).str());
+}
+
 void FieldModelInstruction::ProcessXYI(CodeGenerator* code_gen, const std::string& entity){
     FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
     const float scale = 128.0f * cg->GetScaleFactor();
-    // Constants are already scaled by the formatter, but values read from a bank (usually stored
-    // by AXYZI) are in field units, so they need to be scaled here.
+    // Constants and values read from a bank (usually stored by AXYZI, in field units) are scaled
+    // by the formatter.
     const auto format_coordinate = [&](uint32 bank, int16 value){
-        const auto& formatted = FieldCodeGenerator::FormatValueOrVariable(
+        return FieldCodeGenerator::FormatValueOrVariable(
           cg->GetFormatter(), bank, value, FieldCodeGenerator::ValueType::Float, scale
         );
-        if (bank == 0) return formatted;
-        return "(" + formatted + ") / " + std::to_string(scale);
     };
     const auto x = format_coordinate(params_[0]->GetUnsigned(), params_[4]->GetSigned());
     const auto y = format_coordinate(params_[1]->GetUnsigned(), params_[5]->GetSigned());
@@ -499,6 +522,29 @@ void FieldModelInstruction::ProcessMOVE(CodeGenerator* code_gen, const std::stri
     code_gen->AddOutputLine((boost::format("self.%1%:move_sync()") % entity).str());
 }
 
+void FieldModelInstruction::ProcessCMOVE(CodeGenerator* code_gen, const std::string& entity){
+    FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
+    const float scale = 128.0f * cg->GetScaleFactor();
+    const auto& x = FieldCodeGenerator::FormatValueOrVariable(
+      cg->GetFormatter(), params_[0]->GetUnsigned(), params_[2]->GetSigned(),
+      FieldCodeGenerator::ValueType::Float, scale
+    );
+    const auto& y = FieldCodeGenerator::FormatValueOrVariable(
+      cg->GetFormatter(), params_[1]->GetUnsigned(), params_[3]->GetSigned(),
+      FieldCodeGenerator::ValueType::Float, scale
+    );
+    // Like MOVE, but the entity doesn't play its walk animation and doesn't turn to the
+    // direction of the move (a sliding door, for example).
+    code_gen->AddOutputLine((boost::format("self.%1%:move_auto_animation(false)") % entity).str());
+    code_gen->AddOutputLine((boost::format("self.%1%:move_auto_rotation(false)") % entity).str());
+    code_gen->AddOutputLine(
+      (boost::format("self.%1%:move_to_position(%2%, %3%)") % entity % x % y).str()
+    );
+    code_gen->AddOutputLine((boost::format("self.%1%:move_sync()") % entity).str());
+    code_gen->AddOutputLine((boost::format("self.%1%:move_auto_rotation(true)") % entity).str());
+    code_gen->AddOutputLine((boost::format("self.%1%:move_auto_animation(true)") % entity).str());
+}
+
 void FieldModelInstruction::ProcessFMOVE(CodeGenerator* code_gen, const std::string& entity){
     FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
     const float scale = 128.0f * cg->GetScaleFactor();

+ 2 - 0
src/installer/decompiler/field/instruction/FieldModelInstruction.h

@@ -158,6 +158,7 @@ class FieldModelInstruction : public KernelCallInstruction{
          * Processes a XYI opcode: sets the X and Y position of the entity (and its triangle).
          * Unlike XYZI, it doesn't change the visibility of the entity.
          */
+        void ProcessXYZ(CodeGenerator* code_gen, const std::string& entity);
         void ProcessXYI(CodeGenerator* code_gen, const std::string& entity);
 
         void ProcessMOVE(CodeGenerator* code_gen, const std::string& entity);
@@ -309,6 +310,7 @@ class FieldModelInstruction : public KernelCallInstruction{
          * @param[in,out] code_gen Code generator to append lines.
          * @param[in] entity Name of the entity.
          */
+        void ProcessCMOVE(CodeGenerator* code_gen, const std::string& entity);
         void ProcessFMOVE(CodeGenerator* code_gen, const std::string& entity);
 
         /**

+ 18 - 1
src/installer/decompiler/field/instruction/FieldModuleInstruction.cpp

@@ -78,7 +78,7 @@ void FieldModuleInstruction::ProcessInst(
         case OPCODES::BTRLD: code_gen->WriteTodo(md.GetEntityName(), "BTRLD"); break;
         case OPCODES::BTLTB: code_gen->WriteTodo(md.GetEntityName(), "BTLTB"); break;
         case OPCODES::MAPJUMP: ProcessMAPJUMP(code_gen, func); break;
-        case OPCODES::LSTMP: code_gen->WriteTodo(md.GetEntityName(), "LSTMP"); break;
+        case OPCODES::LSTMP: ProcessLSTMP(code_gen); break;
         case OPCODES::BATTLE: ProcessBATTLE(code_gen); break;
         case OPCODES::BTLON: ProcessBTLON(code_gen); break;
         case OPCODES::BTLMD: ProcessBTLMD(code_gen); break;
@@ -102,6 +102,23 @@ void FieldModuleInstruction::ProcessInst(
     }
 }
 
+void FieldModuleInstruction::ProcessLSTMP(CodeGenerator* code_gen){
+    // Stores the ID of the field the player comes from (see the header of the scripts).
+    FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
+    // Bank 0 is not a variable (some fields use it with no destination): nothing to store.
+    if (params_[0]->GetUnsigned() * 16 + params_[1]->GetUnsigned() == 0){
+        code_gen->AddOutputLine("-- LSTMP without a destination");
+        return;
+    }
+    code_gen->AddOutputLine((
+      boost::format("%1% = Data.PreviousFieldId or 0")
+      % FieldCodeGenerator::FormatValueOrVariable(
+        cg->GetFormatter(), params_[0]->GetUnsigned() * 16 + params_[1]->GetUnsigned(),
+        params_[2]->GetUnsigned()
+      )
+    ).str());
+}
+
 void FieldModuleInstruction::ProcessBATTLE(CodeGenerator* code_gen){
     FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
     // Operands: two bank nibbles, one of them always zero, and then the battle ID or the address

+ 1 - 0
src/installer/decompiler/field/instruction/FieldModuleInstruction.h

@@ -63,6 +63,7 @@ class FieldModuleInstruction : public KernelCallInstruction{
          *
          * @param[in,out] code_gen Code generator to append lines.
          */
+        void ProcessLSTMP(CodeGenerator* code_gen);
         void ProcessBATTLE(CodeGenerator* code_gen);
 
         /**

+ 8 - 2
src/installer/decompiler/field/instruction/FieldPartyInstruction.cpp

@@ -36,7 +36,10 @@ void FieldPartyInstruction::ProcessInst(
         case OPCODES::GOLDD: ProcessGOLDD(code_gen); break;
         case OPCODES::HMPMAX1: code_gen->WriteTodo(md.GetEntityName(), "HMPMAX1"); break;
         case OPCODES::HMPMAX2: code_gen->WriteTodo(md.GetEntityName(), "HMPMAX2"); break;
-        case OPCODES::MHMMX: code_gen->WriteTodo(md.GetEntityName(), "MHMMX"); break;
+        case OPCODES::MHMMX:
+            // Full HP and MP of all the characters, and no status.
+            code_gen->AddOutputLine("restore_all_characters()");
+            break;
         case OPCODES::HMPMAX3: code_gen->WriteTodo(md.GetEntityName(), "HMPMAX3"); break;
         case OPCODES::MPU: code_gen->WriteTodo(md.GetEntityName(), "MPU"); break;
         case OPCODES::MPD: code_gen->WriteTodo(md.GetEntityName(), "MPD"); break;
@@ -128,9 +131,12 @@ void FieldPartyInstruction::ProcessDLITM(CodeGenerator* code_gen){
 }
 
 void FieldPartyInstruction::ProcessCKITM(CodeGenerator* code_gen){
+    // Operands: the bank of the destination (in the two nibbles of the first byte), the ID of the
+    // item and the address, in that bank, that receives how many of the item there are.
     code_gen->AddOutputLine((
       boost::format("Banks[%1%][%2%] = Inventory.get_item_quantity(%3%)")
-      % params_[0]->GetUnsigned() % params_[2]->GetUnsigned() % params_[1]->GetUnsigned()
+      % (params_[0]->GetUnsigned() * 16 + params_[1]->GetUnsigned()) % params_[3]->GetUnsigned()
+      % params_[2]->GetUnsigned()
     ).str());
 }
 

+ 7 - 1
src/installer/decompiler/field/instruction/FieldWalkmeshInstruction.cpp

@@ -30,7 +30,13 @@ void FieldWalkmeshInstruction::ProcessInst(
     FunctionMetaData md(func.metadata);
     //std::cout << "WMesh opcode: " << opcode_ << "\n";
     switch (opcode_){
-        case OPCODES::SLIP: code_gen->WriteTodo(md.GetEntityName(), "SLIP"); break;
+        case OPCODES::SLIP:
+            // Lets the player slide along the walls or not.
+            code_gen->AddOutputLine(
+              (boost::format("entity_manager:set_player_slip(%1%)")
+                % FieldCodeGenerator::FormatBool(params_[0]->GetUnsigned())).str()
+            );
+            break;
         case OPCODES::UC: ProcessUC(code_gen); break;
         case OPCODES::IDLCK:
             // Triangle id, on or off

+ 17 - 2
src/installer/decompiler/field/instruction/FieldWindowInstruction.cpp

@@ -39,6 +39,21 @@ static bool TryParseInteger(const std::string& value, int& parsed_value){
   }
 }
 
+void FieldWindowInstruction::ProcessMPARA(CodeGenerator* code_gen){
+    // Gives a value to a variable code of the dialogs of a window. The parameters are the bank
+    // (in the two nibbles of the first byte), the window, the number of the variable code in the
+    // text and the value, or its address if the bank is not zero.
+    FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
+    const uint32 bank = params_[0]->GetUnsigned() * 16 + params_[1]->GetUnsigned();
+    const auto& value = FieldCodeGenerator::FormatValueOrVariable(
+      cg->GetFormatter(), bank, params_[4]->GetUnsigned()
+    );
+    code_gen->AddOutputLine((
+      boost::format("dialog:set_variable(\"%1%\", \"var%2%\", tostring(%3%))")
+      % params_[2]->GetUnsigned() % params_[3]->GetUnsigned() % value
+    ).str());
+}
+
 void FieldWindowInstruction::ProcessInst(
   Function& func, ValueStack&, Engine* engine, CodeGenerator *code_gen
 ){
@@ -53,8 +68,8 @@ void FieldWindowInstruction::ProcessInst(
         case OPCODES::WNUMB: code_gen->WriteTodo(md.GetEntityName(), "WNUMB"); break;
         case OPCODES::STTIM: ProcessSTTIM(code_gen); break;
         case OPCODES::MESSAGE: ProcessMESSAGE(code_gen, eng.GetScriptName()); break;
-        case OPCODES::MPARA: code_gen->WriteTodo(md.GetEntityName(), "MPARA"); break;
-        case OPCODES::MPRA2: code_gen->WriteTodo(md.GetEntityName(), "MPRA2"); break;
+        case OPCODES::MPARA: ProcessMPARA(code_gen); break;
+        case OPCODES::MPRA2: ProcessMPARA(code_gen); break;
         case OPCODES::MPNAM: ProcessMPNAM(code_gen, eng.GetScriptName()); break;
         case OPCODES::ASK: ProcessASK(code_gen, eng.GetScriptName()); break;
         case OPCODES::MENU: ProcessMENU(code_gen); break;

+ 2 - 0
src/installer/decompiler/field/instruction/FieldWindowInstruction.h

@@ -100,6 +100,8 @@ class FieldWindowInstruction : public KernelCallInstruction{
          */
         void ProcessASK(CodeGenerator* code_gen, const std::string& script_name);
 
+        void ProcessMPARA(CodeGenerator* code_gen);
+
         void ProcessMPNAM(CodeGenerator* code_gen, const std::string& script_name);
 
 

+ 5 - 0
src/map/VGearsBackground2DFile.cpp

@@ -38,6 +38,7 @@ namespace VGears{
 
     void Background2DFile::unloadImpl(){
         texture_name_.clear();
+        palette_name_.clear();
         // GCC error:
         // error: no match for ‘operator=’ (operand types are ‘Ogre::Vector4’
         // {aka ‘Ogre::Vector<4, float>’} and ‘int’)
@@ -54,6 +55,10 @@ namespace VGears{
 
     String Background2DFile::GetTextureName() const{ return texture_name_;}
 
+    void Background2DFile::SetPaletteName(const String &palette_name){palette_name_ = palette_name;}
+
+    String Background2DFile::GetPaletteName() const{return palette_name_;}
+
     void Background2DFile::SetClip(const Ogre::Vector2 &clip){clip_ = clip;}
 
     Ogre::Vector2 Background2DFile::GetClip() const{return clip_;}

+ 19 - 0
src/map/VGearsBackground2DFile.h

@@ -76,6 +76,20 @@ namespace VGears{
              */
             virtual String GetTextureName() const;
 
+            /**
+             * Sets the name of the file with the palettes that scripts animate (optional).
+             *
+             * @param[in] palette_name The resource name of the palette file, or empty.
+             */
+            virtual void SetPaletteName(const String &palette_name);
+
+            /**
+             * Retrieves the name of the palette file.
+             *
+             * @return The resource name of the palette file, or empty if there is none.
+             */
+            virtual String GetPaletteName() const;
+
             /**
              * Sets the background range.
              *
@@ -183,6 +197,11 @@ namespace VGears{
              */
             String texture_name_;
 
+            /**
+             * The name of the palette file, empty if there is none.
+             */
+            String palette_name_;
+
             /**
              * The background clip.
              */

+ 3 - 0
src/map/VGearsBackground2DFileXMLSerializer.cpp

@@ -84,6 +84,9 @@ namespace VGears{
             );
         }
         dest->SetTextureName(texture_name);
+        String palette_name;
+        ReadAttribute(node, "palette", palette_name, String());
+        dest->SetPaletteName(palette_name);
         Ogre::Vector2 clip;
         ReadAttribute(node, "clip", clip, Ogre::Vector2(320, 240));
         dest->SetClip(clip);

+ 5 - 5
test/core/ScreenFadeState.cpp

@@ -104,15 +104,15 @@ BOOST_AUTO_TEST_CASE(TestScreenFadeStateInstantBlackAndNormalFade){
     BOOST_CHECK_CLOSE(fade.GetAlpha(), 1.0f, 0.01f);
     BOOST_CHECK_SMALL(fade.GetColour().r, 0.0001f);
 
-    // Type 6 covers the field with the colour little by little, and keeps it.
+    // Type 6 adds the colour to the field little by little, and keeps it.
     BOOST_REQUIRE(fade.StartFade(6, 255, 255, 255, 8));
-    BOOST_CHECK_EQUAL(fade.GetBlend(), ScreenFadeState::BLEND_NORMAL);
-    BOOST_CHECK_SMALL(fade.GetAlpha(), 0.0001f);
+    BOOST_CHECK_EQUAL(fade.GetBlend(), ScreenFadeState::BLEND_ADD);
+    BOOST_CHECK_SMALL(fade.GetColour().r, 0.0001f);
     fade.Advance(0.5f);
-    BOOST_CHECK_CLOSE(fade.GetAlpha(), 0.5f, 0.01f);
+    BOOST_CHECK_CLOSE(fade.GetColour().r, 0.5f, 0.01f);
     BOOST_CHECK(fade.Advance(0.5f));
     BOOST_CHECK(fade.IsVisible());
-    BOOST_CHECK_CLOSE(fade.GetAlpha(), 1.0f, 0.01f);
+    BOOST_CHECK_CLOSE(fade.GetColour().r, 1.0f, 0.01f);
 }
 
 BOOST_AUTO_TEST_CASE(TestScreenFadeStateNFade){

+ 14 - 0
test/installer/ExternalTools.cpp

@@ -16,6 +16,7 @@
 #include <boost/test/unit_test.hpp>
 #include <boost/filesystem.hpp>
 #include <QtCore/QCoreApplication>
+#include <algorithm>
 #include <fstream>
 #include <sstream>
 #include "installer/ExternalTools.h"
@@ -242,6 +243,19 @@ BOOST_AUTO_TEST_CASE(FfmpegReadsStdin){
     BOOST_CHECK(FfmpegStdinArguments("out.ogg") == expected);
 }
 
+BOOST_AUTO_TEST_CASE(FfmpegMidiRemovesTheSilenceAtTheEnd){
+    const std::vector<std::string> arguments = FfmpegMidiArguments("out.ogg");
+    // It reads the standard input and writes the file.
+    BOOST_CHECK(arguments.size() >= 3);
+    BOOST_CHECK(arguments.back() == "out.ogg");
+    BOOST_CHECK(std::find(arguments.begin(), arguments.end(), "-") != arguments.end());
+    // The filter reverses the audio, removes the silence at its start and reverses it again.
+    const auto filter = std::find(arguments.begin(), arguments.end(), "-af");
+    BOOST_REQUIRE(filter != arguments.end() && filter + 1 != arguments.end());
+    BOOST_CHECK(filter[1].find("areverse,silenceremove=") == 0);
+    BOOST_CHECK(filter[1].rfind(",areverse") == filter[1].size() - std::string(",areverse").size());
+}
+
 BOOST_AUTO_TEST_CASE(ShortVersions){
     Tool ffmpeg;
     ffmpeg.version = "ffmpeg version 9.0.2-1 Copyright (c) 2000-2026 the FFmpeg developers";