Ver código fonte

Merge branch 'release/v0.4.0'

Iñigo Valentin 2 dias atrás
pai
commit
5d4ef01fc3
100 arquivos alterados com 5996 adições e 975 exclusões
  1. 19 6
      .claude/skills/release/SKILL.md
  2. 0 1
      CMake/Packaging.cmake
  3. 1 1
      CMakeLists.txt
  4. 73 34
      README.md
  5. 6 3
      data/data/screens/_screens.xml
  6. 258 0
      data/data/screens/exchange_menu/exchange_menu.xml
  7. 15 0
      data/data/screens/item_menu/item_menu.xml
  8. 5 0
      data/data/screens/main_menu/main_menu.xml
  9. 87 2
      data/data/screens/materia_menu/materia_menu.xml
  10. 25 0
      data/data/screens/save_menu/save_menu.xml
  11. 210 0
      data/data/screens/shop_menu/shop_menu.xml
  12. 1 0
      data/data/scripts/_scripts.xml
  13. 312 56
      data/data/scripts/battle/battle_camera.lua
  14. 600 107
      data/data/scripts/battle/battle_ui.lua
  15. 53 0
      data/data/scripts/character_abilities.lua
  16. 14 1
      data/data/scripts/data.lua
  17. 70 17
      data/data/scripts/field.lua
  18. 463 0
      data/data/scripts/menu/exchange_menu.lua
  19. 100 16
      data/data/scripts/menu/item_menu.lua
  20. 53 4
      data/data/scripts/menu/main_menu.lua
  21. 408 7
      data/data/scripts/menu/materia_menu.lua
  22. 6 17
      data/data/scripts/menu/menu_lib.lua
  23. 6 0
      data/data/scripts/menu/name_menu.lua
  24. 4 1
      data/data/scripts/menu/pause_menu.lua
  25. 35 10
      data/data/scripts/menu/phs_menu.lua
  26. 102 6
      data/data/scripts/menu/save_menu.lua
  27. 686 0
      data/data/scripts/menu/shop_menu.lua
  28. 11 0
      data/data/scripts/save.lua
  29. 359 126
      data/data/scripts/system.lua
  30. 20 4
      data/data/scripts/worldmap/triangle_triggers.lua
  31. 10 0
      data/data/scripts/worldmap/world_settings.lua
  32. 162 0
      data/data/scripts/worldmap/world_vm.lua
  33. 20 0
      data/data/texts/english/menu.xml
  34. 13 14
      doc/AUTHORS.md
  35. 46 38
      doc/BUILD.md
  36. 80 0
      doc/CHANGELOG.md
  37. 1 1
      doc/HISTORY.md
  38. 0 25
      doc/INSTALL.md
  39. 0 2
      doc/INSTALL_DATA.md
  40. 2 2
      doc/RUN.md
  41. 29 0
      doc/TODO.md
  42. 4 4
      src/Version.h
  43. 43 25
      src/core/Background2D.cpp
  44. 13 1
      src/core/Background2D.h
  45. 13 4
      src/core/BattleManager.cpp
  46. 21 9
      src/core/BattleManager.h
  47. 5 18
      src/core/CameraManager.cpp
  48. 3 3
      src/core/CameraManager.h
  49. 54 7
      src/core/ConfigCmdHandlerCommands.h
  50. 42 36
      src/core/DebugDraw.cpp
  51. 20 0
      src/core/DebugDraw.h
  52. 36 2
      src/core/DialogsManager.cpp
  53. 23 1
      src/core/DialogsManager.h
  54. 5 0
      src/core/Entity.cpp
  55. 11 0
      src/core/Entity.h
  56. 161 10
      src/core/EntityManager.cpp
  57. 46 0
      src/core/EntityManager.h
  58. 21 3
      src/core/EntityModel.cpp
  59. 2 0
      src/core/EntityModel.h
  60. 8 2
      src/core/MoviePlayer.cpp
  61. 23 0
      src/core/MoviePlayer.h
  62. 3 0
      src/core/ScreenFade.cpp
  63. 19 0
      src/core/ScriptManager.cpp
  64. 8 1
      src/core/ScriptManager.h
  65. 9 0
      src/core/ScriptManagerBinds.h
  66. 5 0
      src/core/UiManager.cpp
  67. 37 4
      src/core/UiTextArea.cpp
  68. 22 1
      src/core/UiTextArea.h
  69. 5 1
      src/core/XmlBackground2DFile.cpp
  70. 9 0
      src/core/XmlEnemyFile.cpp
  71. 4 3
      src/core/XmlFormationFile.cpp
  72. 90 1
      src/installer/BattleCameraScripts.h
  73. 81 7
      src/installer/BattleDataInstaller.cpp
  74. 9 0
      src/installer/BattleDataInstaller.h
  75. 6 0
      src/installer/DataInstaller.cpp
  76. 3 2
      src/installer/FieldDataInstaller.cpp
  77. 12 2
      src/installer/FieldTextWriter.cpp
  78. 268 190
      src/installer/KernelDataInstaller.cpp
  79. 43 1
      src/installer/KernelDataInstaller.h
  80. 31 17
      src/installer/MediaDataInstaller.cpp
  81. 90 29
      src/installer/data/AbFile.cpp
  82. 14 0
      src/installer/data/AbFile.h
  83. 21 30
      src/installer/data/BattleSceneFile.cpp
  84. 12 7
      src/installer/data/Formation.h
  85. 16 16
      src/installer/decompiler/field/FieldDisassembler.cpp
  86. 7 1
      src/installer/decompiler/field/instruction/FieldCameraInstruction.cpp
  87. 40 22
      src/installer/decompiler/field/instruction/FieldControlFlowInstruction.cpp
  88. 26 0
      src/installer/decompiler/field/instruction/FieldMathInstruction.cpp
  89. 7 0
      src/installer/decompiler/field/instruction/FieldMathInstruction.h
  90. 6 1
      src/installer/decompiler/field/instruction/FieldMediaInstruction.cpp
  91. 24 1
      src/installer/decompiler/field/instruction/FieldModuleInstruction.cpp
  92. 8 0
      src/installer/decompiler/field/instruction/FieldModuleInstruction.h
  93. 50 6
      src/installer/decompiler/field/instruction/FieldPartyInstruction.cpp
  94. 16 0
      src/installer/decompiler/field/instruction/FieldPartyInstruction.h
  95. 19 1
      src/installer/decompiler/field/instruction/FieldWalkmeshInstruction.cpp
  96. 2 0
      src/installer/decompiler/field/instruction/FieldWalkmeshInstruction.h
  97. 20 2
      src/installer/decompiler/field/instruction/FieldWindowInstruction.cpp
  98. 2 0
      src/installer/decompiler/field/instruction/FieldWindowInstruction.h
  99. 29 3
      src/modules/worldmap/WorldmapModule.cpp
  100. 4 0
      src/modules/worldmap/WorldmapModule.h

+ 19 - 6
.claude/skills/release/SKILL.md

@@ -20,6 +20,15 @@ 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.
 
+## Requirements
+
+- `gh` (GitHub CLI) installed and logged in (`gh auth status`), for step 9.
+  Check it in the preflight; if missing, warn the user (the release can still be
+  cut, but step 9 can't run).
+- Git push access to all the configured remotes.
+- Build dependencies for `v-gears` and `v-gears-installer` and `cpack` (see
+  `doc/BUILD.md`).
+
 ## 1. Preflight
 
 Run these checks in order.
@@ -31,13 +40,15 @@ Run these checks in order.
 - `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`.
+- `git fetch --all --tags`, then check `develop` is not behind its upstream
+  (`git rev-list --count develop..@{u}` must be 0).
 - 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):
 
+- `gh auth status` fails or `gh` is missing (see Requirements): step 9 can't run.
 - 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
@@ -154,9 +165,11 @@ 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:
+Show the user `git log --oneline --graph -8 --all` and the tag, and list the
+remotes with `git remote -v`. Ask for confirmation to push to **all available
+remotes**, then push to each one in turn. If a push to a remote fails (for
+example it asks for credentials), report it, keep going with the others, and
+don't try to work around it.
 
 ```
 git push <remote> master develop vX.Y.Z
@@ -166,10 +179,10 @@ 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
+Pushing the tag to a GitHub remote 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
+already be on the GitHub remote (step 8) and `gh` to be authenticated
 (`gh auth status`).
 
 Ask the user to confirm, then:

+ 0 - 1
CMake/Packaging.cmake

@@ -24,7 +24,6 @@ install(
         ${CMAKE_SOURCE_DIR}/COPYING.txt
         ${CMAKE_SOURCE_DIR}/doc/AUTHORS.md
         ${CMAKE_SOURCE_DIR}/doc/HISTORY.md
-        ${CMAKE_SOURCE_DIR}/doc/INSTALL.md
         ${CMAKE_SOURCE_DIR}/doc/INSTALL_DATA.md
         ${CMAKE_SOURCE_DIR}/doc/RUN.md
     DESTINATION ${VGEARS_INSTALL_DOCDIR}

+ 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.5 LANGUAGES C CXX)
+project(V-Gears VERSION 0.4.0 LANGUAGES C CXX)
 
 # Provide a central common include for project-wide policies and defaults.
 list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/CMake")

+ 73 - 34
README.md

@@ -1,67 +1,106 @@
 # <img src="v-gears.png" alt="V-Gears" width="50"/> V-Gears
 
-## What is V-Gears? 
+**Final Fantasy VII, running on a new, free engine.**
 
-V-Gears is a free implementation of the game Final Fantasy 7 engine, designed to work with the original game data.
+V-Gears is a reimplementation of the Final Fantasy VII engine. It takes the data from your own PC copy of the game and runs it natively on a modern system, with no emulator in between. The fields, the battles, the menus and the world map are being rebuilt one piece at a time, with open code that anyone can read, fix and extend.
 
-It's designed to run the original game data on modern operating systems, making the game playable without the need of emulators.
+<p align="center">
+  <img src="https://v-gears.inigovalentin.com/img/screenshot/battle.gif" alt="A battle running in V-Gears" width="400"/>
+  <img src="https://v-gears.inigovalentin.com/img/screenshot/worldmap.gif" alt="The world map running in V-Gears" width="400"/>
+</p>
 
-It's free software, and it's designed to be cross-platform. It, of course, doesn't include any copyrighted data from the original game, but it provides an installer to get the required data from your own PC copy of the game.
+> V-Gears contains **no copyrighted data** from the original game. Its installer extracts what it needs, on your machine, from your own disks. All the screenshots on this page are real V-Gears captures, but the models, textures, backgrounds and other art in them belong to the original game and are not distributed here.
 
-It's a continuation of [q-gears](https://github.com/q-gears/q-gears "Q-Gears on Github"), which is an enormous project started by some great people many years ago, with the same purpose as this, but which unfortunately became stalled.
+## How far along is it?
 
-## Current status
+It's a work in progress: there is plenty to see and play, but expect bugs and missing pieces.
 
-Note that, while these are actual screenshots of V-Gears, none of the images, sprites, textures, backgrounds, etc are part of the project. They have been extracted locally from an original Final Fantasy VII game, and are in no way distributed here.
-### Field maps:
+| Part | State | In short |
+|--|--|--|
+| [Field maps](#field-maps) | 🟢 Mostly playable | Almost all maps work, with dialogs, music and videos |
+| [Battles](#battles) | 🟢 Mostly playable | Most commands and spells work; many are still missing their effects |
+| [Menus](#menus) | 🟢 Mostly complete | Items, materia, equipment, party, shops, saving and more |
+| [World map](#world-map) | 🟡 Playable, with bugs | Walk, drive, sail and fly around |
+| Minigames | 🔴 Missing | They are skipped, and the story goes on |
+
+This page describes the current development code, which can be ahead of the latest release. The [changelog](doc/CHANGELOG.md "Changelog") tells what each release brought.
+
+## Field maps
+
+Walk around Midgar and beyond. Most models, animations and script opcodes are converted and running, along with background music, animated backgrounds, random encounters and the original videos. Some maps still have bugs or quirks, and a few can crash the game.
 
-Most of the field maps are working. Some are buggy, some have their own quircks, and some can even crash the whole game, but overall, almost oll of them are playable. Most models, animations and opcodes are extracted and implemented. Background music work, and FMVs can be played
 |**Cloud model**|**Dialogs**|**Animations**|
 |--|--|--|
-|[<img src="https://v-gears.inigovalentin.com/img/screenshot/cloud.png" alt="Cloud model" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/cloud.png "Cloud model")|[<img src="https://v-gears.inigovalentin.com/img/screenshot/dialog.png" alt="dialog" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/dialog.png "Dialogs")|[<img src="https://v-gears.inigovalentin.com/img/screenshot/animations.gif" alt="animation" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/animations.gif "Animations")|
+|[<img src="https://v-gears.inigovalentin.com/img/screenshot/cloud.png" alt="Cloud model" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/cloud.png "Cloud model")|[<img src="https://v-gears.inigovalentin.com/img/screenshot/dialog.png" alt="Dialog" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/dialog.png "Dialogs")|[<img src="https://v-gears.inigovalentin.com/img/screenshot/animations.gif" alt="Animation" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/animations.gif "Animations")|
 |**Transparencies**|**Timers**|**Choices**|
 |[<img src="https://v-gears.inigovalentin.com/img/screenshot/transparent_dialogs.png" alt="Transparency" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/transparent_dialogs.png "Transparency")|[<img src="https://v-gears.inigovalentin.com/img/screenshot/timers.png" alt="Timers" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/timers.png "Timers")|[<img src="https://v-gears.inigovalentin.com/img/screenshot/choices.png" alt="Choices" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/choices.png "Choices")|
 
-### Battle:
-Battles are... playable. Battle models and animations are implemented. The battle commands show according to the equiped materia. Basic attacks and magic are working, and some spell effects are shown. But there is atill a lot to fix: Most formulas, a lot of commands, summons...
-**Battle Flow**|
-|--|
-[<img src="https://v-gears.inigovalentin.com/img/screenshot/battle.gif" alt="Battle Flow" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/battle.gif "Battle Flow")|
+## Battles
+
+Battles are pretty much playable, with the original enemies, formations, models, animations and AI scripts.
 
-### Menus:
+- **Rules:** damage, hit and turn order formulas, checked against the original executable.
+- **Commands:** the battle menu follows the equipped materia, with attacks and magic, Steal, Sense, Throw, Coin, Morph, Manipulate, Mime, Enemy Skill, the W commands and more.
+- **Materia:** linked support materia such as All, Quadra Magic, Counter or Final Attack.
+- **Limit breaks:** the limit bar, learning new techniques and multi-hit attacks.
+- **Spectacle:** the original battle cameras, caster auras, effects for the Fire, Ice, Bolt and Cure spells and some status magic, and the Shiva, Ifrit and Ramuh summons.
 
-All menus are implemented and working. They behave exactly like the originals. 
+Still on the way: effects for the other spells and summons, Cait Sith's and Vincent's special limits, and plenty of fine tuning.
 
-|**Begin**|**Main**|**Name**|
+
+## Menus
+
+Most menus are implemented and behave like the originals: items, magic, materia, equipment, status, order, limits, config, party swapping, shops and saving. A few details are still missing. For example, characters keep their default names, as the name menu is switched off for now.
+
+|**Begin**|**Main**|**Materia**|
 |--|--|--|
-|[<img src="https://v-gears.inigovalentin.com/img/screenshot/begin_menu.png" alt="Begin Menu" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/begin_menu.png "Begin Menu")|[<img src="https://v-gears.inigovalentin.com/img/screenshot/main_menu.png" alt="Main Menu" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/main_menu.png "Main Menu")|[<img src="https://v-gears.inigovalentin.com/img/screenshot/name_menu.png" alt="Name Menu" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/name_menu.png "Name Menu")|
-|**Items**|**Key Items**|**Equip**|
-|[<img src="https://v-gears.inigovalentin.com/img/screenshot/item_menu.png" alt="Item Menu" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/item_menu.png "Item Menu")|[<img src="https://v-gears.inigovalentin.com/img/screenshot/item_menu_key.png" alt="Key items menuy" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/item_menu_key.png "Key items menu")|[<img src="https://v-gears.inigovalentin.com/img/screenshot/equip_menu.png" alt="Equip Menu" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/equip_menu.png "Equip Menu")|
-|**Materia**|||
-|[<img src="https://v-gears.inigovalentin.com/img/screenshot/materia_menu.png" alt="Materia Menu" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/materia_menu.png "Materia Menu")|[<img src="https://v-gears.inigovalentin.com/img/screenshot/save_menu.png" alt="Save Menu" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/save_menu.png "Save Menu")||
+|[<img src="https://v-gears.inigovalentin.com/img/screenshot/begin_menu.png" alt="Begin menu" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/begin_menu.png "Begin Menu")|[<img src="https://v-gears.inigovalentin.com/img/screenshot/main_menu.png" alt="Main menu" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/main_menu.png "Main Menu")|[<img src="https://v-gears.inigovalentin.com/img/screenshot/materia_menu.png" alt="Materia menu" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/materia_menu.png "Materia Menu")|
+|**Items**|**Save**|**Equip**|
+|[<img src="https://v-gears.inigovalentin.com/img/screenshot/item_menu.png" alt="Item menu" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/item_menu.png "Item Menu")|[<img src="https://v-gears.inigovalentin.com/img/screenshot/save_menu.png" alt="Save menu" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/save_menu.png "Save Menu")|[<img src="https://v-gears.inigovalentin.com/img/screenshot/equip_menu.png" alt="Equip menu" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/equip_menu.png "Equip Menu")|
 
-### World map:
 
-The world map is bareli playable. The world map models are extracted and can be displayed. The world map is navigable, and most cities can be entered. Most vehicles are implemented and can be used, but there are still a number of bugs
+## World map
 
-|**Worldmap**|**Dialogs**|**Animations**|
+The world map is playable, and it runs on the original world scripts, so it follows your progress in the story. Explore the overworld, the depths of the ocean and the snowfield: walk, enter most cities, get into fights, and travel by chocobo, buggy, Tiny Bronco, submarine or airship, with animated water, fog, snow and changing music. There are still a number of bugs and some unfinished scenes.
+
+|**World map**|**The Highwind**|**On the move**|
 |--|--|--|
-|[<img src="https://v-gears.inigovalentin.com/img/screenshot/world_map.png" alt="The worldmap and the vehicles" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/world_map.png "The worldmap and the vehicles")|[<img src="https://v-gears.inigovalentin.com/img/screenshot/highwind.png" alt="The Highwind, mid-flight" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/highwind.png "The Highwind, mid-flight")|[<img src="https://v-gears.inigovalentin.com/img/screenshot/worldmap.gif" alt="World map working" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/worldmap.gif "World map working")| 
+|[<img src="https://v-gears.inigovalentin.com/img/screenshot/world_map.png" alt="The world map and the vehicles" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/world_map.png "The world map and the vehicles")|[<img src="https://v-gears.inigovalentin.com/img/screenshot/highwind.png" alt="The Highwind, mid-flight" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/highwind.png "The Highwind, mid-flight")|[<img src="https://v-gears.inigovalentin.com/img/screenshot/worldmap.gif" alt="World map working" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/worldmap.gif "World map working")|
+
+## The installer
 
-### Installer:
-The installer is the tool that extract the data from the original game
-|**Installer**|**Advanced**|
+The installer turns your copy of the game into data that V-Gears can use. Point it to the ISO image of the PC install disk, choose a folder, and let it work. It converts the sounds, the music and the videos (with the help of FFmpeg and TiMidity; the videos come from the three game disks), and then it can verify the result and launch the game.
+
+|**Installer**|**Advanced options**|
 |--|--|
 |[<img src="https://v-gears.inigovalentin.com/img/screenshot/installer.png" alt="Installer" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/installer.png "Installer")|[<img src="https://v-gears.inigovalentin.com/img/screenshot/installer_advanced.png" alt="Advanced options" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/installer_advanced.png "Advanced options")|
 
-### Debug Tools
+## Under the hood
+
+V-Gears is written in C++14, with [Ogre](https://www.ogre3d.org/ "Ogre") for the graphics and LuaJIT for the scripts. The original field and world scripts are decompiled into Lua during the installation, and the battles and menus are written in Lua too, so a lot of the game can be read and changed without recompiling.
+
+When the original behaviour isn't documented, it is worked out from the game itself: damage formulas, camera scripts, summon effects and more come from studying the original executable and data files.
+
+Debug tools help to see what is going on:
+
 |**Field maps**|**Walkmesh**|**Console**|
 |--|--|--|
 |[<img src="https://v-gears.inigovalentin.com/img/screenshot/debug_dialog.png" alt="Debug fields" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/debug_dialog.png "Debug Fields")|[<img src="https://v-gears.inigovalentin.com/img/screenshot/walkmesh.png" alt="Walkmesh" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/walkmesh.png "Walkmesh")|[<img src="https://v-gears.inigovalentin.com/img/screenshot/console.png" alt="Console" width="250"/>](https://v-gears.inigovalentin.com/img/screenshot/console.png "Console")|
 
-## In the meantime...
+## Try it
+
+You need your own copy of the PC version of Final Fantasy VII, as disk images. The guides cover Linux.
+
+1. **Get V-Gears:** download a package from the [releases](https://github.com/InigoValentin/V-Gears/releases "Releases") (they only work on systems with the same library versions as the one they were built on), or [build it yourself](doc/BUILD.md "Building guide").
+2. **Add the game data** with `v-gears-installer`, following the [data installation guide](doc/INSTALL_DATA.md "Data installation guide").
+3. **Play:** start `v-gears`. The [run guide](doc/RUN.md "Run guide") lists the controls.
+
+## A bit of history
+
+V-Gears continues [Q-Gears](https://github.com/q-gears/q-gears "Q-Gears on Github"), an enormous project started in 2006 by some great people with the same purpose, which unfortunately stalled. Read the [whole story](doc/HISTORY.md "V-Gears history").
 
-If it picked your curiosity, you can check out the [history](doc/HISTORY.md "V-Gears history") behind the project. Or, if you want to try it for yourself, maybe the [build](doc/BUILD.md "Building guide") and [installaton](doc/INSTALL.md "Installation guide") guides are a good place to start.
+## Join in
 
-Or even better, if you want to see this done and want to contribute, clone the repo, read the [style guide](doc/STYLE.md "V-Gears C++ Style Guide") and have a go at it!
+If you want to see this finished, help is welcome. Clone the repo, read the [C++](doc/STYLE.md "V-Gears C++ Style Guide") and [Lua](doc/STYLE-LUA.md "V-Gears Lua Style Guide") style guides, pick something from the [to-do list](doc/TODO.md "To-do list") (or whatever breaks first when you play), and have a go at it!
 
+V-Gears is free software, released under the [GNU General Public License v3](COPYING.txt "License").

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

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

+ 258 - 0
data/data/screens/exchange_menu/exchange_menu.xml

@@ -0,0 +1,258 @@
+<screen name="ExchangeMenu" script="scripts/menu/exchange_menu.lua" visible="false">
+    <sprite name="Background" x="0" y="0" width="100%" height="100%" colour="0 0 0" visible="true"/>
+    <widget name="Container" width="40%" height="40%" x="0" y="0" align="left" valign="top" scale="2.5 2.5" visible="true">
+        <widget name="Info" x="0" y="0" width="100%" height="28" visible="true">
+            <prototype name="Window" />
+            <sprite name="Icon" image="icons/materia_1.png" x="10" y="6" width="16" height="16" visible="false"/>
+            <text_area name="Name" x="32" y="8" font="FFVIIFont" visible="false" />
+            <widget name="Stars" x="100%-190" y="7" width="90" height="16" visible="true">
+                <sprite name="Star1" image="icons/materia_star_1.png" x="0" y="0" width="15" height="15" visible="false"/>
+                <sprite name="Star2" image="icons/materia_star_1.png" x="16" y="0" width="15" height="15" visible="false"/>
+                <sprite name="Star3" image="icons/materia_star_1.png" x="32" y="0" width="15" height="15" visible="false"/>
+                <sprite name="Star4" image="icons/materia_star_1.png" x="48" y="0" width="15" height="15" visible="false"/>
+                <sprite name="Star5" image="icons/materia_star_1.png" x="64" y="0" width="15" height="15" visible="false"/>
+            </widget>
+        </widget>
+        <widget name="Help" x="0" y="28" width="100%" height="24" visible="true">
+            <prototype name="Window" />
+            <text_area name="Help" x="16" y="6" font="FFVIIFont" visible="true" />
+        </widget>
+        <widget name="Title" x="100%-86" y="0" width="86" height="24" visible="true">
+            <prototype name="Window" />
+            <text_area name="Title" x="16" y="6" text_name="MateriaMenuTitle" font="FFVIIFont" visible="true" />
+        </widget>
+        <widget name="Characters" x="0" y="52" width="66%" height="100%-52" visible="true">
+            <sprite name="ScrollBg" x="100%-10" y="2" width="8" height="100%-6" colour="0.2 0.2 0.2" alpha="0.8" visible="true"/>
+            <sprite name="Scroll" x="100%-9" y="3" width="6" height="18" colour="0.7 0.7 0.7" visible="true"/>
+            <widget name="Block1" x="0" y="0" width="100%-12" height="58" visible="false">
+                <prototype name="Window" />
+                <sprite name="Portrait" image="other/choco.png" x="8" y="12" width="26" height="29" visible="true"/>
+                <text_area name="Name" x="40" y="6" font="FFVIIFont" visible="true" />
+                <sprite name="WIcon" image="icons/item_weapon_0.png" x="40" y="22" width="14" height="14" visible="true"/>
+                <sprite name="AIcon" image="icons/item_armor.png" x="40" y="39" width="14" height="14" visible="true"/>
+                <sprite name="WSlot1" image="icons/materia_slot.png" x="70" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot2" image="icons/materia_slot.png" x="86" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot3" image="icons/materia_slot.png" x="102" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot4" image="icons/materia_slot.png" x="118" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot5" image="icons/materia_slot.png" x="134" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot6" image="icons/materia_slot.png" x="150" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot7" image="icons/materia_slot.png" x="166" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot8" image="icons/materia_slot.png" x="182" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WLink1" image="icons/materia_slot_link.png" x="81" y="22" width="8" height="14" visible="false"/>
+                <sprite name="WLink2" image="icons/materia_slot_link.png" x="113" y="22" width="8" height="14" visible="false"/>
+                <sprite name="WLink3" image="icons/materia_slot_link.png" x="145" y="22" width="8" height="14" visible="false"/>
+                <sprite name="WLink4" image="icons/materia_slot_link.png" x="177" y="22" width="8" height="14" visible="false"/>
+                <sprite name="WMat1" image="icons/materia_1.png" x="72" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat2" image="icons/materia_1.png" x="88" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat3" image="icons/materia_1.png" x="104" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat4" image="icons/materia_1.png" x="120" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat5" image="icons/materia_1.png" x="136" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat6" image="icons/materia_1.png" x="152" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat7" image="icons/materia_1.png" x="168" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat8" image="icons/materia_1.png" x="184" y="24" width="10" height="10" visible="false"/>
+                <sprite name="ASlot1" image="icons/materia_slot.png" x="70" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot2" image="icons/materia_slot.png" x="86" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot3" image="icons/materia_slot.png" x="102" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot4" image="icons/materia_slot.png" x="118" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot5" image="icons/materia_slot.png" x="134" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot6" image="icons/materia_slot.png" x="150" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot7" image="icons/materia_slot.png" x="166" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot8" image="icons/materia_slot.png" x="182" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ALink1" image="icons/materia_slot_link.png" x="81" y="39" width="8" height="14" visible="false"/>
+                <sprite name="ALink2" image="icons/materia_slot_link.png" x="113" y="39" width="8" height="14" visible="false"/>
+                <sprite name="ALink3" image="icons/materia_slot_link.png" x="145" y="39" width="8" height="14" visible="false"/>
+                <sprite name="ALink4" image="icons/materia_slot_link.png" x="177" y="39" width="8" height="14" visible="false"/>
+                <sprite name="AMat1" image="icons/materia_1.png" x="72" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat2" image="icons/materia_1.png" x="88" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat3" image="icons/materia_1.png" x="104" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat4" image="icons/materia_1.png" x="120" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat5" image="icons/materia_1.png" x="136" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat6" image="icons/materia_1.png" x="152" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat7" image="icons/materia_1.png" x="168" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat8" image="icons/materia_1.png" x="184" y="41" width="10" height="10" visible="false"/>
+            </widget>
+            <widget name="Block2" x="0" y="58" width="100%-12" height="58" visible="false">
+                <prototype name="Window" />
+                <sprite name="Portrait" image="other/choco.png" x="8" y="12" width="26" height="29" visible="true"/>
+                <text_area name="Name" x="40" y="6" font="FFVIIFont" visible="true" />
+                <sprite name="WIcon" image="icons/item_weapon_0.png" x="40" y="22" width="14" height="14" visible="true"/>
+                <sprite name="AIcon" image="icons/item_armor.png" x="40" y="39" width="14" height="14" visible="true"/>
+                <sprite name="WSlot1" image="icons/materia_slot.png" x="70" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot2" image="icons/materia_slot.png" x="86" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot3" image="icons/materia_slot.png" x="102" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot4" image="icons/materia_slot.png" x="118" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot5" image="icons/materia_slot.png" x="134" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot6" image="icons/materia_slot.png" x="150" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot7" image="icons/materia_slot.png" x="166" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot8" image="icons/materia_slot.png" x="182" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WLink1" image="icons/materia_slot_link.png" x="81" y="22" width="8" height="14" visible="false"/>
+                <sprite name="WLink2" image="icons/materia_slot_link.png" x="113" y="22" width="8" height="14" visible="false"/>
+                <sprite name="WLink3" image="icons/materia_slot_link.png" x="145" y="22" width="8" height="14" visible="false"/>
+                <sprite name="WLink4" image="icons/materia_slot_link.png" x="177" y="22" width="8" height="14" visible="false"/>
+                <sprite name="WMat1" image="icons/materia_1.png" x="72" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat2" image="icons/materia_1.png" x="88" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat3" image="icons/materia_1.png" x="104" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat4" image="icons/materia_1.png" x="120" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat5" image="icons/materia_1.png" x="136" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat6" image="icons/materia_1.png" x="152" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat7" image="icons/materia_1.png" x="168" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat8" image="icons/materia_1.png" x="184" y="24" width="10" height="10" visible="false"/>
+                <sprite name="ASlot1" image="icons/materia_slot.png" x="70" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot2" image="icons/materia_slot.png" x="86" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot3" image="icons/materia_slot.png" x="102" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot4" image="icons/materia_slot.png" x="118" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot5" image="icons/materia_slot.png" x="134" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot6" image="icons/materia_slot.png" x="150" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot7" image="icons/materia_slot.png" x="166" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot8" image="icons/materia_slot.png" x="182" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ALink1" image="icons/materia_slot_link.png" x="81" y="39" width="8" height="14" visible="false"/>
+                <sprite name="ALink2" image="icons/materia_slot_link.png" x="113" y="39" width="8" height="14" visible="false"/>
+                <sprite name="ALink3" image="icons/materia_slot_link.png" x="145" y="39" width="8" height="14" visible="false"/>
+                <sprite name="ALink4" image="icons/materia_slot_link.png" x="177" y="39" width="8" height="14" visible="false"/>
+                <sprite name="AMat1" image="icons/materia_1.png" x="72" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat2" image="icons/materia_1.png" x="88" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat3" image="icons/materia_1.png" x="104" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat4" image="icons/materia_1.png" x="120" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat5" image="icons/materia_1.png" x="136" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat6" image="icons/materia_1.png" x="152" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat7" image="icons/materia_1.png" x="168" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat8" image="icons/materia_1.png" x="184" y="41" width="10" height="10" visible="false"/>
+            </widget>
+            <widget name="Block3" x="0" y="116" width="100%-12" height="58" visible="false">
+                <prototype name="Window" />
+                <sprite name="Portrait" image="other/choco.png" x="8" y="12" width="26" height="29" visible="true"/>
+                <text_area name="Name" x="40" y="6" font="FFVIIFont" visible="true" />
+                <sprite name="WIcon" image="icons/item_weapon_0.png" x="40" y="22" width="14" height="14" visible="true"/>
+                <sprite name="AIcon" image="icons/item_armor.png" x="40" y="39" width="14" height="14" visible="true"/>
+                <sprite name="WSlot1" image="icons/materia_slot.png" x="70" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot2" image="icons/materia_slot.png" x="86" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot3" image="icons/materia_slot.png" x="102" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot4" image="icons/materia_slot.png" x="118" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot5" image="icons/materia_slot.png" x="134" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot6" image="icons/materia_slot.png" x="150" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot7" image="icons/materia_slot.png" x="166" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot8" image="icons/materia_slot.png" x="182" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WLink1" image="icons/materia_slot_link.png" x="81" y="22" width="8" height="14" visible="false"/>
+                <sprite name="WLink2" image="icons/materia_slot_link.png" x="113" y="22" width="8" height="14" visible="false"/>
+                <sprite name="WLink3" image="icons/materia_slot_link.png" x="145" y="22" width="8" height="14" visible="false"/>
+                <sprite name="WLink4" image="icons/materia_slot_link.png" x="177" y="22" width="8" height="14" visible="false"/>
+                <sprite name="WMat1" image="icons/materia_1.png" x="72" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat2" image="icons/materia_1.png" x="88" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat3" image="icons/materia_1.png" x="104" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat4" image="icons/materia_1.png" x="120" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat5" image="icons/materia_1.png" x="136" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat6" image="icons/materia_1.png" x="152" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat7" image="icons/materia_1.png" x="168" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat8" image="icons/materia_1.png" x="184" y="24" width="10" height="10" visible="false"/>
+                <sprite name="ASlot1" image="icons/materia_slot.png" x="70" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot2" image="icons/materia_slot.png" x="86" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot3" image="icons/materia_slot.png" x="102" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot4" image="icons/materia_slot.png" x="118" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot5" image="icons/materia_slot.png" x="134" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot6" image="icons/materia_slot.png" x="150" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot7" image="icons/materia_slot.png" x="166" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot8" image="icons/materia_slot.png" x="182" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ALink1" image="icons/materia_slot_link.png" x="81" y="39" width="8" height="14" visible="false"/>
+                <sprite name="ALink2" image="icons/materia_slot_link.png" x="113" y="39" width="8" height="14" visible="false"/>
+                <sprite name="ALink3" image="icons/materia_slot_link.png" x="145" y="39" width="8" height="14" visible="false"/>
+                <sprite name="ALink4" image="icons/materia_slot_link.png" x="177" y="39" width="8" height="14" visible="false"/>
+                <sprite name="AMat1" image="icons/materia_1.png" x="72" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat2" image="icons/materia_1.png" x="88" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat3" image="icons/materia_1.png" x="104" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat4" image="icons/materia_1.png" x="120" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat5" image="icons/materia_1.png" x="136" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat6" image="icons/materia_1.png" x="152" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat7" image="icons/materia_1.png" x="168" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat8" image="icons/materia_1.png" x="184" y="41" width="10" height="10" visible="false"/>
+            </widget>
+            <widget name="Block4" x="0" y="174" width="100%-12" height="58" visible="false">
+                <prototype name="Window" />
+                <sprite name="Portrait" image="other/choco.png" x="8" y="12" width="26" height="29" visible="true"/>
+                <text_area name="Name" x="40" y="6" font="FFVIIFont" visible="true" />
+                <sprite name="WIcon" image="icons/item_weapon_0.png" x="40" y="22" width="14" height="14" visible="true"/>
+                <sprite name="AIcon" image="icons/item_armor.png" x="40" y="39" width="14" height="14" visible="true"/>
+                <sprite name="WSlot1" image="icons/materia_slot.png" x="70" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot2" image="icons/materia_slot.png" x="86" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot3" image="icons/materia_slot.png" x="102" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot4" image="icons/materia_slot.png" x="118" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot5" image="icons/materia_slot.png" x="134" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot6" image="icons/materia_slot.png" x="150" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot7" image="icons/materia_slot.png" x="166" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WSlot8" image="icons/materia_slot.png" x="182" y="22" width="14" height="14" visible="false"/>
+                <sprite name="WLink1" image="icons/materia_slot_link.png" x="81" y="22" width="8" height="14" visible="false"/>
+                <sprite name="WLink2" image="icons/materia_slot_link.png" x="113" y="22" width="8" height="14" visible="false"/>
+                <sprite name="WLink3" image="icons/materia_slot_link.png" x="145" y="22" width="8" height="14" visible="false"/>
+                <sprite name="WLink4" image="icons/materia_slot_link.png" x="177" y="22" width="8" height="14" visible="false"/>
+                <sprite name="WMat1" image="icons/materia_1.png" x="72" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat2" image="icons/materia_1.png" x="88" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat3" image="icons/materia_1.png" x="104" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat4" image="icons/materia_1.png" x="120" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat5" image="icons/materia_1.png" x="136" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat6" image="icons/materia_1.png" x="152" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat7" image="icons/materia_1.png" x="168" y="24" width="10" height="10" visible="false"/>
+                <sprite name="WMat8" image="icons/materia_1.png" x="184" y="24" width="10" height="10" visible="false"/>
+                <sprite name="ASlot1" image="icons/materia_slot.png" x="70" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot2" image="icons/materia_slot.png" x="86" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot3" image="icons/materia_slot.png" x="102" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot4" image="icons/materia_slot.png" x="118" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot5" image="icons/materia_slot.png" x="134" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot6" image="icons/materia_slot.png" x="150" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot7" image="icons/materia_slot.png" x="166" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ASlot8" image="icons/materia_slot.png" x="182" y="39" width="14" height="14" visible="false"/>
+                <sprite name="ALink1" image="icons/materia_slot_link.png" x="81" y="39" width="8" height="14" visible="false"/>
+                <sprite name="ALink2" image="icons/materia_slot_link.png" x="113" y="39" width="8" height="14" visible="false"/>
+                <sprite name="ALink3" image="icons/materia_slot_link.png" x="145" y="39" width="8" height="14" visible="false"/>
+                <sprite name="ALink4" image="icons/materia_slot_link.png" x="177" y="39" width="8" height="14" visible="false"/>
+                <sprite name="AMat1" image="icons/materia_1.png" x="72" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat2" image="icons/materia_1.png" x="88" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat3" image="icons/materia_1.png" x="104" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat4" image="icons/materia_1.png" x="120" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat5" image="icons/materia_1.png" x="136" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat6" image="icons/materia_1.png" x="152" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat7" image="icons/materia_1.png" x="168" y="41" width="10" height="10" visible="false"/>
+                <sprite name="AMat8" image="icons/materia_1.png" x="184" y="41" width="10" height="10" visible="false"/>
+            </widget>
+            <sprite name="Cursor" image="icons/cursor.png" x="48" y="18" width="24" height="17" visible="false"/>
+            <sprite name="Held" image="icons/cursor.png" x="48" y="18" width="24" height="17" visible="false">
+                <animation name="Blink" length="0.4" alpha="0:1, 0.2:1, 0.21:0, 0.39:0, 0.4:1" />
+            </sprite>
+        </widget>
+        <widget name="Inventory" x="66%" y="52" width="34%" height="100%-52" visible="true">
+            <prototype name="Window" />
+            <sprite name="ScrollBg" x="100%-12" y="2" width="10" height="100%-6" colour="0.2 0.2 0.2" alpha="0.8" visible="true"/>
+            <sprite name="Scroll" x="100%-11" y="3" width="8" height="18" colour="0.7 0.7 0.7" visible="true"/>
+            <sprite name="Icon1" image="icons/materia_1.png" x="8" y="7" width="12" height="12" visible="false"/>
+            <text_area name="Name1" x="24" y="6" font="FFVIIFont" visible="false" />
+            <sprite name="Icon2" image="icons/materia_1.png" x="8" y="23" width="12" height="12" visible="false"/>
+            <text_area name="Name2" x="24" y="22" font="FFVIIFont" visible="false" />
+            <sprite name="Icon3" image="icons/materia_1.png" x="8" y="39" width="12" height="12" visible="false"/>
+            <text_area name="Name3" x="24" y="38" font="FFVIIFont" visible="false" />
+            <sprite name="Icon4" image="icons/materia_1.png" x="8" y="55" width="12" height="12" visible="false"/>
+            <text_area name="Name4" x="24" y="54" font="FFVIIFont" visible="false" />
+            <sprite name="Icon5" image="icons/materia_1.png" x="8" y="71" width="12" height="12" visible="false"/>
+            <text_area name="Name5" x="24" y="70" font="FFVIIFont" visible="false" />
+            <sprite name="Icon6" image="icons/materia_1.png" x="8" y="87" width="12" height="12" visible="false"/>
+            <text_area name="Name6" x="24" y="86" font="FFVIIFont" visible="false" />
+            <sprite name="Icon7" image="icons/materia_1.png" x="8" y="103" width="12" height="12" visible="false"/>
+            <text_area name="Name7" x="24" y="102" font="FFVIIFont" visible="false" />
+            <sprite name="Icon8" image="icons/materia_1.png" x="8" y="119" width="12" height="12" visible="false"/>
+            <text_area name="Name8" x="24" y="118" font="FFVIIFont" visible="false" />
+            <sprite name="Icon9" image="icons/materia_1.png" x="8" y="135" width="12" height="12" visible="false"/>
+            <text_area name="Name9" x="24" y="134" font="FFVIIFont" visible="false" />
+            <sprite name="Icon10" image="icons/materia_1.png" x="8" y="151" width="12" height="12" visible="false"/>
+            <text_area name="Name10" x="24" y="150" font="FFVIIFont" visible="false" />
+            <sprite name="Icon11" image="icons/materia_1.png" x="8" y="167" width="12" height="12" visible="false"/>
+            <text_area name="Name11" x="24" y="166" font="FFVIIFont" visible="false" />
+            <sprite name="Icon12" image="icons/materia_1.png" x="8" y="183" width="12" height="12" visible="false"/>
+            <text_area name="Name12" x="24" y="182" font="FFVIIFont" visible="false" />
+            <sprite name="Icon13" image="icons/materia_1.png" x="8" y="199" width="12" height="12" visible="false"/>
+            <text_area name="Name13" x="24" y="198" font="FFVIIFont" visible="false" />
+            <sprite name="Icon14" image="icons/materia_1.png" x="8" y="215" width="12" height="12" visible="false"/>
+            <text_area name="Name14" x="24" y="214" font="FFVIIFont" visible="false" />
+            <sprite name="Cursor" image="icons/cursor.png" x="-8" y="5" width="24" height="17" visible="false"/>
+            <sprite name="Held" image="icons/cursor.png" x="-8" y="5" width="24" height="17" visible="false">
+                <animation name="Blink" length="0.4" alpha="0:1, 0.2:1, 0.21:0, 0.39:0, 0.4:1" />
+            </sprite>
+        </widget>
+    </widget>
+</screen>

+ 15 - 0
data/data/screens/item_menu/item_menu.xml

@@ -136,6 +136,21 @@
                 <animation name="Position12" length="0" y="0:82%+2" />
                 <animation name="Position13" length="0" y="0:89%+2" />
             </sprite>
+            <sprite name="Held" image="icons/cursor.png" x="-11" y="5%+2" width="24" height="17" visible="false">
+                <animation name="Blink1" length="0.4" y="0:5%+2" alpha="0:1, 0.2:1, 0.21:0, 0.39:0, 0.4:1" />
+                <animation name="Blink2" length="0.4" y="0:12%+2" alpha="0:1, 0.2:1, 0.21:0, 0.39:0, 0.4:1" />
+                <animation name="Blink3" length="0.4" y="0:19%+2" alpha="0:1, 0.2:1, 0.21:0, 0.39:0, 0.4:1" />
+                <animation name="Blink4" length="0.4" y="0:26%+2" alpha="0:1, 0.2:1, 0.21:0, 0.39:0, 0.4:1" />
+                <animation name="Blink5" length="0.4" y="0:33%+2" alpha="0:1, 0.2:1, 0.21:0, 0.39:0, 0.4:1" />
+                <animation name="Blink6" length="0.4" y="0:40%+2" alpha="0:1, 0.2:1, 0.21:0, 0.39:0, 0.4:1" />
+                <animation name="Blink7" length="0.4" y="0:47%+2" alpha="0:1, 0.2:1, 0.21:0, 0.39:0, 0.4:1" />
+                <animation name="Blink8" length="0.4" y="0:54%+2" alpha="0:1, 0.2:1, 0.21:0, 0.39:0, 0.4:1" />
+                <animation name="Blink9" length="0.4" y="0:61%+2" alpha="0:1, 0.2:1, 0.21:0, 0.39:0, 0.4:1" />
+                <animation name="Blink10" length="0.4" y="0:68%+2" alpha="0:1, 0.2:1, 0.21:0, 0.39:0, 0.4:1" />
+                <animation name="Blink11" length="0.4" y="0:75%+2" alpha="0:1, 0.2:1, 0.21:0, 0.39:0, 0.4:1" />
+                <animation name="Blink12" length="0.4" y="0:82%+2" alpha="0:1, 0.2:1, 0.21:0, 0.39:0, 0.4:1" />
+                <animation name="Blink13" length="0.4" y="0:89%+2" alpha="0:1, 0.2:1, 0.21:0, 0.39:0, 0.4:1" />
+            </sprite>
 
 
         </widget>

+ 5 - 0
data/data/screens/main_menu/main_menu.xml

@@ -63,6 +63,11 @@
                 <animation name="Position2" length="0" y="0:32%+40" />
                 <animation name="Position3" length="0" y="0:62%+40" />
             </sprite>
+            <sprite name="Held" image="icons/cursor.png" x="0" y="2%+40" width="24" height="16" visible="false">
+                <animation name="Blink1" length="0.4" y="0:2%+40" alpha="0:1, 0.2:1, 0.21:0, 0.39:0, 0.4:1" />
+                <animation name="Blink2" length="0.4" y="0:32%+40" alpha="0:1, 0.2:1, 0.21:0, 0.39:0, 0.4:1" />
+                <animation name="Blink3" length="0.4" y="0:62%+40" alpha="0:1, 0.2:1, 0.21:0, 0.39:0, 0.4:1" />
+            </sprite>
         </widget>
         <widget name="Menu" x="100%-105" y="2%" width="90" height="144" visible="true">
             <prototype name="Window" />

+ 87 - 2
data/data/screens/materia_menu/materia_menu.xml

@@ -90,9 +90,34 @@
             <widget name="Empty" x="0" y ="0" width="100%" height="100%" visible="false">
             </widget>
             <widget name="Commands" x="0" y ="0" width="100%" height="100%" visible="false">
-                <widget name="Box" x="20" y ="20" width="100%-40" height="60" visible="true">
+                <widget name="Box" x="4" y="12" width="100%-8" height="88" visible="true">
                     <prototype name="Window" />
-                    <!-- TODO -->
+                    <text_area name="Command1" x="20" y="8" font="FFVIIFont" visible="false" />
+                    <text_area name="Command2" x="20" y="26" font="FFVIIFont" visible="false" />
+                    <text_area name="Command3" x="20" y="44" font="FFVIIFont" visible="false" />
+                    <text_area name="Command4" x="20" y="62" font="FFVIIFont" visible="false" />
+                    <text_area name="Command5" x="88" y="8" font="FFVIIFont" visible="false" />
+                    <text_area name="Command6" x="88" y="26" font="FFVIIFont" visible="false" />
+                    <text_area name="Command7" x="88" y="44" font="FFVIIFont" visible="false" />
+                    <text_area name="Command8" x="88" y="62" font="FFVIIFont" visible="false" />
+                    <text_area name="Command9" x="156" y="8" font="FFVIIFont" visible="false" />
+                    <text_area name="Command10" x="156" y="26" font="FFVIIFont" visible="false" />
+                    <text_area name="Command11" x="156" y="44" font="FFVIIFont" visible="false" />
+                    <text_area name="Command12" x="156" y="62" font="FFVIIFont" visible="false" />
+                    <sprite name="Cursor" image="icons/cursor.png" x="3" y="10" width="24" height="17" visible="false">
+                        <animation name="Position1" length="0" x="0:3" y="0:10" />
+                        <animation name="Position2" length="0" x="0:3" y="0:28" />
+                        <animation name="Position3" length="0" x="0:3" y="0:46" />
+                        <animation name="Position4" length="0" x="0:3" y="0:64" />
+                        <animation name="Position5" length="0" x="0:71" y="0:10" />
+                        <animation name="Position6" length="0" x="0:71" y="0:28" />
+                        <animation name="Position7" length="0" x="0:71" y="0:46" />
+                        <animation name="Position8" length="0" x="0:71" y="0:64" />
+                        <animation name="Position9" length="0" x="0:139" y="0:10" />
+                        <animation name="Position10" length="0" x="0:139" y="0:28" />
+                        <animation name="Position11" length="0" x="0:139" y="0:46" />
+                        <animation name="Position12" length="0" x="0:139" y="0:64" />
+                    </sprite>
                 </widget>
             </widget>
             <widget name="EnemySkill" x="0" y ="0" width="100%" height="100%" visible="false">
@@ -229,5 +254,65 @@
                 <animation name="Position10" length="0" y="0:85%+3" />
             </sprite>
         </widget>
+        <widget name="Abilities" x="230" y="99" width="100%-230" height="100%-99" visible="false">
+            <prototype name="Window" />
+            <text_area name="Name1" x="20" y="4%" font="FFVIIFont" visible="true" />
+            <text_area name="Mp1" x="100%-48" y="4%" font="FFVIIMenuDigits" visible="true" />
+            <text_area name="Name2" x="20" y="13%" font="FFVIIFont" visible="true" />
+            <text_area name="Mp2" x="100%-48" y="13%" font="FFVIIMenuDigits" visible="true" />
+            <text_area name="Name3" x="20" y="22%" font="FFVIIFont" visible="true" />
+            <text_area name="Mp3" x="100%-48" y="22%" font="FFVIIMenuDigits" visible="true" />
+            <text_area name="Name4" x="20" y="31%" font="FFVIIFont" visible="true" />
+            <text_area name="Mp4" x="100%-48" y="31%" font="FFVIIMenuDigits" visible="true" />
+            <text_area name="Name5" x="20" y="40%" font="FFVIIFont" visible="true" />
+            <text_area name="Mp5" x="100%-48" y="40%" font="FFVIIMenuDigits" visible="true" />
+            <text_area name="Name6" x="20" y="49%" font="FFVIIFont" visible="true" />
+            <text_area name="Mp6" x="100%-48" y="49%" font="FFVIIMenuDigits" visible="true" />
+            <text_area name="Name7" x="20" y="58%" font="FFVIIFont" visible="true" />
+            <text_area name="Mp7" x="100%-48" y="58%" font="FFVIIMenuDigits" visible="true" />
+            <text_area name="Name8" x="20" y="67%" font="FFVIIFont" visible="true" />
+            <text_area name="Mp8" x="100%-48" y="67%" font="FFVIIMenuDigits" visible="true" />
+            <text_area name="Name9" x="20" y="76%" font="FFVIIFont" visible="true" />
+            <text_area name="Mp9" x="100%-48" y="76%" font="FFVIIMenuDigits" visible="true" />
+            <text_area name="Name10" x="20" y="85%" font="FFVIIFont" visible="true" />
+            <text_area name="Mp10" x="100%-48" y="85%" font="FFVIIMenuDigits" visible="true" />
+            <sprite name="Cursor" image="icons/cursor.png" x="-15" y="8" width="24" height="17" visible="true">
+                <animation name="Position1" length="0" y="0:4%+3" />
+                <animation name="Position2" length="0" y="0:13%+3" />
+                <animation name="Position3" length="0" y="0:22%+3" />
+                <animation name="Position4" length="0" y="0:31%+3" />
+                <animation name="Position5" length="0" y="0:40%+3" />
+                <animation name="Position6" length="0" y="0:49%+3" />
+                <animation name="Position7" length="0" y="0:58%+3" />
+                <animation name="Position8" length="0" y="0:67%+3" />
+                <animation name="Position9" length="0" y="0:76%+3" />
+                <animation name="Position10" length="0" y="0:85%+3" />
+            </sprite>
+        </widget>
+        <widget name="OrderMenu" x="170" y="2" width="108" height="84" visible="false">
+            <prototype name="Window" />
+            <text_area name="Item1" text_name="MateriaMenuArrange" x="20" y="6" font="FFVIIFont" visible="true" />
+            <text_area name="Item2" text_name="MateriaMenuExchange" x="20" y="24" font="FFVIIFont" visible="true" />
+            <text_area name="Item3" text_name="MateriaMenuRemoveAll" x="20" y="42" font="FFVIIFont" visible="true" />
+            <text_area name="Item4" text_name="MateriaMenuTrash" x="20" y="60" font="FFVIIFont" visible="true" />
+            <sprite name="Cursor" image="icons/cursor.png" x="-8" y="8" width="24" height="17" visible="true">
+                <animation name="Position1" length="0" y="0:8" />
+                <animation name="Position2" length="0" y="0:26" />
+                <animation name="Position3" length="0" y="0:44" />
+                <animation name="Position4" length="0" y="0:62" />
+            </sprite>
+        </widget>
+        <widget name="TrashWindow" x="50%-110" y="50%-31" width="220" height="64" visible="false">
+            <prototype name="Window" />
+            <sprite name="Icon" image="icons/materia_0.png" x="12" y="6" width="18" height="18" visible="true"/>
+            <text_area name="Name" x="36" y="9" font="FFVIIFont" visible="true" />
+            <sprite name="Star1" image="icons/materia_star_0.png" x="12" y="28" width="15" height="15" visible="true"/>
+            <sprite name="Star2" image="icons/materia_star_0.png" x="28" y="28" width="15" height="15" visible="true"/>
+            <sprite name="Star3" image="icons/materia_star_0.png" x="44" y="28" width="15" height="15" visible="true"/>
+            <sprite name="Star4" image="icons/materia_star_0.png" x="60" y="28" width="15" height="15" visible="true"/>
+            <sprite name="Star5" image="icons/materia_star_0.png" x="76" y="28" width="15" height="15" visible="true"/>
+            <text_area name="LblAP" text_name="MateriaMenuAP" x="12" y="47" font="FFVIIFont" visible="true" />
+            <text_area name="AP" x="100%-90" y="47" font="FFVIIMenuDigits" visible="true" />
+        </widget>
     </widget>
 </screen>

+ 25 - 0
data/data/screens/save_menu/save_menu.xml

@@ -25,5 +25,30 @@
             <animation name="Position2" length="0" y="0:48%+12" />
             <animation name="Position3" length="0" y="0:81%+12" />
         </sprite>
+        <widget name="ConfirmSame" x="50%-100" y="50%-33" width="200" height="66" visible="false">
+            <prototype name="Window" />
+            <text_area name="Question" text_name="SaveMenuOverride" x="16" y="8" font="FFVIIFont" visible="true" />
+            <text_area name="Yes" text_name="Yes" x="44" y="28" font="FFVIIFont" visible="true" />
+            <text_area name="No" text_name="No" x="44" y="44" font="FFVIIFont" visible="true" />
+            <sprite name="Cursor" image="icons/cursor.png" x="20" y="29" width="24" height="17" visible="true">
+                <animation name="Position1" length="0" y="0:29" />
+                <animation name="Position2" length="0" y="0:45" />
+            </sprite>
+        </widget>
+        <widget name="ConfirmOther" x="50%-150" y="50%-41" width="300" height="82" visible="false">
+            <prototype name="Window" />
+            <text_area name="Question" text_name="SaveMenuOverride" x="16" y="8" font="FFVIIFont" visible="true" />
+            <text_area name="Warning" text_name="SaveMenuOtherPlaythrough" x="16" y="24" font="FFVIIFont" visible="true" />
+            <text_area name="Yes" text_name="Yes" x="44" y="44" font="FFVIIFont" visible="true" />
+            <text_area name="No" text_name="No" x="44" y="60" font="FFVIIFont" visible="true" />
+            <sprite name="Cursor" image="icons/cursor.png" x="20" y="45" width="24" height="17" visible="true">
+                <animation name="Position1" length="0" y="0:45" />
+                <animation name="Position2" length="0" y="0:61" />
+            </sprite>
+        </widget>
+        <widget name="Saved" x="50%-60" y="50%-17" width="120" height="34" visible="false">
+            <prototype name="Window" />
+            <text_area name="Text" text_name="SaveMenuSaved" x="16" y="9" font="FFVIIFont" visible="true" />
+        </widget>
     </widget>
 </screen>

+ 210 - 0
data/data/screens/shop_menu/shop_menu.xml

@@ -0,0 +1,210 @@
+<screen name="ShopMenu" script="scripts/menu/shop_menu.lua" visible="false">
+    <sprite name="Background" x="0" y="0" width="100%" height="100%" colour="0 0 0" visible="true"/>
+    <widget name="Container" width="40%" height="40%" x="0" y="0" align="left" valign="top" scale="2.5 2.5" visible="true">
+        <widget name="TopBar" x="0" y="0" width="100%-100" height="24" visible="true">
+            <prototype name="Window" />
+            <widget name="Commands" x="0" y="0" width="100%" height="100%" visible="true">
+                <text_area name="Buy" x="36" y="6" text_name="ShopMenuBuy" font="FFVIIFont" visible="true" />
+                <text_area name="Sell" x="96" y="6" text_name="ShopMenuSell" font="FFVIIFont" visible="true" />
+                <text_area name="Exit" x="156" y="6" text_name="ShopMenuExit" font="FFVIIFont" visible="true" />
+                <sprite name="Cursor" image="icons/cursor.png" x="6" y="6" width="24" height="17" visible="true">
+                    <animation name="Position1" length="0" x="0:6" />
+                    <animation name="Position2" length="0" x="0:66" />
+                    <animation name="Position3" length="0" x="0:126" />
+                </sprite>
+            </widget>
+            <text_area name="PromptBuy" x="16" y="6" text_name="ShopMenuPromptBuy" font="FFVIIFont" visible="false" />
+            <text_area name="PromptSell" x="16" y="6" text_name="ShopMenuPromptSell" font="FFVIIFont" visible="false" />
+            <text_area name="PromptQuantity" x="16" y="6" text_name="ShopMenuPromptQuantity" font="FFVIIFont" visible="false" />
+        </widget>
+        <widget name="Title" x="100%-100" y="0" width="100" height="24" visible="true">
+            <prototype name="Window" />
+            <text_area name="Title" x="12" y="6" font="FFVIIFont" visible="true" />
+        </widget>
+        <widget name="Help" x="0" y="24" width="100%" height="24" visible="true">
+            <prototype name="Window" />
+            <text_area name="Help" x="16" y="6" font="FFVIIFont" visible="true" />
+        </widget>
+        <widget name="List" x="0" y="48" width="62%" height="100%-148" visible="true">
+            <prototype name="Window" />
+            <sprite name="Icon1" image="icons/item_item.png" x="26" y="8" width="13" height="15" visible="false" />
+            <text_area name="Name1" x="44" y="8" font="FFVIIFont" visible="true" />
+            <text_area name="Price1" x="100%-76" y="8" font="FFVIIMenuDigits" visible="true" />
+            <sprite name="Icon2" image="icons/item_item.png" x="26" y="24" width="13" height="15" visible="false" />
+            <text_area name="Name2" x="44" y="24" font="FFVIIFont" visible="true" />
+            <text_area name="Price2" x="100%-76" y="24" font="FFVIIMenuDigits" visible="true" />
+            <sprite name="Icon3" image="icons/item_item.png" x="26" y="40" width="13" height="15" visible="false" />
+            <text_area name="Name3" x="44" y="40" font="FFVIIFont" visible="true" />
+            <text_area name="Price3" x="100%-76" y="40" font="FFVIIMenuDigits" visible="true" />
+            <sprite name="Icon4" image="icons/item_item.png" x="26" y="56" width="13" height="15" visible="false" />
+            <text_area name="Name4" x="44" y="56" font="FFVIIFont" visible="true" />
+            <text_area name="Price4" x="100%-76" y="56" font="FFVIIMenuDigits" visible="true" />
+            <sprite name="Icon5" image="icons/item_item.png" x="26" y="72" width="13" height="15" visible="false" />
+            <text_area name="Name5" x="44" y="72" font="FFVIIFont" visible="true" />
+            <text_area name="Price5" x="100%-76" y="72" font="FFVIIMenuDigits" visible="true" />
+            <sprite name="Icon6" image="icons/item_item.png" x="26" y="88" width="13" height="15" visible="false" />
+            <text_area name="Name6" x="44" y="88" font="FFVIIFont" visible="true" />
+            <text_area name="Price6" x="100%-76" y="88" font="FFVIIMenuDigits" visible="true" />
+            <sprite name="Icon7" image="icons/item_item.png" x="26" y="104" width="13" height="15" visible="false" />
+            <text_area name="Name7" x="44" y="104" font="FFVIIFont" visible="true" />
+            <text_area name="Price7" x="100%-76" y="104" font="FFVIIMenuDigits" visible="true" />
+            <sprite name="Icon8" image="icons/item_item.png" x="26" y="120" width="13" height="15" visible="false" />
+            <text_area name="Name8" x="44" y="120" font="FFVIIFont" visible="true" />
+            <text_area name="Price8" x="100%-76" y="120" font="FFVIIMenuDigits" visible="true" />
+            <sprite name="Cursor" image="icons/cursor.png" x="0" y="6" width="24" height="17" visible="false">
+                <animation name="Position1" length="0" y="0:6" />
+                <animation name="Position2" length="0" y="0:22" />
+                <animation name="Position3" length="0" y="0:38" />
+                <animation name="Position4" length="0" y="0:54" />
+                <animation name="Position5" length="0" y="0:70" />
+                <animation name="Position6" length="0" y="0:86" />
+                <animation name="Position7" length="0" y="0:102" />
+                <animation name="Position8" length="0" y="0:118" />
+            </sprite>
+        </widget>
+        <widget name="Info" x="62%" y="48" width="38%" height="100%-148" visible="true">
+            <prototype name="Window" />
+            <text_area name="GilLbl" text_name="ShopMenuGil" x="16" y="6" font="FFVIIFont" visible="true" />
+            <text_area name="Gil" x="30" y="19" font="FFVIIMenuDigits" visible="true" />
+            <text_area name="OwnedLbl" text_name="ShopMenuOwned" x="16" y="38" font="FFVIIFont" visible="true" />
+            <text_area name="Owned" x="30" y="51" font="FFVIIMenuDigits" visible="true" />
+            <text_area name="EquippedLbl" text_name="ShopMenuEquipped" x="16" y="68" font="FFVIIFont" visible="true" />
+            <text_area name="Equipped" x="30" y="81" font="FFVIIMenuDigits" visible="true" />
+        </widget>
+        <widget name="Party" x="0" y="100%-100" width="100%" height="100" visible="true">
+            <prototype name="Window" />
+            <widget name="Slot1" x="0%" y="4" width="33%" height="30" visible="false">
+                <sprite name="Portrait" image="other/choco.png" x="6" y="0" width="26" height="29" visible="true" />
+                <text_area name="AtkLbl" text_name="ShopMenuAtk" x="36" y="1" font="FFVIIFont" visible="true" />
+                <text_area name="AtkOld" x="46" y="2" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="AtkArw" text_name="EquipMenuArrow" x="68" y="1" font="FFVIIFont" visible="true" />
+                <text_area name="AtkNew" x="78" y="2" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="DefLbl" text_name="ShopMenuDef" x="36" y="14" font="FFVIIFont" visible="true" />
+                <text_area name="DefOld" x="46" y="15" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="DefArw" text_name="EquipMenuArrow" x="68" y="14" font="FFVIIFont" visible="true" />
+                <text_area name="DefNew" x="78" y="15" font="FFVIIMenuDigits" visible="true" />
+            </widget>
+            <widget name="Slot2" x="33%" y="4" width="33%" height="30" visible="false">
+                <sprite name="Portrait" image="other/choco.png" x="6" y="0" width="26" height="29" visible="true" />
+                <text_area name="AtkLbl" text_name="ShopMenuAtk" x="36" y="1" font="FFVIIFont" visible="true" />
+                <text_area name="AtkOld" x="46" y="2" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="AtkArw" text_name="EquipMenuArrow" x="68" y="1" font="FFVIIFont" visible="true" />
+                <text_area name="AtkNew" x="78" y="2" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="DefLbl" text_name="ShopMenuDef" x="36" y="14" font="FFVIIFont" visible="true" />
+                <text_area name="DefOld" x="46" y="15" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="DefArw" text_name="EquipMenuArrow" x="68" y="14" font="FFVIIFont" visible="true" />
+                <text_area name="DefNew" x="78" y="15" font="FFVIIMenuDigits" visible="true" />
+            </widget>
+            <widget name="Slot3" x="66%" y="4" width="33%" height="30" visible="false">
+                <sprite name="Portrait" image="other/choco.png" x="6" y="0" width="26" height="29" visible="true" />
+                <text_area name="AtkLbl" text_name="ShopMenuAtk" x="36" y="1" font="FFVIIFont" visible="true" />
+                <text_area name="AtkOld" x="46" y="2" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="AtkArw" text_name="EquipMenuArrow" x="68" y="1" font="FFVIIFont" visible="true" />
+                <text_area name="AtkNew" x="78" y="2" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="DefLbl" text_name="ShopMenuDef" x="36" y="14" font="FFVIIFont" visible="true" />
+                <text_area name="DefOld" x="46" y="15" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="DefArw" text_name="EquipMenuArrow" x="68" y="14" font="FFVIIFont" visible="true" />
+                <text_area name="DefNew" x="78" y="15" font="FFVIIMenuDigits" visible="true" />
+            </widget>
+            <widget name="Slot4" x="0%" y="35" width="33%" height="30" visible="false">
+                <sprite name="Portrait" image="other/choco.png" x="6" y="0" width="26" height="29" visible="true" />
+                <text_area name="AtkLbl" text_name="ShopMenuAtk" x="36" y="1" font="FFVIIFont" visible="true" />
+                <text_area name="AtkOld" x="46" y="2" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="AtkArw" text_name="EquipMenuArrow" x="68" y="1" font="FFVIIFont" visible="true" />
+                <text_area name="AtkNew" x="78" y="2" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="DefLbl" text_name="ShopMenuDef" x="36" y="14" font="FFVIIFont" visible="true" />
+                <text_area name="DefOld" x="46" y="15" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="DefArw" text_name="EquipMenuArrow" x="68" y="14" font="FFVIIFont" visible="true" />
+                <text_area name="DefNew" x="78" y="15" font="FFVIIMenuDigits" visible="true" />
+            </widget>
+            <widget name="Slot5" x="33%" y="35" width="33%" height="30" visible="false">
+                <sprite name="Portrait" image="other/choco.png" x="6" y="0" width="26" height="29" visible="true" />
+                <text_area name="AtkLbl" text_name="ShopMenuAtk" x="36" y="1" font="FFVIIFont" visible="true" />
+                <text_area name="AtkOld" x="46" y="2" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="AtkArw" text_name="EquipMenuArrow" x="68" y="1" font="FFVIIFont" visible="true" />
+                <text_area name="AtkNew" x="78" y="2" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="DefLbl" text_name="ShopMenuDef" x="36" y="14" font="FFVIIFont" visible="true" />
+                <text_area name="DefOld" x="46" y="15" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="DefArw" text_name="EquipMenuArrow" x="68" y="14" font="FFVIIFont" visible="true" />
+                <text_area name="DefNew" x="78" y="15" font="FFVIIMenuDigits" visible="true" />
+            </widget>
+            <widget name="Slot6" x="66%" y="35" width="33%" height="30" visible="false">
+                <sprite name="Portrait" image="other/choco.png" x="6" y="0" width="26" height="29" visible="true" />
+                <text_area name="AtkLbl" text_name="ShopMenuAtk" x="36" y="1" font="FFVIIFont" visible="true" />
+                <text_area name="AtkOld" x="46" y="2" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="AtkArw" text_name="EquipMenuArrow" x="68" y="1" font="FFVIIFont" visible="true" />
+                <text_area name="AtkNew" x="78" y="2" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="DefLbl" text_name="ShopMenuDef" x="36" y="14" font="FFVIIFont" visible="true" />
+                <text_area name="DefOld" x="46" y="15" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="DefArw" text_name="EquipMenuArrow" x="68" y="14" font="FFVIIFont" visible="true" />
+                <text_area name="DefNew" x="78" y="15" font="FFVIIMenuDigits" visible="true" />
+            </widget>
+            <widget name="Slot7" x="0%" y="66" width="33%" height="30" visible="false">
+                <sprite name="Portrait" image="other/choco.png" x="6" y="0" width="26" height="29" visible="true" />
+                <text_area name="AtkLbl" text_name="ShopMenuAtk" x="36" y="1" font="FFVIIFont" visible="true" />
+                <text_area name="AtkOld" x="46" y="2" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="AtkArw" text_name="EquipMenuArrow" x="68" y="1" font="FFVIIFont" visible="true" />
+                <text_area name="AtkNew" x="78" y="2" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="DefLbl" text_name="ShopMenuDef" x="36" y="14" font="FFVIIFont" visible="true" />
+                <text_area name="DefOld" x="46" y="15" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="DefArw" text_name="EquipMenuArrow" x="68" y="14" font="FFVIIFont" visible="true" />
+                <text_area name="DefNew" x="78" y="15" font="FFVIIMenuDigits" visible="true" />
+            </widget>
+            <widget name="Slot8" x="33%" y="66" width="33%" height="30" visible="false">
+                <sprite name="Portrait" image="other/choco.png" x="6" y="0" width="26" height="29" visible="true" />
+                <text_area name="AtkLbl" text_name="ShopMenuAtk" x="36" y="1" font="FFVIIFont" visible="true" />
+                <text_area name="AtkOld" x="46" y="2" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="AtkArw" text_name="EquipMenuArrow" x="68" y="1" font="FFVIIFont" visible="true" />
+                <text_area name="AtkNew" x="78" y="2" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="DefLbl" text_name="ShopMenuDef" x="36" y="14" font="FFVIIFont" visible="true" />
+                <text_area name="DefOld" x="46" y="15" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="DefArw" text_name="EquipMenuArrow" x="68" y="14" font="FFVIIFont" visible="true" />
+                <text_area name="DefNew" x="78" y="15" font="FFVIIMenuDigits" visible="true" />
+            </widget>
+            <widget name="Slot9" x="66%" y="66" width="33%" height="30" visible="false">
+                <sprite name="Portrait" image="other/choco.png" x="6" y="0" width="26" height="29" visible="true" />
+                <text_area name="AtkLbl" text_name="ShopMenuAtk" x="36" y="1" font="FFVIIFont" visible="true" />
+                <text_area name="AtkOld" x="46" y="2" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="AtkArw" text_name="EquipMenuArrow" x="68" y="1" font="FFVIIFont" visible="true" />
+                <text_area name="AtkNew" x="78" y="2" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="DefLbl" text_name="ShopMenuDef" x="36" y="14" font="FFVIIFont" visible="true" />
+                <text_area name="DefOld" x="46" y="15" font="FFVIIMenuDigits" visible="true" />
+                <text_area name="DefArw" text_name="EquipMenuArrow" x="68" y="14" font="FFVIIFont" visible="true" />
+                <text_area name="DefNew" x="78" y="15" font="FFVIIMenuDigits" visible="true" />
+            </widget>
+        </widget>
+        <widget name="Quantity" x="50%-110" y="50%-31" width="220" height="62" visible="false">
+            <prototype name="Window" />
+            <text_area name="Name" x="12" y="7" font="FFVIIFont" visible="true" />
+            <text_area name="Times" text_name="ShopMenuTimes" x="12" y="23" font="FFVIIFont" visible="true" />
+            <text_area name="Count" x="24" y="24" font="FFVIIMenuDigits" visible="true" />
+            <text_area name="Total" x="100%-90" y="24" font="FFVIIMenuDigits" visible="true" />
+            <sprite name="Slot1" image="icons/materia_slot.png" x="12" y="42" width="16" height="16" visible="false"/>
+            <sprite name="Slot2" image="icons/materia_slot.png" x="29" y="42" width="16" height="16" visible="false"/>
+            <sprite name="Link1" image="icons/materia_slot_link.png" x="24" y="42" width="9" height="16" visible="false"/>
+            <sprite name="Slot3" image="icons/materia_slot.png" x="46" y="42" width="16" height="16" visible="false"/>
+            <sprite name="Slot4" image="icons/materia_slot.png" x="63" y="42" width="16" height="16" visible="false"/>
+            <sprite name="Link2" image="icons/materia_slot_link.png" x="58" y="42" width="9" height="16" visible="false"/>
+            <sprite name="Slot5" image="icons/materia_slot.png" x="80" y="42" width="16" height="16" visible="false"/>
+            <sprite name="Slot6" image="icons/materia_slot.png" x="97" y="42" width="16" height="16" visible="false"/>
+            <sprite name="Link3" image="icons/materia_slot_link.png" x="92" y="42" width="9" height="16" visible="false"/>
+            <sprite name="Slot7" image="icons/materia_slot.png" x="114" y="42" width="16" height="16" visible="false"/>
+            <sprite name="Slot8" image="icons/materia_slot.png" x="131" y="42" width="16" height="16" visible="false"/>
+            <sprite name="Link4" image="icons/materia_slot_link.png" x="126" y="42" width="9" height="16" visible="false"/>
+        </widget>
+        <widget name="MateriaSale" x="50%-110" y="50%-41" width="220" height="82" visible="false">
+            <prototype name="Window" />
+            <sprite name="Icon" image="icons/materia_0.png" x="12" y="6" width="18" height="18" visible="true"/>
+            <text_area name="Name" x="36" y="9" font="FFVIIFont" visible="true" />
+            <sprite name="Star1" image="icons/materia_star_0.png" x="12" y="28" width="15" height="15" visible="true"/>
+            <sprite name="Star2" image="icons/materia_star_0.png" x="28" y="28" width="15" height="15" visible="true"/>
+            <sprite name="Star3" image="icons/materia_star_0.png" x="44" y="28" width="15" height="15" visible="true"/>
+            <sprite name="Star4" image="icons/materia_star_0.png" x="60" y="28" width="15" height="15" visible="true"/>
+            <sprite name="Star5" image="icons/materia_star_0.png" x="76" y="28" width="15" height="15" visible="true"/>
+            <text_area name="ApLbl" text_name="ShopMenuAP" x="12" y="47" font="FFVIIFont" visible="true" />
+            <text_area name="Ap" x="100%-90" y="47" font="FFVIIMenuDigits" visible="true" />
+            <text_area name="PriceLbl" text_name="ShopMenuGil" x="12" y="63" font="FFVIIFont" visible="true" />
+            <text_area name="Price" x="100%-90" y="63" font="FFVIIMenuDigits" visible="true" />
+        </widget>
+    </widget>
+</screen>

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

@@ -16,6 +16,7 @@
     <script file="gamedata/items.lua" />
     <script file="gamedata/key_items.lua" />
     <script file="gamedata/materia.lua" />
+    <script file="gamedata/shops.lua" />
     <script file="gamedata/summons.lua" />
     <script file="gamedata/weapons.lua" />
 

+ 312 - 56
data/data/scripts/battle/battle_camera.lua

@@ -7,14 +7,16 @@
 -- and camera_multiple of the attacks. The interpreters are in ff7.exe (0x5c2341 and 0x5c3f45).
 --
 -- A script is a list of opcodes (0xd5-0xff, other values do nothing) with operands that are bytes or
--- 16 bit values (little endian, with sign). Positions are in the units of the original game, in a
--- frame with x to the side, y down and z forward (toward the enemies, for the party), and the ones
--- that follow an actor are relative to a point of it, the offsets turned with the way it faces if
--- the stream has "rotate" on. The frame of the scene is converted with
+-- 16 bit values (little endian, with sign). Positions are in the units of the original game, with x to
+-- the side, y down and z in depth (the enemies are in the negative side), and the ones that follow an
+-- actor are relative to a point of it, the offsets turned with the way it faces if the stream has
+-- "rotate" on. The frame of the scene is converted like the positions of the formations:
 --
---   scene = (x, -z, -y) / 255      (a reflection: the original frame is left handed)
+--   scene = (x, z, -y) / 255
 --
--- (the division is the one the installer uses for every coordinate of the battle). The streams run
+-- (the division is the one the installer uses for every coordinate of the battle). The facing angle of
+-- an actor in ff7.exe is the one of the direction to its target plus half a turn (0x420d5b), so the
+-- positive z of a turned offset is behind the actor. The streams run
 -- one opcode after the other until one of them waits or places the point (the ones that do are
 -- listed in YIELDS), once per tick, 15 ticks per second like the effects.
 --
@@ -95,6 +97,8 @@ function BattleCamera.new(position, look, env)
     local f = env.formation
     self.cam.pos = {f.pos[1], f.pos[2], f.pos[3]}
     self.look.pos = {f.look[1], f.look[2], f.look[3]}
+    -- The camera the script started on (opcode d9). The opcode dd changes the one of e1 and e2, not it.
+    self.base = f
     return self
 end
 
@@ -120,7 +124,7 @@ end
 --- Converts a vector of the original frame to the scene, as an offset.
 local function to_scene_offset(x, y, z)
     local k = BattleCamera.UNIT
-    return x * k, -z * k, -y * k
+    return x * k, z * k, -y * k
 end
 
 --- Converts a position of the original frame (absolute) to the scene.
@@ -130,20 +134,41 @@ end
 
 --- Position of a point of an actor, plus an offset of the original frame.
 --
+-- As in ff7.exe, the offsets of the position of the camera grow with the size of the model (0x5c6290) and
+-- turn with the way it faces if the stream has "rotate" on, and the ones of the point it looks at do
+-- neither: they only move down by the height that the model has for it (0x5c5a78). None of that applies to
+-- the center of a group of targets.
+--
+-- @param kind Stream of the offset, "pos" or "look".
 -- @param rotate If the offset turns with the way the actor faces.
-function BattleCamera:anchor(ref, point, ox, oy, oz, rotate)
+function BattleCamera:anchor(ref, point, ox, oy, oz, rotate, kind)
     local actor = self.env:actor(ref)
     if actor == nil then return nil end
-    -- The points of the original are bones. All of the used ones (0 and 10) are near the middle of
-    -- the body, so they are the middle of the actor.
-    local px, py, pz = actor.pos[1], actor.pos[2], actor.pos[3] + actor.height * 0.5
+    -- The points are ends of bones of the model. Without that data (an old install), the middle of the actor.
+    local px, py, pz
+    if actor.point ~= nil then px, py, pz = actor.point(point) end
+    if px == nil then px, py, pz = actor.pos[1], actor.pos[2], actor.pos[3] + actor.height * 0.5 end
+    if actor.group then
+        rotate = false
+    end
+    if kind == "look" then
+        oy = oy + (actor.look_height or 0)
+        rotate = false
+    elseif actor.size ~= nil then
+        local function scale(value, size)
+            -- A Small actor halves the factors, but they don't go under 256.
+            if actor.small then size = math.max(256, math.floor(size / 2)) end
+            return math.floor(value * size / 256)
+        end
+        ox, oy, oz = scale(ox, actor.size[1]), scale(oy, actor.size[2]), scale(oz, actor.size[3])
+    end
     local k = BattleCamera.UNIT
     local dx, dy, dz
     if rotate then
-        -- x is to the left of the way it faces (reflection), z forward, y down.
+        -- x is to the left of the way it faces, z behind it, y down (the rotation of 0x5c6290).
         local fx, fy = actor.forward[1], actor.forward[2]
-        dx = (-fy) * ox * k + fx * oz * k
-        dy = fx * ox * k + fy * oz * k
+        dx = (-fy) * ox * k - fx * oz * k
+        dy = fx * ox * k - fy * oz * k
         dz = -oy * k
     else
         dx, dy, dz = to_scene_offset(ox, oy, oz)
@@ -171,13 +196,51 @@ end
 local function start_follow(stream, ref, point, ox, oy, oz, ticks, rotate)
     stream.tasks[#stream.tasks + 1] = {
         type = "follow", ref = ref, point = point, off = {ox, oy, oz}, ticks = math.max(1, ticks),
-        age = 0, rotate = rotate,
+        age = 0, rotate = rotate, kind = stream.kind,
+    }
+end
+
+--- Starts an orbit of the position around the point the camera looks at (opcode f8 of the position,
+-- task 0x5c3c7d of ff7.exe).
+--
+-- All the values are the ones of the script: angles in 4096ths of a turn, distances in the original frame.
+--
+-- @param speed Angle added each tick.
+-- @param radius Horizontal distance to the point, in eighths.
+-- @param angle Starting angle.
+-- @param radius_speed Added to the radius each tick.
+-- @param y_speed Added to the height (down) of the camera each tick.
+local function start_orbit(stream, speed, radius, angle, radius_speed, y_speed, ticks)
+    stream.tasks[#stream.tasks + 1] = {
+        type = "orbit", speed = speed, radius = radius, angle = angle, radius_speed = radius_speed,
+        y_speed = y_speed, ticks = math.max(1, ticks), age = 0,
     }
 end
 
+--- The reference of the "current actor" of the opcodes (byte 0xbe40e4 of ff7.exe): the target, or
+-- the group of targets if there are several or after the opcode df.
+function BattleCamera:current_ref()
+    return self.group and "targets" or "current"
+end
+
+--- Position of one of the two views a model has for the cameras (opcode e0): the position of the
+-- camera or the point it looks at, depending on the stream. It doesn't turn or grow with the model. The
+-- height of the first view is over the ground, and the one of the second over the actor.
+--
+-- @param view 0 or 1.
+-- @return Nil if there is no data, like for a group of targets.
+function BattleCamera:view_point(ref, view, kind)
+    local actor = self.env:actor(ref)
+    if actor == nil or actor.views == nil or actor.views[view + 1] == nil then return nil end
+    local offset = actor.views[view + 1][kind]
+    local x, y, z = to_scene_offset(offset[1], offset[2], offset[3])
+    if view ~= 0 then z = z + actor.pos[3] end
+    return vec(actor.pos[1] + x, actor.pos[2] + y, z)
+end
+
 --- Places a stream at a point of an actor, now.
 function BattleCamera:place(stream, ref, point, ox, oy, oz, rotate)
-    local p = self:anchor(ref, point, ox, oy, oz, rotate)
+    local p = self:anchor(ref, point, ox, oy, oz, rotate, stream.kind)
     if p ~= nil then stream.pos = p end
 end
 
@@ -219,6 +282,9 @@ function BattleCamera:run(stream)
             end
         elseif op == 0xdc then
             stream.rotate = true
+        elseif op == 0xdf then
+            -- From now on, the "current actor" of both streams is the group of targets.
+            self.group = true
         elseif kind == "pos" and op == 0xf1 then
             stream.rotate = false
         elseif kind == "look" and op == 0xdb then
@@ -227,10 +293,15 @@ function BattleCamera:run(stream)
             stream.linear = false
         elseif kind == "pos" and op == 0xdb then
             stream.linear = true
-        elseif op == 0xe1 or op == 0xd9 or op == 0xdd then
-            -- The camera that was in use.
-            if op == 0xdd then u8(stream) end
-            local source = kind == "pos" and env.formation.pos or env.formation.look
+        elseif op == 0xdd then
+            -- Chooses the camera of the formation that e1 and e2 use, for both streams.
+            local index = u8(stream)
+            local chosen = env.formation_at ~= nil and env.formation_at(index) or nil
+            if chosen ~= nil then env.formation, self.formation_index = chosen, index end
+        elseif op == 0xe1 or op == 0xd9 then
+            -- The camera of the formation (e1), or the one that was in use before the script (d9).
+            local view = op == 0xd9 and self.base or env.formation
+            local source = kind == "pos" and view.pos or view.look
             stream.pos = {source[1], source[2], source[3]}
         elseif op == 0xe2 then
             local source = kind == "pos" and env.formation.pos or env.formation.look
@@ -238,6 +309,11 @@ function BattleCamera:run(stream)
         elseif op == 0xe6 then
             local x, y, z = s16(stream), s16(stream), s16(stream)
             start_move(stream, self:absolute(x, y, z), u8(stream))
+        elseif op == 0xe0 then
+            -- Move to a view of the current actor: view, ticks.
+            local view, ticks = u8(stream), u8(stream)
+            local target = self:view_point(self:current_ref(), view, kind)
+            if target ~= nil then start_move(stream, target, ticks) end
         elseif (kind == "pos" and op == 0xf9) or (kind == "look" and op == 0xfa) then
             local x, y, z = s16(stream), s16(stream), s16(stream)
             stream.pos = self:absolute(x, y, z)
@@ -245,13 +321,13 @@ function BattleCamera:run(stream)
             -- Move to a point of an actor, with an offset: actor (e3 and d8), point, x, y, z, ticks.
             local ref
             if op == 0xe3 then ref = actor_from_byte(u8(stream))
-            elseif op == 0xd8 then u8(stream) ref = "targets"
+            elseif op == 0xd8 then ref = {target = u8(stream) + 1}
             elseif op == 0xe4 then ref = "attacker"
-            else ref = "current" end
+            else ref = self:current_ref() end
             local point = u8(stream)
             local x, y, z = s16(stream), s16(stream), s16(stream)
             local ticks = u8(stream)
-            local target = self:anchor(ref, point, x, y, z, stream.rotate)
+            local target = self:anchor(ref, point, x, y, z, stream.rotate, stream.kind)
             if target ~= nil then start_move(stream, target, ticks) end
         elseif (kind == "pos" and (op == 0xe7 or op == 0xe9 or op == 0xeb))
           or (kind == "look" and (op == 0xe8 or op == 0xea or op == 0xec)) then
@@ -259,7 +335,7 @@ function BattleCamera:run(stream)
             local ref
             if op == 0xeb or op == 0xec then ref = actor_from_byte(u8(stream))
             elseif op == 0xe7 or op == 0xe8 then ref = "attacker"
-            else ref = "current" end
+            else ref = self:current_ref() end
             local point = u8(stream)
             local x, y, z = s16(stream), s16(stream), s16(stream)
             local ticks = u8(stream)
@@ -270,13 +346,17 @@ function BattleCamera:run(stream)
             local ref
             if (kind == "pos" and op == 0xef) or (kind == "look" and op == 0xf0) then ref = actor_from_byte(u8(stream))
             elseif (kind == "pos" and op == 0xf0) or (kind == "look" and op == 0xf9) then ref = "attacker"
-            else ref = "current" end
+            else ref = self:current_ref() end
             local point = u8(stream)
             local x, y, z = s16(stream), s16(stream), s16(stream)
             self:place(stream, ref, point, x, y, z, stream.rotate)
+        elseif kind == "pos" and op == 0xf8 then
+            local speed, radius, angle = s16(stream), s16(stream), s16(stream)
+            local radius_speed, y_speed, ticks = s16(stream), s16(stream), s16(stream)
+            start_orbit(stream, speed, radius, angle, radius_speed, y_speed, ticks)
         else
-            -- Opcodes that don't change the camera (events of the battle, the orbits f2 and f3, the
-            -- moves to the data of an actor e0, 0xf8 of the position): skip their operands.
+            -- Opcodes that don't change the camera (events of the battle) and the ones no script of the
+            -- game uses (like f2 and f3): skip their operands.
             stream.pc = stream.pc + length
         end
         if yields[op] and op ~= 0xff and op ~= 0xf4 then return end
@@ -301,8 +381,19 @@ function BattleCamera:run_tasks(stream)
                     task.start[3] + (task.target[3] - task.start[3]) * f,
                 }
             end
+        elseif task.type == "orbit" then
+            task.angle = task.angle + task.speed
+            local a = task.angle * 2 * math.pi / 4096
+            local r = task.radius * 8 * BattleCamera.UNIT
+            local center = self.look.pos
+            stream.pos = {
+                center[1] + math.sin(a) * r,
+                center[2] + math.cos(a) * r,
+                stream.pos[3] - task.y_speed * BattleCamera.UNIT,
+            }
+            task.radius = task.radius + task.radius_speed
         else
-            local p = self:anchor(task.ref, task.point, task.off[1], task.off[2], task.off[3], task.rotate)
+            local p = self:anchor(task.ref, task.point, task.off[1], task.off[2], task.off[3], task.rotate, task.kind)
             if p ~= nil then stream.pos = p end
         end
         if task.age < task.ticks then alive[#alive + 1] = task end
@@ -369,6 +460,50 @@ local function entity_info(entity)
 end
 BattleCameraController.heights = {}
 
+--- Data of the battle models for the cameras, by model name. False for the models without it.
+BattleCameraController.models = {}
+
+--- Gets the camera data of a model, written by the installer. Nil if there is none.
+local function model_data(name)
+    if name == nil then return nil end
+    local data = BattleCameraController.models[name]
+    if data == nil then
+        local chunk = loadfile("./data/scripts/battle_models/" .. name .. "_camera.lua")
+        if chunk ~= nil then chunk() end
+        data = BattleModelCameras ~= nil and BattleModelCameras[name] or false
+        BattleCameraController.models[name] = data
+    end
+    return data or nil
+end
+
+--- Describes an actor of the scene for the camera.
+--
+-- @param entity Its entity.
+-- @param side Its side, and index its place in it.
+-- @param forward The way it faces.
+local function actor_info(entity, side, index, forward)
+    local x, y, z, height = entity_info(entity)
+    local info = {pos = {x, y, z}, height = height, forward = forward({x, y, z})}
+    local ui = UiContainer.BattleUi
+    local data = model_data(ui:get_model_name(side, index))
+    if data ~= nil then
+        info.size, info.look_height, info.views = data.size, data.look_height, data.views
+        info.small = ui:has_status(side, index, BattleStatus.SMALL)
+        -- Position of a point of the model, nil if the model doesn't have it.
+        info.point = function(point)
+            local bone = data.points[point + 1]
+            if bone == nil then return nil end
+            local bx, by, bz
+            if bone == 0 then bx, by, bz = entity:get_bone_position(0)
+            elseif data.lengths[bone - 1] ~= nil then bx, by, bz = entity:get_bone_end(bone - 1, data.lengths[bone - 1])
+            end
+            if bx == nil or (bx == 0 and by == 0 and bz == 0) then return nil end
+            return bx, by, bz
+        end
+    end
+    return info
+end
+
 --- Builds the environment of the camera for an action.
 local function build_env(side, actor, target_side, targets, formation)
     local ui = UiContainer.BattleUi
@@ -376,27 +511,27 @@ local function build_env(side, actor, target_side, targets, formation)
         local e = ui:get_entity(s, index)
         return e
     end
-    -- Center of the targets (their entities) and of the attacker.
-    local function center_of(s, list)
-        local sx, sy, sz, n = 0, 0, 0, 0
-        local height = 0
+    -- Middle of the area the targets are in, on the ground.
+    local function ground_center(s, list)
+        local min_x, max_x, min_y, max_y
         for _, index in ipairs(list) do
             local e = entity_of(s, index)
             if e ~= nil then
-                local x, y, z, h = entity_info(e)
-                sx, sy, sz, n, height = sx + x, sy + y, sz + z, n + 1, math.max(height, h)
+                local x, y = entity_info(e)
+                min_x, max_x = math.min(min_x or x, x), math.max(max_x or x, x)
+                min_y, max_y = math.min(min_y or y, y), math.max(max_y or y, y)
             end
         end
-        if n == 0 then return nil end
-        return {sx / n, sy / n, sz / n}, height
+        if min_x == nil then return nil end
+        return {(min_x + max_x) / 2, (min_y + max_y) / 2, 0}
     end
     local attacker_entity = entity_of(side, actor)
-    local attacker_pos, attacker_height
+    local attacker_pos
     if attacker_entity ~= nil then
-        local x, y, z, h = entity_info(attacker_entity)
-        attacker_pos, attacker_height = {x, y, z}, h
+        local x, y, z = entity_info(attacker_entity)
+        attacker_pos = {x, y, z}
     end
-    local target_pos, target_height = center_of(target_side, targets)
+    local target_pos = ground_center(target_side, targets)
     local function direction(from, to)
         if from == nil or to == nil then return {0, -1} end
         local dx, dy = to[1] - from[1], to[2] - from[2]
@@ -404,28 +539,33 @@ local function build_env(side, actor, target_side, targets, formation)
         if l < 0.0001 then return {0, -1} end
         return {dx / l, dy / l}
     end
+    local function toward(to) return function(from) return direction(from, to) end end
     local env = {formation = formation}
     function env:actor(ref)
         if ref == "attacker" then
-            if attacker_pos == nil then return nil end
-            return {pos = attacker_pos, height = attacker_height, forward = direction(attacker_pos, target_pos)}
+            if attacker_entity == nil then return nil end
+            return actor_info(attacker_entity, side, actor, toward(target_pos))
+        elseif ref == "current" and #targets == 1 then
+            local e = entity_of(target_side, targets[1])
+            if e ~= nil then return actor_info(e, target_side, targets[1], toward(attacker_pos)) end
         elseif ref == "current" or ref == "targets" then
-            if target_pos == nil then return nil end
-            if ref == "current" then
-                -- The first target.
-                local e = entity_of(target_side, targets[1])
-                if e ~= nil then
-                    local x, y, z, h = entity_info(e)
-                    return {pos = {x, y, z}, height = h, forward = direction({x, y, z}, attacker_pos)}
-                end
-            end
-            return {pos = target_pos, height = target_height, forward = direction(target_pos, attacker_pos)}
+            -- The center of the group of targets, on the ground (0x5bfe39).
+            local center = ground_center(target_side, targets)
+            if center == nil then return nil end
+            return {
+                group = true, pos = center, height = 0, forward = direction(center, attacker_pos),
+                point = function() return center[1], center[2], center[3] end,
+            }
+        elseif type(ref) == "table" and ref.target ~= nil then
+            -- One of the targets, by its place in the list (opcode d8).
+            local index = targets[ref.target] or targets[1]
+            local e = entity_of(target_side, index)
+            if e ~= nil then return actor_info(e, target_side, index, toward(attacker_pos)) end
         elseif type(ref) == "table" then
-            local e = entity_of(ref.side == "party" and Battle.TargetGroup.PARTY or Battle.TargetGroup.ENEMIES, ref.index)
+            local ref_side = ref.side == "party" and Battle.TargetGroup.PARTY or Battle.TargetGroup.ENEMIES
+            local e = entity_of(ref_side, ref.index)
             if e == nil then return nil end
-            local x, y, z, h = entity_info(e)
-            local other = ref.side == "party" and target_pos or attacker_pos
-            return {pos = {x, y, z}, height = h, forward = direction({x, y, z}, other)}
+            return actor_info(e, ref_side, ref.index, toward(ref.side == "party" and target_pos or attacker_pos))
         end
         return nil
     end
@@ -443,6 +583,7 @@ end
 -- @return True if there is a camera.
 function BattleCameraController:start(side, actor, target_side, targets, camera_single, camera_multiple)
     self:stop(false)
+    self.from_script = false
     if Battle.is_camera_auto ~= nil and not Battle.is_camera_auto() then return false end
     if targets == nil or #targets == 0 then return false end
     local id = #targets > 1 and camera_multiple or camera_single
@@ -470,6 +611,115 @@ function BattleCameraController:start(side, actor, target_side, targets, camera_
     return true
 end
 
+--- Starts the camera of the victory: shots of the party at fixed places, which depend on the camera
+-- file of the layout of the battle (camera id -3 of ff7.exe, set at 0x42dbd7).
+--
+-- @return True if there is a camera (an old install doesn't have its data).
+function BattleCameraController:start_victory()
+    local variant = math.random(0, 2)
+    local file = self.FILE_BY_LAYOUT[battle_manager:get_layout()] or 0
+    local data = Game.BattleCameras ~= nil and Game.BattleCameras[file] or nil
+    if data == nil or data.victory_position == nil then return false end
+    local position = data.scripts[data.victory_position[variant + 1]]
+    local look = data.scripts[data.victory_look[variant + 1]]
+    if position == nil and look == nil then return false end
+    self:reset()
+    local index = UiContainer.BattleUi.camera_index or 0
+    local px, py, pz, lx, ly, lz = battle_manager:get_camera(index)
+    -- These scripts don't use any actor.
+    local env = {formation = {pos = {px, py, pz}, look = {lx, ly, lz}}, actor = function() return nil end}
+    self.camera = BattleCamera.new(position, look, env)
+    self.camera_index = index
+    print("Battle camera: victory, variant " .. tostring(variant) .. " file " .. tostring(file))
+    return true
+end
+
+--- Starts one of the camera scripts that ff7.exe has (camera id -2): the ones of the start of the
+-- battles, and the ones that the animation scripts of some enemies use. They go to a camera of the
+-- formation, which they can change.
+--
+-- @param id Number of the script.
+-- @return True if there is a camera.
+function BattleCameraController:start_script(id)
+    local data = Game.BattleCameras ~= nil and Game.BattleCameras.intro or nil
+    if data == nil or id == nil or id < 0 then return false end
+    local position = data.scripts[data.position[id + 1]]
+    local look = data.scripts[data.look[id + 1]]
+    if position == nil and look == nil then return false end
+    local function formation_at(index)
+        if index < 0 or index > 2 then return nil end
+        local px, py, pz, lx, ly, lz = battle_manager:get_camera(index)
+        return {pos = {px, py, pz}, look = {lx, ly, lz}}
+    end
+    local index = UiContainer.BattleUi.camera_index or 0
+    local env = {formation = formation_at(index), formation_at = formation_at, actor = function() return nil end}
+    self:reset()
+    self.camera = BattleCamera.new(position, look, env)
+    self.camera_index = index
+    self.from_script = true
+    return true
+end
+
+--- Starts the camera of the start of a battle: from some other place to a camera of the formation.
+-- The formation chooses the script.
+--
+-- @return True if there is a camera.
+function BattleCameraController:start_intro()
+    self:reset()
+    UiContainer.BattleUi.camera_index = 0
+    local id = battle_manager:get_intro_camera()
+    if not self:start_script(id) then return false end
+    print("Battle camera: start of the battle, script " .. tostring(id))
+    return true
+end
+
+--- Changes the camera of the formation the battle rests on, moving to it.
+--
+-- @param index 0 to 2.
+function BattleCameraController:set_view(index)
+    if index < 0 or index > 2 then return end
+    local previous = UiContainer.BattleUi.camera_index or 0
+    UiContainer.BattleUi.camera_index = index
+    self.camera_index = index
+    if self.camera ~= nil or previous == index then return end
+    local px, py, pz, lx, ly, lz = battle_manager:get_camera(previous)
+    local from = self.returning ~= nil and self.returning.to or nil
+    local cam, look = from ~= nil and from[1] or {px, py, pz}, from ~= nil and from[2] or {lx, ly, lz}
+    px, py, pz, lx, ly, lz = battle_manager:get_camera(index)
+    self.returning = {target = {{px, py, pz}, {lx, ly, lz}}, cam = cam, look = look, index = index}
+    self.accumulated = 0
+end
+
+--- Is a script of an animation still moving the camera? It goes on even with no action.
+function BattleCameraController:is_script_running()
+    return self.camera ~= nil and self.from_script == true and not self.camera:is_finished()
+end
+
+--- Moves the camera of the start of the battle, and leaves the one of the formation when it ends.
+--
+-- @param dt Seconds since the last call.
+-- @return True while it goes on.
+function BattleCameraController:update_intro(dt)
+    if self.camera == nil then return false end
+    self:update(dt)
+    if not self.camera:is_finished() then return true end
+    local index = self.camera_index or 0
+    self:reset()
+    battle_manager:set_camera(index)
+    return false
+end
+
+--- Forgets the camera in use, without moving anything.
+function BattleCameraController:reset()
+    self.camera = nil
+    self.from_script = false
+    self.returning = nil
+    self.last = nil
+    self.previous = nil
+    self.current = nil
+    self.accumulated = 0
+end
+
 --- Stops the camera and goes back to the one of the formation.
 --
 -- The original doesn't jump: every tick the camera and the point it looks at cover half of the
@@ -532,6 +782,12 @@ function BattleCameraController:update(dt)
     while self.accumulated >= 1 do
         self.accumulated = self.accumulated - 1
         self.camera:tick()
+        -- A script chose another camera of the formation: the battle stays on it.
+        local view = self.camera.formation_index
+        if view ~= nil then
+            self.camera_index = view
+            UiContainer.BattleUi.camera_index = view
+        end
         local cam, look = self.camera:get()
         self.previous = self.current
         self.current = {cam = {cam[1], cam[2], cam[3]}, look = {look[1], look[2], look[3]}}

Diferenças do arquivo suprimidas por serem muito extensas
+ 600 - 107
data/data/scripts/battle/battle_ui.lua


+ 53 - 0
data/data/scripts/character_abilities.lua

@@ -19,6 +19,9 @@ local function get_materia_level(materia, ap)
     return level
 end
 
+--- See get_materia_level, the stats need it too.
+Characters.get_materia_level = get_materia_level
+
 --- Gets the magic, summons and enemy skills a character can use with the materia that is equipped.
 --
 -- Every ability is listed once, even if more than one materia gives it.
@@ -91,6 +94,56 @@ Characters.get_abilities = function(char_id)
     return result
 end
 
+--- Gets the commands a character has in battle, in the order the battle menu shows them.
+--
+-- The Attack command (or the materia that replace it, like Slash-All or Flash) goes first. Then
+-- come the commands of the materia, Item (unless W-Item is equipped), Magic and Summon (if the
+-- character has spells or summons, and no W-Magic or W-Summon is equipped). The Limit command is
+-- not included, as it only appears in battle when the limit bar is full.
+--
+-- @param char_id ID of the character.
+-- @return List of IDs of commands (see Game.Commands).
+Characters.get_commands = function(char_id)
+    local commands = { 1 }
+    local character = Characters[char_id]
+    if character == nil then return commands end
+    local w_magic, w_summon, w_item = false, false, false
+    for _, part in ipairs({ "weapon", "armor" }) do
+        local equipment = character[part]
+        for slot = 0, 7 do
+            local equipped = equipment.materia[slot]
+            local materia = (equipped ~= nil) and Game.Materia[equipped.id] or nil
+            if materia ~= nil and materia.type == Materia.TYPE.COMMAND and materia.command ~= nil then
+                local level = get_materia_level(materia, equipped.ap or 0)
+                local command
+                for l, id in ipairs(materia.command) do
+                    if level >= l then command = id end
+                end
+                if command ~= nil then
+                    if command == 1 or command == 20 or (command >= 24 and command <= 27) then
+                        commands[1] = command
+                    else
+                        commands[#commands + 1] = command
+                    end
+                    if command == 21 then w_magic = true end
+                    if command == 22 then w_summon = true end
+                    if command == 23 then w_item = true end
+                end
+            end
+        end
+    end
+    local abilities = Characters.get_abilities(char_id)
+    if not w_item then commands[#commands + 1] = 4 end
+    if #abilities.magic > 0 and not w_magic then commands[#commands + 1] = 2 end
+    if #abilities.summon > 0 and not w_summon then commands[#commands + 1] = 3 end
+    local function substitute(id) return id == 1 or id == 20 or (id >= 24 and id <= 27) end
+    table.sort(commands, function(l, r)
+        if substitute(l) ~= substitute(r) then return substitute(l) end
+        return l < r
+    end)
+    return commands
+end
+
 --- Gets what the independent materia (Long Range, Mega All, Counter Attack, Cover, Pre-Emptive, EXP
 -- Plus and Gil Plus) of a character do in battle.
 --

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

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

+ 70 - 17
data/data/scripts/field.lua

@@ -14,6 +14,21 @@ load_field_map_request = function(map_name, point_name)
     end
 end
 
+--- Starts a minigame (the MINIGAME opcode).
+--
+-- The minigames are not implemented yet: the game goes on as if the minigame had been played, and
+-- jumps to the field that the original game goes to when it ends. The scripts of that field decide
+-- from the state of the game what comes next (the bike of blackbgb leads to the fight against the
+-- Motor Ball, because the script of the field set that state before starting the minigame).
+--
+-- @param game Number of the minigame.
+-- @param map_name Field where the game goes on.
+-- @param point_name Point of that field where the player is placed.
+minigame = function(game, map_name, point_name)
+    print("The minigame " .. tostring(game) .. " is not implemented: skipping it.")
+    load_field_map_request(map_name, point_name)
+end
+
 dispatch_menu = function(menu_id, parameter)
     menu_id = tonumber(menu_id)
     parameter = tonumber(parameter)
@@ -45,6 +60,8 @@ dispatch_menu = function(menu_id, parameter)
         open_menu("save")
     elseif menu_id == 15 then
         Party.steal_materia()
+    elseif menu_id == 17 then
+        Characters.unequip_materia(parameter)
     elseif menu_id == 18 then
         Characters.remove_materia(parameter)
     elseif menu_id == 19 then
@@ -93,17 +110,17 @@ end
 -- @param entity_name The entity name.
 -- @param character_id Id of the character to assign.
 set_entity_to_character = function(entity_name, character_id)
-    if character_id == Party[1] and entity_name ~= "" then
+    if character_id == Party.get_leader() and entity_name ~= "" then
         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
+    -- The model of a playable character is shown only if it is the leader of the party (the one the
+    -- scripts set, see Party.get_leader). 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
+    if character_id ~= Party.get_leader() and entity_name ~= "" and Party.get_leader() ~= nil then
         local entity = entity_manager:get_entity(entity_name)
         if entity ~= nil then
             entity:set_visible(false)
@@ -202,6 +219,12 @@ player_lock = function(lock)
     MenuSettings.available = (lock == false)
 end
 
+--- Locks or unlocks the menu button (MENU2), with no effect on the player.
+-- @param lock True to lock, false to unlock.
+menu_lock = function(lock)
+    MenuSettings.available = (lock == false)
+end
+
 --- Sets a bit variable on (1).
 --
 -- @param bank Memory bank (0-index, as in game).
@@ -243,6 +266,9 @@ end
 -- @param az Address at which to store the Z coordinate.
 -- @param at Address at which to store the triangle.
 -- @param scale Map scale to multiply values
+-- The coordinates are rounded: the walkmesh is saved with six digits, so a height of 193 units comes
+-- as 192.9997 once scaled, and the scripts compare it with the exact value (blin68_1 asks for it to
+-- talk to a character).
 axyzi = function(bx, by, bz, bt, id, ax, ay, az, at, scale)
     local entity = entity_manager:get_entity_from_index(id)
     if entity == nil then
@@ -250,9 +276,9 @@ axyzi = function(bx, by, bz, bt, id, ax, ay, az, at, scale)
     end
     local x, y, z = entity:get_position()
     local t = entity:get_move_triangle_id()
-    Banks[bx][ax] = math.floor(x * scale)
-    Banks[by][ay] = math.floor(y * scale)
-    Banks[bz][az] = math.floor(z * scale)
+    Banks[bx][ax] = math.floor(x * scale + 0.5)
+    Banks[by][ay] = math.floor(y * scale + 0.5)
+    Banks[bz][az] = math.floor(z * scale + 0.5)
     Banks[bt][at] = t
     return 0
 end
@@ -271,8 +297,8 @@ getaxy = function(bx, by, id, ax, ay, scale)
         do return end
     end
     local x, y = entity:get_position()
-    Banks[bx][ax] = math.floor(x * scale)
-    Banks[by][ay] = math.floor(y * scale)
+    Banks[bx][ax] = math.floor(x * scale + 0.5)
+    Banks[by][ay] = math.floor(y * scale + 0.5)
     return 0
 end
 
@@ -290,9 +316,13 @@ name_character = function(id)
         print("Tried to rename invalid character with ID " .. tostring(id))
         return 0
     end
+    -- Cait Sith and Vincent get their data before they are named.
+    Characters.load_recruit_record(id)
     -- While the name menu is not enabled, the character just gets its default name.
     if not UiContainer.NameMenu.enabled then
         UiContainer.NameMenu:apply_default_name(id)
+        -- The level of the character is set once it has a name.
+        Characters.join(id)
         return 0
     end
     UiContainer.NameMenu.id = id
@@ -310,9 +340,20 @@ end
 -- @param menu The name of the menu.
 open_menu = function(menu)
     if menu == "party" then
-        -- TODO
+        -- The button that asked for the menu is still down: wait for it, or it would close the menu.
+        while entity_manager:is_key_on(16 + 64) do script:wait(0) end
+        script:request_end_sync(Script.UI, "MainMenu", "show", 0)
+        while ui_manager:get_widget("MainMenu"):is_visible() do script:wait(0) end
+        -- The same with the button that closed it: the script would see it as a new request.
+        while entity_manager:is_key_on(16 + 64) do script:wait(0) end
     elseif menu == "save" then
-        -- TODO
+        -- The button that asked for the menu (a script may read it) is down: wait for it.
+        while entity_manager:is_key_on(32 + 64) do script:wait(0) end
+        UiContainer.SaveMenu.operation = "save"
+        UiContainer.SaveMenu.standalone = true
+        script:request_end_sync(Script.UI, "SaveMenu", "show", 0)
+        while UiContainer.current_menu == "save" do script:wait(0) end
+        while entity_manager:is_key_on(32 + 64) do script:wait(0) end
     end
 end
 
@@ -320,7 +361,13 @@ end
 --
 -- @param id Shop ID.
 open_shop = function(id)
-    -- TODO: Implement
+    -- The button that talked to the shop (a script may read it) is down: wait for it, or it would
+    -- act in the menu.
+    while entity_manager:is_key_on(32 + 64) do script:wait(0) end
+    UiContainer.ShopMenu.shop_id = tonumber(id)
+    script:request_end_sync(Script.UI, "ShopMenu", "show", 0)
+    while UiContainer.current_menu == "shop" do script:wait(0) end
+    while entity_manager:is_key_on(32 + 64) do script:wait(0) end
 end
 
 --- Plays one of the tracks assigned to the field.
@@ -328,10 +375,12 @@ end
 -- @param id ID of the track in the field.
 play_map_music = function(id)
     local track_id = audio_manager:get_track_id(id)
+    -- A track of the field with no music (-1, an empty AKAO frame of the field file) is silence: the
+    -- scenes use it between two tracks, and some fields (trackin) have no music at all.
     if track_id ~= -1 then
         audio_manager:play_music(tostring(track_id))
     else
-        print("Requested non-existent music track ID " .. tostring(id))
+        audio_manager:stop_music()
     end
 end
 
@@ -347,8 +396,9 @@ end
 -- @param fade_in Fade in parameter of the original opcode (0 means no fade).
 change_map_music = function(id, fade_out, fade_in)
     local track_id = audio_manager:get_track_id(id)
+    -- A track with no music is silence (see play_map_music).
     if track_id == -1 then
-        print("Requested non-existent music track ID " .. tostring(id))
+        audio_manager:stop_music()
         return
     end
     if fade_in == 0 then
@@ -448,15 +498,18 @@ System["MapChanger"] = {
 
 --- Runs a script of the entity of a character (the PREQ, PRQSW and PRQEW opcodes).
 --
--- @param character ID of the character, the one that the entity was given with the PC opcode.
+-- @param character Slot of the party (0 is the leader), not the ID of a character: the scripts of a
+-- scene with another party (Aerith leading the party, for example) ask for the slot, and the
+-- request goes to the entity of the character that is in it (the one given with the PC opcode).
 -- @param script_name Name of the script function.
 -- @param priority Priority of the script.
 -- @param mode "request" does not wait, "start_sync" waits for the script to start and "end_sync" for
 -- it to end.
 party_request = function(character, script_name, priority, mode)
-    local entity = entity_manager:get_entity_from_character_id(character)
+    local character_id = Party[character + 1]
+    local entity = character_id ~= nil and entity_manager:get_entity_from_character_id(character_id) or nil
     if entity == nil then
-        print("party_request: there is no entity for the character " .. tostring(character) .. ".")
+        print("party_request: there is no entity for the party slot " .. tostring(character) .. ".")
         return
     end
     local name = entity:get_name()

+ 463 - 0
data/data/scripts/menu/exchange_menu.lua

@@ -0,0 +1,463 @@
+if UiContainer == nil then UiContainer = {} end
+
+--- The materia exchange menu (Materia > Order > Exchange).
+--
+-- The left window lists every character enabled in the PHS, with the slots of their weapon and
+-- armor. The right window is the materia of the inventory. The cursor goes through all the slots
+-- and all the positions of the inventory.
+--
+-- Confirm on a position with a materia picks it up: its cursor stays blinking while the real one
+-- moves. Confirm on another position swaps the two (the destination can be empty). Confirm on the
+-- picked position, or cancel, drops it. Cancel with nothing picked closes the menu.
+--
+-- A position is a table: {kind = "equip", char = index in `chars`, part = "weapon" or "armor",
+-- slot = 0-7} or {kind = "inv", index = slot of Materia}.
+UiContainer.ExchangeMenu = UiContainer.Menu.new{
+
+    id = "exchange",
+
+    --- Menu that opened this one.
+    parent = "materia",
+
+    --- Character blocks shown at once in the left window.
+    BLOCKS = 4,
+
+    --- Rows shown at once in the inventory window.
+    INV_ROWS = 14,
+
+    --- Position and size of the elements of the left window.
+    BLOCK_Y = 0,
+    BLOCK_HEIGHT = 58,
+    ROW_Y = {weapon = 22, armor = 39},
+    SLOT_X = 70,
+    SLOT_PITCH = 16,
+
+    --- Position of the rows of the inventory window.
+    INV_Y = 6,
+    INV_PITCH = 16,
+
+    --- IDs of the characters in the list (enabled in the PHS).
+    chars = {},
+
+    --- First character shown in the left window.
+    first = 1,
+
+    --- First inventory slot shown in the right window.
+    inv_first = 1,
+
+    --- Position of the cursor.
+    pos = nil,
+
+    --- Position of the picked materia, or nil.
+    held = nil,
+
+    --- Last position of the left window and of the inventory the cursor was on, to come back to.
+    last_equip = nil,
+    last_inv = 1,
+
+    states = {
+        [""] = {
+            confirm_sound = false,
+            cancel_sound = false,
+            confirm = function(self) return self:confirm() end,
+            cancel = function(self) return self:cancel() end,
+            buttons = {},
+        },
+    },
+
+    -----------------------------------------------------------------------------------------------
+    -- Opening and closing
+    -----------------------------------------------------------------------------------------------
+
+    --- Opens the menu.
+    show = function(self)
+        self.chars = {}
+        for char_id = 0, 8 do
+            local character = Characters[char_id]
+            if type(character) == "table" and character.enabled == true then
+                self.chars[#self.chars + 1] = char_id
+            end
+        end
+        self.first = 1
+        self.inv_first = 1
+        self.held = nil
+        self.last_inv = 1
+        self.last_equip = nil
+        local rows = self:rows()
+        if #rows > 0 then
+            self.pos = {kind = "equip", char = rows[1].char, part = rows[1].part, slot = 0}
+        else
+            self.pos = {kind = "inv", index = 1}
+        end
+        self:activate()
+        ui_manager:get_widget("MateriaMenu"):set_visible(false)
+        ui_manager:get_widget("ExchangeMenu"):set_visible(true)
+        self:refresh()
+        return 0
+    end,
+
+    --- Closes the menu and goes back to the materia menu.
+    hide = function(self)
+        ui_manager:get_widget("ExchangeMenu"):set_visible(false)
+        ui_manager:get_widget("MateriaMenu"):set_visible(true)
+        UiContainer.current_menu = "materia"
+        UiContainer.current_submenu = "order"
+        -- The materia menu shows the equipment, so it has to know what changed.
+        UiContainer.MateriaMenu:on_exchange_closed()
+        return 0
+    end,
+
+    -----------------------------------------------------------------------------------------------
+    -- Positions
+    -----------------------------------------------------------------------------------------------
+
+    --- Number of materia slots of the weapon or armor of a character of the list.
+    slot_count = function(self, char, part)
+        local equipment = Characters[self.chars[char]][part]
+        return #(Game.Items[equipment.id].slots)
+    end,
+
+    --- Rows of the left window that have slots, in order.
+    --
+    -- @return List of {char = index in `chars`, part = "weapon" or "armor", slots = count}.
+    rows = function(self)
+        local rows = {}
+        for char = 1, #self.chars do
+            for _, part in ipairs({"weapon", "armor"}) do
+                local count = self:slot_count(char, part)
+                if count > 0 then rows[#rows + 1] = {char = char, part = part, slots = count} end
+            end
+        end
+        return rows
+    end,
+
+    --- Gets the materia in a position (nil if empty).
+    get = function(self, pos)
+        if pos.kind == "inv" then return Materia[pos.index] end
+        return Characters[self.chars[pos.char]][pos.part].materia[pos.slot]
+    end,
+
+    --- Puts a materia (or nil) in a position.
+    set = function(self, pos, materia)
+        if pos.kind == "inv" then
+            Materia[pos.index] = materia
+        else
+            Characters[self.chars[pos.char]][pos.part].materia[pos.slot] = materia
+        end
+    end,
+
+    --- Are two positions the same?
+    same = function(self, a, b)
+        if a == nil or b == nil or a.kind ~= b.kind then return false end
+        if a.kind == "inv" then return a.index == b.index end
+        return a.char == b.char and a.part == b.part and a.slot == b.slot
+    end,
+
+    --- Moves the cursor up or down.
+    --
+    -- In the left window it goes through the rows that have slots (wrapping around), keeping the
+    -- column or going to the last slot of a shorter row. In the inventory it goes through all the
+    -- slots, without wrapping.
+    move_vertical = function(self, delta)
+        local pos = self.pos
+        if pos.kind == "inv" then
+            local index = pos.index + delta
+            if index < 1 or index > MAX_MATERIA_SLOTS then
+                UiContainer.play_sound("Error")
+                return
+            end
+            pos.index = index
+        else
+            local rows = self:rows()
+            local current = 1
+            for i, row in ipairs(rows) do
+                if row.char == pos.char and row.part == pos.part then current = i end
+            end
+            local target = rows[(current - 1 + delta) % #rows + 1]
+            pos.char, pos.part = target.char, target.part
+            pos.slot = math.min(pos.slot, target.slots - 1)
+        end
+        UiContainer.play_sound("Cursor")
+        self:refresh()
+    end,
+
+    --- Moves the cursor left or right.
+    --
+    -- Right from the last slot of a row goes to the inventory, and left from the inventory goes
+    -- back to the slot it came from.
+    move_horizontal = function(self, delta)
+        local pos = self.pos
+        if pos.kind == "inv" then
+            if delta > 0 then
+                UiContainer.play_sound("Error")
+                return
+            end
+            local rows = self:rows()
+            if #rows == 0 then
+                UiContainer.play_sound("Error")
+                return
+            end
+            self.last_inv = pos.index
+            local back = self.last_equip or {char = rows[1].char, part = rows[1].part, slot = 0}
+            self.pos = {kind = "equip", char = back.char, part = back.part, slot = back.slot}
+        else
+            local slot = pos.slot + delta
+            if slot < 0 then
+                UiContainer.play_sound("Error")
+                return
+            elseif slot >= self:slot_count(pos.char, pos.part) then
+                self.last_equip = {char = pos.char, part = pos.part, slot = pos.slot}
+                self.pos = {kind = "inv", index = self.last_inv}
+            else
+                pos.slot = slot
+            end
+        end
+        UiContainer.play_sound("Cursor")
+        self:refresh()
+    end,
+
+    --- Moves the cursor in the inventory by a page.
+    move_page = function(self, delta)
+        if self.pos.kind ~= "inv" then return end
+        local index = math.max(1, math.min(MAX_MATERIA_SLOTS, self.pos.index + delta * self.INV_ROWS))
+        if index == self.pos.index then
+            UiContainer.play_sound("Error")
+            return
+        end
+        UiContainer.play_sound("Cursor")
+        self.pos.index = index
+        self:refresh()
+    end,
+
+    -----------------------------------------------------------------------------------------------
+    -- Actions
+    -----------------------------------------------------------------------------------------------
+
+    --- Confirm: picks up the materia of the cursor, or swaps it with the picked one.
+    confirm = function(self)
+        if self.held == nil then
+            if self:get(self.pos) == nil then return false end
+            UiContainer.play_sound("Cursor")
+            self.held = {}
+            for key, value in pairs(self.pos) do self.held[key] = value end
+            self:refresh()
+            return
+        end
+        if self:same(self.held, self.pos) then
+            UiContainer.play_sound("Back")
+            self.held = nil
+            self:refresh()
+            return
+        end
+        local from, to = self.held, self.pos
+        local moved, replaced = self:get(from), self:get(to)
+        self:set(from, replaced)
+        self:set(to, moved)
+        self.held = nil
+        -- The materia change the stats of the characters involved, and the current HP and MP can't
+        -- be over the new maximums.
+        local recalculated = {}
+        for _, pos in ipairs({from, to}) do
+            if pos.kind == "equip" and not recalculated[pos.char] then
+                recalculated[pos.char] = true
+                Characters.recalculate_stats(self.chars[pos.char])
+            end
+        end
+        UiContainer.play_sound("Cursor")
+        self:refresh()
+    end,
+
+    --- Cancel: drops the picked materia, or closes the menu.
+    cancel = function(self)
+        if self.held ~= nil then
+            self.held = nil
+            self:refresh()
+            UiContainer.play_sound("Back")
+            return
+        end
+        UiContainer.play_sound("Back")
+        script:request_end_sync(Script.UI, "ExchangeMenu", "hide", 0)
+    end,
+
+    -----------------------------------------------------------------------------------------------
+    -- Widgets
+    -----------------------------------------------------------------------------------------------
+
+    --- Scrolls the windows so that the cursor is in them, and redraws everything.
+    refresh = function(self)
+        local pos = self.pos
+        if pos.kind == "equip" then
+            if pos.char < self.first then
+                self.first = pos.char
+            elseif pos.char > self.first + self.BLOCKS - 1 then
+                self.first = pos.char - self.BLOCKS + 1
+            end
+        else
+            if pos.index < self.inv_first then
+                self.inv_first = pos.index
+            elseif pos.index > self.inv_first + self.INV_ROWS - 1 then
+                self.inv_first = pos.index - self.INV_ROWS + 1
+            end
+        end
+        self:populate_equip()
+        self:populate_inventory()
+        self:place_cursors()
+        local materia = self:get(pos)
+        self:populate_info(materia)
+        ui_manager:get_widget("ExchangeMenu.Container.Help.Help"):set_text(
+            materia ~= nil and Game.Materia[materia.id].description or "")
+    end,
+
+    --- Fills the top bar with the icon, name and stars of a materia (nothing if it is nil).
+    populate_info = function(self, materia)
+        local bar = "ExchangeMenu.Container.Info."
+        ui_manager:get_widget(bar .. "Icon"):set_visible(materia ~= nil)
+        ui_manager:get_widget(bar .. "Name"):set_visible(materia ~= nil)
+        local data = materia ~= nil and Game.Materia[materia.id] or nil
+        local levels = data ~= nil and data.levels_ap or {}
+        local level = 0
+        for _, level_ap in ipairs(levels) do
+            if level_ap > (materia.ap or 0) then break end
+            level = level + 1
+        end
+        if data ~= nil then
+            ui_manager:get_widget(bar .. "Icon"):set_image("icons/materia_" .. tostring(data.type) .. ".png")
+            ui_manager:get_widget(bar .. "Name"):set_text(data.name)
+        end
+        for star = 1, 5 do
+            local widget = ui_manager:get_widget(bar .. "Stars.Star" .. star)
+            if data == nil or star > #levels then
+                widget:set_visible(false)
+            else
+                widget:set_image((star <= level and "icons/materia_star_" or "icons/materia_star_empty_")
+                    .. tostring(data.type) .. ".png")
+                widget:set_visible(true)
+            end
+        end
+    end,
+
+    --- Fills the blocks of the left window.
+    populate_equip = function(self)
+        local window = "ExchangeMenu.Container.Characters."
+        for b = 1, self.BLOCKS do
+            local block = window .. "Block" .. b
+            local char_id = self.chars[self.first + b - 1]
+            ui_manager:get_widget(block):set_visible(char_id ~= nil)
+            if char_id ~= nil then
+                local character = Characters[char_id]
+                ui_manager:get_widget(block .. ".Portrait"):set_image("characters/" .. tostring(char_id) .. ".png")
+                ui_manager:get_widget(block .. ".Name"):set_text(character.name)
+                ui_manager:get_widget(block .. ".WIcon"):set_image("icons/item_weapon_" .. tostring(char_id) .. ".png")
+                self:populate_slots(block, "W", character.weapon)
+                self:populate_slots(block, "A", character.armor)
+            end
+        end
+        -- Scroll bar.
+        local scroll = ui_manager:get_widget(window .. "Scroll")
+        local hidden = math.max(0, #self.chars - self.BLOCKS)
+        local fraction = hidden > 0 and (self.first - 1) / hidden or 0
+        scroll:set_y(fraction * 100, 3 - fraction * 24)
+        scroll:set_visible(hidden > 0)
+        ui_manager:get_widget(window .. "ScrollBg"):set_visible(hidden > 0)
+    end,
+
+    --- Fills the slots of the weapon or armor of a block.
+    --
+    -- @param block Path of the block.
+    -- @param prefix "W" or "A".
+    -- @param equipment Weapon or armor of the character (an entry of Characters).
+    populate_slots = function(self, block, prefix, equipment)
+        local slots = Game.Items[equipment.id].slots
+        for s = 1, 8 do
+            local slot = ui_manager:get_widget(block .. "." .. prefix .. "Slot" .. s)
+            local mat = ui_manager:get_widget(block .. "." .. prefix .. "Mat" .. s)
+            slot:set_visible(#slots >= s)
+            local materia = equipment.materia[s - 1]
+            if #slots >= s and materia ~= nil then
+                mat:set_image("icons/materia_" .. tostring(Game.Materia[materia.id].type) .. ".png")
+                mat:set_visible(true)
+            else
+                mat:set_visible(false)
+            end
+            -- A link joins an odd slot with the next one.
+            if s % 2 ~= 0 then
+                ui_manager:get_widget(block .. "." .. prefix .. "Link" .. (math.floor(s / 2) + 1)):set_visible(
+                    #slots > s and slots[s] == 1)
+            end
+        end
+    end,
+
+    --- Fills the rows of the inventory window.
+    populate_inventory = function(self)
+        local window = "ExchangeMenu.Container.Inventory."
+        for r = 1, self.INV_ROWS do
+            local materia = Materia[self.inv_first + r - 1]
+            local icon = ui_manager:get_widget(window .. "Icon" .. r)
+            local name = ui_manager:get_widget(window .. "Name" .. r)
+            if materia ~= nil then
+                local data = Game.Materia[materia.id]
+                icon:set_image("icons/materia_" .. tostring(data.type) .. ".png")
+                icon:set_visible(true)
+                name:set_text(data.name)
+                name:set_visible(true)
+            else
+                icon:set_visible(false)
+                name:set_visible(false)
+            end
+        end
+        local scroll = ui_manager:get_widget(window .. "Scroll")
+        local fraction = (self.inv_first - 1) / (MAX_MATERIA_SLOTS - self.INV_ROWS)
+        scroll:set_y(fraction * 100, 3 - fraction * 24)
+    end,
+
+    --- Coordinates of a position inside its window, and the window.
+    --
+    -- @return Window ("Characters" or "Inventory"), x, y, or nil if the position is not visible.
+    cursor_place = function(self, pos)
+        if pos.kind == "inv" then
+            local row = pos.index - self.inv_first
+            if row < 0 or row >= self.INV_ROWS then return nil end
+            return "Inventory", -8, self.INV_Y + self.INV_PITCH * row - 1
+        end
+        local block = pos.char - self.first
+        if block < 0 or block >= self.BLOCKS then return nil end
+        return "Characters", self.SLOT_X + self.SLOT_PITCH * pos.slot - 22,
+            self.BLOCK_Y + self.BLOCK_HEIGHT * block + self.ROW_Y[pos.part] - 1
+    end,
+
+    --- Places the cursor and the blinking cursor of the picked materia.
+    place_cursors = function(self)
+        local base = "ExchangeMenu.Container."
+        for _, window in ipairs({"Characters", "Inventory"}) do
+            ui_manager:get_widget(base .. window .. ".Cursor"):set_visible(false)
+            ui_manager:get_widget(base .. window .. ".Held"):set_visible(false)
+        end
+        local function place(pos, name)
+            if pos == nil then return end
+            local window, x, y = self:cursor_place(pos)
+            if window == nil then return end
+            local cursor = ui_manager:get_widget(base .. window .. "." .. name)
+            cursor:set_x(0, x)
+            cursor:set_y(0, y)
+            cursor:set_visible(true)
+            if name == "Held" then cursor:set_default_animation("Blink") end
+        end
+        place(self.pos, "Cursor")
+        place(self.held, "Held")
+    end,
+}
+
+--- Directional buttons and pages.
+local function direction(handler)
+    return function(self, event)
+        if event == "Press" or event == "Repeat" then handler(self) end
+    end
+end
+
+local buttons = UiContainer.ExchangeMenu.states[""].buttons
+buttons[Config.CONTROLS.UP] = direction(function(self) self:move_vertical(-1) end)
+buttons[Config.CONTROLS.DOWN] = direction(function(self) self:move_vertical(1) end)
+buttons[Config.CONTROLS.LEFT] = direction(function(self) self:move_horizontal(-1) end)
+buttons[Config.CONTROLS.RIGHT] = direction(function(self) self:move_horizontal(1) end)
+buttons[Config.ACTIONS.L1] = direction(function(self) self:move_page(-1) end)
+buttons[Config.ACTIONS.R1] = direction(function(self) self:move_page(1) end)

+ 100 - 16
data/data/scripts/menu/item_menu.lua

@@ -71,6 +71,12 @@ UiContainer.ItemMenu = {
     -- Slots in the party inventory
     inventory_size = 320,
 
+    --- True while the items are being ordered by hand (Order > Custom).
+    custom_mode = false,
+
+    --- Inventory position of the item picked in the custom order, or nil.
+    custom_held = nil,
+
     --- Run when the menu is creaded.
     --
     -- It does nothing.
@@ -151,7 +157,9 @@ UiContainer.ItemMenu = {
                 elseif button == Config.ACTIONS.CONFIRM then
                     audio_manager:play_sound("Cursor")
                     if self.order_cursor_position == 1 then
-                        Inventory.sort(Inventory.ORDER.CUSTOM)
+                        -- Custom: the items are moved by hand in the list.
+                        self.submenu_custom(self)
+                        return 0
                     elseif self.order_cursor_position == 2 then
                         Inventory.sort(Inventory.ORDER.FIELD)
                     elseif self.order_cursor_position == 3 then
@@ -233,9 +241,21 @@ UiContainer.ItemMenu = {
                     end
                 elseif button == Config.ACTIONS.CANCEL and event == "Press" then
                     audio_manager:play_sound("Back")
-                    self.submenu_bar(self)
-                    UiContainer.current_submenu = "bar_selection"
-                    ui_manager:get_widget("ItemMenu.Container.ItemList.Cursor"):set_visible(false)
+                    if self.custom_mode then
+                        if self.custom_held ~= nil then
+                            -- Drop the picked item.
+                            self.custom_held = nil
+                        else
+                            -- Back to the order options.
+                            self.submenu_order(self)
+                        end
+                    else
+                        self.submenu_bar(self)
+                        UiContainer.current_submenu = "bar_selection"
+                        ui_manager:get_widget("ItemMenu.Container.ItemList.Cursor"):set_visible(false)
+                    end
+                elseif button == Config.ACTIONS.CONFIRM and event == "Press" and self.custom_mode then
+                    self.custom_confirm(self)
                 elseif button == Config.ACTIONS.CONFIRM then
                     local selected = Inventory[self.item_cursor_item_selected]
                     if selected ~= nil and Game.Items[selected.item].menu == 1 then
@@ -436,6 +456,8 @@ UiContainer.ItemMenu = {
                 end
 
             end
+            -- The blinking cursor of the custom order follows the list when it scrolls.
+            if self.custom_mode then self.update_held(self) end
         end
         return 0
     end,
@@ -465,6 +487,9 @@ UiContainer.ItemMenu = {
     --- Initializes the selection of the menu section in the top bar.
     submenu_bar = function(self)
         UiContainer.current_submenu = "bar_selection"
+        self.custom_mode = false
+        self.custom_held = nil
+        self.update_held(self)
         ui_manager:get_widget("ItemMenu.Container.ItemList.Cursor"):set_visible(false)
         ui_manager:get_widget("ItemMenu.Container.ItemMenuCharacters.Cursor"):set_visible(false)
         ui_manager:get_widget("ItemMenu.Container.ItemMenuCharacters.CursorMultiple"):set_visible(false)
@@ -479,6 +504,9 @@ UiContainer.ItemMenu = {
     --- Initializes the sorting mode window.
     submenu_order = function(self)
         UiContainer.current_submenu = "order_selection"
+        self.custom_mode = false
+        self.custom_held = nil
+        self.update_held(self)
         self.order_cursor_position = 1
         ui_manager:get_widget("ItemMenu.Container.ItemList.Cursor"):set_visible(false)
         ui_manager:get_widget("ItemMenu.Container.ItemMenuCharacters.Cursor"):set_visible(false)
@@ -491,6 +519,56 @@ UiContainer.ItemMenu = {
         ui_manager:get_widget("ItemMenu.Container.ItemOrder.Cursor"):set_default_animation("Position" .. self.order_cursor_position)
     end,
 
+    --- Starts the custom order: the cursor goes over the list of items, and they can be swapped.
+    submenu_custom = function(self)
+        self.custom_mode = true
+        self.custom_held = nil
+        ui_manager:get_widget("ItemMenu.Container.ItemOrder"):set_visible(false)
+        ui_manager:get_widget("ItemMenu.Container.ItemOrder.Cursor"):set_visible(false)
+        self.submenu_items(self)
+    end,
+
+    --- Confirm in the custom order: picks the highlighted item, or swaps it with the picked one.
+    --
+    -- Items can only be swapped with other items, so the list never gets empty places in the
+    -- middle.
+    custom_confirm = function(self)
+        local index = self.item_cursor_item_selected
+        if self.custom_held == nil then
+            if Inventory[index] == nil then
+                audio_manager:play_sound("Error")
+                return
+            end
+            audio_manager:play_sound("Cursor")
+            self.custom_held = index
+        elseif self.custom_held == index then
+            audio_manager:play_sound("Back")
+            self.custom_held = nil
+        elseif Inventory[index] == nil then
+            audio_manager:play_sound("Error")
+        else
+            audio_manager:play_sound("Cursor")
+            Inventory[self.custom_held], Inventory[index] = Inventory[index], Inventory[self.custom_held]
+            self.custom_held = nil
+            self.populate_items(self)
+            self.show_item_description(self)
+        end
+    end,
+
+    --- Places the blinking cursor of the item picked in the custom order, or hides it.
+    update_held = function(self)
+        local held = ui_manager:get_widget("ItemMenu.Container.ItemList.Held")
+        local row = nil
+        if self.custom_held ~= nil then row = self.custom_held - self.first_item_in_window end
+        if row == nil or row < 1 or row > self.item_cursor_position_total then
+            held:set_visible(false)
+            return
+        end
+        held:set_visible(true)
+        held:set_default_animation("Blink" .. tostring(row))
+        held:play_animation("Blink" .. tostring(row))
+    end,
+
     --- Shows the description of the highlighted inventory item, or clears it if the slot is empty.
     show_item_description = function(self)
         local label = ui_manager:get_widget("ItemMenu.Container.ItemMenuSecondBar.ItemText")
@@ -763,28 +841,34 @@ UiContainer.ItemMenu = {
                 end
         elseif Game.Items[item].id == 71 then
             -- Power source. Can't be differenciated by other means other than ID. STR bonus + 1.
-            -- Original game caps bonus at 255. V-Gears doesn't.
-            Characters[char_id].stats.str.bonus = Characters[char_id].stats.str.bonus + 1
+            if not Characters.add_stat_bonus(char_id, "str") then
+                return false
+            end
         elseif Game.Items[item].id == 72 then
             -- Guard source. Can't be differenciated by other means other than ID. VIT bonus + 1.
-            -- Original game caps bonus at 255. V-Gears doesn't.
-            Characters[char_id].stats.vit.bonus = Characters[char_id].stats.vit.bonus + 1
+            if not Characters.add_stat_bonus(char_id, "vit") then
+                return false
+            end
         elseif Game.Items[item].id == 73 then
             -- Magic source. Can't be differenciated by other means other than ID. MAG bonus + 1.
-            -- Original game caps bonus at 255. V-Gears doesn't.
-            Characters[char_id].stats.mag.bonus = Characters[char_id].stats.mag.bonus + 1
+            if not Characters.add_stat_bonus(char_id, "mag") then
+                return false
+            end
         elseif Game.Items[item].id == 74 then
             -- Mind source. Can't be differenciated by other means other than ID. SPR bonus + 1.
-            -- Original game caps bonus at 255. V-Gears doesn't.
-            Characters[char_id].stats.spr.bonus = Characters[char_id].stats.spr.bonus + 1
+            if not Characters.add_stat_bonus(char_id, "spr") then
+                return false
+            end
         elseif Game.Items[item].id == 75 then
             -- Speed source. Can't be differenciated by other means other than ID. DEX bonus + 1.
-            -- Original game caps bonus at 255. V-Gears doesn't.
-            Characters[char_id].stats.dex.bonus = Characters[char_id].stats.dex.bonus + 1
+            if not Characters.add_stat_bonus(char_id, "dex") then
+                return false
+            end
         elseif Game.Items[item].id == 76 then
             -- Luck source. Can't be differenciated by other means other than ID. LCK bonus + 1.
-            -- Original game caps bonus at 255. V-Gears doesn't.
-            Characters[char_id].stats.lck.bonus = Characters[char_id].stats.lck.bonus + 1
+            if not Characters.add_stat_bonus(char_id, "lck") then
+                return false
+            end
         elseif Game.Items[item].id == 87 then
             -- Omnislash. Can't be differenciated by other means other than ID.
             -- Functionality hardcoded here.

+ 53 - 4
data/data/scripts/menu/main_menu.lua

@@ -13,6 +13,7 @@ local BAR_WIDTH = 62
 local STAY = "stay"
 
 local CHARACTERS_CURSOR = "MainMenu.Container.Characters.Cursor"
+local CHARACTERS_HELD = "MainMenu.Container.Characters.Held"
 
 --- The main menu.
 UiContainer.MainMenu = UiContainer.Menu.new{
@@ -78,11 +79,12 @@ UiContainer.MainMenu = UiContainer.Menu.new{
             UiContainer.current_character_id = Party[slot]
             script:request_end_sync(Script.UI, "StatusMenu", "show", 0)
         end,
-        --- Toggles the row (front/back) of the character. Stays in the character selection.
+        --- Picks the character to change its row or swap it with another party slot.
+        -- A blinking cursor stays on it while the cursor moves (see the order_swap state).
         [ENTRY.ORDER] = function(self, slot)
-            local character = Characters[Party[slot]]
-            character.back_row = not character.back_row
-            self:update_portrait(slot)
+            self.order_held = slot
+            self:set_order_held(slot)
+            self:set_state("order_swap")
             return STAY
         end,
         [ENTRY.LIMIT] = function(self, slot)
@@ -91,6 +93,9 @@ UiContainer.MainMenu = UiContainer.Menu.new{
         end,
     },
 
+    --- Party slot of the character picked with Order.
+    order_held = 0,
+
     states = {
         --- Choosing an entry of the menu.
         [""] = {
@@ -137,8 +142,52 @@ UiContainer.MainMenu = UiContainer.Menu.new{
                 ui_manager:get_widget(CHARACTERS_CURSOR):set_visible(false)
             end,
         },
+
+        --- Order: a character is picked (blinking cursor) and the cursor moves over the three
+        -- party slots, empty ones included. Confirm on the picked character toggles its row;
+        -- confirm on another slot swaps the two.
+        order_swap = {
+            cursor = function(self) return self.character_cursor end,
+            axis = "vertical",
+            confirm_sound = false,
+            cancel = function(self)
+                self:set_order_held(nil)
+                self:set_state("main_character")
+            end,
+            confirm = function(self, cursor)
+                local held, slot = self.order_held, cursor:index()
+                if slot == held then
+                    local character = Characters[Party[held]]
+                    character.back_row = not character.back_row
+                    self:update_portrait(held)
+                    UiContainer.play_sound("Cursor")
+                else
+                    -- The first slot can't be left empty.
+                    if Party[slot] == nil and held == 1 then return false end
+                    Party[held], Party[slot] = Party[slot], Party[held]
+                    self:populate_character(held)
+                    self:populate_character(slot)
+                    UiContainer.play_sound("Cursor")
+                end
+                self:set_order_held(nil)
+                self:set_state("main_character")
+            end,
+        },
     },
 
+    --- Shows (or hides, with nil) the blinking cursor that marks the character picked with Order.
+    set_order_held = function(self, slot)
+        local held = ui_manager:get_widget(CHARACTERS_HELD)
+        held:set_visible(slot ~= nil)
+        if slot ~= nil then
+            local animation = "Blink" .. tostring(slot)
+            held:set_default_animation(animation)
+            held:play_animation(animation)
+        else
+            held:set_alpha(1.0)
+        end
+    end,
+
     --- Handles the menu button while the main menu is closed.
     on_inactive_button = function(self, button, event)
         if ui_manager:get_widget("MainMenu"):is_visible() == false

+ 408 - 7
data/data/scripts/menu/materia_menu.lua

@@ -30,6 +30,49 @@ UiContainer.MateriaMenu = {
     --- Max materias in the list
     list_size = 200,
 
+    --- Commands of the character, shown in the Check window.
+    commands = {},
+
+    --- Cursor over the commands of the Check window (columns of four, filled top to bottom).
+    command_cursor = UiContainer.Cursor.new{
+        widget = "MateriaMenu.Container.Details.Commands.Box.Cursor",
+        total = 1,
+        on_move = function() UiContainer.MateriaMenu:populate_command_help() end,
+    },
+
+    --- Cursor over the options of the Order menu.
+    order_cursor = UiContainer.Cursor.new{
+        widget = "MateriaMenu.Container.OrderMenu.Cursor",
+        total = 4,
+        wrap = true,
+        on_move = function() UiContainer.MateriaMenu:populate_order_help() end,
+    },
+
+    --- Descriptions of the options of the Order menu.
+    ORDER_HELP = {
+        "Sort the materia in the inventory",
+        "Exchange materia between the characters and the inventory",
+        "Remove all the materia equipped on the character",
+        "Trash materia",
+    },
+
+    --- Options of the Order menu that are not available yet.
+    ORDER_DISABLED = {},
+
+    --- True while the materia list is used to choose a materia to trash (Order > Trash).
+    trash_mode = false,
+
+    --- Entries of the list of spells, summons or enemy skills of a command.
+    abilities = {},
+
+    --- Cursor over the abilities list.
+    ability_cursor = UiContainer.ListCursor.new{
+        widget = "MateriaMenu.Container.Abilities.Cursor",
+        rows = 10,
+        on_scroll = function() UiContainer.MateriaMenu:populate_abilities() end,
+        on_move = function() UiContainer.MateriaMenu:populate_ability_help() end,
+    },
+
     --- Run when the menu is creaded.
     --
     -- It does nothing.
@@ -85,9 +128,15 @@ UiContainer.MateriaMenu = {
                     self.populate_details(self, false)
                 elseif button == Config.ACTIONS.CONFIRM then
                     if self.header_position_row == 1 and self.header_position == 1 then
-                        -- TODO: Command menu
+                        if #self.commands == 0 then
+                            audio_manager:play_sound("Error")
+                        else
+                            audio_manager:play_sound("Cursor")
+                            self.submenu_commands(self)
+                        end
                     elseif self.header_position_row == 2 and self.header_position == 1 then
-                        -- TODO: Order menu
+                        audio_manager:play_sound("Cursor")
+                        self.submenu_order(self)
                     else
                         -- TODO: Check for  avalid slot before entering list
                         if self.header_position_row == 1 and #(Game.Items[Characters[self.char_id].weapon.id].slots) > self.header_position - 2 then
@@ -104,6 +153,31 @@ UiContainer.MateriaMenu = {
                 else
                     return 0
                 end
+            elseif UiContainer.current_submenu == "order" then
+                if button == Config.ACTIONS.CANCEL and event == "Press" then
+                    audio_manager:play_sound("Back")
+                    self.submenu_none(self)
+                elseif button == Config.ACTIONS.CONFIRM and event == "Press" then
+                    self.run_order(self)
+                elseif event == "Press" or event == "Repeat" then
+                    self.order_cursor:handle(button, "vertical")
+                end
+            elseif UiContainer.current_submenu == "commands" then
+                if button == Config.ACTIONS.CANCEL and event == "Press" then
+                    audio_manager:play_sound("Back")
+                    self.submenu_none(self)
+                elseif button == Config.ACTIONS.CONFIRM and event == "Press" then
+                    self.open_command(self)
+                elseif event == "Press" or event == "Repeat" then
+                    self:move_command_cursor(button)
+                end
+            elseif UiContainer.current_submenu == "abilities" then
+                if button == Config.ACTIONS.CANCEL and event == "Press" then
+                    audio_manager:play_sound("Back")
+                    self.submenu_commands(self)
+                elseif event == "Press" or event == "Repeat" then
+                    self.ability_cursor:handle(button, "vertical")
+                end
             elseif UiContainer.current_submenu == "list" then
                 if button == Config.CONTROLS.DOWN then
                     if self.list_first_visible + self.list_position > self.list_size then
@@ -161,11 +235,27 @@ UiContainer.MateriaMenu = {
                     end
                 elseif button == Config.ACTIONS.CANCEL and event == "Press" then
                     audio_manager:play_sound("Back")
-                    self.submenu_none(self)
+                    if self.trash_mode then
+                        self.submenu_order(self)
+                        self.order_cursor:set(4)
+                    else
+                        self.submenu_none(self)
+                    end
                 elseif button == Config.ACTIONS.CONFIRM then
-                    -- TODO: Replace for "Equip materia" sound.
-                    audio_manager:play_sound("Cursor")
-                    self.equip_materia(self)
+                    if self.trash_mode then
+                        self.submenu_trash_confirm(self)
+                    else
+                        -- TODO: Replace for "Equip materia" sound.
+                        audio_manager:play_sound("Cursor")
+                        self.equip_materia(self)
+                    end
+                end
+            elseif UiContainer.current_submenu == "trash_confirm" then
+                if button == Config.ACTIONS.CANCEL and event == "Press" then
+                    audio_manager:play_sound("Back")
+                    self.submenu_trash(self)
+                elseif button == Config.ACTIONS.CONFIRM and event == "Press" then
+                    self.trash_materia(self)
                 end
             end
         end
@@ -193,17 +283,309 @@ UiContainer.MateriaMenu = {
     --- Enters or returns to the main equip menu.
     submenu_none = function(self)
         UiContainer.current_submenu = ""
+        self.trash_mode = false
+        ui_manager:get_widget("MateriaMenu.Container.TrashWindow"):set_visible(false)
         UiContainer.populate_character_data("MateriaMenu.Container.Character", Characters[self.char_id])
         ui_manager:get_widget("MateriaMenu.Container.Character.Portrait"):set_image("characters/" .. tostring(self.char_id) .. ".png")
         self.populate_equip(self)
         -- TODO: Do something for chars 9 and 10
         ui_manager:get_widget("MateriaMenu.Container.Character.WpnIcon"):set_image("icons/item_weapon_" .. tostring(self.char_id) .. ".png")
         ui_manager:get_widget("MateriaMenu.Container.List.Cursor"):set_visible(false)
+        ui_manager:get_widget("MateriaMenu.Container.Abilities"):set_visible(false)
+        ui_manager:get_widget("MateriaMenu.Container.OrderMenu"):set_visible(false)
+        ui_manager:get_widget("MateriaMenu.Container.Details.Commands.Box.Cursor"):set_visible(false)
         --TODO: Uncomment when implemented: ui_manager:get_widget("MateriaMenu.Container.Order.Cursor"):set_visible(false)
         ui_manager:get_widget("MateriaMenu.Container.Character.Cursor"):set_visible(true)
         self.populate_details(self, false)
     end,
 
+    --- Refreshes the menu after the exchange menu closed (the equipment and stats may have changed).
+    on_exchange_closed = function(self)
+        UiContainer.populate_character_data("MateriaMenu.Container.Character", Characters[self.char_id])
+        self.populate_equip(self)
+        self.populate_list(self)
+        self.populate_order_help(self)
+    end,
+
+    --- Opens the Order menu (Arrange, Exchange, Remove all, Trash).
+    submenu_order = function(self)
+        UiContainer.current_submenu = "order"
+        self.trash_mode = false
+        ui_manager:get_widget("MateriaMenu.Container.TrashWindow"):set_visible(false)
+        ui_manager:get_widget("MateriaMenu.Container.List.Cursor"):set_visible(false)
+        ui_manager:get_widget("MateriaMenu.Container.OrderMenu"):set_visible(true)
+        for option = 1, 4 do
+            local item = ui_manager:get_widget("MateriaMenu.Container.OrderMenu.Item" .. option)
+            if self.ORDER_DISABLED[option] then item:set_colour(0.6, 0.6, 0.6) else item:set_colour(1, 1, 1) end
+        end
+        self.order_cursor:set(1)
+    end,
+
+    --- Enters (or returns to) the materia list to choose the materia to trash.
+    submenu_trash = function(self)
+        self.trash_mode = true
+        -- The Order popup stays open (with Trash highlighted) while choosing.
+        ui_manager:get_widget("MateriaMenu.Container.TrashWindow"):set_visible(false)
+        self.submenu_list(self)
+    end,
+
+    --- Opens the window that shows the highlighted materia before it is trashed.
+    submenu_trash_confirm = function(self)
+        local materia = Materia[self.list_first_visible + self.list_position - 1]
+        if materia == nil then
+            audio_manager:play_sound("Error")
+            return
+        end
+        audio_manager:play_sound("Cursor")
+        UiContainer.current_submenu = "trash_confirm"
+        local data = Game.Materia[materia.id]
+        local window = "MateriaMenu.Container.TrashWindow."
+        local levels = data.levels_ap or {}
+        local level = 0
+        for _, level_ap in ipairs(levels) do
+            if level_ap > (materia.ap or 0) then break end
+            level = level + 1
+        end
+        ui_manager:get_widget(window .. "Icon"):set_image("icons/materia_" .. tostring(data.type) .. ".png")
+        ui_manager:get_widget(window .. "Name"):set_text(data.name)
+        for star = 1, 5 do
+            local widget = ui_manager:get_widget(window .. "Star" .. star)
+            if star > #levels then
+                widget:set_visible(false)
+            else
+                widget:set_image((star <= level and "icons/materia_star_" or "icons/materia_star_empty_")
+                    .. tostring(data.type) .. ".png")
+                widget:set_visible(true)
+            end
+        end
+        ui_manager:get_widget(window .. "AP"):set_text(UiContainer.pad_value(materia.ap or 0, 8))
+        ui_manager:get_widget("MateriaMenu.Container.TrashWindow"):set_visible(true)
+    end,
+
+    --- Discards the materia shown in the trash window and goes back to the list.
+    trash_materia = function(self)
+        Materia[self.list_first_visible + self.list_position - 1] = nil
+        audio_manager:play_sound("Cursor")
+        self.populate_list(self)
+        self.submenu_trash(self)
+    end,
+
+    --- Shows the description of the highlighted option of the Order menu.
+    populate_order_help = function(self)
+        ui_manager:get_widget("MateriaMenu.Container.Help.Help"):set_text(self.ORDER_HELP[self.order_cursor:index()] or "")
+    end,
+
+    --- Runs the highlighted option of the Order menu.
+    run_order = function(self)
+        local option = self.order_cursor:index()
+        if self.ORDER_DISABLED[option] then
+            audio_manager:play_sound("Error")
+        elseif option == 1 then
+            audio_manager:play_sound("Cursor")
+            self.arrange_materia(self)
+        elseif option == 2 then
+            audio_manager:play_sound("Cursor")
+            script:request_end_sync(Script.UI, "ExchangeMenu", "show", 0)
+        elseif option == 4 then
+            audio_manager:play_sound("Cursor")
+            self.submenu_trash(self)
+        elseif option == 3 then
+            if self.remove_all_materia(self) then
+                audio_manager:play_sound("Cursor")
+            else
+                audio_manager:play_sound("Error")
+            end
+        end
+    end,
+
+    --- IDs of the master materia (Master Command, Master Magic and Master Summon).
+    MASTER_MATERIA = {[48] = true, [73] = true, [90] = true},
+
+    --- Sorts the materia of the inventory, as the original game does.
+    --
+    -- By type (the order of Materia.TYPE: magic, support, command, independent, summon); in each
+    -- type the master materia go first, then by ID ascending and by AP descending. The empty slots
+    -- go at the end.
+    arrange_materia = function(self)
+        local sorted = {}
+        for slot = 1, MAX_MATERIA_SLOTS do
+            if Materia[slot] ~= nil then sorted[#sorted + 1] = {materia = Materia[slot], order = #sorted} end
+        end
+        local master = self.MASTER_MATERIA
+        table.sort(sorted, function(l, r)
+            local l_id, r_id = l.materia.id, r.materia.id
+            local l_type, r_type = Game.Materia[l_id].type, Game.Materia[r_id].type
+            if l_type ~= r_type then return l_type < r_type end
+            if (master[l_id] == true) ~= (master[r_id] == true) then return master[l_id] == true end
+            if l_id ~= r_id then return l_id < r_id end
+            if (l.materia.ap or 0) ~= (r.materia.ap or 0) then return (l.materia.ap or 0) > (r.materia.ap or 0) end
+            return l.order < r.order
+        end)
+        for slot = 1, MAX_MATERIA_SLOTS do
+            Materia[slot] = sorted[slot] ~= nil and sorted[slot].materia or nil
+        end
+        self.list_first_visible = 1
+        self.list_position = 1
+        ui_manager:get_widget("MateriaMenu.Container.List.Cursor"):set_default_animation("Position1")
+        self.populate_list(self)
+    end,
+
+    --- Moves all the materia equipped on the character to the inventory.
+    --
+    -- If the inventory has not room for all of it, as many as fit are removed (the ones of the weapon
+    -- first, in slot order).
+    -- @return False if nothing was removed.
+    remove_all_materia = function(self)
+        local equipped = {}
+        local character = Characters[self.char_id]
+        for _, equipment in ipairs({character.weapon, character.armor}) do
+            for slot = 0, 7 do
+                if equipment.materia[slot] ~= nil then equipped[#equipped + 1] = {equipment, slot} end
+            end
+        end
+        local free = {}
+        for slot = 1, MAX_MATERIA_SLOTS do
+            if Materia[slot] == nil then free[#free + 1] = slot end
+        end
+        local count = math.min(#equipped, #free)
+        if count == 0 then return false end
+        for i = 1, count do
+            local place = equipped[i]
+            Materia[free[i]] = place[1].materia[place[2]]
+            place[1].materia[place[2]] = nil
+        end
+        -- The materia change the stats, and the current HP and MP can't be over the new maximums.
+        Characters.recalculate_stats(self.char_id)
+        self.submenu_none(self)
+        self.populate_list(self)
+        return true
+    end,
+
+    --- Enters (or returns to) the navigable list of commands of the Check window.
+    submenu_commands = function(self)
+        UiContainer.current_submenu = "commands"
+        ui_manager:get_widget("MateriaMenu.Container.Abilities"):set_visible(false)
+        ui_manager:get_widget("MateriaMenu.Container.Details.Commands.Box.Cursor"):set_visible(true)
+        self.command_cursor.total = #self.commands
+        if self.command_cursor.position > #self.commands then self.command_cursor.position = 1 end
+        self.command_cursor:refresh()
+    end,
+
+    --- Number of commands in each column of the Check window.
+    COMMAND_ROWS = 4,
+
+    --- Moves the command cursor. The commands fill the columns from top to bottom.
+    --
+    -- Up and down wrap inside the column, left and right wrap around the columns keeping the row
+    -- (or going to the last command of a shorter column).
+    move_command_cursor = function(self, button)
+        local rows = self.COMMAND_ROWS
+        local index = self.command_cursor:index() - 1
+        local column, row = math.floor(index / rows), index % rows
+        local columns = math.ceil(#self.commands / rows)
+        local function length(c) return math.min(rows, #self.commands - c * rows) end
+        if button == Config.CONTROLS.UP then
+            row = (row - 1) % length(column)
+        elseif button == Config.CONTROLS.DOWN then
+            row = (row + 1) % length(column)
+        elseif button == Config.CONTROLS.LEFT then
+            column = (column - 1) % columns
+            row = math.min(row, length(column) - 1)
+        elseif button == Config.CONTROLS.RIGHT then
+            column = (column + 1) % columns
+            row = math.min(row, length(column) - 1)
+        else
+            return
+        end
+        audio_manager:play_sound("Cursor")
+        self.command_cursor:set(column * rows + row + 1)
+    end,
+
+    --- Shows the description of the highlighted command.
+    populate_command_help = function(self)
+        local command = Game.Commands[self.commands[self.command_cursor:index()]]
+        ui_manager:get_widget("MateriaMenu.Container.Help.Help"):set_text(command ~= nil and command.description or "")
+    end,
+
+    --- Gets the kind of list a command opens.
+    --
+    -- @param command Definition of the command (an entry of Game.Commands).
+    -- @return "magic", "summon" or "eskill", or nil if the command has no list.
+    command_list_kind = function(self, command)
+        local menu = command ~= nil and command.menu or nil
+        if menu == Battle.Menu.MAGIC or menu == Battle.Menu.W_MAGIC then return "magic"
+        elseif menu == Battle.Menu.SUMMON or menu == Battle.Menu.W_SUMMON then return "summon"
+        elseif menu == Battle.Menu.E_SKILL then return "eskill"
+        end
+        return nil
+    end,
+
+    --- Opens the list of a command (spells, summons or enemy skills), if it has one.
+    open_command = function(self)
+        local command = Game.Commands[self.commands[self.command_cursor:index()]]
+        local kind = self:command_list_kind(command)
+        local entries = kind ~= nil and self:build_abilities(kind) or {}
+        if #entries == 0 then
+            audio_manager:play_sound("Error")
+            return
+        end
+        audio_manager:play_sound("Cursor")
+        self.abilities = entries
+        UiContainer.current_submenu = "abilities"
+        ui_manager:get_widget("MateriaMenu.Container.Abilities"):set_visible(true)
+        self.ability_cursor.count = #entries
+        self.ability_cursor:reset()
+        self:populate_abilities()
+    end,
+
+    --- Gets the spells, summons or enemy skills the character can use in battle.
+    --
+    -- @param kind "magic", "summon" or "eskill".
+    -- @return List of {attack = ID of the attack, times = uses per battle of a summon}.
+    build_abilities = function(self, kind)
+        local abilities = Characters.get_abilities(self.char_id)
+        local entries = {}
+        if kind == "magic" then
+            -- The spells of a materia go together.
+            for _, group in ipairs(abilities.magic_groups) do
+                for _, spell in ipairs(group) do entries[#entries + 1] = {attack = spell} end
+            end
+        elseif kind == "summon" then
+            for _, summon in ipairs(abilities.summon) do
+                entries[#entries + 1] = {attack = summon.id, times = summon.times}
+            end
+        else
+            for _, skill in ipairs(abilities.e_skill) do entries[#entries + 1] = {attack = skill} end
+        end
+        return entries
+    end,
+
+    --- Fills the rows of the abilities list.
+    populate_abilities = function(self)
+        local window = "MateriaMenu.Container.Abilities."
+        for row = 1, 10 do
+            local entry = self.abilities[self.ability_cursor.first + row - 1]
+            local data = entry ~= nil and Game.Attacks[entry.attack] or nil
+            if data == nil then
+                ui_manager:get_widget(window .. "Name" .. row):set_text("")
+                ui_manager:get_widget(window .. "Mp" .. row):set_text("")
+            else
+                local name = data.name
+                if entry.times ~= nil and entry.times < 255 then name = name .. " x" .. tostring(entry.times) end
+                ui_manager:get_widget(window .. "Name" .. row):set_text(name)
+                ui_manager:get_widget(window .. "Mp" .. row):set_text(UiContainer.pad_value(data.mp or 0, 3))
+            end
+        end
+        self:populate_ability_help()
+    end,
+
+    --- Shows the description of the highlighted ability.
+    populate_ability_help = function(self)
+        local entry = self.abilities[self.ability_cursor:index()]
+        local data = entry ~= nil and Game.Attacks[entry.attack] or nil
+        ui_manager:get_widget("MateriaMenu.Container.Help.Help"):set_text(data ~= nil and data.description or "")
+    end,
+
     submenu_list = function(self)
         UiContainer.current_submenu = "list"
         ui_manager:get_widget("MateriaMenu.Container.List.Cursor"):set_visible(true)
@@ -314,7 +696,26 @@ UiContainer.MateriaMenu = {
         ui_manager:get_widget("MateriaMenu.Container.Details.EnemySkill"):set_visible(false)
         ui_manager:get_widget("MateriaMenu.Container.Details.Materia"):set_visible(false)
         ui_manager:get_widget("MateriaMenu.Container.Help.Help"):set_text("")
-        -- TODO
+        -- The commands the character has in battle.
+        local commands = Characters.get_commands(self.char_id)
+        self.commands = commands
+        for i = 1, 12 do
+            local widget = ui_manager:get_widget("MateriaMenu.Container.Details.Commands.Box.Command" .. i)
+            local command = Game.Commands[commands[i]]
+            if command ~= nil then
+                widget:set_text(command.name)
+                widget:set_visible(true)
+                -- Commands with a list but nothing in it (no enemy skill learned...) are dimmed.
+                local kind = self:command_list_kind(command)
+                if kind ~= nil and #self:build_abilities(kind) == 0 then
+                    widget:set_colour(0.6, 0.6, 0.6)
+                else
+                    widget:set_colour(1, 1, 1)
+                end
+            else
+                widget:set_visible(false)
+            end
+        end
     end,
 
     --- Populated the details of the selected header item (check, materia, or none).

+ 6 - 17
data/data/scripts/menu/menu_lib.lua

@@ -37,9 +37,8 @@ end
 
 --- Calculates how much of the way to the next level a character has done.
 --
--- Uses the EXP curve of the character (see Game.Growth.curves): the EXP needed to attain a level
--- L is Mod * (L - 1)^2 / 10, where Mod is the gradient of the curve segment for L. The character
--- stores the EXP still missing for the next level (exp_to_next).
+-- The character stores the experience still missing for the next level (exp_to_next), see
+-- Characters.exp_threshold.
 --
 -- @param character Entry of the Characters table.
 -- @return A number from 0 to 1. 0 if it can't be calculated (e.g. level 99).
@@ -48,21 +47,11 @@ UiContainer.exp_progress = function(character)
     if definition == nil or definition.curves == nil or definition.curves.exp == nil then
         return 0
     end
-    local curve = Game.Growth.curves[definition.curves.exp]
     local level = character.level
-    local target = level + 1
-    if curve == nil or target > 99 then return 0 end
-    local segment
-    if target <= 11 then segment = 0
-    elseif target <= 21 then segment = 1
-    elseif target <= 31 then segment = 2
-    elseif target <= 41 then segment = 3
-    elseif target <= 51 then segment = 4
-    elseif target <= 61 then segment = 5
-    elseif target <= 81 then segment = 6
-    else segment = 7 end
-    local span = math.floor(curve[segment].gradient * level * level / 10)
-    if span <= 0 or character.exp_to_next == nil then return 0 end
+    if level >= Characters.MAX_LEVEL or character.exp_to_next == nil then return 0 end
+    local span = Characters.exp_threshold(character.char_id, level)
+      - Characters.exp_threshold(character.char_id, level - 1)
+    if span <= 0 then return 0 end
     return math.max(0, math.min(1, 1 - character.exp_to_next / span))
 end
 

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

@@ -186,6 +186,10 @@ UiContainer.NameMenu = {
         local name = Characters[id].name
         -- HACK: Hack for Ex-Soldier default. Can this be extracted from menu.lgp?
         if string.lower(name) == "ex-soldier" then return "Cloud" end
+        -- The initial data of the game only holds "Red" for him.
+        if id == 4 and string.lower(name) == "red" then return "Red XIII" end
+        -- The data of ff7.exe that he joins with spells his name wrong.
+        if id == 6 and string.lower(name) == "cait seith" then return "Cait Sith" end
         return name
     end,
 
@@ -300,6 +304,8 @@ UiContainer.NameMenu = {
         if self.chocobo == false then
             Characters[self.id].name = self.name
             export_character_names()
+            -- The level of the character is set once it has a name.
+            Characters.join(self.id)
         else
             -- TODO: Do chocobo.
         end

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

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

+ 35 - 10
data/data/scripts/menu/phs_menu.lua

@@ -55,7 +55,8 @@ local function neighbour(cell, button)
     return nil
 end
 
---- Is a character locked in its place? Locked characters can't be moved or replaced.
+--- Is a character locked in the party? Locked characters can't leave the party or join it, but they
+-- can change slots inside it.
 local function is_locked(char_id)
     return char_id ~= nil and Characters[char_id].locked == true
 end
@@ -93,8 +94,12 @@ end
 --  * party <-> party: changes the order (or moves the character to an empty slot).
 --  * party <-> reserve: the character leaves the party and the other one (if any) takes its place.
 --  * reserve <-> reserve: not allowed.
--- Locked characters can't be moved or replaced. The party can only be left once it has three
--- characters, or all the available ones if there are fewer.
+-- Locked characters can't leave the party or join it, but their slots can be swapped.
+-- The party can only be left once it has three characters, or all the available ones if there are
+-- fewer.
+--
+-- This menu never changes the leader of the field (see Party.get_leader). If the leader leaves the
+-- party, the character of the first slot becomes the leader.
 UiContainer.PhsMenu = UiContainer.Menu.new{
 
     id = "phs",
@@ -205,7 +210,8 @@ UiContainer.PhsMenu = UiContainer.Menu.new{
         local character = self:get_character(cell)
         if self.held == nil then
             -- Pick a character.
-            if character == nil or is_locked(character) then return false end
+            -- A locked character can only be moved inside the party.
+            if character == nil or (is_locked(character) and not is_party_cell(cell)) then return false end
             self:set_held(cell)
             return
         end
@@ -227,13 +233,15 @@ UiContainer.PhsMenu = UiContainer.Menu.new{
         if not is_party_cell(from) and not is_party_cell(to) then return false end
         local a = self:get_character(from)
         local b = self:get_character(to)
-        if is_locked(a) or is_locked(b) then return false end
+        -- Locked characters can swap slots in the party, but can't leave it or join it.
+        if (is_locked(a) or is_locked(b)) and not (is_party_cell(from) and is_party_cell(to)) then
+            return false
+        end
 
         -- Both cells exchange their contents, so nobody in the reserve changes place.
         self:set_character(from, b)
         self:set_character(to, a)
-        set_party(Party[1], Party[2], Party[3])
-        -- TODO: If the leader (first slot) changed, change the player entity of the field too.
+        set_party(Party[1], Party[2], Party[3], true)
         return true
     end,
 
@@ -243,7 +251,7 @@ UiContainer.PhsMenu = UiContainer.Menu.new{
         for slot = 1, PARTY_SLOTS do
             if Party[slot] ~= nil then members[#members + 1] = Party[slot] end
         end
-        set_party(members[1], members[2], members[3])
+        set_party(members[1], members[2], members[3], true)
     end,
 
     --- Shows the characters of the party and of the reserve.
@@ -283,14 +291,23 @@ UiContainer.PhsMenu = UiContainer.Menu.new{
         end
     end,
 
+    --- Is the menu opened by a field script (change party) instead of by the main menu?
+    standalone = false,
+
     --- Opens the PHS menu.
     show = function(self)
         self:activate()
+        if self.standalone then
+            entity_manager:set_paused(true)
+            MenuSettings.pause_available = false
+            self.menu_was_available = MenuSettings.available
+            MenuSettings.available = false
+        end
         -- Empty slots may hold an invalid ID (e.g. -1). Leave them as nil.
         for slot = 1, PARTY_SLOTS do
             if Party[slot] ~= nil and Characters[Party[slot]] == nil then Party[slot] = nil end
         end
-        set_party(Party[1], Party[2], Party[3])
+        set_party(Party[1], Party[2], Party[3], true)
         -- Whoever is in the party is available, even if no script enabled them.
         for slot = 1, PARTY_SLOTS do
             if Party[slot] ~= nil then Characters[Party[slot]].enabled = true end
@@ -307,7 +324,15 @@ UiContainer.PhsMenu = UiContainer.Menu.new{
     hide = function(self)
         self:compact_party()
         ui_manager:get_widget("PhsMenu"):set_visible(false)
-        self:deactivate()
+        if self.standalone then
+            self.standalone = false
+            self:deactivate("")
+            MenuSettings.available = self.menu_was_available
+            MenuSettings.pause_available = true
+            entity_manager:set_paused(false)
+        else
+            self:deactivate()
+        end
         return 0
     end,
 }

+ 102 - 6
data/data/scripts/menu/save_menu.lua

@@ -19,7 +19,48 @@ UiContainer.SaveMenu = UiContainer.Menu.new{
         on_scroll = function() UiContainer.SaveMenu:populate_slots() end,
     },
 
+    --- Cursors over Yes and No of the confirmation windows.
+    confirm_cursor = {
+        same = UiContainer.Cursor.new{widget = "SaveMenu.Container.ConfirmSame.Cursor", total = 2},
+        other = UiContainer.Cursor.new{widget = "SaveMenu.Container.ConfirmOther.Cursor", total = 2},
+    },
+
+    --- Slot (1-based) waiting for the confirmation, and which window is open ("same" or "other").
+    pending_slot = nil,
+    confirm_kind = "same",
+
     states = {
+        --- Confirmation to override a slot. Yes is the default unless the slot belongs to another
+        -- playthrough.
+        confirm_save = {
+            cursor = function(self) return self.confirm_cursor[self.confirm_kind] end,
+            axis = "vertical",
+            confirm_sound = false,
+            confirm = function(self, cursor)
+                if cursor:index() == 1 then
+                    self:save_slot(self.pending_slot)
+                else
+                    self:close_confirm()
+                    UiContainer.play_sound("Back")
+                end
+            end,
+            cancel = function(self) self:close_confirm() end,
+        },
+
+        --- "Game saved". Confirm or cancel close it.
+        saved = {
+            confirm_sound = false,
+            cancel_sound = false,
+            confirm = function(self)
+                self:close_saved()
+                UiContainer.play_sound("Back")
+            end,
+            cancel = function(self)
+                self:close_saved()
+                UiContainer.play_sound("Back")
+            end,
+        },
+
         [""] = {
             cursor = function(self) return self.cursor end,
             axis = "vertical",
@@ -34,6 +75,9 @@ UiContainer.SaveMenu = UiContainer.Menu.new{
         },
     },
 
+    --- Is the menu opened by a field script (a save point of a scene) instead of by the main menu?
+    standalone = false,
+
     --- Opens the save menu.
     --
     -- Populates and updates displayed data before opening.
@@ -48,12 +92,21 @@ UiContainer.SaveMenu = UiContainer.Menu.new{
             return 0
         end
         self:activate()
+        if self.standalone then
+            entity_manager:set_paused(true)
+            MenuSettings.pause_available = false
+            self.menu_was_available = MenuSettings.available
+            MenuSettings.available = false
+        end
         local loading = (self.operation == "load")
         local container = "SaveMenu.Container."
         ui_manager:get_widget(container .. "TopBar.DescSave"):set_visible(not loading)
         ui_manager:get_widget(container .. "TopBar.DescLoad"):set_visible(loading)
         ui_manager:get_widget(container .. "Title.TitleSave"):set_visible(not loading)
         ui_manager:get_widget(container .. "Title.TitleLoad"):set_visible(loading)
+        ui_manager:get_widget("SaveMenu.Container.ConfirmSame"):set_visible(false)
+        ui_manager:get_widget("SaveMenu.Container.ConfirmOther"):set_visible(false)
+        ui_manager:get_widget("SaveMenu.Container.Saved"):set_visible(false)
         ui_manager:get_widget("SaveMenu"):set_visible(true)
         self.cursor.count = self.max_slots
         self.cursor:reset()
@@ -97,13 +150,20 @@ UiContainer.SaveMenu = UiContainer.Menu.new{
 
     action = function(self, slot)
         if self.operation == "save" then
-            if savemap_manager:is_slot_empty(slot - 1) == false and ControlKey ~= savemap_manager:get_slot_control_key(slot - 1) then
-                -- TODO: Confirmation dialog
-                print("OVERRIDE ANOTHER SAVE")
+            if savemap_manager:is_slot_empty(slot - 1) == true then
+                -- Nothing to override.
+                self:save_slot(slot)
+                return
             end
-            save_game(slot - 1, true)
+            -- Ask first. A slot of another playthrough is not overridden unless the player says so.
+            self.pending_slot = slot
+            local other = (ControlKey ~= savemap_manager:get_slot_control_key(slot - 1))
+            self.confirm_kind = other and "other" or "same"
+            ui_manager:get_widget("SaveMenu.Container.ConfirmSame"):set_visible(not other)
+            ui_manager:get_widget("SaveMenu.Container.ConfirmOther"):set_visible(other)
+            self.confirm_cursor[self.confirm_kind]:set(other and 2 or 1)
+            self:set_state("confirm_save")
             audio_manager:play_sound("Cursor")
-            self:populate_slots()
         elseif self.operation == "load" then
             audio_manager:play_sound("Window")
             script:request_end_sync(Script.UI, "SaveMenu", "hide", 0)
@@ -112,10 +172,46 @@ UiContainer.SaveMenu = UiContainer.Menu.new{
         end
     end,
 
+    --- Closes the confirmation window without saving.
+    close_confirm = function(self)
+        ui_manager:get_widget("SaveMenu.Container.ConfirmSame"):set_visible(false)
+        ui_manager:get_widget("SaveMenu.Container.ConfirmOther"):set_visible(false)
+        self.pending_slot = nil
+        self:set_state("")
+    end,
+
+    --- Saves the game in a slot and shows the "Game saved" window.
+    --
+    -- @param slot Slot to save in (1-based).
+    save_slot = function(self, slot)
+        ui_manager:get_widget("SaveMenu.Container.ConfirmSame"):set_visible(false)
+        ui_manager:get_widget("SaveMenu.Container.ConfirmOther"):set_visible(false)
+        self.pending_slot = nil
+        save_game(slot - 1, true)
+        audio_manager:play_sound("Cursor")
+        self:populate_slots()
+        ui_manager:get_widget("SaveMenu.Container.Saved"):set_visible(true)
+        self:set_state("saved")
+    end,
+
+    --- Closes the "Game saved" window.
+    close_saved = function(self)
+        ui_manager:get_widget("SaveMenu.Container.Saved"):set_visible(false)
+        self:set_state("")
+    end,
+
     --- Hides the item menu and goes back to the main menu.
     hide = function(self)
         ui_manager:get_widget("SaveMenu"):set_visible(false)
-        self:deactivate(self.operation == "load" and "begin" or "main")
+        if self.standalone then
+            self.standalone = false
+            self:deactivate("")
+            MenuSettings.available = self.menu_was_available
+            MenuSettings.pause_available = true
+            entity_manager:set_paused(false)
+        else
+            self:deactivate(self.operation == "load" and "begin" or "main")
+        end
         savemap_manager:release()
         return 0;
     end,

+ 686 - 0
data/data/scripts/menu/shop_menu.lua

@@ -0,0 +1,686 @@
+if UiContainer == nil then UiContainer = {} end
+
+--- The shop menu.
+--
+-- Opened by the field scripts (open_shop). The shop to open is set in `shop_id` before showing the
+-- menu. The inventory of each shop is in Game.Shops (gamedata/shops.lua). Prices are the ones of
+-- the items and materia, the same in every shop. Items are sold for half of their price, materia for its AP (see materia_sell_price).
+--
+-- States:
+--  * "" (command): Buy, Sell or Exit.
+--  * "buy": list of the things the shop sells.
+--  * "buy_quantity": how many of the highlighted item to buy.
+--  * "sell": list of the things of the party that can be sold.
+--  * "sell_quantity": how many of the highlighted item to sell.
+--  * "sell_materia": stars, AP and price of the highlighted materia, to confirm the sale.
+UiContainer.ShopMenu = UiContainer.Menu.new{
+
+    id = "shop",
+
+    --- ID of the shop to open (index of Game.Shops).
+    shop_id = 0,
+
+    --- Visible rows of the list.
+    ROWS = 8,
+
+    --- Characters shown in the party window (the 9 that can be enabled).
+    MAX_CHARACTERS = 9,
+
+    --- Most items of a kind that the party can carry.
+    MAX_QUANTITY = 99,
+
+    --- Names of the kinds of shop (the type of the shop in Game.Shops).
+    TITLES = {
+        [1] = "Weapon Shop",
+        [2] = "Item Shop",
+        [3] = "Materia Shop",
+        [4] = "Drug Store",
+        [5] = "Tool Shop",
+        [6] = "Accessory Shop",
+        [7] = "Item Shop",
+        [8] = "Item Shop",
+    },
+
+    --- Entries of the list being shown. Each one is {materia = bool, id = ID, price = gil, ...}.
+    entries = {},
+
+    --- Quantity chosen in the quantity states.
+    quantity = 1,
+
+    --- Most that can be chosen in the quantity states.
+    max_quantity = 1,
+
+    --- Cursor over Buy, Sell and Exit.
+    command_cursor = UiContainer.Cursor.new{
+        widget = "ShopMenu.Container.TopBar.Commands.Cursor",
+        total = 3,
+    },
+
+    --- Cursor over the visible rows of the list, scrolling over the entries.
+    list_cursor = UiContainer.ListCursor.new{
+        widget = "ShopMenu.Container.List.Cursor",
+        rows = 8,
+        on_scroll = function() UiContainer.ShopMenu:populate_list() end,
+        on_move = function() UiContainer.ShopMenu:populate_details() end,
+    },
+
+    states = {
+        -- Buy, Sell, Exit.
+        [""] = {
+            cursor = function(self) return self.command_cursor end,
+            axis = "horizontal",
+            confirm_sound = false,
+            confirm = function(self, cursor)
+                local command = cursor:index()
+                if command == 1 then
+                    UiContainer.play_sound("Cursor")
+                    self:enter_list("buy")
+                elseif command == 2 then
+                    if not self:enter_list("sell") then return false end
+                    UiContainer.play_sound("Cursor")
+                else
+                    UiContainer.play_sound("Back")
+                    script:request_end_sync(Script.UI, "ShopMenu", "hide", 0)
+                end
+            end,
+            cancel = function(self)
+                script:request_end_sync(Script.UI, "ShopMenu", "hide", 0)
+            end,
+        },
+
+        buy = {
+            cursor = function(self) return self.list_cursor end,
+            axis = "vertical",
+            confirm_sound = false,
+            confirm = function(self, cursor)
+                return self:start_buy(self.entries[cursor:index()])
+            end,
+            cancel = function(self) self:enter_command() end,
+        },
+
+        buy_quantity = {
+            confirm_sound = false,
+            confirm = function(self) return self:buy(self.entries[self.list_cursor:index()]) end,
+            cancel = function(self) self:set_state("buy") self:update_prompt() end,
+        },
+
+        sell = {
+            cursor = function(self) return self.list_cursor end,
+            axis = "vertical",
+            confirm_sound = false,
+            confirm = function(self, cursor)
+                return self:start_sell(self.entries[cursor:index()])
+            end,
+            cancel = function(self) self:enter_command() end,
+        },
+
+        -- Details of a materia before selling it: confirm sells it, cancel goes back to the list.
+        sell_materia = {
+            confirm_sound = false,
+            confirm = function(self) return self:sell(self.entries[self.list_cursor:index()]) end,
+            cancel = function(self) self:set_state("sell") self:update_prompt() end,
+        },
+
+        sell_quantity = {
+            confirm_sound = false,
+            confirm = function(self) return self:sell(self.entries[self.list_cursor:index()]) end,
+            cancel = function(self) self:set_state("sell") self:update_prompt() end,
+        },
+    },
+
+    -----------------------------------------------------------------------------------------------
+    -- Opening and closing
+    -----------------------------------------------------------------------------------------------
+
+    --- Opens the shop set in `shop_id`.
+    show = function(self)
+        local shop = Game.Shops ~= nil and Game.Shops[self.shop_id] or nil
+        if shop == nil then
+            print("Tried to open invalid shop " .. tostring(self.shop_id))
+            return 0
+        end
+        self.shop = shop
+        self.materia_shop = (shop.type == 3)
+        self:activate()
+        -- Like the other menus opened by the scenes: the game is paused and the main menu is not
+        -- available meanwhile.
+        entity_manager:set_paused(true)
+        MenuSettings.pause_available = false
+        self.menu_was_available = MenuSettings.available
+        MenuSettings.available = false
+        ui_manager:get_widget("ShopMenu"):set_visible(true)
+        ui_manager:get_widget("ShopMenu.Background"):set_visible(true)
+        ui_manager:get_widget("ShopMenu.Container.Title.Title"):set_text(self.TITLES[shop.type] or "Shop")
+        self:populate_party(nil)
+        self.command_cursor:set(1)
+        self:enter_command()
+        return 0
+    end,
+
+    --- Closes the shop.
+    hide = function(self)
+        ui_manager:get_widget("ShopMenu.Background"):set_visible(false)
+        ui_manager:get_widget("ShopMenu"):set_visible(false)
+        self:deactivate()
+        MenuSettings.available = self.menu_was_available
+        MenuSettings.pause_available = true
+        entity_manager:set_paused(false)
+        return 0
+    end,
+
+    -----------------------------------------------------------------------------------------------
+    -- States
+    -----------------------------------------------------------------------------------------------
+
+    --- Goes back to the Buy / Sell / Exit command.
+    enter_command = function(self)
+        self:set_state("")
+        self.entries = {}
+        self.list_cursor.count = 0
+        self:update_prompt()
+        self:populate_list()
+        self:populate_details()
+    end,
+
+    --- Enters the list of things to buy or sell.
+    --
+    -- @param mode "buy" or "sell".
+    -- @return False if there is nothing to list.
+    enter_list = function(self, mode)
+        local entries
+        if mode == "buy" then
+            entries = self:buy_entries()
+        else
+            entries = self:sell_entries()
+        end
+        if #entries == 0 then return false end
+        self.entries = entries
+        self.list_cursor.count = #entries
+        self.list_cursor.first = 1
+        self.list_cursor:set(1)
+        self:set_state(mode)
+        self:update_prompt()
+        self:populate_list()
+        self:populate_details()
+        return true
+    end,
+
+    --- Shows the prompt (or the commands) that match the current state.
+    update_prompt = function(self)
+        local state = self:get_state()
+        local bar = "ShopMenu.Container.TopBar."
+        ui_manager:get_widget(bar .. "Commands"):set_visible(state == "")
+        ui_manager:get_widget(bar .. "PromptBuy"):set_visible(state == "buy")
+        ui_manager:get_widget(bar .. "PromptSell"):set_visible(state == "sell")
+        ui_manager:get_widget(bar .. "PromptQuantity"):set_visible(
+            state == "buy_quantity" or state == "sell_quantity")
+        ui_manager:get_widget("ShopMenu.Container.MateriaSale"):set_visible(state == "sell_materia")
+        ui_manager:get_widget("ShopMenu.Container.Quantity"):set_visible(
+            state == "buy_quantity" or state == "sell_quantity")
+        ui_manager:get_widget("ShopMenu.Container.List.Cursor"):set_visible(state ~= "")
+    end,
+
+    -----------------------------------------------------------------------------------------------
+    -- Entries
+    -----------------------------------------------------------------------------------------------
+
+    --- Gets the data of the thing an entry refers to.
+    entry_data = function(self, entry)
+        if entry.materia then return Game.Materia[entry.id] end
+        return Game.Items[entry.id]
+    end,
+
+    --- Entries of the things that the shop sells.
+    buy_entries = function(self)
+        local entries = {}
+        for _, listed in ipairs(self.shop.items) do
+            local entry = {materia = listed[1], id = listed[2]}
+            local data = self:entry_data(entry)
+            if data ~= nil then
+                entry.price = data.price
+                table.insert(entries, entry)
+            end
+        end
+        return entries
+    end,
+
+    --- Entries of the things that the party can sell.
+    --
+    -- Materia shops buy materia. The others buy items, weapons, armors and accessories.
+    sell_entries = function(self)
+        local entries = {}
+        if self.materia_shop then
+            for slot = 1, MAX_MATERIA_SLOTS do
+                local owned = Materia[slot]
+                if owned ~= nil and Game.Materia[owned.id] ~= nil then
+                    table.insert(entries, {
+                        materia = true, id = owned.id, slot = slot, ap = owned.ap or 0,
+                        price = self:materia_sell_price(owned.id, owned.ap or 0),
+                        sellable = true,
+                    })
+                end
+            end
+        else
+            for slot = 1, MAX_INVENTORY_SLOTS do
+                local owned = Inventory[slot]
+                if owned ~= nil and Game.Items[owned.item] ~= nil then
+                    local data = Game.Items[owned.item]
+                    table.insert(entries, {
+                        materia = false, id = owned.item, quantity = owned.quantity,
+                        price = math.floor(data.price / 2),
+                        sellable = (data.sell ~= 0),
+                    })
+                end
+            end
+        end
+        return entries
+    end,
+
+    --- Gil that a materia is sold for.
+    --
+    -- As in ff7.exe: a materia sells for the AP it has. A mastered one sells for 70 times its
+    -- price, and the ones priced 1 (the master materia, which have no levels to master) for 1.
+    --
+    -- @param id ID of the materia.
+    -- @param ap AP of the materia.
+    materia_sell_price = function(self, id, ap)
+        local data = Game.Materia[id]
+        if data.price == 1 then return 1 end
+        local levels = data.levels_ap or {}
+        if #levels > 1 and ap >= levels[#levels] then return data.price * 70 end
+        return ap
+    end,
+
+    --- Icon of an entry.
+    entry_icon = function(self, entry)
+        if entry.materia then
+            return "icons/materia_" .. tostring(Game.Materia[entry.id].type) .. ".png"
+        end
+        local data = Game.Items[entry.id]
+        if data.type == Inventory.ITEM_TYPE.ARMOR then
+            return "icons/item_armor.png"
+        elseif data.type == Inventory.ITEM_TYPE.ACCESSORY then
+            return "icons/item_accessory.png"
+        elseif data.type == Inventory.ITEM_TYPE.WEAPON then
+            for _, user in ipairs(data.users or {}) do
+                if user >= 0 and user <= 8 then
+                    return "icons/item_weapon_" .. tostring(user) .. ".png"
+                end
+            end
+        end
+        return "icons/item_item.png"
+    end,
+
+    -----------------------------------------------------------------------------------------------
+    -- Counting
+    -----------------------------------------------------------------------------------------------
+
+    --- How many of a thing does the party carry (not equipped)?
+    owned_count = function(self, entry)
+        if not entry.materia then return Inventory.get_item_quantity(entry.id) end
+        local count = 0
+        for slot = 1, MAX_MATERIA_SLOTS do
+            if Materia[slot] ~= nil and Materia[slot].id == entry.id then count = count + 1 end
+        end
+        return count
+    end,
+
+    --- How many of a thing are equipped by the characters?
+    equipped_count = function(self, entry)
+        local count = 0
+        for char_id = 0, 8 do
+            local character = Characters[char_id]
+            if type(character) == "table" and character.weapon ~= nil then
+                if entry.materia then
+                    for _, equipment in ipairs({character.weapon, character.armor}) do
+                        for slot = 0, 7 do
+                            local materia = equipment.materia ~= nil and equipment.materia[slot] or nil
+                            if materia ~= nil and materia.id == entry.id then count = count + 1 end
+                        end
+                    end
+                else
+                    if character.weapon.id == entry.id then count = count + 1 end
+                    if character.armor ~= nil and character.armor.id == entry.id then count = count + 1 end
+                    if character.accessory == entry.id then count = count + 1 end
+                end
+            end
+        end
+        return count
+    end,
+
+    --- Is there room in the inventory for one more of a thing?
+    has_room = function(self, entry)
+        if entry.materia then
+            for slot = 1, MAX_MATERIA_SLOTS do
+                if Materia[slot] == nil then return true end
+            end
+            return false
+        end
+        if Inventory.get_item_quantity(entry.id) > 0 then
+            return Inventory.get_item_quantity(entry.id) < self.MAX_QUANTITY
+        end
+        for slot = 1, MAX_INVENTORY_SLOTS do
+            if Inventory[slot] == nil then return true end
+        end
+        return false
+    end,
+
+    -----------------------------------------------------------------------------------------------
+    -- Buying
+    -----------------------------------------------------------------------------------------------
+
+    --- Starts buying the highlighted entry.
+    --
+    -- Materia is bought straight away. For anything else the quantity is asked.
+    -- @return False if it can't be bought.
+    start_buy = function(self, entry)
+        if entry == nil or Inventory.money < entry.price or not self:has_room(entry) then
+            return false
+        end
+        if entry.materia then
+            return self:buy(entry)
+        end
+        local room = self.MAX_QUANTITY - Inventory.get_item_quantity(entry.id)
+        local affordable = (entry.price > 0) and math.floor(Inventory.money / entry.price) or room
+        self.max_quantity = math.max(1, math.min(room, affordable))
+        self:enter_quantity("buy_quantity")
+        UiContainer.play_sound("Cursor")
+    end,
+
+    --- Buys the chosen quantity of an entry.
+    buy = function(self, entry)
+        if entry == nil then return false end
+        local quantity = entry.materia and 1 or self.quantity
+        local total = entry.price * quantity
+        if Inventory.money < total or not self:has_room(entry) then
+            return false
+        end
+        Inventory.remove_money(total)
+        if entry.materia then
+            Materia.add(entry.id, 0)
+        else
+            Inventory.add_item(entry.id, quantity)
+        end
+        UiContainer.play_sound("Buy")
+        self:set_state("buy")
+        self:update_prompt()
+        self:populate_details()
+    end,
+
+    -----------------------------------------------------------------------------------------------
+    -- Selling
+    -----------------------------------------------------------------------------------------------
+
+    --- Starts selling the highlighted entry.
+    --
+    -- Materia is sold straight away. For anything else the quantity is asked.
+    -- @return False if it can't be sold.
+    start_sell = function(self, entry)
+        -- Materia can be sold for 0 gil (it has no AP).
+        if entry == nil or not entry.sellable then return false end
+        if not entry.materia and entry.price <= 0 then return false end
+        if entry.materia then
+            self:set_state("sell_materia")
+            self:update_prompt()
+            self:populate_materia_sale(entry)
+            UiContainer.play_sound("Cursor")
+            return
+        end
+        self.max_quantity = entry.quantity
+        self:enter_quantity("sell_quantity")
+        UiContainer.play_sound("Cursor")
+    end,
+
+    --- Sells the chosen quantity of an entry.
+    sell = function(self, entry)
+        if entry == nil or not entry.sellable then return false end
+        if entry.materia then
+            Materia[entry.slot] = nil
+            Inventory.add_money(entry.price)
+        else
+            Inventory.remove_item(entry.id, self.quantity)
+            Inventory.add_money(entry.price * self.quantity)
+        end
+        UiContainer.play_sound("Buy")
+        -- The list changes: build it again and keep the cursor where it was if it can.
+        local first, position = self.list_cursor.first, self.list_cursor.position
+        local entries = self:sell_entries()
+        if #entries == 0 then
+            self:enter_command()
+            return
+        end
+        self.entries = entries
+        self.list_cursor.count = #entries
+        local index = math.min(first + position - 1, #entries)
+        first = math.max(1, math.min(first, #entries - self.ROWS + 1))
+        self.list_cursor.first = first
+        self.list_cursor:set(index - first + 1)
+        self:set_state("sell")
+        self:update_prompt()
+        self:populate_list()
+        self:populate_details()
+    end,
+
+    -----------------------------------------------------------------------------------------------
+    -- Quantity
+    -----------------------------------------------------------------------------------------------
+
+    --- Opens the window to choose how many to buy or sell.
+    enter_quantity = function(self, state)
+        self.quantity = 1
+        self:set_state(state)
+        self:update_prompt()
+        self:populate_quantity()
+    end,
+
+    --- Changes the quantity.
+    --
+    -- @param delta Amount to add. The quantity is kept between 1 and the maximum.
+    change_quantity = function(self, delta)
+        local quantity = math.max(1, math.min(self.max_quantity, self.quantity + delta))
+        if quantity == self.quantity then
+            UiContainer.play_sound("Error")
+            return
+        end
+        UiContainer.play_sound("Cursor")
+        self.quantity = quantity
+        self:populate_quantity()
+    end,
+
+    -----------------------------------------------------------------------------------------------
+    -- Widgets
+    -----------------------------------------------------------------------------------------------
+
+    --- Fills the quantity window.
+    populate_quantity = function(self)
+        local entry = self.entries[self.list_cursor:index()]
+        local window = "ShopMenu.Container.Quantity."
+        ui_manager:get_widget(window .. "Name"):set_text(self:entry_data(entry).name)
+        ui_manager:get_widget(window .. "Count"):set_text(UiContainer.pad_value(self.quantity, 2))
+        ui_manager:get_widget(window .. "Total"):set_text(
+            UiContainer.pad_value(entry.price * self.quantity, 8))
+        self:populate_slots(entry)
+    end,
+
+    --- Shows the materia slots and links of a weapon or armor in the quantity window, as the
+    -- equipment menu does. Other things have no slots.
+    populate_slots = function(self, entry)
+        local data = (not entry.materia) and Game.Items[entry.id] or nil
+        local slots = {}
+        local growth = 1
+        if data ~= nil and (data.type == Inventory.ITEM_TYPE.WEAPON or data.type == Inventory.ITEM_TYPE.ARMOR) then
+            slots = data.slots or {}
+            growth = data.growth
+        end
+        local window = "ShopMenu.Container.Quantity."
+        for s = 1, 8 do
+            local slot = ui_manager:get_widget(window .. "Slot" .. s)
+            slot:set_visible(#slots >= s)
+            if growth == 0 then
+                slot:set_image("icons/materia_slot_no_growth.png")
+            else
+                slot:set_image("icons/materia_slot.png")
+            end
+            if s % 2 ~= 0 then
+                -- A link joins an odd slot with the next one.
+                ui_manager:get_widget(window .. "Link" .. (math.floor(s / 2) + 1)):set_visible(
+                    #slots > s and slots[s] == 1)
+            end
+        end
+    end,
+
+    --- Fills the window that shows a materia before it is sold.
+    populate_materia_sale = function(self, entry)
+        local data = Game.Materia[entry.id]
+        local window = "ShopMenu.Container.MateriaSale."
+        local levels = data.levels_ap or {}
+        local level = 0
+        for _, level_ap in ipairs(levels) do
+            if level_ap > entry.ap then break end
+            level = level + 1
+        end
+        ui_manager:get_widget(window .. "Icon"):set_image("icons/materia_" .. tostring(data.type) .. ".png")
+        ui_manager:get_widget(window .. "Name"):set_text(data.name)
+        for star = 1, 5 do
+            local widget = ui_manager:get_widget(window .. "Star" .. star)
+            if star > #levels then
+                widget:set_visible(false)
+            else
+                widget:set_image((star <= level and "icons/materia_star_" or "icons/materia_star_empty_")
+                    .. tostring(data.type) .. ".png")
+                widget:set_visible(true)
+            end
+        end
+        ui_manager:get_widget(window .. "Ap"):set_text(UiContainer.pad_value(entry.ap, 8))
+        ui_manager:get_widget(window .. "Price"):set_text(UiContainer.pad_value(entry.price, 8))
+    end,
+
+    --- Fills the rows of the list.
+    populate_list = function(self)
+        local list = "ShopMenu.Container.List."
+        for row = 1, self.ROWS do
+            local entry = self.entries[self.list_cursor.first + row - 1]
+            local icon = ui_manager:get_widget(list .. "Icon" .. row)
+            local name = ui_manager:get_widget(list .. "Name" .. row)
+            local price = ui_manager:get_widget(list .. "Price" .. row)
+            if entry == nil then
+                icon:set_visible(false)
+                name:set_text("")
+                price:set_text("")
+            else
+                icon:set_image(self:entry_icon(entry))
+                icon:set_visible(true)
+                name:set_text(self:entry_data(entry).name)
+                price:set_text(UiContainer.pad_value(entry.price, 7))
+                -- Things that can't be sold are shown dimmed.
+                if entry.sellable == false or (self:get_state() == "sell" and not entry.materia and entry.price <= 0) then
+                    name:set_colour(0.6, 0.6, 0.6)
+                else
+                    name:set_colour(1, 1, 1)
+                end
+            end
+        end
+    end,
+
+    --- Fills the description, the gil, the amounts and the party for the highlighted entry.
+    populate_details = function(self)
+        local info = "ShopMenu.Container.Info."
+        ui_manager:get_widget(info .. "Gil"):set_text(UiContainer.pad_value(Inventory.money, 8))
+        local entry = self.entries[self.list_cursor:index()]
+        if self:get_state() == "" or entry == nil then
+            ui_manager:get_widget("ShopMenu.Container.Help.Help"):set_text("")
+            ui_manager:get_widget(info .. "Owned"):set_text("")
+            ui_manager:get_widget(info .. "Equipped"):set_text("")
+            self:populate_party(nil)
+            return
+        end
+        ui_manager:get_widget("ShopMenu.Container.Help.Help"):set_text(
+            self:entry_data(entry).description or "")
+        ui_manager:get_widget(info .. "Owned"):set_text(UiContainer.pad_value(self:owned_count(entry), 8))
+        ui_manager:get_widget(info .. "Equipped"):set_text(UiContainer.pad_value(self:equipped_count(entry), 8))
+        self:populate_party(entry)
+    end,
+
+    --- Fills the party window: portraits of every character enabled in the PHS, and how the
+    -- stats change if the entry is equipped.
+    --
+    -- @param entry Highlighted entry, or nil to show only the portraits.
+    populate_party = function(self, entry)
+        local data = (entry ~= nil and not entry.materia) and Game.Items[entry.id] or nil
+        local is_weapon = data ~= nil and data.type == Inventory.ITEM_TYPE.WEAPON
+        local is_armor = data ~= nil and data.type == Inventory.ITEM_TYPE.ARMOR
+        -- Each character has the spot of its ID, even if that leaves empty spots between them.
+        for char_id = 0, self.MAX_CHARACTERS - 1 do
+            local slot = char_id + 1
+            local character = Characters[char_id]
+            if not (type(character) == "table" and character.enabled == true) then
+                ui_manager:get_widget("ShopMenu.Container.Party.Slot" .. slot):set_visible(false)
+            else
+                local widget = "ShopMenu.Container.Party.Slot" .. slot
+                ui_manager:get_widget(widget):set_visible(true)
+                ui_manager:get_widget(widget .. ".Portrait"):set_image("characters/" .. tostring(char_id) .. ".png")
+                local can_use = false
+                if is_weapon or is_armor then
+                    for _, user in ipairs(data.users or {}) do
+                        if user == char_id then can_use = true end
+                    end
+                end
+                local stats = character.stats or {}
+                local attack, defense = stats.atk or 0, stats.def or 0
+                local new_attack, new_defense = attack, defense
+                if can_use and is_weapon then
+                    new_attack = attack - Game.Items[character.weapon.id].power + data.power
+                elseif can_use and is_armor then
+                    new_defense = defense - Game.Items[character.armor.id].defense.physical
+                        + data.defense.physical
+                end
+                self:populate_stat(widget .. ".Atk", can_use, attack, new_attack)
+                self:populate_stat(widget .. ".Def", can_use, defense, new_defense)
+            end
+        end
+    end,
+
+    --- Fills a stat row of a party member.
+    --
+    -- @param prefix Path of the row widgets, without the Lbl/Old/Arw/New suffix.
+    -- @param visible Show the row?
+    -- @param old Value now.
+    -- @param new Value if equipped.
+    populate_stat = function(self, prefix, visible, old, new)
+        for _, part in ipairs({"Lbl", "Old", "Arw", "New"}) do
+            ui_manager:get_widget(prefix .. part):set_visible(visible)
+        end
+        if not visible then return end
+        ui_manager:get_widget(prefix .. "Old"):set_text(UiContainer.pad_value(old, 3))
+        local value = ui_manager:get_widget(prefix .. "New")
+        value:set_text(UiContainer.pad_value(new, 3))
+        if new > old then
+            value:set_colour(1, 1, 0)
+        elseif new < old then
+            value:set_colour(1, 0, 0)
+        else
+            value:set_colour(1, 1, 1)
+        end
+    end,
+}
+
+--- Directional buttons of the quantity states.
+--
+-- Up and down change the quantity by one, left and right by ten.
+local function quantity_buttons()
+    local deltas = {
+        [Config.CONTROLS.UP] = 1,
+        [Config.CONTROLS.DOWN] = -1,
+        [Config.CONTROLS.RIGHT] = 10,
+        [Config.CONTROLS.LEFT] = -10,
+    }
+    local buttons = {}
+    for button, delta in pairs(deltas) do
+        buttons[button] = function(self, event)
+            if event == "Press" or event == "Repeat" then self:change_quantity(delta) end
+        end
+    end
+    return buttons
+end
+UiContainer.ShopMenu.states.buy_quantity.buttons = quantity_buttons()
+UiContainer.ShopMenu.states.sell_quantity.buttons = quantity_buttons()

+ 11 - 0
data/data/scripts/save.lua

@@ -25,6 +25,8 @@ save_game = function(slot, force)
        end
     end
     savemap_manager:set_party(Party[1] or -1, Party[2] or -1, Party[3] or -1)
+    -- The leader of the field is not always the first member of the party.
+    savemap_manager:set_setting("field_leader", Party.get_leader() or -1)
     for i = 1, MAX_INVENTORY_SLOTS do
         if Inventory[i] ~= nil then
             savemap_manager:set_item(i - 1, Inventory[i].item, Inventory[i].quantity)
@@ -187,6 +189,9 @@ end
 --
 -- @param slot The slot to load (0-15).
 load_game = function(slot)
+    -- The game that was loaded keeps the control key of its slot, so it can be saved there again
+    -- without being taken for another playthrough.
+    ControlKey = savemap_manager:get_slot_control_key(slot)
     -- Populate banks
     for b = 0, Banks.COUNT do
         for a = 0, Banks.SIZE do
@@ -204,6 +209,12 @@ load_game = function(slot)
             Party[p] = nil
         end
     end
+    -- Games saved before the leader was saved have the first member as leader.
+    Party.leader = nil
+    if savemap_manager:is_slot_setting_set(slot, "field_leader") then
+        local leader = savemap_manager:get_slot_setting(slot, "field_leader")
+        if leader >= 0 then Party.leader = leader end
+    end
     -- The battles and dialogs read the party from the text manager.
     export_party_members()
     -- The inventory and the materia are 1-based in the game, and 0-based in the savemap.

+ 359 - 126
data/data/scripts/system.lua

@@ -132,16 +132,54 @@ end
 
 --- Sets the current party.
 --
+-- This is what the scripts do (PRTYE and the party selection), so the first character also becomes
+-- the leader of the field: the character the player controls (see Party.get_leader). Changing the
+-- order of the party in the menus does not change the leader, so they pass `keep_leader`.
+--
 -- @param character1 The first member character ID, the party leader.
 -- @param character2 The second member character ID, can be nil.
 -- @param character3 The third member character ID, can be nil.
-set_party = function(character1, character2, character3)
+-- @param keep_leader If true, the leader of the field is not changed.
+set_party = function(character1, character2, character3, keep_leader)
     Party[1] = character1
     Party[2] = character2
     Party[3] = character3
+    if not keep_leader then Party.leader = character1 end
     export_party_members()
 end
 
+--- Gets the leader of the party in the field: the character whose entity the player controls.
+--
+-- It is set by the scripts when they set the party, and it isn't changed by moving characters
+-- around in the Order menu. If there is no leader, or the leader isn't in the party (a party made
+-- by adding characters, or a game saved before the leader was saved), the first member of the party
+-- becomes the leader, and stays so until a script changes it.
+--
+-- @return ID of the character, or nil if there is no party.
+Party.get_leader = function()
+    if Party.leader ~= nil then
+        for slot = 1, 3 do
+            if Party[slot] == Party.leader then return Party.leader end
+        end
+    end
+    Party.leader = Party[1]
+    return Party.leader
+end
+
+--- Sets the party from three values (SPTYE), the ones that GTPYE stored: 254 and 255 are an empty
+-- place.
+--
+-- @param character1 The first member character ID, the party leader.
+-- @param character2 The second member character ID.
+-- @param character3 The third member character ID.
+set_party_from_values = function(character1, character2, character3)
+    local function id(value)
+        if value == nil or value >= 254 then return nil end
+        return value
+    end
+    set_party(id(character1), id(character2), id(character3))
+end
+
 --- Checks if a a character ID actually belongs to a character.
 --
 -- @param character The ID to check.
@@ -197,6 +235,7 @@ remove_party_character = function(character)
     for i = 1, 3 do
         if Party[i] == character then
             Party[i] = nil
+            if Party.leader == character then Party.leader = nil end
             export_party_members()
             return
         end
@@ -241,6 +280,15 @@ set_character_enable = function(character, enable)
         return
     end
     Characters[character].enabled = enable;
+    -- As in ff7.exe (0x61c782), a character that is hidden also leaves the party, locked or not.
+    if not enable then
+        for i = 1, 3 do
+            if Party[i] == character then
+                Party[i] = nil
+                export_party_members()
+            end
+        end
+    end
 end
 
 --- Checks if a character is enabled in the PHS.
@@ -473,124 +521,296 @@ Inventory.sort = function(criteria)
     end
 end
 
+-- Leveling up, as in ff7.exe (1998 build, functions 0x5c76d9 to 0x5c7bb1).
+
+Characters.MAX_LEVEL = 99
+Characters.MAX_EXP = 999999999
+--- Caps of the base stats that level ups give. Sources go to the stat bonus, not to the base.
+Characters.MAX_BASE_STAT = 100
+Characters.MAX_BASE_HP = 9999
+Characters.MAX_BASE_MP = 999
+
+--- Divides truncating toward zero, like the integer divisions of the original.
+local function divide(a, b)
+    local quotient = a / b
+    if quotient < 0 then return math.ceil(quotient) end
+    return math.floor(quotient)
+end
+
+--- Gets the segment of the growth curves used for a level: one every 10 levels up to 60, then one
+-- every 20.
+local function curve_segment(level)
+    if level <= 60 then return math.max(0, math.floor((level - 1) / 10)) end
+    return math.min(7, math.floor((level - 61) / 20) + 6)
+end
+
+--- Picks one of the 12 bonuses: a random number from 1 to 8 plus how far the character is behind.
+local function bonus_index(difference)
+    return math.max(0, math.min(11, math.random(1, 8) + difference))
+end
+
+--- Gets the total experience a character needs to go from a level to the next one.
+--
+-- It's the sum of gradient * n^2 / 10 for n from 1 to the level, all of them with the gradient of
+-- the segment of that level.
+--
+-- @param id Character ID.
+-- @param level The level.
+-- @return The total experience, 0 for level 0.
+Characters.exp_threshold = function(id, level)
+    local gradient = Game.Growth.curves[Game.Characters[id].curves.exp][curve_segment(level)].gradient
+    local total = 0
+    for n = 1, level do total = total + math.floor(gradient * n * n / 10) end
+    return total
+end
+
+--- Raises the base stats of a character for one level.
+--
+-- Each stat has a curve that gives the value expected at the new level; the further the character
+-- is below it, the better the bonus is likely to be.
+local function level_up(id)
+    local character = Characters[id]
+    local stats = character.stats
+    local level = character.level
+    local segment = curve_segment(level)
+    local curves = Game.Characters[id].curves
+    local function curve(name) return Game.Growth.curves[curves[name]][segment] end
+
+    for _, name in ipairs({"str", "vit", "mag", "spr", "dex", "lck"}) do
+        local stat = stats[name]
+        local value = math.max(1, stat.base)
+        local data = curve(name)
+        local expected = math.floor(data.gradient * (level + 1) / 100) + data.base
+        local gain = Game.Growth.bonus.primary[bonus_index(expected - value)]
+        stat.base = math.min(Characters.MAX_BASE_STAT, value + gain)
+    end
+
+    local hp = curve("hp")
+    local function expected_hp(n) return hp.gradient * n + hp.base * 40 end
+    local value = math.max(1, stats.hp.base)
+    local index = bonus_index(divide(expected_hp(level) * 100, value) - 100)
+    local gain = divide((expected_hp(level + 1) - expected_hp(level)) * Game.Growth.bonus.hp[index], 100)
+    stats.hp.base = math.min(Characters.MAX_BASE_HP, value + gain)
+
+    local mp = curve("mp")
+    local function expected_mp(n) return math.floor(mp.gradient * n / 10) + mp.base * 2 end
+    value = math.max(1, stats.mp.base)
+    index = bonus_index(divide(expected_mp(level) * 100, value) - 100)
+    gain = divide((expected_mp(level + 1) - expected_mp(level)) * Game.Growth.bonus.mp[index], 100)
+    stats.mp.base = math.min(Characters.MAX_BASE_MP, value + gain)
+
+    character.level = level + 1
+end
+
+--- Gives experience to a character, and levels it up as many times as it reaches.
+--
+-- The current HP and MP don't change, only the base values and the maximums.
+--
+-- @param id Character ID.
+-- @param exp Experience gained.
+-- @return The number of levels gained.
+Characters.add_exp = function(id, exp)
+    local character = Characters[id]
+    local definition = Game.Characters[id]
+    if character == nil or definition == nil or definition.curves == nil then return 0 end
+    character.exp = math.min(Characters.MAX_EXP, (character.exp or 0) + exp)
+    local first_level = character.level
+    while character.level < Characters.MAX_LEVEL
+      and character.exp >= Characters.exp_threshold(id, character.level) do
+        level_up(id)
+    end
+    if character.level < Characters.MAX_LEVEL then
+        character.exp_to_next = Characters.exp_threshold(id, character.level) - character.exp
+    else
+        character.exp_to_next = 0
+    end
+    if character.level > first_level then Characters.recalculate_stats(id) end
+    return character.level - first_level
+end
+
+--- Variable of the field scripts with the level of the characters whose level doesn't depend on
+-- the one of the party (Yuffie): bank 1, address 2.
+Characters.JOIN_LEVEL_BANK = 1
+Characters.JOIN_LEVEL_ADDRESS = 2
+
+--- Gets the average level of the available characters (in the party or enabled in the PHS), without
+-- counting one of them.
+--
+-- @param excluded ID of the character that isn't counted.
+-- @return The average, or the level of the excluded character if there is nobody else.
+Characters.average_level = function(excluded)
+    local sum, count = 0, 0
+    for id = 0, 8 do
+        if id ~= excluded and Characters[id] ~= nil and (IFMEMBQ(id) or IFPRTYQ(id)) then
+            sum = sum + Characters[id].level
+            count = count + 1
+        end
+    end
+    if count == 0 then return Characters[excluded].level end
+    return math.floor(sum / count)
+end
+
+--- Copies a table and the tables in it.
+local function copy_table(source)
+    if type(source) ~= "table" then return source end
+    local result = {}
+    for key, value in pairs(source) do result[key] = copy_table(value) end
+    return result
+end
+
+--- Gives a character the data it joins with. The slots of Cait Sith and Vincent hold young Cloud and
+-- Sephiroth at the start: ff7.exe replaces the whole slot with data of its own when the window to
+-- name them opens (0x70ec9a). Nothing happens for the other characters.
+--
+-- The availability and the lock in the party are not part of that data, and are kept.
+--
+-- @param id Character ID.
+Characters.load_recruit_record = function(id)
+    local record = Game.RecruitRecords ~= nil and Game.RecruitRecords[id] or nil
+    if record == nil or Characters[id] == nil then return end
+    local character = copy_table(record)
+    character.enabled = Characters[id].enabled
+    character.locked = Characters[id].locked
+    Characters[id] = character
+    Characters.recalculate_stats(id)
+end
+
+--- Sets the level of a character that joins, as in ff7.exe (0x5c72a6). The original does it when the
+-- window to name the character is closed (for everybody but Cloud).
+--
+-- The level is the average of the other available characters plus half of the level offset of the
+-- character. With an odd offset (Yuffie) it comes from a variable of the field scripts instead, and
+-- the character is built again from level 1. The experience of the previous level is added to the
+-- one the character has, and it levels up as usual, so it never goes down. HP and MP end up filled.
+--
+-- @param id Character ID.
+Characters.join = function(id)
+    local character = Characters[id]
+    local definition = Game.Characters[id]
+    if id == 0 or character == nil or definition == nil or definition.curves == nil then return end
+    -- The offset is a signed byte.
+    local offset = tonumber(definition.initial_level) or 0
+    if offset > 127 then offset = offset - 256 end
+    local stats = character.stats
+    local level
+    if offset % 2 == 0 then
+        level = Characters.average_level(id) + divide(offset, 2)
+    else
+        level = Banks[Characters.JOIN_LEVEL_BANK][Characters.JOIN_LEVEL_ADDRESS] or 0
+        -- It is unknown what writes the variable in a normal game: without it, the character would
+        -- be left at level 1, so the average of the party is used.
+        if level == 0 then level = Characters.average_level(id) end
+        character.level = 1
+        character.exp = 0
+        for _, name in ipairs({"str", "vit", "mag", "spr", "dex", "lck", "hp", "mp"}) do
+            stats[name].base = 1
+        end
+    end
+    level = math.max(1, math.min(Characters.MAX_LEVEL, level))
+    Characters.add_exp(id, Characters.exp_threshold(id, level - 1))
+    stats.hp.current = stats.hp.base
+    stats.mp.current = stats.mp.base
+    Characters.recalculate_stats(id)
+    print(character.name .. " joins at level " .. tostring(character.level))
+end
+
+--- Names of the primary stats.
+Characters.PRIMARY_STATS = {"str", "vit", "mag", "spr", "dex", "lck"}
+
+--- Cap of the primary stats and of the bonus that the sources give, as in ff7.exe.
+Characters.MAX_STAT = 255
+
+--- Primary stat or maximum raised by each of the Plus materia, by the ID of its ability.
+Characters.PLUS_MATERIA = {
+    [0] = "str", [1] = "vit", [2] = "mag", [3] = "spr", [4] = "dex", [5] = "lck", [8] = "hp", [9] = "mp",
+}
+
+--- Item ID of the Curse Ring, and what it adds to the stats on top of the bonuses of its data.
+Characters.CURSE_RING = 313
+Characters.CURSE_RING_BONUS = {str = 15, vit = 15, mag = 15, spr = 15, dex = 15, lck = 10}
+
+--- Uses a source on a character: one more point of bonus for a primary stat.
+--
+-- @param id Character ID.
+-- @param name Name of the stat, one of {@see Characters.PRIMARY_STATS}.
+-- @return False if the bonus is already at its cap, and nothing happens.
+Characters.add_stat_bonus = function(id, name)
+    local stat = Characters[id].stats[name]
+    if (stat.bonus or 0) >= Characters.MAX_STAT then return false end
+    stat.bonus = (stat.bonus or 0) + 1
+    Characters.recalculate_stats(id)
+    return true
+end
+
 Characters.recalculate_stats = function(id)
     -- Initialize
     local stats = Characters[id].stats
-    stats.str.total = stats.str.base
-    stats.vit.total = stats.vit.base
-    stats.mag.total = stats.mag.base
-    stats.spr.total = stats.spr.base
-    stats.dex.total = stats.dex.base
-    stats.lck.total = stats.lck.base
+    -- The primary stats start with the base value, that grows with the levels, plus the bonus that the
+    -- sources give.
+    for _, name in ipairs(Characters.PRIMARY_STATS) do
+        stats[name].total = stats[name].base + (stats[name].bonus or 0)
+    end
     stats.hp.max = stats.hp.base
     stats.mp.max = stats.mp.base
-    -- Weapon bonus. HP and MP are percents of base, the rest absolutes. The stats are keyed by name,
-    -- so they are walked with pairs (ipairs only walks the array part and found nothing).
     local weapon = Game.Items[Characters[id].weapon.id]
-    for stat, value in pairs(weapon.stats or {}) do
-        if stat == "str" then
-            stats.str.total = stats.str.total + value
-        elseif stat == "vit" then
-            stats.vit.total = stats.vit.total + value
-        elseif stat == "mag" then
-            stats.mag.total = stats.mag.total + value
-        elseif stat == "spr" then
-            stats.spr.total = stats.spr.total + value
-        elseif stat == "dex" then
-            stats.dex.total = stats.dex.total + value
-        elseif stat == "lck" then
-            stats.lck.total = stats.lck.total + value
-        elseif stat == "hp" then
-            stats.hp.max = stats.hp.max + (value * stats.hp.max / 100)
-        elseif stat == "mp" then
-            stats.mp.max = stats.mp.max + (value * stats.mp.max / 100)
-        end
-    end
-    -- Armor bonus. HP and MP are percents of bsae, the rest absolutes.
     local armor = Game.Items[Characters[id].armor.id]
-    for stat, value in pairs(armor.stats or {}) do
-        if stat == "str" then
-            stats.str.total = stats.str.total + value
-        elseif stat == "vit" then
-            stats.vit.total = stats.vit.total + value
-        elseif stat == "mag" then
-            stats.mag.total = stats.mag.total + value
-        elseif stat == "spr" then
-            stats.spr.total = stats.spr.total + value
-        elseif stat == "dex" then
-            stats.dex.total = stats.dex.total + value
-        elseif stat == "lck" then
-            stats.lck.total = stats.lck.total + value
-        elseif stat == "hp" then
-            stats.hp.max = stats.hp.max + (value * stats.hp.max / 100)
-        elseif stat == "mp" then
-            stats.mp.max = stats.mp.max + (value * stats.mp.max / 100)
-        end
-    end
-    -- Accesory bonus
-    local accessory = Game.Items[Characters[id].accessory]
-    if (accessory ~= nil) then
-        for stat, value in pairs(accessory.stats or {}) do
-            if stat == "str" then
-                stats.str.total = stats.str.total + value
-            elseif stat == "vit" then
-                stats.vit.total = stats.vit.total + value
-            elseif stat == "mag" then
-                stats.mag.total = stats.mag.total + value
-            elseif stat == "spr" then
-                stats.spr.total = stats.spr.total + value
-            elseif stat == "dex" then
-                stats.dex.total = stats.dex.total + value
-            elseif stat == "lck" then
-                stats.lck.total = stats.lck.total + value
-            elseif stat == "hp" then
-                stats.hp.max = stats.hp.max + (value * stats.hp.max / 100)
-            elseif stat == "mp" then
-                stats.mp.max = stats.mp.max + (value * stats.mp.max / 100)
+    -- Bonuses of the equipment: points added to the primary stats. They are keyed by name, so they are
+    -- walked with pairs (ipairs only walks the array part and found nothing).
+    for _, item in pairs({weapon, armor, Game.Items[Characters[id].accessory]}) do
+        for name, value in pairs(item.stats or {}) do
+            if stats[name] ~= nil and stats[name].total ~= nil then
+                stats[name].total = stats[name].total + value
             end
         end
     end
+    -- The Curse Ring has more bonuses than its data can hold, ff7.exe adds them (0x6bbb04).
+    if Characters[id].accessory == Characters.CURSE_RING then
+        for name, value in pairs(Characters.CURSE_RING_BONUS) do stats[name].total = stats[name].total + value end
+    end
     -- Get a list of materias
-    local materias = {}
-    for m = 0, 7 do
-        if Characters[id].weapon.materia[m] ~= nil then
-            table.insert(materias, Game.Materia[Characters[id].weapon.materia[m].id])
-        end
-        if Characters[id].armor.materia[m] ~= nil then
-            table.insert(materias, Game.Materia[Characters[id].armor.materia[m].id])
+    local materias, equipped_materias = {}, {}
+    for _, part in ipairs({Characters[id].weapon, Characters[id].armor}) do
+        for m = 0, 7 do
+            local equipped = part.materia[m]
+            if equipped ~= nil and Game.Materia[equipped.id] ~= nil then
+                table.insert(materias, Game.Materia[equipped.id])
+                table.insert(equipped_materias, equipped)
+            end
         end
     end
-    -- Get materia bonuses. All are percents of base.
-    for _, materia in ipairs(materias) do
-        for stat, value in pairs(materia.stats or {}) do
-            if stat == "str" then
-                stats.str.total = stats.str.total + (value * stats.str.base / 100)
-            elseif stat == "vit" then
-                stats.vit.total = stats.vit.total + (value * stats.vit.base / 100)
-            elseif stat == "mag" then
-                stats.mag.total = stats.mag.total + (value * stats.mag.base / 100)
-            elseif stat == "spr" then
-                stats.spr.total = stats.spr.total + (value * stats.spr.base / 100)
-            elseif stat == "dex" then
-                stats.dex.total = stats.dex.total + (value * stats.dex.base / 100)
-            elseif stat == "lck" then
-                stats.lck.total = stats.lck.total + (value * stats.lck.base / 100)
-            elseif stat == "hp" then
-                stats.hp.max = stats.hp.max + (value * stats.hp.max / 100)
-            elseif stat == "mp" then
-                stats.mp.max = stats.mp.max + (value * stats.mp.max / 100)
+    -- Materia changes, as in ff7.exe (0x5cd1e8 and 0x5ce487): points for the primary stats and percents
+    -- for HP and MP, that every equipped materia adds up, and the percents of the Plus materia (HP,
+    -- MP, Speed, Magic and Luck Plus).
+    local points, percents = {}, {}
+    local function add(list, name, value) list[name] = (list[name] or 0) + value end
+    for index, materia in ipairs(materias) do
+        for name, value in pairs(materia.stats or {}) do
+            if name == "hp" or name == "mp" then add(percents, name, value)
+            else add(points, name, value)
             end
         end
+        local name = materia.type == Materia.TYPE.INDEPENDENT and materia.ability ~= nil
+          and Characters.PLUS_MATERIA[materia.ability.id] or nil
+        if name ~= nil then
+            local level = math.max(1, Characters.get_materia_level(materia, equipped_materias[index].ap or 0))
+            local param = materia.ability.param
+            add(percents, name, param[level] or param[#param])
+        end
+    end
+    local function percent_of(value, name)
+        local result = value * math.min(100, percents[name] or 0) / 100
+        -- Truncated toward zero, like the integer division of the original.
+        if result < 0 then return math.ceil(result) end
+        return math.floor(result)
+    end
+    -- The percent of a Plus materia applies to the stat with the equipment, without the materia points.
+    for _, name in ipairs(Characters.PRIMARY_STATS) do
+        local value = math.min(Characters.MAX_STAT, stats[name].total)
+        value = value + percent_of(value, name) + (points[name] or 0)
+        stats[name].total = math.max(0, math.min(Characters.MAX_STAT, math.floor(value)))
     end
-    -- Round down all basic stats
-    stats.str.total = math.floor(stats.str.total)
-    stats.vit.total = math.floor(stats.vit.total)
-    stats.mag.total = math.floor(stats.mag.total)
-    stats.spr.total = math.floor(stats.spr.total)
-    stats.dex.total = math.floor(stats.dex.total)
-    stats.lck.total = math.floor(stats.lck.total)
-    stats.hp.max = math.floor(stats.hp.max)
-    stats.mp.max = math.floor(stats.mp.max)
+    stats.hp.max = math.min(Characters.MAX_BASE_HP, stats.hp.max + percent_of(stats.hp.max, "hp"))
+    stats.mp.max = math.min(Characters.MAX_BASE_MP, stats.mp.max + percent_of(stats.mp.max, "mp"))
 
     -- HP<->MP materia swap the maximum HP and MP. TODO: Unverified: its levels (it is done at any level).
     for _, materia in ipairs(materias) do
@@ -604,24 +824,6 @@ Characters.recalculate_stats = function(id)
     if stats.hp.current ~= nil then stats.hp.current = math.min(stats.hp.current, math.max(1, stats.hp.max)) end
     if stats.mp.current ~= nil then stats.mp.current = math.min(stats.mp.current, math.max(0, stats.mp.max)) end
 
-    if stats.str.total < 1 then
-        stats.str.total = 1
-    end
-    if stats.vit.total < 1 then
-        stats.vit.total = 1
-    end
-    if stats.mag.total < 1 then
-        stats.mag.total = 1
-    end
-    if stats.spr.total < 1 then
-        stats.spr.total = 1
-    end
-    if stats.dex.total < 1 then
-        stats.dex.total = 1
-    end
-    if stats.lck.total < 1 then
-        stats.lck.total = 1
-    end
     if stats.hp.max < 1 then
         stats.hp.max = 1
     end
@@ -648,8 +850,8 @@ Characters.recalculate_stats = function(id)
     if stats.def < 1 then
         stats.def = 1
     end
-    if stats.eva < 1 then
-        stats.eva = 1
+    if stats.eva < 0 then
+        stats.eva = 0
     end
     if stats.matk < 1 then
         stats.matk = 1
@@ -657,8 +859,8 @@ Characters.recalculate_stats = function(id)
     if stats.mdef < 1 then
         stats.mdef = 1
     end
-    if stats.meva < 1 then
-        stats.meva = 1
+    if stats.meva < 0 then
+        stats.meva = 0
     end
 
     -- Cap current HP/MP
@@ -758,6 +960,28 @@ Characters.equip = function(char_id, item_id)
     return true
 end
 
+--- Takes the equipped materia off a character and puts it in the materia inventory (menu 17 of the
+-- field scripts: the "remove materia from other members" of the scenes with a fixed party).
+--
+-- @param id ID of the character.
+Characters.unequip_materia = function(id)
+    local character = Characters[id]
+    if character == nil then return end
+    local free = 1
+    for _, equipment in ipairs({character.weapon, character.armor}) do
+        for slot = 0, 7 do
+            local materia = equipment.materia[slot]
+            if materia ~= nil then
+                while free <= MAX_MATERIA_SLOTS and Materia[free] ~= nil do free = free + 1 end
+                if free > MAX_MATERIA_SLOTS then return end
+                Materia[free] = materia
+                equipment.materia[slot] = nil
+            end
+        end
+    end
+    Characters.recalculate_stats(id)
+end
+
 --- Removes all materia from a character.
 --
 -- @param id ID of the character to remove materia from.
@@ -811,8 +1035,17 @@ Party.split_teams = function(number)
 end
 
 --- Displays a menu to choose a party of three.
+--
+-- The script that asks for it waits until the menu is closed.
 Party.choose_party = function()
-    -- TODO: Implement
+    -- The button that asked for the menu (Cancel) is still down: it would close the menu at once.
+    while entity_manager:is_key_on(64) do script:wait(0) end
+    UiContainer.PhsMenu.standalone = true
+    script:request_end_sync(Script.UI, "PhsMenu", "show", 0)
+    while UiContainer.current_menu == "phs" do script:wait(0) end
+    -- The button that closed the menu is still down: the script that asked for the menu would
+    -- read it as a new request (Cancel opens the menu).
+    while entity_manager:is_key_on(32 + 64) do script:wait(0) end
 end
 
 --- Special event. Removes all materia from the party, equipped and unequipped.

+ 20 - 4
data/data/scripts/worldmap/triangle_triggers.lua

@@ -82,7 +82,7 @@ Memory of the world map scripts (Read, ReadWord, ReadBit and their Write functio
 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
+(Banks[1][127] and the bit 3 of it 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.
 
@@ -123,7 +123,8 @@ 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
+    if not bank then return 0 end
+    return get_byte_nth_bit(Banks[bank][offset], bit_address % 8)
 end
 
 --- Writes a byte of the game variables.
@@ -146,8 +147,9 @@ end
 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
+    -- The bits are the ones of the bytes (the fields set them with BITON/set_bank_bit on Banks).
+    remember(Banks[bank], offset)
+    Banks[bank][offset] = set_byte_nth_bit(Banks[bank][offset], bit_address % 8, value ~= 0 and 1 or 0)
 end
 
 System.WorldMap.locals = {}
@@ -211,6 +213,20 @@ EnterFieldScene = function(field_table_id, scenario)
     end
 
     System.MapChanger.world_map_entry = entry
+    -- Where the player was when entering the field: some exits (the chocobo records, such as the one
+    -- of sichi) place the player where he entered, and the scripts read it as the values 0, 1 (the
+    -- mesh) and 4 (the direction) that the engine gives them.
+    local player = entity_manager:get_player_entity()
+    if player ~= nil and WorldVM ~= nil then
+        local x, _, z = player:get_position()
+        System.WorldMap.entry_position = {
+            x = x,
+            z = z,
+            mesh_x = math.floor(x / WorldVM.MESH_SIZE),
+            mesh_y = math.floor(z / WorldVM.MESH_SIZE),
+            direction = world_map_module:get_model_heading(player:get_name()),
+        }
+    end
     console("camera_free false")
     load_field_map_request(entry.field, "")
     return 0

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

@@ -24,6 +24,14 @@ local FLIGHT_PITCH = 20
 WorldMapSettings = {
     speed = speed,
 
+    --- World units per second for each point of SetActiveEntityMovespeed in the scenes of the Warship
+    -- (the Warship sails at 10 to 40 in them). From ff7.exe: a mesh is 8192 units and the ship moves
+    -- speed / 8192 of a mesh each frame, which is this value with 30 frames per second (a unit of 30 / 4096).
+    scene_speed_unit = 30 / 4096,
+    --- Frames of the scene scripts for each second. The distance does not depend on it (it is for each frame, in
+    -- the exe), only how long the waits and the movement take. 15 is what the user remembers of the original.
+    scene_fps = 15,
+
     --- 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 = {
@@ -34,6 +42,8 @@ WorldMapSettings = {
         highwind = {distance = DISTANCE, pitch = FLIGHT_PITCH},
         submarine = {distance = DISTANCE, pitch = PITCH},
         submarine_underwater = {distance = DISTANCE, pitch = FLIGHT_PITCH},
+        -- The entity of a scripted scene (the Warship).
+        scene = {distance = 1.25, pitch = 25},
     },
 
     --- Music of the world map (the logic is in world_music.lua). Numbers are the tracks of audio/musics.

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

@@ -64,6 +64,7 @@ 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 and WorldVM.is_scene_record(ReadSpecial(6)) then return 9 end
     if map_id == 0 then return WorldVM.get_story_situation() end
     return WorldVM.default_situation[map_id]
 end
@@ -89,6 +90,11 @@ SetActiveEntityMeshCoordinates = function(mesh_x, mesh_y)
         WorldVM.current.mesh_x = mesh_x
         WorldVM.current.mesh_y = mesh_y
     end
+    local scene = WorldVM.scene
+    if scene then
+        scene.mesh_x = mesh_x
+        scene.mesh_y = mesh_y
+    end
     return 0
 end
 
@@ -96,15 +102,83 @@ SetActiveEntityMeshCoordinatesInMesh = function(x, y)
     if WorldVM.current then
         WorldVM.current.in_x = x
         WorldVM.current.in_y = y
+        -- To get only the first position of a scene.
+        if WorldVM.current.stop_at_position then error(WorldVM.STOP) end
+    end
+    local scene = WorldVM.scene
+    if scene and scene.mesh_x then
+        scene.x = scene.mesh_x * WorldVM.MESH_SIZE + x / 4096
+        scene.z = scene.mesh_y * WorldVM.MESH_SIZE + y / 4096
+        scene.entity:set_position(scene.x, scene.y, scene.z)
     end
     return 0
 end
 
+--- Sets where the active entity moves and faces.
 SetActiveEntityDirectionAndFacing = function(direction)
     if WorldVM.current then WorldVM.current.direction = direction end
+    local scene = WorldVM.scene
+    if scene then
+        scene.direction = direction
+        world_map_module:set_model_heading(scene.entity_name, direction)
+        -- ReadSpecial(4) is the direction of the active entity: the scenes turn the ship with
+        -- SetActiveEntityDirectionAndFacing(ReadSpecial(4) - 3) repeated, a few degrees each time.
+        System.WorldMap.specials[4] = direction % 256
+    end
+    return 0
+end
+
+--- Sets where the active entity moves, without turning it.
+SetActiveEntityDirection = function(direction)
+    local scene = WorldVM.scene
+    if scene then scene.direction = direction end
     return 0
 end
 
+--- Sets the speed of the active entity (see WorldMapSettings.scene_speed_unit).
+SetActiveEntityMovespeed = function(speed)
+    local scene = WorldVM.scene
+    if scene then scene.speed = speed end
+    return 0
+end
+
+--- Sets the frames that the next Wait lasts.
+SetWaitFrames = function(frames)
+    local scene = WorldVM.scene
+    if scene then scene.wait_frames = frames end
+    return 0
+end
+
+--- Waits the frames of SetWaitFrames (30 per second), the entity moving all the time. It only waits in a
+-- scene, which runs as a script of the entity; anywhere else (when the scripts only look) it does nothing.
+Wait = function()
+    local scene = WorldVM.scene
+    if not scene then return 0 end
+    local frames = scene.wait_frames or 0
+    scene.wait_frames = 0
+    -- The speed is a distance for each FRAME of the script (speed / 8192 of a mesh, found in ff7.exe), so the
+    -- frame rate only changes how long the scene lasts, not how far the ship goes.
+    local unit = (WorldMapSettings and WorldMapSettings.scene_speed_unit) or 0.05
+    local frame = 1 / ((WorldMapSettings and WorldMapSettings.scene_fps) or 30)
+    while frames > 0 do
+        script:wait(frame)
+        if scene.speed ~= 0 then
+            local angle = scene.direction * 2 * math.pi / 256
+            local step = scene.speed * unit / 30
+            scene.x = scene.x + math.sin(angle) * step
+            scene.z = scene.z + math.cos(angle) * step
+            scene.entity:set_position(scene.x, scene.y, scene.z)
+        end
+        frames = frames - 1
+    end
+    return 0
+end
+
+--- Duration of a frame of the scripts.
+WorldVM.FRAME = 1 / 30
+--- What the scripts that only look at the first position of a scene raise.
+WorldVM.STOP = "world_vm_stop"
+
 --- 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.
@@ -191,6 +265,78 @@ WorldVM.can_enter = function(record, vehicle, landing)
     return allowed ~= nil and allowed[record] == true
 end
 
+--- FIELD.TBL records of the exits to the world that start a scene of the Warship (the parade of Junon, the
+-- Jenova·BIRTH of shpin_3...): the function of its type (8) is the whole scene.
+WorldVM.scene_records = {[36] = true, [37] = true, [38] = true, [39] = true}
+
+--- If an arrival record starts a scene.
+WorldVM.is_scene_record = function(record)
+    return record ~= nil and WorldVM.scene_records[record] == true
+end
+
+--- Where the first command of a function puts the active entity.
+-- @return {x, z, direction} or nil.
+WorldVM.first_position = function(script_function)
+    local spawn = WorldVM.run_sandboxed(function()
+        WorldVM.current = {stop_at_position = true}
+        pcall(script_function, System.WorldMap)
+        local result = WorldVM.current
+        WorldVM.current = nil
+        return result
+    end)
+    if not (spawn.mesh_x and spawn.in_x) 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
+
+--- Starts the scene of the Warship, if the way into the world has one: creates the ship and runs its
+-- function as a script of the entity, so that it can wait. The ship is the active entity (the camera
+-- follows it) and Cloud is hidden. The function ends entering a field.
+-- @param map_id Map of the module (0 WM0, 1 WM2, 2 WM3).
+WorldVM.start_scene = function(map_id)
+    if map_id ~= 0 or not WorldVM.is_scene_record(ReadSpecial(6)) then return end
+    local functions = System.WorldMap.entity_functions
+    local function_id = functions and functions[8] and functions[8][0]
+    local scene_function = function_id and System.WorldMap["world_function_" .. function_id]
+    local model = WorldMapModels.models[WorldMapModels.situations[9][8]]
+    if not (scene_function and model) then
+        print("World map scene: there is no function or model for the Warship")
+        return
+    end
+    local start = WorldVM.first_position(scene_function)
+    if not start then
+        print("World map scene: the function of the Warship doesn't place it")
+        return
+    end
+    local entity_name = "WorldMap" .. model.name .. "_8"
+    EntityContainer[entity_name] = {
+        on_start = function(self)
+            local entity = entity_manager:get_entity(entity_name)
+            if entity == nil then return 0 end
+            local x, y, z = entity:get_position()
+            WorldVM.scene = {
+                entity = entity, entity_name = entity_name, x = x, y = y, z = z,
+                direction = start.direction, speed = 0, wait_frames = 0,
+            }
+            System.WorldMap.specials[4] = start.direction % 256
+            local ok, message = pcall(scene_function, System.WorldMap)
+            WorldVM.scene = nil
+            if not ok then print("World map scene failed: " .. tostring(message)) end
+            return 0
+        end,
+    }
+    world_map_module:add_world_model(
+        model.name .. "_8", WorldMapModels.situations[9][8], start.x, start.z, model.scale, start.direction,
+        0, 0, 0
+    )
+    local cloud = entity_manager:get_entity("WorldMapCloud")
+    if cloud ~= nil then cloud:set_visible(false) end
+    entity_manager:set_player_entity(entity_name)
+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)
@@ -221,6 +367,7 @@ WorldVM.place_models = function(map_id)
             end
         end
     end
+    WorldVM.start_scene(map_id)
 end
 
 --- The types of entities that the init function of the map (function 1) creates with LoadModel,
@@ -298,6 +445,13 @@ WorldVM.prepare = function(map_id)
         end
     end
     System.WorldMap.specials = {}
+    -- Where the player entered the field that the world is entered from (EnterFieldScene).
+    local entry = System.WorldMap.entry_position
+    if entry then
+        System.WorldMap.specials[0] = entry.mesh_x
+        System.WorldMap.specials[1] = entry.mesh_y
+        System.WorldMap.specials[4] = entry.direction
+    end
     -- The arrival of a real field exit has priority over the spawn points of the debug data.
     local real_arrival = System.WorldMap.arrival
     local arrival = real_arrival or (WorldMapDebug and WorldMapDebug.arrival) or 0
@@ -314,6 +468,14 @@ WorldVM.prepare = function(map_id)
             .. (player and (" (the scripts of the record say " .. player.x .. ", " .. player.z .. ")") or ""))
         player = point
     elseif arrival ~= 0 then
+        -- The exits that place the player by the mesh that he entered from (the chocobo ones) put him at the
+        -- corner of that mesh, which can be a mountain: he appears where he entered.
+        if entry and entry.x and player
+            and math.abs(player.x - entry.mesh_x * WorldVM.MESH_SIZE) < 0.01
+            and math.abs(player.z - entry.mesh_y * WorldVM.MESH_SIZE) < 0.01 then
+            player = {x = entry.x, z = entry.z}
+            print("World map arrival: the player appears where he entered, " .. entry.x .. ", " .. entry.z)
+        end
         print("World map arrival: FIELD.TBL record " .. arrival .. (player
             and (", the player appears at " .. player.x .. ", " .. player.z)
             or ", the scripts don't place the player"))

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

@@ -91,6 +91,10 @@
 
     <text name="MateriaMenuTitle">Materia</text>
     <text name="MateriaMenuCheck"><colour value="0.7 0.7 0.7">Check</colour></text>
+    <text name="MateriaMenuArrange">Arrange</text>
+    <text name="MateriaMenuExchange">Exchange</text>
+    <text name="MateriaMenuRemoveAll">Remove all</text>
+    <text name="MateriaMenuTrash">Trash</text>
     <text name="MateriaMenuOrder"><colour value="0.7 0.7 0.7">Order</colour></text>
     <text name="MateriaMenuAP"><colour value="0 0.8 1">A.P.:</colour></text>
     <text name="MateriaMenuAPNext"><colour value="0 0.8 1">Next:</colour></text>
@@ -109,6 +113,9 @@
     <text name="SaveMenuTime">Time</text>
     <text name="SaveMenuMoney">Gil</text>
     <text name="SaveMenuEmptySlot"><colour value="0.6 0.6 0.6">Empty slot</colour></text>
+    <text name="SaveMenuOverride">Override this save slot?</text>
+    <text name="SaveMenuOtherPlaythrough"><colour value="0.75 0.4 1">This slot belongs to another playthrough</colour></text>
+    <text name="SaveMenuSaved"><colour value="0.75 0.4 1">Game saved</colour></text>
     <text name="SaveMenuTitleSave">Save</text>
     <text name="SaveMenuTitleLoad">Load</text>
     <text name="SaveMenuDescSave">Select a slot to save</text>
@@ -251,4 +258,17 @@
     <text name="MagicMenuMpNeeded"><colour value="0 0.8 1">MP needed</colour></text>
     <text name="MagicMenuUses"><colour value="0 0.8 1">Uses</colour></text>
     <text name="StatusMenuTitle">Status</text>
+    <text name="ShopMenuBuy">Buy</text>
+    <text name="ShopMenuSell">Sell</text>
+    <text name="ShopMenuExit">Exit</text>
+    <text name="ShopMenuPromptBuy">What would you like to buy?</text>
+    <text name="ShopMenuPromptSell">What would you like to sell?</text>
+    <text name="ShopMenuPromptQuantity">How many?</text>
+    <text name="ShopMenuTimes">x</text>
+    <text name="ShopMenuGil"><colour value="0 0.8 1">Gil</colour></text>
+    <text name="ShopMenuOwned"><colour value="0 0.8 1">Owned</colour></text>
+    <text name="ShopMenuEquipped"><colour value="0 0.8 1">Equipped</colour></text>
+    <text name="ShopMenuAP"><colour value="0 0.8 1">AP</colour></text>
+    <text name="ShopMenuAtk"><colour value="0 0.8 1">A</colour></text>
+    <text name="ShopMenuDef"><colour value="0 0.8 1">D</colour></text>
 </texts>

+ 13 - 14
doc/AUTHORS.md

@@ -1,16 +1,15 @@
 # Authors
 
-Halkun <[https://forums.qhimm.com/index.php?action=profile;u=109](https://forums.qhimm.com/index.php?action=profile;u=109>
-Akari <https://forums.qhimm.com/index.php?action=profile;u=1266](https://forums.qhimm.com/index.php?action=profile;u=1266>
-Bdulaney88 <draygera@gmail.com>
-Bryce Groff <bgroff@hawaii.edu>
-Gennadiy Brich <gennadiy.brich@gmail.com>
-CapsAdmin <eliashogstvedt@gmail.com>
-Paul <github@paulsapps.com>
-Mike Vidales <this@tranxien.cc>
-sithlord48 <sithlord48@gmail.com>
-Tobias Peters <tobias.peters@kreativeffekt.at>
-Tom-III <brogan.tom.iii@gmail.com>
-myst6re <myst6re@gmail.com>
-Inigo Valentin <i@inigovalentin.com>
-
+- Halkun ([Qhimm Forums profile](https://forums.qhimm.com/index.php?action=profile;u=109))
+- Akari ([Qhimm Forums profile](https://forums.qhimm.com/index.php?action=profile;u=1266))
+- Bdulaney88 <draygera@gmail.com>
+- Bryce Groff <bgroff@hawaii.edu>
+- Gennadiy Brich <gennadiy.brich@gmail.com>
+- CapsAdmin <eliashogstvedt@gmail.com>
+- Paul <github@paulsapps.com>
+- Mike Vidales <this@tranxien.cc>
+- sithlord48 <sithlord48@gmail.com>
+- Tobias Peters <tobias.peters@kreativeffekt.at>
+- Tom-III <brogan.tom.iii@gmail.com>
+- myst6re <myst6re@gmail.com>
+- Iñigo Valentin <i@inigovalentin.com>

+ 46 - 38
doc/BUILD.md

@@ -1,16 +1,28 @@
 # <img src="../v-gears.png" alt="V-Gears" width="50"/> V-Gears Building Guide
 
 ## Install dependencies
-If you are running Debian (or derivates), you can install the required dependencies by running as root
+
+If you are running Debian (or derivates), you can install the required dependencies with:
 
 ```bash
-apt install g++ cmake libqt5widgets5 qtbase5-dev zlib1g-dev libarchive-dev libogre-1.12-dev libois-dev libvorbis-dev libboost-dev libboost-program-options-dev libboost-test-dev libboost-filesystem-dev libboost-thread-dev libopenal-dev libtinyxml-dev libluajit-5.1-dev
+sudo apt install git build-essential cmake qtbase5-dev zlib1g-dev libarchive-dev libogre-1.12-dev libois-dev libvorbis-dev libboost-dev libboost-program-options-dev libboost-test-dev libboost-filesystem-dev libboost-thread-dev libopenal-dev libtinyxml-dev libluajit-5.1-dev
 ```
 
-The data installer also needs FFmpeg and TiMidity (see [Optional programs](#optional-programs)).
+This guide was checked on Debian forky/sid. Other releases and distributions may name some packages differently, especially `libogre-1.12-dev`.
+
+To convert the sound effects, the music and the videos, the data installer also uses FFmpeg and TiMidity. They are not needed to build V-Gears, only to install the game data (see the [data installation guide](INSTALL_DATA.md "Install Data")).
 
 ```bash
-apt install ffmpeg timidity
+sudo apt install ffmpeg timidity
+```
+
+## Get the code
+
+Clone the repository and enter its directory. All the commands in this guide are run from there, which is called the project directory.
+
+```bash
+git clone https://github.com/InigoValentin/V-Gears.git
+cd V-Gears
 ```
 
 ## Build using CMake
@@ -18,38 +30,38 @@ apt install ffmpeg timidity
 From the project directory, run these commands:
 
 ```bash
-mkdir build;
-cd build;
-cmake ../;
-make;
+cmake -S . -B build
+cmake --build build
 ```
 
-If you want to speed it up a bit (it can take several minutes, depending on your system), you can add the parameter `-j` to make to use multiple threads. For instance, `make -j3` will use three cores for the compilation. The build uses a lot of memory, so on machines with little RAM, use a low number (`-j2`).
+If you want to speed it up (it can take several minutes, depending on your system), add `-j` to the second command to use multiple threads. For instance, `cmake --build build -j3` will use three cores for the compilation. The build uses a lot of memory, so on machines with little RAM, use a low number (`-j2`).
 
 Once the build process finishes, you should have the following files (from the project directory):
 
 - `build/bin/v-gears`, the engine executable.
 - `build/bin/v-gears-installer`, the data installer.
 
-If you build with `-DCMAKE_BUILD_TYPE=Debug`, they are in `build/bin_debug/` instead.
+If you add `-DCMAKE_BUILD_TYPE=Debug` to the first command, they are in `build/bin_debug/` instead.
 
 The engine can be launched from anywhere: it finds its data directory (`~/.v-gears/` by default) and fills it from the `data/` folder of the repository the first time. See the [run guide](RUN.md "Run V-Gears") for details.
 
 ## Run the tests (optional)
 
-The tests are not built by default. To build and run the tests of the installer logic (the option rules, the installation layout, the verifier, the log, the tool finder and the movie camera data) and of the data directory and Ogre plugin lookup, which don't need the rest of the engine:
+The tests are not built by default: enable them with `-DBUILD_TESTS=ON`. It's best to use a separate build directory. From the project directory:
 
 ```bash
-mkdir build-tests;
-cd build-tests;
-cmake ../ -DBUILD_TESTS=ON;
-make v-gears-installer-tests;
-./bin/v-gears-installer-tests
+cmake -S . -B build-tests -DBUILD_TESTS=ON
+cmake --build build-tests --target v-gears-tests v-gears-installer-tests
+cd build-tests
+ctest --output-on-failure
 ```
 
-The engine tests (for example the movie state and camera frames) are in the `v-gears-tests` target, built the same way.
+There are two test programs:
 
-<!-- TODO(review): check that `make v-gears-tests` builds on its own and whether more build dependencies (video, audio) are required now. -->
+- `v-gears-tests`, the tests of the engine and of the script decompiler. It links the engine library, so it takes a while to build the first time, and it needs the same dependencies as V-Gears.
+- `v-gears-installer-tests`, the tests of the installer logic (the option rules, the installation layout, the verifier, the log, the tool finder and the movie camera data) and of the data directory and Ogre plugin lookup. It doesn't need the rest of the engine, so it builds quickly.
+
+To build and run only one of them, pass just its name to `--target` and run it from the build directory, for example `./bin/v-gears-installer-tests`.
 
 ## Make packages (optional)
 
@@ -60,14 +72,13 @@ V-Gears can be packaged for Linux as a `.deb` package and as a `.tar.gz` archive
 Use a separate Release build, so it doesn't interfere with your development build. From the project directory:
 
 ```bash
-mkdir build-release;
-cd build-release;
-cmake ../ -DCMAKE_BUILD_TYPE=Release;
-make -j4 v-gears v-gears-installer;
-cpack;
+cmake -S . -B build-release -DCMAKE_BUILD_TYPE=Release
+cmake --build build-release -j4 --target v-gears v-gears-installer
+cd build-release
+cpack
 ```
 
-The first build takes a while. Adjust `-j` as explained in [Build using CMake](#build-using-cmake).
+The first build takes a while. Adjust `-j` as explained in [Build using CMake](#build-using-cmake). Making the `.deb` needs `dpkg-dev`, which comes with `build-essential`.
 
 When `cpack` finishes, `build-release/` contains:
 
@@ -83,7 +94,7 @@ Both have the same files:
 
 - `bin/v-gears` and `bin/v-gears-installer`, the engine and the data installer.
 - `share/v-gears/`, the V-Gears data files (configuration, scripts, screens, fonts...). The engine copies them to the user's data directory (`~/.v-gears/`) the first time it runs, and the data installer adds the game data there.
-- `share/doc/v-gears/`, the documentation and the license.
+- `share/doc/v-gears/`, the documentation for players (not the build and style guides) and the license.
 - `share/applications/` and `share/icons/`, the desktop files and the icons.
 
 The `.deb` installs them under `/usr`, so both programs show in the applications menu. Install it with `apt`, so it installs the dependencies too:
@@ -114,10 +125,18 @@ These can be set when running `cmake` (`-D<option>=<value>`):
 
 ### Install without a package
 
-To install V-Gears directly in the system, with the same files and layout as the packages, run this from the build directory:
+To install V-Gears directly in the system, with the same files and layout as the packages, build it and then install it. From the project directory:
+
+```bash
+cmake -S . -B build-release -DCMAKE_BUILD_TYPE=Release
+cmake --build build-release -j4
+sudo cmake --install build-release --prefix /usr/local
+```
+
+CMake writes the list of installed files to `build-release/install_manifest.txt`. To uninstall, remove those files. This leaves their directories, and your data in `~/.v-gears/`.
 
 ```bash
-sudo cmake --install . --prefix /usr/local
+sudo xargs -d '\n' rm -f -- < build-release/install_manifest.txt
 ```
 
 ## Advanced build options
@@ -139,18 +158,7 @@ If you see warnings about missing Boost or OgreBites, prefer installing the
 appropriate `-dev` packages listed above, or point CMake at your OGRE/Boost
 installation with `-DOGRE_ROOT=...` and `-DBoost_DIR=...`/`-DBoost_LIBRARY_DIRS`.
 
-## Optional programs
-
-To convert the sound effects, the music and the videos, the installer uses FFmpeg and TiMidity. They are not needed to build V-Gears, only to install the data. In Debian (or derivates):
-
-```bash
-apt install ffmpeg timidity
-```
-
-See the [data installation guide](INSTALL_DATA.md "Install Data").
-
 ## Next steps
 
-- [Install V-Gears](INSTALL.md "Install V-Gears")
 - [Install data](INSTALL_DATA.md "Install Data")
 - [Run V-Gears](RUN.md "Run V-Gears")

+ 80 - 0
doc/CHANGELOG.md

@@ -1,5 +1,85 @@
 # Changelog
 
+## 0.4.0
+
+Changes since 0.3.5. Most of the work is in the battle and menu modules (rules, cameras, shops and materia), and in fixes from playing through the fields and the world map.
+
+### Menus
+
+**Shops**
+- New shop menu to buy and sell items, weapons, armor, accessories and materia, opened by the field scripts. The installer reads the inventory of each shop from the game executable.
+- New console command `/shop <shop_id>`.
+- Fixed the ids and prices of the accessories.
+
+**Materia**
+- The Check, Order and Exchange options of the materia menu work.
+
+**Party, items and saving**
+- The Order option of the main menu swaps party slots and rows. The character controlled in the field is set by the scripts, saved with the game, and doesn't change with the party order.
+- Locked characters can change slots, but can't leave or join the party.
+- Item menu: Order > Custom swaps items by hand.
+- The save menu asks before saving over a slot and confirms when the game is saved.
+- New console command `/phs <character_id|all> [on|off]`.
+- The console is drawn over the menus.
+
+### Battle
+
+**Rules**
+- Enemy HP and MP are read from the game data. Enemies pay the MP of their attacks, and fail the ones they can't pay.
+- Source bonuses count in the stats (capped at 255). Equipped materia and accessories modify the stats.
+- Accuracy and evasion fixes, including magic hit chance, Darkness, evade modifiers and several commands.
+- Per character divisors for the limit bar.
+- Fixed MP usage and spell strength with support materia.
+- Only felled enemies give rewards.
+
+**Characters**
+- Characters level up with the growth curves of the original game.
+- Recruits get their level from the party average, and reused characters get their own data first.
+- Fields can enable every character in the PHS, not only the first two. Hiding a character removes it from the party.
+
+**Statuses**
+- Silence, Frog and Small restrict the actions they should.
+- Only physical hits cure Sleep, Confusion and Manipulate. Haste and Slow replace each other, and Petrify removes Sleep, Poison, Confusion and Regen. Actions of combatants that can't act wait until they can.
+- Confused combatants attack or cast a random spell at the opposite side. Berserk party members only use the plain Attack.
+
+**Cameras and animation**
+- Fixed the camera axes, and the depth, aim and scale of the scripted attack cameras.
+- Items and limits use their own cameras. New camera instructions (orbit, target group, single target and model view).
+- Added the camera at the start of a battle, the victory camera, and the shots and view changes of the enemy animations.
+- Fixed the scale of party members, enemies and backgrounds.
+- Unknown animation sequences are skipped.
+- Fixed consecutive battles.
+
+### Field
+
+**Installer and decompiler**
+- New opcodes: `SMTRA` (give materia), `GTPYE` and `SPTYE` (store and restore the party), `MENU` 17 (unequip materia), `MINIGAME` (skips to the return field), `MVCAM` (movie camera), `MUSVT` (stop music), `WNUMB` (number windows), `SLINE` (move a line trigger) and party requests by party slot.
+- Fixed the menu lock, byte arithmetic wrapping, `KAWAI` sub-opcodes (party members could wait forever), and scripts falling through after `RETTO`.
+- Fields no longer fail to convert because of a request to a missing script. frcyo and del3 are no longer skipped.
+- Fixed the intensity of additive tiles. Music tracks 14, 64, 87 and 96 are converted.
+
+**Engine**
+- Touching an entity runs its contact script. Fixes to script priorities, movement and turn syncs, scripted walks off the walkmesh, player entity changes and party followers.
+- Fixed the camera limits of off-center ranges and the height of characters in some scripted walks.
+- Backgrounds hold up to 4096 tiles of each kind, and tile intensity scales their colour.
+- Movies can be drawn behind the models, and fades don't cover them.
+- Dialogs handle long texts and number windows, and text pauses are counted in frames.
+- The party and save menus can be opened by scripts. The pause menu doesn't open when a script reads Start.
+- `/map` uses the field list, and `/screenshot` saves PNG files.
+
+### World map
+
+- Entering a field from the world no longer makes the player walk on their own.
+- Flags set by fields are seen by the world scripts.
+- The Warship scenes after jundoc1a and shpin_3 play.
+- Placed models face the right way.
+- Exits back to the world map put the player where they entered.
+
+### Build and documentation
+
+- The tests build again.
+- Updated the README and the build, run and authors documentation. `INSTALL.md` was removed.
+
 ## 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.

+ 1 - 1
doc/HISTORY.md

@@ -66,7 +66,7 @@ For a while, I added no new functionalities to the engine itself. That changed a
 
 ---
 
-##The Future - Here Is Where You Keep Going.
+## The Future - Here Is Where You Keep Going.
 
 I know I won't be the one who finishes V-Gears. Hell, I know I'm not the one who will announce the version 1 of it. I honestly don't have the skills or the time to do so.
 

+ 0 - 25
doc/INSTALL.md

@@ -1,25 +0,0 @@
-# <img src="../v-gears.png" alt="V-Gears" width="50"/> V-Gears Installation Guide
-
-## Manual installation
-
-The data installer can do this for you: enable "Copy V-Gears data files" in its advanced options and it copies the `data/` folder of the repository (`share/v-gears/` in an installed package) to the installation directory. To do it by hand:
-
-1. Create a folder for V-Gears data, outside the project. In Linux-based systems, it's recommended to use `~/.v-gears/`.
-2. Copy all the contents of the `data/` folder of the repository to the newly created directory. It should end up like this:
-```
-~/.v-gears/
-  ├── data
-  ├── field_models_and_animation_metadata.xml
-  ├── plugins.cfg
-  ├── plugins_d.cfg
-  ├── resources.cfg
-  └── resources_d.cfg
-```
-3. If you used a directory other than `~/.v-gears/`, start V-Gears from it, or pass it with `--data-dir` (see [Run V-Gears](RUN.md "Run V-Gears")).
-
-If you skip these steps, V-Gears copies the files to `~/.v-gears/` itself the first time it runs.
-
-## Next steps
-
-- [Install data](INSTALL_DATA.md "Install Data")
-- [Run V-Gears](RUN.md "Run V-Gears")

+ 0 - 2
doc/INSTALL_DATA.md

@@ -35,8 +35,6 @@ To add the missing audio later, install the programs and run the installer again
 
 ## Launch the Installer
 
-If you have followed the [build](BUILD.md "Building guide") and [installaton](INSTALL.md "Installation guide") guides, you'll have the game data copied to `~/.v-gears/` (or you can let the installer copy it, see below), and the binaries compiled somewhere (we'll assume they are in `~/V-Gears/build/bin`, change the directories according to your system). Just run the installer:
-
 ```Bash
 ~/V-Gears/build/bin/v-gears-installer
 ```

+ 2 - 2
doc/RUN.md

@@ -2,7 +2,7 @@
 
 ## Run the engine
 
-If you have followed the [build](BUILD.md "Building guide") and [installation](INSTALL.md "Installation guide") guides, you'll have the game data installed to `~/.v-gears/`, and the binaries compiled somewhere (we'll assume they are in `~/V-Gears/build/bin`, change the directories according to your system).
+If you have followed the [build](BUILD.md "Building guide") and [installation](INSTALL_DATA.md "Installation guide") guides, you'll have the game data installed to `~/.v-gears/`, and the binaries compiled somewhere (we'll assume they are in `~/V-Gears/build/bin`, change the directories according to your system).
 
 Run the engine from any directory:
 
@@ -39,7 +39,7 @@ The default bindings are in `config/config.cfg` of the installation directory, i
 |Page Up / Page Down|L1 / R1|Switch tab or character in menus|
 |Left Ctrl|run|Run in the field|
 
-The settings made in the in-game config menu (controls, sound, etc.) are saved with the game settings and loaded on start.
+The control settings changes made in the in-game config menu are saved with the game settings and loaded on start.
 
 <!-- TODO(review): verify the table against the in-game config menu (control remapping), and check the gamepad status. -->
 

+ 29 - 0
doc/TODO.md

@@ -24,6 +24,16 @@ First step: play the scene with log level 3 and look at the time between the `di
 layer of mds5_4 has no such opcodes and still scrolls with the rest, and it is not known why it should
 not.
 
+## Battle: recruits that remain untested
+
+Yuffie, Vincent and Cait Sith remain untested: the level they join with (`Characters.join` in `system.lua`)
+and, for Vincent and Cait Sith, the data they get when they are named (`Characters.load_recruit_record`). The
+other characters are working fine.
+
+- Yuffie's level comes from the variable at bank 1, address 2. Only the field blackbg4 writes it, so it is not
+  known what sets it in a normal game. While it is 0 the average level of the party is used, which is not from
+  the original.
+
 ## Battle: special limits
 
 Not done yet (kernel data in ff7.exe, ids 170-176, see `get_special_limit` in `battle_ui.lua`):
@@ -101,3 +111,22 @@ collides with several solid NPCs that stop around it (`CheckSolidCollisions`).
 The model of Ren was invisible. The probable cause (an instant `OFST` did not cancel a running smooth
 offset, so Ren stayed 4 units away) was fixed in `Entity::ScriptOffsetToPosition`, but it has not been
 tested in the game. Check the helicopter intro of pillar_3 and that Ren appears and jumps down.
+
+## World map: the exit of sichi
+
+When the player leaves sichi he appears where he entered (the exit script puts him at the corner of the mesh, which is a mountain, so `WorldVM.prepare` uses the exact position saved by `EnterFieldScene`). The original game position for this exit is not known. The direction that is saved (special 4) is not used for the player.
+
+## World map: the scenes of the Warship (what is missing)
+
+The scenes after jundoc1a (record 36) and shpin_3 (record 37) work: `WorldVM.start_scene` in `world_vm.lua` runs the
+function of the Warship (type 8) as a script of the entity, with `Wait`, speed and direction (the speed is
+`speed / 8192` of a mesh each frame, from ff7.exe; the scripts run at 15 frames per second, which is what the user
+remembers of the original). Not done:
+
+- `PlaySoundEffect(381)` at the start is a stub (the sound id is not mapped to an audio file).
+- `kernel_unknown_0x319`, `0x31C`, `0x31F`, `0x329`, `0x32A` and `0x32F` are stubs: they may be camera moves, fades or
+  sound state, and the original may use them to frame the ship or fade out at the end. They can be decoded from the
+  jump table at 0x75bfb9 of ff7.exe (kernel dispatcher 0x75b14c).
+- The records 38 and 39 also have a Warship scene in `world_function_64`; it is not known which fields lead to them and they
+  were not tested. The last move of record 37 (direction 176, facing 48) is a plain move without turning.
+- The vehicles may run at 15 frames per second as well (their speeds were tuned by eye).

+ 4 - 4
src/Version.h

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

+ 43 - 25
src/core/Background2D.cpp

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

+ 13 - 1
src/core/Background2D.h

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

+ 13 - 4
src/core/BattleManager.cpp

@@ -50,13 +50,11 @@ template<>BattleManager *Ogre::Singleton<BattleManager>::msSingleton = nullptr;
 ConfigVar cv_debug_battle_grid("debug_battle_grid", "Draw debug battle grid", "false");
 ConfigVar cv_debug_battle_axis("debug_battle_axis", "Draw debug battle axis", "false");
 
-const float BattleManager::ENEMY_SCALE = 0.0032f;
+const float BattleManager::ENEMY_SCALE = 1.0f / 255.0f;
 
 const float BattleManager::ATTACK_SCALE = 0.0032f;
 
-const float BattleManager::PARTY_SCALE = 0.0039f;
-
-const float BattleManager::SCENE_SCALE = 0.0012f;
+const float BattleManager::PARTY_SCALE = 1.0f / 255.0f;
 
 const float BattleManager::PARTY_Y = 5.0f;
 
@@ -106,6 +104,7 @@ void BattleManager::ClearBattle(){
     // TODO location_ = null;
     camera_.clear();
     initial_camera_ = 0;
+    intro_camera_ = -1;
     layout_ = LAYOUT::NORMAL;
     escape_difficulty_ = 0.0f;
     arena_battle_ = false;
@@ -636,6 +635,16 @@ void BattleManager::SetInitialCamera(const unsigned int id){
     initial_camera_ = id;
 }
 
+void BattleManager::SetIntroCamera(const int id){
+    if (module_ != Module::BATTLE){
+        LOG_ERROR("Tried to set the camera in the BattleManager, but it's not in battle mode.");
+        return;
+    }
+    intro_camera_ = id;
+}
+
+int BattleManager::ScriptGetIntroCamera() const{return intro_camera_;}
+
 void BattleManager::LoadParty(){
     if (module_ != Module::BATTLE){
         LOG_ERROR("Tried to load party in the BattleManager, but it's not in battle mode.");

+ 21 - 9
src/core/BattleManager.h

@@ -290,7 +290,6 @@ class BattleManager : public Manager, public Ogre::Singleton<BattleManager>{
           const int orientation, const char* animation
         );
 
-
         /**
          * Adds a mesh of a visual effect to the battle scene.
          *
@@ -349,7 +348,6 @@ class BattleManager : public Manager, public Ogre::Singleton<BattleManager>{
          */
         void ScriptRemoveDynamicMesh(const char* name);
 
-
         /**
          * Sets the battle layout.
          *
@@ -576,6 +574,20 @@ class BattleManager : public Manager, public Ogre::Singleton<BattleManager>{
          */
         void SetInitialCamera(const unsigned int id);
 
+        /**
+         * Sets the camera script of the start of the battle.
+         *
+         * @param[in] id ID of the script, -1 for none.
+         */
+        void SetIntroCamera(const int id);
+
+        /**
+         * Gets the camera script of the start of the battle.
+         *
+         * @return ID of the script, -1 if there is none.
+         */
+        int ScriptGetIntroCamera() const;
+
         /**
          * Changes the battle camera to one of the cameras of the formation.
          *
@@ -651,7 +663,6 @@ class BattleManager : public Manager, public Ogre::Singleton<BattleManager>{
          */
         void ClearDynamicMeshes();
 
-
         /**
          * Loads the party members into the battle.
          */
@@ -718,7 +729,8 @@ class BattleManager : public Manager, public Ogre::Singleton<BattleManager>{
         static const float SIDE_DISTANCE;
 
         /**
-         * Scale factor for battle enemy models.
+         * Scale factor for battle enemy models: the one of the positions of the battle (the original units are
+         * 255 times smaller than the ones of the scene).
          */
         static const float ENEMY_SCALE;
 
@@ -727,11 +739,6 @@ class BattleManager : public Manager, public Ogre::Singleton<BattleManager>{
          */
         static const float PARTY_SCALE;
 
-        /**
-         * Scale factor for battle background models.
-         */
-        static const float SCENE_SCALE;
-
         /**
          * Scale factor for battle attack and spell models.
          */
@@ -763,6 +770,11 @@ class BattleManager : public Manager, public Ogre::Singleton<BattleManager>{
          */
         unsigned int initial_camera_;
 
+        /**
+         * Camera script of the start of the battle.
+         */
+        int intro_camera_;
+
         /**
          * Battle layout.
          */

+ 5 - 18
src/core/CameraManager.cpp

@@ -174,12 +174,6 @@ void CameraManager::Set2DCamera(
 void CameraManager::StartBattleCamera(
   const Ogre::Vector3 position, const Ogre::Vector3 orientation
 ){
-    /*
-     * TODO: Something is wrong here. The camera look 'mostly' okay, but it's still weird.
-     * Also, there are variations and it doesn't look the same on successive calls.
-     * I thinks it's something related to the lookAt functions.
-     * Try to fix it. First, replace the deprecated calls, and see what happens.
-     */
     if (module_ != Module::BATTLE){
         LOG_ERROR("Tried to start battle camera but the CameraManager is already in battle mode");
         return;
@@ -218,15 +212,8 @@ void CameraManager::StartBattleCamera(
 }
 
 void CameraManager::SetBattleCamera(const Ogre::Vector3 position, const Ogre::Vector3 orientation){
-    camera_->resetFrustumExtents();
-    camera_->setFOVy(Ogre::Radian(Ogre::Math::PI / 4.0f));
-    camera_->setOrientation(Ogre::Quaternion::IDENTITY);
-    camera_->setPosition(position);
-    //CameraManager::getSingleton().GetCurrentCamera()->setFixedYawAxis(true, Ogre::Vector3::UNIT_Y);
-    camera_->lookAt(orientation);
-    camera_->roll(Ogre::Angle(90));
-    // Fix: compensate for the battle UI covered section of the screen.
-    camera_->move(Ogre::Vector3(0, 0, -4));
+    // The second vector is the point the camera looks at.
+    SetBattleCameraUpright(position, orientation);
 }
 
 void CameraManager::SetBattleCameraUpright(
@@ -245,9 +232,9 @@ void CameraManager::SetBattleCameraUpright(
     camera_->setFOVy(Ogre::Radian(Ogre::Math::PI / 4.0f));
     camera_->setPosition(position);
     camera_->setOrientation(Ogre::Quaternion(right, up, -direction));
-    // Compensation of the battle UI, like the other battle cameras. They move the camera 4 units
-    // down at about 60 units from the scene, so it's proportional to the distance here, because
-    // the cameras of the effects go from very far to very close.
+    // Compensation of the section of the screen that the battle UI covers: the camera moves down. It's
+    // proportional to the distance (4 units at about 60 from the scene), because the cameras of the
+    // effects go from very far to very close.
     const float distance = (look_at - position).length();
     camera_->move(Ogre::Vector3(0, 0, -0.066f * distance));
 }

+ 3 - 3
src/core/CameraManager.h

@@ -174,7 +174,7 @@ class CameraManager : public Manager, public Ogre::Singleton<CameraManager>{
         const Ogre::Vector3 ProjectPointToScreen(const Ogre::Vector3& point);
 
         /**
-         * Sets the battle camera.
+         * Sets the battle camera, like {@see SetBattleCameraUpright}.
          *
          * Unlike {@see StartBattleCamera}, it doesn't save the state of the field camera, so it
          * can be used to change the camera during a battle.
@@ -187,8 +187,8 @@ class CameraManager : public Manager, public Ogre::Singleton<CameraManager>{
         /**
          * Sets the battle camera, always with the Z axis of the scene pointing up.
          *
-         * {@see SetBattleCamera} is only upright for cameras looking toward negative X, so this
-         * one is for the cameras of the effects, that can look anywhere.
+         * It also moves the camera down to compensate for the part of the screen that the battle
+         * interface covers.
          *
          * @param[in] position Camera position.
          * @param[in] look_at Point the camera looks at.

+ 54 - 7
src/core/ConfigCmdHandlerCommands.h

@@ -20,6 +20,7 @@
 #include <OgreStringConverter.h>
 #include "Console.h"
 #include "EntityManager.h"
+#include "ScriptManager.h"
 #include "Logger.h"
 #include "XmlMapFile.h"
 #include "XmlMapsFile.h"
@@ -292,11 +293,55 @@ void CmdMap(const Ogre::StringVector& params){
         Console::getSingleton().AddTextToOutput("Usage: /map [map_id]");
         return;
     }
-    EntityManager::getSingleton().Clear();
-    XmlMapsFile xml("./data/maps.xml");
-    Ogre::String file_name = xml.GetMapFileNameByName(params[1]);
-    XmlMapFile xml_map("./data/" + file_name);
-    xml_map.LoadMap();
+    // The same as the map function of the scripts (the old list of maps, ./data/maps.xml, doesn't
+    // exist: the fields are in ./data/fields/_fields.xml).
+    ScriptManager::getSingleton().RunString("map(\"" + params[1] + "\")");
+}
+
+/**
+ * Opens a shop, to test the shop menu by hand.
+ *
+ * @param[in] params Command parameters: the command name and the ID of the shop (0-79).
+ */
+void CmdShop(const Ogre::StringVector& params){
+    if (params.size() != 2){
+        Console::getSingleton().AddTextToOutput("Usage: /shop <shop_id>");
+        return;
+    }
+    // The scripts open shops with open_shop(), that waits for the menu to close and can only run
+    // in a script. Showing the menu directly doesn't need that.
+    ScriptManager::getSingleton().RunString(
+      "UiContainer.ShopMenu.shop_id = tonumber(\"" + params[1] + "\") or -1; "
+      "UiContainer.ShopMenu:show()"
+    );
+}
+
+/**
+ * Enables or disables characters in the PHS.
+ *
+ * @param[in] params Command parameters: the command name, the ID of the character (0-8) or "all", and
+ * optionally "on" (the default) or "off".
+ */
+void CmdPhs(const Ogre::StringVector& params){
+    if (params.size() < 2 || params.size() > 3){
+        Console::getSingleton().AddTextToOutput("Usage: /phs <character_id|all> [on|off]");
+        return;
+    }
+    const bool enable = params.size() < 3 || (params[2] != "off" && params[2] != "0");
+    const std::string value = enable ? "true" : "false";
+    std::string first = "0";
+    std::string last = "8";
+    if (params[1] != "all"){
+        first = params[1];
+        last = params[1];
+    }
+    ScriptManager::getSingleton().RunString(
+      "for id = (tonumber(\"" + first + "\") or -1), (tonumber(\"" + last + "\") or -2) do "
+      "if type(Characters[id]) == \"table\" then Characters[id].enabled = " + value + " end end"
+    );
+    Console::getSingleton().AddTextToOutput(
+      std::string(enable ? "Enabled " : "Disabled ") + (params[1] == "all" ? "all characters" : "character " + params[1]) + " in the PHS"
+    );
 }
 
 /**
@@ -305,7 +350,7 @@ void CmdMap(const Ogre::StringVector& params){
  * @param[in] complete_params The map names will be loaded here.
  */
 void CmdMapCompletion(Ogre::StringVector& complete_params){
-    XmlMapsFile xml("./data/maps.xml");
+    XmlMapsFile xml("./data/fields/_fields.xml");
     xml.GetMapNames(complete_params);
 }
 
@@ -368,7 +413,7 @@ void CmdResolutionCompletition(Ogre::StringVector& complete_params){
  */
 void CmdScreenshot(const Ogre::StringVector& params){
     Ogre::RenderWindow* window = VGears::Application::getSingleton().getRenderWindow();
-    Ogre::String ret = window->writeContentsToTimestampedFile("screenshot_", ".tga");
+    Ogre::String ret = window->writeContentsToTimestampedFile("screenshot_", ".png");
     Console::getSingleton().AddTextToOutput("Screenshot " + ret + " saved.");
 }
 
@@ -486,6 +531,8 @@ void ConfigCmdHandler::InitCmd(){
     );
     AddCommand("set_log_level", "Set log messages level", "", CmdSetLogLevel, NULL);
     AddCommand("map", "Run game module", "", CmdMap, CmdMapCompletion);
+    AddCommand("shop", "Open a shop", "<shop_id>", CmdShop, NULL);
+    AddCommand("phs", "Enable or disable characters in the PHS", "<character_id|all> [on|off]", CmdPhs, NULL);
     AddCommand("resolution", "Change resolution", "", CmdResolution, CmdResolutionCompletition);
     AddCommand("screenshot", "Capture current screen content", "", CmdScreenshot, NULL);
     AddCommand("fade", "Start a screen fade", "<type> <r> <g> <b> <speed>", CmdFade, NULL);

+ 42 - 36
src/core/DebugDraw.cpp

@@ -416,45 +416,51 @@ void DebugDraw::Text(
     }
 }
 
+void DebugDraw::SetOverlayDrawnByUi(const bool drawn_by_ui){overlay_drawn_by_ui_ = drawn_by_ui;}
+
+void DebugDraw::RenderOverlay(){
+    render_system_->clearFrameBuffer(Ogre::FBT_DEPTH);
+    // The text and the quads are given in screen coordinates. The background leaves its scroll
+    // in the view matrix, so without this they would move with it, but not at the same speed.
+    render_system_->_setWorldMatrix(Ogre::Matrix4::IDENTITY);
+    render_system_->_setViewMatrix(Ogre::Matrix4::IDENTITY);
+    render_system_->_setProjectionMatrix(Ogre::Matrix4::IDENTITY);
+    auto render_params= render_system_->getFixedFunctionParams(Ogre::TVC_NONE, Ogre::FOG_NONE);
+    render_params->setConstant(
+      Ogre::GpuProgramParameters::ACT_WORLD_MATRIX, Ogre::Matrix4::IDENTITY
+    );
+    render_params->setConstant(
+      Ogre::GpuProgramParameters::ACT_PROJECTION_MATRIX, Ogre::Matrix4::IDENTITY
+    );
+    render_params->setConstant(
+      Ogre::GpuProgramParameters::ACT_VIEW_MATRIX, Ogre::Matrix4::IDENTITY
+    );
+    render_system_->applyFixedFunctionParams(render_params, Ogre::GPV_GLOBAL);
+
+    if (line_render_operation_.vertexData->vertexCount != 0){
+        scene_manager_->_setPass(material_->getTechnique(0)->getPass(0), true, false);
+        render_system_->_render(line_render_operation_);
+        line_render_operation_.vertexData->vertexCount = 0;
+    }
+    if (quad_render_operation_.vertexData->vertexCount != 0){
+        scene_manager_->_setPass(material_->getTechnique(0)->getPass(0), true, false);
+        render_system_->_render(quad_render_operation_);
+        quad_render_operation_.vertexData->vertexCount = 0;
+    }
+    if (text_render_operation_.vertexData->vertexCount != 0){
+        scene_manager_->_setPass(
+          font_->getMaterial()->getTechnique(0)->getPass(0), true, false
+        );
+        render_system_->_render(text_render_operation_);
+        text_render_operation_.vertexData->vertexCount = 0;
+    }
+}
+
 void DebugDraw::renderQueueEnded(
   Ogre::uint8 queueGroupId, const Ogre::String& invocation, bool& repeatThisInvocation
 ){
     if (queueGroupId == Ogre::RENDER_QUEUE_OVERLAY){
-        render_system_->clearFrameBuffer(Ogre::FBT_DEPTH);
-        // The text and the quads are given in screen coordinates. The background leaves its scroll
-        // in the view matrix, so without this they would move with it, but not at the same speed.
-        render_system_->_setWorldMatrix(Ogre::Matrix4::IDENTITY);
-        render_system_->_setViewMatrix(Ogre::Matrix4::IDENTITY);
-        render_system_->_setProjectionMatrix(Ogre::Matrix4::IDENTITY);
-        auto render_params= render_system_->getFixedFunctionParams(Ogre::TVC_NONE, Ogre::FOG_NONE);
-        render_params->setConstant(
-          Ogre::GpuProgramParameters::ACT_WORLD_MATRIX, Ogre::Matrix4::IDENTITY
-        );
-        render_params->setConstant(
-          Ogre::GpuProgramParameters::ACT_PROJECTION_MATRIX, Ogre::Matrix4::IDENTITY
-        );
-        render_params->setConstant(
-          Ogre::GpuProgramParameters::ACT_VIEW_MATRIX, Ogre::Matrix4::IDENTITY
-        );
-        render_system_->applyFixedFunctionParams(render_params, Ogre::GPV_GLOBAL);
-
-        if (line_render_operation_.vertexData->vertexCount != 0){
-            scene_manager_->_setPass(material_->getTechnique(0)->getPass(0), true, false);
-            render_system_->_render(line_render_operation_);
-            line_render_operation_.vertexData->vertexCount = 0;
-        }
-        if (quad_render_operation_.vertexData->vertexCount != 0){
-            scene_manager_->_setPass(material_->getTechnique(0)->getPass(0), true, false);
-            render_system_->_render(quad_render_operation_);
-            quad_render_operation_.vertexData->vertexCount = 0;
-        }
-        if (text_render_operation_.vertexData->vertexCount != 0){
-            scene_manager_->_setPass(
-              font_->getMaterial()->getTechnique(0)->getPass(0), true, false
-            );
-            render_system_->_render(text_render_operation_);
-            text_render_operation_.vertexData->vertexCount = 0;
-        }
+        if (!overlay_drawn_by_ui_) RenderOverlay();
     }
     else if (queueGroupId == Ogre::RENDER_QUEUE_MAIN){
         render_system_->_setWorldMatrix(Ogre::Matrix4::IDENTITY);
@@ -505,7 +511,7 @@ void DebugDraw::DestroyLineVertexBuffer(){
 }
 
 void DebugDraw::CreateLine3dVertexBuffer(){
-    line_3d_max_vertex_ = 1024 * 2;
+    line_3d_max_vertex_ = 8192 * 2;
     line_3d_render_operation_.vertexData = new Ogre::VertexData;
     line_3d_render_operation_.vertexData->vertexStart = 0;
     Ogre::VertexDeclaration* vertex_declaration

+ 20 - 0
src/core/DebugDraw.h

@@ -195,6 +195,21 @@ class DebugDraw : public Ogre::RenderQueueListener, public Ogre::Singleton<Debug
           const Ogre::String& text
         );
 
+        /**
+         * Sets whether the overlay is drawn by whoever calls {@see RenderOverlay}, instead of when
+         * the overlay queue ends.
+         *
+         * The listeners are called in the order they were added, and this one was added before the
+         * menus. The menus take over the drawing of the overlay to draw the console over them.
+         * Moving this listener after the others instead breaks the drawing of the background.
+         */
+        void SetOverlayDrawnByUi(const bool drawn_by_ui);
+
+        /**
+         * Draws the overlay of the debug drawing: the lines, quads and text in screen space.
+         */
+        void RenderOverlay();
+
         /**
          * Ends the render queue.
          *
@@ -209,6 +224,11 @@ class DebugDraw : public Ogre::RenderQueueListener, public Ogre::Singleton<Debug
         );
 
     private:
+        /**
+         * Is the overlay drawn by the UI, after the menus?
+         */
+        bool overlay_drawn_by_ui_ = false;
+
 
         /**
          * Creates a 2D line vertex buffer (2 vertices).

+ 36 - 2
src/core/DialogsManager.cpp

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

+ 23 - 1
src/core/DialogsManager.h

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

+ 5 - 0
src/core/Entity.cpp

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

+ 11 - 0
src/core/Entity.h

@@ -387,6 +387,17 @@ class Entity{
             return std::make_tuple(0.0f, 0.0f, 0.0f);
         }
 
+        /**
+         * Gets the position in the scene of the end of a bone of the skeleton of the entity.
+         *
+         * @param[in] bone Number of the bone.
+         * @param[in] length Length of the bone, in the units of the model.
+         * @return The position, all zeros if there is no such bone.
+         */
+        virtual std::tuple<float, float, float> ScriptGetBoneEnd(const int bone, const float length){
+            return std::make_tuple(0.0f, 0.0f, 0.0f);
+        }
+
         /**
          * Attaches another model to a bone of this entity's skeleton, like the weapon a battle character
          * holds. A previously attached model is replaced.

+ 161 - 10
src/core/EntityManager.cpp

@@ -69,7 +69,7 @@ static const float ENCOUNTER_CHECK_FRAMES = 8.0f;
  */
 static const float ENCOUNTER_STEP_VALUE = 5.0f;
 
-const float EntityManager::SCENE_SCALE = 0.003f;
+const float EntityManager::SCENE_SCALE = 1.0f / 255.0f;
 
 const unsigned int EntityManager::BATTLE_BACKGROUND_ID = 1000;
 
@@ -184,14 +184,28 @@ EntityManager::~EntityManager(){
 void EntityManager::Input(const VGears::Event& event){
     background_2d_.InputDebug(event);
     if (paused_ == true) return;
+    if (ignore_held_walk_){
+        InputManager& input = InputManager::getSingleton();
+        if (
+          !input.IsGameEventPressed("walk_left") && !input.IsGameEventPressed("walk_right")
+          && !input.IsGameEventPressed("walk_up") && !input.IsGameEventPressed("walk_down")
+        ) ignore_held_walk_ = false;
+    }
     if (player_entity_ != NULL && player_lock_ == false){
-        if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_left") player_move_.x = -1;
-        else if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_right")
-            player_move_.x = 1;
-        if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_down") player_move_.y = -1;
-        else if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_up")
-            player_move_.y = 1;
-        if (event.type == VGears::ET_KEY_REPEAT && event.event == "run") player_run_ = true;
+        // Keys held since the world map are ignored until they are released.
+        const bool key_ignored = ignore_held_walk_ && (
+          event.event == "walk_left" || event.event == "walk_right" || event.event == "walk_up"
+          || event.event == "walk_down" || event.event == "run"
+        );
+        if (!key_ignored){
+            if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_left") player_move_.x = -1;
+            else if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_right")
+                player_move_.x = 1;
+            if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_down") player_move_.y = -1;
+            else if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_up")
+                player_move_.y = 1;
+            if (event.type == VGears::ET_KEY_REPEAT && event.event == "run") player_run_ = true;
+        }
         if (event.type == VGears::ET_KEY_PRESS && event.event == "CONFIRM"){
             CheckEntityInteract();
             for (unsigned int i = 0; i < entity_triggers_.size(); ++ i){
@@ -320,6 +334,15 @@ void EntityManager::UpdateField(){
                             }
                         }
                         else is_move = PerformWalkmeshMove(entity_[i], speed, remaining_time);
+                        // The scripts set the animation of a scene as the default one (DFANM) and
+                        // don't set it back, but the player stands normally again as soon as they
+                        // walk in the original game (blin67_3, where Cloud ends the scene crouched).
+                        if (
+                          is_move == true && player_lock_ == false && player_entity_ == entity_[i]
+                          && entity_[i]->GetDefaultAnimationName() != "Idle"
+                        ){
+                            entity_[i]->ScriptSetDefaultAnimation("Idle");
+                        }
                         if (entity_[i]->GetMoveAutoAnimation() == true){
                             if (is_move == true){
                                 if (speed >= entity_[i]->GetMoveRunSpeed()){
@@ -361,6 +384,7 @@ void EntityManager::UpdateField(){
                 break;
         }
     }
+    CheckEntityContacts();
     // Reset player move. It already must be handled in update
     player_move_ = Ogre::Vector3::ZERO;
     player_run_ = false;
@@ -503,7 +527,8 @@ void EntityManager::RemoveBattleEntity(const Ogre::String& name){
         ScriptManager::getSingleton().RemoveEntity(ScriptManager::BATTLE, name);
         battle_entity_.erase(it);
         // The entity is not deleted, as its destructor would destroy the model again, like in
-        // ClearBattle.
+        // ClearBattle. So what the model holds (a weapon) has to be destroyed here.
+        entity->ScriptAttachModel("", -1, 0.0f, 0.0f, 0.0f);
         Ogre::Root::getSingleton().getSceneManager("Scene")->destroyEntity(name);
         scene_node_->removeAndDestroyChild("Battle_" + name);
         entity->ReleaseResources();
@@ -578,6 +603,7 @@ void EntityManager::OnResize(){background_2d_.OnResize();}
 void EntityManager::ClearField(){
     ClearEncounterTables();
     entities_hidden_by_battle_.clear();
+    entities_in_contact_.clear();
     walkmesh_.Clear();
     background_2d_.Clear();
     screen_fade_.Clear();
@@ -611,6 +637,9 @@ void EntityManager::ClearBattle(){
         ScriptManager::getSingleton().RemoveEntity(
           ScriptManager::ENTITY, battle_entity_[i]->GetName()
         );
+        // The model held in a bone (a weapon) is another Ogre entity, and the next battle creates
+        // one with the same name.
+        battle_entity_[i]->ScriptAttachModel("", -1, 0.0f, 0.0f, 0.0f);
         Ogre::Root::getSingleton().getSceneManager("Scene")->destroyEntity(
           battle_entity_[i]->GetName()
         );
@@ -827,6 +856,10 @@ void EntityManager::ScriptSetPlayerEntity(const char* name){
             // is left as it is.
             if (player_entity_ != nullptr && background_2d_.GetAutoScrollEntity() == player_entity_)
                 background_2d_.ScriptAutoScrollToEntity(entity_[i]);
+            // The camera follows the player when no script has said anything about it (the fields
+            // without a Director, such as ujunon1, have no opcode that starts it).
+            else if (!background_2d_.HasScrollControl())
+                background_2d_.ScriptAutoScrollToEntity(entity_[i]);
             player_entity_ = entity_[i];
             // Also, make it non-talkable. Visibility and solidity are left to the scripts, as in
             // the original game: some fields use hidden helper entities (like the 'camera') as
@@ -853,7 +886,16 @@ void EntityManager::ScriptPlacePlayerAtFieldEntry(
         ));
         player_entity_->SetRotation(Ogre::Degree(direction));
         player_entity_->SetMoveTriangleId(safe_triangle_id);
+        // In the WALKMESH state the entity walks to its move position: without this one it walks to
+        // whatever it had (the origin of the field), and the player enters the town walking.
+        player_entity_->SetMovePosition(player_entity_->GetPosition());
         player_entity_->SetState(Entity::WALKMESH);
+        // The player starts standing still: no move or run from the world map, and the held keys
+        // don't count until they are released.
+        player_move_ = Ogre::Vector3::ZERO;
+        player_run_ = false;
+        ignore_held_walk_ = true;
+        player_entity_->PlayAnimationContinue(player_entity_->GetDefaultAnimationName());
 }
 
 Entity* EntityManager::ScriptGetPlayerEntity() const{
@@ -881,6 +923,18 @@ void EntityManager::ScriptPlayerLock(const bool lock){
     }
     player_lock_ = lock;
     if (lock == true) player_move_ = Ogre::Vector3::ZERO;
+    // A field with no entity for the leader of the party (the parade of junonr4, where the player
+    // is a soldier that no PC opcode names) gives the control to the entity whose script lets go
+    // of it.
+    else if (player_entity_ == nullptr && IsFieldModule()){
+        const ScriptId script = ScriptManager::getSingleton().GetCurrentScriptId();
+        Entity* entity = GetEntity(script.entity);
+        if (entity != nullptr && !entity->IsLine()){
+            LOG_TRIVIAL("The control goes to '" + script.entity + "', there is no player entity.");
+            ScriptSetPlayerEntity(script.entity.c_str());
+            if (!background_2d_.HasScrollControl()) background_2d_.ScriptAutoScrollToEntity(entity);
+        }
+    }
 }
 
 bool EntityManager::IsPlayerLocked() const{return player_lock_;}
@@ -1026,7 +1080,12 @@ void EntityManager::SetEncounterRate(float rate){
     else encounter_rate_ = rate;
 }
 
+bool EntityManager::IsStartKeyRead() const{
+    return std::chrono::steady_clock::now() - start_key_read_time_ < std::chrono::milliseconds(300);
+}
+
 bool EntityManager::IsKeyOn(unsigned int key_code){
+    if (key_code & 2048) start_key_read_time_ = std::chrono::steady_clock::now();
     // The keys are read even if the player is locked: scenes lock the player and still ask for a
     // button, as the minigames that need to be pressed at the right time do. The scripts that
     // must not read the keys at some point (while a message is open, for example) have their own
@@ -1181,8 +1240,23 @@ bool EntityManager::PerformWalkmeshMove(Entity* entity, const float speed, const
         return false;
     }
     int current_triangle = entity->GetMoveTriangleId();
+    // A character that is not on the walkmesh (Jenova of shpin_3, that is placed outside it and
+    // moves with FMOVE) is walked in a straight line, or the scene that waits for it would never go
+    // on.
+    if (current_triangle == -1 && scripted_move && entity != player_entity_){
+        const float step = std::min(direction.length(), distance_to_target);
+        Ogre::Vector2 move = direction;
+        if (!move.isZeroLength()) move.normalise();
+        move *= step;
+        entity->SetPosition(Ogre::Vector3(start_point.x + move.x, start_point.y + move.y, start_point.z));
+        if (distance_to_target - step <= stop_distance + 0.0001f) entity->UnsetMove();
+        return step > 0.0f;
+    }
     if (current_triangle == -1){
-        LOG_ERROR("Entity '" + entity->GetName() + "' not placed on walkmesh and can't move.");
+        // The entities that a scene places later (the soldiers of the parade of junonr4) are asked
+        // to move before it, and wait. Only the player has to be on the walkmesh.
+        if (entity == player_entity_)
+            LOG_ERROR("Entity '" + entity->GetName() + "' not placed on walkmesh and can't move.");
         return false;
     }
     Ogre::Vector3 rotation(0.0f, 0.0f, 0.0f);
@@ -1444,6 +1518,7 @@ bool EntityManager::WalkmeshBorderCross(
       entity == player_entity_ && !player_lock_, entity->IsScriptedMove()
     );
     Ogre::Vector2 pos = Ogre::Vector2(position.x, position.y);
+    bool searched_other_triangle = false;
     for (;;){
         Ogre::Vector3 A3 = walkmesh_.GetA(current_triangle);
         Ogre::Vector3 B3 = walkmesh_.GetB(current_triangle);
@@ -1470,6 +1545,33 @@ bool EntityManager::WalkmeshBorderCross(
                 continue;
             }
         }
+        // A walk of a script goes on over the edge: it keeps the last triangle, unless the point is
+        // inside another one (the triangles apart from the rest, that scenes use to put a character
+        // higher than the floor, are not joined to it: the character would keep that height after
+        // leaving it).
+        if (free_walk && !searched_other_triangle){
+            searched_other_triangle = true;
+            int other_triangle = -1;
+            float other_distance = 9999.0f;
+            for (int i = 0; i < walkmesh_.GetNumberOfTriangles(); ++ i){
+                if (i == current_triangle) continue;
+                const Ogre::Vector3 a = walkmesh_.GetA(i);
+                const Ogre::Vector3 b = walkmesh_.GetB(i);
+                const Ogre::Vector3 c = walkmesh_.GetC(i);
+                if (!Ogre::Math::pointInTri2D(
+                  pos, Ogre::Vector2(a.x, a.y), Ogre::Vector2(b.x, b.y), Ogre::Vector2(c.x, c.y)
+                )) continue;
+                const float distance = std::abs(position.z - PointElevation(pos, a, b, c));
+                if (distance < other_distance){
+                    other_distance = distance;
+                    other_triangle = i;
+                }
+            }
+            if (other_triangle >= 0){
+                current_triangle = other_triangle;
+                continue;
+            }
+        }
         position.z = PointElevation(pos, A3, B3, C3);
         entity->SetMoveTriangleId(current_triangle);
         // A walk of a script goes on over the edge, keeping the last triangle.
@@ -1639,6 +1741,55 @@ void EntityManager::CheckTriggers(Entity* entity, const Ogre::Vector3& position)
     }
 }
 
+void EntityManager::ScriptSetLine(
+  const char* name, const float x1, const float y1, const float z1, const float x2, const float y2,
+  const float z2
+){
+    for (EntityTrigger* trigger : entity_triggers_){
+        if (trigger->GetName() == name){
+            trigger->SetPoints(Ogre::Vector3(x1, y1, z1), Ogre::Vector3(x2, y2, z2));
+            return;
+        }
+    }
+}
+
+void EntityManager::CheckEntityContacts(){
+    if (IsBattleModule() || !IsFieldModule()) return;
+    if (player_entity_ == nullptr || player_lock_ || !player_entity_->IsSolid()){
+        entities_in_contact_.clear();
+        return;
+    }
+    const Ogre::Vector3 player_position = player_entity_->GetPosition();
+    for (Entity* entity : entity_){
+        if (entity == player_entity_ || entity->IsLine() || !entity->IsSolid()) continue;
+        const Ogre::Vector3 position = entity->GetPosition();
+        const float height = (position.z < player_position.z)
+          ? entity->GetHeight() : player_entity_->GetHeight();
+        const float distance_z = position.z - player_position.z + height;
+        bool touching = false;
+        if (distance_z < height * 2 && distance_z >= 0){
+            const float reach = player_entity_->GetSolidRadius() + entity->GetSolidRadius() + 0.05f;
+            const float dx = position.x - player_position.x;
+            const float dy = position.y - player_position.y;
+            touching = dx * dx + dy * dy < reach * reach;
+        }
+        if (!touching){
+            entities_in_contact_.erase(entity);
+            continue;
+        }
+        if (!entities_in_contact_.insert(entity).second) continue;
+        ScriptEntity* script_entity = ScriptManager::getSingleton().GetScriptEntityByName(
+          ScriptManager::ENTITY, entity->GetName()
+        );
+        // Most entities have no script for it: nothing to say then.
+        if (script_entity != nullptr){
+            ScriptManager::getSingleton().ScriptRequest(
+              script_entity, "script_2", INTERACT_SCRIPT_PRIORITY, "", "", false, false
+            );
+        }
+    }
+}
+
 void EntityManager::CheckEntityInteract(){
     if (IsBattleModule()){
         LOG_WARNING(

+ 46 - 0
src/core/EntityManager.h

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

+ 21 - 3
src/core/EntityModel.cpp

@@ -145,6 +145,20 @@ std::tuple<float, float, float> EntityModel::ScriptGetBonePosition(const int bon
     return std::make_tuple(position.x, position.y, position.z);
 }
 
+std::tuple<float, float, float> EntityModel::ScriptGetBoneEnd(const int bone, const float length){
+    Ogre::SkeletonInstance* skeleton = model_->getSkeleton();
+    const Ogre::String name = "bone" + std::to_string(bone);
+    if (skeleton == nullptr || !skeleton->hasBone(name)) return std::make_tuple(0.0f, 0.0f, 0.0f);
+    // Bring the skeleton to the current frame of the animation.
+    model_->_updateAnimation();
+    Ogre::Bone* node = skeleton->getBone(name);
+    // The bones go along their Y axis, where their children are placed.
+    const Ogre::Vector3 end = node->_getDerivedPosition()
+      + node->_getDerivedOrientation() * (node->_getDerivedScale() * Ogre::Vector3(0, length, 0));
+    const Ogre::Vector3 position = model_->_getParentNodeFullTransform() * end;
+    return std::make_tuple(position.x, position.y, position.z);
+}
+
 bool EntityModel::ScriptAttachModel(
   const char* model, const int bone, const float rx, const float ry, const float rz
 ){
@@ -308,9 +322,13 @@ void EntityModel::PlayAnimation(
         // finishes, so any script waiting for it would wait forever.
         if (animation_current_->getLength() <= 0.0f) animation_current_->setLoop(false);
         animation_current_->setEnabled(true);
-        animation_current_->setTimePosition(
-          (start == -1) ? animation_current_->getLength() : start
-        );
+        // A pose at the very end of the animation (the dead soldiers of shpin_3, that hold the last
+        // frame) is shown as the first frame: past the last key, the interpolation goes on to the
+        // first one, as it does when it loops. The time stays a hair before the end.
+        float time = (start == -1) ? animation_current_->getLength() : start;
+        const float length = animation_current_->getLength();
+        if (length > 0.0f && time >= length) time = std::max(0.0f, length - 0.0005f);
+        animation_current_->setTimePosition(time);
         animation_end_time_ = (end == -1) ? animation_current_->getLength() : end;
         animation_hold_ = (start != -1 && start == end) ? 1.0f / 30.0f : 0.0f;
         animation_state_ = state;

+ 2 - 0
src/core/EntityModel.h

@@ -75,6 +75,8 @@ class EntityModel : public Entity{
 
         virtual std::tuple<float, float, float> ScriptGetBonePosition(const int bone);
 
+        virtual std::tuple<float, float, float> ScriptGetBoneEnd(const int bone, const float length);
+
         virtual bool ScriptAttachModel(
           const char* model, const int bone, const float rx, const float ry, const float rz
         );

+ 8 - 2
src/core/MoviePlayer.cpp

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

+ 23 - 0
src/core/MoviePlayer.h

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

+ 3 - 0
src/core/ScreenFade.cpp

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

+ 19 - 0
src/core/ScriptManager.cpp

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

+ 8 - 1
src/core/ScriptManager.h

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

+ 9 - 0
src/core/ScriptManagerBinds.h

@@ -139,6 +139,7 @@ void ScriptManager::InitBinds(){
       "set_alpha", &Entity::ScriptSetAlpha,
       "set_texture", &Entity::ScriptSetTexture,
       "get_bone_position", &Entity::ScriptGetBonePosition,
+      "get_bone_end", &Entity::ScriptGetBoneEnd,
       "attach_model", sol::overload(
         [](Entity& entity, const char* model, const int bone){
             return entity.ScriptAttachModel(model, bone, 0.0f, 0.0f, 0.0f);
@@ -230,6 +231,8 @@ void ScriptManager::InitBinds(){
       "roll_encounter_battle", &EntityManager::ScriptRollEncounterBattle,
       "is_key_on", &EntityManager::IsKeyOn,
       "is_key_off", &EntityManager::IsKeyOff,
+      "is_start_key_read", &EntityManager::IsStartKeyRead,
+      "set_line", &EntityManager::ScriptSetLine,
       "set_entity_to_character", &EntityManager::SetEntityToCharacter
     );
 
@@ -251,6 +254,7 @@ void ScriptManager::InitBinds(){
       "set_dynamic_mesh", &BattleManager::ScriptSetDynamicMesh,
       "remove_dynamic_mesh", &BattleManager::ScriptRemoveDynamicMesh,
       "get_layout", &BattleManager::ScriptGetLayout,
+      "get_intro_camera", &BattleManager::ScriptGetIntroCamera,
       "get_attack", [](BattleManager& manager, const int id, sol::this_state state) -> sol::object{
           sol::state_view view(state);
           const AttackData* attack = manager.GetAttackData(id);
@@ -383,6 +387,7 @@ void ScriptManager::InitBinds(){
       "get_battle_track_id", &AudioManager::ScriptGetBattleTrack,
       "set_battle_track_id", &AudioManager::ScriptSetBattleTrack,
       "play_music_once", &AudioManager::ScriptPlayMusicOnce,
+      "stop_music", &AudioManager::MusicStop,
       "is_music_playing", &AudioManager::ScriptIsMusicPlaying,
       "set_music_volume", &AudioManager::ScriptSetMusicVolume,
       "set_sound_volume", &AudioManager::ScriptSetSoundVolume
@@ -524,6 +529,7 @@ void ScriptManager::InitBinds(){
       "MoviePlayer",
       "set", &MoviePlayer::ScriptSet,
       "stop", &MoviePlayer::ScriptStop,
+      "use_movie_camera", &MoviePlayer::ScriptUseMovieCamera,
       "get_frame", &MoviePlayer::ScriptGetFrame,
       "is_playing", &MoviePlayer::ScriptIsPlaying
     );
@@ -558,6 +564,7 @@ void ScriptManager::InitBinds(){
       "Dialog",
       "dialog_open", &DialogsManager::OpenDialog,
       "set_numeric", &DialogsManager::SetNumeric,
+      "set_number", &DialogsManager::SetNumber,
       "update_timer", &DialogsManager::UpdateTimer,
       "set_mode", &DialogsManager::SetMode,
       "dialog_set_text", &DialogsManager::SetText,
@@ -657,6 +664,8 @@ void ScriptManager::InitBinds(){
       "unboard_vehicle", &VGears::WorldmapModule::UnboardVehicle,
       "set_encounters_locked", &VGears::WorldmapModule::SetEncountersLocked,
       "set_model_orientation", &VGears::WorldmapModule::SetModelOrientation,
+      "set_model_heading", &VGears::WorldmapModule::SetModelHeading,
+      "get_model_heading", &VGears::WorldmapModule::GetModelHeading,
       "set_model_offset", &VGears::WorldmapModule::SetModelOffset,
       "set_entity_altitude", &VGears::WorldmapModule::SetEntityAltitude,
       "enter", &VGears::WorldmapModule::Enter,

+ 5 - 0
src/core/UiManager.cpp

@@ -19,6 +19,7 @@
 #include <iostream>
 #include <cctype>
 #include <algorithm>
+#include "core/DebugDraw.h"
 #include "core/Logger.h"
 #include "core/ScriptManager.h"
 #include "core/UiManager.h"
@@ -36,9 +37,12 @@ template<>UiManager *Ogre::Singleton<UiManager>::msSingleton = nullptr;
 
 UiManager::UiManager(){
     Ogre::Root::getSingleton().getSceneManager("Scene")->addRenderQueueListener(this);
+    // The console is drawn after the widgets, so it is over them.
+    if (DebugDraw::getSingletonPtr() != nullptr) DebugDraw::getSingleton().SetOverlayDrawnByUi(true);
 }
 
 UiManager::~UiManager(){
+    if (DebugDraw::getSingletonPtr() != nullptr) DebugDraw::getSingleton().SetOverlayDrawnByUi(false);
     Ogre::Root::getSingleton().getSceneManager("Scene")->removeRenderQueueListener(this);
     for (size_t i = 0; i < fonts_.size(); ++ i) delete fonts_[i];
     for (size_t i = 0; i < widgets_.size(); ++ i) delete widgets_[i];
@@ -160,6 +164,7 @@ void UiManager::renderQueueEnded(
     if (queueGroupId == Ogre::RENDER_QUEUE_OVERLAY){
         Ogre::Root::getSingletonPtr()->getRenderSystem()->clearFrameBuffer(Ogre::FBT_DEPTH);
         for (unsigned int i = 0; i < widgets_.size(); ++ i) widgets_[i]->Render();
+        if (DebugDraw::getSingletonPtr() != nullptr) DebugDraw::getSingleton().RenderOverlay();
     }
 }
 

+ 37 - 4
src/core/UiTextArea.cpp

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

+ 22 - 1
src/core/UiTextArea.h

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

+ 5 - 1
src/core/XmlBackground2DFile.cpp

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

+ 9 - 0
src/core/XmlEnemyFile.cpp

@@ -50,6 +50,15 @@ void XmlEnemyFile::LoadEnemy(Enemy& enemy){
                 else if (GetString(node_stat, "id") == "spd") enemy.SetDex(value);
                 else if (GetString(node_stat, "id") == "lck") enemy.SetLck(value);
                 else if (GetString(node_stat, "id") == "eva") enemy.SetEva(value);
+                // The maximum goes first, the current value is capped to it.
+                else if (GetString(node_stat, "id") == "hp"){
+                    enemy.SetHpMax(value);
+                    enemy.SetHp(value);
+                }
+                else if (GetString(node_stat, "id") == "mp"){
+                    enemy.SetMpMax(value);
+                    enemy.SetMp(value);
+                }
                 node_stat = node_stat->NextSibling();
             }
         }

+ 4 - 3
src/core/XmlFormationFile.cpp

@@ -55,15 +55,16 @@ void XmlFormationFile::LoadFormation(){
         }
         else if (node->Type() == TiXmlNode::TINYXML_ELEMENT && node->ValueStr() == "camera"){
             BattleManager::getSingleton().SetInitialCamera(GetInt(node, "initial"));
+            BattleManager::getSingleton().SetIntroCamera(GetInt(node, "intro", -1));
             TiXmlNode* camera_node = node->FirstChild();
             while (camera_node != nullptr){
                 int id = GetInt(camera_node, "id");
                 Ogre::Vector3 pos = Ogre::Vector3(
-                  GetInt(camera_node, "x"), GetInt(camera_node, "y"), GetInt(camera_node, "z")
+                  GetFloat(camera_node, "x"), GetFloat(camera_node, "y"), GetFloat(camera_node, "z")
                 );
                 Ogre::Vector3 dir = Ogre::Vector3(
-                  GetInt(camera_node, "direction_x"), GetInt(camera_node, "direction_y"),
-                  GetInt(camera_node, "direction_z")
+                  GetFloat(camera_node, "direction_x"), GetFloat(camera_node, "direction_y"),
+                  GetFloat(camera_node, "direction_z")
                 );
                 BattleManager::getSingleton().AddCamera(id, pos, dir);
                 camera_node = camera_node->NextSibling();

+ 90 - 1
src/installer/BattleCameraScripts.h

@@ -26,6 +26,7 @@
 #include <ostream>
 #include <string>
 #include <vector>
+#include "ExeEffectCameras.h"
 
 /**
  * Reads the camera scripts of the battles (camdat0.bin, camdat1.bin and camdat2.bin of data/battle).
@@ -40,6 +41,9 @@
  * operands (bytes and 16 bit values). The lengths of the operands for each opcode of the two kinds
  * of scripts were found in the interpreter of ff7.exe (0x5c2341 for the position, 0x5c3f45 for the
  * point it looks at). A script ends with 0xff, or with 0xfe followed by 0xc0 (loop).
+ *
+ * The third pointer is the list of the scripts of the camera of the victory (the camera id -3 in the
+ * game): three for the position, one for each variant, and then three for the point it looks at.
  */
 namespace BattleCameraScripts{
 
@@ -50,6 +54,8 @@ namespace BattleCameraScripts{
     struct Set{
         std::vector<uint32_t> position;
         std::vector<uint32_t> look;
+        std::vector<uint32_t> victory_position;
+        std::vector<uint32_t> victory_look;
         std::map<uint32_t, std::vector<uint8_t>> scripts;
     };
 
@@ -183,9 +189,86 @@ namespace BattleCameraScripts{
                 list.back() = key;
             }
         }
+        const uint32_t victory = ReadU32(d, 8) - base;
+        if (victory >= d.size()) return false;
+        for (int i = 0; i < 6; ++ i){
+            const bool position = i < 3;
+            const uint32_t offset = ReadU32(d, victory + 4 * i) - base;
+            std::vector<uint8_t> script;
+            if (offset >= d.size() || !ReadScript(d, offset, position, script)) return false;
+            const uint32_t key = offset * 2 + (position ? 0 : 1);
+            set.scripts[key] = script;
+            (position ? set.victory_position : set.victory_look).push_back(key);
+        }
         return true;
     }
 
+    /**
+     * Reads the scripts of the cameras of the start of the battles (the camera id -2 in the game) from
+     * ff7.exe. There are two lists of pointers, one for the position and one for the point it looks
+     * at, indexed by the camera byte of the formation (read at 0x5c2406 and 0x5c400a in the 1998
+     * build). An entry that isn't a script has the key 0.
+     *
+     * @return False if the file couldn't be read or the scripts aren't there.
+     */
+    inline bool ReadIntro(const std::string& path, Set& set){
+        set = Set();
+        ExeEffectCameras::Image image;
+        if (!ExeEffectCameras::LoadImage(path, image)) return false;
+        const uint32_t tables[2] = {0x8f70d0, 0x8f7270};
+        const size_t count = (tables[1] - tables[0]) / 4;
+        size_t valid = 0;
+        for (int kind = 0; kind < 2; ++ kind){
+            const bool position = kind == 0;
+            std::vector<uint32_t>& list = position ? set.position : set.look;
+            const int64_t table = ExeEffectCameras::FileOffset(image.sections, tables[kind]);
+            if (table < 0) return false;
+            for (size_t i = 0; i < count; ++ i){
+                list.push_back(0);
+                const uint32_t address = ReadU32(image.data, table + 4 * i);
+                const int64_t offset = ExeEffectCameras::FileOffset(image.sections, address);
+                std::vector<uint8_t> script;
+                // They start with an opcode, and none is long.
+                if (offset < 0 || image.data[offset] < 0xd5
+                  || !ReadScript(image.data, static_cast<uint32_t>(offset), position, script)
+                  || script.size() > 512) continue;
+                const uint32_t key = static_cast<uint32_t>(offset) * 2 + (position ? 0 : 1);
+                set.scripts[key] = script;
+                list.back() = key;
+                ++ valid;
+            }
+        }
+        // Another version of the executable has other things there.
+        return valid >= count;
+    }
+
+    /**
+     * Writes the cameras of the start of the battles, after {@see WriteLua}. Game.BattleCameras.intro
+     * has the lists "position" and "look" (index = camera of the formation + 1) and the scripts.
+     */
+    inline void WriteIntroLua(std::ostream& out, const Set& set){
+        const std::string name = "Game.BattleCameras.intro";
+        out << "-- Cameras of the start of the battles, read from ff7.exe.\n"
+            << name << " = {position = {}, look = {}, scripts = {}}\n";
+        for (int kind = 0; kind < 2; ++ kind){
+            const std::vector<uint32_t>& list = kind == 0 ? set.position : set.look;
+            out << name << "." << (kind == 0 ? "position" : "look") << " = {";
+            for (size_t i = 0; i < list.size(); ++ i){
+                if (i % 16 == 0) out << "\n    ";
+                out << list[i] << ", ";
+            }
+            out << "\n}\n";
+        }
+        for (const auto& script : set.scripts){
+            out << name << ".scripts[" << script.first << "] = {";
+            for (size_t i = 0; i < script.second.size(); ++ i){
+                if (i % 24 == 0) out << "\n    ";
+                out << static_cast<int>(script.second[i]) << ", ";
+            }
+            out << "\n}\n";
+        }
+    }
+
     /**
      * Writes the sets to a Lua file. Game.BattleCameras[file] has the list "position" and "look"
      * (index = camera id * 3 + variant + 1, the value is the name of a script), and the table
@@ -195,7 +278,8 @@ namespace BattleCameraScripts{
         out << "-- Camera scripts of the battles, read from camdat0.bin, camdat1.bin and camdat2.bin.\n"
             << "-- Game.BattleCameras[file].position[camera id * 3 + variant + 1] is the name of a script in\n"
             << "-- Game.BattleCameras[file].scripts (the bytes of the script), the same for .look (the point\n"
-            << "-- the camera looks at). See scripts/battle/battle_camera.lua for the format.\n"
+            << "-- the camera looks at). .victory_position[variant + 1] and .victory_look are the ones of the\n"
+            << "-- camera of the victory. See scripts/battle/battle_camera.lua for the format.\n"
             << "Game.BattleCameras = Game.BattleCameras or {}\n";
         for (const auto& item : sets){
             const Set& set = item.second;
@@ -210,6 +294,11 @@ namespace BattleCameraScripts{
                 }
                 out << "\n}\n";
             }
+            for (int kind = 0; kind < 2; ++ kind){
+                out << name << "." << (kind == 0 ? "victory_position" : "victory_look") << " = {";
+                for (const uint32_t key : kind == 0 ? set.victory_position : set.victory_look) out << key << ", ";
+                out << "}\n";
+            }
             for (const auto& script : set.scripts){
                 out << name << ".scripts[" << script.first << "] = {";
                 for (size_t i = 0; i < script.second.size(); ++ i){

+ 81 - 7
src/installer/BattleDataInstaller.cpp

@@ -23,6 +23,7 @@
 #include <set>
 #include <cctype>
 #include <cstdio>
+#include <cstring>
 #include <cstdlib>
 #include <algorithm>
 #include <zlib.h>
@@ -593,6 +594,13 @@ unsigned int BattleDataInstaller::ConvertBattleModel(){
             // ones (enemies and the rest of the models with scripts) have 32.
             AbFile ab(File(output_dir_ + "temp/battle_models/" + model.script), !info.is_player);
             ab.GenerateScripts(model.id + "_" + info.name_normal, data_dir_ + "scripts/battle_models/");
+            if (!info.is_scene && "" != model.hrc){
+                WriteModelCamera(
+                  File(output_dir_ + "temp/battle_models/" + model.script),
+                  File(output_dir_ + "temp/battle_models/" + model.hrc + "bin"),
+                  model.id + "_" + info.name_normal
+                );
+            }
         }
 
         // Playable characters hold their weapons in battle (but Red XIII, who has none). Each one is a
@@ -901,6 +909,13 @@ void BattleDataInstaller::WriteBattleCameras(){
     }
     std::ofstream file(data_dir_ + "gamedata/battle_cameras.lua");
     BattleCameraScripts::WriteLua(file, sets);
+    // The ones of the start of the battles are in the executable.
+    BattleCameraScripts::Set intro;
+    auto exe_path = const_cast<DiskImage&>(disk_image_).filePath("ff7.exe");
+    if (exe_path != nullptr && BattleCameraScripts::ReadIntro(*exe_path, intro)){
+        BattleCameraScripts::WriteIntroLua(file, intro);
+    }
+    else std::cerr << "[WARNING] Can't read the cameras of the start of the battles from ff7.exe." << std::endl;
 }
 
 void BattleDataInstaller::WriteEffectMeshes(){
@@ -1091,6 +1106,14 @@ void BattleDataInstaller::WriteEnemies(){
         stat_eva->SetAttribute("id", "eva");
         stat_eva->SetAttribute("value", enemy.eva);
         stats->LinkEndChild(stat_eva.release());
+        std::unique_ptr<TiXmlElement> stat_hp(new TiXmlElement("stat"));
+        stat_hp->SetAttribute("id", "hp");
+        stat_hp->SetAttribute("value", enemy.hp);
+        stats->LinkEndChild(stat_hp.release());
+        std::unique_ptr<TiXmlElement> stat_mp(new TiXmlElement("stat"));
+        stat_mp->SetAttribute("id", "mp");
+        stat_mp->SetAttribute("value", enemy.mp);
+        stats->LinkEndChild(stat_mp.release());
         container->LinkEndChild(stats.release());
         std::unique_ptr<TiXmlElement> elements(new TiXmlElement("elements"));
         for (Enemy::Element element : enemy.elements){
@@ -1375,16 +1398,17 @@ void BattleDataInstaller::WriteFormations(){
         container->LinkEndChild(enemies.release());
         std::unique_ptr<TiXmlElement> cameras(new TiXmlElement("camera"));
         cameras->SetAttribute("initial", formation.initial_camera_position);
+        cameras->SetAttribute("intro", formation.intro_camera);
         int c = 0;
         for (Formation::Camera camera : formation.camera_positions){
             std::unique_ptr<TiXmlElement> camera_xml(new TiXmlElement("position"));
             camera_xml->SetAttribute("id", c);
-            camera_xml->SetAttribute("x", camera.x);
-            camera_xml->SetAttribute("y", camera.y);
-            camera_xml->SetAttribute("z", camera.z);
-            camera_xml->SetAttribute("direction_x", camera.d_x);
-            camera_xml->SetAttribute("direction_y", camera.d_y);
-            camera_xml->SetAttribute("direction_z", camera.d_z);
+            camera_xml->SetDoubleAttribute("x", camera.x);
+            camera_xml->SetDoubleAttribute("y", camera.y);
+            camera_xml->SetDoubleAttribute("z", camera.z);
+            camera_xml->SetDoubleAttribute("direction_x", camera.d_x);
+            camera_xml->SetDoubleAttribute("direction_y", camera.d_y);
+            camera_xml->SetDoubleAttribute("direction_z", camera.d_z);
             cameras->LinkEndChild(camera_xml.release());
             c ++;
         }
@@ -1622,6 +1646,54 @@ void BattleDataInstaller::GenerateRsdFiles(SpellModel model, std::string path){
     }
 }
 
+void BattleDataInstaller::WriteModelCamera(
+  File script, File skeleton, const std::string& model_name
+){
+    // The scripts of a model start with a header of 0x68 bytes, that ff7.exe copies to the data the
+    // cameras use (0x42b6a0): 16 points of the model at 0x12, the factors of the size at 0x44, two
+    // views of the model (a camera position and a point to look at) at 0x4C and the height of the point
+    // the camera looks at, at 0x64.
+    if (script.GetFileSize() < 0x68 || skeleton.GetFileSize() < 16) return;
+    skeleton.SetOffset(12);
+    const unsigned int bones = skeleton.readU32LE();
+    if (bones == 0 || skeleton.GetFileSize() < 16 + bones * 12) return;
+    std::ofstream file(data_dir_ + "scripts/battle_models/" + model_name + "_camera.lua");
+    if (!file) return;
+    file << "-- Data of the model for the cameras of the battles. A point is the end of the bone with the\n"
+      << "-- number of the point minus one (0 is the root).\n"
+      << "BattleModelCameras = BattleModelCameras or {}\n"
+      << "BattleModelCameras[\"" << model_name << "\"] = {\n    points = {";
+    script.SetOffset(0x12);
+    for (int i = 0; i < 16; i ++) file << static_cast<int>(script.readU8()) << ", ";
+    file << "},\n    size = {";
+    script.SetOffset(0x44);
+    for (int i = 0; i < 3; i ++) file << static_cast<int>(static_cast<int16_t>(script.readU16LE())) << ", ";
+    // The two views, one after the other.
+    script.SetOffset(0x4C);
+    file << "},\n    views = {";
+    for (int v = 0; v < 2; v ++){
+        for (int p = 0; p < 2; p ++){
+            file << (p == 0 ? "{pos = {" : "look = {");
+            for (int i = 0; i < 3; i ++) file << static_cast<int>(static_cast<int16_t>(script.readU16LE())) << ", ";
+            file << (p == 0 ? "}, " : "}}, ");
+        }
+    }
+    script.SetOffset(0x64);
+    file << "},\n    look_height = " << static_cast<int>(static_cast<int16_t>(script.readU16LE()))
+      << ",\n    lengths = {";
+    // The bones are the last data of the skeleton: parent, length (negative) and polygons.
+    skeleton.SetOffset(skeleton.GetFileSize() - bones * 12);
+    for (unsigned int b = 0; b < bones; b ++){
+        skeleton.readU32LE();
+        const u32 raw = skeleton.readU32LE();
+        float length = 0.0f;
+        std::memcpy(&length, &raw, sizeof(length));
+        skeleton.readU32LE();
+        file << "[" << b << "] = " << -length << ", ";
+    }
+    file << "},\n}\n";
+}
+
 void BattleDataInstaller::DecompileBattleModelHrc(
   File compiled, BattleModel model, std::string path, std::string skeleton_name
 ){
@@ -1723,7 +1795,9 @@ void BattleDataInstaller::DecompileSceneModelHrc(
         decompiled += "bone" + std::to_string(b) + "\n";
         if (b == 0) decompiled += "root\n";
         else decompiled += ("bone" + std::to_string(b - 1) + "\n");
-        decompiled += "100.000000\n";
+        // The pieces share the coordinates of the scene. A length would move each one along the depth, away
+        // from the previous one.
+        decompiled += "0.000000\n";
         decompiled += "1 " + model.p[b].substr(0, 4) + "\n\n";
     }
     std::ofstream out(path);

+ 9 - 0
src/installer/BattleDataInstaller.h

@@ -417,6 +417,15 @@ class BattleDataInstaller{
          */
         void GenerateRsdFiles(SpellModel model, std::string path);
 
+        /**
+         * Writes the data of a model that the cameras of the battles use, as a Lua script.
+         *
+         * @param[in] script The file with the animation scripts of the model.
+         * @param[in] skeleton The skeleton of the model.
+         * @param[in] model_name Name of the model, like rt_cloud.
+         */
+        void WriteModelCamera(File script, File skeleton, const std::string& model_name);
+
         /**
          * Decompiles a compiled HRC file.
          *

+ 6 - 0
src/installer/DataInstaller.cpp

@@ -229,6 +229,7 @@ float DataInstaller::Progress(){
             }
             write_output_line_("Parsing item and materia prices...", 2, true);
             kernel_installer_->ReadPrices();
+            kernel_installer_->WriteShops(data_dir_ + "gamedata/shops.lua");
             installation_state_ = KERNEL_COMMANDS;
             return CalcProgress();
         case KERNEL_COMMANDS:
@@ -300,6 +301,11 @@ float DataInstaller::Progress(){
         case KERNEL_SAVEMAP:
             write_output_line_("Extracting the initial savemap...", 2, true);
             kernel_installer_->ReadInitialSaveMap();
+            {
+                auto exe_path = disk_image_.filePath("ff7.exe");
+                if (exe_path) kernel_installer_->ReadRecruitRecords(*exe_path);
+                else write_output_line_("ff7.exe not found, Cait Sith and Vincent won't have their data.", 2, true);
+            }
             kernel_installer_->WriteInitialSaveMap(data_dir_ + "gamedata/initial_savemap.lua");
             installation_state_ = MEDIA_IMAGES;
             return CalcProgress();

+ 3 - 2
src/installer/FieldDataInstaller.cpp

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

+ 12 - 2
src/installer/FieldTextWriter.cpp

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

+ 268 - 190
src/installer/KernelDataInstaller.cpp

@@ -15,6 +15,8 @@
 
 
 #include <tinyxml.h>
+#include <algorithm>
+#include <iterator>
 #include <fstream>
 #include <iostream>
 #include <memory>
@@ -39,6 +41,34 @@ void KernelDataInstaller::ReadPrices(){
     for (int i = 320; i < 416; i ++) prices_[i] = exe_file.readU32LE();
 }
 
+void KernelDataInstaller::WriteShops(std::string file_name){
+    // Shop inventories are a table of 80 records of 84 bytes in ff7.exe: u16 type, u16 number of
+    // entries, and 10 entries of u32 kind (0: item, weapon, armor or accessory; 1: materia) and u32
+    // index (the index of the item as in the prices table, or the ID of the materia).
+    const int SHOP_TABLE_OFFSET = 0x00512AD8;
+    const int SHOP_COUNT = 80;
+    std::fstream file;
+    file.open(file_name, std::ios::out);
+    if (!file) return;
+    File exe_file(exe_path_);
+    file << "-- Inventory of each shop. Prices are the ones of the items and the materia.\n"
+      << "-- type: kind of shop (1: weapons, 2: items, 3: materia...). Entries are {materia, id}.\n"
+      << "Game.Shops = {}\n";
+    for (int s = 0; s < SHOP_COUNT; s ++){
+        exe_file.SetOffset(SHOP_TABLE_OFFSET + s * 84);
+        u16 type = exe_file.readU16LE();
+        u16 count = exe_file.readU16LE();
+        file << "Game.Shops[" << s << "] = {\n    type = " << type << ",\n    items = {";
+        for (int i = 0; i < 10; i ++){
+            u32 kind = exe_file.readU32LE();
+            u32 index = exe_file.readU32LE();
+            if (i >= count) continue;
+            file << "\n        {" << (kind == 1 ? "true" : "false") << ", " << index << "},";
+        }
+        file << "\n    }\n}\n";
+    }
+}
+
 int KernelDataInstaller::ReadCommands(){
 
     // Empty the command list
@@ -494,6 +524,8 @@ void KernelDataInstaller::WriteCharacters(std::string file_name){
           << "        mp = " << static_cast<int>(character.curve_mp) << ",\n"
           << "        exp = " << static_cast<int>(character.curve_exp) << ",\n"
           << "    },\n"
+          << "    limit_divisors = {" << character.limit_1_div << ", " << character.limit_2_div << ", "
+          << character.limit_3_div << ", " << character.limit_4_div << "},\n"
           << "    limits = {\n"
           << "        [1] = {\n"
           << "            kills = 0,\n"
@@ -591,7 +623,7 @@ void KernelDataInstaller::ReadGrowth(){
         else growth_.curves[i].type = CURVE_EXP;
         for (int j = 0; j < 8; j ++){
             growth_.curves[i].gradient[j] = growth_file.readU8();
-            growth_.curves[i].base[j] = growth_file.readU8();
+            growth_.curves[i].base[j] = static_cast<s8>(growth_file.readU8());
         }
     }
 }
@@ -611,7 +643,7 @@ void KernelDataInstaller::WriteGrowth(std::string file_name){
         file << "Game.Growth.curves[" << i << "] = {\n";
         for (int j = 0; j < 8; j ++){
             file << "    [" << j << "] = {gradient = " << static_cast<int>(growth_.curves[i].gradient[j])
-              << ", base = " << static_cast<int>(growth_.curves[i].gradient[j]) << "},\n";
+              << ", base = " << static_cast<int>(growth_.curves[i].base[j]) << "},\n";
         }
         file << "}\n";
     }
@@ -1400,10 +1432,10 @@ void KernelDataInstaller::WriteAccessories(std::string file_name){
     file.open(file_name, std::ios::out);
     if (!file) return;
     for (AccessoryData accessory : accessories_){
-        file << "Game.Items[" << accessory.id + 287 << "] = {\n"
+        file << "Game.Items[" << accessory.id + 288 << "] = {\n"
           << "    type = Inventory.ITEM_TYPE.ACCESSORY,\n"
-          << "    id = " << accessory.id + 287 << ",\n"
-          << "    price = " << prices_[accessory.id + 287] << ",\n"
+          << "    id = " << accessory.id + 288 << ",\n"
+          << "    price = " << prices_[accessory.id + 288] << ",\n"
           << "    name = \"" << accessory.name << "\",\n"
           << "    description = \"" << accessory.description << "\",\n"
           << "    sell = " << accessory.sellable << ",\n"
@@ -2077,100 +2109,131 @@ void KernelDataInstaller::ReadInitialSaveMap(){
     savemap_file.WriteFile("/home/ivalentin/initialsavemap");
     // The initial savemap in KERNEL.BIN startas at 0x0054, directly into Cloud's level.
     // It skips the header (PC and PSX, checksum, preview data and window colour).
-    for (int i = 0; i < 9; i ++){
-        savemap_.characters[i].identifier = savemap_file.readU8();
-        savemap_.characters[i].level = savemap_file.readU8();
-        savemap_.characters[i].str = savemap_file.readU8();
-        savemap_.characters[i].vit = savemap_file.readU8();
-        savemap_.characters[i].mag = savemap_file.readU8();
-        savemap_.characters[i].spr = savemap_file.readU8();
-        savemap_.characters[i].dex = savemap_file.readU8();
-        savemap_.characters[i].lck = savemap_file.readU8();
-        savemap_.characters[i].str_bonus = savemap_file.readU8();
-        savemap_.characters[i].vit_bonus = savemap_file.readU8();
-        savemap_.characters[i].mag_bonus = savemap_file.readU8();
-        savemap_.characters[i].spr_bonus = savemap_file.readU8();
-        savemap_.characters[i].dex_bonus = savemap_file.readU8();
-        savemap_.characters[i].lck_bonus = savemap_file.readU8();
-        savemap_.characters[i].limit_level = savemap_file.readU8();
-        savemap_.characters[i].limit_bar = savemap_file.readU8();
-        bool name_end = false;
-        savemap_.characters[i].name = "";
-        for (int j = 0; j < 12; j ++){
-            savemap_.characters[i].name_raw[i] = savemap_file.readU8();
-            if (name_end == false){
-                if (savemap_.characters[i].name_raw[i] != 0XFF){
-                    savemap_.characters[i].name += ENGLISH_CHARS[savemap_.characters[i].name_raw[i]];
-                }
-                else name_end = true;
+    for (int i = 0; i < 9; i ++) ReadSaveMapCharacter(savemap_file, savemap_.characters[i]);
+    // The initial savemap ends up after character data, end now.
+}
+
+void KernelDataInstaller::ReadSaveMapCharacter(File& savemap_file, SaveMap::Character& character){
+    character.identifier = savemap_file.readU8();
+    character.level = savemap_file.readU8();
+    character.str = savemap_file.readU8();
+    character.vit = savemap_file.readU8();
+    character.mag = savemap_file.readU8();
+    character.spr = savemap_file.readU8();
+    character.dex = savemap_file.readU8();
+    character.lck = savemap_file.readU8();
+    character.str_bonus = savemap_file.readU8();
+    character.vit_bonus = savemap_file.readU8();
+    character.mag_bonus = savemap_file.readU8();
+    character.spr_bonus = savemap_file.readU8();
+    character.dex_bonus = savemap_file.readU8();
+    character.lck_bonus = savemap_file.readU8();
+    character.limit_level = savemap_file.readU8();
+    character.limit_bar = savemap_file.readU8();
+    bool name_end = false;
+    character.name = "";
+    for (int j = 0; j < 12; j ++){
+        character.name_raw[j] = savemap_file.readU8();
+        if (name_end == false){
+            if (character.name_raw[j] != 0XFF){
+                character.name += ENGLISH_CHARS[character.name_raw[j]];
             }
+            else name_end = true;
         }
-        savemap_.characters[i].weapon = savemap_file.readU8();
-        savemap_.characters[i].armor = savemap_file.readU8();
-        savemap_.characters[i].accessory = savemap_file.readU8();
-        savemap_.characters[i].status_raw = savemap_file.readU8();
-        if (savemap_.characters[i].status_raw == (savemap_.characters[i].status_raw | 0x10)){
-            savemap_.characters[i].sadness = true;
-            savemap_.characters[i].fury = false;
-        }
-        else if (savemap_.characters[i].status_raw == (savemap_.characters[i].status_raw | 0x20)){
-            savemap_.characters[i].sadness = false;
-            savemap_.characters[i].fury = true;
-        }
-        else{
-            savemap_.characters[i].sadness = false;
-            savemap_.characters[i].fury = false;
-        }
-        savemap_.characters[i].row_raw = savemap_file.readU8();
-        if (savemap_.characters[i].row_raw == 0xFE) savemap_.characters[i].back_row = true;
-        else savemap_.characters[i].back_row = false;
-        savemap_.characters[i].level_progress = savemap_file.readU8();
-        savemap_.characters[i].learned_limits_raw = savemap_file.readU16LE();
-        for (int j = 0; j < 4; j ++){
-            savemap_.characters[i].limits_learned[j][0] = false;
-            savemap_.characters[i].limits_learned[j][1] = false;
-        }
-        if (savemap_.characters[i].learned_limits_raw == (savemap_.characters[i].learned_limits_raw | 0x0001))
-            savemap_.characters[i].limits_learned[0][0] = true;
-        if (savemap_.characters[i].learned_limits_raw == (savemap_.characters[i].learned_limits_raw | 0x0002))
-            savemap_.characters[i].limits_learned[0][1] = true;
-        if (savemap_.characters[i].learned_limits_raw == (savemap_.characters[i].learned_limits_raw | 0x0008))
-            savemap_.characters[i].limits_learned[1][0] = true;
-        if (savemap_.characters[i].learned_limits_raw == (savemap_.characters[i].learned_limits_raw | 0x0010))
-            savemap_.characters[i].limits_learned[1][1] = true;
-        if (savemap_.characters[i].learned_limits_raw == (savemap_.characters[i].learned_limits_raw | 0x0040))
-            savemap_.characters[i].limits_learned[2][0] = true;
-        if (savemap_.characters[i].learned_limits_raw == (savemap_.characters[i].learned_limits_raw | 0x0080))
-            savemap_.characters[i].limits_learned[2][1] = true;
-        if (savemap_.characters[i].learned_limits_raw == (savemap_.characters[i].learned_limits_raw | 0x0200))
-            savemap_.characters[i].limits_learned[3][0] = true;
-        savemap_.characters[i].kills = savemap_file.readU16LE();
-        savemap_.characters[i].limit_uses[0] = savemap_file.readU16LE();
-        savemap_.characters[i].limit_uses[1] = savemap_file.readU16LE();
-        savemap_.characters[i].limit_uses[2] = savemap_file.readU16LE();
-        savemap_.characters[i].hp = savemap_file.readU16LE();
-        savemap_.characters[i].base_hp = savemap_file.readU16LE();
-        savemap_.characters[i].mp = savemap_file.readU16LE();
-        savemap_.characters[i].base_mp = savemap_file.readU16LE();
-        savemap_.characters[i].unknown = savemap_file.readU32LE();
-        savemap_.characters[i].max_hp = savemap_file.readU16LE();
-        savemap_.characters[i].max_mp = savemap_file.readU16LE();
-        savemap_.characters[i].exp = savemap_file.readU32LE();
-        for (int m = 0; m < 8; m ++){
-            savemap_.characters[i].weapon_materia[m].id = savemap_file.readU8();
-            // TODO: Identify Enemy Skill, do special treatment
-            savemap_.characters[i].weapon_materia[m].ap // WARNING: AP has only three bytes.
-              = savemap_file.readU8() + (savemap_file.readU8() << 8) + (savemap_file.readU8() << 16);
-        }
-        for (int m = 0; m < 8; m ++){
-            savemap_.characters[i].armor_materia[m].id = savemap_file.readU8();
-            // TODO: Identify Enemy Skill, do special treatment
-            savemap_.characters[i].armor_materia[m].ap // WARNING: AP has only three bytes.
-              = savemap_file.readU8() + (savemap_file.readU8() << 8) + (savemap_file.readU8() << 16);
+    }
+    character.weapon = savemap_file.readU8();
+    character.armor = savemap_file.readU8();
+    character.accessory = savemap_file.readU8();
+    character.status_raw = savemap_file.readU8();
+    if (character.status_raw == (character.status_raw | 0x10)){
+        character.sadness = true;
+        character.fury = false;
+    }
+    else if (character.status_raw == (character.status_raw | 0x20)){
+        character.sadness = false;
+        character.fury = true;
+    }
+    else{
+        character.sadness = false;
+        character.fury = false;
+    }
+    character.row_raw = savemap_file.readU8();
+    if (character.row_raw == 0xFE) character.back_row = true;
+    else character.back_row = false;
+    character.level_progress = savemap_file.readU8();
+    character.learned_limits_raw = savemap_file.readU16LE();
+    for (int j = 0; j < 4; j ++){
+        character.limits_learned[j][0] = false;
+        character.limits_learned[j][1] = false;
+    }
+    if (character.learned_limits_raw == (character.learned_limits_raw | 0x0001))
+        character.limits_learned[0][0] = true;
+    if (character.learned_limits_raw == (character.learned_limits_raw | 0x0002))
+        character.limits_learned[0][1] = true;
+    if (character.learned_limits_raw == (character.learned_limits_raw | 0x0008))
+        character.limits_learned[1][0] = true;
+    if (character.learned_limits_raw == (character.learned_limits_raw | 0x0010))
+        character.limits_learned[1][1] = true;
+    if (character.learned_limits_raw == (character.learned_limits_raw | 0x0040))
+        character.limits_learned[2][0] = true;
+    if (character.learned_limits_raw == (character.learned_limits_raw | 0x0080))
+        character.limits_learned[2][1] = true;
+    if (character.learned_limits_raw == (character.learned_limits_raw | 0x0200))
+        character.limits_learned[3][0] = true;
+    character.kills = savemap_file.readU16LE();
+    character.limit_uses[0] = savemap_file.readU16LE();
+    character.limit_uses[1] = savemap_file.readU16LE();
+    character.limit_uses[2] = savemap_file.readU16LE();
+    character.hp = savemap_file.readU16LE();
+    character.base_hp = savemap_file.readU16LE();
+    character.mp = savemap_file.readU16LE();
+    character.base_mp = savemap_file.readU16LE();
+    character.unknown = savemap_file.readU32LE();
+    character.max_hp = savemap_file.readU16LE();
+    character.max_mp = savemap_file.readU16LE();
+    character.exp = savemap_file.readU32LE();
+    for (int m = 0; m < 8; m ++){
+        character.weapon_materia[m].id = savemap_file.readU8();
+        // TODO: Identify Enemy Skill, do special treatment
+        character.weapon_materia[m].ap // WARNING: AP has only three bytes.
+          = savemap_file.readU8() + (savemap_file.readU8() << 8) + (savemap_file.readU8() << 16);
+    }
+    for (int m = 0; m < 8; m ++){
+        character.armor_materia[m].id = savemap_file.readU8();
+        // TODO: Identify Enemy Skill, do special treatment
+        character.armor_materia[m].ap // WARNING: AP has only three bytes.
+          = savemap_file.readU8() + (savemap_file.readU8() << 8) + (savemap_file.readU8() << 16);
+    }
+    character.exp_to_next = savemap_file.readU32LE();
+}
+
+void KernelDataInstaller::ReadRecruitRecords(const std::string& exe_path){
+    recruit_records_found_ = false;
+    std::ifstream exe(exe_path, std::ios::binary);
+    const std::vector<u8> data(
+      (std::istreambuf_iterator<char>(exe)), std::istreambuf_iterator<char>()
+    );
+    // The data of Cait Sith and Vincent are two character records like the ones of the savemap, one
+    // after the other (at 0x9138d0 in the 1998 build). They are found by their contents: the
+    // character IDs 6 and 7, valid levels, weapons of each one and names that end.
+    const size_t size = 0x84;
+    for (size_t offset = 0; offset + 2 * size <= data.size(); offset ++){
+        bool found = true;
+        for (int r = 0; r < 2 && found; r ++){
+            const u8* record = &data[offset + r * size];
+            const int first_weapon = r == 0 ? 101 : 114;
+            const int last_weapon = r == 0 ? 113 : 127;
+            found = record[0] == 6 + r && record[1] >= 1 && record[1] <= 99
+              && record[0x1C] >= first_weapon && record[0x1C] <= last_weapon
+              && std::find(record + 0x10, record + 0x1C, 0xFF) != record + 0x1C;
         }
-        savemap_.characters[i].exp_to_next = savemap_file.readU32LE();
+        if (!found) continue;
+        File records(&data[offset], 0, 2 * size);
+        for (int r = 0; r < 2; r ++) ReadSaveMapCharacter(records, recruit_records_[r]);
+        recruit_records_found_ = true;
+        return;
     }
-    // The initial savemap ends up after character data, end now.
+    std::cerr << "[WARNING] Can't find the data of Cait Sith and Vincent in ff7.exe." << std::endl;
 }
 
 void KernelDataInstaller::WriteInitialSaveMap(std::string file_name){
@@ -2179,106 +2242,121 @@ void KernelDataInstaller::WriteInitialSaveMap(std::string file_name){
     file.open(file_name, std::ios::out);
     if (!file) return;
     for (int c = 0; c < 9; c ++){
-        int total_count; // Utility to count in loops.
-        SaveMap::Character character = savemap_.characters[c];
-        file
-          << "Characters[" << c << "] = {\n"
-          << "    char_id = " << static_cast<int>(character.identifier) << ",\n"
-          << "    name = \"" << character.name << "\",\n"
-          << "    enabled = false,\n"
-          << "    locked = false,\n"
-          << "    level = " << static_cast<int>(character.level) << ",\n"
-          << "    kills = " << character.kills << ",\n"
-          << "    back_row = " << (character.back_row ? "true" : "false") << ",\n"
-          << "    exp = " << character.exp << ",\n"
-          << "    exp_to_next = " << character.exp_to_next << ",\n"
-          << "    stats = {\n"
-          << "        str = {base = " << static_cast<int>(character.str)
-          << ", bonus = " << static_cast<int>(character.str_bonus)
-          << ", total = " << static_cast<int>(character.str + character.str_bonus) << "},\n"
-          << "        vit = {base = " << static_cast<int>(character.vit)
-          << ", bonus = " << static_cast<int>(character.vit_bonus)
-          << ", total = " << static_cast<int>(character.vit + character.vit_bonus) << "},\n"
-          << "        mag = {base = " << static_cast<int>(character.mag)
-          << ", bonus = " << static_cast<int>(character.mag_bonus)
-          << ", total = " << static_cast<int>(character.mag + character.mag_bonus) << "},\n"
-          << "        spr = {base = " << static_cast<int>(character.spr)
-          << ", bonus = " << static_cast<int>(character.spr_bonus)
-          << ", total = " << static_cast<int>(character.spr + character.spr_bonus) << "},\n"
-          << "        dex = {base = " << static_cast<int>(character.dex)
-          << ", bonus = " << static_cast<int>(character.dex_bonus)
-          << ", total = " << static_cast<int>(character.dex + character.dex_bonus) << "},\n"
-          << "        lck = {base = " << static_cast<int>(character.lck)
-          << ", bonus = " << static_cast<int>(character.lck_bonus)
-          << ", total = " << static_cast<int>(character.lck + character.lck_bonus) << "},\n"
-          << "        hp = {current = " << character.hp  << ", base = " << character.base_hp
-          << ", max = " << character.max_hp << "},\n"
-          << "        mp = {current = " << character.mp  << ", base = " << character.base_mp
-          << ", max = " << character.max_mp << "},\n"
-          << "        atk = 0,\n"
-          << "        acc = 0,\n"
-          << "        def = 0,\n"
-          << "        eva = 0,\n"
-          << "        matk = 0,\n"
-          << "        mdef = 0,\n"
-          << "        meva = 0\n"
-          << "    },\n"
-          << "    limit = {\n"
-          << "        current = " << static_cast<int>(character.limit_level) << ",\n"
-          << "        bar = " << static_cast<int>(character.limit_bar) << ",\n"
-          << "        learned = {\n"
-          << "            [1] = {[1] = " << (character.limits_learned[0][0] == 1 ? "true" : "false")
-          << ", [2] = " << (character.limits_learned[0][1] == 1 ? "true" : "false") << "},\n"
-          << "            [2] = {[1] = " << (character.limits_learned[1][0] == 1 ? "true" : "false")
-          << ", [2] = " << (character.limits_learned[1][1] == 1 ? "true" : "false") << "},\n"
-          << "            [3] = {[1] = " << (character.limits_learned[2][0] == 1 ? "true" : "false")
-          << ", [2] = " << (character.limits_learned[2][1] == 1 ? "true" : "false") << "},\n"
-          << "            [4] = {[1] = " << (character.limits_learned[3][0] == 1 ? "true" : "false")
-          << ", [2] = " << (character.limits_learned[3][1] == 1 ? "true" : "false") << "}\n"
-          << "        },\n"
-          << "        uses = {[1] = " << character.limit_uses[0] << ", [2] = "
-          << character.limit_uses[1] << ", [3] = " << character.limit_uses[2] << ", [4] = 0}\n"
-          << "    },\n"
-          << "    weapon = {\n"
-          << "        id = " << static_cast<int>(character.weapon) + 128 << ",\n"
-          << "        materia = {";
-        total_count = 0;
-        for (int m = 0; m < 8; m ++){
-            if (character.weapon_materia[m].id < 255){
-                total_count ++;
-                file << "\n            [" << m << "] = {id = "
-                  << static_cast<int>(character.weapon_materia[m].id) << ", ap = "
-                  << character.weapon_materia[m].ap << "},";
-            }
-        }
-        if (total_count > 0) file << "\n        }\n    },\n";
-        else file << "}\n    },\n";
-        file
-          << "    armor = {\n"
-          << "        id = " << static_cast<int>(character.armor) + 256 << ",\n"
-          << "        materia = {";
-        total_count = 0;
-        for (int m = 0; m < 8; m ++){
-            if (character.armor_materia[m].id < 255){
-                total_count ++;
-                file << "\n            [" << m << "] = {id = "
-                  << static_cast<int>(character.armor_materia[m].id) << ", ap = "
-                  << character.armor_materia[m].ap << "},";
-            }
+        file << "Characters[" << c << "] = ";
+        WriteSaveMapCharacter(file, savemap_.characters[c]);
+        file << "Characters.recalculate_stats(" << c << ")\n\n";
+    }
+    if (recruit_records_found_){
+        file << "-- Data that Cait Sith and Vincent get when they join, from ff7.exe.\n"
+          << "Game.RecruitRecords = {}\n";
+        for (int r = 0; r < 2; r ++){
+            file << "Game.RecruitRecords[" << 6 + r << "] = ";
+            WriteSaveMapCharacter(file, recruit_records_[r]);
         }
-        if (total_count > 0) file << "\n        }\n    },\n";
-        else file << "}\n    },\n";
-        file << "    accessory = ";
-        if (character.accessory < 0xFF) file << static_cast<int>(character.accessory) + 287;
-        else file << "nil";
-        file << ",\n    status = {";
-        if (character.fury) file << FURY;
-        if (character.sadness) file << SADNESS;
-        file << "}\n}\nCharacters.recalculate_stats(" << c << ")\n\n";
     }
     file.close();
 }
 
+void KernelDataInstaller::WriteSaveMapCharacter(
+  std::ostream& file, const SaveMap::Character& character
+){
+    int total_count; // Utility to count in loops.
+    file
+      << "{\n"
+      << "    char_id = " << static_cast<int>(character.identifier) << ",\n"
+      << "    name = \"" << character.name << "\",\n"
+      << "    enabled = false,\n"
+      << "    locked = false,\n"
+      << "    level = " << static_cast<int>(character.level) << ",\n"
+      << "    kills = " << character.kills << ",\n"
+      << "    back_row = " << (character.back_row ? "true" : "false") << ",\n"
+      << "    exp = " << character.exp << ",\n"
+      << "    exp_to_next = " << character.exp_to_next << ",\n"
+      << "    stats = {\n"
+      << "        str = {base = " << static_cast<int>(character.str)
+      << ", bonus = " << static_cast<int>(character.str_bonus)
+      << ", total = " << static_cast<int>(character.str + character.str_bonus) << "},\n"
+      << "        vit = {base = " << static_cast<int>(character.vit)
+      << ", bonus = " << static_cast<int>(character.vit_bonus)
+      << ", total = " << static_cast<int>(character.vit + character.vit_bonus) << "},\n"
+      << "        mag = {base = " << static_cast<int>(character.mag)
+      << ", bonus = " << static_cast<int>(character.mag_bonus)
+      << ", total = " << static_cast<int>(character.mag + character.mag_bonus) << "},\n"
+      << "        spr = {base = " << static_cast<int>(character.spr)
+      << ", bonus = " << static_cast<int>(character.spr_bonus)
+      << ", total = " << static_cast<int>(character.spr + character.spr_bonus) << "},\n"
+      << "        dex = {base = " << static_cast<int>(character.dex)
+      << ", bonus = " << static_cast<int>(character.dex_bonus)
+      << ", total = " << static_cast<int>(character.dex + character.dex_bonus) << "},\n"
+      << "        lck = {base = " << static_cast<int>(character.lck)
+      << ", bonus = " << static_cast<int>(character.lck_bonus)
+      << ", total = " << static_cast<int>(character.lck + character.lck_bonus) << "},\n"
+      << "        hp = {current = " << character.hp  << ", base = " << character.base_hp
+      << ", max = " << character.max_hp << "},\n"
+      << "        mp = {current = " << character.mp  << ", base = " << character.base_mp
+      << ", max = " << character.max_mp << "},\n"
+      << "        atk = 0,\n"
+      << "        acc = 0,\n"
+      << "        def = 0,\n"
+      << "        eva = 0,\n"
+      << "        matk = 0,\n"
+      << "        mdef = 0,\n"
+      << "        meva = 0\n"
+      << "    },\n"
+      << "    limit = {\n"
+      << "        current = " << static_cast<int>(character.limit_level) << ",\n"
+      << "        bar = " << static_cast<int>(character.limit_bar) << ",\n"
+      << "        learned = {\n"
+      << "            [1] = {[1] = " << (character.limits_learned[0][0] == 1 ? "true" : "false")
+      << ", [2] = " << (character.limits_learned[0][1] == 1 ? "true" : "false") << "},\n"
+      << "            [2] = {[1] = " << (character.limits_learned[1][0] == 1 ? "true" : "false")
+      << ", [2] = " << (character.limits_learned[1][1] == 1 ? "true" : "false") << "},\n"
+      << "            [3] = {[1] = " << (character.limits_learned[2][0] == 1 ? "true" : "false")
+      << ", [2] = " << (character.limits_learned[2][1] == 1 ? "true" : "false") << "},\n"
+      << "            [4] = {[1] = " << (character.limits_learned[3][0] == 1 ? "true" : "false")
+      << ", [2] = " << (character.limits_learned[3][1] == 1 ? "true" : "false") << "}\n"
+      << "        },\n"
+      << "        uses = {[1] = " << character.limit_uses[0] << ", [2] = "
+      << character.limit_uses[1] << ", [3] = " << character.limit_uses[2] << ", [4] = 0}\n"
+      << "    },\n"
+      << "    weapon = {\n"
+      << "        id = " << static_cast<int>(character.weapon) + 128 << ",\n"
+      << "        materia = {";
+    total_count = 0;
+    for (int m = 0; m < 8; m ++){
+        if (character.weapon_materia[m].id < 255){
+            total_count ++;
+            file << "\n            [" << m << "] = {id = "
+              << static_cast<int>(character.weapon_materia[m].id) << ", ap = "
+              << character.weapon_materia[m].ap << "},";
+        }
+    }
+    if (total_count > 0) file << "\n        }\n    },\n";
+    else file << "}\n    },\n";
+    file
+      << "    armor = {\n"
+      << "        id = " << static_cast<int>(character.armor) + 256 << ",\n"
+      << "        materia = {";
+    total_count = 0;
+    for (int m = 0; m < 8; m ++){
+        if (character.armor_materia[m].id < 255){
+            total_count ++;
+            file << "\n            [" << m << "] = {id = "
+              << static_cast<int>(character.armor_materia[m].id) << ", ap = "
+              << character.armor_materia[m].ap << "},";
+        }
+    }
+    if (total_count > 0) file << "\n        }\n    },\n";
+    else file << "}\n    },\n";
+    file << "    accessory = ";
+    if (character.accessory < 0xFF) file << static_cast<int>(character.accessory) + 288;
+    else file << "nil";
+    file << ",\n    status = {";
+    if (character.fury) file << FURY;
+    if (character.sadness) file << SADNESS;
+    file << "}\n}\n";
+}
+
 std::string KernelDataInstaller::GetBasicStatName(int id){
     std::string name = "stat";
     switch (id){

+ 43 - 1
src/installer/KernelDataInstaller.h

@@ -42,6 +42,13 @@ class KernelDataInstaller{
          */
         void ReadPrices();
 
+        /**
+         * Writes the inventories of the shops, read from the executable.
+         *
+         * @param file_name Path of the Lua file to write.
+         */
+        void WriteShops(std::string file_name);
+
         /**
          * Reads the command data from the kernel.
          *
@@ -199,6 +206,15 @@ class KernelDataInstaller{
          */
         void ReadInitialSaveMap();
 
+        /**
+         * Reads from ff7.exe the character data that Cait Sith and Vincent get when they join.
+         *
+         * Their slots of the initial savemap hold young Cloud and Sephiroth.
+         *
+         * @param[in] exe_path Path to ff7.exe.
+         */
+        void ReadRecruitRecords(const std::string& exe_path);
+
         /**
          * Saves the initial savemap to a Lua script.
          *
@@ -2516,7 +2532,7 @@ class KernelDataInstaller{
             /**
              * Curve bases.
              */
-            u8 base[8];
+            s8 base[8];
 
         };
 
@@ -2621,6 +2637,32 @@ class KernelDataInstaller{
          */
         SaveMap savemap_;
 
+        /**
+         * Reads one character record of the savemap.
+         *
+         * @param[in,out] savemap_file Data, at the start of the record.
+         * @param[out] character The character read.
+         */
+        void ReadSaveMapCharacter(File& savemap_file, SaveMap::Character& character);
+
+        /**
+         * Writes one character record as a Lua table.
+         *
+         * @param[in,out] file Target file.
+         * @param[in] character The character to write.
+         */
+        void WriteSaveMapCharacter(std::ostream& file, const SaveMap::Character& character);
+
+        /**
+         * Character data of Cait Sith and Vincent when they join.
+         */
+        SaveMap::Character recruit_records_[2];
+
+        /**
+         * True if the recruit records could be read.
+         */
+        bool recruit_records_found_ = false;
+
         /**
          * The kernel file.
          */

+ 31 - 17
src/installer/MediaDataInstaller.cpp

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

+ 90 - 29
src/installer/data/AbFile.cpp

@@ -15,8 +15,26 @@
 
 #include <iostream>
 #include <fstream>
+#include <map>
 #include "data/AbFile.h"
 
+namespace{
+
+    /**
+     * Number of bytes of parameters of the opcodes that aren't decompiled, found in the script
+     * interpreter of ff7.exe (0x41fb14, the handlers are listed at 0x424832). Opcodes that aren't
+     * here or in the decompiler have none. Getting one wrong turns its parameters into opcodes.
+     */
+    const std::map<u8, int> PARAMETER_BYTES = {
+        {0x90, 3}, {0x94, 5}, {0x96, 2}, {0x97, 2}, {0x98, 1}, {0x99, 6}, {0x9A, 4}, {0x9D, 1},
+        {0xA0, 1}, {0xA1, 2}, {0xA3, 1}, {0xA7, 1}, {0xA8, 2}, {0xAB, 4}, {0xAC, 1}, {0xAF, 1},
+        {0xB5, 11}, {0xBA, 2}, {0xBD, 4}, {0xBE, 1}, {0xBF, 2}, {0xC4, 3}, {0xC7, 3}, {0xC8, 5},
+        {0xCB, 8}, {0xCC, 1}, {0xCF, 8}, {0xD4, 3}, {0xD5, 8}, {0xD6, 1}, {0xD7, 2}, {0xDA, 1},
+        {0xDB, 4}, {0xDC, 3}, {0xDD, 2}, {0xDE, 2}, {0xE7, 1}, {0xE9, 3}, {0xF5, 1}, {0xF8, 1},
+        {0xFB, 4}, {0xFD, 6},
+    };
+}
+
 AbFile::AbFile(File file, bool enemy): ab_file_(file), is_enemy_(enemy){
     scripts_.clear();
     file.SetOffset(0);
@@ -53,6 +71,16 @@ void AbFile::Read(){
     }
 }
 
+u8 AbFile::ReadByte(){
+    if (ab_file_.GetCurrentOffset() >= ab_file_.GetFileSize()) return 0;
+    return ab_file_.readU8();
+}
+
+u16 AbFile::ReadWord(){
+    const u16 low = ReadByte();
+    return low | (ReadByte() << 8);
+}
+
 std::string AbFile::DecompileScript(u32 offset){
     u32 intial_offset = ab_file_.GetCurrentOffset();
     ab_file_.SetOffset(offset);
@@ -70,17 +98,19 @@ std::string AbFile::DecompileScript(u32 offset){
             end = true;
             break;
         }
+        // Some scripts that no model uses point to data that goes on to the end of the file.
+        if (ab_file_.GetCurrentOffset() >= ab_file_.GetFileSize()) break;
         total_opcodes ++;
-        u8 opcode = ab_file_.readU8();
+        u8 opcode = ReadByte();
         if (opcode >= 0x00 && opcode <= 0x8D) line << "    play_animation(" << static_cast<int>(opcode) << ")";
         else{
             switch (opcode){
                 case 0x91: // Play effect, one 1 byte parameter.
-                    line << "    play_effect(" << static_cast<int>(ab_file_.readU8()) << ")";
+                    line << "    play_effect(" << static_cast<int>(ReadByte()) << ")";
                     break;
                 case 0xA9: // Increase script counter by two. Two 1 byte parameters, ignored
-                    ab_file_.readU8();
-                    ab_file_.readU8();
+                    ReadByte();
+                    ReadByte();
                     break;
                 case 0xAA: // Unpause camera, no parameters.
                     line << "    unpause_camera()";
@@ -91,27 +121,47 @@ std::string AbFile::DecompileScript(u32 offset){
                      //   distance (2 bytes), distance from the joint.
                      //   start (1 byte), effect start.
                      //   end (1 byte), effect end.
-                    line << "    set_effect(" << static_cast<int>(ab_file_.readU8()) << ", " << ab_file_.readU16LE()
-                      << ", " << static_cast<int>(ab_file_.readU8()) << ", "
-                      << static_cast<int>(ab_file_.readU8()) << ")";
+                    line << "    set_effect(" << static_cast<int>(ReadByte()) << ", " << ReadWord()
+                      << ", " << static_cast<int>(ReadByte()) << ", "
+                      << static_cast<int>(ReadByte()) << ")";
                     break;
                 case 0xB6: // Pause camera and finish animation. One byte parameter, animation ID.
-                    line << "    pause_camera_finish_animation(" << static_cast<int>(ab_file_.readU8()) << ")";
+                    line << "    pause_camera_finish_animation(" << static_cast<int>(ReadByte()) << ")";
                     break;
                 case 0xB9: // Set camera. One byte parameter, camera ID.
-                    line << "    set_camera(" << static_cast<int>(ab_file_.readU8()) << ")";
+                    line << "    set_camera(" << static_cast<int>(ReadByte()) << ")";
                     break;
                 case 0x06:
                      // Play hurt animation, including action, effect and sound. It will not display
                      // damage and barrier effect. One byte parameter, the amount of frames to wait
                      // before starting.
-                    line << "    execute_hurt(" << static_cast<int>(ab_file_.readU8()) << ")";
+                    line << "    execute_hurt(" << static_cast<int>(ReadByte()) << ")";
+                    break;
+                case 0xBC:
+                    // Set the camera of the formation the battle rests on. One byte parameter, 0 to 2.
+                    line << "    set_formation_camera(" << static_cast<int>(ReadByte()) << ")";
                     break;
-                case 0xC1: // Jump to label set by 0xC9 (::jump::). No parameters.
-                    line << "    goto jump";
+                case 0xC1:
+                    // Jump to the label set by 0xC9 (::jump::). No parameters. It always jumps, so what
+                    // comes after it is not part of the script. The game looks for the label byte by
+                    // byte from the start, and in many scripts it is a parameter of another opcode:
+                    // then what follows it hasn't been decompiled yet, and it's done now.
+                    if (!label_set){
+                        const u32 next = ab_file_.GetCurrentOffset();
+                        ab_file_.SetOffset(offset);
+                        while (ab_file_.GetCurrentOffset() < next - 1 && ReadByte() != 0xC9){}
+                        if (ab_file_.GetCurrentOffset() < next - 1){
+                            label_set = true;
+                            line << "    ::jump::";
+                            break;
+                        }
+                        ab_file_.SetOffset(next);
+                    }
+                    line << "    goto jump\n    return 0";
+                    end = true;
                     break;
                 case 0xC2: // Show damage. One byte parameter, frames to wait before showing.
-                    line << "    execute_damage(" << static_cast<int>(ab_file_.readU8()) << ")";
+                    line << "    execute_damage(" << static_cast<int>(ReadByte()) << ")";
                     break;
                 case 0xC5:
                      // Set value from 0x800f8374 (unit fade time) as wait time for action script.
@@ -122,7 +172,7 @@ std::string AbFile::DecompileScript(u32 offset){
                      // Set value to 0x800f8374 (unit fade time) for futher use. One byte parameter,
                      // wait time. I have no idea what this is used for.
                     line
-                      << "    set_unit_fade_time(" << static_cast<int>(ab_file_.readU8()) << ")";
+                      << "    set_unit_fade_time(" << static_cast<int>(ReadByte()) << ")";
                     break;
                 case 0xC9: // Set a jump label. Only do it once per script. No prameters
                     if (!label_set){
@@ -140,8 +190,8 @@ std::string AbFile::DecompileScript(u32 offset){
                      // Jump to enemy, two parameters
                      //   (2 bytes), I don't know what it is.
                      //   (1 byte), I don't know what it is.
-                    line << "    jump_to_enemy(" << ab_file_.readU16LE() << ", "
-                      << static_cast<int>(ab_file_.readU8()) << ")";
+                    line << "    jump_to_enemy(" << ReadWord() << ", "
+                      << static_cast<int>(ReadByte()) << ")";
                     break;
                 case 0xD1:
                      // Move to enemy using function 0x800cf5bc by number of steps. Stop distance is
@@ -149,16 +199,16 @@ std::string AbFile::DecompileScript(u32 offset){
                      //   distance (2 byte), unknown.
                      //   unknown (2 bytes), unknown.
                      //   steps (1 byte), number of steps.
-                    line << "    move_to_target(" << ab_file_.readU16LE() << ", " << ab_file_.readU16LE() << ", "
-                      << static_cast<int>(ab_file_.readU8()) << ")";
+                    line << "    move_to_target(" << ReadWord() << ", " << ReadWord() << ", "
+                      << static_cast<int>(ReadByte()) << ")";
                     break;
                 case 0xD8:
                     // Play sound using attacker settings after waiting given number of frames.
                     // Two parameters:
                     //   wait (1 byte), frames to wait before the sound.
                     //   sound (2 bytes), sound ID.
-                    line << "    play_sound_for_attacker(" << static_cast<int>(ab_file_.readU8()) << ", "
-                      << ab_file_.readU16LE() <<  ")";
+                    line << "    play_sound_for_attacker(" << static_cast<int>(ReadByte()) << ", "
+                      << ReadWord() <<  ")";
                     break;
                 case 0xE5:
                     // Set initial (idle) direction for current unit according to situation. No
@@ -189,7 +239,7 @@ std::string AbFile::DecompileScript(u32 offset){
                     line << "    wait()";
                     break;
                 case 0xF4: // Set frames to wait. 1 parameter, frames to wait (1 byte).
-                    line << "    set_wait(" << static_cast<int>(ab_file_.readU8()) << ")";
+                    line << "    set_wait(" << static_cast<int>(ReadByte()) << ")";
                     break;
                 case 0xF6:
                     // Play die effect (depends on die type) if unit is dead. Used in enemy hurt
@@ -199,7 +249,7 @@ std::string AbFile::DecompileScript(u32 offset){
                 case 0xF7:
                     // After wait time ends execute hurt action, effect, sound. This will display
                     // damage and barriers effect. One byte parameter, wait time, in frames.
-                    line << "    execute_attack(" << static_cast<int>(ab_file_.readU8()) << ")";
+                    line << "    execute_attack(" << static_cast<int>(ReadByte()) << ")";
                     break;
                 case 0xFA: // Instantly set default position for units. No parameters.
                     line << "    return_position()";
@@ -213,24 +263,35 @@ std::string AbFile::DecompileScript(u32 offset){
                 case 0xF1: // Return.
                 case 0xEE: // Return.
                 case 0xFF: // Return.
-                //case 0xC1: // Return.
-                case 0xA2: // Return.
                     line << "    return 0";
                     end = true;
                     break;
                 case 0xFE:
-                    // Special return opcode. Return only if next byte is 0xC0.
+                    // Special return opcode. Return only if next byte is 0xC0. If it isn't, that byte
+                    // is the next opcode.
                     {
-                        u8 param = ab_file_.readU8();
-                        if (param == 0xC0){
+                        u32 next = ab_file_.GetCurrentOffset();
+                        if (ReadByte() == 0xC0){
                             line << "    return 0";
                             end = true;
                         }
-                        else line << "    -- 0xFE not paired with 0xC0 for return.";
+                        else{
+                            ab_file_.SetOffset(next);
+                            line << "    -- 0xFE not paired with 0xC0 for return.";
+                        }
                     }
                     break;
                 default:
-                    line << "    -- Unknown/unused opcode.";
+                    {
+                        auto length = PARAMETER_BYTES.find(opcode);
+                        if (length == PARAMETER_BYTES.end()) line << "    -- Unknown/unused opcode.";
+                        else{
+                            line << "    -- Not decompiled opcode, parameters:";
+                            for (int i = 0; i < length->second; i ++){
+                                line << " " << static_cast<int>(ReadByte());
+                            }
+                        }
+                    }
 
 
             }

+ 14 - 0
src/installer/data/AbFile.h

@@ -75,6 +75,20 @@ class AbFile{
          */
         std::string DecompileScript(u32 offset);
 
+        /**
+         * Reads the next byte of the file.
+         *
+         * @return The byte, 0 past the end of the file.
+         */
+        u8 ReadByte();
+
+        /**
+         * Reads the next two bytes of the file, little endian.
+         *
+         * @return The value, with 0 for the bytes past the end of the file.
+         */
+        u16 ReadWord();
+
         /**
          * The ab file.
          */

+ 21 - 30
src/installer/data/BattleSceneFile.cpp

@@ -49,28 +49,14 @@ void BattleSceneFile::Read(File file){
     }
     for (int c = 0; c < 4; c ++){
         for (int p = 0; p < 3; p ++){
-            // Camera positions are stored as 16 bit floats. Here, 16 bit are being read, then, the
-            // sign is checked to fit it into -32766 and 32767 (0x7F9b). Then, the number is
-            // divided by 255 (0xFF) to keep just the integer part.
-            scene_.camera[c].camera[p].x = file.readU16LE();
-            if (scene_.camera[c].camera[p].x > 0x7F9B) scene_.camera[c].camera[p].x -= 0xFFFF;
-            scene_.camera[c].camera[p].x /= 0xFF;
-            // Y and Z are inverted in original data.
-            scene_.camera[c].camera[p].y = file.readU16LE();
-            if (scene_.camera[c].camera[p].y > 0x7F9B) scene_.camera[c].camera[p].y -= 0xFFFF;
-            scene_.camera[c].camera[p].y /= 0xFF;
-            scene_.camera[c].camera[p].z = file.readU16LE();
-            if (scene_.camera[c].camera[p].z > 0x7F9B) scene_.camera[c].camera[p].z -= 0xFFFF;
-            scene_.camera[c].camera[p].z /= 0xFF;
-            scene_.camera[c].camera[p].d_x = file.readU16LE();
-            if (scene_.camera[c].camera[p].d_x > 0x7F9B) scene_.camera[c].camera[p].d_x -= 0xFFFF;
-            scene_.camera[c].camera[p].d_x /= 0xFF;
-            scene_.camera[c].camera[p].d_y = file.readU16LE();
-            if (scene_.camera[c].camera[p].d_y > 0x7F9B) scene_.camera[c].camera[p].d_y -= 0xFFFF;
-            scene_.camera[c].camera[p].d_y /= 0xFF;
-            scene_.camera[c].camera[p].d_z = file.readU16LE();
-            if (scene_.camera[c].camera[p].d_z > 0x7F9B) scene_.camera[c].camera[p].d_z -= 0xFFFF;
-            scene_.camera[c].camera[p].d_z /= 0xFF;
+            // The position of the camera and the point it looks at, signed 16 bit values in the units of
+            // the original game. They are kept as they are, and converted when the formations are built.
+            scene_.camera[c].camera[p].x = static_cast<int16_t>(file.readU16LE());
+            scene_.camera[c].camera[p].y = static_cast<int16_t>(file.readU16LE());
+            scene_.camera[c].camera[p].z = static_cast<int16_t>(file.readU16LE());
+            scene_.camera[c].camera[p].d_x = static_cast<int16_t>(file.readU16LE());
+            scene_.camera[c].camera[p].d_y = static_cast<int16_t>(file.readU16LE());
+            scene_.camera[c].camera[p].d_z = static_cast<int16_t>(file.readU16LE());
         }
         for (int p = 0; p < 12; p ++) scene_.camera[c].unused[p] = file.readU8();
     }
@@ -462,16 +448,21 @@ void BattleSceneFile::Read(File file){
         formation.location_name = LocationToString(scene_.setup[f].location);
         for (int c = 0; c < 3; c ++){
             Formation::Camera camera;
-            camera.x = scene_.camera[f].camera[c].x;
-            camera.y = scene_.camera[f].camera[c].y;
-            camera.z = scene_.camera[f].camera[c].z;
-            camera.d_x = scene_.camera[f].camera[c].d_x;
-            camera.d_y = scene_.camera[f].camera[c].d_y;
-            camera.d_z = scene_.camera[f].camera[c].d_z;
+            // The original data has x to the side, y down and z in depth (the enemies are in the negative
+            // side). The scene has the same x, the depth in y and z up, in units 255 times bigger, like the
+            // positions of the enemies.
+            const BattleSceneFile::Scene::Camera::Position& source = scene_.camera[f].camera[c];
+            camera.x = source.x / 255.0f;
+            camera.y = source.z / 255.0f;
+            camera.z = -source.y / 255.0f;
+            camera.d_x = source.d_x / 255.0f;
+            camera.d_y = source.d_z / 255.0f;
+            camera.d_z = -source.d_y / 255.0f;
             formation.camera_positions.push_back(camera);
         }
-        if (scene_.setup[f].camera < formation.camera_positions.size())
-            formation.initial_camera_position = scene_.setup[f].camera;
+        // The camera byte of the formation is the script of the camera at the start of the battle, which
+        // ends at the first camera of the formation unless it chooses another one.
+        formation.intro_camera = scene_.setup[f].camera;
         for (int a = 0; a < 4; a ++){
             if (scene_.setup[f].next_arena_candidates[a] != 999){
                 formation.next_arena_formation_candidates.push_back(scene_.setup[f].next_arena_candidates[a]);

+ 12 - 7
src/installer/data/Formation.h

@@ -193,32 +193,32 @@ struct Formation{
         /**
          * X position.
          */
-        int x;
+        float x;
 
         /**
          * Y position.
          */
-        int y;
+        float y;
 
         /**
          * z position.
          */
-        int z;
+        float z;
 
         /**
          * X direction.
          */
-        int d_x;
+        float d_x;
 
         /**
          * Y direction.
          */
-        int d_y;
+        float d_y;
 
         /**
          * z direction.
          */
-        int d_z;
+        float d_z;
 
         /**
          * Constructor.
@@ -303,6 +303,11 @@ struct Formation{
      */
     int initial_camera_position;
 
+    /**
+     * Camera script of the start of the battle.
+     */
+    int intro_camera;
+
     /**
      * Indicates if the formation is an arena battle.
      */
@@ -321,7 +326,7 @@ struct Formation{
     Formation():
       id(0), next_formation(-1), escape_counter(0.0f), escapable(true), skip_victory_pose(false),
       skip_spoils(false), preemptive_disabled(false), layout(Layout::NORMAL), location(-1),
-      location_name(""), initial_camera_position(0),is_arena_battle(false)
+      location_name(""), initial_camera_position(0), intro_camera(-1),is_arena_battle(false)
     {
         enemies.clear();
         camera_positions.clear();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

+ 50 - 6
src/installer/decompiler/field/instruction/FieldPartyInstruction.cpp

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

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

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

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

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

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

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

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

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

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

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

+ 29 - 3
src/modules/worldmap/WorldmapModule.cpp

@@ -1762,9 +1762,9 @@ namespace VGears {
             * Ogre::Quaternion(Ogre::Degree(rotation_y), Ogre::Vector3::UNIT_Y)
             * Ogre::Quaternion(Ogre::Degree(rotation_z), Ogre::Vector3::UNIT_Z)
         );
-        // The direction of the script is a full turn in 256. How it relates to the heading of the
-        // module (0 faces +Z) is a guess.
-        const Ogre::Radian heading(Ogre::Degree(-direction * 360.0f / 256.0f));
+        // The direction of the script is a full turn in 256: 0 faces +Z (south), 64 east (+X), 128 north and
+        // 192 west. Checked with the sea around Junon in the scene of the Warship, which sails at 192.
+        const Ogre::Radian heading(Ogre::Degree(direction * 360.0f / 256.0f));
         static_cast<EntityModel*>(entity)->GetModel()->getParentSceneNode()->getParentSceneNode()
           ->setOrientation(Ogre::Quaternion(heading, Ogre::Vector3::UNIT_Y));
     }
@@ -1827,6 +1827,27 @@ namespace VGears {
         );
     }
 
+    void WorldmapModule::SetModelHeading(const char* entity_name, const float direction){
+        if (entity_name == nullptr) return;
+        ::Entity* entity = EntityManager::getSingleton().GetEntity(entity_name);
+        if (entity == nullptr) return;
+        // The same heading as AddWorldModelFromScript.
+        const Ogre::Radian heading(Ogre::Degree(direction * 360.0f / 256.0f));
+        static_cast<EntityModel*>(entity)->GetModel()->getParentSceneNode()->getParentSceneNode()
+          ->setOrientation(Ogre::Quaternion(heading, Ogre::Vector3::UNIT_Y));
+    }
+
+    int WorldmapModule::GetModelHeading(const char* entity_name){
+        if (entity_name == nullptr) return 0;
+        ::Entity* entity = EntityManager::getSingleton().GetEntity(entity_name);
+        if (entity == nullptr) return 0;
+        const Ogre::Quaternion orientation = static_cast<EntityModel*>(entity)->GetModel()
+          ->getParentSceneNode()->getParentSceneNode()->getOrientation();
+        const Ogre::Vector3 forward = orientation * Ogre::Vector3(0.0f, 0.0f, 1.0f);
+        const float turns = std::atan2(forward.x, forward.z) / Ogre::Math::TWO_PI;
+        return static_cast<int>(std::floor(turns * 256.0f + 0.5f)) & 255;
+    }
+
     bool WorldmapModule::SurfaceToOverworld(EntityModel* submarine){
         const Ogre::Vector3 position = submarine->GetPosition();
         // The same position of WM0 has to be deep water.
@@ -2112,6 +2133,10 @@ namespace VGears {
         current_vehicle_ = VehicleType::TINY_BRONCO;
       }
       else{
+        // An entity of a scripted scene (the Warship): the camera follows it and nothing else happens.
+        if (active_entity != nullptr){
+          UpdateCamera(event.timeSinceLastFrame, false);
+        }
         return true;
       }
 
@@ -2292,6 +2317,7 @@ namespace VGears {
         else if (active_entity == highwind_entity_) camera_name = "highwind";
         else if (active_entity == submarine_entity_) camera_name = "submarine";
         else if (active_entity == tiny_bronco_entity_) camera_name = "tiny_bronco";
+        else if (active_entity != player_entity_) camera_name = "scene";
         float distance = std::sqrt(1.5f * 1.5f + 2.25f * 2.25f);
         float pitch = std::atan2(1.5f, 2.25f);
         const auto camera_settings = camera_settings_.find(camera_name);

+ 4 - 0
src/modules/worldmap/WorldmapModule.h

@@ -166,6 +166,10 @@ namespace VGears {
             );
 
             void SetModelOrientation(const char* entity_name, const float x, const float y, const float z);
+            /// Turns a model of the scripts to a direction of the game (a full turn is 256).
+            void SetModelHeading(const char* entity_name, const float direction);
+            /// The direction of the game (0 to 255) that a model faces, 0 if it doesn't exist.
+            int GetModelHeading(const char* entity_name);
 
         private:
 

Alguns arquivos não foram mostrados porque muitos arquivos mudaram nesse diff