Kaynağa Gözat

Field module fixes from a play-through: opcodes, camera, party, scripts, media and world map entry

Installer and decompiler:
- Implement the opcodes SMTRA (give materia), GTPYE and SPTYE (store and restore the party), MENU 17 (unequip materia), MINIGAME (skip to the return field), MVCAM (movie camera), MUSVT (stop music), WNUMB (number windows), SLINE (move a line trigger) and the party requests with the slot of the party as the operand.
- Write MENU2 as a real menu lock, and write the byte operations PLUS, MINUS, MUL, INC and DEC with wrap around at 256 (the palette glow of jumin counted below zero).
- Pass the KAWAI sub-opcodes to the instruction with their own number: the sub-opcode 8 was decoded as JOIN, which made party members walk to the player and wait forever (ujunon2).
- Treat RETTO as the end of a script, so it no longer falls through to the next script (the piano of niv_ti2).
- Do not fail the whole field on a REQ or REQSW of a script the entity does not have (niv_ti2 was skipped). Do not write a closing colour tag that was never opened.
- Write the type 3 additive tiles with an intensity of 0.25.
- Convert the four WAV music tracks (14, 64, 87 and 96) of DATA/MUSIC, and list the tracks 94 to 97 in the index.
- Remove frcyo and del3 from the list of fields that were skipped for old crashes.

Engine:
- Scripts: run the contact script (script 2) when the player touches an entity. A request with a higher priority replaces the scripts of the entity that only poll. The offset and turn syncs do not wait when nothing is in progress. A scripted move of an entity that is not on the walkmesh walks in a straight line. The walkmesh entities that have no triangle no longer fill the log. When a script lets go of the control and there is no player entity, the entity that runs the script becomes the player. Characters the camera does not follow now follow the player by default.
- Walkmesh: a scripted walk that leaves a triangle looks for the triangle under the new position, so a character that starts on a loose triangle does not keep its height.
- Camera: mirror the limits of the camera range, which is only different for the ranges that are not centered.
- Background: the buffers hold up to 4096 tiles of each kind. The tiles with an intensity scale their colour.
- Movies: draw the movie behind the models when the script asks for the movie camera (MVCAM), and do not draw the fades of the field over a movie that covers the screen.
- Dialogs: text areas grow their buffer for texts longer than 1024 letters. The pauses of the text are in frames, not seconds. Number windows write the number in the spaces of the text and forget it when they close. A pose that holds the last frame of an animation is shown as the last frame, not as the first.
- Music and console: add stop_music, set_line, minigame and use_movie_camera to the scripts. The /map command uses the list of fields, and /screenshot saves PNG files.
- The pause menu does not open when a script reads the Start button.
- Fix the debug draw line buffer for walkmeshes with many triangles.

Scripts:
- Add the party menu and the save menu for the scripts of the fields. Add menu_lock, minigame. Shared character slots of the savemap. The dialogs are drawn under the menus.
- The empty music slots of a field stop the music. The world map saves where the player entered a field, so the exits that use it put him there.

Docs:
- Notes in the TODO for the scenes of the world map.
Iñigo Valentin 6 saat önce
ebeveyn
işleme
dffb036b9a
47 değiştirilmiş dosya ile 923 ekleme ve 138 silme
  1. 4 3
      data/data/screens/_screens.xml
  2. 12 1
      data/data/scripts/data.lua
  3. 55 12
      data/data/scripts/field.lua
  4. 2 0
      data/data/scripts/menu/name_menu.lua
  5. 4 1
      data/data/scripts/menu/pause_menu.lua
  6. 18 1
      data/data/scripts/menu/phs_menu.lua
  7. 18 1
      data/data/scripts/menu/save_menu.lua
  8. 46 1
      data/data/scripts/system.lua
  9. 14 0
      data/data/scripts/worldmap/triangle_triggers.lua
  10. 15 0
      data/data/scripts/worldmap/world_vm.lua
  11. 18 0
      doc/TODO.md
  12. 43 25
      src/core/Background2D.cpp
  13. 13 1
      src/core/Background2D.h
  14. 6 7
      src/core/ConfigCmdHandlerCommands.h
  15. 1 1
      src/core/DebugDraw.cpp
  16. 36 2
      src/core/DialogsManager.cpp
  17. 23 1
      src/core/DialogsManager.h
  18. 5 0
      src/core/Entity.cpp
  19. 125 1
      src/core/EntityManager.cpp
  20. 43 0
      src/core/EntityManager.h
  21. 7 3
      src/core/EntityModel.cpp
  22. 8 2
      src/core/MoviePlayer.cpp
  23. 23 0
      src/core/MoviePlayer.h
  24. 3 0
      src/core/ScreenFade.cpp
  25. 19 0
      src/core/ScriptManager.cpp
  26. 8 1
      src/core/ScriptManager.h
  27. 5 0
      src/core/ScriptManagerBinds.h
  28. 37 4
      src/core/UiTextArea.cpp
  29. 22 1
      src/core/UiTextArea.h
  30. 5 1
      src/core/XmlBackground2DFile.cpp
  31. 3 2
      src/installer/FieldDataInstaller.cpp
  32. 12 2
      src/installer/FieldTextWriter.cpp
  33. 31 17
      src/installer/MediaDataInstaller.cpp
  34. 16 16
      src/installer/decompiler/field/FieldDisassembler.cpp
  35. 7 1
      src/installer/decompiler/field/instruction/FieldCameraInstruction.cpp
  36. 40 22
      src/installer/decompiler/field/instruction/FieldControlFlowInstruction.cpp
  37. 26 0
      src/installer/decompiler/field/instruction/FieldMathInstruction.cpp
  38. 7 0
      src/installer/decompiler/field/instruction/FieldMathInstruction.h
  39. 6 1
      src/installer/decompiler/field/instruction/FieldMediaInstruction.cpp
  40. 24 1
      src/installer/decompiler/field/instruction/FieldModuleInstruction.cpp
  41. 8 0
      src/installer/decompiler/field/instruction/FieldModuleInstruction.h
  42. 46 3
      src/installer/decompiler/field/instruction/FieldPartyInstruction.cpp
  43. 16 0
      src/installer/decompiler/field/instruction/FieldPartyInstruction.h
  44. 19 1
      src/installer/decompiler/field/instruction/FieldWalkmeshInstruction.cpp
  45. 2 0
      src/installer/decompiler/field/instruction/FieldWalkmeshInstruction.h
  46. 20 2
      src/installer/decompiler/field/instruction/FieldWindowInstruction.cpp
  47. 2 0
      src/installer/decompiler/field/instruction/FieldWindowInstruction.h

+ 4 - 3
data/data/screens/_screens.xml

@@ -2,6 +2,10 @@
     <!-- Main prototypes -->
     <prototype file_name="screens/prototypes.xml" />
 
+    <!-- Dialogs, under the menus: a message that stays open while a menu is used must not hide it. -->
+    <prototype file_name="screens/dialog/prototypes.xml" />
+    <screen file_name="screens/dialog/dialog.xml" />
+
     <!-- Menu screens -->
     <screen file_name="screens/begin_menu/begin_menu.xml" />
     <prototype file_name="screens/main_menu/prototypes.xml" />
@@ -19,9 +23,6 @@
     <screen file_name="screens/name_menu/name_menu.xml" />
     <screen file_name="screens/save_menu/save_menu.xml" />
     <prototype file_name="screens/save_menu/prototypes.xml" />
-    <!-- Dialogs -->
-    <prototype file_name="screens/dialog/prototypes.xml" />
-    <screen file_name="screens/dialog/dialog.xml" />
     <!-- Battle UI -->
     <prototype file_name="screens/battle/prototypes.xml" />
     <screen file_name="screens/battle/battle.xml" />

+ 12 - 1
data/data/scripts/data.lua

@@ -70,9 +70,20 @@ ControlKey = "";
 
 --- Playable characters
 Characters = {}
-for i = 1, 11 do
+for i = 1, 8 do
     Characters[i] = {}
 end
+-- Young Cloud (9) and Sephiroth (10) of the flashbacks share the slots of Cait Sith (6) and Vincent
+-- (7) in the savemap of the game, as in the original game: their data is in those slots.
+Characters[9] = nil
+Characters[10] = nil
+setmetatable(Characters, {
+    __index = function(characters, id)
+        if id == 9 then return rawget(characters, 6) end
+        if id == 10 then return rawget(characters, 7) end
+        return nil
+    end
+})
 
 --- The party inventory.
 --

+ 55 - 12
data/data/scripts/field.lua

@@ -14,6 +14,21 @@ load_field_map_request = function(map_name, point_name)
     end
 end
 
+--- Starts a minigame (the MINIGAME opcode).
+--
+-- The minigames are not implemented yet: the game goes on as if the minigame had been played, and
+-- jumps to the field that the original game goes to when it ends. The scripts of that field decide
+-- from the state of the game what comes next (the bike of blackbgb leads to the fight against the
+-- Motor Ball, because the script of the field set that state before starting the minigame).
+--
+-- @param game Number of the minigame.
+-- @param map_name Field where the game goes on.
+-- @param point_name Point of that field where the player is placed.
+minigame = function(game, map_name, point_name)
+    print("The minigame " .. tostring(game) .. " is not implemented: skipping it.")
+    load_field_map_request(map_name, point_name)
+end
+
 dispatch_menu = function(menu_id, parameter)
     menu_id = tonumber(menu_id)
     parameter = tonumber(parameter)
@@ -45,6 +60,8 @@ dispatch_menu = function(menu_id, parameter)
         open_menu("save")
     elseif menu_id == 15 then
         Party.steal_materia()
+    elseif menu_id == 17 then
+        Characters.unequip_materia(parameter)
     elseif menu_id == 18 then
         Characters.remove_materia(parameter)
     elseif menu_id == 19 then
@@ -202,6 +219,12 @@ player_lock = function(lock)
     MenuSettings.available = (lock == false)
 end
 
+--- Locks or unlocks the menu button (MENU2), with no effect on the player.
+-- @param lock True to lock, false to unlock.
+menu_lock = function(lock)
+    MenuSettings.available = (lock == false)
+end
+
 --- Sets a bit variable on (1).
 --
 -- @param bank Memory bank (0-index, as in game).
@@ -243,6 +266,9 @@ end
 -- @param az Address at which to store the Z coordinate.
 -- @param at Address at which to store the triangle.
 -- @param scale Map scale to multiply values
+-- The coordinates are rounded: the walkmesh is saved with six digits, so a height of 193 units comes
+-- as 192.9997 once scaled, and the scripts compare it with the exact value (blin68_1 asks for it to
+-- talk to a character).
 axyzi = function(bx, by, bz, bt, id, ax, ay, az, at, scale)
     local entity = entity_manager:get_entity_from_index(id)
     if entity == nil then
@@ -250,9 +276,9 @@ axyzi = function(bx, by, bz, bt, id, ax, ay, az, at, scale)
     end
     local x, y, z = entity:get_position()
     local t = entity:get_move_triangle_id()
-    Banks[bx][ax] = math.floor(x * scale)
-    Banks[by][ay] = math.floor(y * scale)
-    Banks[bz][az] = math.floor(z * scale)
+    Banks[bx][ax] = math.floor(x * scale + 0.5)
+    Banks[by][ay] = math.floor(y * scale + 0.5)
+    Banks[bz][az] = math.floor(z * scale + 0.5)
     Banks[bt][at] = t
     return 0
 end
@@ -271,8 +297,8 @@ getaxy = function(bx, by, id, ax, ay, scale)
         do return end
     end
     local x, y = entity:get_position()
-    Banks[bx][ax] = math.floor(x * scale)
-    Banks[by][ay] = math.floor(y * scale)
+    Banks[bx][ax] = math.floor(x * scale + 0.5)
+    Banks[by][ay] = math.floor(y * scale + 0.5)
     return 0
 end
 
@@ -310,9 +336,20 @@ end
 -- @param menu The name of the menu.
 open_menu = function(menu)
     if menu == "party" then
-        -- TODO
+        -- The button that asked for the menu is still down: wait for it, or it would close the menu.
+        while entity_manager:is_key_on(16 + 64) do script:wait(0) end
+        script:request_end_sync(Script.UI, "MainMenu", "show", 0)
+        while ui_manager:get_widget("MainMenu"):is_visible() do script:wait(0) end
+        -- The same with the button that closed it: the script would see it as a new request.
+        while entity_manager:is_key_on(16 + 64) do script:wait(0) end
     elseif menu == "save" then
-        -- TODO
+        -- The button that asked for the menu (a script may read it) is down: wait for it.
+        while entity_manager:is_key_on(32 + 64) do script:wait(0) end
+        UiContainer.SaveMenu.operation = "save"
+        UiContainer.SaveMenu.standalone = true
+        script:request_end_sync(Script.UI, "SaveMenu", "show", 0)
+        while UiContainer.current_menu == "save" do script:wait(0) end
+        while entity_manager:is_key_on(32 + 64) do script:wait(0) end
     end
 end
 
@@ -328,10 +365,12 @@ end
 -- @param id ID of the track in the field.
 play_map_music = function(id)
     local track_id = audio_manager:get_track_id(id)
+    -- A track of the field with no music (-1, an empty AKAO frame of the field file) is silence: the
+    -- scenes use it between two tracks, and some fields (trackin) have no music at all.
     if track_id ~= -1 then
         audio_manager:play_music(tostring(track_id))
     else
-        print("Requested non-existent music track ID " .. tostring(id))
+        audio_manager:stop_music()
     end
 end
 
@@ -347,8 +386,9 @@ end
 -- @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)
+    -- A track with no music is silence (see play_map_music).
     if track_id == -1 then
-        print("Requested non-existent music track ID " .. tostring(id))
+        audio_manager:stop_music()
         return
     end
     if fade_in == 0 then
@@ -448,15 +488,18 @@ System["MapChanger"] = {
 
 --- 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 character Slot of the party (0 is the leader), not the ID of a character: the scripts of a
+-- scene with another party (Aerith leading the party, for example) ask for the slot, and the
+-- request goes to the entity of the character that is in it (the one 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)
+    local character_id = Party[character + 1]
+    local entity = character_id ~= nil and entity_manager:get_entity_from_character_id(character_id) or nil
     if entity == nil then
-        print("party_request: there is no entity for the character " .. tostring(character) .. ".")
+        print("party_request: there is no entity for the party slot " .. tostring(character) .. ".")
         return
     end
     local name = entity:get_name()

+ 2 - 0
data/data/scripts/menu/name_menu.lua

@@ -186,6 +186,8 @@ UiContainer.NameMenu = {
         local name = Characters[id].name
         -- HACK: Hack for Ex-Soldier default. Can this be extracted from menu.lgp?
         if string.lower(name) == "ex-soldier" then return "Cloud" end
+        -- The initial data of the game only holds "Red" for him.
+        if id == 4 and string.lower(name) == "red" then return "Red XIII" end
         return name
     end,
 

+ 4 - 1
data/data/scripts/menu/pause_menu.lua

@@ -20,7 +20,10 @@ UiContainer.PauseMenu = UiContainer.Menu.new{
     -- paused, it only handles the pause event.
     on_button = function(self, button, event)
         if System:is_paused() == false then
-            if button == Config.ACTIONS.START and event == "Press" then
+            -- A scene that reads the Start button itself (to end a choice) doesn't pause the game.
+            if button == Config.ACTIONS.START and event == "Press"
+                and not entity_manager:is_start_key_read()
+            then
                 System:pause()
             end
             return 0

+ 18 - 1
data/data/scripts/menu/phs_menu.lua

@@ -283,9 +283,18 @@ UiContainer.PhsMenu = UiContainer.Menu.new{
         end
     end,
 
+    --- Is the menu opened by a field script (change party) instead of by the main menu?
+    standalone = false,
+
     --- Opens the PHS menu.
     show = function(self)
         self:activate()
+        if self.standalone then
+            entity_manager:set_paused(true)
+            MenuSettings.pause_available = false
+            self.menu_was_available = MenuSettings.available
+            MenuSettings.available = false
+        end
         -- Empty slots may hold an invalid ID (e.g. -1). Leave them as nil.
         for slot = 1, PARTY_SLOTS do
             if Party[slot] ~= nil and Characters[Party[slot]] == nil then Party[slot] = nil end
@@ -307,7 +316,15 @@ UiContainer.PhsMenu = UiContainer.Menu.new{
     hide = function(self)
         self:compact_party()
         ui_manager:get_widget("PhsMenu"):set_visible(false)
-        self:deactivate()
+        if self.standalone then
+            self.standalone = false
+            self:deactivate("")
+            MenuSettings.available = self.menu_was_available
+            MenuSettings.pause_available = true
+            entity_manager:set_paused(false)
+        else
+            self:deactivate()
+        end
         return 0
     end,
 }

+ 18 - 1
data/data/scripts/menu/save_menu.lua

@@ -34,6 +34,9 @@ UiContainer.SaveMenu = UiContainer.Menu.new{
         },
     },
 
+    --- Is the menu opened by a field script (a save point of a scene) instead of by the main menu?
+    standalone = false,
+
     --- Opens the save menu.
     --
     -- Populates and updates displayed data before opening.
@@ -48,6 +51,12 @@ UiContainer.SaveMenu = UiContainer.Menu.new{
             return 0
         end
         self:activate()
+        if self.standalone then
+            entity_manager:set_paused(true)
+            MenuSettings.pause_available = false
+            self.menu_was_available = MenuSettings.available
+            MenuSettings.available = false
+        end
         local loading = (self.operation == "load")
         local container = "SaveMenu.Container."
         ui_manager:get_widget(container .. "TopBar.DescSave"):set_visible(not loading)
@@ -115,7 +124,15 @@ UiContainer.SaveMenu = UiContainer.Menu.new{
     --- Hides the item menu and goes back to the main menu.
     hide = function(self)
         ui_manager:get_widget("SaveMenu"):set_visible(false)
-        self:deactivate(self.operation == "load" and "begin" or "main")
+        if self.standalone then
+            self.standalone = false
+            self:deactivate("")
+            MenuSettings.available = self.menu_was_available
+            MenuSettings.pause_available = true
+            entity_manager:set_paused(false)
+        else
+            self:deactivate(self.operation == "load" and "begin" or "main")
+        end
         savemap_manager:release()
         return 0;
     end,

+ 46 - 1
data/data/scripts/system.lua

@@ -142,6 +142,20 @@ set_party = function(character1, character2, character3)
     export_party_members()
 end
 
+--- Sets the party from three values (SPTYE), the ones that GTPYE stored: 254 and 255 are an empty
+-- place.
+--
+-- @param character1 The first member character ID, the party leader.
+-- @param character2 The second member character ID.
+-- @param character3 The third member character ID.
+set_party_from_values = function(character1, character2, character3)
+    local function id(value)
+        if value == nil or value >= 254 then return nil end
+        return value
+    end
+    set_party(id(character1), id(character2), id(character3))
+end
+
 --- Checks if a a character ID actually belongs to a character.
 --
 -- @param character The ID to check.
@@ -758,6 +772,28 @@ Characters.equip = function(char_id, item_id)
     return true
 end
 
+--- Takes the equipped materia off a character and puts it in the materia inventory (menu 17 of the
+-- field scripts: the "remove materia from other members" of the scenes with a fixed party).
+--
+-- @param id ID of the character.
+Characters.unequip_materia = function(id)
+    local character = Characters[id]
+    if character == nil then return end
+    local free = 1
+    for _, equipment in ipairs({character.weapon, character.armor}) do
+        for slot = 0, 7 do
+            local materia = equipment.materia[slot]
+            if materia ~= nil then
+                while free <= MAX_MATERIA_SLOTS and Materia[free] ~= nil do free = free + 1 end
+                if free > MAX_MATERIA_SLOTS then return end
+                Materia[free] = materia
+                equipment.materia[slot] = nil
+            end
+        end
+    end
+    Characters.recalculate_stats(id)
+end
+
 --- Removes all materia from a character.
 --
 -- @param id ID of the character to remove materia from.
@@ -811,8 +847,17 @@ Party.split_teams = function(number)
 end
 
 --- Displays a menu to choose a party of three.
+--
+-- The script that asks for it waits until the menu is closed.
 Party.choose_party = function()
-    -- TODO: Implement
+    -- The button that asked for the menu (Cancel) is still down: it would close the menu at once.
+    while entity_manager:is_key_on(64) do script:wait(0) end
+    UiContainer.PhsMenu.standalone = true
+    script:request_end_sync(Script.UI, "PhsMenu", "show", 0)
+    while UiContainer.current_menu == "phs" do script:wait(0) end
+    -- The button that closed the menu is still down: the script that asked for the menu would
+    -- read it as a new request (Cancel opens the menu).
+    while entity_manager:is_key_on(32 + 64) do script:wait(0) end
 end
 
 --- Special event. Removes all materia from the party, equipped and unequipped.

+ 14 - 0
data/data/scripts/worldmap/triangle_triggers.lua

@@ -211,6 +211,20 @@ EnterFieldScene = function(field_table_id, scenario)
     end
 
     System.MapChanger.world_map_entry = entry
+    -- Where the player was when entering the field: some exits (the chocobo records, such as the one
+    -- of sichi) place the player where he entered, and the scripts read it as the values 0, 1 (the
+    -- mesh) and 4 (the direction) that the engine gives them.
+    local player = entity_manager:get_player_entity()
+    if player ~= nil and WorldVM ~= nil then
+        local x, _, z = player:get_position()
+        System.WorldMap.entry_position = {
+            x = x,
+            z = z,
+            mesh_x = math.floor(x / WorldVM.MESH_SIZE),
+            mesh_y = math.floor(z / WorldVM.MESH_SIZE),
+            direction = math.floor(player:get_rotation() / 360 * 256) % 256,
+        }
+    end
     console("camera_free false")
     load_field_map_request(entry.field, "")
     return 0

+ 15 - 0
data/data/scripts/worldmap/world_vm.lua

@@ -298,6 +298,13 @@ WorldVM.prepare = function(map_id)
         end
     end
     System.WorldMap.specials = {}
+    -- Where the player entered the field that the world is entered from (EnterFieldScene).
+    local entry = System.WorldMap.entry_position
+    if entry then
+        System.WorldMap.specials[0] = entry.mesh_x
+        System.WorldMap.specials[1] = entry.mesh_y
+        System.WorldMap.specials[4] = entry.direction
+    end
     -- The arrival of a real field exit has priority over the spawn points of the debug data.
     local real_arrival = System.WorldMap.arrival
     local arrival = real_arrival or (WorldMapDebug and WorldMapDebug.arrival) or 0
@@ -314,6 +321,14 @@ WorldVM.prepare = function(map_id)
             .. (player and (" (the scripts of the record say " .. player.x .. ", " .. player.z .. ")") or ""))
         player = point
     elseif arrival ~= 0 then
+        -- The exits that place the player by the mesh that he entered from (the chocobo ones) put him at the
+        -- corner of that mesh, which can be a mountain: he appears where he entered.
+        if entry and entry.x and player
+            and math.abs(player.x - entry.mesh_x * WorldVM.MESH_SIZE) < 0.01
+            and math.abs(player.z - entry.mesh_y * WorldVM.MESH_SIZE) < 0.01 then
+            player = {x = entry.x, z = entry.z}
+            print("World map arrival: the player appears where he entered, " .. entry.x .. ", " .. entry.z)
+        end
         print("World map arrival: FIELD.TBL record " .. arrival .. (player
             and (", the player appears at " .. player.x .. ", " .. player.z)
             or ", the scripts don't place the player"))

+ 18 - 0
doc/TODO.md

@@ -47,6 +47,10 @@ afterwards, because it can grow. Loading and unloading blocks around the player
 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.
 
+## World map: the player keeps walking after entering a town.
+
+When the player enters a town (field) from the world map, the player model keeps playing its walk animation and moving in the direction it was heading on the world map. The field should start with the player standing still, and the stored movement or input state from the world map should be cleared on the transition. Not investigated yet; fix when we return to the world map module.
+
 ## 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
@@ -101,3 +105,17 @@ collides with several solid NPCs that stop around it (`CheckSolidCollisions`).
 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.
+
+## World map: sichi can be entered more than once
+
+The entrance of sichi (FIELD.TBL record 32, trigger function `world_function_129` of `wm0.lua`) should work only once: the function checks `ReadBit(3707)` (the flag that the field sets when it is done) and `ReadSpecial(8)`. Every time the player reaches the entrance the field is entered again, so the story cannot go on. Not investigated: check that the world variables that the field scripts write (`ReadBit`/`WriteBit` use the savemap banks, see `triangle_triggers.lua`) are the same ones that the world scripts read, and that the bit 3707 is really set when leaving sichi. To go on in the meantime, use the console command `map psdun_2`.
+
+When the player leaves sichi he appears where he entered (the exit script puts him at the corner of the mesh, which is a mountain, so `WorldVM.prepare` uses the exact position saved by `EnterFieldScene`). The original game position for this exit is not known. The direction that is saved (special 4) is not used for the player.
+
+## World map: the boat scene after jundoc1a
+
+After the parade of Junon (field jundoc1a) a scene with a boat must happen in the world map, but the player is only taken outside Junon. Not investigated. Things to check: the exit of jundoc1a to the world map (`wm<n>` and its FIELD.TBL record, see `enter_world_map`), the story flags (`progress_game`) that the world scripts read to start the scene (`ReadSpecial(6)`, the record, and the vehicle scripts in `wm0.lua`), and whether the vehicle entities of the scene (the boat) are created by `WorldVM.prepare` for that record.
+
+## World map: the scripted event after shpin_3
+
+After the fight against Jenova·BIRTH in shpin_3 (and its scenes), a scripted event happens in the world map. It is not implemented (not investigated yet). Things to check: the exit of shpin_3 to the world map (the `wm<n>` it uses and the FIELD.TBL record, see `enter_world_map`), the story flag (`progress_game`) and the record that the world scripts read (`ReadSpecial(6)`) to start the event, and the entities, vehicles and scenery that the world script creates for it (see `WorldVM.prepare` and `wm0.lua`). The story flows through the other scripted world events as well (see the one after jundoc1a), so they may share the cause.

+ 43 - 25
src/core/Background2D.cpp

@@ -509,6 +509,11 @@ void Background2D::ScriptAutoScrollToEntity(Entity* entity){
 
 Entity* Background2D::GetAutoScrollEntity() const{return scroll_entity_;}
 
+bool Background2D::HasScrollControl() const{
+    return scroll_entity_ != nullptr || scroll_target_entity_ != nullptr || free_scroll_
+      || has_pending_scroll_;
+}
+
 void Background2D::ScriptScrollToPlayer(const SCROLL_TYPE type, const float seconds){
     Entity* player = EntityManager::getSingleton().ScriptGetPlayerEntity();
     if (player == nullptr) return;
@@ -711,8 +716,16 @@ void Background2D::SetRange(const int min_x, const int min_y, const int max_x, c
       << "Background2D::SetRange " << min_x << " " << min_y << " " << max_x << " " << max_y;
     Ogre::Vector2 half_virtual_screen_size(virtual_screen_size_ / 2);
     half_virtual_screen_size /= screen_proportion_;
-    range_.setMaximum(max_x - half_virtual_screen_size.x , max_y - half_virtual_screen_size.y, 1);
-    range_.setMinimum(min_x + half_virtual_screen_size.x , min_y + half_virtual_screen_size.y, 0);
+    // The scroll is the opposite of the position of the center of the camera (the scripts give it
+    // like that, and the scene is moved, not the camera), so the limits of the camera are the
+    // opposite ones. It only shows in the fields whose range is not centered (nivl_b1): the
+    // camera went beyond the background.
+    range_.setMaximum(
+      -(min_x + half_virtual_screen_size.x), -(min_y + half_virtual_screen_size.y), 1
+    );
+    range_.setMinimum(
+      -(max_x - half_virtual_screen_size.x), -(max_y - half_virtual_screen_size.y), 0
+    );
     Ogre::LogManager::getSingleton().stream() << "Background2D::SetRange " << range_;
     calculateScreenScale();
 }
@@ -740,7 +753,10 @@ void Background2D::AddTile(const VGears::Tile& tile){
     // TODO: move depth calculation to flevelBackgroundLoader maybe? and let
     // Backgorund2D only handle 0 <= depth <= 1 or so?
     // Maybe just move the < 4095 part to flevel background loader?
-    Ogre::Real depth(0.0001f);
+    // The tiles that are less than one unit away (the pieces of a model that a script puts in,
+    // for example) are only a hair away from the camera, but they keep their order: all of them at
+    // the same depth made the tile that is drawn last cover the others, wherever it was.
+    Ogre::Real depth(0.0001f + std::max(tile.depth, 0.0f) * 0.00005f);
     if (tile.depth >= 1){
         if (tile.depth < 4095){
             depth = TileDepthToBuffer(
@@ -777,7 +793,7 @@ void Background2D::virtualScreenToWorldSpace(Ogre::Vector2& pos) const{
 void Background2D::AddTile(
   const int x, const int y, const int width, const int height, const float depth, const float u1,
   const float v1, const float u2, const float v2, const Blending blending, const int area,
-  const int state, const int layer
+  const int state, const int layer, const float intensity
 ){
     Ogre::RenderOperation render_op;
     Ogre::HardwareVertexBufferSharedPtr vertex_buffer;
@@ -858,54 +874,54 @@ void Background2D::AddTile(
     *write_iterator ++ = new_x1;
     *write_iterator ++ = new_y1;
     *write_iterator ++ = depth;
-    *write_iterator ++ = 1;
-    *write_iterator ++ = 1;
-    *write_iterator ++ = 1;
+    *write_iterator ++ = intensity;
+    *write_iterator ++ = intensity;
+    *write_iterator ++ = intensity;
     *write_iterator ++ = 1;
     *write_iterator ++ = u1;
     *write_iterator ++ = v1;
     *write_iterator ++ = new_x2;
     *write_iterator ++ = new_y2;
     *write_iterator ++ = depth;
-    *write_iterator ++ = 1;
-    *write_iterator ++ = 1;
-    *write_iterator ++ = 1;
+    *write_iterator ++ = intensity;
+    *write_iterator ++ = intensity;
+    *write_iterator ++ = intensity;
     *write_iterator ++ = 1;
     *write_iterator ++ = u2;
     *write_iterator ++ = v1;
     *write_iterator ++ = new_x3;
     *write_iterator ++ = new_y3;
     *write_iterator ++ = depth;
-    *write_iterator ++ = 1;
-    *write_iterator ++ = 1;
-    *write_iterator ++ = 1;
+    *write_iterator ++ = intensity;
+    *write_iterator ++ = intensity;
+    *write_iterator ++ = intensity;
     *write_iterator ++ = 1;
     *write_iterator ++ = u2;
     *write_iterator ++ = v2;
     *write_iterator ++ = new_x1;
     *write_iterator ++ = new_y1;
     *write_iterator ++ = depth;
-    *write_iterator ++ = 1;
-    *write_iterator ++ = 1;
-    *write_iterator ++ = 1;
+    *write_iterator ++ = intensity;
+    *write_iterator ++ = intensity;
+    *write_iterator ++ = intensity;
     *write_iterator ++ = 1;
     *write_iterator ++ = u1;
     *write_iterator ++ = v1;
     *write_iterator ++ = new_x3;
     *write_iterator ++ = new_y3;
     *write_iterator ++ = depth;
-    *write_iterator ++ = 1;
-    *write_iterator ++ = 1;
-    *write_iterator ++ = 1;
+    *write_iterator ++ = intensity;
+    *write_iterator ++ = intensity;
+    *write_iterator ++ = intensity;
     *write_iterator ++ = 1;
     *write_iterator ++ = u2;
     *write_iterator ++ = v2;
     *write_iterator ++ = new_x4;
     *write_iterator ++ = new_y4;
     *write_iterator ++ = depth;
-    *write_iterator ++ = 1;
-    *write_iterator ++ = 1;
-    *write_iterator ++ = 1;
+    *write_iterator ++ = intensity;
+    *write_iterator ++ = intensity;
+    *write_iterator ++ = intensity;
     *write_iterator ++ = 1;
     *write_iterator ++ = u1;
     *write_iterator ++ = v2;
@@ -1113,7 +1129,9 @@ void Background2D::RenderBuffer(
 
 void Background2D::CreateVertexBuffers(){
     ResetLayers();
-    alpha_max_vertex_count_ = 2048 * TILE_VERTEX_COUNT;
+    // Some fields have more than 1600 tiles that add their colour (the fire and the light of las0_2,
+    // clsin2_1 and ujunon4), and more than 2500 tiles in all.
+    alpha_max_vertex_count_ = 4096 * TILE_VERTEX_COUNT;
     alpha_render_op_.vertexData = new Ogre::VertexData;
     alpha_render_op_.vertexData->vertexStart = 0;
     Ogre::VertexDeclaration* vertex_declaration = alpha_render_op_.vertexData->vertexDeclaration;
@@ -1130,7 +1148,7 @@ void Background2D::CreateVertexBuffers(){
     alpha_render_op_.vertexData->vertexBufferBinding->setBinding(0, alpha_vertex_buffer_);
     alpha_render_op_.operationType = Ogre::RenderOperation::OT_TRIANGLE_LIST;
     alpha_render_op_.useIndexes = false;
-    add_max_vertex_count_ = 1024 * TILE_VERTEX_COUNT;
+    add_max_vertex_count_ = 4096 * TILE_VERTEX_COUNT;
     add_render_op_.vertexData = new Ogre::VertexData;
     add_render_op_.vertexData->vertexStart = 0;
     vertex_declaration = add_render_op_.vertexData->vertexDeclaration;
@@ -1147,7 +1165,7 @@ void Background2D::CreateVertexBuffers(){
     add_render_op_.vertexData->vertexBufferBinding->setBinding(0, add_vertex_buffer_);
     add_render_op_.operationType = Ogre::RenderOperation::OT_TRIANGLE_LIST;
     add_render_op_.useIndexes = false;
-    subtract_max_vertex_count_ = 512 * TILE_VERTEX_COUNT;
+    subtract_max_vertex_count_ = 2048 * TILE_VERTEX_COUNT;
     subtract_render_op_.vertexData = new Ogre::VertexData;
     subtract_render_op_.vertexData->vertexStart = 0;
     vertex_declaration = subtract_render_op_.vertexData->vertexDeclaration;

+ 13 - 1
src/core/Background2D.h

@@ -130,6 +130,14 @@ class Background2D : public Ogre::RenderQueueListener{
          */
         Entity* GetAutoScrollEntity() const;
 
+        /**
+         * Checks if the camera is following an entity, scrolling to one, or has been placed by a
+         * script.
+         *
+         * @return False if no script has told the camera what to do.
+         */
+        bool HasScrollControl() const;
+
         /**
          * Scrolls the background to the position of the playable character.
          *
@@ -404,13 +412,17 @@ class Background2D : public Ogre::RenderQueueListener{
          * @param[in] blending Blending mode for the tile
          * @param[in] area Scripted area the tile belongs to, or 0 if it always has to be drawn.
          * @param[in] state Bit mask with the layers of the area in which the tile is drawn.
+         * @param[in] layer Layer of the original background the tile is from.
+         * @param[in] intensity Factor of the colour of the tile (0.25 for the additive tiles that
+         * only add a quarter of their colour).
          * @todo Depth is z-index??
          * @todo What are v1, v2, u1 and u2?
          */
         void AddTile(
           const int x, const int y, const int width, const int height, const float depth,
           const float u1, const float v1, const float u2, const float v2, const Blending blending,
-          const int area = 0, const int state = 0, const int layer = 0
+          const int area = 0, const int state = 0, const int layer = 0,
+          const float intensity = 1.0f
         );
 
         /**

+ 6 - 7
src/core/ConfigCmdHandlerCommands.h

@@ -20,6 +20,7 @@
 #include <OgreStringConverter.h>
 #include "Console.h"
 #include "EntityManager.h"
+#include "ScriptManager.h"
 #include "Logger.h"
 #include "XmlMapFile.h"
 #include "XmlMapsFile.h"
@@ -292,11 +293,9 @@ void CmdMap(const Ogre::StringVector& params){
         Console::getSingleton().AddTextToOutput("Usage: /map [map_id]");
         return;
     }
-    EntityManager::getSingleton().Clear();
-    XmlMapsFile xml("./data/maps.xml");
-    Ogre::String file_name = xml.GetMapFileNameByName(params[1]);
-    XmlMapFile xml_map("./data/" + file_name);
-    xml_map.LoadMap();
+    // The same as the map function of the scripts (the old list of maps, ./data/maps.xml, doesn't
+    // exist: the fields are in ./data/fields/_fields.xml).
+    ScriptManager::getSingleton().RunString("map(\"" + params[1] + "\")");
 }
 
 /**
@@ -305,7 +304,7 @@ void CmdMap(const Ogre::StringVector& params){
  * @param[in] complete_params The map names will be loaded here.
  */
 void CmdMapCompletion(Ogre::StringVector& complete_params){
-    XmlMapsFile xml("./data/maps.xml");
+    XmlMapsFile xml("./data/fields/_fields.xml");
     xml.GetMapNames(complete_params);
 }
 
@@ -368,7 +367,7 @@ void CmdResolutionCompletition(Ogre::StringVector& complete_params){
  */
 void CmdScreenshot(const Ogre::StringVector& params){
     Ogre::RenderWindow* window = VGears::Application::getSingleton().getRenderWindow();
-    Ogre::String ret = window->writeContentsToTimestampedFile("screenshot_", ".tga");
+    Ogre::String ret = window->writeContentsToTimestampedFile("screenshot_", ".png");
     Console::getSingleton().AddTextToOutput("Screenshot " + ret + " saved.");
 }
 

+ 1 - 1
src/core/DebugDraw.cpp

@@ -505,7 +505,7 @@ void DebugDraw::DestroyLineVertexBuffer(){
 }
 
 void DebugDraw::CreateLine3dVertexBuffer(){
-    line_3d_max_vertex_ = 1024 * 2;
+    line_3d_max_vertex_ = 8192 * 2;
     line_3d_render_operation_.vertexData = new Ogre::VertexData;
     line_3d_render_operation_.vertexData->vertexStart = 0;
     Ogre::VertexDeclaration* vertex_declaration

+ 36 - 2
src/core/DialogsManager.cpp

@@ -173,6 +173,9 @@ void DialogsManager::SetText(const char* d_name, const char* text){
           height == 0.0f ? data->h : height
         );
         messages_[id]->text_area->SetText(xmlText);
+        data->last_text = text;
+        if (data->number_digits > 0)
+            messages_[id]->text_area->PutNumber(data->number, data->number_digits);
     }
     else{
         ShowMessage(id, data->x, data->y, data->w, data->h);
@@ -206,6 +209,29 @@ bool DialogsManager::ShowScriptMessage(const char* text){
     return true;
 }
 
+void DialogsManager::SetNumber(const char* d_name, const int value, const int digits){
+    int id = GetMessageId(d_name);
+    if (id == -1){
+        LOG_TRIVIAL("SetNumber: dialog '" + Ogre::String(d_name) + "' doesn't exist.");
+        return;
+    }
+    MessageData* data = messages_[id];
+    data->number = std::to_string(value);
+    data->number_digits = digits;
+    // The window is already showing its text: write the new number in it.
+    if (data->state != MS_CLOSED && !data->last_text.empty()){
+        float width = 0.0f;
+        float height = 0.0f;
+        TiXmlNode* xml_text = TextHandler::getSingleton().GetDialog(
+          data->last_text.c_str(), width, height
+        );
+        if (xml_text != NULL){
+            data->text_area->SetText(xml_text);
+            data->text_area->PutNumber(data->number, data->number_digits);
+        }
+    }
+}
+
 void DialogsManager::SetNumeric(const char* d_name, const bool numeric, const bool timer){
     int id = GetMessageId(d_name);
     if (id == -1){
@@ -223,8 +249,11 @@ void DialogsManager::SetNumeric(const char* d_name, const bool numeric, const bo
             timer_window_id_ = id;
         }
         else{
-            messages_[id]->numeric = false;
-            messages_[id]->timer = true;
+            // A number window shows its text as any other, with the number in it (WNUMB).
+            messages_[id]->text_area->SetFont("FFVIIFont");
+            messages_[id]->text_area->SetPadding(3, 5, 3, 5);
+            messages_[id]->numeric = true;
+            messages_[id]->timer = false;
         }
     }
     else{
@@ -390,6 +419,11 @@ void DialogsManager::ShowMessage(
 void DialogsManager::HideMessage(const int id){
     messages_[id]->auto_close = false;
     messages_[id]->state = MS_CLOSED;
+    // The number of a number window (WNUMB) belongs to it while it is open: the next text of the
+    // window has no number, or its spaces (the new lines of the texts) would be filled with it.
+    messages_[id]->number.clear();
+    messages_[id]->number_digits = 0;
+    messages_[id]->last_text.clear();
     if (messages_[id]->window != NULL) messages_[id]->window->SetVisible(false);
     if (messages_[id]->cursor != NULL) messages_[id]->cursor->SetVisible(false);
     messages_[id]->text_area->SetVisible(false);

+ 23 - 1
src/core/DialogsManager.h

@@ -99,7 +99,8 @@ struct MessageData{
       visible(true),
       translucent(false),
       timer(false),
-      numeric(false)
+      numeric(false),
+      number_digits(0)
     {}
 
     /**
@@ -238,6 +239,17 @@ struct MessageData{
      * Indicates if the window background is for a number.
      */
     bool numeric;
+
+    /**
+     * Name of the text that the window shows, to write the number again when it changes.
+     */
+    std::string last_text;
+
+    /**
+     * The number that goes in the text (WNUMB) and the width of it. Zero digits is no number.
+     */
+    std::string number;
+    int number_digits;
 };
 
 /**
@@ -335,6 +347,16 @@ class DialogsManager : public Manager, public Ogre::Singleton<DialogsManager>{
          */
         void SetNumeric(const char* d_name, const bool numeric, const bool timer);
 
+        /**
+         * Sets the number of a number window (WNUMB). It is written in the spaces of the text, and
+         * it is updated at once if the window is showing it.
+         *
+         * @param[in] d_name Name of the dialog.
+         * @param[in] value The number.
+         * @param[in] digits Width of the number.
+         */
+        void SetNumber(const char* d_name, const int value, const int digits);
+
         /**
          * Updates the timer.
          *

+ 5 - 0
src/core/Entity.cpp

@@ -597,6 +597,9 @@ void Entity::ScriptOffsetToPosition(
 }
 
 int Entity::ScriptOffsetSync(){
+    // Nothing to wait for if the offset has already finished (the offset of a script that
+    // waits for a move that took longer, such as Jenova of shpin_3): nothing would resume it.
+    if (offset_type_ == AT_NONE) return 1;
     ScriptId script = ScriptManager::getSingleton().GetCurrentScriptId();
     LOG_TRIVIAL(
       "Wait entity '" + name_ + "' offset for function '"
@@ -656,6 +659,8 @@ void Entity::ScriptFaceEntity(Entity* entity){
 }
 
 int Entity::ScriptTurnSync(){
+    // The same as the offset: a turn that has already finished is not waited for.
+    if (turn_type_ == AT_NONE) return 1;
     ScriptId script = ScriptManager::getSingleton().GetCurrentScriptId();
     LOG_TRIVIAL(
       "Wait entity '" + name_ + "' turn for function '"

+ 125 - 1
src/core/EntityManager.cpp

@@ -320,6 +320,15 @@ void EntityManager::UpdateField(){
                             }
                         }
                         else is_move = PerformWalkmeshMove(entity_[i], speed, remaining_time);
+                        // The scripts set the animation of a scene as the default one (DFANM) and
+                        // don't set it back, but the player stands normally again as soon as they
+                        // walk in the original game (blin67_3, where Cloud ends the scene crouched).
+                        if (
+                          is_move == true && player_lock_ == false && player_entity_ == entity_[i]
+                          && entity_[i]->GetDefaultAnimationName() != "Idle"
+                        ){
+                            entity_[i]->ScriptSetDefaultAnimation("Idle");
+                        }
                         if (entity_[i]->GetMoveAutoAnimation() == true){
                             if (is_move == true){
                                 if (speed >= entity_[i]->GetMoveRunSpeed()){
@@ -361,6 +370,7 @@ void EntityManager::UpdateField(){
                 break;
         }
     }
+    CheckEntityContacts();
     // Reset player move. It already must be handled in update
     player_move_ = Ogre::Vector3::ZERO;
     player_run_ = false;
@@ -578,6 +588,7 @@ void EntityManager::OnResize(){background_2d_.OnResize();}
 void EntityManager::ClearField(){
     ClearEncounterTables();
     entities_hidden_by_battle_.clear();
+    entities_in_contact_.clear();
     walkmesh_.Clear();
     background_2d_.Clear();
     screen_fade_.Clear();
@@ -827,6 +838,10 @@ void EntityManager::ScriptSetPlayerEntity(const char* name){
             // is left as it is.
             if (player_entity_ != nullptr && background_2d_.GetAutoScrollEntity() == player_entity_)
                 background_2d_.ScriptAutoScrollToEntity(entity_[i]);
+            // The camera follows the player when no script has said anything about it (the fields
+            // without a Director, such as ujunon1, have no opcode that starts it).
+            else if (!background_2d_.HasScrollControl())
+                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
@@ -881,6 +896,18 @@ void EntityManager::ScriptPlayerLock(const bool lock){
     }
     player_lock_ = lock;
     if (lock == true) player_move_ = Ogre::Vector3::ZERO;
+    // A field with no entity for the leader of the party (the parade of junonr4, where the player
+    // is a soldier that no PC opcode names) gives the control to the entity whose script lets go
+    // of it.
+    else if (player_entity_ == nullptr && IsFieldModule()){
+        const ScriptId script = ScriptManager::getSingleton().GetCurrentScriptId();
+        Entity* entity = GetEntity(script.entity);
+        if (entity != nullptr && !entity->IsLine()){
+            LOG_TRIVIAL("The control goes to '" + script.entity + "', there is no player entity.");
+            ScriptSetPlayerEntity(script.entity.c_str());
+            if (!background_2d_.HasScrollControl()) background_2d_.ScriptAutoScrollToEntity(entity);
+        }
+    }
 }
 
 bool EntityManager::IsPlayerLocked() const{return player_lock_;}
@@ -1026,7 +1053,12 @@ void EntityManager::SetEncounterRate(float rate){
     else encounter_rate_ = rate;
 }
 
+bool EntityManager::IsStartKeyRead() const{
+    return std::chrono::steady_clock::now() - start_key_read_time_ < std::chrono::milliseconds(300);
+}
+
 bool EntityManager::IsKeyOn(unsigned int key_code){
+    if (key_code & 2048) start_key_read_time_ = std::chrono::steady_clock::now();
     // The keys are read even if the player is locked: scenes lock the player and still ask for a
     // button, as the minigames that need to be pressed at the right time do. The scripts that
     // must not read the keys at some point (while a message is open, for example) have their own
@@ -1181,8 +1213,23 @@ bool EntityManager::PerformWalkmeshMove(Entity* entity, const float speed, const
         return false;
     }
     int current_triangle = entity->GetMoveTriangleId();
+    // A character that is not on the walkmesh (Jenova of shpin_3, that is placed outside it and
+    // moves with FMOVE) is walked in a straight line, or the scene that waits for it would never go
+    // on.
+    if (current_triangle == -1 && scripted_move && entity != player_entity_){
+        const float step = std::min(direction.length(), distance_to_target);
+        Ogre::Vector2 move = direction;
+        if (!move.isZeroLength()) move.normalise();
+        move *= step;
+        entity->SetPosition(Ogre::Vector3(start_point.x + move.x, start_point.y + move.y, start_point.z));
+        if (distance_to_target - step <= stop_distance + 0.0001f) entity->UnsetMove();
+        return step > 0.0f;
+    }
     if (current_triangle == -1){
-        LOG_ERROR("Entity '" + entity->GetName() + "' not placed on walkmesh and can't move.");
+        // The entities that a scene places later (the soldiers of the parade of junonr4) are asked
+        // to move before it, and wait. Only the player has to be on the walkmesh.
+        if (entity == player_entity_)
+            LOG_ERROR("Entity '" + entity->GetName() + "' not placed on walkmesh and can't move.");
         return false;
     }
     Ogre::Vector3 rotation(0.0f, 0.0f, 0.0f);
@@ -1444,6 +1491,7 @@ bool EntityManager::WalkmeshBorderCross(
       entity == player_entity_ && !player_lock_, entity->IsScriptedMove()
     );
     Ogre::Vector2 pos = Ogre::Vector2(position.x, position.y);
+    bool searched_other_triangle = false;
     for (;;){
         Ogre::Vector3 A3 = walkmesh_.GetA(current_triangle);
         Ogre::Vector3 B3 = walkmesh_.GetB(current_triangle);
@@ -1470,6 +1518,33 @@ bool EntityManager::WalkmeshBorderCross(
                 continue;
             }
         }
+        // A walk of a script goes on over the edge: it keeps the last triangle, unless the point is
+        // inside another one (the triangles apart from the rest, that scenes use to put a character
+        // higher than the floor, are not joined to it: the character would keep that height after
+        // leaving it).
+        if (free_walk && !searched_other_triangle){
+            searched_other_triangle = true;
+            int other_triangle = -1;
+            float other_distance = 9999.0f;
+            for (int i = 0; i < walkmesh_.GetNumberOfTriangles(); ++ i){
+                if (i == current_triangle) continue;
+                const Ogre::Vector3 a = walkmesh_.GetA(i);
+                const Ogre::Vector3 b = walkmesh_.GetB(i);
+                const Ogre::Vector3 c = walkmesh_.GetC(i);
+                if (!Ogre::Math::pointInTri2D(
+                  pos, Ogre::Vector2(a.x, a.y), Ogre::Vector2(b.x, b.y), Ogre::Vector2(c.x, c.y)
+                )) continue;
+                const float distance = std::abs(position.z - PointElevation(pos, a, b, c));
+                if (distance < other_distance){
+                    other_distance = distance;
+                    other_triangle = i;
+                }
+            }
+            if (other_triangle >= 0){
+                current_triangle = other_triangle;
+                continue;
+            }
+        }
         position.z = PointElevation(pos, A3, B3, C3);
         entity->SetMoveTriangleId(current_triangle);
         // A walk of a script goes on over the edge, keeping the last triangle.
@@ -1639,6 +1714,55 @@ void EntityManager::CheckTriggers(Entity* entity, const Ogre::Vector3& position)
     }
 }
 
+void EntityManager::ScriptSetLine(
+  const char* name, const float x1, const float y1, const float z1, const float x2, const float y2,
+  const float z2
+){
+    for (EntityTrigger* trigger : entity_triggers_){
+        if (trigger->GetName() == name){
+            trigger->SetPoints(Ogre::Vector3(x1, y1, z1), Ogre::Vector3(x2, y2, z2));
+            return;
+        }
+    }
+}
+
+void EntityManager::CheckEntityContacts(){
+    if (IsBattleModule() || !IsFieldModule()) return;
+    if (player_entity_ == nullptr || player_lock_ || !player_entity_->IsSolid()){
+        entities_in_contact_.clear();
+        return;
+    }
+    const Ogre::Vector3 player_position = player_entity_->GetPosition();
+    for (Entity* entity : entity_){
+        if (entity == player_entity_ || entity->IsLine() || !entity->IsSolid()) continue;
+        const Ogre::Vector3 position = entity->GetPosition();
+        const float height = (position.z < player_position.z)
+          ? entity->GetHeight() : player_entity_->GetHeight();
+        const float distance_z = position.z - player_position.z + height;
+        bool touching = false;
+        if (distance_z < height * 2 && distance_z >= 0){
+            const float reach = player_entity_->GetSolidRadius() + entity->GetSolidRadius() + 0.05f;
+            const float dx = position.x - player_position.x;
+            const float dy = position.y - player_position.y;
+            touching = dx * dx + dy * dy < reach * reach;
+        }
+        if (!touching){
+            entities_in_contact_.erase(entity);
+            continue;
+        }
+        if (!entities_in_contact_.insert(entity).second) continue;
+        ScriptEntity* script_entity = ScriptManager::getSingleton().GetScriptEntityByName(
+          ScriptManager::ENTITY, entity->GetName()
+        );
+        // Most entities have no script for it: nothing to say then.
+        if (script_entity != nullptr){
+            ScriptManager::getSingleton().ScriptRequest(
+              script_entity, "script_2", INTERACT_SCRIPT_PRIORITY, "", "", false, false
+            );
+        }
+    }
+}
+
 void EntityManager::CheckEntityInteract(){
     if (IsBattleModule()){
         LOG_WARNING(

+ 43 - 0
src/core/EntityManager.h

@@ -15,6 +15,8 @@
 
 #pragma once
 
+#include <chrono>
+#include <set>
 #include <map>
 #include <utility>
 #include <vector>
@@ -552,6 +554,32 @@ class EntityManager : public Manager, public Ogre::Singleton<EntityManager>{
          */
         bool IsKeyOff(unsigned int key_code);
 
+        /**
+         * Checks if a script has asked for the Start button a moment ago.
+         *
+         * The scenes that use Start for their own ends (blin70_3, to end the choice of the party)
+         * ask for it every frame, so the pause menu must not open with the same press.
+         *
+         * @return True if a script is asking for the Start button.
+         */
+        bool IsStartKeyRead() const;
+
+        /**
+         * Moves the line of a line entity (SLINE).
+         *
+         * @param[in] name Name of the entity.
+         * @param[in] x1 First vertex of the line.
+         * @param[in] y1 First vertex of the line.
+         * @param[in] z1 First vertex of the line.
+         * @param[in] x2 Second vertex of the line.
+         * @param[in] y2 Second vertex of the line.
+         * @param[in] z2 Second vertex of the line.
+         */
+        void ScriptSetLine(
+          const char* name, const float x1, const float y1, const float z1, const float x2,
+          const float y2, const float z2
+        );
+
         /**
          * Assigns a character to an entity.
          *
@@ -782,6 +810,17 @@ class EntityManager : public Manager, public Ogre::Singleton<EntityManager>{
          */
         void CheckEntityInteract();
 
+        /**
+         * Runs the contact script (script 2) of the entities that the player touches.
+         *
+         * The script of an entity that the original game runs when the player collides with it
+         * (the old man of condor1 starts his conversation that way, and only after it can be
+         * talked to). It runs once for each touch.
+         */
+        void CheckEntityContacts();
+
+
+
         /**
          * Calculates the next offset step for an entity.
          *
@@ -895,6 +934,10 @@ class EntityManager : public Manager, public Ogre::Singleton<EntityManager>{
          * Applies only for manual movement.
          */
         bool player_run_;
+        /// Entities that the player is touching.
+        std::set<const Entity*> entities_in_contact_;
+        /// Last time that a script asked for the Start button.
+        std::chrono::steady_clock::time_point start_key_read_time_;
 
         /**
          * Indicates if the player runs by default, and the run key makes it walk instead.

+ 7 - 3
src/core/EntityModel.cpp

@@ -308,9 +308,13 @@ void EntityModel::PlayAnimation(
         // finishes, so any script waiting for it would wait forever.
         if (animation_current_->getLength() <= 0.0f) animation_current_->setLoop(false);
         animation_current_->setEnabled(true);
-        animation_current_->setTimePosition(
-          (start == -1) ? animation_current_->getLength() : start
-        );
+        // A pose at the very end of the animation (the dead soldiers of shpin_3, that hold the last
+        // frame) is shown as the first frame: past the last key, the interpolation goes on to the
+        // first one, as it does when it loops. The time stays a hair before the end.
+        float time = (start == -1) ? animation_current_->getLength() : start;
+        const float length = animation_current_->getLength();
+        if (length > 0.0f && time >= length) time = std::max(0.0f, length - 0.0005f);
+        animation_current_->setTimePosition(time);
         animation_end_time_ = (end == -1) ? animation_current_->getLength() : end;
         animation_hold_ = (start != -1 && start == end) ? 1.0f / 30.0f : 0.0f;
         animation_state_ = state;

+ 8 - 2
src/core/MoviePlayer.cpp

@@ -168,8 +168,14 @@ int MoviePlayer::ScriptPlay(){
     return -1;
 }
 
+void MoviePlayer::ScriptUseMovieCamera(const bool use){movie_camera_ = use;}
+
+bool MoviePlayer::IsDrawnOver() const{
+    return state_.IsPlaying() && camera_data_.empty() && !movie_camera_;
+}
+
 bool MoviePlayer::IsDrawnBehind() const{
-    return state_.IsPlaying() && !camera_data_.empty();
+    return state_.IsPlaying() && (!camera_data_.empty() || movie_camera_);
 }
 
 void MoviePlayer::SetModelsHidden(const bool hidden){
@@ -298,7 +304,7 @@ void MoviePlayer::renderQueueStarted(
 ){
     if (!state_.IsPlaying()) return;
     if (!EntityManager::getSingleton().IsFieldModule()) return;
-    if (!camera_data_.empty()){
+    if (!camera_data_.empty() || movie_camera_){
         // Behind the models, which come in the main queue. They are only drawn if the movie has a
         // camera in the frame, or they would be in the wrong place. They are hidden with the
         // visibility mask of the viewport: skipping the queue would also skip the listeners that

+ 23 - 0
src/core/MoviePlayer.h

@@ -85,6 +85,14 @@ class MoviePlayer : public Ogre::RenderQueueListener{
          */
         int ScriptGetFrame() const;
 
+        /**
+         * Makes the next movies the background of the field (MVCAM): the models are drawn over them
+         * even if the movie has no camera data (the elevator of junair).
+         *
+         * @param[in] use True while the models go over the movies.
+         */
+        void ScriptUseMovieCamera(const bool use);
+
         /**
          * @return True while a movie is being played.
          */
@@ -98,6 +106,16 @@ class MoviePlayer : public Ogre::RenderQueueListener{
          */
         bool IsDrawnBehind() const;
 
+        /**
+         * Checks if the movie covers the whole screen, over the field.
+         *
+         * The movies with no camera are drawn over everything of the field, and the fades of the
+         * field (the scenes black the screen before a movie starts) must not hide them.
+         *
+         * @return True if a movie is playing over the field.
+         */
+        bool IsDrawnOver() const;
+
         /**
          * Draws the movie. If it has a camera it's drawn behind the models, and the models are
          * only drawn in the frames that have a camera. If not, it's drawn over the field and below
@@ -138,6 +156,11 @@ class MoviePlayer : public Ogre::RenderQueueListener{
          */
         bool camera_valid_ = false;
 
+        /**
+         * The script (MVCAM) wants the models over the movie.
+         */
+        bool movie_camera_ = false;
+
         /**
          * Whether the movie camera is in use.
          */

+ 3 - 0
src/core/ScreenFade.cpp

@@ -160,6 +160,9 @@ void ScreenFade::renderQueueStarted(
 ){
     if (queue_group_id != Ogre::RENDER_QUEUE_OVERLAY || !state_.IsVisible()) return;
     if (!EntityManager::getSingleton().IsFieldModule()) return;
+    // A movie that covers the screen is not under the fade: the scenes black the field and then
+    // play the movie (mtnvl2).
+    if (EntityManager::getSingleton().GetMoviePlayer()->IsDrawnOver()) return;
 
     Ogre::MaterialPtr material;
     switch (state_.GetBlend()){

+ 19 - 0
src/core/ScriptManager.cpp

@@ -118,6 +118,13 @@ void ScriptManager::Input(const VGears::Event& event){
 }
 
 void ScriptManager::Update(const ScriptManager::Type type){
+    // Remove the scripts that a request has replaced.
+    for (unsigned int i = 0; i < script_entity_.size(); ++ i){
+        if (script_entity_[i].type != type) continue;
+        for (size_t k = script_entity_[i].queue.size(); k --;){
+            if (script_entity_[i].queue[k].replaced) RemoveEntityScript(script_entity_[i], k);
+        }
+    }
     // Resort all queue. This will give correct info for debug draw.
     for (unsigned int i = 0; i < script_entity_.size(); ++ i){
         if (script_entity_[i].type == type){
@@ -739,6 +746,18 @@ bool ScriptManager::ScriptRequest(
             }
         }
 
+        // A script that is only polling (a loop that waits for a key or a flag, with no pause)
+        // is replaced by the request of one with a higher priority, as the scenes do to stop the
+        // loops of the keys (the mimic of the parade of junin1a).
+        if (function != "on_update" && function != "on_start" && function != "on_button"){
+            for (QueueScript& other : script_entity->queue){
+                if (
+                  other.priority > priority && other.yield && !other.wait
+                  && other.function != "on_update" && other.function != "on_start"
+                  && other.function != "on_button"
+                ) other.replaced = true;
+            }
+        }
         script_entity->queue.push_back(script);
         script_entity->resort = true;
         return true;

+ 8 - 1
src/core/ScriptManager.h

@@ -66,7 +66,8 @@ struct QueueScript{
       state(NULL),
       seconds_to_wait(0),
       wait(false),
-      yield(false)
+      yield(false),
+      replaced(false)
     {}
 
     /**
@@ -94,6 +95,12 @@ struct QueueScript{
      */
     int priority;
 
+    /**
+     * A request with a higher priority (a smaller number) has replaced the script, which was a
+     * loop that was only polling something. It is removed in the next update.
+     */
+    bool replaced;
+
     /**
      * Current state.
      */

+ 5 - 0
src/core/ScriptManagerBinds.h

@@ -230,6 +230,8 @@ void ScriptManager::InitBinds(){
       "roll_encounter_battle", &EntityManager::ScriptRollEncounterBattle,
       "is_key_on", &EntityManager::IsKeyOn,
       "is_key_off", &EntityManager::IsKeyOff,
+      "is_start_key_read", &EntityManager::IsStartKeyRead,
+      "set_line", &EntityManager::ScriptSetLine,
       "set_entity_to_character", &EntityManager::SetEntityToCharacter
     );
 
@@ -383,6 +385,7 @@ void ScriptManager::InitBinds(){
       "get_battle_track_id", &AudioManager::ScriptGetBattleTrack,
       "set_battle_track_id", &AudioManager::ScriptSetBattleTrack,
       "play_music_once", &AudioManager::ScriptPlayMusicOnce,
+      "stop_music", &AudioManager::MusicStop,
       "is_music_playing", &AudioManager::ScriptIsMusicPlaying,
       "set_music_volume", &AudioManager::ScriptSetMusicVolume,
       "set_sound_volume", &AudioManager::ScriptSetSoundVolume
@@ -524,6 +527,7 @@ void ScriptManager::InitBinds(){
       "MoviePlayer",
       "set", &MoviePlayer::ScriptSet,
       "stop", &MoviePlayer::ScriptStop,
+      "use_movie_camera", &MoviePlayer::ScriptUseMovieCamera,
       "get_frame", &MoviePlayer::ScriptGetFrame,
       "is_playing", &MoviePlayer::ScriptIsPlaying
     );
@@ -558,6 +562,7 @@ void ScriptManager::InitBinds(){
       "Dialog",
       "dialog_open", &DialogsManager::OpenDialog,
       "set_numeric", &DialogsManager::SetNumeric,
+      "set_number", &DialogsManager::SetNumber,
       "update_timer", &DialogsManager::UpdateTimer,
       "set_mode", &DialogsManager::SetMode,
       "dialog_set_text", &DialogsManager::SetText,

+ 37 - 4
src/core/UiTextArea.cpp

@@ -211,6 +211,26 @@ void UiTextArea::SetPadding(
     padding_left_ = left;
 }
 
+void UiTextArea::PutNumber(const std::string& number, const int digits){
+    if (digits <= 0) return;
+    int run_end = -1;
+    for (size_t i = 0; i < text_.size();){
+        if (text_[i].char_code == ' '){
+            size_t j = i;
+            while (j < text_.size() && text_[j].char_code == ' ') ++ j;
+            if (static_cast<int>(j - i) >= digits) run_end = static_cast<int>(j);
+            i = j;
+        }
+        else ++ i;
+    }
+    if (run_end < 0) return;
+    std::string padded = number;
+    while (static_cast<int>(padded.size()) < digits) padded = " " + padded;
+    if (static_cast<int>(padded.size()) > digits) padded = padded.substr(padded.size() - digits);
+    for (int k = 0; k < digits; ++ k) text_[run_end - digits + k].char_code = padded[k];
+    update_transformation_ = true;
+}
+
 void UiTextArea::SetText(const char* text){
     // Don't call PrepareTextFromNode from here!
     // Use the non-recursive SetTextFromNode.
@@ -222,6 +242,7 @@ void UiTextArea::SetText(const char* text){
     SetTextFromNode(doc.RootElement(), colour_1_);
     text_state_ = TS_SHOW_TEXT;
     update_transformation_ = true;
+    GrowVertexBuffer(text_.size());
     if (text_.size() > max_letters_){
         text_.clear();
         LOG_ERROR(
@@ -260,6 +281,7 @@ void UiTextArea::SetText(TiXmlNode* text){
     PrepareTextFromNode(text, colour_1_);
     text_state_ = TS_SHOW_TEXT;
     update_transformation_ = true;
+    GrowVertexBuffer(text_.size());
     if (text_.size() > max_letters_){
         text_.clear();
         LOG_ERROR(
@@ -617,7 +639,8 @@ void UiTextArea::PrepareTextFromNode(TiXmlNode* node, const Ogre::ColourValue& c
                           = node->ToElement()->Attribute(Ogre::String("time"));
                         if (string != NULL){
                             TextChar new_char;
-                            new_char.pause_time = Ogre::StringConverter::parseReal(*string);
+                            // The time of the pause is in frames of the game (30 per second), as in the original game.
+                            new_char.pause_time = Ogre::StringConverter::parseReal(*string) / 30.0f;
                             text_.push_back(new_char);
                         }
                     }
@@ -783,7 +806,8 @@ void UiTextArea::SetTextFromNode(TiXmlNode* node, const Ogre::ColourValue& colou
                       = node->ToElement()->Attribute(Ogre::String("time"));
                     if (string != NULL){
                         TextChar new_char;
-                        new_char.pause_time = Ogre::StringConverter::parseReal(*string);
+                        // The time of the pause is in frames of the game (30 per second), as in the original game.
+                        new_char.pause_time = Ogre::StringConverter::parseReal(*string) / 30.0f;
                         text_.push_back(new_char);
                     }
                 }
@@ -931,8 +955,17 @@ void UiTextArea::PrepareTextFromText(
     };
 }
 
-void UiTextArea::CreateVertexBuffer(){
-    max_letters_ = 1024;
+void UiTextArea::GrowVertexBuffer(const unsigned int letters){
+    const unsigned int LIMIT = 8192;
+    if (letters <= max_letters_ || letters > LIMIT || render_operation_.vertexData == nullptr) return;
+    unsigned int size = max_letters_ > 0 ? max_letters_ : 1024;
+    while (size < letters) size *= 2;
+    DestroyVertexBuffer();
+    CreateVertexBuffer(size);
+}
+
+void UiTextArea::CreateVertexBuffer(const unsigned int letters){
+    max_letters_ = letters;
     render_operation_.vertexData = new Ogre::VertexData;
     render_operation_.vertexData->vertexStart = 0;
     Ogre::VertexDeclaration* vertex_declaration = render_operation_.vertexData->vertexDeclaration;

+ 22 - 1
src/core/UiTextArea.h

@@ -281,6 +281,16 @@ class UiTextArea : public UiWidget{
          */
         void SetText(TiXmlNode* text);
 
+        /**
+         * Writes a number in the text (WNUMB): it takes the place of the last run of spaces that
+         * is wide enough for it, aligned to the right. The texts of the number windows have those
+         * spaces for it ("Live TV Ratings              %").
+         *
+         * @param[in] number The digits of the number.
+         * @param[in] digits Width of the number.
+         */
+        void PutNumber(const std::string& number, const int digits);
+
         /**
          * Removes the text from the text area.
          */
@@ -416,8 +426,19 @@ class UiTextArea : public UiWidget{
 
         /**
          * Creates a vertex buffer for the textarea.
+         *
+         * @param[in] letters Number of letters that fit in it.
+         */
+        void CreateVertexBuffer(const unsigned int letters = 1024);
+
+        /**
+         * Makes the vertex buffer bigger if the text doesn't fit (some dialogs of the fields have
+         * more than a thousand letters). The text areas start with a small one because there are
+         * hundreds of them.
+         *
+         * @param[in] letters Number of letters that are needed.
          */
-        void CreateVertexBuffer();
+        void GrowVertexBuffer(const unsigned int letters);
 
         /**
          * Destroys a vertex buffer for the textarea.

+ 5 - 1
src/core/XmlBackground2DFile.cpp

@@ -76,9 +76,13 @@ void XmlBackground2DFile::Load(){
                 const int state = GetInt(node, "state", 0);
                 // The layer of the original background the tile is from.
                 const int layer = GetInt(node, "layer", 0);
+                // The additive tiles that only add a quarter of their colour (the glow of
+                // ujunon4) write it here.
+                const float intensity = GetFloat(node, "intensity", 1.0f);
                 background->AddTile(
                   static_cast<int>(destination.x), static_cast<int>(destination.y),
-                  width, height, buffer_depth, uv.x, uv.y, uv.z, uv.w, blending, area, state, layer
+                  width, height, buffer_depth, uv.x, uv.y, uv.z, uv.w, blending, area, state, layer,
+                  intensity
                 );
                 TiXmlNode* node2 = node->FirstChild();
                 while (node2 != nullptr){

+ 3 - 2
src/installer/FieldDataInstaller.cpp

@@ -225,7 +225,6 @@ bool FieldDataInstaller::IsAFieldFile(const Ogre::String& resource_name){
 bool FieldDataInstaller::WillCrash(const Ogre::String& resource_name){
     if (
       resource_name == "bugin1a" // crashes in back ground image generation
-      || resource_name == "frcyo" // Hangs in decompliation
       || resource_name == "fr_e" // Background image crash
       || resource_name == "las4_2" // Background image crash
       || resource_name == "las4_3" // Background image crash
@@ -234,7 +233,6 @@ bool FieldDataInstaller::WillCrash(const Ogre::String& resource_name){
       || resource_name == "trnad_3" // Background image crash
       || resource_name == "bonevil2" // stof
       || resource_name == "coloin1" // boost::bad_format_string: format-string is ill-formed
-      || resource_name == "del3" // Segmentation fault.
       || resource_name == "elmin4_2" // boost::bad_format_string: format-string is ill-formed
     ) return true;
     return false;
@@ -1108,6 +1106,9 @@ void FieldDataInstaller::PcFieldToVGearsField(VGears::FLevelFilePtr& field){
                     // TODO: Should probably throw to fail conversion:
                     else blending_str = "unknown";
                     xml_element->SetAttribute("blending", blending_str);
+                    // Type 3 adds only a quarter of the colour of the tile: with all of it the
+                    // glows turn white (ujunon4).
+                    if (sprite.blending == 3) xml_element->SetAttribute("intensity", "0.25");
                     // The layer is needed by the scripts that scroll them at their own speed.
                     xml_element->SetAttribute("layer", layer_index);
                     // The sprites that belong to a group (animation_id) are drawn only while a

+ 12 - 2
src/installer/FieldTextWriter.cpp

@@ -272,8 +272,12 @@ void FieldTextWriter::Write(const std::vector<u8>& script_section_buffer, std::s
                 }
                 else if (temp2 == 0xD9){ // White, or back to normal.
                     AddText(dialog);
-                    logger_->Log("</colour>");
-                    colour_opened --;
+                    // Some texts close a colour that they never opened (sinin2_2), which would
+                    // break the XML.
+                    if (colour_opened > 0){
+                        logger_->Log("</colour>");
+                        colour_opened --;
+                    }
                 }
                 else if (temp2 == 0xDA){ // Flash (blink), global for a window.
                     // TODO: Implement
@@ -318,9 +322,15 @@ void FieldTextWriter::Write(const std::vector<u8>& script_section_buffer, std::s
                     dialog.push_back(ENGLISH_CHARS[temp]);
                 }
                 else{
+                    // 0xE3 and 0xE4 end the sentences of many dialogs. Their exact meaning is not
+                    // verified: they are written as a full stop and an exclamation mark.
+                    if (temp == 0xE3 && english == true) dialog.push_back('.');
+                    else if (temp == 0xE4 && english == true) dialog.push_back('!');
+                    else{
                     AddText(dialog);
                     if (temp == 0xa9) logger_->Log("..."); // TODO Verify.
                     else logger_->Log("[MISSING CHAR " + HexToString(temp, 2, '0') + "]");
+                    }
                 }
             }
         }

+ 31 - 17
src/installer/MediaDataInstaller.cpp

@@ -1460,31 +1460,45 @@ bool MediaDataInstaller::InstallMusics(){
 }
 
 void MediaDataInstaller::InstallHQMusics(){
-    std::vector<std::string> hq_musics = {"hearth", "sato", "sensui", "wind"};
-    for (const std::string hq_music : hq_musics){
-
-        int index = 2000;
+    // Four tracks are not MIDI files: they are the WAV files of DATA/MUSIC (HEART.WAV, SATO.WAV,
+    // SENSUI.WAV and WIND.WAV). The index of the music (MUSIC.IDX) says which track is each one, and
+    // they are installed as the other ones are, with the number of the track as the name. Without
+    // them tracks 14, 64, 87 and 96 are missing (the music of junair2, for example).
+    std::vector<std::string> hq_musics = {"heart", "sato", "sensui", "wind"};
+    for (const std::string& hq_music : hq_musics){
+        int index = -1;
         for (auto const& m : musics_map_){
             if (m.second == hq_music){
                 index = m.first;
                 break;
             }
         }
-
-        if (ToolsReady(false)){
-            const std::string ffmpeg = ffmpeg_tool_.path;
-            // TODO: This path doesn't exist in the PC install disk (the files are in DATA/MUSIC, and one of them is
-            // called HEART, not "hearth"), so these conversions have never run. They are skipped quietly, as
-            // before, until the source files and the destination are sorted out.
-            const std::string wav = disk_image_.getContentPath() + "musics/" + hq_music + ".wav";
-            const std::string ogg = data_dir_ + "audio/sounds/" + std::to_string(index) + ".ogg";
-            if (!boost::filesystem::exists(wav)) continue;
-            RunConversion(
-              "high quality music " + hq_music,
-              [ffmpeg, wav, ogg](std::string* error){return ExternalTools::ConvertToOgg(ffmpeg, wav, ogg, error);}
-            );
+        if (index < 0){
+            InstallLog::Get().Add("[WARNING] The music " + hq_music + " is not in the index of the music.");
+            continue;
         }
+        if (!ToolsReady(false)) continue;
+        const std::string ffmpeg = ffmpeg_tool_.path;
+        std::string upper = hq_music;
+        std::transform(upper.begin(), upper.end(), upper.begin(), ::toupper);
+        const std::unique_ptr<std::string> wav_path = disk_image_.filePath("data/music/" + upper + ".wav");
+        if (!wav_path || !boost::filesystem::exists(*wav_path)){
+            InstallLog::Get().Add("[WARNING] The file of the music " + hq_music + " was not found.");
+            continue;
+        }
+        const std::string wav = *wav_path;
+        const std::string ogg = data_dir_ + "audio/musics/" + std::to_string(index) + ".ogg";
+        RunConversion(
+          "high quality music " + hq_music,
+          [ffmpeg, wav, ogg](std::string* error){return ExternalTools::ConvertToOgg(ffmpeg, wav, ogg, error);}
+        );
     }
+    // The index lists the tracks by their position, and the MIDI files are four less than the tracks:
+    // the last ones (94 to 97) were left out of it. A track with no file is not written to the index.
+    int last_id = 0;
+    for (auto const& m : musics_map_) last_id = std::max(last_id, m.first);
+    for (int id = static_cast<int>(musics_.size()); id <= last_id; ++ id)
+        musics_.push_back("audio/musics/" + std::to_string(id) + ".ogg");
 }
 
 bool MediaDataInstaller::ToolsReady(bool need_timidity){

+ 16 - 16
src/installer/decompiler/field/FieldDisassembler.cpp

@@ -249,7 +249,7 @@ void FieldDisassembler::AddFunc(
     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;
+          || last_opcode_ == OPCODES::JMPBL || last_opcode_ == OPCODES::RETTO;
         if (!ends){
             const auto& entries = header_.entity_scripts[entity_index];
             for (size_t i = 1; i < entries.size(); ++ i){
@@ -832,51 +832,51 @@ bool FieldDisassembler::ReadOpCodesToPositionOrReturn(
                     switch (opcode){
                         case OPCODES_KAWAI::EYETX:
                             // Parameters were "BBBB"
-                            ParseOpcode(opcode, "EYETX", new FieldModelInstruction(), 0, parameters.c_str());
+                            ParseOpcode((OPCODES::KAWAI << 8) | opcode, "EYETX", new FieldModelInstruction(), 0, parameters.c_str());
                             break;
                         case OPCODES_KAWAI::TRNSP:
                             // Parameters were "B"
-                            ParseOpcode(opcode, "TRNSP", new FieldModelInstruction(), 0, parameters.c_str());
+                            ParseOpcode((OPCODES::KAWAI << 8) | opcode, "TRNSP", new FieldModelInstruction(), 0, parameters.c_str());
                             break;
                         case OPCODES_KAWAI::AMBNT:
                             // Parameters were "AMBNT"
-                            ParseOpcode(opcode, "AMBNT", new FieldModelInstruction(), 0, parameters.c_str());
+                            ParseOpcode((OPCODES::KAWAI << 8) | opcode, "AMBNT", new FieldModelInstruction(), 0, parameters.c_str());
                             break;
                         case OPCODES_KAWAI::Unknown03:
-                            ParseOpcode(opcode, "Unknown03", new FieldModelInstruction(), 0, parameters.c_str());
+                            ParseOpcode((OPCODES::KAWAI << 8) | opcode, "Unknown03", new FieldModelInstruction(), 0, parameters.c_str());
                             break;
                         case OPCODES_KAWAI::Unknown04:
-                            ParseOpcode(opcode, "Unknown04", new FieldModelInstruction(), 0, parameters.c_str());
+                            ParseOpcode((OPCODES::KAWAI << 8) | opcode, "Unknown04", new FieldModelInstruction(), 0, parameters.c_str());
                             break;
                         case OPCODES_KAWAI::Unknown05:
-                            ParseOpcode(opcode, "Unknown05", new FieldModelInstruction(), 0, parameters.c_str());
+                            ParseOpcode((OPCODES::KAWAI << 8) | opcode, "Unknown05", new FieldModelInstruction(), 0, parameters.c_str());
                             break;
                         case OPCODES_KAWAI::LIGHT:
-                            ParseOpcode(opcode, "LIGHT", new FieldModelInstruction(), 0, parameters.c_str());
+                            ParseOpcode((OPCODES::KAWAI << 8) | opcode, "LIGHT", new FieldModelInstruction(), 0, parameters.c_str());
                             break;
                         case OPCODES_KAWAI::Unknown07:
-                            ParseOpcode(opcode, "Unknown07", new FieldModelInstruction(), 0, parameters.c_str());
+                            ParseOpcode((OPCODES::KAWAI << 8) | opcode, "Unknown07", new FieldModelInstruction(), 0, parameters.c_str());
                             break;
                         case OPCODES_KAWAI::Unknown08:
-                            ParseOpcode(opcode, "Unknown08", new FieldModelInstruction(), 0, parameters.c_str());
+                            ParseOpcode((OPCODES::KAWAI << 8) | opcode, "Unknown08", new FieldModelInstruction(), 0, parameters.c_str());
                             break;
                         case OPCODES_KAWAI::Unknown09:
-                            ParseOpcode(opcode, "Unknown09", new FieldModelInstruction(), 0, parameters.c_str());
+                            ParseOpcode((OPCODES::KAWAI << 8) | opcode, "Unknown09", new FieldModelInstruction(), 0, parameters.c_str());
                             break;
                         case OPCODES_KAWAI::SBOBJ:
-                            ParseOpcode(opcode, "SBOBJ", new FieldModelInstruction(), 0, parameters.c_str());
+                            ParseOpcode((OPCODES::KAWAI << 8) | opcode, "SBOBJ", new FieldModelInstruction(), 0, parameters.c_str());
                             break;
                         case OPCODES_KAWAI::Unknown0B:
-                            ParseOpcode(opcode, "Unknown0B", new FieldModelInstruction(), 0, parameters.c_str());
+                            ParseOpcode((OPCODES::KAWAI << 8) | opcode, "Unknown0B", new FieldModelInstruction(), 0, parameters.c_str());
                             break;
                         case OPCODES_KAWAI::Unknown0C:
-                            ParseOpcode(opcode, "Unknown0C", new FieldModelInstruction(), 0, parameters.c_str());
+                            ParseOpcode((OPCODES::KAWAI << 8) | opcode, "Unknown0C", new FieldModelInstruction(), 0, parameters.c_str());
                             break;
                         case OPCODES_KAWAI::SHINE:
-                            ParseOpcode(opcode, "SHINE", new FieldModelInstruction(), 0, parameters.c_str());
+                            ParseOpcode((OPCODES::KAWAI << 8) | opcode, "SHINE", new FieldModelInstruction(), 0, parameters.c_str());
                             break;
                         case OPCODES_KAWAI::RESET:
-                            ParseOpcode(opcode, "RESET", new FieldModelInstruction(), 0, parameters.c_str());
+                            ParseOpcode((OPCODES::KAWAI << 8) | opcode, "RESET", new FieldModelInstruction(), 0, parameters.c_str());
                             break;
                         default:
                             throw UnknownSubOpcodeException(this->address_, opcode);

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

@@ -43,7 +43,13 @@ void FieldCameraInstruction::ProcessInst(
     case OPCODES::FADE: ProcessFADE(code_gen); break;
     case OPCODES::FADEW: code_gen->AddOutputLine("screen_fade:wait()"); break;
     case OPCODES::SCRLP: code_gen->WriteTodo(md.GetEntityName(), "SCRLP"); break;
-    case OPCODES::MVCAM: code_gen->WriteTodo(md.GetEntityName(), "MVCAM"); break;
+    case OPCODES::MVCAM:
+        // The movie is the background of the field: the models are drawn over it.
+        code_gen->AddOutputLine(
+          std::string("movie_player:use_movie_camera(")
+          + (params_[0]->GetUnsigned() != 0 ? "true" : "false") + ")"
+        );
+        break;
     case OPCODES::SCRLA: ProcessSCRLA(code_gen, static_cast<FieldEngine&>(*engine)); break;
     default:
         code_gen->AddOutputLine(FieldCodeGenerator::FormatInstructionNotImplemented(

+ 40 - 22
src/installer/decompiler/field/instruction/FieldControlFlowInstruction.cpp

@@ -65,8 +65,8 @@ 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.
+    // Operands: the slot of the party (0 is the leader), the priority and the index of the script.
+    // The entity is the one of the character in that slot, 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);
@@ -79,31 +79,49 @@ void FieldControlFlowInstruction::ProcessPartyRequest(
 void FieldControlFlowInstruction::ProcessREQ(
   CodeGenerator* code_gen, const FieldEngine& engine
 ){
-    FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
-    const auto& entity = engine.EntityByIndex(params_[0]->GetSigned());
-    const auto& script_name = cg->GetFormatter().GetFriendlyFunctionName(
-      entity.GetName(), entity.FunctionByIndex(params_[2]->GetUnsigned())
-    );
-    auto priority = params_[1]->GetUnsigned();
-    code_gen->AddOutputLine((
-      boost::format("script:request(Script.ENTITY, \"%1%\", \"%2%\", %3%)")
-      % entity.GetName() % script_name % priority
-    ).str());
+    // Some scripts ask for a script that the entity doesn't have (niv_ti2): it does nothing.
+    try{
+        FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
+        const auto& entity = engine.EntityByIndex(params_[0]->GetSigned());
+        const auto& script_name = cg->GetFormatter().GetFriendlyFunctionName(
+          entity.GetName(), entity.FunctionByIndex(params_[2]->GetUnsigned())
+        );
+        auto priority = params_[1]->GetUnsigned();
+        code_gen->AddOutputLine((
+          boost::format("script:request(Script.ENTITY, \"%1%\", \"%2%\", %3%)")
+          % entity.GetName() % script_name % priority
+        ).str());
+    }
+    catch (const DecompilerException&){
+        code_gen->AddOutputLine((
+          boost::format("-- ERROR call to non existing function index %1%")
+          % params_[2]->GetUnsigned()
+        ).str());
+    }
 }
 
 void FieldControlFlowInstruction::ProcessREQSW(
   CodeGenerator* code_gen, const FieldEngine& engine
 ){
-    FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
-    const auto& entity = engine.EntityByIndex(params_[0]->GetSigned());
-    const auto& script_name = cg->GetFormatter().GetFriendlyFunctionName(
-      entity.GetName(), entity.FunctionByIndex(params_[2]->GetUnsigned())
-    );
-    auto priority = params_[1]->GetUnsigned();
-    code_gen->AddOutputLine((
-      boost::format("script:request_start_sync(Script.ENTITY, \"%1%\", \"%2%\", %3%)")
-      % entity.GetName() % script_name % priority
-    ).str());
+    // Some scripts ask for a script that the entity doesn't have (niv_ti2): it does nothing.
+    try{
+        FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
+        const auto& entity = engine.EntityByIndex(params_[0]->GetSigned());
+        const auto& script_name = cg->GetFormatter().GetFriendlyFunctionName(
+          entity.GetName(), entity.FunctionByIndex(params_[2]->GetUnsigned())
+        );
+        auto priority = params_[1]->GetUnsigned();
+        code_gen->AddOutputLine((
+          boost::format("script:request_start_sync(Script.ENTITY, \"%1%\", \"%2%\", %3%)")
+          % entity.GetName() % script_name % priority
+        ).str());
+    }
+    catch (const DecompilerException&){
+        code_gen->AddOutputLine((
+          boost::format("-- ERROR call to non existing function index %1%")
+          % params_[2]->GetUnsigned()
+        ).str());
+    }
 }
 
 void FieldControlFlowInstruction::ProcessREQEW(

+ 26 - 0
src/installer/decompiler/field/instruction/FieldMathInstruction.cpp

@@ -245,6 +245,18 @@ void FieldMathInstruction::ProcessBITOFF(CodeGenerator* code_gen){
     ).str());
 }
 
+bool FieldMathInstruction::IsByteOperation() const{
+    switch (opcode_){
+        case OPCODES::PLUS:
+        case OPCODES::MINUS:
+        case OPCODES::MUL:
+        case OPCODES::INC:
+        case OPCODES::DEC:
+            return true;
+        default: return false;
+    }
+}
+
 void FieldMathInstruction::ProcessPLUSx_MINUSx(CodeGenerator* code_gen, const std::string& op){
     FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
     // TODO: Check for assignment to value.
@@ -254,6 +266,14 @@ void FieldMathInstruction::ProcessPLUSx_MINUSx(CodeGenerator* code_gen, const st
     const auto& rhs = FieldCodeGenerator::FormatValueOrVariable(
       cg->GetFormatter(), params_[1]->GetUnsigned(), params_[3]->GetUnsigned()
     );
+    // The byte variables wrap around (a script that counts down from zero relies on it, as the
+    // palette animation of jumin does). The words are left as they are.
+    if (IsByteOperation()){
+        code_gen->AddOutputLine(
+          (boost::format("%1% = (%1% %2% %3%) %% 256") % lhs % op % rhs).str()
+        );
+        return;
+    }
     // TODO: repect destination bank sizes and wraparound
     code_gen->AddOutputLine((boost::format("%1% = %1% %2% %3%") % lhs % op % rhs).str());
 }
@@ -277,6 +297,12 @@ void FieldMathInstruction::ProcessINCx_DECx(CodeGenerator* code_gen, const std::
     const auto& destination = FieldCodeGenerator::FormatValueOrVariable(
       cg->GetFormatter(), params_[0]->GetUnsigned(), params_[1]->GetUnsigned()
     );
+    if (IsByteOperation()){
+        code_gen->AddOutputLine(
+          (boost::format("%1% = (%1% %2% 1) %% 256") % destination % op).str()
+        );
+        return;
+    }
     // TODO: repect destination bank sizes and wraparound
     code_gen->AddOutputLine((boost::format("%1% = %1% %2% 1") % destination % op).str());
 }

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

@@ -113,6 +113,13 @@ class FieldMathInstruction : public StoreInstruction{
          */
         void ProcessBITOFF(CodeGenerator* code_gen);
 
+        /**
+         * Checks if the opcode works on a byte variable, which wraps around at 256.
+         *
+         * @return True for PLUS, MINUS, MUL, INC and DEC (their word versions end in 2).
+         */
+        bool IsByteOperation() const;
+
         void ProcessPLUSx_MINUSx(CodeGenerator* code_gen, const std::string& op);
 
         void ProcessFunctionOfTwo(CodeGenerator* code_gen, const std::string& function);

+ 6 - 1
src/installer/decompiler/field/instruction/FieldMediaInstruction.cpp

@@ -35,7 +35,12 @@ void FieldMediaInstruction::ProcessInst(
         case OPCODES::MUSIC: ProcessMUSIC(code_gen); break;
         case OPCODES::SOUND: ProcessSOUND(code_gen); break;
         case OPCODES::AKAO: ProcessAKAO(code_gen); break;
-        case OPCODES::MUSVT: code_gen->WriteTodo(md.GetEntityName(), "MUSVT"); break;
+        case OPCODES::MUSVT:
+            // Music volume transition. Its use (the end of the parades of junin1a and jundoc1a)
+            // is to take the music out: the script waits (CHMST) for it to end. The fade is not
+            // known, so the music stops.
+            code_gen->AddOutputLine("audio_manager:stop_music()");
+            break;
         case OPCODES::MUSVM: code_gen->WriteTodo(md.GetEntityName(), "MUSVM"); break;
         case OPCODES::MULCK: ProcessMULCK(code_gen); break;
         case OPCODES::BMUSC: ProcessBMUSC(code_gen); break;

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

@@ -73,7 +73,7 @@ void FieldModuleInstruction::ProcessInst(
         case (OPCODES::SPECIAL << 8) | OPCODES_SPECIAL::CLITM:
             code_gen->WriteTodo(md.GetEntityName(), "CLITM");
             break;
-        case OPCODES::MINIGAME: code_gen->WriteTodo(md.GetEntityName(), "MINIGAME"); break;
+        case OPCODES::MINIGAME: ProcessMINIGAME(code_gen, func); break;
         case OPCODES::BTMD2: code_gen->WriteTodo(md.GetEntityName(), "BTMD2"); break;
         case OPCODES::BTRLD: code_gen->WriteTodo(md.GetEntityName(), "BTRLD"); break;
         case OPCODES::BTLTB: code_gen->WriteTodo(md.GetEntityName(), "BTLTB"); break;
@@ -144,6 +144,29 @@ void FieldModuleInstruction::ProcessBTLON(CodeGenerator* code_gen){
     ).str());
 }
 
+void FieldModuleInstruction::ProcessMINIGAME(CodeGenerator* code_gen, Function& func){
+    // Operands: the field where the game goes on when the minigame ends (and where the player is
+    // placed there, as in MAPJUMP) and the number of the minigame.
+    FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
+    const auto target_map_id = params_[0]->GetUnsigned();
+    FunctionMetaData md(func.metadata);
+    const std::string source_spawn_point_name = cg->GetFormatter().GetSpawnPointName(
+      target_map_id, md.GetEntityName(), func.name, address_
+    );
+    cg->GetFormatter().AddSpawnPoint(
+      target_map_id, md.GetEntityName(), func.name, address_,
+      params_[1]->GetSigned(), // X
+      params_[2]->GetSigned(), // Y
+      params_[3]->GetSigned(), // Walk mesh triangle ID
+      params_[4]->GetSigned()  // Angle
+    );
+    const std::string target_map_name = cg->GetFormatter().GetMapName(target_map_id);
+    code_gen->AddOutputLine((
+      boost::format("minigame(%1%, \"%2%\", \"%3%\")")
+      % params_[5]->GetUnsigned() % target_map_name % source_spawn_point_name
+    ).str());
+}
+
 void FieldModuleInstruction::ProcessMAPJUMP(CodeGenerator* code_gen, Function& func){
     FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
     const auto target_map_id = params_[0]->GetUnsigned();

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

@@ -118,4 +118,12 @@ class FieldModuleInstruction : public KernelCallInstruction{
          * @param[in] func Function to get the spawn point from.
          */
         void ProcessMAPJUMP(CodeGenerator* code_gen, Function& func);
+
+        /**
+         * Starts a minigame, and goes on to a field when it ends.
+         *
+         * @param[in,out] code_gen Code generator to append lines.
+         * @param[in] func Function to get the spawn point from.
+         */
+        void ProcessMINIGAME(CodeGenerator* code_gen, Function& func);
 };

+ 46 - 3
src/installer/decompiler/field/instruction/FieldPartyInstruction.cpp

@@ -30,8 +30,8 @@ void FieldPartyInstruction::ProcessInst(
     FunctionMetaData md(func.metadata);
     //std::cout << "Party opcode: " << opcode_ << "\n";
     switch (opcode_){
-        case OPCODES::SPTYE: code_gen->WriteTodo(md.GetEntityName(), "SPTYE"); break;
-        case OPCODES::GTPYE: code_gen->WriteTodo(md.GetEntityName(), "GTPYE"); break;
+        case OPCODES::SPTYE: ProcessPartyVariables(code_gen, true); break;
+        case OPCODES::GTPYE: ProcessPartyVariables(code_gen, false); break;
         case OPCODES::GOLDU: ProcessGOLDU(code_gen); break;
         case OPCODES::GOLDD: ProcessGOLDD(code_gen); break;
         case OPCODES::HMPMAX1: code_gen->WriteTodo(md.GetEntityName(), "HMPMAX1"); break;
@@ -48,7 +48,7 @@ void FieldPartyInstruction::ProcessInst(
         case OPCODES::STITM: ProcessSTITM(code_gen); break;
         case OPCODES::DLITM: ProcessDLITM(code_gen); break;
         case OPCODES::CKITM: ProcessCKITM(code_gen); break;
-        case OPCODES::SMTRA: code_gen->WriteTodo(md.GetEntityName(), "SMTRA"); break;
+        case OPCODES::SMTRA: ProcessSMTRA(code_gen, md.GetEntityName()); break;
         case OPCODES::DMTRA: code_gen->WriteTodo(md.GetEntityName(), "DMTRA"); break;
         case OPCODES::CMTRA: code_gen->WriteTodo(md.GetEntityName(), "CMTRA"); break;
         case OPCODES::GETPC: code_gen->WriteTodo(md.GetEntityName(), "GETPC"); break;
@@ -140,6 +140,49 @@ void FieldPartyInstruction::ProcessCKITM(CodeGenerator* code_gen){
     ).str());
 }
 
+void FieldPartyInstruction::ProcessSMTRA(CodeGenerator* code_gen, const std::string& entity){
+    // Operands: four bank nibbles (all of them zero in the original fields: the values are
+    // literal), the ID of the materia and its AP, in three bytes (255, 255, 255 is the most).
+    for (int i = 0; i < 4; i ++){
+        if (params_[i]->GetUnsigned() != 0){
+            code_gen->WriteTodo(entity, "SMTRA");
+            return;
+        }
+    }
+    const long ap = params_[5]->GetUnsigned() + params_[6]->GetUnsigned() * 256
+      + params_[7]->GetUnsigned() * 256 * 256;
+    code_gen->AddOutputLine((
+      boost::format("Materia.add(%1%, %2%)") % params_[4]->GetUnsigned() % ap
+    ).str());
+}
+
+void FieldPartyInstruction::ProcessPartyVariables(CodeGenerator* code_gen, const bool set){
+    // Operands: the banks of three variables (a nibble for each, plus an unused one) and their
+    // addresses. GTPYE stores the characters of the party in them (255 for an empty place) and
+    // SPTYE sets the party from them. The scenes that change the party (a flashback) keep it that
+    // way and restore it.
+    FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
+    std::string variables[3];
+    for (int i = 0; i < 3; i ++){
+        variables[i] = FieldCodeGenerator::FormatValueOrVariable(
+          cg->GetFormatter(), params_[i]->GetUnsigned(), params_[4 + i]->GetUnsigned()
+        );
+    }
+    if (set){
+        code_gen->AddOutputLine((
+          boost::format("set_party_from_values(%1%, %2%, %3%)")
+          % variables[0] % variables[1] % variables[2]
+        ).str());
+    }
+    else{
+        for (int i = 0; i < 3; i ++){
+            code_gen->AddOutputLine(
+              (boost::format("%1% = Party[%2%] or 255") % variables[i] % (i + 1)).str()
+            );
+        }
+    }
+}
+
 void FieldPartyInstruction::ProcessPRTYE(CodeGenerator* code_gen){
     std::string chars[3];
     for (int i = 0; i < 3; i ++){

+ 16 - 0
src/installer/decompiler/field/instruction/FieldPartyInstruction.h

@@ -163,6 +163,22 @@ class FieldPartyInstruction : public KernelCallInstruction{
 
         void ProcessPRTYE(CodeGenerator* code_gen);
 
+        /**
+         * Gives a materia to the party.
+         *
+         * @param[in,out] code_gen Code generator to append lines.
+         * @param[in] entity Name of the entity, for the unimplemented cases.
+         */
+        void ProcessSMTRA(CodeGenerator* code_gen, const std::string& entity);
+
+        /**
+         * Stores the party in variables (GTPYE) or sets it from them (SPTYE).
+         *
+         * @param[in,out] code_gen Code generator to append lines.
+         * @param[in] set True to set the party from the variables, false to store it in them.
+         */
+        void ProcessPartyVariables(CodeGenerator* code_gen, const bool set);
+
         /**
          * Processes a MMBUD opcode: makes a character available or unavailable in the PHS.
          */

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

@@ -47,7 +47,7 @@ void FieldWalkmeshInstruction::ProcessInst(
             break;
         case OPCODES::LINE: ProcessLINE(code_gen, md.GetEntityName()); break;
         case OPCODES::LINON: ProcessLINON(code_gen); break;
-        case OPCODES::SLINE: code_gen->WriteTodo(md.GetEntityName(), "SLINE"); break;
+        case OPCODES::SLINE: ProcessSLINE(code_gen, md.GetEntityName()); break;
         default:
             code_gen->AddOutputLine(FieldCodeGenerator::FormatInstructionNotImplemented(
               md.GetEntityName(), address_, opcode_
@@ -83,6 +83,24 @@ void FieldWalkmeshInstruction::ProcessLINE(CodeGenerator* code_gen, const std::s
     );
 }
 
+void FieldWalkmeshInstruction::ProcessSLINE(CodeGenerator* code_gen, const std::string& entity){
+    // Moves the line of the entity (the lines of the parade of junonr4 follow the last soldier).
+    // Operands: the banks of the six coordinates (a nibble each) and the six coordinates, which are
+    // values or the addresses of the variables that hold them.
+    FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
+    std::string coordinates[6];
+    for (int i = 0; i < 6; i ++){
+        coordinates[i] = "(" + FieldCodeGenerator::FormatValueOrVariable(
+          cg->GetFormatter(), params_[i]->GetUnsigned(), params_[6 + i]->GetSigned()
+        ) + ") / 128";
+    }
+    code_gen->AddOutputLine((
+      boost::format("entity_manager:set_line(\"%1%\", %2%, %3%, %4%, %5%, %6%, %7%)")
+      % entity % coordinates[0] % coordinates[1] % coordinates[2] % coordinates[3]
+      % coordinates[4] % coordinates[5]
+    ).str());
+}
+
 void FieldWalkmeshInstruction::ProcessLINON(CodeGenerator* code_gen){
     std::string on = ((params_[0]->GetSigned() == 1) ? "true" : "false");
     code_gen->AddOutputLine("self.on = " + on);

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

@@ -97,5 +97,7 @@ class FieldWalkmeshInstruction : public KernelCallInstruction{
          *
          * @param[in,out] code_gen Code generator to append lines.
          */
+        void ProcessSLINE(CodeGenerator* code_gen, const std::string& entity);
+
         void ProcessLINON(CodeGenerator* code_gen);
 };

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

@@ -65,7 +65,7 @@ void FieldWindowInstruction::ProcessInst(
         case OPCODES::WCLS: ProcessWCLSE(code_gen); break;
         case OPCODES::WSIZW: ProcessWSIZW(code_gen); break;
         case OPCODES::WSPCL: ProcessWSPCL(code_gen); break;
-        case OPCODES::WNUMB: code_gen->WriteTodo(md.GetEntityName(), "WNUMB"); break;
+        case OPCODES::WNUMB: ProcessWNUMB(code_gen); break;
         case OPCODES::STTIM: ProcessSTTIM(code_gen); break;
         case OPCODES::MESSAGE: ProcessMESSAGE(code_gen, eng.GetScriptName()); break;
         case OPCODES::MPARA: ProcessMPARA(code_gen); break;
@@ -102,6 +102,19 @@ void FieldWindowInstruction::ProcessWSIZW(CodeGenerator* code_gen){
     ).str());
 }
 
+void FieldWindowInstruction::ProcessWNUMB(CodeGenerator* code_gen){
+    // Operands: the bank of the value (two nibbles), the window, the address of the value (a word
+    // of the bank) and the number of digits, with a byte that is zero between them.
+    FieldCodeGenerator* cg = static_cast<FieldCodeGenerator*>(code_gen);
+    const std::string value = FieldCodeGenerator::FormatValueOrVariable(
+      cg->GetFormatter(), params_[0]->GetUnsigned(), params_[3]->GetUnsigned()
+    );
+    code_gen->AddOutputLine((
+      boost::format("dialog:set_number(\"%1%\", %2%, %3%)")
+      % params_[2]->GetUnsigned() % value % params_[5]->GetUnsigned()
+    ).str());
+}
+
 void FieldWindowInstruction::ProcessWSPCL(CodeGenerator* code_gen){
     auto window_id = params_[0]->GetUnsigned();
     std::string numeric = "false";
@@ -195,6 +208,11 @@ void FieldWindowInstruction::ProcessMENU(CodeGenerator* code_gen){
         case 0x0F: // Steal materia event.
             code_gen->AddOutputLine("Party.steal_materia()");
             break;
+        case 0x11: // Take the materia off a character.
+            code_gen->AddOutputLine(
+              (boost::format("Characters.unequip_materia(%1%)") % param).str()
+            );
+            break;
         case 0x12: // Remove materia from character.
             code_gen->AddOutputLine(
               (boost::format("Characters.remove_materia(%1%)") % param).str()
@@ -286,7 +304,7 @@ void FieldWindowInstruction::ProcessMPNAM(CodeGenerator* code_gen, const std::st
 
 void FieldWindowInstruction::ProcessMENU2(CodeGenerator* code_gen){
     code_gen->AddOutputLine((
-      boost::format("-- field:menu_lock(%1%)")
+      boost::format("menu_lock(%1%)")
       % FieldCodeGenerator::FormatBool(params_[0]->GetUnsigned())
     ).str());
 }

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

@@ -214,6 +214,8 @@ class FieldWindowInstruction : public KernelCallInstruction{
          *
          * @param[in,out] code_gen Code generator to append lines.
          */
+        void ProcessWNUMB(CodeGenerator* code_gen);
+
         void ProcessWSPCL(CodeGenerator* code_gen);
 
         /**