Jelajahi Sumber

Merge branch 'release/v0.3.5'

Iñigo Valentin 5 jam lalu
induk
melakukan
e5435220e0
97 mengubah file dengan 4991 tambahan dan 311 penghapusan
  1. 207 0
      .claude/skills/release/SKILL.md
  2. 1 1
      CMakeLists.txt
  3. 6 2
      data/data/screens/begin_menu/begin_menu.xml
  4. 5 0
      data/data/scripts/_scripts.xml
  5. 41 0
      data/data/scripts/debug_data.lua
  6. 81 7
      data/data/scripts/field.lua
  7. 23 3
      data/data/scripts/menu/begin_menu.lua
  8. 50 0
      data/data/scripts/system.lua
  9. 95 0
      data/data/scripts/worldmap/script_stubs.lua
  10. 132 0
      data/data/scripts/worldmap/triangle_triggers.lua
  11. 1 10
      data/data/scripts/worldmap/vehicles.lua
  12. 102 0
      data/data/scripts/worldmap/world_model_table.lua
  13. 64 0
      data/data/scripts/worldmap/world_music.lua
  14. 113 0
      data/data/scripts/worldmap/world_settings.lua
  15. 335 0
      data/data/scripts/worldmap/world_vm.lua
  16. 2 0
      data/data/texts/english/menu.xml
  17. 48 0
      doc/CHANGELOG.md
  18. 2 0
      doc/INSTALL_DATA.md
  19. 69 0
      doc/TODO.md
  20. 1 0
      src/CMakeLists.txt
  21. 3 3
      src/Version.h
  22. 5 0
      src/common/VGearsApplication.h
  23. 17 0
      src/core/AudioManager.cpp
  24. 16 0
      src/core/AudioManager.h
  25. 95 5
      src/core/Background2D.cpp
  26. 59 0
      src/core/Background2D.h
  27. 247 0
      src/core/BackgroundPalette.cpp
  28. 167 0
      src/core/BackgroundPalette.h
  29. 4 2
      src/core/DebugDraw.cpp
  30. 15 0
      src/core/DebugDraw.h
  31. 27 11
      src/core/DialogsManager.cpp
  32. 3 0
      src/core/DialogsManager.h
  33. 33 7
      src/core/Entity.cpp
  34. 47 0
      src/core/Entity.h
  35. 77 8
      src/core/EntityManager.cpp
  36. 35 0
      src/core/EntityManager.h
  37. 38 0
      src/core/EntityModel.cpp
  38. 30 0
      src/core/EntityModel.h
  39. 4 1
      src/core/ScreenFadeState.cpp
  40. 17 1
      src/core/ScriptManager.cpp
  41. 35 4
      src/core/ScriptManagerBinds.h
  42. 3 0
      src/core/XmlBackground2DFile.cpp
  43. 34 2
      src/data/VGearsBackgroundFile.cpp
  44. 46 0
      src/data/VGearsBackgroundFile.h
  45. 8 0
      src/data/VGearsTriggersFile.h
  46. 71 45
      src/installer/ExternalTools.cpp
  47. 14 0
      src/installer/ExternalTools.h
  48. 232 18
      src/installer/FieldDataInstaller.cpp
  49. 6 1
      src/installer/FieldDataInstaller.h
  50. 12 1
      src/installer/FieldTextWriter.cpp
  51. 4 1
      src/installer/InstallVerifier.cpp
  52. 39 11
      src/installer/WorldInstaller.cpp
  53. 162 0
      src/installer/WorldModelTable.h
  54. 14 1
      src/installer/decompiler/CodeGenerator.cpp
  55. 12 0
      src/installer/decompiler/CodeGenerator.h
  56. 41 3
      src/installer/decompiler/field/FieldCodeGenerator.cpp
  57. 9 0
      src/installer/decompiler/field/FieldCodeGenerator.h
  58. 2 0
      src/installer/decompiler/field/FieldDecompiler.cpp
  59. 17 0
      src/installer/decompiler/field/FieldDecompiler.h
  60. 20 0
      src/installer/decompiler/field/FieldDisassembler.cpp
  61. 5 0
      src/installer/decompiler/field/FieldDisassembler.h
  62. 23 0
      src/installer/decompiler/field/FieldEngine.cpp
  63. 60 0
      src/installer/decompiler/field/FieldEngine.h
  64. 68 26
      src/installer/decompiler/field/instruction/FieldBackgroundInstruction.cpp
  65. 2 1
      src/installer/decompiler/field/instruction/FieldBackgroundInstruction.h
  66. 17 3
      src/installer/decompiler/field/instruction/FieldControlFlowInstruction.cpp
  67. 1 0
      src/installer/decompiler/field/instruction/FieldControlFlowInstruction.h
  68. 35 12
      src/installer/decompiler/field/instruction/FieldMathInstruction.cpp
  69. 2 0
      src/installer/decompiler/field/instruction/FieldMathInstruction.h
  70. 24 2
      src/installer/decompiler/field/instruction/FieldMediaInstruction.cpp
  71. 4 0
      src/installer/decompiler/field/instruction/FieldMediaInstruction.h
  72. 56 10
      src/installer/decompiler/field/instruction/FieldModelInstruction.cpp
  73. 2 0
      src/installer/decompiler/field/instruction/FieldModelInstruction.h
  74. 18 1
      src/installer/decompiler/field/instruction/FieldModuleInstruction.cpp
  75. 1 0
      src/installer/decompiler/field/instruction/FieldModuleInstruction.h
  76. 8 2
      src/installer/decompiler/field/instruction/FieldPartyInstruction.cpp
  77. 7 1
      src/installer/decompiler/field/instruction/FieldWalkmeshInstruction.cpp
  78. 17 2
      src/installer/decompiler/field/instruction/FieldWindowInstruction.cpp
  79. 2 0
      src/installer/decompiler/field/instruction/FieldWindowInstruction.h
  80. 18 0
      src/installer/decompiler/world/WorldCodeGenerator.cpp
  81. 12 0
      src/installer/decompiler/world/WorldCodeGenerator.h
  82. 28 1
      src/installer/decompiler/world/WorldDisassembler.cpp
  83. 14 0
      src/installer/decompiler/world/WorldEngine.cpp
  84. 44 0
      src/installer/decompiler/world/WorldEngine.h
  85. 3 2
      src/installer/decompiler/world/instruction/WorldBinaryEqualStackInstruction.cpp
  86. 32 25
      src/installer/decompiler/world/instruction/WorldKernelCallInstruction.cpp
  87. 16 1
      src/installer/decompiler/world/instruction/WorldLoadBankInstruction.cpp
  88. 2 1
      src/installer/decompiler/world/instruction/WorldNoOutputInstruction.cpp
  89. 17 1
      src/installer/decompiler/world/instruction/WorldStoreInstruction.cpp
  90. 47 28
      src/installer/decompiler/world/instruction/WorldSubStackInstruction.cpp
  91. 5 0
      src/map/VGearsBackground2DFile.cpp
  92. 19 0
      src/map/VGearsBackground2DFile.h
  93. 3 0
      src/map/VGearsBackground2DFileXMLSerializer.cpp
  94. 977 36
      src/modules/worldmap/WorldmapModule.cpp
  95. 285 3
      src/modules/worldmap/WorldmapModule.h
  96. 5 5
      test/core/ScreenFadeState.cpp
  97. 14 0
      test/installer/ExternalTools.cpp

+ 207 - 0
.claude/skills/release/SKILL.md

@@ -0,0 +1,207 @@
+---
+name: release
+description: Cut a V-Gears release using git-flow. Bumps the version, writes the CHANGELOG entry, merges release/vX.Y.Z into master, tags it, merges back into develop, and (after confirmation) pushes. Usage - /release X.Y.Z
+disable-model-invocation: true
+argument-hint: X.Y.Z
+---
+
+# Release V-Gears
+
+Cut release `$ARGUMENTS` (format `X.Y.Z`, no leading `v`). If no argument is
+given, read the current version and ask the user which one to use (suggest the
+next minor).
+
+The project uses git-flow: `release/vX.Y.Z` is branched from `develop`, merged
+with `--no-ff` into `master`, tagged `vX.Y.Z` (annotated), and the tag is merged
+back into `develop`. Follow that exactly (see `git log --merges` for examples:
+"Merge branch 'release/v0.3.4'" and "Merge tag 'v0.3.4' into develop").
+
+Never push, force anything, or delete branches without the explicit
+confirmation in step 8. Stop and report on any failure instead of working
+around it.
+
+## 1. Preflight
+
+Run these checks in order.
+
+**Stop conditions** (report and stop, do not continue):
+
+- `git branch --show-current` must be `develop`. If not, ask the user before
+  switching.
+- `git status --porcelain` must be empty. If there are any uncommitted changes
+  (modified, staged or untracked files), list them, warn the user, and stop.
+  The user must commit or stash first. Do not stash or commit on their behalf.
+- `git fetch --all --tags`, then check `develop` is not behind `origin/develop`.
+- The tag `vX.Y.Z` and branch `release/vX.Y.Z` must not already exist.
+- The new version must be greater than the current one in `CMakeLists.txt`
+  (`project(V-Gears VERSION ...)`).
+
+**Warning** (tell the user and ask whether to continue):
+
+- Unmerged feature branches. List local and remote branches not yet merged into
+  `develop`: `git branch -a --no-merged develop`, ignoring `master`, `HEAD`
+  aliases and `develop` itself. For each one show the name and the number of
+  commits ahead of `develop` (`git rev-list --count develop..<branch>`). Their
+  work will not be in this release; ask the user to confirm that is intended.
+
+Find the previous release tag with `git describe --tags --abbrev=0`.
+
+## 2. Create the release branch
+
+```
+git checkout -b release/vX.Y.Z develop
+```
+
+## 3. Bump the version
+
+Update every place that holds the version:
+
+- `CMakeLists.txt`: `project(V-Gears VERSION X.Y.Z ...)`. This is the source of
+  truth; `src/Version.h.in` generates the build's `Version.h` from it.
+- `src/Version.h` (tracked, hand-maintained): `VGEARS_VERSION`,
+  `VGEARS_VERSION_MAJOR`, `VGEARS_VERSION_MINOR`, `VGEARS_VERSION_PATCH` and
+  `VGEARS_VERSION_SIGNATURE` (`"V-Gears vX.Y.Z"`). Set **every** field from the
+  new version (the existing values may be stale or inconsistent, e.g. a PATCH
+  that doesn't match `VGEARS_VERSION`). After editing, check that all five
+  agree with `X.Y.Z` and with `CMakeLists.txt`.
+
+Then `grep -rn "<previous version>" --include=*.md --include=*.txt --include=*.in .`
+(excluding `build*`, `_OLD`, `CHANGELOG.md`) and report any other version
+mentions to the user; update the ones that are clearly the app version.
+
+## 4. Changelog
+
+Draft a new `## X.Y.Z` section at the top of `doc/CHANGELOG.md`, directly under
+the `# Changelog` heading. The file is sorted by version in **decreasing order
+(newest first)**: the new section goes above all existing ones, and existing
+sections must keep that order. After editing, check the `## ` headings are
+strictly descending.
+
+1. Collect changes: `git log <prev-tag>..develop --no-merges --format='%h %s'`
+   and `git diff --stat <prev-tag>..develop`. Read diffs where commit messages
+   are vague. Do not invent changes that are not in the history.
+2. Match the style of the existing entries:
+   - First line: `Changes since <prev version>.` followed by one sentence
+     summarising where most of the work went.
+   - `### Area` headings (e.g. Battle, Field, World map, Installer, Engine and
+     scripting), with `**Subgroup**` labels and `- ` bullets where an area is
+     big.
+   - Plain, factual bullets describing user-visible behaviour, not commit
+     messages. No marketing language.
+3. Also review `doc/TODO.md`: remove or tick items that this release completed.
+   Don't add new items unless the user asks.
+4. **Show the drafted changelog (and TODO changes) to the user and wait for
+   approval or edits before committing.**
+
+## 5. Build, test and package
+
+Packaging is described in `doc/BUILD.md` ("Make packages"). Use the release
+build directory (create it if missing), with the project's build settings from
+memory (keep the fallbacks ON). Run `make` with half the system's cores:
+
+```
+mkdir -p build-release
+cd build-release
+cmake ../ -DCMAKE_BUILD_TYPE=Release
+make -j"$(( $(nproc) / 2 > 0 ? $(nproc) / 2 : 1 ))" v-gears v-gears-installer
+cpack
+```
+
+(`doc/BUILD.md` uses a fixed `-j4`; here `-j` is half of `nproc`, with a
+minimum of 1, unless the user says otherwise.) The version must have been bumped (step 3) before this, since the
+package version comes from `CMakeLists.txt`.
+
+Optionally run the tests (`-DBUILD_TESTS=ON` in a separate `build-tests`
+directory, targets `v-gears-installer-tests` and `v-gears-tests`, as in
+`doc/BUILD.md`); ask the user whether to run them, as it needs another build.
+
+When `cpack` finishes, `build-release/` must contain these four files for the
+new version (older versions' files are also in that directory; **ignore those**):
+
+- `v-gears_X.Y.Z_amd64.deb`
+- `v-gears_X.Y.Z_amd64.deb.sha256`
+- `v-gears-X.Y.Z-Linux-x86_64.tar.gz`
+- `v-gears-X.Y.Z-Linux-x86_64.tar.gz.sha256`
+
+Verify all four exist and are newer than the version bump commit, and verify
+the checksums (`sha256sum -c` from inside `build-release`, for the new files
+only). Report failures and stop. Note the packages only work on the distribution
+and version they were built on; mention this in the final report.
+
+## 6. Commit on the release branch
+
+```
+git add CMakeLists.txt src/Version.h doc/CHANGELOG.md doc/TODO.md
+git commit -m "vX.Y.Z"
+```
+
+(Past release commits were titled just with the version. Stage only the release
+files, nothing else.) End the commit message with the standard attribution
+lines.
+
+## 7. Merge and tag (local only)
+
+```
+git checkout master
+git merge --no-ff release/vX.Y.Z -m "Merge branch 'release/vX.Y.Z'"
+git tag -a vX.Y.Z -m "vX.Y.Z"
+git checkout develop
+git merge --no-ff vX.Y.Z -m "Merge tag 'vX.Y.Z' into develop"
+git branch -d release/vX.Y.Z
+```
+
+If a merge conflicts, stop and show the conflicts. Don't resolve silently.
+
+## 8. Push (requires confirmation)
+
+Show the user `git log --oneline --graph -8 --all` and the tag, then ask which
+remotes to push to. Remotes configured: `origin`, `github`, `inigovalentin`.
+Push only the ones the user confirms:
+
+```
+git push <remote> master develop vX.Y.Z
+```
+
+Never use `--force`. Pushing publishes the tag; it can't be cleanly undone.
+
+## 9. GitHub release (ask first)
+
+Pushing the tag to `github` does **not** create a GitHub Release by itself: it
+only makes the tag visible. This step creates the Release object from the
+existing tag `vX.Y.Z` and uploads the package files to it. It needs the tag to
+already be on the `github` remote (step 8) and `gh` to be authenticated
+(`gh auth status`).
+
+Ask the user to confirm, then:
+
+1. Extract the new `## X.Y.Z` section of `doc/CHANGELOG.md` (without the heading
+   line) into a file in the scratchpad directory.
+2. Create the release from the tag and attach the four package files, run from
+   the repo root:
+
+```
+gh release create vX.Y.Z \
+  --repo InigoValentin/V-Gears \
+  --verify-tag \
+  --title "vX.Y.Z" \
+  --notes-file <scratchpad>/release-notes.md \
+  build-release/v-gears_X.Y.Z_amd64.deb \
+  build-release/v-gears_X.Y.Z_amd64.deb.sha256 \
+  build-release/v-gears-X.Y.Z-Linux-x86_64.tar.gz \
+  build-release/v-gears-X.Y.Z-Linux-x86_64.tar.gz.sha256
+```
+
+`--verify-tag` makes it fail instead of creating the tag if it isn't on the
+remote. Pass exact file names, never a glob like `build-release/*`, so old
+versions' packages are not uploaded. Afterwards run
+`gh release view vX.Y.Z --repo InigoValentin/V-Gears` and confirm the four
+assets are listed. Print the release URL.
+
+If the user declines, say the release can be created later with the same
+command.
+
+## 10. Report
+
+Finish with a short summary: version, tag, commits created, remotes pushed, and
+the four package files, the GitHub release URL if created, and anything
+skipped or left for the user.

+ 1 - 1
CMakeLists.txt

@@ -1,7 +1,7 @@
 # Minimum required CMake and project declaration
 cmake_minimum_required(VERSION 3.5)
 # Enable both C and CXX languages so C and C++ toolchains are configured.
-project(V-Gears VERSION 0.3.4 LANGUAGES C CXX)
+project(V-Gears VERSION 0.3.5 LANGUAGES C CXX)
 
 # Provide a central common include for project-wide policies and defaults.
 list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/CMake")

+ 6 - 2
data/data/screens/begin_menu/begin_menu.xml

@@ -9,13 +9,17 @@
             <animation name="Position5" length="0" y="0:134" />
             <animation name="Position6" length="0" y="0:146" />
             <animation name="Position7" length="0" y="0:158" />
+            <animation name="Position8" length="0" y="0:170" />
+            <animation name="Position9" length="0" y="0:182" />
         </sprite>
         <text_area name="Text1" x="158" y="80" text_name="BeginMenuNewGame" font="FFVIIFont" visible="true" />
         <text_area name="Text2" x="158" y="92" text_name="BeginMenuLoadGame" font="FFVIIFont" visible="true" />
         <text_area name="Text3" x="158" y="110" text_name="BeginMenu2" font="FFVIIFont" visible="true" />
         <text_area name="Text4" x="158" y="122" text_name="BeginMenu3" font="FFVIIFont" visible="true" />
         <text_area name="Text5" x="158" y="134" text_name="BeginMenu4" font="FFVIIFont" visible="true" />
-        <text_area name="Text6" x="158" y="146" text_name="BeginMenu5" font="FFVIIFont" visible="true" />
-        <text_area name="Text7" x="158" y="158" text_name="BeginMenu6" font="FFVIIFont" visible="true" />
+        <text_area name="Text6" x="158" y="146" text_name="BeginMenuWorld1" font="FFVIIFont" visible="true" />
+        <text_area name="Text7" x="158" y="158" text_name="BeginMenuWorld2" font="FFVIIFont" visible="true" />
+        <text_area name="Text8" x="158" y="170" text_name="BeginMenu5" font="FFVIIFont" visible="true" />
+        <text_area name="Text9" x="158" y="182" text_name="BeginMenu6" font="FFVIIFont" visible="true" />
     </widget>
 </screen>

+ 5 - 0
data/data/scripts/_scripts.xml

@@ -30,6 +30,11 @@
     <script file="scripts/field.lua" />
     <script file="scripts/worldmap/triangle_triggers.lua" />
     <script file="scripts/worldmap/vehicles.lua" />
+    <script file="scripts/worldmap/world_model_table.lua" />
+    <script file="scripts/worldmap/world_settings.lua" />
+    <script file="scripts/worldmap/world_music.lua" />
+    <script file="scripts/worldmap/world_vm.lua" />
+    <script file="scripts/worldmap/script_stubs.lua" />
     <script file="scripts/battle_ai.lua" />
     <script file="scripts/battle/battle_ai_vm.lua" />
     <script file="scripts/battle/battle_camera.lua" />

+ 41 - 0
data/data/scripts/debug_data.lua

@@ -169,3 +169,44 @@ Materia.add(44)
 Materia.add(12)
 Materia.add(15, 2000)
 Materia.add(24)
+
+-- Where the entities of the overworld appear when it is loaded, in world units (x, z). Without this the
+-- game would use the spawn points of the story (not known yet), so they are all around the start of the
+-- test map, near Kalm. Remove an entry to use the default of that entity.
+WorldMapDebug = WorldMapDebug or {}
+WorldMapDebug.spawn = {
+    Cloud = {42.0, 36.5},
+    Chocobo = {42.5, 37.5},
+    Highwind = {43.0, 36.5},
+    Buggy = {42.0, 36.0},
+    Submarine = {41.5, 36.5},
+    TinyBronco = {42.0, 37.37},
+}
+
+-- Story of the overworld, for testing the models that depend on it. Without anything here the game
+-- takes the situation (the set of models of the map, 0 to 12) from the story, like the original does:
+-- the story counter (word 0 of the game variables, Banks[2][0] in the fields) and two flags (the bits
+-- 976 and 7220) give 0 the start (counter under 1000), 1 to 4 the Diamond Weapon (1000 to 1579; +1 with
+-- the bit 976, +2 from 1620 on), 5 to 8 the Ultimate Weapon and the Ruby Weapon (from 1580; +1 from
+-- 1620, +2 with the bit 7220). The situation can be forced for a map with WorldMapDebug.situation[map]
+-- (1 to 4 Diamond Weapon, with the Midgar cannon in 2 and 4 and the second Highwind in 3 and 4; 5 and
+-- 6 Ultimate Weapon; 7 and 8 Ruby Weapon; 11 the underwater map; 12 the snowstorm one).
+--
+-- The variables are the ones of the savemap that the world scripts read, and the fields write: they
+-- are written when the map is loaded. "word" and "byte" are by the address in bytes (the story counter
+-- is word 0), "bit" by the address in bits (the vehicles are the bits 1016 to 1021: 1016 the Buggy, 1018
+-- the Tiny Bronco, 1020 the Highwind, 1008 the Chocobo, 6787 and 6802 the Submarine, 6803 the Diamond
+-- Weapon appears) and "special" the values that the engine gives to the world (6 is the FIELD.TBL
+-- record of the exit by which the world was entered).
+--
+-- WorldMapDebug.arrival is that record, to test entering the world from a field exit: the vehicles
+-- and the player are where their scripts put them for it, except the ones with a spawn above.
+-- The map has to be loaded again to change any of this. Example: the story at 1400 with the Buggy, the
+-- Tiny Bronco and the Highwind.
+--WorldMapDebug.situation = {[0] = 3}
+--WorldMapDebug.arrival = 51
+WorldMapDebug.variables = {}
+--WorldMapDebug.variables = {
+--    word = {[0] = 1400},
+--    bit = {[1016] = 1, [1018] = 1, [1020] = 1},
+--}

+ 81 - 7
data/data/scripts/field.lua

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

+ 23 - 3
data/data/scripts/menu/begin_menu.lua

@@ -8,7 +8,7 @@ UiContainer.BeginMenu = UiContainer.Menu.new{
     --- Cursor over the entries.
     cursor = UiContainer.Cursor.new{
         widget = "BeginMenu.Container.Cursor",
-        total = 7,
+        total = 9,
     },
 
     --- Run when the menu is created.
@@ -96,7 +96,27 @@ UiContainer.BeginMenu = UiContainer.Menu.new{
             world_map_module:init()
         end,
 
-        -- 6: Start map.
+        -- 6: World map 1 (WM2).
+        function(self)
+            set_party(0, 2, 3)
+            script:request_end_sync(Script.UI, "BeginMenu", "hide", 0)
+            console("camera_free true")
+            console("debug_entity 2")
+            MenuSettings.pause_available = true
+            world_map_module:init(1)
+        end,
+
+        -- 7: World map 2 (WM3).
+        function(self)
+            set_party(0, 2, 3)
+            script:request_end_sync(Script.UI, "BeginMenu", "hide", 0)
+            console("camera_free true")
+            console("debug_entity 2")
+            MenuSettings.pause_available = true
+            world_map_module:init(2)
+        end,
+
+        -- 8: Start map.
         function(self)
             load_field_map_request("startmap", "")
             console("camera_free false")
@@ -105,7 +125,7 @@ UiContainer.BeginMenu = UiContainer.Menu.new{
             MenuSettings.pause_available = true
         end,
 
-        -- 7: Test battle.
+        -- 9: Test battle.
         function(self)
             --load_field_map_request("startmap", "")
             console("camera_free false")

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

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

+ 95 - 0
data/data/scripts/worldmap/script_stubs.lua

@@ -0,0 +1,95 @@
+--[[
+Stubs for the functions that the decompiled world map scripts (wm0.lua, wm2.lua and wm3.lua) call
+and that are not implemented yet.
+
+Each one does nothing and returns 0, and is reported the first time it is called, so the scripts
+that use them keep running instead of failing with a Lua error. They are not an implementation:
+the names come from the decompiler, and most of the ones called "kernel_unknown_*" have an unknown
+purpose.
+
+A function that is already defined somewhere else is never replaced.
+]]
+
+WorldMapStubs = WorldMapStubs or { reported = {} }
+
+--- Creates the stub of a function.
+-- @param name Name of the function.
+-- @return The stub.
+local function make_stub(name, quiet)
+    return function(...)
+        if not quiet and not WorldMapStubs.reported[name] then
+            WorldMapStubs.reported[name] = true
+            print("World map script function not implemented: " .. name)
+        end
+        return 0
+    end
+end
+
+--- Bitwise and of two numbers. The scripts of the world map use it for flags, and the Lua of the
+-- game has no bit library.
+BitAnd = function(a, b)
+    a = math.floor(a) % 4294967296
+    b = math.floor(b) % 4294967296
+    local result, bit = 0, 1
+    for _ = 1, 32 do
+        if a % 2 == 1 and b % 2 == 1 then result = result + bit end
+        a = math.floor(a / 2)
+        b = math.floor(b / 2)
+        bit = bit * 2
+    end
+    return result
+end
+
+--- Bitwise or of two numbers.
+BitOr = function(a, b)
+    a = math.floor(a) % 4294967296
+    b = math.floor(b) % 4294967296
+    local result, bit = 0, 1
+    for _ = 1, 32 do
+        if a % 2 == 1 or b % 2 == 1 then result = result + bit end
+        a = math.floor(a / 2)
+        b = math.floor(b / 2)
+        bit = bit * 2
+    end
+    return result
+end
+
+-- Functions of the decompiled scripts with a known name.
+local stubbed_functions = {
+    "Wait", "SetWaitFrames", "LoadModel", "SetActiveEntityDirectionAndFacing",
+    "SetActiveEntityDirection", "SetActiveEntityMovespeed", "SetActiveEntityMeshCoordinates",
+    "SetActiveEntityMeshCoordinatesInMesh", "SetLightMeshCoordinates",
+    "SetLightMeshCoordinatesInMesh", "SetActivePoint", "WaitForWindowReady",
+    "WaitForMessageAcknowledge", "SetWindowDimensions", "SetWindowMessage", "SetWindowParameters",
+    "SetControlLock", "PlaySoundEffect", "EnterVehicle", "FadeOut", "FadeIn",
+    "SetSubmarineColor", "SetChocoboType", "SetWorldProgress", "SetMeteorTexture", "Unknown333",
+    "Unknown_AKAO", "SetBattleLock", "TriggerBattle", "UnknownFunction1B",
+}
+for _, name in ipairs(stubbed_functions) do
+    if rawget(_G, name) == nil then
+        -- The ones with a known name are only the things that the placement of the entities doesn't
+        -- need (windows, waits, locks): not reported. The unknown ones are, to see what is missing.
+        _G[name] = make_stub(name, true)
+    end
+end
+
+-- The decompiler names the functions it can't identify "kernel_unknown_0x<opcode>". There are too
+-- many to list, and a new installation can have more, so they are stubbed when they are used.
+local previous_metatable = getmetatable(_G)
+setmetatable(_G, {
+    __index = function(table, key)
+        if type(key) == "string" and key:match("^kernel_unknown_0x%x+$") then
+            local stub = make_stub(key)
+            rawset(table, key, stub)
+            return stub
+        end
+        if previous_metatable and previous_metatable.__index then
+            if type(previous_metatable.__index) == "function" then
+                return previous_metatable.__index(table, key)
+            end
+            return previous_metatable.__index[key]
+        end
+        return nil
+    end,
+    __newindex = previous_metatable and previous_metatable.__newindex or nil,
+})

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

@@ -61,6 +61,11 @@ System.WorldMap = {
         local world_function = function_index
           and self["world_function_" .. tostring(function_index)]
         if world_function then
+            -- A place can only be entered by the vehicles that the settings say (WorldMapSettings.entry).
+            local record = WorldVM and WorldVM.find_field_entry(world_function)
+            if record and not WorldVM.can_enter(record, self.vehicle, self.landing) then
+                return
+            end
             world_function(self)
         else
             print(
@@ -71,6 +76,132 @@ System.WorldMap = {
     end,
 }
 
+--[[
+Memory of the world map scripts (Read, ReadWord, ReadBit and their Write functions).
+
+The variables of the game are the savemap from 0xBA4, the same as the memory banks of the field
+scripts: the address (or the bit, for ReadBit) goes through 256 bytes for each pair of banks, 1 and 2,
+3 and 4, 11 and 12, 13 and 14, and 7 and 15. The first one of the pair is the one for bytes and bits
+(Banks[1][127] and the bit 3 of it, BitBanks[1][127][3], are Read(127) and ReadBit(1019)), and the second
+one the one for words (Banks[2][0], the story counter, is ReadWord(0)). That way what the fields give
+(the vehicles, the progress of the story) is what the world has.
+
+ReadLocal and ReadSpecial are not game variables: the first is the memory of the scripts and the second
+what the engine gives them (the way in which the world was entered, in System.WorldMap.specials: 5 is 0
+when entering from a field and 6 the FIELD.TBL record of the exit).
+]]
+local BYTE_BANKS = {[0] = 1, 3, 11, 13, 7}
+local WORD_BANKS = {[0] = 2, 4, 12, 14, 15}
+
+--- Journal of the writes, when System.WorldMap.journal is a table: WorldVM undoes the changes of the
+-- functions that it runs only to see what they do.
+local function remember(container, key)
+    local journal = System.WorldMap.journal
+    if journal then journal[#journal + 1] = {container, key, container[key]} end
+end
+
+--- Where a byte address of the game variables is.
+-- @return The bank for bytes, the one for words and the address in them. nil if it is not in a bank.
+local function locate(address)
+    local index = math.floor(address / 256)
+    if index < 0 or index > 4 then return nil end
+    return BYTE_BANKS[index], WORD_BANKS[index], address % 256
+end
+
+--- Reads a byte of the game variables.
+Read = function(address)
+    local bank, _, offset = locate(address)
+    return bank and Banks[bank][offset] or 0
+end
+
+--- Reads a word of the game variables.
+ReadWord = function(address)
+    local _, bank, offset = locate(address)
+    return bank and Banks[bank][offset] or 0
+end
+
+--- Reads a bit of the game variables, as the address in bits.
+ReadBit = function(bit_address)
+    local bank, _, offset = locate(math.floor(bit_address / 8))
+    return bank and BitBanks[bank][offset][bit_address % 8] or 0
+end
+
+--- Writes a byte of the game variables.
+Write = function(address, value)
+    local bank, _, offset = locate(address)
+    if not bank then return end
+    remember(Banks[bank], offset)
+    Banks[bank][offset] = value
+end
+
+--- Writes a word of the game variables.
+WriteWord = function(address, value)
+    local _, bank, offset = locate(address)
+    if not bank then return end
+    remember(Banks[bank], offset)
+    Banks[bank][offset] = value
+end
+
+--- Writes a bit of the game variables, as the address in bits.
+WriteBit = function(bit_address, value)
+    local bank, _, offset = locate(math.floor(bit_address / 8))
+    if not bank then return end
+    remember(BitBanks[bank][offset], bit_address % 8)
+    BitBanks[bank][offset][bit_address % 8] = value ~= 0 and 1 or 0
+end
+
+System.WorldMap.locals = {}
+System.WorldMap.specials = {}
+
+--- Reads a value of the memory of the scripts.
+ReadLocal = function(address)
+    return System.WorldMap.locals[address] or 0
+end
+
+--- Writes a value of the memory of the scripts.
+WriteLocal = function(address, value)
+    System.WorldMap.locals[address] = value
+end
+
+--- Reads a value that the engine gives to the scripts.
+ReadSpecial = function(address)
+    return System.WorldMap.specials[address] or 0
+end
+
+--- Writes a value that the engine gives to the scripts.
+WriteSpecial = function(address, value)
+    System.WorldMap.specials[address] = value
+end
+
+--- The map of the module (0 WM0, 1 WM2, 2 WM3) that a field exit to the world map goes to.
+-- It is what the game does with the record: some of them are the underwater map (the submarine, 30, 31,
+-- 42 and 56) and from 60 on the snowstorm one.
+-- @param point_name Spawn point name of the exit (it has the coordinates).
+-- @param record FIELD.TBL record of the exit.
+-- @return The map.
+local function world_map_for_record(record)
+    if record == 30 or record == 31 or record == 42 or record == 56 then return 1 end
+    if record >= 60 then return 2 end
+    return 0
+end
+
+--- Goes from a field to the world map by a field exit.
+-- @param record FIELD.TBL record of the exit. The scripts of the world know where the player and the
+-- vehicles are by it.
+enter_world_map = function(record, point_name)
+    -- The "wm<N>" of the fields is one less than the record that the scripts of the world use (the exit of
+    -- Fort Condor is wm5 and its record is 6, the one of the submarine station wm41 and its record 42).
+    record = record + 1
+    -- Every field script starts with EntityContainer = {}, which deletes the scripts of the vehicles.
+    local vehicles = loadfile("./data/scripts/worldmap/vehicles.lua")
+    if vehicles then vehicles() else print("Could not reload the scripts of the vehicles") end
+    System.WorldMap.arrival = record
+    System.WorldMap.arrival_name = point_name
+    console("camera_free true")
+    MenuSettings.pause_available = true
+    world_map_module:enter(world_map_for_record(record))
+end
+
 EnterFieldScene = function(field_table_id, scenario)
     local field_table = System.WorldMap.field_table[tonumber(field_table_id)]
     local entry = field_table and field_table[tonumber(scenario)]
@@ -80,6 +211,7 @@ EnterFieldScene = function(field_table_id, scenario)
     end
 
     System.MapChanger.world_map_entry = entry
+    console("camera_free false")
     load_field_map_request(entry.field, "")
     return 0
 end

+ 1 - 10
data/data/scripts/worldmap/vehicles.lua

@@ -131,17 +131,12 @@ EntityContainer["WorldMapHighwind"].board = function(self)
 end
 EntityContainer["WorldMapHighwind"].unboard = function(self)
     if not is_unboarding_terrain_allowed(self) then
-        show_vehicle_error("The Highwind cannot be unboarded on this terrain.")
         return false
     end
+    -- The module lands the Highwind on the ground, wherever it was flying.
     if not world_map_module:unboard_vehicle(self.entity_name) then
         return false
     end
-
-    local vehicle_entity = entity_manager:get_entity(self.entity_name)
-    if vehicle_entity then
-        vehicle_entity:move_by(0, -self.rise_amount, 0)
-    end
     return true
 end
 
@@ -181,7 +176,6 @@ EntityContainer["WorldMapBuggy"].board = function(self)
 end
 EntityContainer["WorldMapBuggy"].unboard = function(self)
     if not is_unboarding_terrain_allowed(self) then
-        show_vehicle_error("The Buggy cannot be unboarded on this terrain.")
         return false
     end
     return world_map_module:unboard_vehicle(self.entity_name)
@@ -242,7 +236,6 @@ EntityContainer["WorldMapChocobo"].board = function(self)
 end
 EntityContainer["WorldMapChocobo"].unboard = function(self)
     if not is_unboarding_terrain_allowed(self) then
-        show_vehicle_error("The Chocobo cannot be unboarded on this terrain.")
         return false
     end
     return world_map_module:unboard_vehicle(self.entity_name)
@@ -276,7 +269,6 @@ EntityContainer["WorldMapSubmarine"].board = function(self)
 end
 EntityContainer["WorldMapSubmarine"].unboard = function(self)
     if not is_unboarding_terrain_allowed(self) then
-        show_vehicle_error("The Submarine cannot be unboarded on this terrain.")
         return false
     end
     return world_map_module:unboard_vehicle(self.entity_name)
@@ -312,7 +304,6 @@ EntityContainer["WorldMapTinyBronco"].board = function(self)
 end
 EntityContainer["WorldMapTinyBronco"].unboard = function(self)
     if not is_unboarding_terrain_allowed(self) then
-        show_vehicle_error("The Tiny Bronco cannot be unboarded on this terrain.")
         return false
     end
     return world_map_module:unboard_vehicle(self.entity_name)

+ 102 - 0
data/data/scripts/worldmap/world_model_table.lua

@@ -0,0 +1,102 @@
+-- The models of the world map and where each type of entity of the world scripts uses which one.
+--
+-- The data is from the tables of ff7.exe (see src/installer/WorldModelTable.h): the models are the
+-- HRC files of WORLD_US.LGP with the name and the scale the game gives them, and "situations" has
+-- the model that each type of entity has in each of the 13 situations of the map (the argument of
+-- LoadModel in the scripts is the type). The scale is the raw value of the game: 0x200 is 1.
+
+WorldMapModels = {
+    --- Name that the game gives each type of entity.
+    type_names = {
+        [0] = "cloud",
+        [1] = "tifa",
+        [2] = "cid",
+        [3] = "highwind",
+        [4] = "chocobo",
+        [5] = "tiny bronco",
+        [6] = "buggy",
+        [7] = "canon",
+        [8] = "warship",
+        [9] = "tail",
+        [10] = "diamond weapon",
+        [11] = "ultimate weapon",
+        [12] = "condor",
+        [13] = "submarine",
+        [14] = "gold saucer",
+        [15] = "rocket",
+        [16] = "rocket base",
+        [17] = "gernika",
+        [18] = "underwater mark",
+        [19] = "chocobo (2)",
+        [20] = "midgar cannon",
+        [21] = "snowpole 1",
+        [22] = "snowpole 2",
+        [23] = "snowpole 3",
+        [24] = "barrier",
+        [25] = "rock",
+        [26] = "coral key",
+        [27] = "sea object",
+        [28] = "submarine (2)",
+        [29] = "ruby weapon",
+        [30] = "emerald weapon",
+    },
+
+    --- HRC file (without extension), name and raw scale of each model.
+    models = {
+        aja = {name = "choko", scale = 0x200},
+        dva = {name = "tybrco", scale = 0x280},
+        aba = {name = "buggy", scale = 0x200},
+        aaa = {name = "barrier", scale = 0xdac},
+        bkd = {name = "condor", scale = 0xc80},
+        coc = {name = "rocket", scale = 0x8fc},
+        cpc = {name = "rocketbase", scale = 0x8fc},
+        cfc = {name = "goldsaucer", scale = 0xaf0},
+        -- "animation" is the position of the animation (from 0, in the order of the game) that the model
+        -- plays when it is placed, 0 if it is not there. Ultima Weapon: 0 stands, 1 flies, 2 is rammed
+        -- by the Highwind, 3 threatens a town, 4 hovers, 5 starts the battle, 6 a transition. Ruby
+        -- Weapon: 0 idle (out of the ground), 1 only the head shown, 2 the transition from 1 to 0.
+        -- Diamond Weapon: 0 stands, 1 walks, 2 and 3 turn left and right, 4 pose before the battle.
+        -- Emerald Weapon: 0 idle, 1 moving. "altitude" is a fixed height of the world (not over the
+        -- ground) where the entity is put, instead of the terrain.
+        -- The rotation of the model, in degrees (x, y, z), is how it has to be turned to face the way
+        -- that the direction of the script says. It was found by looking at the model.
+        aia = {name = "canon", scale = 0x1000, rotation = {0, 180, 0}},
+        cnb = {name = "rock", scale = 0x834},
+        cgd = {name = "highwind", scale = 0x300},
+        ddd = {name = "sbmrn", scale = 0x200},
+        dkc = {name = "tail", scale = 0x300},
+        bna = {name = "diaweapon", scale = 0x400},
+        eke = {name = "warship", scale = 0x1b8},
+        cmb = {name = "midgulcanon", scale = 0x1000},
+        cid = {name = "highwind02", scale = 0x300},
+        dyb = {name = "ultima", scale = 0x200, animation = 4},
+        cqc = {name = "ruby", scale = 0x280, animation = 1},
+        cec = {name = "gernika", scale = 0x1000},
+        eje = {name = "underseemk", scale = 0x1000},
+        ble = {name = "coralkey", scale = 0x300},
+        dic = {name = "seeobject", scale = 0x800},
+        dga = {name = "sbmrn2", scale = 0x200},
+        bud = {name = "emerald", scale = 0x280, animation = 0, altitude = -0.9},
+        djc = {name = "snowpole", scale = 0x300},
+        bbe = {name = "cloud", scale = 0x200},
+        dlb = {name = "tifa", scale = 0x200},
+        ata = {name = "cid", scale = 0x200},
+    },
+
+    --- For each situation, the HRC file of the model of each type of entity.
+    situations = {
+        [0] = {[4] = "aja", [5] = "dva", [6] = "aba", [7] = "aia", [12] = "bkd", [14] = "cfc", [15] = "coc", [16] = "cpc", [24] = "aaa", [25] = "cnb"},
+        [1] = {[3] = "cgd", [4] = "aja", [7] = "aia", [9] = "dkc", [10] = "bna", [12] = "bkd", [13] = "ddd", [14] = "cfc", [15] = "coc", [16] = "cpc", [19] = "aja", [24] = "aaa", [25] = "cnb"},
+        [2] = {[3] = "cgd", [4] = "aja", [9] = "dkc", [10] = "bna", [12] = "bkd", [13] = "ddd", [14] = "cfc", [15] = "coc", [16] = "cpc", [19] = "aja", [20] = "cmb", [24] = "aaa", [25] = "cnb"},
+        [3] = {[3] = "cid", [4] = "aja", [7] = "aia", [9] = "dkc", [10] = "bna", [12] = "bkd", [13] = "ddd", [14] = "cfc", [15] = "coc", [16] = "cpc", [19] = "aja", [24] = "aaa", [25] = "cnb"},
+        [4] = {[3] = "cid", [4] = "aja", [9] = "dkc", [10] = "bna", [12] = "bkd", [13] = "ddd", [14] = "cfc", [15] = "coc", [16] = "cpc", [19] = "aja", [20] = "cmb", [24] = "aaa", [25] = "cnb"},
+        [5] = {[3] = "cgd", [4] = "aja", [9] = "dkc", [11] = "dyb", [12] = "bkd", [13] = "ddd", [14] = "cfc", [15] = "coc", [16] = "cpc", [19] = "aja", [20] = "cmb", [24] = "aaa", [25] = "cnb"},
+        [6] = {[3] = "cid", [4] = "aja", [9] = "dkc", [11] = "dyb", [12] = "bkd", [13] = "ddd", [14] = "cfc", [15] = "coc", [16] = "cpc", [19] = "aja", [20] = "cmb", [24] = "aaa", [25] = "cnb"},
+        [7] = {[3] = "cgd", [4] = "aja", [9] = "dkc", [12] = "bkd", [13] = "ddd", [14] = "cfc", [15] = "coc", [16] = "cpc", [19] = "aja", [20] = "cmb", [25] = "cnb", [29] = "cqc"},
+        [8] = {[3] = "cid", [4] = "aja", [9] = "dkc", [12] = "bkd", [13] = "ddd", [14] = "cfc", [15] = "coc", [16] = "cpc", [19] = "aja", [20] = "cmb", [25] = "cnb", [29] = "cqc"},
+        [9] = {[7] = "aia", [8] = "eke"},
+        [10] = {[7] = "aia", [8] = "eke"},
+        [11] = {[13] = "ddd", [17] = "cec", [18] = "eje", [26] = "ble", [27] = "dic", [28] = "dga", [30] = "bud"},
+        [12] = {[21] = "djc", [22] = "djc", [23] = "djc"},
+    },
+}

+ 64 - 0
data/data/scripts/worldmap/world_music.lua

@@ -0,0 +1,64 @@
+--[[
+Music of the world map. The data (tracks, overrides and conditions) is in world_settings.lua
+(WorldMapSettings.music); this has the logic that picks the track and plays it.
+
+WorldMusic.update is called by the module when a map starts, when the vehicle changes, and every half
+second (the story can change the music while the map is on).
+]]
+
+WorldMusic = WorldMusic or {current = nil}
+
+--- Calls a function of the settings that can fail without stopping the game.
+local function safe(func, ...)
+    if type(func) ~= "function" then return nil end
+    local ok, result = pcall(func, ...)
+    if ok then return result end
+    return nil
+end
+
+--- Gets the track of a map and a vehicle.
+-- @param map_id 0 for WM0, 1 for WM2 (underwater), 2 for WM3 (snow).
+-- @param vehicle walk, chocobo, buggy, tiny_bronco, highwind or submarine.
+-- @return The track or nil.
+WorldMusic.choose = function(map_id, vehicle)
+    local music = WorldMapSettings and WorldMapSettings.music
+    if not music then return nil end
+    if map_id == 1 then return music.underwater end
+    if map_id == 2 then return music.snow end
+
+    -- The Chocobo always has priority.
+    if vehicle == "chocobo" and music.chocobo then return music.chocobo end
+
+    -- Overrides of the story: the vehicles don't change them.
+    for _, override in ipairs(music.overrides or {}) do
+        if safe(override.when) then return override.track end
+    end
+
+    -- The vehicles with their own track.
+    if vehicle == "highwind" and music.highwind and not safe(music.cloud_away) then
+        return music.highwind
+    end
+    if vehicle ~= "walk" and vehicle ~= "highwind" and vehicle ~= "chocobo" and music[vehicle] then
+        return music[vehicle]
+    end
+
+    -- The default one of the story.
+    local from_story = music.danger_from_story
+    if music.danger and from_story and ReadWord(0) >= from_story then return music.danger end
+    return music.default
+end
+
+--- Plays the track of the moment if it is not the one that is playing.
+-- @param map_id Map of the module.
+-- @param vehicle Name of the vehicle.
+WorldMusic.update = function(map_id, vehicle)
+    local track = WorldMusic.choose(map_id, vehicle)
+    if track == nil or track == WorldMusic.current then return end
+    WorldMusic.current = track
+    audio_manager:play_music(tostring(track))
+end
+
+--- Forgets the track that was playing (the next update plays it again).
+WorldMusic.reset = function()
+    WorldMusic.current = nil
+end

+ 113 - 0
data/data/scripts/worldmap/world_settings.lua

@@ -0,0 +1,113 @@
+-- Settings of the world map that are meant to be edited.
+
+local BLOCK = 8182 / 4096 -- units of a mesh block (a map block is 2 of them)
+local BASE = BLOCK * 0.45 -- the speed that the game has by default for walking
+
+--- Movement speeds, in world units per second (about 0.9 is the default walking speed).
+-- A name that is removed uses the default of the module (walking 0.9, the vehicles twice that).
+local speed = {
+    walk = BASE,
+    chocobo = BASE * 1.5,
+    buggy = BASE * 1.2,
+    tiny_bronco = BASE * 1.2,
+    -- The Highwind and the submarine (in WM2 and when diving) when they move forward.
+    highwind = BASE * 2,
+    submarine = BASE * 1.2,
+}
+
+-- The camera that the module had: 2.7 units from the vehicle, 33.7 degrees over the ground (the offset
+-- 1.5 up and 2.25 back). It is the distance that was good for the fastest vehicle.
+local DISTANCE = 2.0
+local PITCH = 33.7
+-- A bit more parallel to the ground, for the vehicles that fly.
+local FLIGHT_PITCH = 20
+WorldMapSettings = {
+    speed = speed,
+
+    --- Camera: distance to the vehicle (world units) and angle over the ground (degrees), by vehicle.
+    -- submarine_underwater is the submarine in WM2 and submarine the one that floats in WM0.
+    camera = {
+        walk = {distance = 1.35, pitch = PITCH},
+        chocobo = {distance = DISTANCE, pitch = PITCH},
+        buggy = {distance = DISTANCE, pitch = PITCH},
+        tiny_bronco = {distance = DISTANCE, pitch = PITCH},
+        highwind = {distance = DISTANCE, pitch = FLIGHT_PITCH},
+        submarine = {distance = DISTANCE, pitch = PITCH},
+        submarine_underwater = {distance = DISTANCE, pitch = FLIGHT_PITCH},
+    },
+
+    --- Music of the world map (the logic is in world_music.lua). Numbers are the tracks of audio/musics.
+    -- Written from the description of the game by the user, and from the scripts of the world (wm0.lua);
+    -- the pieces that are not known yet are marked TODO and are the ones to fix.
+    music = {
+        -- On foot (and the vehicles that have no music of their own).
+        default = 13, -- world_map
+        -- TODO: the track that replaces the default after some point of disc two (70, world_map_danger),
+        -- and the value of the story counter (ReadWord(0)) where it starts. nil means it never starts.
+        danger = 70,
+        danger_from_story = nil,
+
+        -- The Chocobo always has its own track (assumed, not checked).
+        chocobo = 50, -- chocobo_ride
+        -- The Highwind (WM0) has its own track, except when the music is an override of the story or
+        -- when cloud_away() is true.
+        highwind = 46, -- airship
+        -- TODO: the Buggy, the Tiny Bronco and the submarine of WM0 have no known music: they use
+        -- the default one. Put the track here when it is known (nil = the default).
+        buggy = nil,
+        tiny_bronco = nil,
+        submarine = nil,
+
+        -- WM2 (underwater) and WM3 (snow): one track that never changes.
+        -- TODO: 84 and 76 are from memory (84 is the "submarine" track of the installer), check them.
+        underwater = 84,
+        snow = 76,
+
+        --- Overrides of the story, in order of priority. The first one whose when() is true gives the
+        -- track, and the vehicles (except the Chocobo) don't change it.
+        overrides = {
+            -- While the Diamond Weapon is around. The conditions are the ones of the world script that
+            -- calls Unknown_AKAO(6) (bit 6803 set, 7212 set, 7209 not set); that 6 is guessed to mean 69.
+            -- TODO: check that the music ends with the Diamond Weapon (what ends it, when 7209 is set?).
+            {name = "diamond_weapon", track = 69, when = function()
+                return ReadBit(6803) ~= 0 and ReadBit(7212) ~= 0 and ReadBit(7209) == 0
+            end},
+            -- Before the last visit to Midgar. The script calls Unknown_AKAO(7) when the story counter is
+            -- exactly 1596; that 7 is guessed to mean 71.
+            -- TODO: the real range of the story counter (it may last more than that value).
+            {name = "before_last_midgar", track = 71, when = function()
+                return ReadWord(0) == 1596
+            end},
+        },
+
+        --- True while Cloud is not in the party: the Highwind doesn't change the music then.
+        -- TODO: find out when (the story counter range, or a flag). For now it is never.
+        cloud_away = function()
+            return false
+        end,
+    },
+
+    --- Which vehicles can enter the places of the map (towns, caves...). The numbers are the FIELD.TBL
+    -- records, the first parameter of EnterFieldScene (1 Midgar, 2 Kalm, 3 the chocobo farm, 7 Junon, 15 North
+    -- Corel, 18 Costa del Sol, 59 the northern cave...). On foot everything can be entered.
+    entry = {
+        --- Records that any vehicle can enter. The scripted events and the submarine station are here
+        -- so that nothing gets stuck.
+        -- TODO: check the list (50-52 are the ship fields, 56 the submarine station): add the other
+        -- records that are story events and not places, if some vehicle must be able to trigger them.
+        exempt = {[50] = true, [51] = true, [52] = true, [56] = true},
+
+        --- Exceptions to "only on foot", by vehicle: records that it can enter.
+        allowed = {
+            chocobo = {[3] = true}, -- the chocobo farm
+            -- Corel, Junon and Costa del Sol.
+            -- TODO: check the records of Corel: 15 is North Corel (ncorel), 14 Mt. Corel (mtcrl_0) and 16
+            -- the Corel desert (desert2) could be it too.
+            buggy = {[7] = true, [15] = true, [18] = true},
+        },
+
+        --- Records that the Highwind enters when it lands on the NORTHERND_CAVE terrain (it cannot enter
+        -- anything else, and it never enters while it is flying).
+        highwind_landing = {[59] = true}, -- the northern cave (las0_1)
+    },
+}

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

@@ -0,0 +1,335 @@
+--[[
+The part of the world map script machine that places the models.
+
+The decompiled scripts of the world map (wm0.lua, wm2.lua and wm3.lua) have a function for each type
+of entity that runs when the entity is created ("event 0" of the type), and sets where it is with
+SetActiveEntityMeshCoordinates, SetActiveEntityMeshCoordinatesInMesh and
+SetActiveEntityDirectionAndFacing. The installer writes which function is it in
+System.WorldMap.entity_functions[type][event].
+
+Here these three functions and LoadModel only store what the scripts ask, and WorldVM.place_models runs
+the functions of the types that have a simple one, and the models are created in the module with the
+positions that it got. Variables that the scripts read (Read) are 0 for now, as there is no savemap
+for them.
+]]
+
+WorldVM = WorldVM or {}
+
+--- Types of entities whose "event 0" function only sets the position, and that are not the
+-- vehicles. The functions of the other types run windows and wait for them, or depend on the story.
+WorldVM.static_types = {
+    [7] = true, [12] = true, [14] = true, [15] = true, [16] = true, [17] = true, [18] = true,
+    [20] = true, [24] = true, [25] = true, [26] = true, [28] = true,
+    -- The weapons. Their functions set the position by the story variables and don't wait.
+    [10] = true, [11] = true, [29] = true, [30] = true,
+}
+
+--- Situation of the models (the one of WorldMapModels.situations) that is used in the maps that don't
+-- depend on the story: the underwater one and the snowstorm one (WM0 has WorldVM.get_situation).
+WorldVM.default_situation = {[0] = 0, [1] = 11, [2] = 12}
+
+--- The situation of the models of WM0, from the story. It is the function 0x75cd4f of ff7.exe: the story
+-- counter (ReadWord(0)) and two flags of the savemap (the bits 976 and 7220) give a
+-- stage from 0 to 8, which is the situation (0 the start, 1 to 4 the Diamond Weapon, 5 and 6 the
+-- Ultimate Weapon, 7 and 8 the Ruby Weapon). The game also uses 9 and 10 (the Warship and the cannon)
+-- when it enters the world from some fields of Midgar, which is not handled.
+-- @return The situation.
+WorldVM.get_story_situation = function()
+    local story = ReadWord(0)
+    if story < 1000 then return 0 end
+    local late = story >= 1620 and 1 or 0
+    if story < 1580 then
+        -- The bit 976 is bit 0 of the byte 122 (the cannon is gone, as the world scripts use it).
+        return 1 + ReadBit(976) + late * 2
+    end
+    -- The bit 7220 is bit 4 of the byte 902.
+    return 5 + late + ReadBit(7220) * 2
+end
+
+--- Writes the variables of the story that the debug data has (WorldMapDebug.variables), for testing.
+WorldVM.apply_debug_variables = function()
+    local variables = WorldMapDebug and WorldMapDebug.variables
+    if not variables then return end
+    for address, value in pairs(variables.byte or {}) do Write(address, value) end
+    for address, value in pairs(variables.word or {}) do WriteWord(address, value) end
+    for address, value in pairs(variables.bit or {}) do WriteBit(address, value) end
+    for address, value in pairs(variables.special or {}) do WriteSpecial(address, value) end
+end
+
+--- Gets the situation of the models of a map.
+-- WorldMapDebug.situation[map] has priority, for testing.
+-- @param map_id Map of the module (0 WM0, 1 WM2, 2 WM3).
+-- @return The situation.
+WorldVM.get_situation = function(map_id)
+    WorldVM.apply_debug_variables()
+    local debug_situation = WorldMapDebug and WorldMapDebug.situation and WorldMapDebug.situation[map_id]
+    if debug_situation then return debug_situation end
+    if map_id == 0 then return WorldVM.get_story_situation() end
+    return WorldVM.default_situation[map_id]
+end
+
+--- Types of the vehicles of WM0, by the name of their entity.
+WorldVM.vehicle_types = {Highwind = 3, Chocobo = 4, TinyBronco = 5, Buggy = 6, Submarine = 13}
+
+--- Size of a mesh in the world, in the units of the module (8182 is the size in the fixed point of
+-- the game, and 4096 is 1).
+-- The exits of the fields save the world coordinates in units of 8 (to fit 16 bits). To be checked in game.
+WorldVM.EXIT_SCALE = 8
+WorldVM.MESH_SIZE = 8182 / 4096
+
+--- The position that the script gave to the entity that it is placing.
+WorldVM.current = nil
+
+LoadModel = function(model_type)
+    return 0
+end
+
+SetActiveEntityMeshCoordinates = function(mesh_x, mesh_y)
+    if WorldVM.current then
+        WorldVM.current.mesh_x = mesh_x
+        WorldVM.current.mesh_y = mesh_y
+    end
+    return 0
+end
+
+SetActiveEntityMeshCoordinatesInMesh = function(x, y)
+    if WorldVM.current then
+        WorldVM.current.in_x = x
+        WorldVM.current.in_y = y
+    end
+    return 0
+end
+
+SetActiveEntityDirectionAndFacing = function(direction)
+    if WorldVM.current then WorldVM.current.direction = direction end
+    return 0
+end
+
+--- Runs something that only looks at what a script does, and undoes what it wrote to the variables
+-- (it marks that it showed a window...).
+-- @param action Function to run.
+-- @return What the function returns.
+WorldVM.run_sandboxed = function(action)
+    local journal = {}
+    local previous_journal = System.WorldMap.journal
+    local saved_locals = System.WorldMap.locals
+    local saved_specials = {}
+    for address, value in pairs(System.WorldMap.specials) do saved_specials[address] = value end
+    System.WorldMap.journal = journal
+    System.WorldMap.locals = {}
+    local a, b, c = action()
+    for index = #journal, 1, -1 do
+        local entry = journal[index]
+        entry[1][entry[2]] = entry[3]
+    end
+    System.WorldMap.journal = previous_journal
+    System.WorldMap.locals = saved_locals
+    System.WorldMap.specials = saved_specials
+    return a, b, c
+end
+
+--- Runs the function that creates an entity of a type, and gets where it puts it.
+-- @param model_type Type of the entity.
+-- @return A table with x and z (world units) and direction (0 to 255), nil if the type has no function
+-- or it didn't set a position.
+WorldVM.get_spawn = function(model_type)
+    local functions = System.WorldMap.entity_functions
+    local function_id = functions and functions[model_type] and functions[model_type][0]
+    local script_function = function_id and System.WorldMap["world_function_" .. function_id]
+    if not script_function then return nil end
+    local spawn, ok, message = WorldVM.run_sandboxed(function()
+        WorldVM.current = {}
+        local call_ok, call_message = pcall(script_function, System.WorldMap)
+        local result = WorldVM.current
+        WorldVM.current = nil
+        return result, call_ok, call_message
+    end)
+    if not ok then
+        print("World map entity function of type " .. model_type .. " failed: " .. tostring(message))
+        return nil
+    end
+    if not (spawn.mesh_x and spawn.mesh_y and spawn.in_x and spawn.in_y) then return nil end
+    return {
+        x = spawn.mesh_x * WorldVM.MESH_SIZE + spawn.in_x / 4096,
+        z = spawn.mesh_y * WorldVM.MESH_SIZE + spawn.in_y / 4096,
+        direction = spawn.direction or 0,
+    }
+end
+
+--- Which field a function of a trigger enters (EnterFieldScene), without doing anything else of what it
+-- does: it runs it as something that only looks (it undoes the writes to the variables).
+-- @param script_function The function (world_function_N).
+-- @return The FIELD.TBL record that it enters, nil if it doesn't enter one.
+WorldVM.find_field_entry = function(script_function)
+    local previous = EnterFieldScene
+    local record = nil
+    EnterFieldScene = function(field_table_id)
+        record = record or tonumber(field_table_id)
+        return 0
+    end
+    WorldVM.run_sandboxed(function()
+        pcall(script_function, System.WorldMap)
+    end)
+    EnterFieldScene = previous
+    return record
+end
+
+--- If a vehicle can enter a place (WorldMapSettings.entry).
+-- @param record FIELD.TBL record of the place.
+-- @param vehicle walk, chocobo, buggy, tiny_bronco, highwind or submarine.
+-- @param landing True if the Highwind has just landed.
+-- @return True if it can.
+WorldVM.can_enter = function(record, vehicle, landing)
+    if vehicle == nil or vehicle == "walk" then return true end
+    local entry = WorldMapSettings and WorldMapSettings.entry
+    if not entry then return true end
+    if entry.exempt and entry.exempt[record] then return true end
+    if vehicle == "highwind" then
+        return landing == true and entry.highwind_landing ~= nil and entry.highwind_landing[record] == true
+    end
+    local allowed = entry.allowed and entry.allowed[vehicle]
+    return allowed ~= nil and allowed[record] == true
+end
+
+--- Creates the models that the scripts place in a map.
+-- @param map_id Map of the module (0 WM0, 1 WM2, 2 WM3).
+WorldVM.place_models = function(map_id)
+    local situation = WorldVM.get_situation(map_id)
+    local set = situation and WorldMapModels.situations[situation]
+    if not set then return end
+    WorldVM.apply_debug_variables()
+    for model_type, hrc in pairs(set) do
+        local model = WorldMapModels.models[hrc]
+        local exists = WorldVM.loaded_types == nil or WorldVM.loaded_types[model_type]
+        if exists and WorldVM.static_types[model_type] and model then
+            local spawn = WorldVM.get_spawn(model_type)
+            if spawn then
+                local rotation = model.rotation or {0, 0, 0}
+                world_map_module:add_world_model(
+                    model.name .. "_" .. model_type, hrc, spawn.x, spawn.z, model.scale, spawn.direction,
+                    rotation[1], rotation[2], rotation[3]
+                )
+                -- The model plays its default animation (model.animation, the first one if it
+                -- is not set: the scenery has a single static one). The others are for events.
+                local entity_name = "WorldMap" .. model.name .. "_" .. model_type
+                if model.altitude then world_map_module:set_entity_altitude(entity_name, model.altitude) end
+                local entity = entity_manager:get_entity(entity_name)
+                if entity ~= nil and entity:get_animation_count() > 0 then
+                    entity:set_default_animation_index(model.animation or 0)
+                    entity:play_animation_index(model.animation or 0)
+                end
+            end
+        end
+    end
+end
+
+--- The types of entities that the init function of the map (function 1) creates with LoadModel,
+-- for the story and the flags that there are. For WM0 it also gives where the player appears when the
+-- world is entered from a field (SetActiveEntity... of that function).
+-- @return A table with the types as keys, and the position of the player (as get_spawn) or nil.
+WorldVM.scan_init = function()
+    local init = System.WorldMap.world_function_1
+    local types = {}
+    if not init then return nil end
+    local previous_load_model = LoadModel
+    LoadModel = function(model_type)
+        types[model_type] = true
+        return 0
+    end
+    local player, ok, message = WorldVM.run_sandboxed(function()
+        WorldVM.current = {}
+        local call_ok, call_message = pcall(init, System.WorldMap)
+        local result = WorldVM.current
+        WorldVM.current = nil
+        return result, call_ok, call_message
+    end)
+    LoadModel = previous_load_model
+    if not ok then
+        print("World map init function failed: " .. tostring(message))
+        return nil
+    end
+    local position = nil
+    if player.mesh_x and player.mesh_y and player.in_x and player.in_y then
+        position = {
+            x = player.mesh_x * WorldVM.MESH_SIZE + player.in_x / 4096,
+            z = player.mesh_y * WorldVM.MESH_SIZE + player.in_y / 4096,
+        }
+    end
+    return types, position
+end
+
+--- The position that a field exit gives in the world map.
+-- The exit saves x, y (world units of the exit, 16 bits) by the name of its spawn point.
+-- @param name Spawn point name given by the field.
+-- @return {x, z} in the units of the module, or nil.
+WorldVM.arrival_point = function(name)
+    if not name or name == "" then return nil end
+    if WorldVM.arrivals == nil then
+        local chunk = loadfile("./data/scripts/worldmap/world_arrivals.lua")
+        WorldArrivals = nil
+        if chunk then pcall(chunk) end
+        WorldVM.arrivals = WorldArrivals or false
+    end
+    local exit = WorldVM.arrivals and WorldVM.arrivals[name]
+    -- The exits to the world have 0, 0 (all of the ones of the game): the position is in the scripts.
+    if not exit or (exit.x == 0 and exit.y == 0) then return nil end
+    return {x = exit.x * WorldVM.EXIT_SCALE / 4096, z = exit.y * WorldVM.EXIT_SCALE / 4096}
+end
+
+--- Prepares a map before its entities are created: gives the scripts how the world was entered, finds out
+-- which entities exist for the story and the flags, and sets where they start.
+--
+-- The way in is the FIELD.TBL record of the field exit that was used (System.WorldMap.arrival, or
+-- WorldMapDebug.arrival to test), 0 if the world wasn't entered from a field. The vehicles that the
+-- story hasn't given are hidden, except the ones that the debug data has a spawn for (WorldMapDebug.spawn),
+-- which also keep that position. The other ones are where their scripts put them, or at the default of
+-- the module if the script doesn't say (their last position is not saved yet).
+-- @param map_id Map of the module (0 WM0, 1 WM2, 2 WM3).
+WorldVM.prepare = function(map_id)
+    WorldVM.apply_debug_variables()
+    -- The speeds of walking and of each vehicle (world_settings.lua).
+    if WorldMapSettings and WorldMapSettings.speed then
+        for name, speed in pairs(WorldMapSettings.speed) do world_map_module:set_speed(name, speed) end
+    end
+    -- The distance and the angle of the camera for walking and for each vehicle.
+    if WorldMapSettings and WorldMapSettings.camera then
+        for name, camera in pairs(WorldMapSettings.camera) do
+            world_map_module:set_camera(name, camera.distance, camera.pitch)
+        end
+    end
+    System.WorldMap.specials = {}
+    -- 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
+    System.WorldMap.arrival = nil
+    System.WorldMap.specials[5] = 0
+    System.WorldMap.specials[6] = arrival
+    local types, player = WorldVM.scan_init()
+    WorldVM.loaded_types = types
+    -- The field exit gives the coordinates itself (installer: world_arrivals.lua), they are what counts.
+    local point = real_arrival and WorldVM.arrival_point(System.WorldMap.arrival_name)
+    System.WorldMap.arrival_name = nil
+    if point then
+        print("World map arrival: the exit gives " .. point.x .. ", " .. point.z
+            .. (player and (" (the scripts of the record say " .. player.x .. ", " .. player.z .. ")") or ""))
+        player = point
+    elseif arrival ~= 0 then
+        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"))
+    end
+    if map_id ~= 0 then return end
+    local debug_spawn = WorldMapDebug and WorldMapDebug.spawn or {}
+    for name, model_type in pairs(WorldVM.vehicle_types) do
+        local forced = debug_spawn[name] ~= nil
+        if types and not types[model_type] and not forced then
+            world_map_module:set_vehicle_hidden(name)
+        elseif not forced or real_arrival then
+            local spawn = WorldVM.get_spawn(model_type)
+            if spawn then world_map_module:set_spawn(name, spawn.x, spawn.z) end
+        end
+    end
+    if arrival ~= 0 and player and (debug_spawn.Cloud == nil or real_arrival) then
+        world_map_module:set_spawn("Cloud", player.x, player.z)
+    end
+end

+ 2 - 0
data/data/texts/english/menu.xml

@@ -26,6 +26,8 @@
     <text name="BeginMenu2"><colour value="0.5 0.5 0.5">DEBUG: Quick map</colour></text>
     <text name="BeginMenu3"><colour value="0.5 0.5 0.5">DEBUG: Entity testarea</colour></text>
     <text name="BeginMenu4"><colour value="0.5 0.5 0.5">DEBUG: World map test</colour></text>
+    <text name="BeginMenuWorld1"><colour value="0.5 0.5 0.5">DEBUG: World map 1 (WM2)</colour></text>
+    <text name="BeginMenuWorld2"><colour value="0.5 0.5 0.5">DEBUG: World map 2 (WM3)</colour></text>
     <text name="BeginMenu5"><colour value="0.5 0.5 0.5">DEBUG: Debug Room</colour></text>
     <text name="BeginMenu6"><colour value="0.5 0.5 0.5">DEBUG: Test Battle</colour></text>
 

+ 48 - 0
doc/CHANGELOG.md

@@ -1,5 +1,53 @@
 # Changelog
 
+## 0.3.5
+
+Changes since 0.3.4. Most of the work is in the world map module, which now runs the original world scripts, and in the field module and its installer.
+
+### World map
+
+**Story and scripts**
+- The world script decompiler handles more opcodes (0x11d, 0x31b, 0x33c, 0x355, 0x01b), and fixes `Write(Read(N), v)` stores and address collisions between local, byte, word and bit banks. The scripts of the animated world models now decompile correctly.
+- The world memory shares the field memory banks, so the story counter and the vehicle flags set by the field scripts are visible to the world scripts.
+- The world situation (Midgar era, cannon destroyed, Ultimate Weapon killed...) is chosen from the story and flags instead of a debug value.
+- Vehicles the story has not given yet are hidden; the positions in the scripts are used as spawns.
+- Scenery models are placed from the world scripts. New bindings `get_animation_name`, `play_animation_index` and `set_default_animation_index`.
+- Entering from a field: the world script selects the map and the player spawn; the player appears at the exit point set by the field script. `vehicles.lua` is reloaded on entering the world and on returning from a field.
+- The installer writes the world map exit locations.
+
+**Settings**
+- New `world_settings.lua`: speed and camera (distance and pitch) per vehicle, walking speed, music tracks and overrides, and town entry rules.
+- Music depends on the vehicle and on the story progress.
+- Towns can only be entered under the conditions of each vehicle.
+
+**Visuals and mechanics**
+- Animated water textures in WM0.
+- Fog in WM2, and WM2/WM3 texture mapping fixed with the texture table.
+- WM3: snow overlay, camera behaviour and poles.
+- Cliff terrain can't be walked on foot.
+- Faster search of the triangle under a position (spatial grid).
+
+### Field
+
+**Decompiler and installer**
+- Entities without a model (Director, AD, MES) are handled, so the model opcodes are harmless on them; names that aren't valid Lua identifiers are skipped.
+- `LSTMP` fixed: the previous field id is stored from each script header, and a destination in bank 0 is guarded.
+- Scripts that fall through into the next one now call it explicitly.
+- New opcodes `PREQ`, `PRQSW`, `PRQEW` (`party_request`) and `CKITM` (key item check).
+- The Director uses the entity named "cloud" for `place_player_at_map_entry` and autoscroll.
+- Text colour tags left open at the end of a dialog are closed.
+
+**Engine**
+- Background palettes (`BackgroundPalette`): the palette opcodes repaint the tiles of the animated palettes (for example waterfalls).
+- Background scrolling: scripted scrolls are not clamped, scrolls that follow an entity are clamped to the range.
+- Changing the player entity moves the autoscroll to the new player and copies the position of the previous one if the new one has none.
+- Single-frame animations are held, and a running offset is cancelled by `AT_NONE`.
+- Additive screen fade (type 6) fixed.
+- Timer dialog windows: rendering and padding.
+- Movies without a sound file are skipped quietly. `play_sounds` takes optional arguments.
+- `field.lua`: `party_request` helper; fixed the map change race that erased a request made in the first frame of a field.
+- `system.lua`: `NullEntity`; `Timer` updates the dialog.
+
 ## 0.3.4
 
 Changes since 0.3.2. Most of the work is in the battle module, which now uses data extracted from the original game for cameras, effects and rules.

+ 2 - 0
doc/INSTALL_DATA.md

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

+ 69 - 0
doc/TODO.md

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

+ 1 - 0
src/CMakeLists.txt

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

+ 3 - 3
src/Version.h

@@ -22,8 +22,8 @@
 /**
  * Application version.
  */
-#define VGEARS_VERSION "0.3.4"
+#define VGEARS_VERSION "0.3.5"
 #define VGEARS_VERSION_MAJOR "0"
 #define VGEARS_VERSION_MINOR "3"
-#define VGEARS_VERSION_PATCH "2"
-#define VGEARS_VERSION_SIGNATURE "V-Gears v0.3.4"
+#define VGEARS_VERSION_PATCH "5"
+#define VGEARS_VERSION_SIGNATURE "V-Gears v0.3.5"

+ 5 - 0
src/common/VGearsApplication.h

@@ -79,6 +79,11 @@ namespace VGears{
              */
             Ogre::RenderWindow* getRenderWindow(void);
 
+            /**
+             * The overlay system (it must be added to a scene manager as a render queue listener to draw overlays).
+             */
+            Ogre::OverlaySystem* GetOverlaySystem(){return _overlay_system.get();}
+
             /**
              * Retrieves the Ogre resources file name.
              *

+ 17 - 0
src/core/AudioManager.cpp

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

+ 16 - 0
src/core/AudioManager.h

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

+ 95 - 5
src/core/Background2D.cpp

@@ -19,6 +19,8 @@
 #include <OgreException.h>
 #include <OgreViewport.h>
 #include <OgreTechnique.h>
+#include <OgreTextureManager.h>
+#include <OgreHardwarePixelBuffer.h>
 #include <algorithm>
 #include "core/Background2D.h"
 #include "core/CameraManager.h"
@@ -44,6 +46,7 @@ Background2D::Background2D():
   scroll_current_seconds_(0),
   scroll_target_entity_(nullptr),
   scroll_follow_target_(false),
+  free_scroll_(false),
   position_(Ogre::Vector2::ZERO),
   position_real_(Ogre::Vector2::ZERO),
   offset_(Ogre::Vector2::ZERO),
@@ -74,6 +77,10 @@ Background2D::Background2D():
     pass->setDepthCheckEnabled(true);
     pass->setDepthWriteEnabled(true);
     pass->setLightingEnabled(false);
+    // Additive tiles blend with what is behind. They don't write depth, or a tile in front (such as
+    // the light beams, at depth 0) would hide the additive tiles behind it, like the waterfall of
+    // eals_1.
+    pass->setDepthWriteEnabled(false);
     pass->setSceneBlending(Ogre::SBT_ADD);
     pass->setAlphaRejectFunction(Ogre::CMPF_GREATER);
     pass->setAlphaRejectValue(0);
@@ -91,6 +98,8 @@ Background2D::Background2D():
     pass->setDepthWriteEnabled(true);
     pass->setLightingEnabled(false);
     pass->setSceneBlending(Ogre::SBT_ADD);
+    // Like the additive tiles, they don't write depth.
+    pass->setDepthWriteEnabled(false);
     pass->setSceneBlendingOperation(Ogre::SBO_SUBTRACT);
     pass->setAlphaRejectFunction(Ogre::CMPF_LESS);
     pass->setAlphaRejectValue(0);
@@ -126,6 +135,7 @@ void Background2D::Update(){
         has_pending_scroll_ = false;
         SetScroll(pending_scroll_);
     }
+    UpdatePalette();
     UpdateShake(Timer::getSingleton().GetGameTimeDelta());
     // The layers that scroll by themselves.
     for (int layer = 0; layer < LAYER_COUNT; ++ layer){
@@ -402,6 +412,64 @@ void Background2D::ScriptAreaClear(const int area){
     RefreshArea(area);
 }
 
+void Background2D::SetPalette(const Ogre::String& name){
+    if (palette_.Load(name)){
+        palette_image_loaded_ = false;
+        Ogre::LogManager::getSingleton().stream() << "Background2D: palette file loaded " << name;
+    }
+}
+
+void Background2D::ScriptPaletteStore(int page, int slot, int count){
+    palette_.Store(page, slot, count);
+}
+
+void Background2D::ScriptPaletteLoad(int slot, int page, int count){
+    palette_.Load(slot, page, count);
+}
+
+void Background2D::ScriptPaletteCopy(int source, int destination, int count){
+    palette_.Copy(source, destination, count);
+}
+
+void Background2D::ScriptPaletteMultiply(
+  int source, int destination, int start, int count, int red, int green, int blue
+){
+    palette_.Multiply(source, destination, start, count, red, green, blue);
+}
+
+void Background2D::ScriptPaletteAdd(
+  int source, int destination, int red, int green, int blue, int count
+){
+    palette_.Add(source, destination, red, green, blue, count);
+}
+
+void Background2D::UpdatePalette(){
+    if (palette_.IsEmpty() || image_name_.empty()) return;
+    if (!palette_image_loaded_){
+        try{
+            palette_image_.load(
+              image_name_, Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME
+            );
+        }
+        catch (const Ogre::Exception& e){
+            LOG_ERROR("Background palette: can't load image '" + image_name_ + "': " + e.what());
+            palette_.Clear();
+            return;
+        }
+        palette_image_loaded_ = true;
+    }
+    if (!palette_.Paint(palette_image_)) return;
+    Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(image_name_);
+    if (!texture){
+        texture = Ogre::TextureManager::getSingleton().load(
+          image_name_, Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME
+        );
+    }
+    if (texture){
+        texture->getBuffer()->blitFromMemory(palette_image_.getPixelBox());
+    }
+}
+
 void Background2D::Clear(){
     scroll_entity_ = nullptr;
     scroll_position_start_ = Ogre::Vector2::ZERO;
@@ -410,6 +478,7 @@ void Background2D::Clear(){
     scroll_current_seconds_ = 0;
     scroll_target_entity_ = nullptr;
     scroll_follow_target_ = false;
+    free_scroll_ = false;
     has_pending_scroll_ = false;
     position_ = Ogre::Vector2::ZERO;
     position_real_ = Ogre::Vector2::ZERO;
@@ -424,6 +493,8 @@ void Background2D::Clear(){
     animation_played_.clear();
     tiles_.clear();
     area_states_on_.clear();
+    palette_.Clear();
+    palette_image_loaded_ = false;
     shake_x_ = ShakeAxis();
     shake_y_ = ShakeAxis();
     shake_offset_ = Ogre::Vector2::ZERO;
@@ -431,7 +502,10 @@ void Background2D::Clear(){
     CreateVertexBuffers();
 }
 
-void Background2D::ScriptAutoScrollToEntity(Entity* entity){scroll_entity_ = entity;}
+void Background2D::ScriptAutoScrollToEntity(Entity* entity){
+    scroll_entity_ = entity;
+    free_scroll_ = false;
+}
 
 Entity* Background2D::GetAutoScrollEntity() const{return scroll_entity_;}
 
@@ -439,7 +513,10 @@ void Background2D::ScriptScrollToPlayer(const SCROLL_TYPE type, const float seco
     Entity* player = EntityManager::getSingleton().ScriptGetPlayerEntity();
     if (player == nullptr) return;
     scroll_entity_ = nullptr;
-    StartScroll(GetEntityScroll(player), type, seconds, player, type == Background2D::NONE);
+    // The camera follows the player when the scroll ends, whatever the transition: scenes end with
+    // SCRLC (scroll to the player) and give the control back without any other camera opcode, as
+    // the first visit of mrkt2 does.
+    StartScroll(GetEntityScroll(player), type, seconds, player, true);
 }
 
 void Background2D::ScriptScrollToEntity(
@@ -455,7 +532,7 @@ void Background2D::ScriptScrollToEntity(
 
 void Background2D::UpdateScrollTarget(){
     if (scroll_target_entity_ != nullptr)
-        scroll_position_end_ = ClampScroll(GetEntityScroll(scroll_target_entity_));
+        scroll_position_end_ = ClampToRange(GetEntityScroll(scroll_target_entity_));
 }
 
 const Ogre::Vector2 Background2D::GetEntityScroll(const Entity* entity) const{
@@ -483,12 +560,14 @@ void Background2D::StartScroll(
     scroll_target_entity_ = target_entity;
     scroll_follow_target_ = follow_target;
     if (type == Background2D::NONE || seconds <= 0){
+        // The camera that goes to an entity is limited to the background.
+        if (target_entity != nullptr) free_scroll_ = false;
         SetScroll(position);
         UnsetScroll();
         return;
     }
     scroll_position_start_ = position_;
-    scroll_position_end_ = ClampScroll(position);
+    scroll_position_end_ = (target_entity != nullptr) ? ClampToRange(position) : ClampScroll(position);
     scroll_type_ = type;
     scroll_seconds_ = seconds;
     scroll_current_seconds_ = 0;
@@ -502,6 +581,7 @@ void Background2D::ScriptScrollToPosition(
       + Ogre::StringConverter::toString(Ogre::Vector2(x, y)) + "'."
     );
     scroll_entity_ = nullptr;
+    free_scroll_ = true;
     if (type == Background2D::NONE || seconds <= 0){
         // The scripts set a position and then scroll from it to another one, in the same frame.
         // The camera is only moved at the end of the frame, so if another scroll comes first the
@@ -544,7 +624,10 @@ void Background2D::ScriptOffset(const float x, const float y){
 
 void Background2D::UnsetScroll(){
     scroll_type_ = Background2D::NONE;
-    if (scroll_follow_target_) scroll_entity_ = scroll_target_entity_;
+    if (scroll_follow_target_){
+        scroll_entity_ = scroll_target_entity_;
+        free_scroll_ = false;
+    }
     scroll_target_entity_ = nullptr;
     scroll_follow_target_ = false;
     for(unsigned int i = 0; i < scroll_sync_.size(); ++ i)
@@ -574,6 +657,10 @@ void Background2D::SetScroll(const Ogre::Vector2& position){
 }
 
 const Ogre::Vector2 Background2D::ClampScroll(const Ogre::Vector2& position) const{
+    return free_scroll_ ? position : ClampToRange(position);
+}
+
+const Ogre::Vector2 Background2D::ClampToRange(const Ogre::Vector2& position) const{
     Ogre::Vector2 clamped = position;
     Ogre::Vector3 pos_3d(position.x, position.y, 0);
     if (!range_.contains(pos_3d)){
@@ -602,6 +689,8 @@ const Ogre::Vector2 Background2D::GetScreenScroll() const{return GetScroll() * s
 
 void Background2D::SetImage(const Ogre::String& image){
     Ogre::LogManager::getSingleton().stream() << "Background2D::SetImage " << image;
+    image_name_ = image;
+    palette_image_loaded_ = false;
     Ogre::Pass* pass = alpha_material_->getTechnique(0)->getPass(0);
     Ogre::TextureUnitState* tex = pass->getTextureUnitState(0);
     tex->setTextureName(image);
@@ -1096,6 +1185,7 @@ void Background2D::load(const VGears::Background2DFilePtr& background){
     assert(background != nullptr);
     background->load();
     SetImage(background->GetTextureName());
+    if (!background->GetPaletteName().empty()) SetPalette(background->GetPaletteName());
     virtual_screen_size_ = background->GetClip();
     SetRange(background->GetRange());
     const Ogre::Vector3& position(background->GetPosition());

+ 59 - 0
src/core/Background2D.h

@@ -22,6 +22,7 @@
 #include <OgreRoot.h>
 #include "map/VGearsBackground2DFile.h"
 #include "Background2DAnimation.h"
+#include "BackgroundPalette.h"
 #include "Entity.h"
 #include "ScriptManager.h"
 
@@ -347,6 +348,26 @@ class Background2D : public Ogre::RenderQueueListener{
          */
         void SetImage( const Ogre::String& image );
 
+        /**
+         * Loads the palettes of the image, if a script animates them.
+         *
+         * @param[in] name Resource name of the palette file (palette.bin of the field).
+         */
+        void SetPalette(const Ogre::String& name);
+
+        /**
+         * Palette opcodes of the scripts, see BackgroundPalette.
+         */
+        void ScriptPaletteStore(int page, int slot, int count);
+        void ScriptPaletteLoad(int slot, int page, int count);
+        void ScriptPaletteCopy(int source, int destination, int count);
+        void ScriptPaletteMultiply(
+          int source, int destination, int start, int count, int red, int green, int blue
+        );
+        void ScriptPaletteAdd(
+          int source, int destination, int red, int green, int blue, int count
+        );
+
         /**
          * Set the background scrolling range.
          *
@@ -722,6 +743,11 @@ class Background2D : public Ogre::RenderQueueListener{
          */
         const Ogre::Vector2 ClampScroll(const Ogre::Vector2& position) const;
 
+        /**
+         * Limits a scroll position to the background range, always.
+         */
+        const Ogre::Vector2 ClampToRange(const Ogre::Vector2& position) const;
+
         /**
          * Calculates the screen scale.
          *
@@ -789,6 +815,31 @@ class Background2D : public Ogre::RenderQueueListener{
          */
         std::map<int, unsigned int> area_states_on_;
 
+        /**
+         * Painting again of the tiles of the palettes the scripts animate.
+         */
+        void UpdatePalette();
+
+        /**
+         * The palettes the scripts animate.
+         */
+        BackgroundPalette palette_;
+
+        /**
+         * Name of the image of the background.
+         */
+        Ogre::String image_name_;
+
+        /**
+         * A copy of the image of the background, where the animated tiles are painted.
+         */
+        Ogre::Image palette_image_;
+
+        /**
+         * True if palette_image_ has the image.
+         */
+        bool palette_image_loaded_ = false;
+
         /**
          * The shake of the view in the X axis.
          */
@@ -974,6 +1025,14 @@ class Background2D : public Ogre::RenderQueueListener{
          */
         bool scroll_follow_target_;
 
+        /**
+         * True while a script has moved the camera to a position. The original game doesn't limit
+         * those scrolls to the background, so a scene can show the empty space around it (the
+         * models of ealin_12 are moved there while the camera is away). The camera that follows
+         * an entity is always limited.
+         */
+        bool free_scroll_;
+
         /**
          * Position of an instant scroll that waits for the end of the frame.
          *

+ 247 - 0
src/core/BackgroundPalette.cpp

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

+ 167 - 0
src/core/BackgroundPalette.h

@@ -0,0 +1,167 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+
+#pragma once
+
+#include <cstdint>
+#include <vector>
+#include <OgreImage.h>
+#include <OgreString.h>
+#include <OgreTexture.h>
+
+/**
+ * Palette animations of a 2D background.
+ *
+ * The backgrounds of the original game use 8 bit tiles with palettes, and the scripts change the
+ * palettes while the field runs (waterfalls, lights, fades). The tiles of the image of a field are
+ * already painted with their palette, so for the palettes a script changes the installer saves the
+ * palettes and the indexes of the tiles (palette.bin), and this class paints them again when the
+ * script changes a palette.
+ *
+ * The scripts work like in the original game: an array of palettes in memory (the "slots", 16
+ * colors each) and the palettes of the background (the "pages"). Colors are the 16 bit values of
+ * the original game: 5 bits per channel (red in the lowest bits) and the flag 0x8000.
+ */
+class BackgroundPalette{
+    public:
+
+        /**
+         * Loads the palette data of a field.
+         *
+         * @param[in] name Resource name of the palette file.
+         * @return True if it was loaded.
+         */
+        bool Load(const Ogre::String& name);
+
+        /**
+         * Removes all data.
+         */
+        void Clear();
+
+        /**
+         * Checks if there is palette data.
+         */
+        bool IsEmpty() const;
+
+        /**
+         * Stores colors of a page in the array of palettes (STPAL).
+         */
+        void Store(int page, int slot, int count);
+
+        /**
+         * Loads colors of a page from the array of palettes (LDPAL).
+         */
+        void Load(int slot, int page, int count);
+
+        /**
+         * Copies colors inside the array of palettes (CPPAL).
+         */
+        void Copy(int source, int destination, int count);
+
+        /**
+         * Multiplies the channels of colors in the array of palettes (MPPAL, MPPAL2). 64 is 1.0.
+         */
+        void Multiply(
+          int source, int destination, int start, int count, int red, int green, int blue
+        );
+
+        /**
+         * Adds signed values to the channels of colors in the array of palettes (ADPAL).
+         */
+        void Add(int source, int destination, int red, int green, int blue, int count);
+
+        /**
+         * Paints the tiles of the pages that changed in the image.
+         *
+         * @param[in,out] image The image of the whole background, which is changed.
+         * @return True if the image changed.
+         */
+        bool Paint(Ogre::Image& image);
+
+        /**
+         * The color of a palette entry as it is shown, like the installer does it.
+         *
+         * @param[in] color Color of the original game (5 bits per channel and the flag 0x8000).
+         * @param[in] first Color 0 of the same page, used for the empty colors.
+         * @param[in] index Index of the color in the page.
+         * @param[in] first_hidden True if the first color of the page is transparent.
+         * @param[out] rgba The 4 bytes to write: red, green, blue, alpha.
+         */
+        static void ToRgba(
+          uint16_t color, uint16_t first, int index, bool first_hidden, uint8_t* rgba
+        );
+
+        /**
+         * Checks if the first color of a page is a bright marker color, whose empty entries are
+         * hidden (see ToRgba).
+         */
+        static bool IsBrightFirstColor(uint16_t first);
+
+        /**
+         * Multiplies a color (see Multiply).
+         */
+        static uint16_t MultiplyColor(uint16_t color, int red, int green, int blue);
+
+        /**
+         * Adds a value to the channels of a color (see Add).
+         */
+        static uint16_t AddToColor(uint16_t color, int red, int green, int blue);
+
+    private:
+
+        /**
+         * A tile that has to be painted again when its page changes.
+         */
+        struct Tile{
+            uint16_t x;
+            uint16_t y;
+            uint16_t width;
+            uint16_t height;
+            uint16_t page;
+            bool first_hidden;
+            std::vector<uint8_t> indexes;
+        };
+
+        /**
+         * Number of colors that a slot of the array has.
+         */
+        static const int SLOT_COLORS = 16;
+
+        /**
+         * Size of the array of palettes, in colors (256 slots).
+         */
+        static const int ARRAY_SIZE = 256 * SLOT_COLORS;
+
+        /**
+         * The palette pages.
+         */
+        std::vector<std::vector<uint16_t>> pages_;
+
+        /**
+         * The array of palettes.
+         */
+        std::vector<uint16_t> array_ = std::vector<uint16_t>(ARRAY_SIZE, 0);
+
+        /**
+         * The tiles.
+         */
+        std::vector<Tile> tiles_;
+
+        /**
+         * The pages that changed since the last call to Paint.
+         */
+        std::vector<bool> dirty_;
+};

+ 4 - 2
src/core/DebugDraw.cpp

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

+ 15 - 0
src/core/DebugDraw.h

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

+ 27 - 11
src/core/DialogsManager.cpp

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

+ 3 - 0
src/core/DialogsManager.h

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

+ 33 - 7
src/core/Entity.cpp

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

+ 47 - 0
src/core/Entity.h

@@ -15,6 +15,8 @@
 
 #pragma once
 
+#include <algorithm>
+#include <cmath>
 #include <tuple>
 #include <OgreString.h>
 #include "EntityCollision.h"
@@ -99,6 +101,21 @@ enum LinearMovement{
 /**
  * Any entity in a field.
  */
+/**
+ * Arc cosine of a ratio, in radians, that never gives NaN.
+ *
+ * The cosine of the angle between two vectors can end up a bit over 1 or under -1 because of float
+ * rounding (for example when moving exactly along an axis), and acosf gives NaN then. A NaN
+ * rotation breaks the bounding box of the entity and Ogre asserts. A zero length vector gives 0.
+ *
+ * @param[in] dot The dot product of the vectors.
+ * @param[in] length_product The product of the lengths of the vectors.
+ */
+inline float SafeAcos(const float dot, const float length_product){
+    if (!(length_product > 0.0f)) return 0.0f;
+    return std::acos(std::max(-1.0f, std::min(1.0f, dot / length_product)));
+}
+
 class Entity{
 
     public:
@@ -549,6 +566,28 @@ class Entity{
          */
         virtual unsigned int GetAnimationCount() const;
 
+        /**
+         * Gets the name of an animation by its position, in the order they were added to the model.
+         *
+         * @param[in] index Position of the animation, starting at 0.
+         * @return The name, empty if there is no such animation.
+         */
+        virtual Ogre::String GetAnimationName(const unsigned int index) const;
+
+        /**
+         * Plays, looped, the animation at a position (see GetAnimationName).
+         *
+         * @param[in] index Position of the animation, starting at 0.
+         */
+        void ScriptPlayAnimationIndex(const unsigned int index);
+
+        /**
+         * Sets the default animation to the one at a position (see GetAnimationName).
+         *
+         * @param[in] index Position of the animation, starting at 0.
+         */
+        void ScriptSetDefaultAnimationIndex(const unsigned int index);
+
         /**
          * Retrieves the duration of an animation.
          *
@@ -1546,6 +1585,14 @@ class Entity{
          */
         float animation_end_time_;
 
+        /**
+         * Seconds left that the animation has to wait before it can end. A range of one frame
+         * (start and end equal) lasts a frame of the original game (1/30 s), not an update of the
+         * engine, so the scripts that play an animation frame by frame are not faster at a high
+         * frame rate.
+         */
+        float animation_hold_ = 0.0f;
+
         /**
          * Indicates if an automation must be played automatically.
          */

+ 77 - 8
src/core/EntityManager.cpp

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

+ 35 - 0
src/core/EntityManager.h

@@ -140,6 +140,15 @@ class EntityManager : public Manager, public Ogre::Singleton<EntityManager>{
          */
         void RemoveBattleEntity(const Ogre::String& name);
 
+        /**
+         * Removes a world map entity (like a pole that was added while playing).
+         *
+         * If the manager is not in the world module, or the entity doesn't exist, it will do nothing.
+         *
+         * @param[in] name Entity name.
+         */
+        void RemoveWorldMapEntity(const Ogre::String& name);
+
         /**
          * Clears all world map information in the entity manager.
          *
@@ -387,6 +396,27 @@ class EntityManager : public Manager, public Ogre::Singleton<EntityManager>{
          */
         void ScriptPlayerLock(const bool lock);
 
+        /**
+         * Sets if the player can slide along the walls (SLIP in the field scripts).
+         *
+         * When it is off, a move of the player that is blocked by a wall is not turned into a
+         * move along the wall. It is on by default and when a field is loaded.
+         *
+         * @param[in] slip True to let the player slide.
+         */
+        void ScriptSetPlayerSlip(const bool slip);
+
+        /**
+         * Retrieves the height of a point of a walkmesh triangle.
+         *
+         * @param[in] triangle The triangle.
+         * @param[in] x X coordinate of the point.
+         * @param[in] y Y coordinate of the point.
+         * @param[in] fallback Value returned if there is no such triangle.
+         * @return The height of the triangle at the point.
+         */
+        float GetTriangleHeight(int triangle, float x, float y, float fallback) const;
+
         /**
          * Sets if the player moves running by default.
          *
@@ -854,6 +884,11 @@ class EntityManager : public Manager, public Ogre::Singleton<EntityManager>{
          */
         bool player_lock_;
 
+        /**
+         * Indicates if the player slides along the walls (see ScriptSetPlayerSlip).
+         */
+        bool player_slip_ = true;
+
         /**
          * Indicates if the playable is being moved by running.
          *

+ 38 - 0
src/core/EntityModel.cpp

@@ -89,6 +89,12 @@ unsigned int EntityModel::GetAnimationCount() const{
     return states->getAnimationStates().size();
 }
 
+Ogre::String EntityModel::GetAnimationName(const unsigned int index) const{
+    Ogre::SkeletonInstance* skeleton = model_->getSkeleton();
+    if (skeleton == nullptr || index >= skeleton->getNumAnimations()) return "";
+    return skeleton->getAnimation(index)->getName();
+}
+
 Ogre::Entity* EntityModel::GetModel(){return model_;}
 
 Ogre::MaterialPtr EntityModel::OwnMaterial(Ogre::SubEntity* sub_entity){
@@ -306,6 +312,7 @@ void EntityModel::PlayAnimation(
           (start == -1) ? animation_current_->getLength() : start
         );
         animation_end_time_ = (end == -1) ? animation_current_->getLength() : end;
+        animation_hold_ = (start != -1 && start == end) ? 1.0f / 30.0f : 0.0f;
         animation_state_ = state;
         animation_play_type_ = play_type;
     }
@@ -336,8 +343,39 @@ void EntityModel::PlayAnimationContinue(const Ogre::String& animation){
     }
 }
 
+void EntityModel::StopAnimation(){
+    if (animation_current_ != nullptr){
+        animation_current_->setEnabled(false);
+        animation_current_ = nullptr;
+    }
+    animation_current_name_.clear();
+}
+
+void EntityModel::PlayAnimationPaused(const Ogre::String& animation){
+    if (!HasAnimation(animation)) return;
+    if (animation_frozen_ && animation_current_name_ == animation) return;
+    PlayAnimation(animation, Entity::AUTO_ANIMATION, Entity::PLAY_LOOPED, 0, -1);
+    animation_speed_ = 0.0f;
+    animation_frozen_ = true;
+}
+
+void EntityModel::UnfreezeAnimation(){
+    if (!animation_frozen_) return;
+    animation_speed_ = 1.0f;
+    animation_frozen_ = false;
+}
+
+bool EntityModel::HasAnimation(const Ogre::String& animation) const{
+    return model_->getAllAnimationStates() != nullptr
+      && model_->getAllAnimationStates()->hasAnimationState(animation);
+}
+
 void EntityModel::UpdateAnimation(const float delta){
     if (animation_current_ != nullptr){
+        if (animation_hold_ > 0.0f){
+            animation_hold_ -= delta;
+            if (animation_hold_ > 0.0f) return;
+        }
         float delta_mod = delta * animation_speed_;
         bool stop_check
           = (animation_current_->hasEnded() == true)

+ 30 - 0
src/core/EntityModel.h

@@ -63,6 +63,7 @@ class EntityModel : public Entity{
         virtual float GetAnimationLength(const Ogre::String& animation) const;
 
         virtual unsigned int GetAnimationCount() const;
+        virtual Ogre::String GetAnimationName(const unsigned int index) const;
 
         Ogre::Entity* GetModel();
 
@@ -101,6 +102,32 @@ class EntityModel : public Entity{
          */
         virtual void PlayAnimationContinue(const Ogre::String& animation);
 
+        /**
+         * Stops the animation that is playing, and leaves the model in its bind pose.
+         */
+        void StopAnimation();
+
+        /**
+         * Shows the first frame of an animation and keeps it still. Calling it again with the same
+         * animation does nothing. {@see UnfreezeAnimation()} makes it play.
+         *
+         * @param[in] animation The name of the animation.
+         */
+        void PlayAnimationPaused(const Ogre::String& animation);
+
+        /**
+         * Makes an animation that was paused with {@see PlayAnimationPaused()} play again.
+         */
+        void UnfreezeAnimation();
+
+        /**
+         * Gets if the model has an animation.
+         *
+         * @param[in] animation The name of the animation.
+         * @return True if it has it.
+         */
+        bool HasAnimation(const Ogre::String& animation) const;
+
         /**
          * Updates the animation.
          *
@@ -141,6 +168,9 @@ class EntityModel : public Entity{
          */
         Ogre::AnimationState* animation_current_;
 
+        /// True while {@see PlayAnimationPaused()} keeps the animation still.
+        bool animation_frozen_ = false;
+
         /**
          * Blend mode of the model, one of {@see Entity::EffectBlend}.
          */

+ 4 - 1
src/core/ScreenFadeState.cpp

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

+ 17 - 1
src/core/ScriptManager.cpp

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

+ 35 - 4
src/core/ScriptManagerBinds.h

@@ -174,7 +174,10 @@ void ScriptManager::InitBinds(){
       ),
       "get_animation_length", &Entity::ScriptGetAnimationLength,
       "get_animation_count", &Entity::GetAnimationCount,
-      "set_default_animation", &Entity::ScriptSetDefaultAnimation
+      "get_animation_name", &Entity::GetAnimationName,
+      "play_animation_index", &Entity::ScriptPlayAnimationIndex,
+      "set_default_animation", &Entity::ScriptSetDefaultAnimation,
+      "set_default_animation_index", &Entity::ScriptSetDefaultAnimationIndex
     );
     sol::table entity_type = lua["Entity"];
     BindYielding(entity_type, "move_sync", &Entity::ScriptMoveSync);
@@ -219,6 +222,7 @@ void ScriptManager::InitBinds(){
       "get_player_entity", &EntityManager::ScriptGetPlayerEntity,
       "unset_player_entity", &EntityManager::ScriptUnsetPlayerEntity,
       "player_lock", &EntityManager::ScriptPlayerLock,
+      "set_player_slip", &EntityManager::ScriptSetPlayerSlip,
       "is_player_locked", &EntityManager::IsPlayerLocked,
       "set_player_default_run", &EntityManager::SetPlayerDefaultRun,
       "random_encounters_on", &EntityManager::SetRandomEncounters,
@@ -365,11 +369,21 @@ void ScriptManager::InitBinds(){
         sol::resolve<void(const char*)>(&AudioManager::ScriptPlaySound),
         sol::resolve<void(const char*, const int)>(&AudioManager::ScriptPlaySound)
       ),
-      "play_sounds", &AudioManager::ScriptPlaySounds,
+      // The scripts pass nil for the sounds the opcode doesn't use.
+      "play_sounds", [](
+        AudioManager& audio, sol::optional<std::string> name1, sol::optional<std::string> name2,
+        sol::optional<std::string> name3, sol::optional<std::string> name4
+      ){
+          if (name1) audio.ScriptPlaySounds(
+            name1->c_str(), name2 ? name2->c_str() : "", name3 ? name3->c_str() : "",
+            name4 ? name4->c_str() : ""
+          );
+      },
       "get_track_id", &AudioManager::ScriptGetTrack,
       "get_battle_track_id", &AudioManager::ScriptGetBattleTrack,
       "set_battle_track_id", &AudioManager::ScriptSetBattleTrack,
       "play_music_once", &AudioManager::ScriptPlayMusicOnce,
+      "is_music_playing", &AudioManager::ScriptIsMusicPlaying,
       "set_music_volume", &AudioManager::ScriptSetMusicVolume,
       "set_sound_volume", &AudioManager::ScriptSetSoundVolume
     );
@@ -488,6 +502,11 @@ void ScriptManager::InitBinds(){
       "area_on", &Background2D::ScriptAreaOn,
       "area_off", &Background2D::ScriptAreaOff,
       "area_clear", &Background2D::ScriptAreaClear,
+      "palette_store", &Background2D::ScriptPaletteStore,
+      "palette_load", &Background2D::ScriptPaletteLoad,
+      "palette_copy", &Background2D::ScriptPaletteCopy,
+      "palette_multiply", &Background2D::ScriptPaletteMultiply,
+      "palette_add", &Background2D::ScriptPaletteAdd,
       "shake", &Background2D::ScriptShake,
       "set_layer_parallax", &Background2D::ScriptSetLayerParallax,
       "set_layer_scroll", &Background2D::ScriptSetLayerScroll,
@@ -626,14 +645,26 @@ void ScriptManager::InitBinds(){
     // Commands to initiate modules
     lua.new_usertype<VGears::WorldmapModule>(
       "world_map_module",
-      "init", &VGears::WorldmapModule::Init,
+      "init", sol::overload(
+        [](VGears::WorldmapModule& module){module.Init(0);},
+        [](VGears::WorldmapModule& module, const int map_id){module.Init(map_id);}
+      ),
       "suspend", &VGears::WorldmapModule::Suspend,
       "clear_vehicle_terrains", &VGears::WorldmapModule::ClearVehicleTerrains,
       "add_vehicle_terrain", &VGears::WorldmapModule::AddVehicleTerrain,
       "get_terrain_type_under_entity", &VGears::WorldmapModule::GetTerrainTypeUnderEntity,
       "get_terrain_triangle_under_entity", &VGears::WorldmapModule::GetTerrainTriangleUnderEntity,
       "unboard_vehicle", &VGears::WorldmapModule::UnboardVehicle,
-      "set_encounters_locked", &VGears::WorldmapModule::SetEncountersLocked
+      "set_encounters_locked", &VGears::WorldmapModule::SetEncountersLocked,
+      "set_model_orientation", &VGears::WorldmapModule::SetModelOrientation,
+      "set_model_offset", &VGears::WorldmapModule::SetModelOffset,
+      "set_entity_altitude", &VGears::WorldmapModule::SetEntityAltitude,
+      "enter", &VGears::WorldmapModule::Enter,
+      "set_spawn", &VGears::WorldmapModule::SetSpawn,
+      "set_speed", &VGears::WorldmapModule::SetSpeed,
+      "set_camera", &VGears::WorldmapModule::SetCamera,
+      "set_vehicle_hidden", &VGears::WorldmapModule::SetVehicleHidden,
+      "add_world_model", &VGears::WorldmapModule::AddWorldModelFromScript
     );
 
     // Register all command handlers

+ 3 - 0
src/core/XmlBackground2DFile.cpp

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

+ 34 - 2
src/data/VGearsBackgroundFile.cpp

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

+ 46 - 0
src/data/VGearsBackgroundFile.h

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

+ 8 - 0
src/data/VGearsTriggersFile.h

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

+ 71 - 45
src/installer/ExternalTools.cpp

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

+ 14 - 0
src/installer/ExternalTools.h

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

+ 232 - 18
src/installer/FieldDataInstaller.cpp

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

+ 6 - 1
src/installer/FieldDataInstaller.h

@@ -393,6 +393,11 @@ class FieldDataInstaller{
          */
         void CollectSpawnAndScaleFactors(int field_index);
 
+        /**
+         * Writes the coordinates of the exits to the world map (scripts/worldmap/world_arrivals.lua).
+         */
+        void WriteWorldArrivals();
+
         /**
          * Converts FFVII PC fields to V-Gears format.
          *
@@ -461,7 +466,7 @@ class FieldDataInstaller{
          *
          * @return Lua code to put at the beginning of a field script.
          */
-        static std::string FieldScriptHeader();
+        static std::string FieldScriptHeader(const int field_id = -1);
 
     private:
 

+ 12 - 1
src/installer/FieldTextWriter.cpp

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

+ 4 - 1
src/installer/InstallVerifier.cpp

@@ -163,7 +163,10 @@ VerifyResult VerifyInstallation(const std::string& root, const std::string& refe
 
     const std::string world = "World map";
     for (const char* file : {"WM0.MAP", "WM2.MAP", "WM3.MAP"}) check.File(world, std::string("data/wm/") + file);
-    check.File(world, "data/scripts/worldmap/wm0.lua");
+    // The scripts of the maps are decompiled by the installer, the other ones are copied from the
+    // V-Gears data folder.
+    for (const char* file : {"wm0.lua", "wm2.lua", "wm3.lua", "triangle_triggers.lua", "vehicles.lua", "script_stubs.lua"})
+        check.File(world, std::string("data/scripts/worldmap/") + file);
     check.File(world, "data/gamedata/world_encounters.xml");
     check.Files(world, "data/models/world/terrain/0", ".mesh", 1);
 

+ 39 - 11
src/installer/WorldInstaller.cpp

@@ -31,6 +31,8 @@
 #include "data/VGearsLGPArchive.h"
 #include "data/WorldMapWalkmesh.h"
 #include "data/VGearsHRCFileManager.h"
+#include "data/VGearsAFileManager.h"
+#include "WorldModelTable.h"
 #include "data/FF7Data.h"
 #include "decompiler/ControlFlow.h"
 #include "decompiler/DecompilerException.h"
@@ -401,17 +403,25 @@ void WorldInstaller::ProcessModels(){
             auto mesh_name = VGears::NameLookup::model(hrc_base_name) + ".mesh";
             Ogre::MeshPtr mesh(Ogre::MeshManager::getSingleton().load(mesh_name, "FFVII"));
             Ogre::SkeletonPtr skeleton(mesh->getSkeleton());
-            // TODO: a files??
-            /*for (std::string anim : model.a){
-                VGears::AFileManager &afl_mgr(VGears::AFileManager::GetSingleton());
-                Ogre::String a_base_name;
-                VGears::StringUtil::splitBase(anim, a_base_name);
-                VGears::AFilePtr a
-                  = afl_mgr.load(a_base_name + ".a", "FFVII").staticCast<VGears::AFile>();
-                // Convert the FF7 name to a more readable name set in the meta data.
-                VGears::StringUtil::splitBase(anim, base_name);
-                a->AddTo(skeleton, VGears::NameLookup::Animation(base_name));
-            }*/
+            // The animations of the model, from the tables of ff7.exe (see WorldModelTable.h). Their names
+            // are the ones of the A files, in lower case.
+            for (const WorldModelTable::Model& model : WorldModelTable::MODELS){
+                if (hrc_base_name != model.hrc) continue;
+                for (unsigned int i = 0; i < model.animation_count; ++ i){
+                    const std::string animation_file = std::string(model.animations[i]) + ".a";
+                    try{
+                        VGears::AFilePtr a = VGears::AFileManager::GetSingleton().load(
+                          animation_file, "FFVII"
+                        ).staticCast<VGears::AFile>();
+                        a->AddTo(skeleton, model.animations[i]);
+                    }
+                    catch (const std::exception& ex){
+                        std::cerr << "[ERROR] Exception converting animation " << animation_file << " of world model "
+                          << file_name << ": " << ex.what() << std::endl;
+                    }
+                }
+                break;
+            }
             ExportMesh(data_dir_ + "models/world/", mesh);
             // Models can share a skeleton name with different bones (also with field models), so drop this one
             // (with its skeleton and mesh) before converting the next.
@@ -870,6 +880,24 @@ bool WorldInstaller::GenerateScripts(
                     << static_cast<unsigned int>(mesh_function_id) << "] = " << function_index << "\n";
         }
 
+        // The functions that run when an entity of a type is created, and for the other events of the
+        // entities. The type is in the bits 8 to 13 of the type of the function, and the event in the low byte.
+        script_file << "System.WorldMap.entity_functions = {}\n";
+        for (size_t function_index = 0; function_index < generated_functions.size(); ++function_index){
+                if (!generated_functions[function_index]) continue;
+                const size_t type_offset = function_index * 4;
+                if (type_offset + 1 >= event_data.size()) continue;
+                const uint16 function_type = static_cast<uint16>(event_data[type_offset])
+                    | static_cast<uint16>(event_data[type_offset + 1] << 8);
+                if ((function_type >> 14) != 1) continue;
+                const unsigned int entity_type = (function_type >> 8) & 0x3F;
+                const unsigned int event = function_type & 0xFF;
+                script_file << "System.WorldMap.entity_functions[" << entity_type << "] = "
+                    << "System.WorldMap.entity_functions[" << entity_type << "] or {}\n"
+                    << "System.WorldMap.entity_functions[" << entity_type << "][" << event << "] = "
+                    << function_index << "\n";
+        }
+
         script_file << "System.WorldMap.field_table = {}\n";
         for (size_t record_index = 0; record_index < 64; ++record_index){
                 for (size_t scenario = 0; scenario < 2; ++scenario){

+ 162 - 0
src/installer/WorldModelTable.h

@@ -0,0 +1,162 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+/**
+ * The models of the world maps, and the animations that each one uses.
+ *
+ * The data comes from the tables of ff7.exe (the 1998 build, .data section at 0x95bfd0 to 0x95cad4).
+ * A record has 20 bytes: a pointer to the name of the model, a pointer to its HRC file, the number of
+ * animations, a value (scale), and a pointer to the animations in a list of names of A files. The
+ * code that selects the models of a map (0x74f5dc) has a jump table of 13 cases, and each case picks
+ * a part of the records. The animations of every model have the same number of bones as the model.
+ */
+namespace WorldModelTable{
+
+    /**
+     * A model of the world maps.
+     */
+    struct Model{
+
+        /// Name of the HRC file, without extension.
+        const char* hrc;
+
+        /// Name that the game gives the model.
+        const char* name;
+
+        /// Value that the game stores with the model. It is probably its scale, in fixed point
+        /// where 0x1000 is 1, but this is not confirmed.
+        unsigned int scale_raw;
+
+        /// Names of the A files (animations) of the model, without extension. The first one is
+        /// the first in the table.
+        const char* animations[11];
+
+        /// Number of animations.
+        unsigned int animation_count;
+    };
+
+    /**
+     * The models that are in the tables of the game. They are in the order of their first appearance.
+     */
+    static const Model MODELS[] = {
+        {"aja", "choko", 0x200, {"asc", "asd", "ase"}, 3},
+        {"dva", "tybrco", 0x280, {"dya"}, 1},
+        {"aba", "buggy", 0x200, {"age", "aha", "ahb", "ahc", "ahd", "ahe"}, 6},
+        {"aaa", "barrier", 0xdac, {"aae"}, 1},
+        {"bkd", "condor", 0xc80, {"bld"}, 1},
+        {"coc", "rocket", 0x8fc, {"cpb"}, 1},
+        {"cpc", "rocketbase", 0x8fc, {"cqb"}, 1},
+        {"cfc", "goldsaucer", 0xaf0, {"cgc"}, 1},
+        {"aia", "canon", 0x1000, {"aie"}, 1},
+        {"cnb", "rock", 0x834, {"cob"}, 1},
+        {"cgd", "highwind", 0x300, {"cic"}, 1},
+        {"ddd", "sbmrn", 0x200, {"dfe"}, 1},
+        {"dkc", "tail", 0x300, {"dla"}, 1},
+        {"bna", "diaweapon", 0x400, {"btd", "bte", "bua", "bub", "buc"}, 5},
+        {"eke", "warship", 0x1b8, {"ena"}, 1},
+        {"cmb", "midgulcanon", 0x1000, {"cna"}, 1},
+        {"cid", "highwind02", 0x300, {"cma"}, 1},
+        {"dyb", "ultima", 0x200, {"eic", "eid", "eie", "eja", "ejb", "ejc", "ejd"}, 7},
+        {"cqc", "ruby", 0x280, {"dda", "ddb", "ddc"}, 3},
+        {"cec", "gernika", 0x1000, {"cfb"}, 1},
+        {"eje", "underseemk", 0x1000, {"ekd"}, 1},
+        {"ble", "coralkey", 0x300, {"bme"}, 1},
+        {"dic", "seeobject", 0x800, {"djb"}, 1},
+        {"dga", "sbmrn2", 0x200, {"dib"}, 1},
+        {"bud", "emerald", 0x280, {"cea", "ceb"}, 2},
+        {"djc", "snowpole", 0x300, {"dkb"}, 1},
+        {"bbe", "cloud", 0x200, {"bid", "bie", "bja", "bjb", "bjc", "bjd", "bje", "bka", "bkb", "bkc"}, 10},
+        {"dlb", "tifa", 0x200, {"dse", "dta", "dtb", "dtc", "dtd", "dte", "dua", "dub", "duc", "dud", "due"}, 11},
+        {"ata", "cid", 0x200, {"aze", "baa", "bab", "bac", "bad", "bae", "bba", "bbb", "bbc", "bbd"}, 10},
+    };
+
+    static const unsigned int MODEL_COUNT = sizeof(MODELS) / sizeof(MODELS[0]);
+
+    /**
+     * The models that the game loads for a situation of the world map, in the order of the table.
+     * The first 11 are the overworld in different moments of the story, and the last two are the
+     * underwater map (WM2) and the snowstorm map (WM3).
+     */
+    struct ModelSet{
+
+        /// What the set is for.
+        const char* description;
+
+        /// Names of the HRC files of its models, in the order of the game.
+        const char* models[13];
+
+        /// Number of models.
+        unsigned int model_count;
+    };
+
+    static const ModelSet MODEL_SETS[] = {
+        {"overworld, start (choko..rock)", {"aja", "dva", "aba", "aaa", "bkd", "coc", "cpc", "cfc", "aia", "cnb"}, 10},
+        {"overworld", {"aja", "aja", "cgd", "ddd", "bkd", "coc", "cpc", "cfc", "aia", "dkc", "aaa", "bna", "cnb"}, 13},
+        {"overworld", {"aja", "aja", "cgd", "ddd", "bkd", "coc", "cpc", "cfc", "cmb", "dkc", "aaa", "bna", "cnb"}, 13},
+        {"overworld", {"aja", "aja", "cid", "ddd", "bkd", "coc", "cpc", "cfc", "aia", "dkc", "aaa", "bna", "cnb"}, 13},
+        {"overworld", {"aja", "aja", "cid", "ddd", "bkd", "coc", "cpc", "cfc", "cmb", "dkc", "aaa", "bna", "cnb"}, 13},
+        {"overworld", {"aja", "aja", "cgd", "ddd", "bkd", "coc", "cpc", "cfc", "cmb", "dkc", "aaa", "dyb", "cnb"}, 13},
+        {"overworld", {"aja", "aja", "cid", "ddd", "bkd", "coc", "cpc", "cfc", "cmb", "dkc", "aaa", "dyb", "cnb"}, 13},
+        {"overworld", {"aja", "aja", "cgd", "ddd", "bkd", "coc", "cpc", "cfc", "cmb", "dkc", "cqc", "cnb"}, 12},
+        {"overworld", {"aja", "aja", "cid", "ddd", "bkd", "coc", "cpc", "cfc", "cmb", "dkc", "cqc", "cnb"}, 12},
+        {"overworld", {"eke", "aia"}, 2},
+        {"overworld", {"eke", "aia"}, 2},
+        {"underwater (WM2)", {"ddd", "cec", "eje", "ble", "dic", "dga", "bud"}, 7},
+        {"snowstorm (WM3)", {"djc", "djc", "djc"}, 3},
+    };
+
+    static const unsigned int MODEL_SET_COUNT = sizeof(MODEL_SETS) / sizeof(MODEL_SETS[0]);
+
+
+    /**
+     * The model that each type of entity of the world scripts uses, for each situation of the map
+     * (the same ones as MODEL_SETS). The type is the argument of the LoadModel call (opcode 0x300)
+     * of the scripts, and nullptr means that the situation has no model for it.
+     *
+     * The table is in ff7.exe at 0x95f5d0 (32 bytes for every situation, the byte is the slot of the
+     * model in the set plus one, and the game reads it at 0x75edd0 and 0x75ec57). The types 0, 1
+     * and 2 are the player: Cloud, Tifa and Cid.
+     */
+    static const char* const TYPE_MODELS[13][32] = {
+        {nullptr, nullptr, nullptr, nullptr, "aja", "dva", "aba", "aia", nullptr, nullptr, nullptr, nullptr, "bkd", nullptr, "cfc", "coc", "cpc", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, "aaa", "cnb", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr},
+        {nullptr, nullptr, nullptr, "cgd", "aja", nullptr, nullptr, "aia", nullptr, "dkc", "bna", nullptr, "bkd", "ddd", "cfc", "coc", "cpc", nullptr, nullptr, "aja", nullptr, nullptr, nullptr, nullptr, "aaa", "cnb", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr},
+        {nullptr, nullptr, nullptr, "cgd", "aja", nullptr, nullptr, nullptr, nullptr, "dkc", "bna", nullptr, "bkd", "ddd", "cfc", "coc", "cpc", nullptr, nullptr, "aja", "cmb", nullptr, nullptr, nullptr, "aaa", "cnb", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr},
+        {nullptr, nullptr, nullptr, "cid", "aja", nullptr, nullptr, "aia", nullptr, "dkc", "bna", nullptr, "bkd", "ddd", "cfc", "coc", "cpc", nullptr, nullptr, "aja", nullptr, nullptr, nullptr, nullptr, "aaa", "cnb", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr},
+        {nullptr, nullptr, nullptr, "cid", "aja", nullptr, nullptr, nullptr, nullptr, "dkc", "bna", nullptr, "bkd", "ddd", "cfc", "coc", "cpc", nullptr, nullptr, "aja", "cmb", nullptr, nullptr, nullptr, "aaa", "cnb", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr},
+        {nullptr, nullptr, nullptr, "cgd", "aja", nullptr, nullptr, nullptr, nullptr, "dkc", nullptr, "dyb", "bkd", "ddd", "cfc", "coc", "cpc", nullptr, nullptr, "aja", "cmb", nullptr, nullptr, nullptr, "aaa", "cnb", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr},
+        {nullptr, nullptr, nullptr, "cid", "aja", nullptr, nullptr, nullptr, nullptr, "dkc", nullptr, "dyb", "bkd", "ddd", "cfc", "coc", "cpc", nullptr, nullptr, "aja", "cmb", nullptr, nullptr, nullptr, "aaa", "cnb", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr},
+        {nullptr, nullptr, nullptr, "cgd", "aja", nullptr, nullptr, nullptr, nullptr, "dkc", nullptr, nullptr, "bkd", "ddd", "cfc", "coc", "cpc", nullptr, nullptr, "aja", "cmb", nullptr, nullptr, nullptr, nullptr, "cnb", nullptr, nullptr, nullptr, "cqc", nullptr, nullptr},
+        {nullptr, nullptr, nullptr, "cid", "aja", nullptr, nullptr, nullptr, nullptr, "dkc", nullptr, nullptr, "bkd", "ddd", "cfc", "coc", "cpc", nullptr, nullptr, "aja", "cmb", nullptr, nullptr, nullptr, nullptr, "cnb", nullptr, nullptr, nullptr, "cqc", nullptr, nullptr},
+        {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, "aia", "eke", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr},
+        {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, "aia", "eke", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr},
+        {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, "ddd", nullptr, nullptr, nullptr, "cec", "eje", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, "ble", "dic", "dga", nullptr, "bud", nullptr},
+        {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, "djc", "djc", "djc", nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr},
+    };
+
+    /**
+     * Names that the game uses for the types of entities of the world scripts, from its model tables.
+     * The ones without a name are not used.
+     */
+    static const char* const TYPE_NAMES[32] = {
+        "cloud", "tifa", "cid", "highwind", "chocobo", "tiny bronco", "buggy", "canon", "warship",
+        "tail", "diamond weapon", "ultimate weapon", "condor", "submarine", "gold saucer", "rocket",
+        "rocket base", "gernika", "underwater mark", "chocobo (2)", "midgar cannon", "snowpole 1",
+        "snowpole 2", "snowpole 3", "barrier", "rock", "coral key", "sea object", "submarine (2)",
+        "ruby weapon", "emerald weapon", nullptr
+    };
+
+}

+ 14 - 1
src/installer/decompiler/CodeGenerator.cpp

@@ -115,10 +115,23 @@ ARGUMENT_ORDER CodeGenerator::GetBinaryOrder(){return bin_order_;}
 
 void CodeGenerator::ProcessInst(Function& function, InstVec& insts, const InstPtr inst){
     inst->ProcessInst(function, stack_, engine_, this);
-    if (inst->IsCondJump()) ProcessCondJumpInst(inst);
+    if (inst->IsCondJump()){
+        switch (cur_group_->type){
+            case GROUP_TYPE_IF:
+            case GROUP_TYPE_WHILE:
+            case GROUP_TYPE_DO_WHILE:
+                ProcessCondJumpInst(inst);
+                break;
+            default:
+                ProcessUnstructuredCondJump(insts, inst);
+                break;
+        }
+    }
     else if (inst->IsUncondJump()) ProcessUncondJumpInst(function, insts, inst);
 }
 
+void CodeGenerator::ProcessUnstructuredCondJump(InstVec&, const InstPtr){}
+
 void CodeGenerator::ProcessUncondJumpInst(Function& function, InstVec& insts, const InstPtr inst){
     switch (cur_group_->type){
         case GROUP_TYPE_BREAK: AddOutputLine(target_lang_->LoopBreak()); break;

+ 12 - 0
src/installer/decompiler/CodeGenerator.h

@@ -197,6 +197,18 @@ class CodeGenerator {
          */
         void ProcessCondJumpInst(const InstPtr inst);
 
+        /**
+         * Processes a conditional jump that is not part of an if or a loop, because the graph was
+         * not analyzed. The default does nothing, so the condition is dropped.
+         *
+         * A generator that wants these jumps overrides it to output the jump with its condition
+         * and to mark the destination label as required.
+         *
+         * @param[in] insts All the instructions of the script.
+         * @param[in] inst The jump.
+         */
+        virtual void ProcessUnstructuredCondJump(InstVec& insts, const InstPtr inst);
+
         /**
          * Indents a string according to the current indentation level.
          *

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

+ 18 - 0
src/installer/decompiler/world/WorldCodeGenerator.cpp

@@ -46,3 +46,21 @@ const InstPtr WorldCodeGenerator::FindLastCall(){
 }
 
 void WorldCodeGenerator::ProcessSpecialMetadata(const InstPtr inst, char c, int pos){}
+
+void WorldCodeGenerator::ProcessUnstructuredCondJump(InstVec& insts, const InstPtr inst){
+    // "Jump if false" pops the condition, and jumps when it is false.
+    const std::string condition = WorldEngine::AsCondition(stack_.Pop());
+    const uint32 dst_addr = inst->GetDestAddress();
+    if (is_label_pass_){
+        for (auto& i : insts){
+            if (i->GetAddress() == dst_addr){
+                i->SetLabelRequired(true);
+                break;
+            }
+        }
+    }
+    // The jump is taken when the condition is false: "not not x" is "x".
+    const std::string jump_if = condition.compare(0, 4, "not ") == 0
+      ? condition.substr(4) : "not " + condition;
+    AddOutputLine("if " + jump_if + " then " + target_lang_->Goto(dst_addr) + " end");
+}

+ 12 - 0
src/installer/decompiler/world/WorldCodeGenerator.h

@@ -56,6 +56,18 @@ class WorldCodeGenerator : public CodeGenerator{
          */
         virtual void ProcessSpecialMetadata(const InstPtr inst, char c, int pos);
 
+        /**
+         * Outputs a jump if false as "if not (condition) then goto label end".
+         *
+         * The scripts of the world map are not analyzed into ifs and loops, so every conditional
+         * jump is a goto. A label is valid in Lua if it is in the same block, and the generated
+         * functions are flat.
+         *
+         * @param[in] insts All the instructions of the script.
+         * @param[in] inst The jump.
+         */
+        virtual void ProcessUnstructuredCondJump(InstVec& insts, const InstPtr inst) override;
+
     protected:
 
         bool OutputOnlyRequiredLabels() const override;

+ 28 - 1
src/installer/decompiler/world/WorldDisassembler.cpp

@@ -90,12 +90,24 @@ void WorldDisassembler::DoDisassemble(){
         this->stream_->Seek(code_offset);
         this->address_ = this->stream_->GetPosition();
         bool end = false;
+        // The farthest address that a jump of the script goes to. A return doesn't end the script
+        // while a jump goes after it.
+        uint32 farthest_jump_target = 0;
         for (;;){
             if (end) break;
             uint32 full_opcode = 0;
             uint16 opcode = this->stream_->ReadU16();
             std::string opcode_prefix;
-            if (opcode == 0x203) end = true;
+            if (opcode == 0x200 || opcode == 0x201){
+                const auto parameter_position = this->stream_->GetPosition();
+                const uint16 target = this->stream_->ReadU16();
+                this->stream_->Seek(parameter_position);
+                // Same address as the instruction addresses before they are divided by 2.
+                farthest_jump_target = std::max<uint32>(
+                  farthest_jump_target, (0x200 + target) * 2
+                );
+            }
+            if (opcode == 0x203) end = this->address_ >= farthest_jump_target;
             if (opcode >= 0x204 && opcode < 0x300)
                 ParseOpcode(opcode, "reset stack", new WorldKernelCallInstruction(), 0, "");
             else{
@@ -124,6 +136,9 @@ void WorldDisassembler::DoDisassemble(){
                     case 0x11c:
                         ParseOpcode(opcode, "push word from bank 0", new WorldLoadBankInstruction(), 2, "w");
                         break;
+                    case 0x11d:
+                        ParseOpcode(opcode, "push word from bank 1", new WorldLoadBankInstruction(), 2, "w");
+                        break;
                     case 0x114:
                         ParseOpcode(opcode, "push bit from bank 0", new WorldLoadBankInstruction(), 2, "w");
                         break;
@@ -152,6 +167,9 @@ void WorldDisassembler::DoDisassemble(){
                         );
                         break;
 
+                    case 0x01b:
+                        ParseOpcode(opcode, "push unknown 1b", new WorldSubStackInstruction(), 2, "");
+                        break;
                     case 0x061:
                         ParseOpcode(opcode, "push greater", new WorldSubStackInstruction(), 2, "");
                         break;
@@ -197,6 +215,15 @@ void WorldDisassembler::DoDisassemble(){
                     case 0x015:
                         ParseOpcode(opcode, "push neg", new WorldSubStackInstruction(), 2, "");
                         break;
+                    case 0x31b:
+                        ParseOpcode(opcode, "unknown 31b", new WorldKernelCallInstruction(), 0, "");
+                        break;
+                    case 0x33c:
+                        ParseOpcode(opcode, "unknown 33c", new WorldKernelCallInstruction(), 0, "");
+                        break;
+                    case 0x355:
+                        ParseOpcode(opcode, "unknown 355", new WorldKernelCallInstruction(), 0, "");
+                        break;
                     case 0x320:
                         ParseOpcode(opcode, "unknown 320", new WorldKernelCallInstruction(), 0, "");
                         break;

+ 14 - 0
src/installer/decompiler/world/WorldEngine.cpp

@@ -30,6 +30,20 @@
 
 WorldEngine::BankValue::BankValue(std::string name) : VarValue(name){}
 
+WorldEngine::BoolValue::BoolValue(std::string condition) : VarValue(condition){}
+
+std::ostream& WorldEngine::BoolValue::Print(std::ostream& output) const{
+    return output << "(" << name_ << " and 1 or 0)";
+}
+
+std::string WorldEngine::BoolValue::Condition() const{return name_;}
+
+std::string WorldEngine::AsCondition(const ValuePtr& value){
+    const BoolValue* boolean = dynamic_cast<const BoolValue*>(value.get());
+    if (boolean != nullptr) return boolean->Condition();
+    return "(" + value->GetString() + " ~= 0)";
+}
+
 WorldEngine::WorldEngine(int script_number) : script_number_(script_number){SetOutputStackEffect(true);}
 
 std::unique_ptr<Disassembler> WorldEngine::GetDisassembler(InstVec &insts){

+ 44 - 0
src/installer/decompiler/world/WorldEngine.h

@@ -47,6 +47,50 @@ class WorldEngine : public Engine{
                 BankValue(std::string name);
         };
 
+        /**
+         * A value that is a Lua boolean, the result of a comparison or a logic operation.
+         *
+         * The script machine only has numbers, and in Lua 0 is true, so a boolean can't be used as
+         * a number nor a number as a condition without a conversion. This value prints as the
+         * number that the machine has (1 or 0), and has the condition for the places that want a
+         * boolean.
+         */
+        class BoolValue : public VarValue{
+
+            public:
+
+                /**
+                 * Constructor.
+                 *
+                 * @param[in] condition Lua expression that is a boolean.
+                 */
+                explicit BoolValue(std::string condition);
+
+                /**
+                 * Prints the value as a number.
+                 *
+                 * @param[out] output The stream to write to.
+                 * @return The stream used for output.
+                 */
+                virtual std::ostream& Print(std::ostream &output) const override;
+
+                /**
+                 * Retrieves the Lua boolean expression.
+                 *
+                 * @return The expression.
+                 */
+                std::string Condition() const;
+        };
+
+        /**
+         * Gets a value as a Lua boolean expression: a boolean as it is, and a number as "different
+         * from 0".
+         *
+         * @param[in] value The value.
+         * @return The expression.
+         */
+        static std::string AsCondition(const ValuePtr& value);
+
         /**
          * Constructor.
          *

+ 3 - 2
src/installer/decompiler/world/instruction/WorldBinaryEqualStackInstruction.cpp

@@ -28,6 +28,7 @@
 void WorldBinaryEqualStackInstruction::ProcessInst(
     Function& function, ValueStack &stack, Engine *engine, CodeGenerator *code_gen
 ){
-    code_gen_data_ = "==";
-    BinaryOpStackInstruction::ProcessInst(function, stack, engine, code_gen);
+    const ValuePtr right = stack.Pop();
+    const ValuePtr left = stack.Pop();
+    stack.Push(new WorldEngine::BoolValue("(" + left->GetString() + " == " + right->GetString() + ")"));
 }

+ 32 - 25
src/installer/decompiler/world/instruction/WorldKernelCallInstruction.cpp

@@ -30,7 +30,8 @@ void WorldKernelCallInstruction::ProcessInst(
 ){
     std::string func;
     switch (opcode_){
-        case 0x203: func = "return;"; break;
+        // A return can be in the middle of a function, and Lua only allows it at the end of a block.
+        case 0x203: func = "do return end"; break;
         case 0x317: func = "TriggerBattle(" + stack.Pop()->GetString() + ");"; break;
         case 0x324:
             // x, y, w, h
@@ -140,33 +141,39 @@ void WorldKernelCallInstruction::ProcessInst(
                 std::string type = stack.Pop()->GetString();
                 std::string comment = "-- ";
                 try{
+                    // The names come from the model tables of ff7.exe, see WorldModelTable.h.
                     switch (std::stoi(type)){
                         case 0: comment += "Cloud"; break;
-                        case 1: comment += "Tifa?"; break;
-                        case 2: comment += "Cid?"; break;
-                        case 3: comment += "Ultimate Weapon"; break;
-                        case 4: comment += "Unknown"; break;
-                        case 5: comment += "Unknown"; break;
-                        case 6: comment += "Unknown"; break;
-                        case 7: comment += "Unknown"; break;
-                        case 8: comment += "Unknown"; break;
-                        case 9: comment += "Unknown"; break;
-                        case 10: comment += "Unknown"; break;
-                        case 11: comment += "Highwind"; break;
-                        case 12: comment += "Unknown"; break;
+                        case 1: comment += "Tifa"; break;
+                        case 2: comment += "Cid"; break;
+                        case 3: comment += "Highwind"; break;
+                        case 4: comment += "Chocobo"; break;
+                        case 5: comment += "Tiny Bronco"; break;
+                        case 6: comment += "Buggy"; break;
+                        case 7: comment += "Cannon"; break;
+                        case 8: comment += "Warship"; break;
+                        case 9: comment += "Tail"; break;
+                        case 10: comment += "Diamond Weapon"; break;
+                        case 11: comment += "Ultimate Weapon"; break;
+                        case 12: comment += "Condor"; break;
                         case 13: comment += "Submarine"; break;
-                        case 14: comment += "Unknown"; break;
-                        case 15: comment += "Unknown"; break;
-                        case 16: comment += "Unknown"; break;
-                        case 17: comment += "Unknown"; break;
-                        case 18: comment += "Unknown"; break;
-                        case 19: comment += "Chocobo"; break;
-                        case 20: comment += "Unknown"; break;
-                        case 21: comment += "Unknown"; break;
-                        case 22: comment += "Unknown"; break;
-                        case 23: comment += "Unknown"; break;
-                        case 24: comment += "Unknown"; break;
-                        case 25: comment += "Unknown"; break;
+                        case 14: comment += "Gold Saucer"; break;
+                        case 15: comment += "Rocket"; break;
+                        case 16: comment += "Rocket Base"; break;
+                        case 17: comment += "Gernika"; break;
+                        case 18: comment += "Underwater mark"; break;
+                        case 19: comment += "Chocobo (2)"; break;
+                        case 20: comment += "Midgar cannon"; break;
+                        case 21: comment += "Snowpole 1"; break;
+                        case 22: comment += "Snowpole 2"; break;
+                        case 23: comment += "Snowpole 3"; break;
+                        case 24: comment += "Barrier"; break;
+                        case 25: comment += "Rock"; break;
+                        case 26: comment += "Coral key"; break;
+                        case 27: comment += "Sea object"; break;
+                        case 28: comment += "Submarine (2)"; break;
+                        case 29: comment += "Ruby Weapon"; break;
+                        case 30: comment += "Emerald Weapon"; break;
                         default: comment += "??"; break;
                     }
                 }

+ 16 - 1
src/installer/decompiler/world/instruction/WorldLoadBankInstruction.cpp

@@ -26,4 +26,19 @@
 
 void WorldLoadBankInstruction::ProcessInst(
   Function &function, ValueStack &stack, Engine *engine, CodeGenerator *code_gen
-){stack.Push(new WorldEngine::BankValue("Read(" + params_[0]->GetString() + ")"));}
+){
+    // The game variables are at the savemap from 0xBA4 (the story counter is the word at 0): the
+    // opcode says if the address is of a byte, a word (0x11c) or a bit (0x114). The second bank
+    // (0x119, 0x11d) is the memory of the script and the "special" ones (0x11b, 0x117) are the
+    // values that the engine gives to the script (how the world was entered...): they have the same
+    // addresses as the game variables, but are not them.
+    std::string function_name = "Read";
+    switch (GetOpcode()){
+        case 0x11c: function_name = "ReadWord"; break;
+        case 0x114: function_name = "ReadBit"; break;
+        case 0x119: case 0x11d: function_name = "ReadLocal"; break;
+        case 0x11b: case 0x117: function_name = "ReadSpecial"; break;
+        default: break;
+    }
+    stack.Push(new WorldEngine::BankValue(function_name + "(" + params_[0]->GetString() + ")"));
+}

+ 2 - 1
src/installer/decompiler/world/instruction/WorldNoOutputInstruction.cpp

@@ -28,5 +28,6 @@
 void WorldNoOutputInstruction::ProcessInst(
   Function& function, ValueStack &stack, Engine *engine, CodeGenerator *code_gen
 ){
-    // TODO
+    // The opcode is "reset stack": what was pushed and not used by the previous statement is gone.
+    while (!stack.IsEmpty()) stack.Pop();
 }

+ 17 - 1
src/installer/decompiler/world/instruction/WorldStoreInstruction.cpp

@@ -32,5 +32,21 @@ void WorldStoreInstruction::ProcessInst(
     // If the bank address is from a load bank instruction, then only
     // the bank address is needed, not what's *at* the bank address.
     ValuePtr bank_addr = stack.Pop();
-    code_gen->AddOutputLine("Write(" + bank_addr->GetString() + ", " + value + ");");
+    // The destination is pushed with a load instruction, but what is written is the variable that it
+    // names, not the one whose address is the value of that variable: Read(12) is Write(12, ...).
+    std::string address = bank_addr->GetString();
+    std::string function_name = "Write";
+    if (dynamic_cast<WorldEngine::BankValue*>(bank_addr.get()) != nullptr && address.back() == ')'){
+        // ReadX(n) is the variable that is written, WriteX(n, value).
+        static const char* const kinds[] = {"Word", "Bit", "Local", "Special", ""};
+        for (const char* kind : kinds){
+            const std::string prefix = std::string("Read") + kind + "(";
+            if (address.compare(0, prefix.size(), prefix) == 0){
+                function_name = std::string("Write") + kind;
+                address = address.substr(prefix.size(), address.size() - prefix.size() - 1);
+                break;
+            }
+        }
+    }
+    code_gen->AddOutputLine(function_name + "(" + address + ", " + value + ");");
 }

+ 47 - 28
src/installer/decompiler/world/instruction/WorldSubStackInstruction.cpp

@@ -27,35 +27,54 @@
 void WorldSubStackInstruction::ProcessInst(
     Function& function, ValueStack &stack, Engine *engine, CodeGenerator *code_gen
 ){
-    std::string op;
-    switch (opcode_){
-        case 0x41: op = "-"; break;
-        case 0x40: op = "+"; break;
-        case 0x80: op = "&&"; break;
-        case 0xa0: op = "||"; break;
-        case 0xc0: op = "|"; break;
-        case 0x15: // neg
-        case 0x17: // not
-            stack.Push(stack.Pop()->Negate());
-            return;
-            break;
-        case 0x30: op = "*";break;
-        case 0x60: op = "<"; break;
-        case 0x61: op = ">"; break;
-        case 0x62: op = "<="; break;
-        case 0x63: op = ">="; break;
-        case 0x0b0: op = "&"; break; // TODO: Review op
-        case 0x51: op = "<<"; break;
-        default:op = "unknown_operation";
+    // The operands are pushed in order, so the first one is the second from the top.
+    if (opcode_ == 0x15){
+        // Negative number.
+        const std::string operand = stack.Pop()->GetString();
+        stack.Push(new VarValue("(-" + operand + ")"));
+        return;
+    }
+    if (opcode_ == 0x1b){
+        // A function of one value that is not known (the emerald weapon uses it on a variable).
+        const std::string operand = stack.Pop()->GetString();
+        stack.Push(new VarValue("UnknownFunction1B(" + operand + ")"));
+        return;
     }
-    std::string value;
-    if (opcode_ == 0x51){
-        const std::string left = stack.Pop()->GetString();
-        const std::string right = stack.Pop()->GetString();
-        value = "((" + left + ") * (2 ^ " + right + "))";
+    if (opcode_ == 0x17){
+        // Logic not.
+        const std::string condition = WorldEngine::AsCondition(stack.Pop());
+        // not not x is x.
+        if (condition.compare(0, 4, "not ") == 0) stack.Push(new WorldEngine::BoolValue(condition.substr(4)));
+        else stack.Push(new WorldEngine::BoolValue("not " + condition));
+        return;
     }
-    else{
-        value = stack.Pop()->GetString() + " " + op + " " + stack.Pop()->GetString();
+    const ValuePtr right = stack.Pop();
+    const ValuePtr left = stack.Pop();
+    const std::string l = left->GetString();
+    const std::string r = right->GetString();
+    switch (opcode_){
+        case 0x40: stack.Push(new VarValue("(" + l + " + " + r + ")")); break;
+        case 0x41: stack.Push(new VarValue("(" + l + " - " + r + ")")); break;
+        case 0x30: stack.Push(new VarValue("(" + l + " * " + r + ")")); break;
+        // Shift right.
+        case 0x51: stack.Push(new VarValue("math.floor(" + l + " / 2 ^ " + r + ")")); break;
+        // Bitwise and, or (see script_stubs.lua).
+        case 0x80: stack.Push(new VarValue("BitAnd(" + l + ", " + r + ")")); break;
+        case 0xa0: stack.Push(new VarValue("BitOr(" + l + ", " + r + ")")); break;
+        case 0x60: stack.Push(new WorldEngine::BoolValue("(" + l + " < " + r + ")")); break;
+        case 0x61: stack.Push(new WorldEngine::BoolValue("(" + l + " > " + r + ")")); break;
+        case 0x62: stack.Push(new WorldEngine::BoolValue("(" + l + " <= " + r + ")")); break;
+        case 0x63: stack.Push(new WorldEngine::BoolValue("(" + l + " >= " + r + ")")); break;
+        case 0xb0:
+            stack.Push(new WorldEngine::BoolValue(
+              "(" + WorldEngine::AsCondition(left) + " and " + WorldEngine::AsCondition(right) + ")"
+            ));
+            break;
+        case 0xc0:
+            stack.Push(new WorldEngine::BoolValue(
+              "(" + WorldEngine::AsCondition(left) + " or " + WorldEngine::AsCondition(right) + ")"
+            ));
+            break;
+        default: stack.Push(new VarValue("unknown_operation(" + l + ", " + r + ")")); break;
     }
-    stack.Push(new VarValue(value));
 }

+ 5 - 0
src/map/VGearsBackground2DFile.cpp

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

+ 19 - 0
src/map/VGearsBackground2DFile.h

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

+ 3 - 0
src/map/VGearsBackground2DFileXMLSerializer.cpp

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

File diff ditekan karena terlalu besar
+ 977 - 36
src/modules/worldmap/WorldmapModule.cpp


+ 285 - 3
src/modules/worldmap/WorldmapModule.h

@@ -18,6 +18,9 @@
 #include <OgreFrameListener.h>
 #include <OgreSingleton.h>
 #include <OgreVector3.h>
+#include <deque>
+#include <map>
+#include <set>
 #include <vector>
 #include "common/TypeDefine.h"
 
@@ -47,8 +50,11 @@ namespace VGears {
 
             /**
              * Initializes the world map module
+             *
+             * @param[in] map_id 0 is the overworld (WM0), 1 is WM2 and 2 is WM3. If another map
+             * was already loaded, it is replaced.
              */
-            void Init();
+            void Init(const int map_id = 0);
             void Suspend();
 
             bool frameStarted(const Ogre::FrameEvent& event) override;
@@ -77,6 +83,90 @@ namespace VGears {
              */
             void SetEncountersLocked(const bool locked);
 
+            /**
+             * Sets the orientation of the model of a world map entity, in degrees. It's the
+             * orientation of the model itself, so the heading of the entity is added to it. It is
+             * for finding the right orientation of a model.
+             *
+             * @param[in] entity_name Name of the entity, like "WorldMapHighwind".
+             * @param[in] x Rotation in X.
+             * @param[in] y Rotation in Y.
+             * @param[in] z Rotation in Z.
+             */
+            /**
+             * Moves the model of a world map entity up or down, in world units, without moving
+             * the entity. It is for finding the right height of a model.
+             *
+             * @param[in] entity_name Name of the entity, like "WorldMapSubmarine".
+             * @param[in] y Height of the model. Negative is down, 0 is the position of the entity.
+             */
+            void SetModelOffset(const char* entity_name, const float y);
+
+            /**
+             * Puts a world map entity at a fixed height of the world, keeping its x and z.
+             *
+             * @param[in] entity_name Name of the entity, like "WorldMapemerald_30".
+             * @param[in] y Height in world units, not relative to the ground.
+             */
+            void SetEntityAltitude(const char* entity_name, const float y);
+
+            /**
+             * Sets where an entity of the overworld appears when the map is loaded, instead of its
+             * default spawn point. It is used by the debug data, see debug_data.lua.
+             *
+             * @param[in] entity_name Name of the entity: "Cloud", "Chocobo", "Highwind", "Buggy",
+             * "Submarine" or "TinyBronco".
+             * @param[in] x Position in X, in world units.
+             * @param[in] z Position in Z, in world units.
+             */
+            void SetSpawn(const char* entity_name, const float x, const float z);
+            /// Sets a movement speed (world units per second) by name: walk, chocobo, buggy, tiny_bronco,
+            /// highwind or submarine (WorldMapSettings.speed in world_settings.lua).
+            void SetSpeed(const char* name, const float speed);
+            /// Sets the camera of a vehicle by name (the ones of the speeds, and submarine_underwater for the
+            /// submarine of WM2): distance to the vehicle in world units and angle over the ground in degrees
+            /// (WorldMapSettings.camera in world_settings.lua).
+            void SetCamera(const char* name, const float distance, const float pitch_degrees);
+
+            /**
+             * Hides a vehicle of the overworld that the story hasn't given yet: it is not visible,
+             * solid nor talkable, so it can't be boarded. Has to be called before the map is created.
+             *
+             * @param[in] entity_name Name of the vehicle: "Chocobo", "Highwind", "Buggy",
+             * "Submarine" or "TinyBronco".
+             */
+            void SetVehicleHidden(const char* entity_name);
+
+            /**
+             * Enters a world map from a field: the map is always built again (its entities, scripts and
+             * models are for the story of now), unlike Init, which keeps the one that was suspended.
+             *
+             * @param[in] map_id Map to enter, 0 WM0, 1 WM2, 2 WM3.
+             */
+            void Enter(const int map_id);
+
+            /**
+             * Creates a model of the world that the scripts place (scenery like the rocket or the
+             * Gold Saucer), at a position of the world. The model is not solid.
+             *
+             * @param[in] name Name of the entity, without the prefix "WorldMap".
+             * @param[in] hrc Name of the HRC file of the model, like "cfc".
+             * @param[in] x Position in X, in world units.
+             * @param[in] z Position in Z, in world units.
+             * @param[in] raw_scale Scale that the game stores with the model: 0x200 is 1.
+             * @param[in] direction Direction that the script gives, from 0 to 255 for a full turn.
+             * @param[in] rotation_x Rotation of the model itself in X, in degrees.
+             * @param[in] rotation_y Rotation of the model itself in Y, in degrees.
+             * @param[in] rotation_z Rotation of the model itself in Z, in degrees.
+             */
+            void AddWorldModelFromScript(
+              const char* name, const char* hrc, const float x, const float z, const int raw_scale,
+              const int direction, const float rotation_x, const float rotation_y,
+              const float rotation_z
+            );
+
+            void SetModelOrientation(const char* entity_name, const float x, const float y, const float z);
+
         private:
 
             struct TerrainTriangle{
@@ -102,6 +192,43 @@ namespace VGears {
                 uint16 words[15];
             };
 
+            void DestroyWorldMap();
+            /**
+             * State of an entity of the overworld, kept while another map is loaded.
+             */
+            struct EntityState{
+                Ogre::String name;
+                Ogre::Vector3 position;
+                Ogre::Quaternion orientation;
+                bool visible;
+                bool solid;
+                bool talkable;
+            };
+
+            /**
+             * Saves the state of the entities of the overworld, to restore it when it is loaded
+             * again.
+             */
+            void SaveOverworldSnapshot();
+
+            /**
+             * Puts the entities of the overworld where they were when the snapshot was saved.
+             */
+            void RestoreOverworldSnapshot();
+
+            /**
+             * Gets the spawn point of an entity: the one that the debug data sets, or the default.
+             */
+            Ogre::Vector3 GetSpawn(
+              const Ogre::String& entity_name, const Ogre::Vector3& default_spawn
+            ) const;
+
+            /// Spawn points that replace the default ones.
+            std::map<Ogre::String, Ogre::Vector2> spawn_overrides_;
+
+            /// Vehicles that the story hasn't given.
+            std::set<Ogre::String> hidden_vehicles_;
+
             void CreateWorldMap(Ogre::SceneManager* scene_manager);
             void CreatePlayer();
                         void CreateCompanionModels();
@@ -110,16 +237,94 @@ namespace VGears {
                             const Ogre::Vector3& desired_position, Ogre::Real target_size,
                             const Ogre::Quaternion& orientation,
                             Ogre::Real collision_radius_scale = 1.0f,
-                            bool talkable = false
+                            bool talkable = false,
+                            Ogre::Real explicit_scale = 0.0f
                         );
             void UpdateCamera(Ogre::Real delta_time, bool snap_to_player);
+            /// Snow map (WM3): the camera turns by itself every few seconds.
+            void UpdateSnowCamera(Ogre::Real delta_time);
+            /// Snow map (WM3): puts a pole where the player is (only 4 poles exist, the oldest goes away).
+            void PlaceSnowPole();
             bool FindWalkableSurface(
                             const Ogre::Vector3& position, Ogre::Vector3& surface,
                             bool grass_only = false, bool require_walkable = true,
                             uint8* walkability_type = nullptr,
-                            size_t* triangle_index = nullptr
+                            size_t* triangle_index = nullptr,
+                            bool use_index = true
             ) const;
+            /// Groups the triangles of the terrain by the cell of a grid they touch, so the search of the
+            /// triangle under a position only checks a few of them.
+            void BuildTerrainIndex();
             bool IsActiveTerrainAllowed(uint8 walkability_type) const;
+            /**
+             * Runs the function of a triangle when it is entered, if it changed.
+             */
+            void EnterTriangle(const TerrainTriangle& triangle);
+
+            /**
+             * Plays the animation that each vehicle has in its state: parked, boarded, or boarded
+             * and moving.
+             *
+             * @param[in] moving True if the active entity is moving.
+             */
+            void UpdateVehicleAnimations(const bool moving);
+
+            /**
+             * Takes the submarine from WM0 to WM2, if it is over deep water inside the underwater
+             * map. It keeps the position and the heading.
+             *
+             * @param[in] submarine The submarine. The entities are replaced if it dives.
+             * @return True if it dived.
+             */
+            bool DiveToUnderwaterMap(EntityModel* submarine);
+
+            /**
+             * Takes the submarine from WM2 back to WM0, if the same position is deep water in
+             * WM0. It keeps the position and the heading.
+             *
+             * @param[in] submarine The submarine. The entities are replaced if it surfaces.
+             * @return True if it surfaced.
+             */
+            bool SurfaceToOverworld(EntityModel* submarine);
+
+            /**
+             * Starts the animation of a dive or a surfacing: the submarine goes under the surface
+             * (or up), the screen fades to black, the map changes, and the screen fades back while
+             * the submarine arrives. The request of the dive or the surfacing has to be set.
+             *
+             * @param[in] dive True for a dive from WM0 to WM2, false for a surfacing.
+             * @param[in] submarine The submarine.
+             */
+            void BeginTransition(const bool dive, EntityModel* submarine);
+
+            /**
+             * Moves the animation of the dive or the surfacing forward. It changes the map in the
+             * middle of it.
+             *
+             * @param[in] delta_time Seconds since the last frame.
+             */
+            void UpdateTransition(const Ogre::Real delta_time);
+
+            /**
+             * Ends the animation: the screen is shown and the player can move again.
+             */
+            void EndTransition();
+
+            /**
+             * Puts the submarine at the position of a surfacing and makes it the one in control.
+             */
+            void PlaceSurfacedSubmarine();
+
+            /**
+             * Moves a flying vehicle: forward with the action button, left and right turn, up and
+             * down change the height.
+             *
+             * @param[in] entity The vehicle.
+             * @param[in] delta_time Seconds since the last frame.
+             * @param[in] highwind True for the Highwind, false for the submarine of WM2.
+             */
+            void UpdateFlight(EntityModel* entity, const Ogre::Real delta_time, const bool highwind);
+
             void TriggerTriangleFunction(const TerrainTriangle& triangle);
             void LoadEncounters();
             void UpdateEncounters(const float delta_time, const TerrainTriangle& triangle);
@@ -133,6 +338,13 @@ namespace VGears {
             bool paused_for_battle_;
 
             std::vector<TerrainTriangle> terrain_triangles_;
+            /// Indices of the triangles (ascending) that touch each cell of the grid, row by row.
+            std::vector<std::vector<uint32>> terrain_grid_;
+            float terrain_grid_min_x_ = 0.0f;
+            float terrain_grid_min_z_ = 0.0f;
+            float terrain_grid_cell_ = 1.0f;
+            int terrain_grid_columns_ = 0;
+            int terrain_grid_rows_ = 0;
             Ogre::SceneManager* scene_manager_;
             Ogre::SceneNode* world_map_node_;
             EntityModel* player_entity_;
@@ -146,9 +358,79 @@ namespace VGears {
             Ogre::Real player_height_offset_;
             int active_function_mesh_index_;
             int active_function_id_;
+            /// Loaded map ID, -1 if none.
+            int map_id_;
+            /// Size of the map in blocks.
+            size_t grid_width_;
+            size_t grid_height_;
+            /// Rotation of the camera around the active entity, in radians. Positive is to the right.
+            float camera_yaw_;
+            /// True while the active entity is a flying vehicle.
+            bool flight_active_;
+            /// Flying vehicle that the flight state belongs to.
+            EntityModel* flight_entity_;
+            /// Rotation of the vehicle around the vertical axis, in radians.
+            float flight_heading_;
+            /// Height of the vehicle.
+            float flight_y_;
+            /// Position of the first block of the map in the 9x7 block grid of the world.
+            size_t origin_x_;
+            size_t origin_y_;
             bool initialized_;
             bool frame_listener_attached_;
             bool cancel_was_pressed_;
+            bool confirm_was_pressed_;
+            /// True while the function of a triangle is triggered by the landing of the Highwind.
+            bool landing_trigger_ = false;
+            /// Triangle of the northern cave that the Highwind has just landed on (a trigger waiting).
+            const TerrainTriangle* landing_after_unboard_ = nullptr;
+            /// Seconds since the music was checked, and the vehicle it was checked with.
+            float music_timer_ = 1.0f;
+            VehicleType music_vehicle_ = VehicleType::ON_FOOT;
+            /// Speeds set by the scripts, by name (the ones that are not set use the default ones).
+            std::map<std::string, float> speeds_;
+            float GetSpeed(const char* name, float default_speed) const;
+            struct CameraSettings{
+                float distance;
+                float pitch_degrees;
+            };
+            /// Cameras set by the scripts, by name (the ones that are not set use the default one).
+            std::map<std::string, CameraSettings> camera_settings_;
+            /// Snow map: seconds until the next automatic turn of the camera.
+            float snow_camera_timer_ = 0.0f;
+            /// Snow map: radians left of the turn that is going on, with the sign of its direction.
+            float snow_camera_remaining_ = 0.0f;
+            /// Snow map: the poles that exist (names of the entities), the oldest first.
+            std::deque<std::string> snow_poles_;
+            unsigned int snow_pole_counter_ = 0;
+            enum class TransitionStage{
+                /// No animation going on.
+                NONE,
+                /// The submarine moves away, in the map where it was.
+                LEAVING,
+                /// The screen goes black.
+                FADING_OUT,
+                /// The submarine comes into the new map and the screen is shown again.
+                ARRIVING
+            };
+            TransitionStage transition_stage_;
+            /// True for a dive, false for a surfacing.
+            bool transition_dive_;
+            float transition_timer_;
+            /// Heights where the submarine is moving between in the current stage.
+            float transition_start_y_;
+            float transition_target_y_;
+            /// State of the entities of WM0 while WM2 is loaded.
+            std::vector<EntityState> overworld_snapshot_;
+            /// A surfacing to WM0 is going on: the submarine appears at the position and heading
+            /// below.
+            bool surface_requested_;
+            Ogre::Vector3 surface_position_;
+            float surface_heading_;
+            /// A dive to WM2 is going on: the submarine appears at the position and heading below.
+            bool dive_requested_;
+            Ogre::Vector3 dive_position_;
+            float dive_heading_;
     };
 
 }

+ 5 - 5
test/core/ScreenFadeState.cpp

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

+ 14 - 0
test/installer/ExternalTools.cpp

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

Beberapa file tidak ditampilkan karena terlalu banyak file yang berubah dalam diff ini