Преглед на файлове

Installer: model conversion fixes, quieter output with a progress bar, clean install, installation record and documentation

- Model parts: the temporary parts of every kind of model are in the same resource group, and many have the same names in different kinds.
- No more fields intentionally skipped
- The field text reader handles fields without texts and empty texts without an end mark. Errors are no longer reported twice.
- Effect models: the models take their textures from the effect folders. A group that uses a texture its model doesn't have gets the material without texture instead of none.
- Battle models without geometry exported as an empty mesh, and empty material lists are not exported.
- An animation with more bones than the skeleton gives one warning instead of one error per bone.
- A map jump to a walkmesh triangle that doesn't exist uses the triangle under its position, and throws a warning.
- Unitialized and unclosed memory errors fixed.
- Output: Ogre writes it own log. Removed debug messages.
- In a terminal, it shows a single progress line, and writes the warnings and errors d) above it.
- The progress covers the whole installation: the extraction of the disk and the copy of the V-Gears data files show their progress too, in the command line and in the window, which is repainted during them.
- Clean install works: it was a checkbox that nothing read. Before extracting the disk, it deletes the converted data in data/, temp/, original_data/ and install.info of a previous installation, and keeps the saves, the controls, the root configuration files, data/config and the videos. It only cleans a directory with plugins.cfg and resources.cfg, needs the V-Gears data files to be copied, and the window asks first. It is --clean in the command line.
- Preserve original data is off by default, and without it the extracted install disk (original_data/) is deleted too. The command line option is --keep-originals instead of --discard-originals. Removed the unused clean_install option and the unused keep_originals parameter of the world map installer, and renamed CleanInstall to RemoveOriginals.
- An installation no longer replaces the files of data/config that exist, so the game configuration is kept.
- The installer writes install.info, a record of the installed parts, the version of the converted data (InstallStamp::DATA_VERSION) and whether the last installation finished. The verifier and the game report unfinished installations, outdated parts and installations without a record.
- Ctrl+C in the command line ends the progress line, says that the installation didn't finish and exits with 130. --strict ends with status 3 when the installation finished with errors in its log.
- The window can install again without being closed.
- The verifier looks for the Ogre plugins where the game looks for them, instead of requiring them in the installation directory.
- Rewrote the data installation guide.
- Tests for the clean installation, the installation record, the verifier and the command line.
Iñigo Valentin преди 2 дни
родител
ревизия
a767d6a8ac
променени са 42 файла, в които са добавени 2014 реда и са изтрити 514 реда
  1. 259 37
      doc/INSTALL_DATA.md
  2. 1 0
      src/CMakeLists.txt
  3. 22 31
      src/common/File.cpp
  4. 31 18
      src/common/File.h
  5. 169 0
      src/common/InstallStamp.cpp
  6. 150 0
      src/common/InstallStamp.h
  7. 20 41
      src/common/LzsFile.cpp
  8. 15 0
      src/common/VGearsApplication.cpp
  9. 8 0
      src/common/VGearsApplication.h
  10. 16 8
      src/data/VGearsAFile.cpp
  11. 12 2
      src/data/VGearsPFile.cpp
  12. 2 1
      src/data/VGearsPFile.h
  13. 85 104
      src/installer/BattleDataInstaller.cpp
  14. 2 2
      src/installer/BattleDataInstaller.h
  15. 353 52
      src/installer/CliInstaller.cpp
  16. 10 0
      src/installer/CliInstaller.h
  17. 56 5
      src/installer/DataInstaller.cpp
  18. 39 8
      src/installer/DataInstaller.h
  19. 17 1
      src/installer/DiskImage.cpp
  20. 4 1
      src/installer/DiskImage.h
  21. 39 30
      src/installer/FieldDataInstaller.cpp
  22. 24 5
      src/installer/FieldTextWriter.cpp
  23. 18 4
      src/installer/InstallCommandLine.cpp
  24. 13 2
      src/installer/InstallCommandLine.h
  25. 54 0
      src/installer/InstallLayout.cpp
  26. 51 0
      src/installer/InstallLayout.h
  27. 5 2
      src/installer/InstallLog.cpp
  28. 16 0
      src/installer/InstallLog.h
  29. 80 7
      src/installer/InstallSteps.cpp
  30. 68 2
      src/installer/InstallSteps.h
  31. 51 9
      src/installer/InstallVerifier.cpp
  32. 24 1
      src/installer/InstallVerifier.h
  33. 68 35
      src/installer/MainWindow.cpp
  34. 5 5
      src/installer/MainWindow.h
  35. 3 3
      src/installer/MainWindow.ui
  36. 4 6
      src/installer/MediaDataInstaller.cpp
  37. 2 2
      src/installer/WorldInstaller.cpp
  38. 1 9
      src/installer/WorldInstaller.h
  39. 54 70
      src/installer/common/BinGZipFile.cpp
  40. 17 3
      src/installer/common/BinGZipFile.h
  41. 1 0
      test/CMakeLists.txt
  42. 145 8
      test/installer/InstallLogic.cpp

+ 259 - 37
doc/INSTALL_DATA.md

@@ -1,84 +1,306 @@
 # <img src="../v-gears.png" alt="V-Gears" width="50"/> V-Gears Data Installation Guide
 
-## What you need
+V-Gears doesn't include any of the data of Final Fantasy VII. `v-gears-installer` reads it from your own copy of the game and converts it to the formats V-Gears uses. It can be used with a window or from the command line, and both install in the same way.
+
+## TL;DR
+
+You need the ISO image of the PC install disk, and FFmpeg and TiMidity for the audio (for example `sudo apt install ffmpeg timidity`).
+
+**With the window:** run `v-gears-installer`, select the ISO in **Final Fantasy VII ISO file**, and click **Install data**.
+
+**From the command line:**
 
-To install the Final Fantasy VII game data you need your own copy of the PC version of the game. The installer reads the **ISO image of the install disk** directly, so there is nothing to extract by hand. It extracts what it needs to `<installation directory>/original_data/` and converts it from there.
+```Bash
+v-gears-installer --iso ff7install.iso
+```
+
+Either way, everything is installed to the directory the game reads (`~/.v-gears/`, or `%USERPROFILE%\v-gears\` on Windows), and you can [run V-Gears](RUN.md "Run V-Gears") when it finishes. For the videos, run it again with each of the game disks 1, 2 and 3 (see [Extract the videos](#extract-the-videos)).
 
-If you also want the videos, you need the ISO images of the PC game disks 1, 2 and 3 (see [Extract the videos](#extract-the-videos)). The disks of the PlayStation versions are not supported.
+## Contents
 
-## FFmpeg and TiMidity
+- [What you need](#what-you-need)
+- [The installation directory](#the-installation-directory)
+- [Install with the window](#install-with-the-window)
+- [Install from the command line](#install-from-the-command-line)
+- [What can be installed](#what-can-be-installed)
+- [Options](#options)
+- [Extract the videos](#extract-the-videos)
+- [Verify an installation](#verify-an-installation)
+- [Troubleshooting](#troubleshooting)
+
+## What you need
 
-The installer converts the sound effects, the music and the videos with two external programs (the videos only need FFmpeg):
+- **The ISO image of the install disk** of the PC version of the game. The installer reads the image directly: there is nothing to extract by hand. The disks of the PlayStation versions are not supported.
+- **The ISO images of the PC game disks 1, 2 and 3**, only if you want the videos (see [Extract the videos](#extract-the-videos)).
+- **FFmpeg and TiMidity**, for the sound effects, the music and the videos (see [FFmpeg and TiMidity](#ffmpeg-and-timidity)).
+- **Free disk space:** a full installation uses about 1 GB. While installing, the installer needs about 3 GB plus the size of the ISO, and it checks that the space is there before it starts.
 
-- [FFmpeg](https://ffmpeg.org/download.html "FFmpeg") converts the sound effects, encodes the music and converts the videos.
+### FFmpeg and TiMidity
+
+The installer converts the audio and the videos with two external programs:
+
+- [FFmpeg](https://ffmpeg.org/download.html "FFmpeg") converts the sound effects, encodes the music and converts the videos. It must be able to write Ogg files (it needs the Vorbis encoder).
 - [TiMidity](https://timidity.sourceforge.net/#download "TiMidity") plays the original MIDI music so FFmpeg can encode it. Only the music needs it.
 
-The silence at the end of each music track (the reverberation that TiMidity renders after the last note) is removed when the music is encoded. The scripts that wait for a track to end, such as the jingle of the inns, would wait for it otherwise, and the files are smaller.
+In most GNU/Linux distributions both are available as packages:
+
+| Distribution | Command |
+|---|---|
+| Debian, Ubuntu | `sudo apt install ffmpeg timidity` |
+| Fedora | `sudo dnf install ffmpeg timidity++` |
+| Arch | `sudo pacman -S ffmpeg timidity++` |
+| macOS (Homebrew) | `brew install ffmpeg timidity` |
+
+On Windows, download a build of FFmpeg and copy `ffmpeg.exe` to a `tools` folder next to the installer, or in the installation directory. TiMidity++ also needs its `timidity.cfg` and the instrument files next to `timidity.exe`.
+
+The installer looks for each program in this order:
+
+1. The program you chose: with **Locate…** in the window (the choice is remembered), or with `--ffmpeg` and `--timidity` in the command line.
+2. A `tools` folder in the installation directory, then one next to the installer, then the folder of the installer itself.
+3. The system `PATH`.
+
+Every program is run once to check that it works. If one that the installation needs is missing, the installer says so before it starts, and what you would lose without it. The rest can be installed without the audio. To add it later, install the programs and run the installer again with only the sound effects and the music selected.
+
+The silence at the end of each music track (the reverberation that TiMidity renders after the last note) is removed when the music is encoded. Otherwise, the scripts that wait for a track to end, such as the jingle of the inns, would wait for the silence too.
+
+## The installation directory
 
-You don't have to configure anything if they are installed. The installer looks for them, in this order:
+The installation directory holds the configuration, the converted game data and the saves, and it is where the game runs. By default it is the one the game reads its data from:
 
-1. The program you chose with **Locate…**. The choice is remembered.
-2. A `tools` folder inside the installation directory, or next to the installer. On Windows, the easiest way is to copy `ffmpeg.exe` there.
-3. The system `PATH`. In most GNU/Linux distributions both are available as packages (for example, `sudo apt install ffmpeg timidity`).
+| System | Default directory |
+|---|---|
+| GNU/Linux, macOS | `~/.v-gears/` |
+| Windows | `%USERPROFILE%\v-gears\` |
 
-The window shows what the installer found (`Audio tools: FFmpeg ✓ … · TiMidity ✓ …`). Every program is run once to check that it works, and FFmpeg must be able to write ogg files (it needs the Vorbis encoder). On Windows, TiMidity also needs its `timidity.cfg` and the instrument files next to `timidity.exe`.
+It is created if it doesn't exist. After an installation it has:
 
-If a program that the installation needs is missing, the installer tells you before it starts. The message says what you would lose, and you can:
+| Path | What it is |
+|---|---|
+| `plugins.cfg`, `resources.cfg` | The configuration of V-Gears and Ogre. |
+| `data/` | The game data: the V-Gears files (scripts, screens, fonts...) and the converted game data. |
+| `data/config/config.cfg` | The configuration of the game (controls, options). An installation never replaces it if it exists. |
+| `data/video/` | The videos, if you extracted them. |
+| `save/` | The saved games, written by the game. |
+| `temp/world_models/` | World map data that the game reads. |
+| `install.info` | The record of the installations: the parts installed, with which version of the installer, and whether the last installation finished. See [Verify an installation](#verify-an-installation). |
+| `installer.log` | The log of the last installation. |
+| `install.log` | The log of Ogre during the last installation. |
 
-- **Locate…** the program in your system.
-- **Get it…**: open its download page.
-- **Check again**, for when you have just installed it.
-- **Continue without** it. The rest is installed normally, and the sound effects, the music, the videos, or any of them, are left out. The extracted `.wav` and `.mid` files stay in `~/.v-gears/data/audio/`, and the indexes only list the files that exist.
-- **Cancel** the installation.
+During the installation the installer also extracts the install disk to `original_data/`, and writes temporary files to `temp/`. They are deleted at the end, unless you keep them with [Preserve original data](#preserve-original-data).
 
-To add the missing audio later, install the programs and run the installer again with only the sound effects and the music selected (the *Media only* option, or *Custom*).
+## Install with the window
 
-## Launch the Installer
+Start the installer without arguments:
 
 ```Bash
 ~/V-Gears/build/bin/v-gears-installer
 ```
 
-It can be started from any directory. When the installation starts, it works from the installation directory.
+It can be started from any directory.
 
-## Run the Installer
-
-1. In **Import data source**, select the ISO image of the install disk. The installer tells you if the image is valid.
-2. In **VGears installation directory**, select where to install, for example `~/.v-gears/`. It will be created if it doesn't exist. It holds the configuration and the converted data, and it is where the game runs.
-3. (Optional) Select **Show advanced options** to choose what to install (see below). The defaults install everything. If the directory doesn't have the V-Gears files yet (configuration, scripts, screens, fonts...), leave **Copy V-Gears data files** checked, and the installer copies them there from the `data/` folder of the repository (`share/v-gears/` in an installed package). The engine also copies them by itself the first time it runs.
+1. In **Final Fantasy VII ISO file**, select the ISO image of the install disk. The installer tells you if the image is valid and supported.
+2. In **VGears installation directory**, select where to install (see [The installation directory](#the-installation-directory)). The installer remembers it.
+3. Optionally, select **Show advanced options** to choose what to install and how (see [What can be installed](#what-can-be-installed) and [Options](#options)). The defaults install everything, and the estimate under the options shows about how much disk space it will use.
 4. Click **Install data**.
 
-Before extracting anything, the installer checks that everything is in place: that the ISO is valid, that the directory is writable and has enough free space (about 3 GB plus the size of the ISO), and that the FFmpeg and TiMidity programs it needs can be used (see below). If something is wrong it tells you and doesn't start.
+The **Audio tools** line shows whether FFmpeg and TiMidity were found, with a **Locate…** link for each.
 
-The log shows the progress. Problems are shown in color (red for errors, orange for warnings), and the full log is written to `installer.log` in the installation directory. Don't be discouraged by some warnings about skipped fields or models, they are known limitations of the converter. The installation is finished when the progress bar reaches 100% and the window can be closed again.
+Before extracting anything, the installer checks that everything is in place: that the ISO is valid, that the directory is writable and has enough free space, that the V-Gears data files and the Ogre plugins can be found, and that the audio tools work. If something is wrong, it tells you what and doesn't start.
 
-An installation can only be done once per installer window. To install again, close the installer and open it again. The estimate under the options shows about how much disk space it will use.
+The progress bar and the log show how the installation goes. Problems are shown in color: red for errors, orange for warnings. Some warnings about skipped fields or models are expected: they are known limitations of the converter. The installation is finished when the bar reaches 100%.
 
 When it finishes:
 
-- **Verify install** checks that the installation directory has everything the game needs, and lists what is missing, grouped by part. If you skipped a part on purpose, its files are expected to be missing.
+- **Verify install** checks that the directory has everything the game needs (see [Verify an installation](#verify-an-installation)).
 - **Launch game** starts V-Gears from the installation directory.
 
+You can install again, or extract the videos of another disk, without closing the window.
+
+## Install from the command line
+
+Any installation option makes the installer work from the command line, without its window. The simplest installation installs everything to the default directory:
+
+```Bash
+v-gears-installer --iso ff7install.iso
+```
+
+The command line installer doesn't need a display, so it can be used over SSH, in a container or in a script. In a terminal it shows a progress bar with what it is doing, and writes the warnings (in orange) and the errors (in red) above it. When the output goes to a file or a pipe, it writes a line for each percent and every message, without colors. Set `NO_COLOR` to turn the colors off in a terminal too.
+
+When it finishes, it writes the number of errors and warnings, the first errors, and where the full log is.
+
+### Examples
+
+```Bash
+# Everything, to another directory.
+v-gears-installer --iso ff7install.iso --output ~/games/v-gears
+
+# Only the field maps and their models (and the kernel data they need).
+v-gears-installer --iso ff7install.iso --preset fields
+
+# The battle data, plus the music.
+v-gears-installer --iso ff7install.iso --preset battle --with music
+
+# Everything except the music.
+v-gears-installer --iso ff7install.iso --without music
+
+# Only some parts.
+v-gears-installer --iso ff7install.iso --preset custom --with kernel,fields,field-models
+
+# Start again from nothing, and don't stop on warnings (for scripts).
+v-gears-installer --iso ff7install.iso --clean --yes
+
+# Add the videos of a game disk to an installation.
+v-gears-installer --iso FF7DISC1.iso
+
+# Check an installation.
+v-gears-installer --verify --output ~/games/v-gears
+```
+
+### Arguments
+
+| Argument | What it does |
+|---|---|
+| `-i`, `--iso <file>` | The disk image. The install disk installs the game; game disks 1, 2 and 3 only add their videos to an installation. |
+| `-o`, `--output <dir>` | The installation directory. Default: the one the game reads (see [The installation directory](#the-installation-directory)). |
+| `-p`, `--preset <name>` | What to install: `everything` (the default), `fields`, `world-map`, `battle`, `media` or `custom`. `custom` starts with nothing. See [Presets](#presets). |
+| `--with <parts>` | Install these parts too, separated by commas. See [Parts](#parts). |
+| `--without <parts>` | Don't install these parts, separated by commas. The parts that need them are left out too. |
+| `--clean` | Delete the data of a previous installation first. See [Clean install](#clean-install). |
+| `--keep-originals` | Keep the extracted disk, the temporary files and the original audio and images. See [Preserve original data](#preserve-original-data). |
+| `--no-copy-data` | Don't copy the V-Gears data files. See [Copy V-Gears data files](#copy-v-gears-data-files). |
+| `--data-dir <dir>` | The V-Gears `data` folder to copy. Default: looked for next to the installer and in the system. |
+| `--ffmpeg <file>` | Path to FFmpeg. Default: looked for as explained in [FFmpeg and TiMidity](#ffmpeg-and-timidity). |
+| `--timidity <file>` | Path to TiMidity. Looked for like FFmpeg. |
+| `-y`, `--yes` | Continue when there are warnings or the audio tools are missing. Without it, the installer stops where the window would ask. |
+| `--strict` | End with exit status 3 if the installation finished with errors in its log. Useful in scripts that must not accept a partial installation. |
+| `--verify` | Check an installation instead of installing. See [Verify an installation](#verify-an-installation). |
+| `--list-parts` | List the parts that can be installed. |
+| `--cli` | Use the command line, not the window. Any of the options above already implies it. |
+| `-h`, `--help` | Show the usage. |
+| `-v`, `--version` | Show the version. |
+
+`--option=value` works too, for example `--preset=fields`.
+
+The window and the command line don't share settings: the command line doesn't use the FFmpeg and TiMidity programs you chose with **Locate…** in the window.
+
+### Exit status
+
+| Status | Meaning |
+|---|---|
+| `0` | The installation, the extraction or the verification went well. An installation that finished with some errors in its log still returns 0, unless `--strict` is given. |
+| `1` | It failed, or it stopped because of a warning or a missing audio tool (use `--yes` to continue anyway), or the verification found something missing. |
+| `2` | The command line is wrong. |
+| `3` | With `--strict`: the installation finished, but there are errors in its log. |
+| `130` | The installation was interrupted (Ctrl+C). The installation directory is incomplete until you install again. |
+
+## What can be installed
+
+### Parts
+
+| Window option | Command line part | What it is | Needs |
+|---|---|---|---|
+| Extract game data | `kernel` | The kernel data: items, materia, characters, the initial savemap, the fonts. | |
+| Extract field maps | `fields` | The field maps, their scripts, backgrounds and texts. | |
+| Extract field 3D models | `field-models` | The models of the characters in the fields. | `fields` |
+| Extract world map data | `world-map` | The world map. | the field maps, installed now or before |
+| Extract world map 3D models | `world-map-models` | The models of the world map. | `world-map` |
+| Extract battle data | `battle-data` | The battle scenes, enemies, formations, attacks and encounters. | |
+| Extract battle models | `battle-models` | The battle models and animations, and the spell effects. | |
+| Extract images | `images` | The images of the menus and the windows. | |
+| Extract sound effects | `sounds` | The sound effects. | FFmpeg |
+| Extract music tracks | `music` | The music. | FFmpeg and TiMidity |
+| Extract videos | `videos` | The videos. They are not on the install disk: see [Extract the videos](#extract-the-videos). | FFmpeg |
+
+A part can't be chosen without what it needs. In the window its option is disabled, and in the command line `--with field-models` alone is an error. When a part is removed, the parts that need it are removed too.
+
+### Presets
+
+| Window | Command line | Parts |
+|---|---|---|
+| Everything | `everything` | All of them. |
+| Field maps and models | `fields` | `kernel`, `fields`, `field-models` |
+| World map only | `world-map` | `world-map`, `world-map-models` |
+| Battle data and models | `battle` | `kernel`, `battle-data`, `battle-models` |
+| Media only (images, sounds, music, videos) | `media` | `images`, `sounds`, `music` |
+| Custom | `custom` | None: choose them yourself. |
+
+In the window the options can only be changed by hand with *Custom*. In the command line, `--with` and `--without` change any preset. For a later installation it's useful to install only what you need, for example only the fields, which is a few minutes faster.
+
+The world map scripts need the field maps. To install only the world map, install the fields first, or together with it.
+
+## Options
+
+### Copy V-Gears data files
+
+Window: **Copy V-Gears data files** (on by default). Command line: on unless `--no-copy-data`.
+
+Copies the files that come with V-Gears (configuration, scripts, screens, fonts...) to the installation directory. They are taken from the `data/` folder of the repository, or `share/v-gears/` in an installed package. In the command line, `--data-dir` chooses another folder.
+
+The game configuration (`data/config/config.cfg`) is only copied if the installation doesn't have it yet, so your settings are kept. Without this option, the installation directory must already have the V-Gears files.
+
+### Clean install
+
+Window: **Clean install** (off by default). Command line: `--clean`.
+
+Before installing, deletes what a previous installation wrote: the converted game data in `data/`, the temporary files in `temp/` and the extracted disk in `original_data/`. A new installation then starts from nothing, without old files of parts you don't install this time.
+
+It keeps:
+
+- The saved games (`save/`).
+- The controls (`controls.cfg`), the configuration of the game (`data/config/`) and the rest of the files in the root of the installation directory, such as `plugins.cfg` and the logs.
+- The videos (`data/video/`), because they come from the game disks and the install disk can't put them back.
+
+It needs **Copy V-Gears data files**, because the V-Gears files in `data/` are deleted too. It only deletes in a directory that is a V-Gears installation (it has `plugins.cfg` and `resources.cfg`). The window asks before deleting anything.
+
+### Preserve original data
+
+Window: **Preserve original data** (off by default). Command line: `--keep-originals`.
+
+To convert the game, the installer extracts the install disk and some original files: the WAV sound effects, the MIDI music, the TEX images and the temporary files of the models. V-Gears doesn't use them, so they are deleted when the installation is complete. This option keeps them, for example to study the original files. It uses about 1 GB more.
+
+The temporary files of the world map (`temp/world_models/`) are always kept, because the game reads them.
+
 ## Extract the videos
 
-The videos are not on the install disk, but on the PC game disks 1, 2 and 3. To get them, run the installer once for each disk: select the disk's ISO as the data source and the same installation directory, and click 'Install data'. The installer detects a game disk, extracts only its videos to `<installation directory>/data/video/` and doesn't touch anything else. Several disks have the same videos, so those already installed are skipped. Unlike the full installation, it can be repeated with the same installer window.
+The videos are not on the install disk, but on the PC game disks 1, 2 and 3. To get them, run the installer once for each disk, with the same installation directory:
+
+- In the window, select the disk's ISO and click **Install data**.
+- In the command line, run `v-gears-installer --iso FF7DISC1.iso` (and the same for the other two disks).
 
-The engine can't decode the original AVI files (Duck TrueMotion 2 codec), so the installer uses FFmpeg to convert each video to a folder of JPEG frames, an `.ogg` sound track (if the video has sound) and a `movie.xml` with the frame count and frame rate. Movies that carry camera data for the field background also get a `camera.cam` file. They are played by the engine's movie player, which draws the frames and plays the sound. FFmpeg is therefore needed to install the videos.
+The installer detects a game disk, extracts only its videos to `data/video/` and doesn't touch anything else. Several disks have the same videos, so those already installed are skipped. The options don't apply to a game disk, and `--clean` can't be used with one.
+
+The engine can't decode the original AVI files (Duck TrueMotion 2 codec), so the installer uses FFmpeg to convert each video to a folder of JPEG frames, an `.ogg` sound track (if the video has sound) and a `movie.xml` with the frame count and the frame rate. The videos that carry camera data for the field background also get a `camera.cam` file. The engine's movie player draws the frames and plays the sound. FFmpeg is therefore needed to install the videos.
 
 <!-- TODO(review): confirm the exact output layout under data/video/ (folder per movie, file names) after a fresh install, and which movies play in game. -->
 
 ## Battle data
 
-The battle installation extracts the battle scenes, enemy and formation data, the attacks, the field and world map encounter tables, and the battle models and animations. It also extracts the visual assets of the spell effects (`magic.lgp`): the meshes and textures of the effects and the sprite lists, which the battle scripts use to recreate the original spell effects. If you installed before these were added, run the installer again with the battle options selected (*Battle* preset or *Custom*) to get them.
+The battle installation extracts the battle scenes, the enemy and formation data, the attacks, the field and world map encounter tables, and the battle models and animations. It also extracts the visual assets of the spell effects (`magic.lgp`): the meshes and textures of the effects and the sprite lists, which the battle scripts use to recreate the original spell effects. If you installed before these were added, run the installer again with the battle parts selected (the *Battle data and models* preset, or `--preset battle`) to get them.
 
 <!-- TODO(review): list of spells with effects (currently the Fire, Ice, Bolt and Cure families) and the reinstall requirement should be re-checked against the current state of battle_fx.lua. -->
 
-## Advanced options
+## Verify an installation
+
+**Verify install** in the window, or `v-gears-installer --verify` in the command line (with `--output` for a directory other than the default), checks that the installation directory has everything the game needs. It lists what is missing, grouped by part.
+
+It only checks that the files exist, it doesn't open them. If you skipped a part on purpose (for example the music), its files are expected to be missing. The Ogre plugins listed in `plugins.cfg` are looked for where the game looks for them: the installation directory, the directory of the game, and the Ogre directories of the system.
+
+It also reads `install.info`, the record that the installer keeps of the installations, and reports:
+
+- An installation that didn't finish, because it was interrupted (Ctrl+C, closing the window) or it failed.
+- The parts that were converted by an older installer: when a new version of the installer converts something differently, the parts installed before have to be installed again. Installing only those parts is enough.
+- An installation without a record, made before the installer kept one. Its data may be outdated.
+
+The game checks the same record when it starts, and writes a warning if the data has to be installed again.
 
-The installer has a list of advanced options, under **Show advanced options**. They have tooltips with short explanations of what they do. For a fresh installation there is usually no need to change them: the *Everything* option installs it all.
+## Troubleshooting
 
-*What to install* has ready-made sets of options. Choose *Custom* to pick them one by one. For later installations it's useful to choose only what you need (for example, only the fields), which shortens the installation by a few minutes.
+- **The installation can't start.** The installer lists what is wrong. The most common problems are an ISO that isn't the PC install disk, a directory without enough free space, and missing Ogre plugins.
+- **The sounds or the music are missing.** FFmpeg or TiMidity were not found or didn't work. Install them and run the installer again with only the sound effects and the music.
+- **Warnings and errors in the log.** Some fields and models are skipped by known limitations of the converter, and some original files are dummies. A few dozen warnings and errors are normal. The full log is in `installer.log`, and the log of Ogre in `install.log`.
+- **Old or wrong files after reinstalling.** Install again with **Clean install** (`--clean`).
+- **The game says the data must be installed again.** The last installation didn't finish, or some parts were installed by an older installer. Run `v-gears-installer --verify` to see which, and install them again.
 
 ## Next steps
 
-- [Run V-Gears](RUN.md "Run V-Gears")
+- [Run V-Gears](RUN.md "Run V-Gears")

+ 1 - 0
src/CMakeLists.txt

@@ -594,6 +594,7 @@ set(VGEARS_SOURCE_FILES
     common/LzsFile.cpp
     common/TypeDefine.cpp
     common/DataDirectory.cpp
+    common/InstallStamp.cpp
     common/OgrePlugins.cpp
     common/VGearsApplication.cpp
     common/VGearsManualObject.cpp

+ 22 - 31
src/common/File.cpp

@@ -21,66 +21,57 @@
 #include <cstring>
 #include "core/Logger.h"
 
-File::File(const Ogre::String& file):
-  file_name_(file),
-  buffer_(nullptr),
-  buffer_size_(0),
-  offset_(0)
-{
+File::File(){}
+
+File::File(const Ogre::String& file): file_name_(file){
     LOG_TRIVIAL("Loading file: " + file_name_ + "\n");
-    buffer_size_ = FileSystem::GetFileSize(file_name_);
     // Zeroed, so a file that can't be read is empty data, not whatever was in memory.
-    buffer_ = static_cast<u8*>(calloc(buffer_size_, sizeof(u8)));
-    if (!FileSystem::ReadFile(file_name_, buffer_, 0, buffer_size_))
+    buffer_.assign(FileSystem::GetFileSize(file_name_), 0);
+    if (!buffer_.empty() && !FileSystem::ReadFile(file_name_, buffer_.data(), 0, buffer_.size()))
         LOG_TRIVIAL("Warning: " + file_name_ + " not found!\n");
 }
 
-File::File(const File* file, u32 offset, u32 length):
-  buffer_(nullptr), buffer_size_(length), offset_(offset)
-{
+File::File(const File* file, u32 offset, u32 length){
     assert(file != nullptr);
     file_name_ = file->GetFileName();
-    buffer_ = static_cast<u8*>(malloc(sizeof(u8) * buffer_size_));
-    file->GetFileBuffer(buffer_, offset_, buffer_size_);
+    // The fragment is a file of its own: it is read from its start.
+    buffer_.assign(length, 0);
+    if (length > 0) file->GetFileBuffer(buffer_.data(), offset, length);
 }
 
-File::File(const u8* buffer, u32 offset, u32 length):
-  file_name_("BUFFER"), buffer_(nullptr), buffer_size_(length), offset_(offset)
-{
+File::File(const u8* buffer, u32 offset, u32 length): file_name_("BUFFER"){
     assert(buffer != nullptr);
-    buffer_ = static_cast<u8*>(malloc(sizeof(u8) * buffer_size_));
-    memcpy(buffer_, buffer + offset, buffer_size_);
+    buffer_.assign(buffer + offset, buffer + offset + length);
 }
 
 File::File(const File* file){
     assert(file != nullptr);
-    buffer_size_ = file->GetFileSize();
-    file_name_   = file->GetFileName();
-    buffer_ = static_cast<u8*>(malloc(sizeof(u8) * buffer_size_));
-    file->GetFileBuffer(buffer_, 0, buffer_size_);
+    file_name_ = file->GetFileName();
+    buffer_ = file->buffer_;
 }
 
-File::~File(){/*free(buffer_);*/}
+File::~File(){}
 
 void File::WriteFile(const Ogre::String& file) const{
-    FileSystem::WriteNewFile(file, buffer_, buffer_size_);
+    FileSystem::WriteNewFile(file, buffer_.data(), static_cast<u32>(buffer_.size()));
 }
 
 const Ogre::String& File::GetFileName() const{return file_name_;}
 
-u32 File::GetFileSize() const{return buffer_size_;}
+u32 File::GetFileSize() const{return static_cast<u32>(buffer_.size());}
 
 void File::GetFileBuffer(u8* buffer, const u32 &start, const u32 &length) const{
     // What is past the end of the file is read as zeros.
-    const u32 available = start < buffer_size_ ? std::min(length, buffer_size_ - start) : 0;
-    if (available > 0) memcpy(buffer, buffer_ + start, available);
+    const u32 size = GetFileSize();
+    const u32 available = start < size ? std::min(length, size - start) : 0;
+    if (available > 0) memcpy(buffer, buffer_.data() + start, available);
     if (available < length) memset(buffer + available, 0, length - available);
 }
 
 // Many of the original files are read past their end by the parsers (truncated animations, headers of the
 // last entry of an archive...). Those bytes are read as zeros, instead of whatever is in memory after the file.
 
-u8 File::GetU8(u32 offset) const{return offset < buffer_size_ ? buffer_[offset] : 0;}
+u8 File::GetU8(u32 offset) const{return offset < buffer_.size() ? buffer_[offset] : 0;}
 
 u16 File::GetU16LE(u32 offset) const{
     return GetU8(offset) | (GetU8(offset + 1) << 8);
@@ -115,6 +106,6 @@ u32 File::readU32LE(){
 u32 File::GetCurrentOffset(){return offset_;}
 
 void File::SetOffset(u32 offset){
-    if (offset < buffer_size_) offset_ = offset;
-    else offset_ = buffer_size_ - 1;
+    if (offset < buffer_.size()) offset_ = offset;
+    else offset_ = buffer_.empty() ? 0 : GetFileSize() - 1;
 }

+ 31 - 18
src/common/File.h

@@ -15,6 +15,7 @@
 
 #pragma once
 
+#include <vector>
 #include <OgreString.h>
 #include "common/TypeDefine.h"
 
@@ -25,6 +26,11 @@ class File{
 
     public:
 
+        /**
+         * Creates an empty file.
+         */
+        File();
+
         /**
          * Opens a file.
          *
@@ -37,7 +43,7 @@ class File{
          *
          * @param[in] file Pointer to the file.
          */
-        File(const File* file);
+        explicit File(const File* file);
 
         /**
          * Loads a file fragment.
@@ -62,6 +68,26 @@ class File{
          */
         virtual ~File();
 
+        /**
+         * Copies a file, with its own copy of the data.
+         */
+        File(const File& file) = default;
+
+        /**
+         * Moves a file.
+         */
+        File(File&& file) = default;
+
+        /**
+         * Copies a file, with its own copy of the data.
+         */
+        File& operator=(const File& file) = default;
+
+        /**
+         * Moves a file.
+         */
+        File& operator=(File&& file) = default;
+
         /**
          * Writes the contents of the buffer to a file.
          *
@@ -149,10 +175,7 @@ class File{
         /**
          * Checks the current offset of the file.
          *
-         * Default is 0. Can be set on instantiation with {@see
-         * File(const File* file, u32 offset, u32 length)} or {@see
-         * File(const u8* buffer, u32 offset, u32 length)} and advanced with
-         * {@see readU8}, {@see readU16LE} or {@see readU32LE}
+         * Default is 0. It is advanced with {@see readU8}, {@see readU16LE} or {@see readU32LE}.
          */
         u32 GetCurrentOffset();
 
@@ -176,22 +199,12 @@ class File{
         /**
          * Current offset of the file.
          *
-         * Default is 0. Can be set on instantiation with {@see
-         * File(const File* file, u32 offset, u32 length)} or {@see
-         * File(const u8* buffer, u32 offset, u32 length)} and advanced with
-         * {@see readU8}, {@see readU16LE} or {@see readU32LE}
+         * Default is 0. It is advanced with {@see readU8}, {@see readU16LE} or {@see readU32LE}.
          */
         u32 offset_ = 0;
 
         /**
-         * The file buffer.
-         *
-         * It contains the file data.
-         */
-        u8* buffer_;
-
-        /**
-         * The allocated size of {@see buffer_}.
+         * The file data. Each file has its own copy, freed with the file.
          */
-        u32 buffer_size_;
+        std::vector<u8> buffer_;
 };

+ 169 - 0
src/common/InstallStamp.cpp

@@ -0,0 +1,169 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <algorithm>
+#include <ctime>
+#include <fstream>
+#include <set>
+#include <sstream>
+#include "common/InstallStamp.h"
+
+namespace VGears{
+
+    namespace InstallStamp{
+
+        namespace bfs = boost::filesystem;
+
+        const char* const FILE_NAME = "install.info";
+
+        namespace{
+
+            /**
+             * Joins a list with commas.
+             */
+            std::string Join(const std::vector<std::string>& items){
+                std::string joined;
+                for (const std::string& item : items) joined += (joined.empty() ? "" : ",") + item;
+                return joined;
+            }
+
+            /**
+             * Splits a list separated by commas, skipping empty items.
+             */
+            std::vector<std::string> Split(const std::string& list){
+                std::vector<std::string> items;
+                std::stringstream stream(list);
+                std::string item;
+                while (std::getline(stream, item, ',')) if (!item.empty()) items.push_back(item);
+                return items;
+            }
+
+            /**
+             * Removes the spaces at both ends.
+             */
+            std::string Trim(std::string text){
+                const auto space = [](unsigned char c){return std::isspace(c) != 0;};
+                while (!text.empty() && space(text.back())) text.pop_back();
+                while (!text.empty() && space(text.front())) text.erase(0, 1);
+                return text;
+            }
+        }
+
+        bool Read(const bfs::path& directory, Stamp& stamp){
+            stamp = Stamp();
+            std::ifstream file((directory / FILE_NAME).string());
+            if (!file.is_open()) return false;
+            std::string line;
+            while (std::getline(file, line)){
+                line = Trim(line);
+                if (line.empty() || line[0] == '#') continue;
+                const size_t equal = line.find('=');
+                if (equal == std::string::npos) continue;
+                const std::string key = Trim(line.substr(0, equal));
+                const std::string value = Trim(line.substr(equal + 1));
+                if (key == "complete") stamp.complete = value == "1";
+                else if (key == "installer") stamp.installer = value;
+                else if (key == "date") stamp.date = value;
+                else if (key == "disk") stamp.disk = value;
+                else if (key == "installing") stamp.installing = Split(value);
+                else if (key.compare(0, 5, "part.") == 0 && key.size() > 5){
+                    int version = 0;
+                    try{version = std::stoi(value);}
+                    catch (...){version = 0;}
+                    stamp.parts[key.substr(5)] = version;
+                }
+            }
+            return true;
+        }
+
+        bool Write(const bfs::path& directory, const Stamp& stamp){
+            std::ofstream file((directory / FILE_NAME).string(), std::ios::out | std::ios::trunc);
+            if (!file.is_open()) return false;
+            file << "# Record of the installations of the game data, written by v-gears-installer.\n"
+                 << "# The game and the verifier read it to know if the data must be installed again.\n"
+                 << "complete=" << (stamp.complete ? 1 : 0) << "\n"
+                 << "installer=" << stamp.installer << "\n"
+                 << "date=" << stamp.date << "\n"
+                 << "disk=" << stamp.disk << "\n";
+            if (!stamp.installing.empty()) file << "installing=" << Join(stamp.installing) << "\n";
+            for (const auto& part : stamp.parts) file << "part." << part.first << "=" << part.second << "\n";
+            return static_cast<bool>(file);
+        }
+
+        void Start(
+          Stamp& stamp, const std::vector<std::string>& parts, const std::string& installer,
+          const std::string& date, const std::string& disk
+        ){
+            // The parts of an installation that didn't finish, and are not installed again now, are not usable.
+            if (!stamp.complete){
+                for (const std::string& part : stamp.installing){
+                    if (std::find(parts.begin(), parts.end(), part) == parts.end()) stamp.parts[part] = 0;
+                }
+            }
+            stamp.complete = false;
+            stamp.installing = parts;
+            stamp.installer = installer;
+            stamp.date = date;
+            stamp.disk = disk;
+        }
+
+        void Finish(Stamp& stamp){
+            for (const std::string& part : stamp.installing) stamp.parts[part] = DATA_VERSION;
+            stamp.installing.clear();
+            stamp.complete = true;
+        }
+
+        std::vector<std::string> Outdated(const Stamp& stamp){
+            std::set<std::string> outdated;
+            for (const auto& part : stamp.parts) if (part.second < DATA_VERSION) outdated.insert(part.first);
+            if (!stamp.complete) outdated.insert(stamp.installing.begin(), stamp.installing.end());
+            return std::vector<std::string>(outdated.begin(), outdated.end());
+        }
+
+        std::vector<std::string> Problems(const bfs::path& directory, bool* found){
+            std::vector<std::string> problems;
+            Stamp stamp;
+            const bool read = Read(directory, stamp);
+            if (found != nullptr) *found = read;
+            if (!read) return problems;
+            if (!stamp.complete){
+                problems.push_back(
+                  "The last installation (" + stamp.date + ") didn't finish: it was interrupted or it failed. "
+                  "Install the data again."
+                );
+            }
+            std::vector<std::string> old;
+            for (const auto& part : stamp.parts){
+                const bool interrupted = std::find(stamp.installing.begin(), stamp.installing.end(), part.first)
+                  != stamp.installing.end();
+                if (part.second < DATA_VERSION && !(interrupted && !stamp.complete)) old.push_back(part.first);
+            }
+            if (!old.empty()){
+                problems.push_back(
+                  "These parts were installed by an older installer, or their installation didn't finish, and must be "
+                  "installed again: " + Join(old) + "."
+                );
+            }
+            return problems;
+        }
+
+        std::string Now(){
+            const std::time_t now = std::time(nullptr);
+            char text[32];
+            std::strftime(text, sizeof(text), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
+            return text;
+        }
+    }
+}

+ 150 - 0
src/common/InstallStamp.h

@@ -0,0 +1,150 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <map>
+#include <string>
+#include <vector>
+#include <boost/filesystem.hpp>
+
+namespace VGears{
+
+    /**
+     * The record of the installations of the game data in a directory (install.info).
+     *
+     * The installer writes it when an installation starts, as unfinished, and again when it finishes. It says what
+     * was installed and with which version of the converted data, so the game and the verifier can tell when an
+     * installation didn't finish, or when a part was converted by an older installer and must be installed again.
+     */
+    namespace InstallStamp{
+
+        /**
+         * Version of the converted data.
+         *
+         * Increase it when the installer converts something differently, so the installations made before have to
+         * be done again. The parts installed with an older version are reported as outdated.
+         *
+         * - 1: First version of the record.
+         */
+        const int DATA_VERSION = 1;
+
+        /**
+         * Name of the file, in the installation directory.
+         */
+        extern const char* const FILE_NAME;
+
+        /**
+         * What the record says.
+         */
+        struct Stamp{
+
+            /**
+             * True if the last installation finished.
+             */
+            bool complete = false;
+
+            /**
+             * Version of the installer that made the last installation.
+             */
+            std::string installer;
+
+            /**
+             * When the last installation started, as "YYYY-MM-DD HH:MM:SS".
+             */
+            std::string date;
+
+            /**
+             * The disk of the last installation.
+             */
+            std::string disk;
+
+            /**
+             * The installed parts (as in the command line of the installer, like "fields"), with the version of
+             * the data they were installed with. 0 if their installation didn't finish.
+             */
+            std::map<std::string, int> parts;
+
+            /**
+             * The parts of the installation that is in progress, or that didn't finish.
+             */
+            std::vector<std::string> installing;
+        };
+
+        /**
+         * Reads the record of a directory.
+         *
+         * @param[in] directory The installation directory.
+         * @param[out] stamp What it says.
+         * @return False if there is no record.
+         */
+        bool Read(const boost::filesystem::path& directory, Stamp& stamp);
+
+        /**
+         * Writes the record of a directory.
+         *
+         * @param[in] directory The installation directory.
+         * @param[in] stamp What to write.
+         * @return False if it can't be written.
+         */
+        bool Write(const boost::filesystem::path& directory, const Stamp& stamp);
+
+        /**
+         * Starts an installation: the record says it is in progress.
+         *
+         * The parts installed before are kept. The ones of an installation that didn't finish, and are not
+         * installed again now, are marked as not installed (version 0).
+         *
+         * @param[in,out] stamp The record of the directory. Empty if there was none.
+         * @param[in] parts The parts that will be installed.
+         * @param[in] installer Version of the installer.
+         * @param[in] date When the installation starts.
+         * @param[in] disk The disk.
+         */
+        void Start(
+          Stamp& stamp, const std::vector<std::string>& parts, const std::string& installer,
+          const std::string& date, const std::string& disk
+        );
+
+        /**
+         * Finishes an installation: its parts are installed with the current version of the data.
+         *
+         * @param[in,out] stamp The record of the directory.
+         */
+        void Finish(Stamp& stamp);
+
+        /**
+         * Gets the parts installed with an older version of the data, or whose installation didn't finish.
+         *
+         * @param[in] stamp The record.
+         * @return The names of the parts, sorted.
+         */
+        std::vector<std::string> Outdated(const Stamp& stamp);
+
+        /**
+         * Describes what is wrong with the installation of a directory, according to its record.
+         *
+         * @param[in] directory The installation directory.
+         * @param[out] found True if there is a record. It can be null.
+         * @return One sentence for each problem. Empty if there is none, or if there is no record.
+         */
+        std::vector<std::string> Problems(const boost::filesystem::path& directory, bool* found = nullptr);
+
+        /**
+         * Gets the current date and time, as written in the record.
+         */
+        std::string Now();
+    }
+}

+ 20 - 41
src/common/LzsFile.cpp

@@ -39,68 +39,47 @@ LzsFile::LzsFile(File* pFile): File(pFile){
 LzsFile::~LzsFile(){}
 
 void LzsFile::ExtractLzs(){
+    const u32 input_size = GetFileSize();
     u32 input_length = GetU32LE(0) + 4;
-    if (input_length != buffer_size_){
+    if (input_length != input_size){
         LOG_TRIVIAL("Warning: extract failed, this is not lzs!\n");
         return;
     }
-    u32 extract_size = (buffer_size_ + 255) & ~255;
-    u8* extractbuffer_ = static_cast<u8*>(malloc(extract_size));
-    unsigned int inputoffset_ = 4;
-    int outputoffset_ = 0;
+    std::vector<u8> output;
+    output.reserve((input_size + 255) & ~255);
+    unsigned int input_offset = 4;
     u8 control_byte = 0;
     u8 control_bit = 0;
-    while (inputoffset_ < buffer_size_){
+    while (input_offset < input_size){
         if (control_bit == 0){
-            control_byte = (static_cast<u8*>(buffer_))[inputoffset_ ++];
+            control_byte = GetU8(input_offset ++);
             control_bit = 8;
         }
-
-        if (control_byte & 1){
-            (static_cast<u8*>(extractbuffer_))[outputoffset_ ++] =
-              (static_cast<u8*>(buffer_))[inputoffset_ ++];
-            if (outputoffset_ == extract_size){
-                extract_size += 256;
-                extractbuffer_ = static_cast<u8*>(realloc(extractbuffer_, extract_size));
-            }
-        }
+        if (control_byte & 1) output.push_back(GetU8(input_offset ++));
         else{
-            u8 reference1 = (static_cast<u8*>(buffer_))[inputoffset_++];
-            u8 reference2 = (static_cast<u8*>(buffer_))[inputoffset_++];
-            u16 referenceoffset_ = reference1 | ((reference2 & 0xF0) << 4);
+            u8 reference1 = GetU8(input_offset ++);
+            u8 reference2 = GetU8(input_offset ++);
+            u16 reference_offset = reference1 | ((reference2 & 0xF0) << 4);
             u8 reference_length = (reference2 & 0xF) + 3;
-            int realoffset_
-              = outputoffset_ - ((outputoffset_ - 18 - referenceoffset_) & 0xFFF);
+            const int output_offset = static_cast<int>(output.size());
+            int real_offset = output_offset - ((output_offset - 18 - reference_offset) & 0xFFF);
             for (int j = 0; j < reference_length; ++ j){
-                if (realoffset_ < 0){
-                    (static_cast<u8*>(extractbuffer_))[outputoffset_++] = 0;
-                }
-                else{
-                    (static_cast<u8*>(extractbuffer_))[outputoffset_++] =
-                      (static_cast<u8*>(extractbuffer_))[realoffset_];
-                }
-                if (outputoffset_ == extract_size){
-                    extract_size += 256;
-                    extractbuffer_ =
-                      static_cast<u8*>(realloc(extractbuffer_, extract_size));
-                }
-                ++ realoffset_;
+                // Before the start of the data, or the byte that is being written: 0.
+                if (real_offset < 0 || real_offset >= static_cast<int>(output.size())) output.push_back(0);
+                else output.push_back(output[real_offset]);
+                ++ real_offset;
             }
         }
         control_byte >>= 1;
         control_bit --;
     }
-    free(buffer_);
-    // the real buffer size and mBufferSize will be a bit different
-    buffer_ = extractbuffer_;
-    buffer_size_ = outputoffset_;
+    buffer_ = std::move(output);
 }
 
 std::vector<VGears::uint8> LzsBuffer::Decompress(
   const std::vector<VGears::uint8>& buffer
 ){
+    if (buffer.empty()) return std::vector<VGears::uint8>();
     LzsFile tmp(static_cast<const u8*>(buffer.data()), 0, buffer.size());
-    std::vector<VGears::uint8> ret(tmp.buffer_size_);
-    ret.assign(tmp.buffer_, tmp.buffer_ + tmp.buffer_size_);
-    return ret;
+    return std::vector<VGears::uint8>(tmp.buffer_.begin(), tmp.buffer_.end());
 }

+ 15 - 0
src/common/VGearsApplication.cpp

@@ -41,6 +41,7 @@
 #include "data/VGearsTriggersFile.h"
 #include "data/VGearsMapListFile.h"
 #include "Version.h"
+#include "common/InstallStamp.h"
 #include <OgreControllerManager.h>
 #include <OgreDefaultHardwareBufferManager.h>
 #include <OgreMaterialManager.h>
@@ -142,6 +143,12 @@ namespace VGears{
         if (_initialized) return false;
         _initialized = true;
         _headless = true;
+        // Ogre writes its messages to the log file only, not to the terminal: the programs that convert data have
+        // their own output. Created before the root, which then doesn't create its own log.
+        if (Ogre::LogManager::getSingletonPtr() == nullptr){
+            _log_manager = std::make_unique<Ogre::LogManager>();
+            _log_manager->createLog(log_filename_, true, false, false);
+        }
         // No plugins file is passed to Ogre: the plugins are looked for in several places, see loadPlugins.
         _root = std::make_unique<Ogre::Root>("", config_filename_, log_filename_);
         loadPlugins(true);
@@ -323,6 +330,14 @@ namespace VGears{
             return false;
         }
         std::cout << "Data directory: " << data_directory.directory.string() << std::endl;
+        // The record of the installations says if the game data must be installed again.
+        bool recorded = false;
+        for (const std::string& problem : InstallStamp::Problems(data_directory.directory, &recorded))
+            std::cout << "Warning: " << problem << std::endl;
+        if (!recorded && bfs::exists(data_directory.directory / "data" / "fields" / "_fields.xml", ec)){
+            std::cout << "Warning: the game data was installed by an older version of v-gears-installer, and may be "
+              "outdated. Install it again with v-gears-installer." << std::endl;
+        }
         return true;
     }
 

+ 8 - 0
src/common/VGearsApplication.h

@@ -18,6 +18,7 @@
 #include <OgreRoot.h>
 #include <OgreOverlaySystem.h>
 #include <OgreHardwareBufferManager.h>
+#include <OgreLogManager.h>
 #include <OgreControllerManager.h>
 #include <OgreTextureManager.h>
 #include <memory>
@@ -322,6 +323,13 @@ namespace VGears{
              */
             std::unique_ptr<Ogre::HardwareBufferManager> _buffer_manager;
 
+            /**
+             * Log manager created without a render system, so Ogre's messages only go to the log file.
+             *
+             * The root uses it instead of creating its own. Declared before the root so it is destroyed after it.
+             */
+            std::unique_ptr<Ogre::LogManager> _log_manager;
+
             /**
              * Controller manager used without a render system, if the root didn't create one.
              *

+ 16 - 8
src/data/VGearsAFile.cpp

@@ -109,15 +109,23 @@ namespace VGears{
             key_frame->setTranslate(ConvertRootTranslation(frame->root_translation, flip_forward_axis));
             SetFrameRotation(key_frame, frame->root_rotation);
         }
+        // Some models of the original game use animations made for a model with more bones (Barret in southmk2,
+        // Yuffie in trnad_4...). The bones are matched by their position, and the ones the skeleton doesn't have
+        // are left out.
+        // The extra bones are not at the end: Tifa's skeleton, whose animations Barret uses, has the hair and an
+        // armour bone in the middle, so the bones after them get the rotations of other bones. Like the original
+        // engine, which has no bone names. These scenes looked right in the game (southmk2, trnad_4, kuro_7,
+        // spipe_2...), so matching the bones by name is not needed for now.
+        const uint32 skeleton_bones = skeleton->getNumBones() > 0 ? skeleton->getNumBones() - 1 : 0;
+        if (bone_count_ > skeleton_bones){
+            Ogre::LogManager::getSingleton().logMessage(
+              "[WARNING] The animation " + name + " has " + std::to_string(bone_count_) + " bones, and the skeleton "
+              + skeleton->getName() + " " + std::to_string(skeleton_bones) + ": the other "
+              + std::to_string(bone_count_ - skeleton_bones) + " are not animated.", Ogre::LML_CRITICAL
+            );
+        }
         for(uint32 i(0); i < bone_count_; ++ i){
-            if (i + 1 >= skeleton->getNumBones()){
-                // TODO: Figure out why this happens/fix it.
-                LOG_ERROR(
-                  "Bone " + std::to_string(i + 1) + "  is out of bounds "
-                  + std::to_string(skeleton->getNumBones()) + " for: " + name
-                  + " in: " + skeleton->getName()
-                );
-            }
+            if (i + 1 >= skeleton->getNumBones()) continue;
             else{
                 bone = skeleton->getBone(i + 1);
                 track = anim->createNodeTrack(track_handle ++, bone);

+ 12 - 2
src/data/VGearsPFile.cpp

@@ -16,6 +16,7 @@
 #include <iostream>
 #include <OgreBone.h>
 #include <OgreLogManager.h>
+#include <OgreMaterialManager.h>
 #include <OgreStringConverter.h>
 #include "data/VGearsPFile.h"
 #include "common/VGearsStringUtil.h"
@@ -135,7 +136,7 @@ namespace VGears{
             const String sub_name(
               bone_name + "/" + rsd_base + "/" + Ogre::StringConverter::toString(g)
             );
-            AddGroup(groups_[g], mo, sub_name, material_base_name, skeleton->getBone(bone_name));
+            AddGroup(groups_[g], mo, sub_name, material_base_name, rsd->getGroup(), skeleton->getBone(bone_name));
         }
     }
 
@@ -151,13 +152,22 @@ namespace VGears{
 
     void PFile::AddGroup(
       const Group &group, ManualObject &mo, const String &sub_name,
-      const String &material_base_name, const Ogre::Bone *bone
+      const String &material_base_name, const String &material_group, const Ogre::Bone *bone
     ) const{
         size_t material_index(0);
         if (group.has_texture) material_index = group.texture_index + 1;
         String material_name(
           material_base_name + "/" + Ogre::StringConverter::toString(material_index)
         );
+        // A group can use a texture that its RSD file doesn't list (some battle effects get it from the effect
+        // that uses them). Without a material the group would have none at all: use the one without texture.
+        if (material_index > 0 && !Ogre::MaterialManager::getSingleton().resourceExists(material_name, material_group)){
+            Ogre::LogManager::getSingleton().logMessage(
+              "[WARNING] The group " + sub_name + " uses the texture " + Ogre::StringConverter::toString(group.texture_index)
+              + ", which " + material_base_name + " doesn't have: it has no texture.", Ogre::LML_CRITICAL
+            );
+            material_name = material_base_name + "/0";
+        }
         const uint16 bone_handle(bone->getHandle());
         const Ogre::Vector3 bone_position(GetPosition(bone));
         size_t index(0);

+ 2 - 1
src/data/VGearsPFile.h

@@ -371,11 +371,12 @@ namespace VGears{
              * @param[in,out] mo The object to add to the group.
              * @param[in] sub_name Name for mo.
              * @param[in] material_base_name Name of the material for mo.
+             * @param[in] material_group Resource group of the materials.
              * @param[in] bone The bone to assign to bo.
              */
             virtual void AddGroup(
               const Group &group, ManualObject &mo, const String &sub_name,
-              const String &material_base_name, const Ogre::Bone *bone
+              const String &material_base_name, const String &material_group, const Ogre::Bone *bone
             ) const;
 
             /**

+ 85 - 104
src/installer/BattleDataInstaller.cpp

@@ -145,7 +145,7 @@ unsigned int BattleDataInstaller::InitializeSpellModels(){
 
 unsigned int BattleDataInstaller::ProcessScene(){
     if (next_scene_ >= scenes_uncompressed_.size()) return total_scenes_;
-    File* scene_file = scenes_uncompressed_[next_scene_];
+    File* scene_file = scenes_uncompressed_[next_scene_].get();
     if (scene_file == NULL){
         // Keep battle IDs stable: an unreadable scene still takes its 4 battle slots.
         std::cout << "Warning: scene " << next_scene_ << " could not be extracted." << std::endl;
@@ -412,7 +412,6 @@ unsigned int BattleDataInstaller::ProcessSpellModel(){
         magic_lgp_files_[next_model_to_process_].WriteFile(
           output_dir_ + "temp/spell_models/" + p_name
         );
-        std::cout << "[BONE RENAMED] " << fname << " --> " << p_name << std::endl;
         bool found = false;
         for (int m = 0; m < spell_models_.size(); m ++){
             if (spell_models_[m].id == id){
@@ -673,13 +672,11 @@ unsigned int BattleDataInstaller::ConvertSpellModel(){
 
         // Decompile the .hrc file (if any)
         if (model.hrc != ""){
-            std::cout << "[DECOMPILE] " << output_dir_ + "temp/spell_models/" + model.hrc << std::endl;
             DecompileSpellModelHrc(
               File(output_dir_ + "temp/spell_models/" + model.hrc), model,
               output_dir_ + "temp/spell_models/" + info.name_normal + ".hrc", model.id
             );
             model.hrc = info.name_normal + ".hrc";
-            std::cout << "    TO: " << (output_dir_ + "temp/spell_models/" + info.name_normal + ".hrc") << std::endl;
         }
         GenerateRsdFiles(model, output_dir_ + "temp/spell_models/");
 
@@ -697,7 +694,6 @@ unsigned int BattleDataInstaller::ConvertSpellModel(){
 
         // Export meshes thet have an .hrc skeleton.
         if (model.hrc != ""){
-            std::cout << "[EXPORT MESH] " << model.hrc << std::endl;
             Ogre::ResourcePtr hrc = VGears::HRCFileManager::GetSingleton().load(model.id + ".hrc", "FFVII");
             Ogre::String base_name;
             VGears::StringUtil::splitBase(model.hrc, base_name);
@@ -790,6 +786,9 @@ unsigned int BattleDataInstaller::InitializeEffectModels(){
         if (it != index.end()){found_folder = ""; return it->second;}
         return static_cast<size_t>(-1);
     };
+    // The folders that have each file, for the textures of the models of the root.
+    std::map<std::string, std::vector<std::string>> texture_folders;
+    for (const auto& entry : index) if (!entry.first.first.empty()) texture_folders[entry.first.second].push_back(entry.first.first);
     std::set<std::string> written;
     auto write = [&](size_t f, const std::string& name){
         if (written.insert(name).second) magic_lgp_files_[f].WriteFile(dir + name);
@@ -817,33 +816,67 @@ unsigned int BattleDataInstaller::InitializeEffectModels(){
         std::string p_folder;
         size_t p_index = find(folder, ply + ".p", p_folder);
         if (p_index == static_cast<size_t>(-1)) continue;
-        const std::string key = key_of(folder);
-        EffectModel model;
-        model.name = key + "_" + EffectSafeName(EffectStem(rsd_name));
         const std::string p_name = key_of(p_folder) + "_" + EffectSafeName(ply) + ".p";
         write(p_index, p_name);
-        std::string rsd = "@RSD940102\nPLY=" + p_name.substr(0, p_name.size() - 2) + ".PLY\n";
-        rsd += "MAT=" + model.name + ".MAT\nGRP=" + model.name + ".GRP\n";
-        std::vector<std::string> tex_names;
-        for (const std::string& t : tex){
-            std::string t_folder;
-            size_t t_index = find(folder, t + ".tex", t_folder);
-            if (t_index == static_cast<size_t>(-1)) continue;
-            const std::string t_name = key_of(t_folder) + "_" + EffectSafeName(t) + ".tex";
-            write(t_index, t_name);
-            tex_names.push_back(t_name);
-        }
-        rsd += "NTEX=" + std::to_string(tex_names.size()) + "\n";
-        for (size_t t = 0; t < tex_names.size(); t ++){
-            rsd += "TEX[" + std::to_string(t) + "]=" + tex_names[t].substr(0, tex_names[t].size() - 4) + ".TIM\n";
+        const std::string stem = EffectSafeName(EffectStem(rsd_name));
+        // Tells if a texture is in a folder, or in the archive root.
+        const auto has_texture = [&](const std::string& texture_folder, const std::string& t){
+            std::string found;
+            return find(texture_folder, t + ".tex", found) != static_cast<size_t>(-1);
+        };
+        // Writes a model with the textures of a folder. The textures keep their place in the list, so the
+        // polygons get the texture they use even if one is missing.
+        const auto add_model = [&](const std::string& name, const std::string& texture_folder){
+            EffectModel model;
+            model.name = name;
+            std::string rsd = "@RSD940102\nPLY=" + p_name.substr(0, p_name.size() - 2) + ".PLY\n";
+            rsd += "MAT=" + model.name + ".MAT\nGRP=" + model.name + ".GRP\n";
+            std::vector<std::string> tex_names;
+            for (const std::string& t : tex){
+                std::string t_folder;
+                const size_t t_index = find(texture_folder, t + ".tex", t_folder);
+                if (t_index == static_cast<size_t>(-1)){
+                    std::cerr << "[WARNING] The texture " << t << " of the effect model " << model.name
+                      << " is not in magic.lgp." << std::endl;
+                    tex_names.push_back(key_of(texture_folder) + "_" + EffectSafeName(t) + ".tex");
+                    continue;
+                }
+                const std::string t_name = key_of(t_folder) + "_" + EffectSafeName(t) + ".tex";
+                write(t_index, t_name);
+                tex_names.push_back(t_name);
+            }
+            rsd += "NTEX=" + std::to_string(tex_names.size()) + "\n";
+            for (size_t t = 0; t < tex_names.size(); t ++){
+                rsd += "TEX[" + std::to_string(t) + "]=" + tex_names[t].substr(0, tex_names[t].size() - 4) + ".TIM\n";
+            }
+            model.textures = tex_names;
+            std::ofstream(dir + model.name + ".rsd") << rsd;
+            // A model with a single bone, with the mesh.
+            std::ofstream(dir + model.name + ".hrc")
+              << ":HEADER_BLOCK 2\n:SKELETON " << model.name << "\n:BONES 1\n\nbone0\nroot\n0.000000\n1 "
+              << model.name << "\n\n";
+            effect_models_.push_back(model);
+        };
+        bool complete = true;
+        for (const std::string& t : tex) complete = complete && has_texture(folder, t);
+        // The models of the archive root are shared by several effects, and each effect has its own version of
+        // their textures in its folder (exp_1.tex is in five, all different). There is a model for each folder
+        // that has all of them, named after the folder like the models of the folders.
+        std::vector<std::string> variants;
+        if (!complete && folder.empty()){
+            std::set<std::string> candidates;
+            for (const std::string& t : tex){
+                const auto found = texture_folders.find(t + ".tex");
+                if (found != texture_folders.end()) candidates.insert(found->second.begin(), found->second.end());
+            }
+            for (const std::string& candidate : candidates){
+                bool all = true;
+                for (const std::string& t : tex) all = all && has_texture(candidate, t);
+                if (all) variants.push_back(candidate);
+            }
         }
-        model.textures = tex_names;
-        std::ofstream(dir + model.name + ".rsd") << rsd;
-        // A model with a single bone, with the mesh.
-        std::ofstream(dir + model.name + ".hrc")
-          << ":HEADER_BLOCK 2\n:SKELETON " << model.name << "\n:BONES 1\n\nbone0\nroot\n0.000000\n1 "
-          << model.name << "\n\n";
-        effect_models_.push_back(model);
+        if (variants.empty()) add_model(key_of(folder) + "_" + stem, folder);
+        else for (const std::string& variant : variants) add_model(key_of(variant) + "_" + stem, variant);
     }
     res_mgr_->removeResourceLocation(dir, "FFVII");
     res_mgr_->addResourceLocation(dir, "FileSystem", "FFVII", true, true);
@@ -861,6 +894,8 @@ unsigned int BattleDataInstaller::ConvertEffectModel(){
             const std::string path = data_dir_ + "models/battle/effects/"
               + texture.substr(0, texture.size() - 4) + ".png";
             if (boost::filesystem::exists(path)) continue;
+            // A texture that is not in magic.lgp is already reported.
+            if (!boost::filesystem::exists(output_dir_ + "temp/effects/" + texture)) continue;
             try{
                 TexFile tex(output_dir_ + "temp/effects/" + texture);
                 tex.SavePng(path);
@@ -1486,87 +1521,29 @@ std::string BattleDataInstaller::BuildAttackFileName(Attack attack){
     return file_name;
 }
 
-File* BattleDataInstaller::ExtractGZipScene(File file){
-    u32 offset = 0;
-    u8* file_buffer = static_cast<u8*>(malloc(file.GetFileSize()));
-    file.GetFileBuffer(file_buffer, 0, file.GetFileSize());
-    u32 extract_size = 256 * 1024;
-    u8* extract_buffer = static_cast<u8*>(malloc(extract_size));
-    int ret;
-    z_stream strm;
-    strm.zalloc = Z_NULL; // Used to allocate the internal state.
-    strm.zfree = Z_NULL; // Used to free the internal state.
-    strm.opaque = Z_NULL; // Private data object passed to zalloc and zfree.
-    strm.next_in = file_buffer + offset; //Next input byte.
-    strm.avail_in = file.GetFileSize() - offset; // Number of bytes available at next_in.
-    strm.next_out = extract_buffer; // Next output byte should be put there.
-    strm.avail_out = extract_size; // Remaining free space at next_out.
-    ret = inflateInit2(&strm, 15 + 32);
-    if (ret != Z_OK){
-        switch (ret){
-            case Z_MEM_ERROR:
-                inflateEnd(&strm);
-                std::cout << "Warning: inflateInit2 - Z_MEM_ERROR in file " << file.GetFileName() << std::endl;
-                break;
-            case Z_STREAM_ERROR:
-                inflateEnd(&strm);
-                std::cout << "Warning: inflateInit2 - Z_STREAM_ERROR in file " << file.GetFileName() << std::endl;
-                break;
-            default:
-                inflateEnd(&strm);
-                std::cout << "Warning: inflateInit2 - unknown error in file " << file.GetFileName() << std::endl;
-        }
-        return NULL;
+std::unique_ptr<File> BattleDataInstaller::ExtractGZipScene(const File& file){
+    std::vector<u8> compressed(file.GetFileSize());
+    if (!compressed.empty()) file.GetFileBuffer(compressed.data(), 0, compressed.size());
+    std::vector<u8> out;
+    std::string error;
+    if (compressed.empty() || !BinGZipFile::Inflate(compressed.data(), compressed.size(), out, error) || out.empty()){
+        std::cout << "Warning: " << (error.empty() ? "empty data" : error) << " in file " << file.GetFileName() << std::endl;
+        return nullptr;
     }
-    do{
-        if (strm.next_out == NULL){
-            inflateEnd(&strm);
-            std::cout << "Warning: strm.next_out == NULL in file " << file.GetFileName() << std::endl;
-            return NULL;
-        }
-        ret = inflate(&strm, Z_NO_FLUSH);
-        assert(ret != Z_STREAM_ERROR);
-        switch (ret){
-            case Z_NEED_DICT:
-                inflateEnd(&strm);
-                std::cout << "Warning: inflate - Z_NEED_DICT in file " << file.GetFileName() << std::endl;
-                return NULL;
-            case Z_DATA_ERROR:
-                inflateEnd(&strm);
-                std::cout << "Warning: inflate - Z_DATA_ERROR in file " << file.GetFileName() << std::endl;
-                return NULL;
-            case Z_MEM_ERROR:
-                inflateEnd(&strm);
-                std::cout << "Warning: inflate - Z_MEM_ERROR in file " << file.GetFileName() << std::endl;
-                return NULL;
-        }
-        if (ret != Z_STREAM_END){
-            extract_buffer = static_cast<u8*>(realloc(extract_buffer, extract_size * 2));
-            if (extract_buffer == NULL){
-                inflateEnd(&strm);
-                //std::cout << "Warning: extract_buffer == NULL in file "
-                //  << file.GetFileName() << std::endl;
-                return NULL;
-            }
-            strm.next_out = static_cast<u8*>(extract_buffer + extract_size);
-            strm.avail_out = extract_size;
-            extract_size *= 2;
-        }
-    } while (ret != Z_STREAM_END);
-    extract_size = extract_size - strm.avail_out;
-    (void)inflateEnd(&strm);
-    if (ret != Z_STREAM_END){
-        std::cout << "Warning: ret != Z_STREAM_END in file " << file.GetFileName() << std::endl;
-        return NULL;
-    }
-    File* out_file = new File(extract_buffer, 0, extract_size);
-    return out_file;
+    return std::make_unique<File>(out.data(), 0, static_cast<u32>(out.size()));
 }
 
 void BattleDataInstaller::ExportMesh(const std::string outdir, const Ogre::MeshPtr &mesh){
     VGears::String base_mesh_name;
     VGears::StringUtil::splitFull(mesh->getName(), base_mesh_name);
     MakeMaterialsUnique(mesh, outdir + base_mesh_name);
+    // A model without geometry (enemy 15, Eye, has only a skeleton and animations) has no bounds, and Ogre
+    // doesn't export a mesh without them. It is exported as an empty mesh at the origin.
+    // Ogre also wants a radius that is not 0, so the bounds are a tiny box.
+    if (mesh->getBounds().isNull() || mesh->getBoundingSphereRadius() <= 0){
+        mesh->_setBounds(Ogre::AxisAlignedBox(Ogre::Vector3(-0.01f), Ogre::Vector3(0.01f)), false);
+        mesh->_setBoundingSphereRadius(0.02f);
+    }
     Ogre::MeshSerializer mesh_serializer;
     Ogre::SkeletonPtr skeleton(mesh->getSkeleton());
     Ogre::SkeletonSerializer skeleton_serializer;
@@ -1576,6 +1553,7 @@ void BattleDataInstaller::ExportMesh(const std::string outdir, const Ogre::MeshP
     mesh->setSkeletonName(outdir + base_mesh_name + ".skeleton");
     mesh_serializer.exportMesh(mesh.get(), data_dir_ + "models/battle/" + outdir + mesh->getName());
     Ogre::MaterialSerializer mat_ser;
+    bool queued = false;
     std::set<std::string> textures;
     Ogre::Mesh::SubMeshList sub_meshes = mesh->getSubMeshes();
     for (Ogre::SubMesh* sub_mesh : sub_meshes){
@@ -1603,10 +1581,13 @@ void BattleDataInstaller::ExportMesh(const std::string outdir, const Ogre::MeshP
         }
         if (std::count(battle_materials_.begin(), battle_materials_.end(), sub_mesh->getMaterialName()) == 0){
             mat_ser.queueForExport(mat);
+            queued = true;
             battle_materials_.push_back(sub_mesh->getMaterialName());
         }
     }
-    mat_ser.exportQueued(data_dir_ + "models/battle/" + outdir + base_mesh_name + VGears::EXT_MATERIAL);
+    // Ogre throws if there is nothing to export (a mesh without geometry, or whose materials are already exported).
+    if (queued)
+        mat_ser.exportQueued(data_dir_ + "models/battle/" + outdir + base_mesh_name + VGears::EXT_MATERIAL);
 }
 
 void BattleDataInstaller::GenerateRsdFiles(BattleModel model, std::string path){

+ 2 - 2
src/installer/BattleDataInstaller.h

@@ -360,7 +360,7 @@ class BattleDataInstaller{
          * @return Uncompressed file. NULL if errors were encountered (they will
          * be logged to console).
          */
-        File* ExtractGZipScene(File file);
+        std::unique_ptr<File> ExtractGZipScene(const File& file);
 
         /**
          * Constructs a file name for the XML file to save an enemy to.
@@ -517,7 +517,7 @@ class BattleDataInstaller{
         /**
          * List of uncompressed scenes.
          */
-        std::vector<File*> scenes_uncompressed_;
+        std::vector<std::unique_ptr<File>> scenes_uncompressed_;
 
         /**
          * Processed scenes.

+ 353 - 52
src/installer/CliInstaller.cpp

@@ -15,7 +15,22 @@
 
 #include <cmath>
 #include <cstdio>
+#include <csignal>
+#include <cstdlib>
+#include <algorithm>
 #include <memory>
+#include <mutex>
+#ifdef _WIN32
+#include <io.h>
+#include <windows.h>
+#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
+#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
+#endif
+#else
+#include <sys/ioctl.h>
+#include <unistd.h>
+#endif
+#include <QtCore/QCoreApplication>
 #include <QtCore/QDir>
 #include <QtCore/QFile>
 #include <QtCore/QFileInfo>
@@ -23,6 +38,7 @@
 #include "DataInstaller.h"
 #include "DiskImage.h"
 #include "ExternalTools.h"
+#include "InstallLayout.h"
 #include "InstallLog.h"
 #include "InstallSteps.h"
 #include "InstallVerifier.h"
@@ -65,55 +81,279 @@ namespace{
     }
 
     /**
-     * Shows the progress of a task, one line for each percent.
+     * Tells if the standard output is a terminal, where a line can be redrawn.
+     */
+    bool IsTerminal(){
+#ifdef _WIN32
+        return _isatty(_fileno(stdout)) != 0;
+#else
+        return isatty(fileno(stdout)) != 0;
+#endif
+    }
+
+    /**
+     * Gets the width of the terminal, in columns.
+     */
+    size_t TerminalWidth(){
+#ifdef _WIN32
+        CONSOLE_SCREEN_BUFFER_INFO info;
+        if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info))
+            return static_cast<size_t>(info.srWindow.Right - info.srWindow.Left + 1);
+#else
+        winsize size;
+        if (ioctl(fileno(stdout), TIOCGWINSZ, &size) == 0 && size.ws_col > 0) return size.ws_col;
+#endif
+        return 80;
+    }
+
+    /**
+     * Tells if the messages can be coloured: the output is a terminal that understands colours, and the user didn't
+     * turn them off (https://no-color.org).
      */
-    class ProgressPrinter{
+    bool CanColour(){
+        if (!IsTerminal() || std::getenv("NO_COLOR") != nullptr) return false;
+#ifdef _WIN32
+        // The Windows console only understands the colour codes if it is asked to.
+        HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
+        DWORD mode = 0;
+        if (!GetConsoleMode(console, &mode)) return false;
+        return SetConsoleMode(console, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING) != 0;
+#else
+        const char* term = std::getenv("TERM");
+        return term == nullptr || std::string(term) != "dumb";
+#endif
+    }
+
+    /**
+     * Colours a message by its severity: orange for warnings, red for errors.
+     *
+     * @param[in] level The severity.
+     * @param[in] text The message.
+     * @param[in] colour False to leave it as it is.
+     */
+    std::string Coloured(InstallLog::Level level, const std::string& text, bool colour){
+        if (!colour || level == InstallLog::INFO) return text;
+        return (level == InstallLog::ERROR_LEVEL ? "\x1b[31m" : "\x1b[38;5;208m") + text + "\x1b[0m";
+    }
+
+    /**
+     * Shows the progress of an installation, and its problems.
+     *
+     * In a terminal, the progress is a single line at the bottom, redrawn in place, with the percent, a bar and
+     * what the installer is doing. The warnings and the errors are written above it as they happen. The rest of
+     * the messages are only in the installation log. The warnings are orange and the errors red, if the terminal
+     * can show colours.
+     *
+     * Elsewhere (the output is a file or a pipe) the log writes every message, and the progress is a line for each
+     * percent.
+     *
+     * The problems can come from other threads (the audio conversions), so everything is drawn with a lock.
+     */
+    class ProgressDisplay{
 
         public:
 
+            ProgressDisplay(): interactive_(IsTerminal()), colour_(CanColour()){}
+
             /**
-             * Shows the progress, if it has changed since it was last shown.
+             * Colours a message by its severity, if the terminal can show colours.
+             */
+            std::string Colour(InstallLog::Level level, const std::string& text) const{
+                return Coloured(level, text, colour_);
+            }
+
+            ~ProgressDisplay(){Detach();}
+
+            /**
+             * Gets the messages of the installation log, which must be open.
+             */
+            void Attach(){
+                if (!interactive_) return;
+                InstallLog& log = InstallLog::Get();
+                log.SetEcho(false);
+                log.SetSink([this](InstallLog::Level level, const std::string& message){
+                    if (level == InstallLog::INFO) SetStatus(message);
+                    else Message(Colour(level, message));
+                });
+            }
+
+            /**
+             * Stops getting the messages of the installation log, and leaves the progress line as it is.
+             */
+            void Detach(){
+                if (!interactive_) return;
+                InstallLog::Get().SetSink(nullptr);
+                std::lock_guard<std::mutex> lock(mutex_);
+                if (drawn_ > 0) std::fputs("\n", stdout);
+                std::fflush(stdout);
+                drawn_ = 0;
+            }
+
+            /**
+             * Shows the progress, if it has gone up since it was last shown.
              *
              * @param[in] progress The progress [0-100].
              */
-            void Show(float progress){
-                const int percent = static_cast<int>(std::floor(progress));
-                if (percent <= last_) return;
-                last_ = percent;
-                char line[32];
-                std::snprintf(line, sizeof(line), "[%3d%%]", percent);
-                Print(line);
+            void SetProgress(float progress){
+                const int percent = std::max(0, std::min(100, static_cast<int>(std::floor(progress))));
+                std::lock_guard<std::mutex> lock(mutex_);
+                // The progress of an installation doesn't go back.
+                if (percent <= percent_) return;
+                percent_ = percent;
+                if (interactive_) Draw();
+                else{
+                    char line[32];
+                    std::snprintf(line, sizeof(line), "[%3d%%]", percent);
+                    Print(line);
+                }
+            }
+
+            /**
+             * Shows what the installer is doing.
+             *
+             * In a terminal it is the text of the progress line. Elsewhere it is written as a line, if it changed.
+             */
+            void SetStatus(const std::string& status){
+                std::lock_guard<std::mutex> lock(mutex_);
+                if (status == status_) return;
+                status_ = status;
+                if (interactive_) Draw();
+                else Print(status);
+            }
+
+            /**
+             * Ends the progress line, so what is written next starts on a line of its own.
+             */
+            void EndLine(){
+                if (!interactive_) return;
+                std::lock_guard<std::mutex> lock(mutex_);
+                if (drawn_ > 0) std::fputs("\n", stdout);
+                std::fflush(stdout);
+                drawn_ = 0;
             }
 
         private:
 
-            int last_ = -1;
+            /**
+             * Writes a message above the progress line.
+             */
+            void Message(const std::string& message){
+                std::lock_guard<std::mutex> lock(mutex_);
+                Clear();
+                std::fputs((message + "\n").c_str(), stdout);
+                Draw();
+            }
+
+            /**
+             * Erases the progress line. The lock must be held.
+             */
+            void Clear(){
+                if (drawn_ == 0) return;
+                std::fputs(("\r" + std::string(drawn_, ' ') + "\r").c_str(), stdout);
+                drawn_ = 0;
+            }
+
+            /**
+             * Draws the progress line over the previous one. The lock must be held.
+             */
+            void Draw(){
+                // One column less than the terminal, so the line never wraps.
+                const size_t width = std::max<size_t>(TerminalWidth(), 20) - 1;
+                const int percent = std::max(percent_, 0);
+                char head[16];
+                std::snprintf(head, sizeof(head), "[%3d%%] ", percent);
+                std::string line = head;
+                size_t columns = line.size();
+                // The bar, if there is room for it and some of the status.
+                const size_t bar = width >= 60 ? 30 : (width >= 40 ? 15 : 0);
+                if (bar > 0){
+                    const size_t full = bar * static_cast<size_t>(percent) / 100;
+#ifdef _WIN32
+                    line += std::string(full, '#') + std::string(bar - full, '-');
+#else
+                    for (size_t i = 0; i < bar; ++ i) line += i < full ? "\u2588" : "\u2591";
+#endif
+                    line += " ";
+                    columns += bar + 1;
+                }
+                std::string status = status_;
+                if (columns + status.size() > width){
+                    status = status.substr(0, width > columns + 3 ? width - columns - 3 : 0);
+                    // Don't cut a UTF-8 character.
+                    while (!status.empty() && (static_cast<unsigned char>(status.back()) & 0xC0) == 0x80)
+                        status.pop_back();
+                    if (!status.empty() && (static_cast<unsigned char>(status.back()) & 0x80)) status.pop_back();
+                    status += "...";
+                }
+                line += status;
+                columns += status.size();
+                // Written over the previous line, padded to cover what is left of it.
+                std::string out = "\r" + line;
+                if (columns < drawn_) out += std::string(drawn_ - columns, ' ');
+                std::fputs(out.c_str(), stdout);
+                std::fflush(stdout);
+                drawn_ = columns;
+            }
+
+            /**
+             * True if the output is a terminal.
+             */
+            const bool interactive_;
+
+            /**
+             * True if the messages are coloured.
+             */
+            const bool colour_;
+
+            /**
+             * The last percent shown, -1 if none.
+             */
+            int percent_ = -1;
+
+            /**
+             * What the installer is doing.
+             */
+            std::string status_;
+
+            /**
+             * Columns of the progress line on the screen, 0 if there is none.
+             */
+            size_t drawn_ = 0;
+
+            /**
+             * Lock for the drawing.
+             */
+            std::mutex mutex_;
     };
 
     /**
-     * Opens the installation log in the installation directory.
-     *
-     * Its messages are already echoed to the terminal by the log itself, so no sink is needed.
+     * Opens the installation log in the installation directory, and shows its messages in the display.
      */
-    void OpenInstallLog(const QString& output, bool append){
+    void OpenInstallLog(const QString& output, bool append, ProgressDisplay& display){
         InstallLog::Get().Open((output + "installer.log").toStdString(), append);
+        display.Attach();
     }
 
     /**
      * Closes the installation log, and writes a summary of the problems.
+     *
+     * @return The number of errors in the log.
      */
-    void CloseInstallLog(){
+    size_t CloseInstallLog(ProgressDisplay& display){
         InstallLog& log = InstallLog::Get();
         log.EndStep();
+        display.Detach();
         const size_t errors = log.Count(InstallLog::ERROR_LEVEL);
         const size_t warnings = log.Count(InstallLog::WARNING);
         const std::string path = log.Path();
         log.Close();
         Print("");
         Print(std::to_string(errors) + " error(s), " + std::to_string(warnings) + " warning(s).");
-        for (const std::string& message : log.First(InstallLog::ERROR_LEVEL, 10)) Print("  " + message);
+        for (const std::string& message : log.First(InstallLog::ERROR_LEVEL, 10))
+            Print("  " + display.Colour(InstallLog::ERROR_LEVEL, message));
         if (errors > 10) Print("  ...");
         Print("The full log is in " + path);
+        return errors;
     }
 
     /**
@@ -169,24 +409,25 @@ namespace{
      *
      * @param[in] disk_image The game disk.
      * @param[in] output The installation directory.
+     * @param[in] strict True to end with an error status if the log has errors.
      * @return The exit status.
      */
-    int ExtractVideos(DiskImage& disk_image, const QString& output){
+    int ExtractVideos(DiskImage& disk_image, const QString& output, bool strict){
         const QStringList errors = InstallSteps::CheckVideoOutput(output);
         if (!errors.isEmpty()){
             PrintList("The extraction can't start:", errors);
             return CliInstaller::EXIT_FAILED;
         }
         // The installation log of a previous run is kept.
-        OpenInstallLog(output, true);
+        ProgressDisplay progress;
+        OpenInstallLog(output, true, progress);
         InstallLog::Get().Add("Extracting the videos of " + disk_image.getId() + "...");
-        ProgressPrinter progress;
         int extracted = 0;
         int skipped = 0;
         bool ok = false;
         try{
             ok = disk_image.extractVideos(
-              output.toStdString() + "data/", [&progress](float value){progress.Show(value);},
+              output.toStdString() + "data/", [&progress](float value){progress.SetProgress(value);},
               [](const std::string& message){InstallLog::Get().Add(message);}, &extracted, &skipped
             );
             if (ok) InstallSteps::ConvertMovies(output.toStdString() + "data/video/");
@@ -196,15 +437,17 @@ namespace{
             ok = false;
         }
         if (ok){
-            progress.Show(100);
+            progress.SetProgress(100);
+            InstallSteps::MarkVideosInstalled(output);
             InstallLog::Get().Add(
               "Videos extracted: " + std::to_string(extracted) + " new, " + std::to_string(skipped)
               + " already installed."
             );
         }
         else InstallLog::Get().Add("[ERROR] Some videos could not be extracted.");
-        CloseInstallLog();
-        return ok ? CliInstaller::EXIT_OK : CliInstaller::EXIT_FAILED;
+        const size_t logged_errors = CloseInstallLog(progress);
+        if (!ok) return CliInstaller::EXIT_FAILED;
+        return strict && logged_errors > 0 ? CliInstaller::EXIT_ERRORS : CliInstaller::EXIT_OK;
     }
 
     /**
@@ -241,10 +484,14 @@ namespace{
 
         // Check everything that can be checked before touching the disk.
         InstallSteps::PreflightResult preflight
-          = InstallSteps::RunPreflight(disk_image, output, arguments.copy_data, game_data);
+          = InstallSteps::RunPreflight(
+          disk_image, output, arguments.copy_data, game_data, arguments.clean
+        );
         for (
           const std::string& problem
-          : InstallRules::Problems(options, QFile::exists(output + "data/fields/_fields.xml"))
+          : InstallRules::Problems(
+            options, !arguments.clean && QFile::exists(output + "data/fields/_fields.xml")
+          )
         ) preflight.errors << QString::fromStdString(problem);
         if (!preflight.errors.isEmpty()){
             PrintList("The installation can't start:", preflight.errors);
@@ -260,17 +507,44 @@ namespace{
         // The audio is converted with external programs: say now, before anything is extracted, if they are missing.
         if (!CheckTools(options, output, arguments.yes)) return CliInstaller::EXIT_FAILED;
 
-        Print("Extracting " + disk_image.getPath() + "...");
-        if (!disk_image.extractImage(output.toStdString())){
-            PrintError("Failed to extract the ISO image.");
-            return CliInstaller::EXIT_FAILED;
+        // Everything is checked: the previous installation can be deleted.
+        if (arguments.clean){
+            const std::string root = output.toStdString();
+            if (!InstallLayout::IsInstallation(root)) Print("Nothing to clean: there is no installation in the directory.");
+            else{
+                Print("Deleting the previous installation (the saves, the controls, the game configuration and the "
+                  "videos are kept)...");
+                const InstallLayout::CleanResult cleaned = InstallLayout::CleanInstallation(root);
+                if (!cleaned.errors.empty()){
+                    QStringList errors;
+                    for (const std::string& error : cleaned.errors) errors << QString::fromStdString(error);
+                    PrintList("The previous installation could not be deleted:", errors);
+                    return CliInstaller::EXIT_FAILED;
+                }
+                Print("Deleted " + std::to_string(cleaned.removed) + " files and folders.");
+            }
         }
-        if (disk_image.getContentPath().empty()){
-            PrintError("The extracted data path is invalid.");
+
+        // From here on, the installation directory is being changed: until it finishes, the record says so.
+        InstallSteps::MarkInstallStarted(output, options, disk_image.getId());
+
+        // The progress of the whole installation: the extraction, the copy and the conversion (see
+        // InstallSteps::OverallProgress).
+        ProgressDisplay progress;
+        // Ends the progress line before writing why the installation stops.
+        const auto fail = [&progress](const std::string& message){
+            progress.EndLine();
+            PrintError(message);
             return CliInstaller::EXIT_FAILED;
-        }
+        };
+        progress.SetStatus("Extracting the install disk...");
+        if (!disk_image.extractImage(output.toStdString(), [&progress](float value){
+              progress.SetProgress(InstallSteps::OverallProgress(InstallSteps::Phase::EXTRACT, value));
+            })) return fail("Failed to extract the ISO image.");
+        if (disk_image.getContentPath().empty()) return fail("The extracted data path is invalid.");
         const std::vector<std::string> missing_files = InstallSteps::MissingRequiredFiles(disk_image);
         if (!missing_files.empty()){
+            progress.EndLine();
             QStringList names;
             for (const std::string& file : missing_files) names << QString::fromStdString(file);
             PrintList("Some of the required files were not found among the extracted data:", names);
@@ -278,24 +552,18 @@ namespace{
         }
         // Copy the V-Gears data files (scripts, screens, fonts...) to the installation directory.
         if (arguments.copy_data){
-            Print("Copying the V-Gears data files...");
-            if (!InstallSteps::CopyDirectory(game_data, output)){
-                PrintError("Failed to copy the V-Gears data files to the installation directory.");
-                return CliInstaller::EXIT_FAILED;
-            }
+            progress.SetStatus("Copying the V-Gears data files...");
+            if (!InstallSteps::CopyDirectory(game_data, output, [&progress](float value){
+                  progress.SetProgress(InstallSteps::OverallProgress(InstallSteps::Phase::COPY, value));
+                })) return fail("Failed to copy the V-Gears data files to the installation directory.");
         }
         // The installer's Ogre setup loads plugins.cfg and resources.cfg from the working directory (and writes
         // install.log there), so run from the installation directory.
-        if (!QFile::exists(output + "plugins.cfg") || !QFile::exists(output + "resources.cfg")){
-            PrintError("The installation directory must contain plugins.cfg and resources.cfg. Don't use --no-copy-data.");
-            return CliInstaller::EXIT_FAILED;
-        }
-        if (!QDir::setCurrent(output)){
-            PrintError("Could not enter the installation directory.");
-            return CliInstaller::EXIT_FAILED;
-        }
+        if (!QFile::exists(output + "plugins.cfg") || !QFile::exists(output + "resources.cfg"))
+            return fail("The installation directory must contain plugins.cfg and resources.cfg. Don't use --no-copy-data.");
+        if (!QDir::setCurrent(output)) return fail("Could not enter the installation directory.");
 
-        OpenInstallLog(output, false);
+        OpenInstallLog(output, false, progress);
         if (options.videos){
             InstallLog::Get().Add(
               "[WARNING] The install disk has no videos. To extract them, run the installer again with game disk 1, "
@@ -306,13 +574,12 @@ namespace{
           = InstallSteps::ToAdvancedOptions(options, arguments.keep_originals);
         const auto write_line = [](const std::string line, int, bool){InstallLog::Get().Add(line);};
         std::string error;
-        ProgressPrinter progress;
         try{
             DataInstaller installer(disk_image, QDir::toNativeSeparators(output).toStdString(), advanced, write_line);
             float value = 0;
             while (value < 100){
                 value = installer.Progress();
-                progress.Show(value);
+                progress.SetProgress(InstallSteps::OverallProgress(InstallSteps::Phase::CONVERT, value));
             }
         }
         catch (const std::exception& ex){
@@ -322,9 +589,14 @@ namespace{
             error = "Unknown error";
         }
         if (!error.empty()) InstallLog::Get().Add("[ERROR] Installation failed: " + error);
-        CloseInstallLog();
+        else InstallSteps::MarkInstallFinished(output);
+        const size_t errors = CloseInstallLog(progress);
         if (!error.empty()) return CliInstaller::EXIT_FAILED;
         Print("Installation finished in " + QDir::toNativeSeparators(output).toStdString());
+        if (arguments.strict && errors > 0){
+            Print("It finished with errors, and --strict was given: the exit status is 3.");
+            return CliInstaller::EXIT_ERRORS;
+        }
         return CliInstaller::EXIT_OK;
     }
 
@@ -353,7 +625,9 @@ namespace{
         const QString game_data = arguments.data_dir.empty()
           ? InstallSteps::FindGameDataDir() : QString::fromStdString(arguments.data_dir);
         Print("Verifying " + QDir::toNativeSeparators(output).toStdString() + "...");
-        const VerifyResult result = VerifyInstallation(output.toStdString(), game_data.toStdString());
+        const VerifyResult result = VerifyInstallation(
+          output.toStdString(), game_data.toStdString(), InstallSteps::PluginSearch()
+        );
         if (result.Ok()){
             Print("Everything the game needs is installed (" + std::to_string(result.checked) + " checks).");
             return CliInstaller::EXIT_OK;
@@ -376,6 +650,27 @@ namespace{
 
 }
 
+namespace{
+
+    /**
+     * Ends the program when it is interrupted (Ctrl+C) or asked to end.
+     *
+     * The progress line is ended, and the user is told that the installation didn't finish: the record of the
+     * installation directory already says so. Only what is safe in a signal handler is used.
+     */
+    extern "C" void OnInterrupt(int){
+        static const char message[] = "\n\nInterrupted: the installation didn't finish. Run the installer again.\n";
+#ifdef _WIN32
+        _write(2, message, sizeof(message) - 1);
+#else
+        const ssize_t written = write(2, message, sizeof(message) - 1);
+        (void)written;
+#endif
+        std::_Exit(CliInstaller::EXIT_INTERRUPTED);
+    }
+
+}
+
 namespace CliInstaller{
 
     int Run(const InstallCommandLine::Arguments& arguments, const std::string& program){
@@ -400,6 +695,8 @@ namespace CliInstaller{
             case InstallCommandLine::Mode::VERIFY:
                 return Verify(arguments);
             case InstallCommandLine::Mode::INSTALL:
+                std::signal(SIGINT, OnInterrupt);
+                std::signal(SIGTERM, OnInterrupt);
                 break;
             case InstallCommandLine::Mode::GUI:
                 PrintError("The installer window can't be opened from the command line installer.");
@@ -443,8 +740,12 @@ namespace CliInstaller{
         }
         // A game disk only has videos: extract them, without the rest of the installation.
         if (disk_image.isVideoDisk()){
+            if (arguments.clean){
+                PrintError("--clean is for the install disk: a game disk only adds its videos to an installation.");
+                return EXIT_USAGE;
+            }
             Print("Game disk: only its videos will be extracted.");
-            return ExtractVideos(disk_image, output);
+            return ExtractVideos(disk_image, output, arguments.strict);
         }
         return Install(arguments, disk_image, output);
     }

+ 10 - 0
src/installer/CliInstaller.h

@@ -41,6 +41,16 @@ namespace CliInstaller{
      */
     const int EXIT_USAGE = 2;
 
+    /**
+     * Exit status when the installation finished with errors in its log, with --strict.
+     */
+    const int EXIT_ERRORS = 3;
+
+    /**
+     * Exit status when the installation is interrupted (Ctrl+C), as usual: 128 plus the number of SIGINT.
+     */
+    const int EXIT_INTERRUPTED = 130;
+
     /**
      * Does what the command line asks.
      *

+ 56 - 5
src/installer/DataInstaller.cpp

@@ -19,6 +19,10 @@
 #include "InstallLayout.h"
 #include "InstallLog.h"
 #include "DiskImage.h"
+#include "data/VGearsAFileManager.h"
+#include "data/VGearsHRCFileManager.h"
+#include "data/VGearsPFileManager.h"
+#include "data/VGearsRSDFileManager.h"
 
 float DataInstaller::LINE_SCALE_FACTOR = 0.0078124970964f;
 
@@ -39,6 +43,12 @@ DataInstaller::DataInstaller(
     Ogre::Log* default_log(Ogre::LogManager::getSingleton().getDefaultLog());
     assert( default_log );
     default_log->setLogDetail(Ogre::LL_LOW);
+    // Ogre's messages only go to its own log (install.log, see Application::initOgreHeadless). Most are expected
+    // while converting (meshes without a skeleton yet, materials without a render system), and in the terminal and
+    // installer.log they hide the messages of the installer. The problems that V-Gears itself writes to that log
+    // (LOG_ERROR and LOG_WARNING) are passed to the installation log.
+    default_log->setDebugOutputEnabled(false);
+    default_log->addListener(&ogre_problems_);
 
     // Assign weights.
     for (int i = IDLE; i < STATE_COUNT; i ++) step_weight_[i] = 1;
@@ -56,7 +66,16 @@ DataInstaller::DataInstaller(
     step_weight_[FIELD_CONVERT_MODELS] = 3;
 }
 
-DataInstaller::~DataInstaller(){}
+DataInstaller::~DataInstaller(){
+    Ogre::Log* default_log = Ogre::LogManager::getSingletonPtr() ? Ogre::LogManager::getSingleton().getDefaultLog() : nullptr;
+    if (default_log) default_log->removeListener(&ogre_problems_);
+}
+
+void DataInstaller::OgreProblems::messageLogged(
+  const Ogre::String& message, Ogre::LogMessageLevel, bool, const Ogre::String&, bool&
+){
+    if (message.compare(0, 7, "[ERROR]") == 0 || message.compare(0, 9, "[WARNING]") == 0) InstallLog::Get().Add(message);
+}
 
 const char* DataInstaller::StepGroup(int state){
     if (state >= FIELD_CONVERT_MODELS_INIT && state <= FIELD_CONVERT_MODELS)
@@ -110,7 +129,7 @@ float DataInstaller::Progress(){
                         );
             battle_installer_ = std::make_unique<BattleDataInstaller>(disk_image_, output_dir_, application_.ResMgr());
             world_installer_ = std::make_unique<WorldInstaller>(
-              disk_image_, output_dir_, options_.keep_originals, application_.ResMgr()
+              disk_image_, output_dir_, application_.ResMgr()
             );
             installation_state_ = BATTLE_SCENES_INIT;
             return CalcProgress();
@@ -171,6 +190,7 @@ float DataInstaller::Progress(){
             if (cur_substep_ >= substeps_) installation_state_ = BATTLE_MODELS_CONVERT_INIT;
             return CalcProgress();
         case BATTLE_MODELS_CONVERT_INIT:
+            UseModelParts("temp/battle_models/");
             cur_substep_ = 0;
             substeps_ =  battle_installer_->ConvertBattleModelsInit();
             installation_state_ = BATTLE_MODELS_CONVERT;
@@ -200,6 +220,7 @@ float DataInstaller::Progress(){
             if (cur_substep_ >= substeps_) installation_state_ = SPELL_MODELS_CONVERT_INIT;
             return CalcProgress();
         case SPELL_MODELS_CONVERT_INIT:
+            UseModelParts("temp/spell_models/");
             cur_substep_ = 0;
             substeps_ =  battle_installer_->ConvertSpellModelsInit();
             installation_state_ = SPELL_MODELS_CONVERT;
@@ -210,6 +231,7 @@ float DataInstaller::Progress(){
             return CalcProgress();
         case EFFECT_MODELS_INIT:
             write_output_line_("Extracting battle effects...", 2, true);
+            UseModelParts("temp/effects/");
             substeps_ = battle_installer_->InitializeEffectModels();
             cur_substep_ = 0;
             installation_state_ = EFFECT_MODELS_CONVERT;
@@ -444,6 +466,7 @@ float DataInstaller::Progress(){
                 return CalcProgress();
             }
             write_output_line_("Converting field models...", 2, true);
+            UseModelParts("temp/char/");
             field_model_names_ = field_installer_->ConvertModelsInit();
             substeps_ = field_model_names_.size();
             cur_substep_ = 0;
@@ -465,6 +488,7 @@ float DataInstaller::Progress(){
                 return CalcProgress();
             }
             write_output_line_("Extracting world map data...", 2, true);
+            UseModelParts("temp/world_models/");
             substeps_ = world_installer_->Initialize();
             cur_substep_ = 0;
             installation_state_ = WM_MATERIALS;
@@ -511,7 +535,7 @@ float DataInstaller::Progress(){
                 }
             }
             write_output_line_("Cleaning up...", 2, true);
-            if (!options_.keep_originals) CleanInstall();
+            if (!options_.keep_originals) RemoveOriginals();
             installation_state_ = DONE;
             return CalcProgress();
         case DONE:
@@ -540,6 +564,31 @@ const float DataInstaller::CalcProgress(){
     return progress;
 }
 
+void DataInstaller::UseModelParts(const std::string& temp_dir){
+    Ogre::ResourceGroupManager& res_mgr = Ogre::ResourceGroupManager::getSingleton();
+    // Only the files of the parts are released: each of them removes what it made (an HRC file its mesh and its
+    // skeleton, an RSD file its materials). Ogre's clearResourceGroup can't be used: it removes those too, and then
+    // their owners fail to remove them.
+    std::vector<Ogre::ResourceManager*> managers = {
+      &VGears::HRCFileManager::GetSingleton(), &VGears::RSDFileManager::GetSingleton(),
+      &VGears::PFileManager::GetSingleton(), &VGears::AFileManager::GetSingleton()
+    };
+    for (Ogre::ResourceManager* manager : managers){
+        std::vector<Ogre::ResourceHandle> handles;
+        auto it = manager->getResourceIterator();
+        while (it.hasMoreElements()){
+            const Ogre::ResourcePtr resource = it.getNext();
+            if (resource->getGroup() == "FFVII") handles.push_back(resource->getHandle());
+        }
+        for (const Ogre::ResourceHandle handle : handles){
+            if (manager->getByHandle(handle)) manager->remove(handle);
+        }
+    }
+    for (const std::string& dir : {"temp/char/", "temp/battle_models/", "temp/spell_models/", "temp/effects/", "temp/world_models/"}){
+        if (dir != temp_dir) res_mgr.removeResourceLocation(output_dir_ + dir, "FFVII");
+    }
+}
+
 void DataInstaller::CreateDirectories(){
     for (const std::string& dir : InstallLayout::DataSubdirs()) CreateDir(dir);
     CreateDir("temp", true);
@@ -572,10 +621,12 @@ void DataInstaller::CreateDirectories(){
     fields_lgp_ = std::make_unique<ScopedLgp>(application_.getRoot(), *fields_lgp_path, "LGP", "FFVIIFields");
 }
 
-void DataInstaller::CleanInstall(){
+void DataInstaller::RemoveOriginals(){
+    boost::system::error_code ec;
     // The game itself reads some of the temp directories, so only the rest are removed.
     for (const std::string& dir : InstallLayout::RemovableTempSubdirs())
-        boost::filesystem::remove_all(InstallLayout::TempDir(output_dir_) + dir + "/");
+        boost::filesystem::remove_all(InstallLayout::TempDir(output_dir_) + dir + "/", ec);
+    boost::filesystem::remove_all(InstallLayout::OriginalDataDir(output_dir_), ec);
 }
 
 void DataInstaller::CreateDir(const std::string& path, bool in_root){

+ 39 - 8
src/installer/DataInstaller.h

@@ -18,6 +18,7 @@
 #include <string>
 #include <vector>
 #include <iostream>
+#include <OgreLog.h>
 #include "common/VGearsApplication.h"
 #include "DiskImage.h"
 #include "FieldDataInstaller.h"
@@ -95,15 +96,11 @@ class DataInstaller{
             bool wm_models;
 
             /**
-             * Option to keep original data after installation.
+             * Option to keep the original data after installation: the extracted install disk, the temporary
+             * files and the original files of the converted sounds, music and images.
              */
             bool keep_originals;
 
-            /**
-             * Option to perform a clean installation.
-             */
-            bool clean_install;
-
         };
 
         /**
@@ -165,9 +162,10 @@ class DataInstaller{
         void CreateDirectories();
 
         /**
-         * Cleans up after the installation is complete.
+         * Removes the original data once the installation is complete: the extracted install disk and the
+         * temporary files the game doesn't read.
          */
-        void CleanInstall();
+        void RemoveOriginals();
 
         /**
          * Installation steps.
@@ -472,6 +470,21 @@ class DataInstaller{
          */
         static const char* StepGroup(int state);
 
+        /**
+         * Prepares the resources for the conversion of a kind of models.
+         *
+         * The parts of the models of every kind (field, battle, spells, effects, world map) are in the same resource
+         * group, and many have the same names in different kinds (the field part cbba.rsd and the battle part
+         * cbba.rsd). Ogre keeps every loaded resource by name, so a model would get the part of another kind of
+         * model, loaded before, or the part of another kind left in its temporary folder by a previous installation
+         * in the same directory. This releases the parts loaded before, and leaves in the group only the temporary
+         * folder of the models that will be converted.
+         *
+         * @param[in] temp_dir Temporary folder of the models, relative to the installation directory
+         * ("temp/char/").
+         */
+        void UseModelParts(const std::string& temp_dir);
+
         /**
          * Substeps in the current installation step.
          */
@@ -527,6 +540,24 @@ class DataInstaller{
          */
         VGears::Application application_;
 
+        /**
+         * Passes the problems that V-Gears writes to Ogre's log to the installation log.
+         */
+        class OgreProblems : public Ogre::LogListener{
+
+            public:
+
+                void messageLogged(
+                  const Ogre::String& message, Ogre::LogMessageLevel lml, bool mask_debug,
+                  const Ogre::String& log_name, bool& skip_message
+                ) override;
+        };
+
+        /**
+         * Listener of Ogre's log. Declared after the application, so it is destroyed before Ogre.
+         */
+        OgreProblems ogre_problems_;
+
         /**
          * LGP archive with field data.
          */

+ 17 - 1
src/installer/DiskImage.cpp

@@ -561,7 +561,19 @@ DiskImage::DiskImage(std::string path) : DiskImage() {
 
 DiskImage::~DiskImage(){};
 
-bool DiskImage::extractImage(std::string installation_path){
+bool DiskImage::extractImage(std::string installation_path, const std::function<void(float)>& progress){
+    // The progress is how much of the image has been read, reported when it goes up by a percent. The reader can go
+    // back to read some parts again, so it only goes up.
+    const qint64 image_size = QFileInfo(QString::fromStdString(path)).size();
+    int last_percent = -1;
+    const auto report = [&](qint64 done){
+        if (!progress || image_size <= 0) return;
+        const int percent = static_cast<int>(std::min<qint64>(100, 100 * done / image_size));
+        if (percent <= last_percent) return;
+        last_percent = percent;
+        progress(static_cast<float>(percent));
+    };
+    report(0);
     struct archive* a;
     struct archive* ext;
     struct archive_entry* entry;
@@ -653,6 +665,7 @@ bool DiskImage::extractImage(std::string installation_path){
                     std::cerr << "Error writing data block: " << archive_error_string(ext) << std::endl;
                     break;
                 }
+                report(archive_filter_bytes(a, -1));
             }
         }
         archive_write_finish_entry(ext);
@@ -809,6 +822,7 @@ bool DiskImage::extractImage(std::string installation_path){
                                 }
                                 out_file.write(chunk.data(), got);
                                 remaining -= static_cast<uint32_t>(got);
+                                report(image_file.tellg());
                             }
                         }
                     }
@@ -825,6 +839,7 @@ bool DiskImage::extractImage(std::string installation_path){
 
         content_path = data_dir;
         is_extracted = true;
+        if (progress) progress(100);
         return true;
     }
 
@@ -846,6 +861,7 @@ bool DiskImage::extractImage(std::string installation_path){
 
     content_path = data_dir;
     is_extracted = true;
+    if (progress) progress(100);
     return true;
 }
 

+ 4 - 1
src/installer/DiskImage.h

@@ -215,9 +215,12 @@ struct DiskImage{
          * path.
          *
          * @param[in] installation_path The v-gears installation directory.
+         * @param[in] progress Receives the progress [0-100]. It can be empty.
          * @return True if the extraction was successful, false otherwise.
          */
-        bool extractImage(std::string installation_path);
+        bool extractImage(
+          std::string installation_path, const std::function<void(float)>& progress = std::function<void(float)>()
+        );
 
         /**
          * Finds a file in the extracted content of the disk image.

+ 39 - 30
src/installer/FieldDataInstaller.cpp

@@ -223,18 +223,8 @@ 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 == "fr_e" // Background image crash
-      || resource_name == "las4_2" // Background image crash
-      || resource_name == "las4_3" // Background image crash
-      || resource_name == "lastmap" // Background image crash
-      || resource_name == "md_e1" // Background image crash
-      || 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 == "elmin4_2" // boost::bad_format_string: format-string is ill-formed
-    ) return true;
+    // No field is known to crash at the moment.
+    (void)resource_name;
     return false;
 }
 
@@ -571,13 +561,11 @@ void FieldDataInstaller::ConvertModels(std::string model_name){
         if (VGears::HRCFileManager::GetSingleton().resourceExists(model->first, "FFVII"))
             VGears::HRCFileManager::GetSingleton().remove(model->first, "FFVII");
         write_output_line_("[ERROR] Ogre exception converting model " + model->first + ": " + ex.what());
-        std::cerr << "[ERROR] Ogre exception converting model " << model->first <<": " << ex.what() << std::endl;
     }
     catch (const std::exception& ex){
         if (VGears::HRCFileManager::GetSingleton().resourceExists(model->first, "FFVII"))
             VGears::HRCFileManager::GetSingleton().remove(model->first, "FFVII");
         write_output_line_("[ERROR] Exception converting model " + model->first + ": " + ex.what());
-        std::cerr << "[ERROR] Exception converting model " << model->first << ": " << ex.what() << std::endl;
     }
 }
 
@@ -728,21 +716,15 @@ void FieldDataInstaller::PcFieldToVGearsField(VGears::FLevelFilePtr& field){
             try{field_text_writer_.Write(raw_field_data, field->getName());}
             catch (const std::out_of_range& ex){
                 write_output_line_("[ERROR] Failed to read texts from field " + field->getName() + ": " + ex.what());
-                std::cerr << "[ERROR] Failed to read texts from field "
-                  << field->getName() << ": " << ex.what() << std::endl;
             }
             field_text_writer_.End();
         }
         else{
             write_output_line_("[ERROR] Failed to open script file from field " + field->getName() + " for writing.");
-            std::cerr << "[ERROR] Failed to open script file from field "
-              << field->getName() << "for writing." << std::endl;
         }
     }
     catch (const ::DecompilerException& ex){
         write_output_line_("[ERROR] Internal decompiler error in field " + field->getName() + ": " + ex.what());
-        std::cerr << "[ERROR] Internal decompiler error in field "
-          << field->getName() << ": " << ex.what() << std::endl;
     }
     // Write out the map file which links all the other files together for a given field.
     {
@@ -836,16 +818,43 @@ void FieldDataInstaller::PcFieldToVGearsField(VGears::FLevelFilePtr& field){
                 // complex. Now "get the Z value of the triangle with that ID". Note that ID
                 // actually just means index.
                 unsigned int triangle_index = static_cast<unsigned int>(gateway.destination.z);
-                if (triangle_index >= field->GetWalkmesh()->GetTriangles().size()){
-                    write_output_line_(
-                      "[WARNING] In field " + field->getName() + ": Map jump triangle ("
-                      + std::to_string(triangle_index) + ") out of bounds ("
-                      + std::to_string(field->GetWalkmesh()->GetTriangles().size()) + ")"
-                    );
-                    std::cerr << "[WARNING] In field " << field->getName()
-                      << ": Map jump triangle (" << triangle_index << ") out of bounds ("
-                      << field->GetWalkmesh()->GetTriangles().size() << ")" << std::endl;
-                    triangle_index = 0;
+                const auto& triangles = field->GetWalkmesh()->GetTriangles();
+                if (triangle_index >= triangles.size()){
+                    // Some map jumps of the original scripts have a triangle that is not in the walkmesh (pillar_3
+                    // to mds6_22). The one under the position is used instead, in the units the walkmesh is
+                    // written in.
+                    const float scale = GetFieldScaleFactor(this_field_id);
+                    const float x = gateway.destination.x / downscaler_next;
+                    const float y = gateway.destination.y / downscaler_next;
+                    const auto side = [x, y](const Ogre::Vector3& a, const Ogre::Vector3& b){
+                        return (x - b.x) * (a.y - b.y) - (a.x - b.x) * (y - b.y);
+                    };
+                    size_t under = triangles.size();
+                    for (size_t t = 0; t < triangles.size() && under == triangles.size(); t ++){
+                        const Ogre::Vector3 a = triangles[t].a / scale, b = triangles[t].b / scale;
+                        const Ogre::Vector3 c = triangles[t].c / scale;
+                        const float d1 = side(a, b), d2 = side(b, c), d3 = side(c, a);
+                        const bool negative = d1 < 0 || d2 < 0 || d3 < 0, positive = d1 > 0 || d2 > 0 || d3 > 0;
+                        if (!(negative && positive)) under = t;
+                    }
+                    const SpawnPointDb::Record& record = spawn_point_records[i];
+                    const std::string source = record.from_script
+                      ? "the script " + record.entity_name + ":" + record.script_function_name + " (address "
+                        + std::to_string(record.gateway_index_or_map_jump_address) + ")"
+                      : "the door " + std::to_string(record.gateway_index_or_map_jump_address);
+                    // Only reported when the position is not on the walkmesh either: those jumps are of the debug
+                    // rooms (blackbg1, blackbg4) or of scenes that place the player themselves.
+                    if (under == triangles.size()){
+                        write_output_line_(
+                          "[WARNING] In field " + field->getName() + ": the entrance from "
+                          + map_list_.at(record.field_id) + " (" + source + ") is on the walkmesh triangle "
+                          + std::to_string(triangle_index) + ", which the walkmesh doesn't have (it has "
+                          + std::to_string(triangles.size()) + "), at (" + std::to_string(gateway.destination.x) + ", "
+                          + std::to_string(gateway.destination.y) + "), which is not on the walkmesh."
+                        );
+                        triangle_index = 0;
+                    }
+                    else triangle_index = static_cast<unsigned int>(under);
                 }
                 const float z_of_triangle_with_id
                   = field->GetWalkmesh()->GetTriangles().at(triangle_index).a.z / GetFieldScaleFactor(this_field_id);

+ 24 - 5
src/installer/FieldTextWriter.cpp

@@ -37,12 +37,22 @@ void FieldTextWriter::Begin(std::string file_name){
 }
 
 u16 FieldTextWriter::GetU16LE(u32 offset){
-    if (offset+1 >= data_.size()) throw std::out_of_range("");
+    if (offset+1 >= data_.size()){
+        throw std::out_of_range(
+          "reading past the end of the script section (" + std::to_string(offset) + " of " + std::to_string(data_.size())
+          + " bytes)"
+        );
+    }
     return *reinterpret_cast<u16*>(&data_[offset]);
 }
 
 u8 FieldTextWriter::GetU8(u32 offset){
-    if (offset >= data_.size()) throw std::out_of_range("");
+    if (offset >= data_.size()){
+        throw std::out_of_range(
+          "reading past the end of the script section (" + std::to_string(offset) + " of " + std::to_string(data_.size())
+          + " bytes)"
+        );
+    }
     return data_[offset];
 }
 
@@ -64,8 +74,15 @@ void FieldTextWriter::Write(const std::vector<u8>& script_section_buffer, std::s
     if (tag_open_){
         logger_->Log("[ERROR exception]");
         logger_->Log("</dialog>\n");
+        tag_open_ = false;
     }
-    u16 dialogCount = GetU16LE(offset_to_sector + offset_to_dialogs);
+    // A field without texts can have its table of texts at the end of the section, with no room for it (nivgate3,
+    // nivl_4), or with bytes that are not a table (las4_42).
+    const u32 table = offset_to_sector + offset_to_dialogs;
+    if (table + 2 > data_.size()) return;
+    const auto fits = [this, table](u32 count){return table + 2 + count * 2 <= data_.size();};
+    u16 dialogCount = GetU16LE(table);
+    if (!fits(dialogCount)) dialogCount = 0;
     // The first string comes right after the table of offsets, so its offset says how many strings
     // there are. A field with 256 of them has a count that doesn't fit (it is read as 0), and the
     // field would have no texts at all.
@@ -73,7 +90,7 @@ void FieldTextWriter::Write(const std::vector<u8>& script_section_buffer, std::s
         const u16 first_offset = GetU16LE(offset_to_sector + offset_to_dialogs + 0x02);
         if (first_offset >= 0x02 && (first_offset % 2) == 0){
             const u16 count_from_table = (first_offset - 0x02) / 2;
-            if (count_from_table > dialogCount) dialogCount = count_from_table;
+            if (count_from_table > dialogCount && fits(count_from_table)) dialogCount = count_from_table;
         }
     }
     for (u16 i = 0; i <dialogCount; ++ i){
@@ -91,7 +108,9 @@ void FieldTextWriter::Write(const std::vector<u8>& script_section_buffer, std::s
         int colour_opened = 0;
         // Number of the next variable code of the dialog (see MPARA and MPRA2 in the scripts).
         int variable_count = 0;
-        for (unsigned char temp = 0x00;; ++ offset){
+        // A text ends with 0xFF, or at the end of the section: the empty texts of some fields have no end mark
+        // (life, life2).
+        for (unsigned char temp = 0x00; offset < data_.size(); ++ offset){
             temp = GetU8(offset);
             if (temp == 0xFF) break;
             if (temp == 0xE0 && english == true){

+ 18 - 4
src/installer/InstallCommandLine.cpp

@@ -151,8 +151,16 @@ namespace InstallCommandLine{
                 arguments.copy_data = false;
                 cli = true;
             }
-            else if (arg == "--discard-originals"){
-                arguments.keep_originals = false;
+            else if (arg == "--keep-originals"){
+                arguments.keep_originals = true;
+                cli = true;
+            }
+            else if (arg == "--clean"){
+                arguments.clean = true;
+                cli = true;
+            }
+            else if (arg == "--strict"){
+                arguments.strict = true;
                 cli = true;
             }
             else if (arg == "-i" || arg == "--iso"){
@@ -241,6 +249,7 @@ namespace InstallCommandLine{
             if (!arguments.iso.empty()) return Invalid("--verify checks an installation, it doesn't take an ISO.");
             if (preset_given || !added.empty() || !removed.empty())
                 return Invalid("--verify checks everything; it doesn't take a preset or parts.");
+            if (arguments.clean) return Invalid("--verify checks an installation, it doesn't delete it.");
             arguments.mode = Mode::VERIFY;
             return arguments;
         }
@@ -271,11 +280,15 @@ namespace InstallCommandLine{
           << "                           must already have them.\n"
           << "      --data-dir <dir>     The V-Gears 'data' folder to copy. Default: looked for next to\n"
           << "                           the installer and in the system.\n"
-          << "      --discard-originals  Delete the original files once converted.\n"
+          << "      --clean              Delete the data of a previous installation first. The saves, the\n"
+          << "                           controls, the game configuration and the videos are kept.\n"
+          << "      --keep-originals     Keep the original data once converted: the extracted disk, the\n"
+          << "                           temporary files and the original sounds, music and images.\n"
           << "      --ffmpeg <file>      Path to FFmpeg. Default: looked for in the 'tools' folder of the\n"
           << "                           installation and of the installer, then in the PATH.\n"
           << "      --timidity <file>    Path to TiMidity. Looked for like FFmpeg.\n"
           << "  -y, --yes                Continue when there are warnings or the audio tools are missing.\n"
+          << "      --strict             End with status 3 if the installation finished with errors in its log.\n"
           << "\n"
           << "Other options:\n"
           << "      --cli                Use the command line, not the window. Implied by any option above.\n"
@@ -286,7 +299,8 @@ namespace InstallCommandLine{
           << "Parts: " << PartNames() << ".\n"
           << "\n"
           << "Exit status: 0 if everything went well, 1 if the installation or the verification failed,\n"
-          << "2 if the command line is wrong.\n";
+          << "2 if the command line is wrong, 3 if it finished with errors and --strict was given, 130 if it\n"
+          << "was interrupted.\n";
         return usage.str();
     }
 

+ 13 - 2
src/installer/InstallCommandLine.h

@@ -114,9 +114,20 @@ namespace InstallCommandLine{
         std::string data_dir;
 
         /**
-         * True to keep the original data after converting it.
+         * True to keep the original data after converting it: the extracted install disk, the temporary files and
+         * the original sounds, music and images.
          */
-        bool keep_originals = true;
+        bool keep_originals = false;
+
+        /**
+         * True to delete the data of a previous installation in the directory first.
+         */
+        bool clean = false;
+
+        /**
+         * True to end with an error status when the installation finished with errors in its log.
+         */
+        bool strict = false;
 
         /**
          * Path to FFmpeg. Empty to look for it.

+ 54 - 0
src/installer/InstallLayout.cpp

@@ -13,10 +13,64 @@
  * GNU General Public License for more details.
  */
 
+#include <algorithm>
+#include <boost/filesystem.hpp>
+#include "common/InstallStamp.h"
 #include "InstallLayout.h"
 
 namespace InstallLayout{
 
+    namespace{
+
+        /**
+         * Removes a file or a directory with its contents, and counts what was removed.
+         */
+        void Remove(const boost::filesystem::path& path, CleanResult& result){
+            boost::system::error_code ec;
+            const auto removed = boost::filesystem::remove_all(path, ec);
+            if (ec) result.errors.push_back(path.string() + ": " + ec.message());
+            else result.removed += removed;
+        }
+
+    }
+
+    std::string OriginalDataDir(const std::string& root){return root + "original_data/";}
+
+    const std::vector<std::string>& CleanInstallKeptDataDirs(){
+        static const std::vector<std::string> dirs = {"config", "video"};
+        return dirs;
+    }
+
+    bool IsInstallation(const std::string& root){
+        boost::system::error_code ec;
+        return boost::filesystem::is_regular_file(root + "plugins.cfg", ec)
+          && boost::filesystem::is_regular_file(root + "resources.cfg", ec);
+    }
+
+    CleanResult CleanInstallation(const std::string& root){
+        namespace fs = boost::filesystem;
+        CleanResult result;
+        if (!IsInstallation(root)) return result;
+        boost::system::error_code ec;
+        if (fs::exists(OriginalDataDir(root), ec)) Remove(OriginalDataDir(root), result);
+        if (fs::exists(TempDir(root), ec)) Remove(TempDir(root), result);
+        // The record of the installations describes what was just deleted.
+        if (fs::exists(root + VGears::InstallStamp::FILE_NAME, ec)) Remove(root + VGears::InstallStamp::FILE_NAME, result);
+        const fs::path data(DataDir(root));
+        if (fs::is_directory(data, ec)){
+            const std::vector<std::string>& kept = CleanInstallKeptDataDirs();
+            std::vector<fs::path> entries;
+            for (fs::directory_iterator it(data, ec), end; !ec && it != end; it.increment(ec))
+                entries.push_back(it->path());
+            if (ec) result.errors.push_back(data.string() + ": " + ec.message());
+            for (const fs::path& entry : entries){
+                if (std::find(kept.begin(), kept.end(), entry.filename().string()) == kept.end())
+                    Remove(entry, result);
+            }
+        }
+        return result;
+    }
+
     std::string DataDir(const std::string& root){return root + "data/";}
 
     std::string TempDir(const std::string& root){return root + "temp/";}

+ 51 - 0
src/installer/InstallLayout.h

@@ -62,6 +62,57 @@ namespace InstallLayout{
      */
     std::vector<std::string> RemovableTempSubdirs();
 
+    /**
+     * Gets the directory where the installation disk is extracted.
+     *
+     * Its files are only read while installing.
+     *
+     * @param[in] root Installation directory, ending with '/'.
+     */
+    std::string OriginalDataDir(const std::string& root);
+
+    /**
+     * Directories of the game data (in <installation directory>/data) that a clean installation keeps: the
+     * configuration of the game, and the videos, which come from the game disks, not from the install disk.
+     */
+    const std::vector<std::string>& CleanInstallKeptDataDirs();
+
+    /**
+     * Tells if a directory is a V-Gears installation: it has the configuration files the installer copies.
+     *
+     * @param[in] root The directory, ending with '/'.
+     */
+    bool IsInstallation(const std::string& root);
+
+    /**
+     * Result of cleaning an installation.
+     */
+    struct CleanResult{
+
+        /**
+         * Number of files and directories removed.
+         */
+        unsigned long long removed = 0;
+
+        /**
+         * What could not be removed.
+         */
+        std::vector<std::string> errors;
+    };
+
+    /**
+     * Deletes what a previous installation wrote, so a new one starts from nothing.
+     *
+     * It removes the extracted disk, the temporary files, the record of the installations (install.info) and the
+     * game data, except the directories in
+     * {@see CleanInstallKeptDataDirs}. The rest of the installation directory (saves, controls, the configuration
+     * files of V-Gears and Ogre, logs) is kept. A directory that is not an installation ({@see IsInstallation}) is
+     * not touched.
+     *
+     * @param[in] root Installation directory, ending with '/'.
+     */
+    CleanResult CleanInstallation(const std::string& root);
+
     /**
      * Directories the game registers as resource locations, relative to the installation directory.
      */

+ 5 - 2
src/installer/InstallLog.cpp

@@ -49,7 +49,7 @@ class InstallLog::Tee : public std::streambuf{
             std::string line;
             {
                 std::lock_guard<std::mutex> lock(mutex_);
-                original_->sputc(static_cast<char>(c));
+                if (log_.echo_) original_->sputc(static_cast<char>(c));
                 if (c == '\n') line.swap(line_);
                 else line_ += static_cast<char>(c);
             }
@@ -100,8 +100,11 @@ void InstallLog::Close(){
     tee_err_.reset();
     std::lock_guard<std::mutex> lock(mutex_);
     if (file_.is_open()) file_.close();
+    echo_ = true;
 }
 
+void InstallLog::SetEcho(bool echo){echo_ = echo;}
+
 void InstallLog::SetSink(Sink sink){
     std::lock_guard<std::mutex> lock(mutex_);
     sink_ = std::move(sink);
@@ -127,7 +130,7 @@ void InstallLog::Add(const std::string& message, bool show){
         if (show) sink = sink_;
     }
     // Echo to the terminal without capturing the message again.
-    if (tee_out_) tee_out_->WriteOriginal(message + "\n");
+    if (tee_out_ && echo_) tee_out_->WriteOriginal(message + "\n");
     if (sink) sink(level, message);
 }
 

+ 16 - 0
src/installer/InstallLog.h

@@ -16,6 +16,7 @@
 #pragma once
 
 #include <fstream>
+#include <atomic>
 #include <functional>
 #include <iostream>
 #include <memory>
@@ -72,6 +73,16 @@ class InstallLog{
          */
         void SetSink(Sink sink);
 
+        /**
+         * Sets if the messages and the captured standard streams are written to the terminal.
+         *
+         * They are by default. A program that draws its own output (the progress line of the command line
+         * installer) turns it off and shows the messages it gets in the sink. Closing the log turns it on again.
+         *
+         * @param[in] echo True to write to the terminal.
+         */
+        void SetEcho(bool echo);
+
         /**
          * Adds a message.
          *
@@ -127,6 +138,11 @@ class InstallLog{
         void AddCaptured(const std::string& line);
 
         mutable std::mutex mutex_;
+
+        /**
+         * True to write the messages and the captured streams to the terminal.
+         */
+        std::atomic<bool> echo_{true};
         std::ofstream file_;
         std::string path_;
         Sink sink_;

+ 80 - 7
src/installer/InstallSteps.cpp

@@ -13,6 +13,7 @@
  * GNU General Public License for more details.
  */
 
+#include <algorithm>
 #include <iostream>
 #include <boost/filesystem.hpp>
 #include <QtCore/QCoreApplication>
@@ -26,10 +27,16 @@
 #include "common/DataDirectory.h"
 #include "common/OgrePlugins.h"
 #include "ExternalTools.h"
+#include "common/InstallStamp.h"
+#include "InstallCommandLine.h"
 #include "InstallLog.h"
 #include "InstallSteps.h"
 #include "MovieCamera.h"
 
+#ifndef VGEARS_INSTALLER_VERSION
+#define VGEARS_INSTALLER_VERSION "unknown"
+#endif
+
 #ifndef VGEARS_OGRE_PLUGIN_DIR
 #define VGEARS_OGRE_PLUGIN_DIR ""
 #endif
@@ -123,9 +130,16 @@ namespace InstallSteps{
     }
 
     PreflightResult RunPreflight(
-      DiskImage& disk_image, const QString& output, bool copy_data, const QString& game_data_dir
+      DiskImage& disk_image, const QString& output, bool copy_data, const QString& game_data_dir, bool clean
     ){
         PreflightResult result;
+        // A clean installation deletes the V-Gears data files too, so they must be copied again.
+        if (clean && !copy_data){
+            result.errors << QObject::tr(
+              "A clean installation deletes the V-Gears data files of the installation directory too: enable 'Copy "
+              "V-Gears data files'."
+            );
+        }
         const QString iso_path = QString::fromStdString(disk_image.getPath());
 
         // Input.
@@ -178,20 +192,35 @@ namespace InstallSteps{
         return result;
     }
 
+    VerifyPlugins PluginSearch(){
+        VerifyPlugins search;
+        search.executable_dir = QCoreApplication::applicationDirPath().toStdString();
+        search.ogre_version = std::to_string(OGRE_VERSION_MAJOR) + "." + std::to_string(OGRE_VERSION_MINOR) + "."
+          + std::to_string(OGRE_VERSION_PATCH);
+        return search;
+    }
+
     QStringList CheckVideoOutput(const QString& output){
         QStringList errors;
         CheckWritable(output, kRequiredVideoSpace, errors);
         return errors;
     }
 
-    bool CopyDirectory(const QString& src, const QString& dst){
+    bool CopyDirectory(const QString& src, const QString& dst, const std::function<void(float)>& progress){
         const QDir src_dir(src);
         if (!QDir().mkpath(dst)) return false;
         bool ok = true;
+        // The files are listed first, to know the progress.
+        QStringList files;
         QDirIterator it(src, QDir::Files | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
-        while (it.hasNext()){
-            const QString file = it.next();
-            const QString target = dst + "/" + src_dir.relativeFilePath(file);
+        while (it.hasNext()) files << it.next();
+        if (progress) progress(0);
+        for (int f = 0; f < files.size(); ++ f){
+            if (progress) progress(100.0f * f / files.size());
+            const QString& file = files[f];
+            const QString relative = src_dir.relativeFilePath(file);
+            const QString target = dst + "/" + relative;
+            if (relative.startsWith("data/config/") && QFile::exists(target)) continue;
             QDir().mkpath(QFileInfo(target).absolutePath());
             if (QFile::exists(target)) QFile::remove(target);
             if (!QFile::copy(file, target)){
@@ -199,9 +228,20 @@ namespace InstallSteps{
                 ok = false;
             }
         }
+        if (progress) progress(100);
         return ok;
     }
 
+    float OverallProgress(Phase phase, float progress){
+        const float value = std::max(0.0f, std::min(100.0f, progress));
+        switch (phase){
+            case Phase::EXTRACT: return value * 0.05f;
+            case Phase::COPY: return 5.0f + value * 0.01f;
+            case Phase::CONVERT: return 6.0f + value * 0.94f;
+        }
+        return value;
+    }
+
     std::vector<std::string> MissingRequiredFiles(DiskImage& disk_image){
         // TODO: Enumerate files or find some better way to do this.
         static const std::vector<std::string> required_files = {
@@ -224,7 +264,6 @@ namespace InstallSteps{
         };
         std::vector<std::string> missing;
         for (const std::string& file : required_files){
-            std::cout << "Checking for required file: " << file << std::endl;
             if (!disk_image.filePath(file)) missing.push_back(file);
         }
         return missing;
@@ -268,6 +307,41 @@ namespace InstallSteps{
         tools.directories.push_back(app_dir.toStdString());
     }
 
+    std::vector<std::string> PartNames(const InstallOptions& options){
+        std::vector<std::string> names;
+        for (const InstallCommandLine::Part& part : InstallCommandLine::Parts()){
+            if (options.*(part.option) && part.option != &InstallOptions::videos) names.push_back(part.name);
+        }
+        return names;
+    }
+
+    void MarkInstallStarted(const QString& output, const InstallOptions& options, const std::string& disk){
+        const boost::filesystem::path dir(output.toStdString());
+        VGears::InstallStamp::Stamp stamp;
+        VGears::InstallStamp::Read(dir, stamp);
+        VGears::InstallStamp::Start(stamp, PartNames(options), VGEARS_INSTALLER_VERSION, VGears::InstallStamp::Now(), disk);
+        if (!VGears::InstallStamp::Write(dir, stamp))
+            std::cout << "[WARNING] The installation record can't be written in " << dir.string() << std::endl;
+    }
+
+    void MarkInstallFinished(const QString& output){
+        const boost::filesystem::path dir(output.toStdString());
+        VGears::InstallStamp::Stamp stamp;
+        VGears::InstallStamp::Read(dir, stamp);
+        VGears::InstallStamp::Finish(stamp);
+        if (!VGears::InstallStamp::Write(dir, stamp))
+            std::cout << "[WARNING] The installation record can't be written in " << dir.string() << std::endl;
+    }
+
+    void MarkVideosInstalled(const QString& output){
+        const boost::filesystem::path dir(output.toStdString());
+        VGears::InstallStamp::Stamp stamp;
+        // Without a record there is no installation to add the videos to: one is made, marked as finished.
+        if (!VGears::InstallStamp::Read(dir, stamp)) stamp.complete = true;
+        stamp.parts["videos"] = VGears::InstallStamp::DATA_VERSION;
+        VGears::InstallStamp::Write(dir, stamp);
+    }
+
     DataInstaller::AdvancedOptions ToAdvancedOptions(const InstallOptions& options, bool keep_originals){
         DataInstaller::AdvancedOptions advanced;
         advanced.battle_data = options.battle_data;
@@ -282,7 +356,6 @@ namespace InstallSteps{
         advanced.wm = options.wm;
         advanced.wm_models = options.wm && options.wm_models;
         advanced.keep_originals = keep_originals;
-        advanced.clean_install = false;
         return advanced;
     }
 

+ 68 - 2
src/installer/InstallSteps.h

@@ -15,6 +15,7 @@
 
 #pragma once
 
+#include <functional>
 #include <string>
 #include <vector>
 #include <QtCore/QString>
@@ -22,6 +23,7 @@
 #include "DataInstaller.h"
 #include "DiskImage.h"
 #include "InstallOptions.h"
+#include "InstallVerifier.h"
 
 /**
  * Steps of an installation that don't depend on the user interface.
@@ -75,9 +77,10 @@ namespace InstallSteps{
      * @param[in] output Absolute installation directory, ending with '/'.
      * @param[in] copy_data True if the V-Gears data files will be copied.
      * @param[in] game_data_dir The V-Gears "data" folder to copy (only used if copy_data is true).
+     * @param[in] clean True if the data of a previous installation will be deleted first.
      */
     PreflightResult RunPreflight(
-      DiskImage& disk_image, const QString& output, bool copy_data, const QString& game_data_dir
+      DiskImage& disk_image, const QString& output, bool copy_data, const QString& game_data_dir, bool clean
     );
 
     /**
@@ -90,12 +93,43 @@ namespace InstallSteps{
      */
     QStringList CheckVideoOutput(const QString& output);
 
+    /**
+     * Gets where the verifier looks for the Ogre plugins: next to this program, with the Ogre version V-Gears was
+     * built with.
+     */
+    VerifyPlugins PluginSearch();
+
     /**
      * Recursively copies a directory, overwriting existing files.
      *
+     * The configuration of the game (data/config) is only copied if it isn't there: the user may have changed it.
+     *
+     * @param[in] src The directory to copy.
+     * @param[in] dst Where to copy it.
+     * @param[in] progress Receives the progress [0-100]. It can be empty.
      * @return True if every file was copied.
      */
-    bool CopyDirectory(const QString& src, const QString& dst);
+    bool CopyDirectory(
+      const QString& src, const QString& dst,
+      const std::function<void(float)>& progress = std::function<void(float)>()
+    );
+
+    /**
+     * Phases of an installation, for its progress.
+     */
+    enum class Phase{EXTRACT, COPY, CONVERT};
+
+    /**
+     * Gets the progress of a whole installation from the progress of one of its phases.
+     *
+     * The phases take a part of the progress that is about the part of the time they take: the extraction of the
+     * disk the first 5%, the copy of the V-Gears data files 1%, and the conversion the rest.
+     *
+     * @param[in] phase The phase.
+     * @param[in] progress Progress of the phase [0-100].
+     * @return Progress of the installation [0-100].
+     */
+    float OverallProgress(Phase phase, float progress);
 
     /**
      * Gets the files the installer needs that are not in an extracted install disk.
@@ -126,6 +160,38 @@ namespace InstallSteps{
      */
     void SetToolLocations(const QString& install_dir, const std::string& ffmpeg, const std::string& timidity);
 
+    /**
+     * Gets the names of the parts an installation installs, as in the command line ("fields"...).
+     *
+     * The videos are not installed from the install disk, so they are not included.
+     */
+    std::vector<std::string> PartNames(const InstallOptions& options);
+
+    /**
+     * Records in the installation directory that an installation has started (see VGears::InstallStamp).
+     *
+     * Until it is marked as finished, the game and the verifier say that the installation didn't finish.
+     *
+     * @param[in] output The installation directory, ending with '/'.
+     * @param[in] options What is installed.
+     * @param[in] disk The disk.
+     */
+    void MarkInstallStarted(const QString& output, const InstallOptions& options, const std::string& disk);
+
+    /**
+     * Records in the installation directory that the installation has finished.
+     *
+     * @param[in] output The installation directory, ending with '/'.
+     */
+    void MarkInstallFinished(const QString& output);
+
+    /**
+     * Records in the installation directory that the videos of a game disk are installed.
+     *
+     * @param[in] output The installation directory, ending with '/'.
+     */
+    void MarkVideosInstalled(const QString& output);
+
     /**
      * Converts the options of an installation to the options of the data installer.
      *

+ 51 - 9
src/installer/InstallVerifier.cpp

@@ -15,6 +15,15 @@
 
 #include "InstallVerifier.h"
 #include <boost/filesystem.hpp>
+#include "common/InstallStamp.h"
+#include "common/OgrePlugins.h"
+
+/**
+ * Directory with the Ogre plugins, found when V-Gears was built. Set by CMake (VGEARS_OGRE_PLUGIN_DIR).
+ */
+#ifndef VGEARS_OGRE_PLUGIN_DIR
+#define VGEARS_OGRE_PLUGIN_DIR ""
+#endif
 
 namespace fs = boost::filesystem;
 
@@ -41,15 +50,32 @@ namespace{
             }
 
             /**
-             * A file whose name starts with a prefix (a library with a version number) must exist in a directory.
+             * The Ogre plugins listed in plugins.cfg must be found where the game looks for them.
+             *
+             * @param[in] group The group of the problems.
+             * @param[in] search Where to look for them.
              */
-            void FileWithPrefix(const std::string& group, const std::string& dir, const std::string& prefix){
-                ++ result_.checked;
+            void OgrePlugins(const std::string& group, const VerifyPlugins& search){
+                if (search.ogre_version.empty()) return;
+                namespace plugins = VGears::OgrePlugins;
+                const fs::path file(root_ + "plugins.cfg");
                 boost::system::error_code ec;
-                for (fs::directory_iterator it(root_ + dir, ec), end; !ec && it != end; it.increment(ec)){
-                    if (it->path().filename().string().compare(0, prefix.size(), prefix) == 0) return;
+                // A missing plugins.cfg is already reported.
+                if (!fs::is_regular_file(file, ec)) return;
+                ++ result_.checked;
+                plugins::Config config;
+                if (!plugins::ReadConfig(file, config)){
+                    Fail(group, "plugins.cfg can't be read");
+                    return;
+                }
+                const std::vector<fs::path> directories = plugins::SearchDirectories(
+                  file.parent_path(), config.folder, fs::path(search.executable_dir), VGEARS_OGRE_PLUGIN_DIR
+                );
+                for (const std::string& name : config.plugins){
+                    ++ result_.checked;
+                    if (plugins::Find(name, directories, search.ogre_version).empty())
+                        Fail(group, "the Ogre plugin " + name + " is not in the installation directory or the system");
                 }
-                Fail(group, "no " + prefix + "* file in " + (dir.empty() ? "the installation directory" : dir));
             }
 
             /**
@@ -93,16 +119,32 @@ namespace{
 
 }
 
-VerifyResult VerifyInstallation(const std::string& root, const std::string& reference_dir){
+VerifyResult VerifyInstallation(
+  const std::string& root, const std::string& reference_dir, const VerifyPlugins& plugins
+){
     VerifyResult result;
     Checker check(root, result);
 
+    // The record of the installations: whether the last one finished, and whether a part is outdated.
+    const std::string installation = "Installation";
+    ++ result.checked;
+    bool recorded = false;
+    for (const std::string& problem : VGears::InstallStamp::Problems(fs::path(root), &recorded))
+        result.problems.push_back({installation, problem});
+    if (!recorded){
+        result.problems.push_back({
+          installation, "there is no record of the installation: it was made by an older installer, whose data may "
+          "be outdated. Install the data again."
+        });
+    }
+
     // Configuration, plugins and the files of the repository, which the game always needs.
     const std::string config = "Configuration";
     check.File(config, "plugins.cfg");
     check.File(config, "resources.cfg");
-    check.FileWithPrefix(config, "", "RenderSystem_GL");
-    check.FileWithPrefix(config, "", "Codec_STBI");
+    // The plugins don't have to be in the installation directory: the game also looks for them next to its
+    // executable and in the system.
+    check.OgrePlugins(config, plugins);
     const std::string game = "Game files";
     for (const char* file : {
       "data/config/config.cfg", "data/system/system.fontdef", "data/system/system.lua", "data/system/system.material",

+ 24 - 1
src/installer/InstallVerifier.h

@@ -55,6 +55,25 @@ struct VerifyResult{
     bool Ok() const{return problems.empty();}
 };
 
+/**
+ * How the Ogre plugins of an installation are looked for.
+ *
+ * They are looked for where the game looks for them (see VGears::OgrePlugins::SearchDirectories): the installation
+ * directory, the directory of the game executable and the system.
+ */
+struct VerifyPlugins{
+
+    /**
+     * Directory of the running program, usually the same as the game's. It can be empty.
+     */
+    std::string executable_dir;
+
+    /**
+     * The Ogre version, as "major.minor.patch": the plugins have it in their file names. Empty to not check them.
+     */
+    std::string ogre_version;
+};
+
 /**
  * Checks that an installation has everything the game needs.
  *
@@ -64,5 +83,9 @@ struct VerifyResult{
  * @param[in] root Installation directory.
  * @param[in] reference_dir V-Gears "data" folder of the game (the one copied to the installation). If not empty,
  * every file in it must exist in the installation too. It can be empty.
+ * @param[in] plugins Where the Ogre plugins listed in plugins.cfg are looked for. Without the Ogre version, the
+ * plugins are not checked.
  */
-VerifyResult VerifyInstallation(const std::string& root, const std::string& reference_dir = "");
+VerifyResult VerifyInstallation(
+  const std::string& root, const std::string& reference_dir = "", const VerifyPlugins& plugins = VerifyPlugins()
+);

+ 68 - 35
src/installer/MainWindow.cpp

@@ -51,11 +51,6 @@
 #include "MovieCamera.h"
 #include <ui_MainWindow.h>
 
-/**
- * Indicates if an installer has already been created.
- */
-static bool installer_created = false;
-
 MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), main_window_(new Ui::MainWindow){
     main_window_->setupUi(this);
     main_window_->advancedOptions->setVisible(main_window_->chk_advanced_options->isChecked());
@@ -126,6 +121,8 @@ void MainWindow::InitSettings(void){
 }
 
 void MainWindow::OpenInstallLog(const QString& dir, bool append){
+    // A new installation starts with an empty log window.
+    if (!append) main_window_->data_log->clear();
     InstallLog& install_log = InstallLog::Get();
     install_log.Open((dir + "installer.log").toStdString(), append);
     install_log.SetSink([this](InstallLog::Level level, const std::string& message){
@@ -235,7 +232,9 @@ void MainWindow::on_btn_verify_clicked(){
         QMessageBox::warning(this, tr("Verify install"), tr("The installation directory does not exist: %1").arg(dir));
         return;
     }
-    const VerifyResult result = VerifyInstallation(dir.toStdString(), InstallSteps::FindGameDataDir().toStdString());
+    const VerifyResult result = VerifyInstallation(
+      dir.toStdString(), InstallSteps::FindGameDataDir().toStdString(), InstallSteps::PluginSearch()
+    );
     // The game can start if its configuration and the V-Gears data files are there.
     bool can_launch = true;
     QString text;
@@ -344,12 +343,13 @@ void MainWindow::on_actionHelp_triggered(){
       "<li>Click <b>Install data</b>. The log shows the progress. Problems are shown in color and also written to "
       "<code>installer.log</code> in the installation directory.</li>"
       "</ol>"
-      "<p>The installation can only be done once per window. To install again, close the installer and open it "
-      "again.</p>"
       "<h3>Options</h3>"
       "<p>Select <b>Show advanced options</b> to choose what to install. <b>What to install</b> offers ready-made "
       "sets; choose <b>Custom</b> to pick the options by hand. Some options need others (for example the field "
-      "models need the field maps). <b>Clean install</b> deletes the data of a previous installation first. The "
+      "models need the field maps). <b>Clean install</b> deletes the data of a previous installation first; the "
+      "saves, the controls, the game configuration and the videos are kept. <b>Preserve original data</b> keeps "
+      "what the installer extracts and no longer needs (the install disk, temporary files and the original "
+      "sounds, music and images); without it, that is deleted at the end. The "
       "estimate under the options shows about how much disk space it needs.</p>"
       "<p>With <b>Copy V-Gears data files</b> the installer also copies the files that come with V-Gears (scripts, "
       "screens, fonts and configuration) to the installation directory.</p>"
@@ -460,9 +460,13 @@ void MainWindow::on_btn_data_run_clicked(){
         }
     }
 
-    // Check everything that can be checked before touching the disk.
-    InstallSteps::PreflightResult preflight = InstallSteps::RunPreflight(disk_image_, output, copy_data, game_data);
-    for (const std::string& problem : InstallRules::Problems(CurrentOptions(), QFile::exists(output + "data/fields/_fields.xml")))
+    // Check everything that can be checked before touching the disk. A clean installation deletes the field maps
+    // that are already installed.
+    const bool clean = main_window_->chk_clean_install->checkState() == Qt::Checked;
+    InstallSteps::PreflightResult preflight
+      = InstallSteps::RunPreflight(disk_image_, output, copy_data, game_data, clean);
+    const bool fields_installed = !clean && QFile::exists(output + "data/fields/_fields.xml");
+    for (const std::string& problem : InstallRules::Problems(CurrentOptions(), fields_installed))
         preflight.errors << QString::fromStdString(problem);
     if (!preflight.errors.isEmpty()){
         QMessageBox::critical(
@@ -480,8 +484,44 @@ void MainWindow::on_btn_data_run_clicked(){
     }
     // The audio is converted with external programs: say now, before anything is extracted, if they are missing.
     if (!ResolveMissingTools(CurrentOptions())) return;
+    // Everything is checked: the previous installation can be deleted.
+    if (clean && InstallLayout::IsInstallation(output.toStdString())){
+        const auto answer = QMessageBox::warning(
+          this, tr("Clean install"),
+          tr("The data of the installation in %1 will be deleted before installing. The saves, the controls, the "
+             "game configuration and the videos are kept.\n\nContinue?").arg(QDir::toNativeSeparators(output)),
+          QMessageBox::Yes | QMessageBox::No, QMessageBox::No
+        );
+        if (answer != QMessageBox::Yes) return;
+        const InstallLayout::CleanResult cleaned = InstallLayout::CleanInstallation(output.toStdString());
+        if (!cleaned.errors.empty()){
+            QStringList errors;
+            for (const std::string& error : cleaned.errors) errors << QString::fromStdString(error);
+            QMessageBox::critical(
+              this, tr("Clean install"),
+              tr("The previous installation could not be deleted:\n\n- %1").arg(errors.join("\n- "))
+            );
+            return;
+        }
+        main_window_->data_log->append(tr("Deleted the previous installation (%1 files and folders).").arg(cleaned.removed));
+    }
+    // From here on, the installation directory is being changed: until it finishes, the record says so.
+    install_dir_ = output;
+    InstallSteps::MarkInstallStarted(output, CurrentOptions(), disk_image_.getId());
     {
-        bool extraction_success = disk_image_.extractImage(output.toStdString());
+        // The extraction and the copy run here, in the window's thread: the progress is shown as they go, and the
+        // window is repainted, without taking the clicks (nothing can be started twice).
+        main_window_->data_progress_bar->setValue(0);
+        const auto show_phase = [this](InstallSteps::Phase phase, const QString& text){
+            return [this, phase, text](float value){
+                ShowProgress(InstallSteps::OverallProgress(phase, value));
+                main_window_->label_progress->setText(text);
+                QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
+            };
+        };
+        bool extraction_success = disk_image_.extractImage(
+          output.toStdString(), show_phase(InstallSteps::Phase::EXTRACT, tr("Extracting the install disk..."))
+        );
         if (!extraction_success) {
             QMessageBox::critical(this, tr("Extraction error"), tr("Failed to extract ISO file."));
             return;
@@ -510,7 +550,9 @@ void MainWindow::on_btn_data_run_clicked(){
         if (copy_data){
             main_window_->data_log->append(tr("Copying data files from %1...").arg(game_data));
             // Everything in the folder goes to the installation directory, and its "data" subfolder to <dir>/data.
-            if (!InstallSteps::CopyDirectory(game_data, output)){
+            if (!InstallSteps::CopyDirectory(
+              game_data, output, show_phase(InstallSteps::Phase::COPY, tr("Copying the V-Gears data files..."))
+            )){
                 QMessageBox::critical(
                   this, tr("Copy error"), tr("Failed to copy the V-Gears data files to the installation directory.")
                 );
@@ -533,14 +575,6 @@ void MainWindow::on_btn_data_run_clicked(){
             QMessageBox::critical(this, tr("Output error"), tr("Could not enter the installation directory."));
             return;
         }
-        if (installer_created){
-            // Due to the use of singletons, the installer can't be re-run.
-            // TODO: Verify that this is true, and if so, try to fix it.
-            QMessageBox::critical(
-              this, tr("Error"), tr("Please, fix the errors, and then close the installer before trying again.")
-            );
-            return;
-        }
         // Collect every message of the installation in one place: the log file, the log window and the summary.
         UpdateToolLocations(output);
         OpenInstallLog(output, false);
@@ -553,11 +587,9 @@ void MainWindow::on_btn_data_run_clicked(){
             if (Qt::Checked == main_window_->chk_videos->checkState()){
                 InstallLog::Get().Add(
                   "[WARNING] The install disk has no videos. To extract them, select game disk 1, 2 or 3 as the "
-                  "ISO and install again (with a new installer window)."
+                  "ISO and install again."
                 );
             }
-            installer_created = true;
-            install_started_ = true;
             const std::string output_path = QDir::toNativeSeparators(output).toStdString();
             const auto write_line = [this](const std::string log_line, int level, bool as_progress = false){
                 InstallLog::Get().Add(log_line);
@@ -569,7 +601,8 @@ void MainWindow::on_btn_data_run_clicked(){
                 }
             };
             // The installation runs in a worker thread so the window stays responsive. Ogre belongs to the thread
-            // that creates it, so the installer is created, run and destroyed there. Setting "BackgroundInstall" to false runs it in the UI thread, step by step from a timer.
+            // that creates it, so the installer is created, run and destroyed there. Setting "BackgroundInstall" to
+            // false runs it in the UI thread, step by step from a timer.
             background_ = settings_->value("BackgroundInstall", true).toBool();
             if (background_){
                 stop_requested_ = false;
@@ -585,7 +618,6 @@ void MainWindow::on_btn_data_run_clicked(){
             InstallLog::Get().Add(std::string("[ERROR] Installation failed: ") + ex.what());
             InstallLog::Get().Close();
             installer_.reset();
-            installer_created = false;
             OnInstallStopped();
             QMessageBox::critical(this, tr("Installation error"), ex.what());
         }
@@ -597,8 +629,7 @@ void MainWindow::on_chk_advanced_options_stateChanged(){
 }
 
 void MainWindow::EnableUi(bool enable){
-    // The installer can't run twice, so once an installation has started the button never comes back.
-    main_window_->btn_data_run->setEnabled(enable && !install_started_);
+    main_window_->btn_data_run->setEnabled(enable);
     main_window_->btn_close->setEnabled(enable);
     main_window_->actionExit->setEnabled(enable);
     main_window_->label_tools->setEnabled(enable);
@@ -608,7 +639,6 @@ void MainWindow::EnableUi(bool enable){
     main_window_->btn_data_src->setEnabled(enable);
     main_window_->line_data_dst->setEnabled(enable);
     main_window_->btn_data_dst->setEnabled(enable);
-    main_window_->data_progress_bar->setValue(0);
     // In background mode the worker thread does the work, so there is nothing to poll.
     if (!enable && !background_) timer_->start(0);
     else timer_->stop();
@@ -619,6 +649,7 @@ void MainWindow::OnInstallStarted(){EnableUi(false);}
 void MainWindow::OnInstallStopped(){EnableUi(true);}
 
 void MainWindow::StartVideoExtraction(const QString& output){
+    main_window_->data_progress_bar->setValue(0);
     // Only the output directory is needed: no plugins, no configuration, no Ogre.
     const QStringList errors = InstallSteps::CheckVideoOutput(output);
     if (!errors.isEmpty()){
@@ -653,10 +684,11 @@ void MainWindow::StartVideoExtraction(const QString& output){
             error = ex.what();
         }
         if (stop_requested_) return;
-        QMetaObject::invokeMethod(this, [this, ok, error, extracted, skipped](){
+        QMetaObject::invokeMethod(this, [this, ok, error, extracted, skipped, output](){
             if (worker_.joinable()) worker_.join();
             if (ok && error.empty()){
                 ShowProgress(100);
+                InstallSteps::MarkVideosInstalled(output);
                 InstallLog::Get().Add(
                   "Videos extracted: " + std::to_string(extracted) + " new, " + std::to_string(skipped)
                   + " already installed."
@@ -808,7 +840,8 @@ void MainWindow::RunInstallation(
             const auto now = std::chrono::steady_clock::now();
             if (progress >= 100 || now - last_shown > std::chrono::milliseconds(100)){
                 last_shown = now;
-                QMetaObject::invokeMethod(this, [this, progress](){ShowProgress(progress);}, Qt::QueuedConnection);
+                const float overall = InstallSteps::OverallProgress(InstallSteps::Phase::CONVERT, progress);
+                QMetaObject::invokeMethod(this, [this, overall](){ShowProgress(overall);}, Qt::QueuedConnection);
             }
         }
     }
@@ -827,14 +860,13 @@ void MainWindow::RunInstallation(
         if (worker_.joinable()) worker_.join();
         if (finished){
             launch_available_ = true;
+            InstallSteps::MarkInstallFinished(install_dir_);
             OnInstallStopped();
             InstallLog::Get().Close();
         }
         else{
             InstallLog::Get().Add("[ERROR] Installation failed: " + error);
             InstallLog::Get().Close();
-            // If the installer could not even be created it can be tried again.
-            if (!created) installer_created = false;
             OnInstallStopped();
             QMessageBox::critical(this, created ? tr("Data conversion exception") : tr("Installation error"), QString::fromStdString(error));
         }
@@ -844,9 +876,10 @@ void MainWindow::RunInstallation(
 void MainWindow::DoProgress(){
     try{
         const float progress = installer_->Progress();
-        ShowProgress(progress);
+        ShowProgress(InstallSteps::OverallProgress(InstallSteps::Phase::CONVERT, progress));
         if (progress >= 100){
             launch_available_ = true;
+            InstallSteps::MarkInstallFinished(install_dir_);
             OnInstallStopped();
             InstallLog::Get().Close();
         }

+ 5 - 5
src/installer/MainWindow.h

@@ -289,11 +289,6 @@ class MainWindow : public QMainWindow{
          */
         bool background_ = false;
 
-        /**
-         * True once an installation has started. The installer can only run once.
-         */
-        bool install_started_ = false;
-
         /**
          * True while the option rules are being applied, to avoid applying them recursively.
          */
@@ -315,4 +310,9 @@ class MainWindow : public QMainWindow{
          * The selected disk image.
          */
         DiskImage disk_image_;
+
+        /**
+         * The installation directory of the installation in progress, ending with '/'.
+         */
+        QString install_dir_;
 };

+ 3 - 3
src/installer/MainWindow.ui

@@ -570,7 +570,7 @@
             </size>
            </property>
            <property name="toolTip">
-            <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;span style=&quot; font-weight:700;&quot;&gt;Delete previously installed files.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br/&gt;&lt;/p&gt;&lt;p&gt;Performs a clean installation, unconditionally removing all previously installed data.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+            <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;b&gt;Delete the previous installation first.&lt;/b&gt;&lt;br&gt;&lt;br&gt;Before installing, the data of a previous installation in the installation directory is deleted: the converted game data, the temporary files and the extracted disk. The saves, the controls, the game configuration and the videos are kept.&lt;br&gt;&lt;br&gt;It needs 'Copy V-Gears data files', since the V-Gears data files are deleted too.&lt;/body&gt;&lt;/html&gt;</string>
            </property>
            <property name="text">
             <string>Clean install</string>
@@ -728,13 +728,13 @@
             </size>
            </property>
            <property name="toolTip">
-            <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;b&gt;Don't delete original data after installation.&lt;/b&gt;&lt;br&gt;&lt;br&gt;The installer extracts some original data from the installation disk, such as MIDI sounds, TEX images, and some LGP archives. If checked, this data will not be deleted when the installation is complete.&lt;br&gt;&lt;br&gt;This data is never used by V-Gears, and there is usually no need to check this.&lt;/body&gt;&lt;/html&gt;</string>
+            <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;b&gt;Keep the original data after the installation.&lt;/b&gt;&lt;br&gt;&lt;br&gt;The installer extracts the install disk and some original data (WAV sounds, MIDI music, TEX images and temporary model files) to convert it. Without this option, all of it is deleted when the installation is complete.&lt;br&gt;&lt;br&gt;V-Gears never uses this data, so there is usually no need to check this.&lt;/body&gt;&lt;/html&gt;</string>
            </property>
            <property name="text">
             <string>Preserve original data</string>
            </property>
            <property name="checked">
-            <bool>true</bool>
+            <bool>false</bool>
            </property>
           </widget>
           <widget class="QCheckBox" name="chk_fields">

+ 4 - 6
src/installer/MediaDataInstaller.cpp

@@ -1321,10 +1321,10 @@ bool MediaDataInstaller::InstallFonts(){
     WindowFonts::IndexImage window;
     WindowFonts::IndexImage text;
     for (u32 i = 0; i < 2; i ++){
-        std::unique_ptr<File> tim(window_.ExtractGZip(i));
-        if (tim == nullptr) return false;
-        std::vector<u8> buffer(tim->GetFileSize());
-        tim->GetFileBuffer(buffer.data(), 0, buffer.size());
+        const File tim = window_.ExtractGZip(i);
+        if (tim.GetFileSize() == 0) return false;
+        std::vector<u8> buffer(tim.GetFileSize());
+        tim.GetFileBuffer(buffer.data(), 0, buffer.size());
         if (!WindowFonts::ReadTim4(buffer.data(), buffer.size(), i == 0 ? window : text)) return false;
     }
     const std::string font_dir = data_dir_ + "fonts/";
@@ -1372,12 +1372,10 @@ bool MediaDataInstaller::InstallSounds(){
               [ffmpeg, wav, ogg](std::string* error){return ExternalTools::ConvertToOgg(ffmpeg, wav, ogg, error);},
               [wav, keep](){if (!keep) std::remove(wav.c_str());}
             );
-            std::cout << "    ADD SOUND " << processed_sounds_ << ".ogg" << std::endl;
             sounds_.push_back("audio/sounds/" + std::to_string(processed_sounds_) + ".ogg");
         }
         else{
             sounds_.push_back("audio/sounds/INVALID.ogg");
-            std::cout << "    -- ADD SOUND INVALID.ogg" << std::endl;
         }
     }
     processed_sounds_ ++;

+ 2 - 2
src/installer/WorldInstaller.cpp

@@ -44,8 +44,8 @@ std::string WorldInstaller::TERRAIN_MODELS_DIR("models/world/terrain");
 
 WorldInstaller::WorldInstaller(
   const DiskImage& disk_image, const std::string output_dir,
-  const bool keep_originals, Ogre::ResourceGroupManager* res_mgr
-): disk_image_(disk_image), output_dir_(output_dir), data_dir_(output_dir + "data/"), keep_originals_(keep_originals), res_mgr_(res_mgr) {}
+  Ogre::ResourceGroupManager* res_mgr
+): disk_image_(disk_image), output_dir_(output_dir), data_dir_(output_dir + "data/"), res_mgr_(res_mgr) {}
 
 WorldInstaller::~WorldInstaller(){}
 

+ 1 - 9
src/installer/WorldInstaller.h

@@ -35,13 +35,10 @@ class WorldInstaller{
          *
          * @param[in] disk_image Disk image to extract the data from.
          * @param[in] output_dir Path to the directory of the installation data.
-         * @param[in] keep_originals True to keep original data after
-         * conversion, false to remove.
          * @param[in] res_mgr The application resource manager.
          */
         WorldInstaller(
-          const DiskImage& disk_image, const std::string output_dir,
-          const bool keep_originals, Ogre::ResourceGroupManager* res_mgr
+          const DiskImage& disk_image, const std::string output_dir, Ogre::ResourceGroupManager* res_mgr
         );
 
         /**
@@ -347,11 +344,6 @@ class WorldInstaller{
          */
         std::string data_dir_;
 
-        /**
-         * If true, original files will not be deleted after conversion.
-         */
-        bool keep_originals_;
-
         /**
          * Number of maps already processed.
          */

+ 54 - 70
src/installer/common/BinGZipFile.cpp

@@ -39,82 +39,66 @@ BinGZipFile::BinGZipFile(u8* buffer, u32 offset, u32 length):
 
 BinGZipFile::~BinGZipFile(){}
 
-File* BinGZipFile::ExtractGZip(u32 file_index){
-    if (file_index >= file_count_) return NULL;
-    u32 extract_size = 256 * 1024;
-    u8* extract_buffer = static_cast<u8*>(malloc(extract_size));
-    int ret;
-    z_stream strm;
-    u32 offset = InnerGetFileOffset(file_index);
-
-    strm.zalloc = Z_NULL; // Used to allocate the internal state.
-    strm.zfree = Z_NULL; // Used to free the internal state.
-    strm.opaque = Z_NULL; // Private data object passed to zalloc and zfree.
-    strm.next_in = buffer_ + offset; //Next input byte.
-    strm.avail_in = buffer_size_; // Number of bytes available at next_in.
-    strm.next_out = extract_buffer; // Next output byte should be put there.
-    strm.avail_out = extract_size; // Remaining free space at next_out.
-    ret = inflateInit2(&strm, 15 + 32);
+bool BinGZipFile::Inflate(const u8* data, size_t size, std::vector<u8>& out, std::string& error){
+    out.assign(256 * 1024, 0);
+    z_stream strm{};
+    strm.zalloc = Z_NULL;
+    strm.zfree = Z_NULL;
+    strm.opaque = Z_NULL;
+    strm.next_in = const_cast<u8*>(data);
+    strm.avail_in = static_cast<uInt>(size);
+    strm.next_out = out.data();
+    strm.avail_out = static_cast<uInt>(out.size());
+    int ret = inflateInit2(&strm, 15 + 32);
     if (ret != Z_OK){
-        switch (ret){
-            case Z_MEM_ERROR:
-                inflateEnd(&strm);
-                LOGGER->Log("Warning: inflateInit2 - Z_MEM_ERROR in file " + file_name_);
-                break;
-            case Z_STREAM_ERROR:
-                inflateEnd(&strm);
-                LOGGER->Log("Warning: inflateInit2 - Z_STREAM_ERROR in file " + file_name_);
-                break;
-            default:
-                inflateEnd(&strm);
-                LOGGER->Log("Warning: inflateInit2 - unknown error in file " + file_name_);
-        }
-        return NULL;
+        error = ret == Z_MEM_ERROR ? "inflateInit2: Z_MEM_ERROR"
+          : (ret == Z_STREAM_ERROR ? "inflateInit2: Z_STREAM_ERROR" : "inflateInit2: unknown error");
+        out.clear();
+        return false;
     }
     do{
-        if (strm.next_out == NULL){
+        ret = inflate(&strm, Z_NO_FLUSH);
+        if (ret == Z_NEED_DICT || ret == Z_DATA_ERROR || ret == Z_MEM_ERROR || ret == Z_STREAM_ERROR){
+            error = ret == Z_NEED_DICT ? "inflate: Z_NEED_DICT"
+              : (ret == Z_DATA_ERROR ? "inflate: Z_DATA_ERROR"
+              : (ret == Z_MEM_ERROR ? "inflate: Z_MEM_ERROR" : "inflate: Z_STREAM_ERROR"));
             inflateEnd(&strm);
-            LOGGER->Log("Warning: strm.next_out == NULL in file " + file_name_);
-            return NULL;
+            out.clear();
+            return false;
         }
-        ret = inflate(&strm, Z_NO_FLUSH);
-        assert(ret != Z_STREAM_ERROR);
-        switch (ret){
-            case Z_NEED_DICT:
-                inflateEnd(&strm);
-                LOGGER->Log("Warning: inflate - Z_NEED_DICT in file " + file_name_);
-                return NULL;
-            case Z_DATA_ERROR:
-                inflateEnd(&strm);
-                LOGGER->Log("Warning: inflate - Z_DATA_ERROR in file " + file_name_);
-                return NULL;
-            case Z_MEM_ERROR:
-                inflateEnd(&strm);
-                LOGGER->Log("Warning: inflate - Z_MEM_ERROR in file " + file_name_);
-                return NULL;
+        if (ret == Z_STREAM_END) break;
+        if (strm.avail_out == 0){
+            // The output is full: make it twice as big.
+            const size_t used = strm.total_out;
+            out.resize(out.size() * 2);
+            strm.next_out = out.data() + used;
+            strm.avail_out = static_cast<uInt>(out.size() - used);
         }
-
-        if (ret != Z_STREAM_END){
-            extract_buffer = static_cast<u8*>(realloc(extract_buffer, extract_size * 2));
-            if (extract_buffer == NULL){
-                inflateEnd(&strm);
-                LOGGER->Log("Warning: extract_buffer == NULL in file " + file_name_);
-                return NULL;
-            }
-            strm.next_out = static_cast<u8*>(extract_buffer + extract_size);
-            strm.avail_out = extract_size;
-            extract_size *= 2;
+        else if (strm.avail_in == 0){
+            // Room to write but nothing left to read: the data is cut.
+            error = "the compressed data is incomplete";
+            inflateEnd(&strm);
+            out.clear();
+            return false;
         }
-    } while (ret != Z_STREAM_END);
-    extract_size = extract_size - strm.avail_out;
-    (void)inflateEnd(&strm);
-    if (ret != Z_STREAM_END){
-        LOGGER->Log("Warning: ret != Z_STREAM_END in file " + file_name_);
-        return NULL;
+    } while (true);
+    out.resize(strm.total_out);
+    inflateEnd(&strm);
+    return true;
+}
+
+File BinGZipFile::ExtractGZip(u32 file_index){
+    if (file_index >= file_count_) return File();
+    const u32 offset = InnerGetFileOffset(file_index);
+    if (offset >= GetFileSize()) return File();
+    std::vector<u8> out;
+    std::string error;
+    if (!Inflate(buffer_.data() + offset, GetFileSize() - offset, out, error)){
+        LOGGER->Log("Warning: " + error + " in file " + file_name_);
+        return File();
     }
-    File* file = new File(extract_buffer, 0, extract_size);
-    free(extract_buffer);
-    return file;
+    if (out.empty()) return File();
+    return File(out.data(), 0, static_cast<u32>(out.size()));
 }
 
 u32 BinGZipFile::GetNumberOfFiles(){return file_count_;}
@@ -122,7 +106,7 @@ u32 BinGZipFile::GetNumberOfFiles(){return file_count_;}
 void BinGZipFile::InnerGetNumberOfFiles(){
     file_count_ = 0;
     // Each file has a 6 byte header, then the GZip data, whose header is checked: stop when they don't fit.
-    for (u32 pointer = 0; pointer + 6 + 8 <= buffer_size_;){
+    for (u32 pointer = 0; pointer + 6 + 8 <= GetFileSize();){
         u16 temp = GetU16LE(pointer);
         if (temp == 0xFFFF) temp = 0; // Hack to deal with scene.bin
         pointer += 6;
@@ -142,7 +126,7 @@ void BinGZipFile::InnerGetNumberOfFiles(){
 u32 BinGZipFile::InnerGetFileOffset(u32 file_index){
     if (file_index >= file_count_) return 0;
     u32 current_file = 0;
-    for (u32 pointer = 0; pointer + 6 + 8 <= buffer_size_;){
+    for (u32 pointer = 0; pointer + 6 + 8 <= GetFileSize();){
         u16 temp = GetU16LE(pointer);
         pointer += 6;
         // Condition for GZip header

+ 17 - 3
src/installer/common/BinGZipFile.h

@@ -15,6 +15,9 @@
 
 #pragma once
 
+#include <string>
+#include <vector>
+
 #include "common/File.h"
 
 /**
@@ -65,10 +68,21 @@ class BinGZipFile : public File{
          * Extracts a file from the compressed BIN file.
          *
          * @param[in] file_index The index of the file to extract.
-         * @return The extracted file, or NULL if there is no file at the
-         * specified index.
+         * @return The extracted file. It is empty if there is no file at the specified index, or it can't be
+         * extracted.
+         */
+        File ExtractGZip(u32 file_index);
+
+        /**
+         * Decompresses GZip data.
+         *
+         * @param[in] data The compressed data.
+         * @param[in] size Size of the compressed data.
+         * @param[out] out The decompressed data.
+         * @param[out] error What went wrong, if it fails.
+         * @return True if the data was decompressed.
          */
-        File* ExtractGZip(u32 file_index);
+        static bool Inflate(const u8* data, size_t size, std::vector<u8>& out, std::string& error);
 
         /**
          * Counts the number of files packed in the compressed BIN file.

+ 1 - 0
test/CMakeLists.txt

@@ -290,6 +290,7 @@ add_executable(v-gears-installer-tests
     common/DataDirectory.cpp
     common/OgrePlugins.cpp
     ${CMAKE_SOURCE_DIR}/src/common/DataDirectory.cpp
+    ${CMAKE_SOURCE_DIR}/src/common/InstallStamp.cpp
     ${CMAKE_SOURCE_DIR}/src/common/OgrePlugins.cpp
     installer/InstallLogic.cpp
     installer/ExternalTools.cpp

+ 145 - 8
test/installer/InstallLogic.cpp

@@ -23,6 +23,8 @@
 #include "installer/InstallLog.h"
 #include "installer/InstallOptions.h"
 #include "installer/InstallVerifier.h"
+#include "common/InstallStamp.h"
+#include "common/OgrePlugins.h"
 #include "installer/TaskPool.h"
 #include "installer/VideoFiles.h"
 #include <atomic>
@@ -308,13 +310,26 @@ BOOST_AUTO_TEST_CASE(EmptyDirectoryMissesEverything){
 
 BOOST_AUTO_TEST_CASE(ConfigurationAndPlugins){
     TempDir dir;
-    dir.Touch("plugins.cfg");
-    dir.Touch("resources.cfg");
     BOOST_CHECK(HasProblem(VerifyInstallation(dir.Root()), "Configuration"));
-    // The plugins have a version suffix.
-    dir.Touch("RenderSystem_GL.so.1.12.10");
-    dir.Touch("Codec_STBI.so.1.12.10");
+    // A plugin that can't be in the system, so only the given directories count.
+    const std::string plugin = "Plugin_VGearsVerifierTest";
+    VerifyPlugins search;
+    search.ogre_version = "1.2.3";
+    const std::string file_name = VGears::OgrePlugins::FileNames(plugin, search.ogre_version).front();
+    std::ofstream(dir.path.string() + "/plugins.cfg") << "Plugin=" << plugin << "\n";
+    dir.Touch("resources.cfg");
+    BOOST_CHECK(HasProblem(VerifyInstallation(dir.Root(), "", search), "Configuration"));
+    // Without the Ogre version the plugins are not checked.
     BOOST_CHECK(!HasProblem(VerifyInstallation(dir.Root()), "Configuration"));
+    // Next to the executable, as the game looks for it there too.
+    TempDir executable;
+    executable.Touch(file_name);
+    search.executable_dir = executable.path.string();
+    BOOST_CHECK(!HasProblem(VerifyInstallation(dir.Root(), "", search), "Configuration"));
+    // In the installation directory.
+    search.executable_dir.clear();
+    dir.Touch(file_name);
+    BOOST_CHECK(!HasProblem(VerifyInstallation(dir.Root(), "", search), "Configuration"));
 }
 
 BOOST_AUTO_TEST_CASE(RootWithoutTrailingSlash){
@@ -597,7 +612,9 @@ BOOST_AUTO_TEST_CASE(CommandLineInstallDefaults){
     BOOST_CHECK_EQUAL(a.iso, "disk.iso");
     BOOST_CHECK(a.output.empty());
     BOOST_CHECK(a.copy_data);
-    BOOST_CHECK(a.keep_originals);
+    BOOST_CHECK(!a.keep_originals);
+    BOOST_CHECK(!a.clean);
+    BOOST_CHECK(!a.strict);
     BOOST_CHECK(!a.yes);
     // Everything, except the videos, which are not on the install disk.
     const InstallOptions o = a.options;
@@ -608,12 +625,17 @@ BOOST_AUTO_TEST_CASE(CommandLineInstallDefaults){
 
 BOOST_AUTO_TEST_CASE(CommandLineInstallerOptionsImplyCli){
     using namespace InstallCommandLine;
-    const Arguments a = Parse({"-i", "disk.iso", "-o", "/tmp/vg", "-y", "--no-copy-data", "--discard-originals"});
+    const Arguments a = Parse({"-i", "disk.iso", "-o", "/tmp/vg", "-y", "--no-copy-data", "--keep-originals", "--clean"});
     BOOST_REQUIRE(a.mode == Mode::INSTALL);
     BOOST_CHECK_EQUAL(a.output, "/tmp/vg");
     BOOST_CHECK(a.yes);
     BOOST_CHECK(!a.copy_data);
-    BOOST_CHECK(!a.keep_originals);
+    BOOST_CHECK(a.keep_originals);
+    BOOST_CHECK(a.clean);
+    // Each of them is enough to use the command line.
+    BOOST_CHECK(Parse({"--clean"}).mode == Mode::INVALID); // No ISO, but not the window.
+    BOOST_CHECK(Parse({"--keep-originals"}).mode == Mode::INVALID);
+    BOOST_CHECK(Parse({"-i", "d.iso", "--strict"}).strict);
     // "--option=value" works too.
     BOOST_CHECK_EQUAL(Parse({"--iso=other.iso"}).iso, "other.iso");
 }
@@ -646,6 +668,9 @@ BOOST_AUTO_TEST_CASE(CommandLineErrors){
     BOOST_CHECK(Parse({"-i", "d.iso", "-p", "custom", "--with", "field-models"}).mode == Mode::INVALID);
     BOOST_CHECK(Parse({"--verify", "-i", "d.iso"}).mode == Mode::INVALID);
     BOOST_CHECK(Parse({"--verify", "--with", "music"}).mode == Mode::INVALID);
+    BOOST_CHECK(Parse({"--verify", "--clean"}).mode == Mode::INVALID);
+    // The old name of the option is gone.
+    BOOST_CHECK(Parse({"-i", "d.iso", "--discard-originals"}).mode == Mode::INVALID);
 }
 
 BOOST_AUTO_TEST_CASE(CommandLineOtherModes){
@@ -658,3 +683,115 @@ BOOST_AUTO_TEST_CASE(CommandLineOtherModes){
     BOOST_CHECK(Parse({"--list-parts"}).mode == Mode::LIST_PARTS);
     BOOST_CHECK(!Usage("v-gears-installer").empty());
 }
+
+// Clean installation.
+
+BOOST_AUTO_TEST_CASE(CleanInstallationDeletesTheDataAndKeepsTheRest){
+    TempDir dir;
+    const std::string root = dir.Root();
+    for (const char* file : {
+      "plugins.cfg", "resources.cfg", "v-gears.cfg", "controls.cfg", "installer.log", "save/0.xml",
+      "data/config/config.cfg", "data/video/opening/movie.xml", "data/fields/md1_1/map.xml",
+      "data/models/fields/aerisflowers.mesh", "data/audio/sounds/1.ogg", "data/scripts/x.lua",
+      "temp/char/cbba.rsd", "temp/world_models/a.p", "original_data/ff7/ff7.exe", "install.info"
+    }) dir.Touch(file);
+    const InstallLayout::CleanResult result = InstallLayout::CleanInstallation(root);
+    BOOST_CHECK(result.errors.empty());
+    BOOST_CHECK(result.removed > 0);
+    // Kept.
+    for (const char* file : {
+      "plugins.cfg", "resources.cfg", "v-gears.cfg", "controls.cfg", "installer.log", "save/0.xml",
+      "data/config/config.cfg", "data/video/opening/movie.xml"
+    }) BOOST_CHECK_MESSAGE(fs::exists(dir.path / file), std::string("kept: ") + file);
+    // Deleted.
+    for (const char* path : {"data/fields", "data/models", "data/audio", "data/scripts", "temp", "original_data", "install.info"})
+        BOOST_CHECK_MESSAGE(!fs::exists(dir.path / path), std::string("deleted: ") + path);
+    BOOST_CHECK(fs::is_directory(dir.path / "data"));
+}
+
+BOOST_AUTO_TEST_CASE(CleanInstallationDoesNotTouchOtherDirectories){
+    // Without the configuration files it is not an installation, and nothing is deleted.
+    TempDir dir;
+    dir.Touch("data/my_files/document.txt");
+    dir.Touch("temp/notes.txt");
+    BOOST_CHECK(!InstallLayout::IsInstallation(dir.Root()));
+    const InstallLayout::CleanResult result = InstallLayout::CleanInstallation(dir.Root());
+    BOOST_CHECK_EQUAL(result.removed, 0u);
+    BOOST_CHECK(fs::exists(dir.path / "data/my_files/document.txt"));
+    BOOST_CHECK(fs::exists(dir.path / "temp/notes.txt"));
+}
+
+BOOST_AUTO_TEST_CASE(OriginalDataIsInsideTheInstallationDirectory){
+    BOOST_CHECK_EQUAL(InstallLayout::OriginalDataDir("/x/"), "/x/original_data/");
+}
+
+// Record of the installations.
+
+BOOST_AUTO_TEST_CASE(InstallStampIsWrittenAndRead){
+    namespace stamp = VGears::InstallStamp;
+    TempDir dir;
+    stamp::Stamp written;
+    stamp::Start(written, {"kernel", "fields"}, "1.2.3", "2026-11-26 10:00:00", "Install Disk");
+    BOOST_REQUIRE(stamp::Write(dir.path, written));
+    stamp::Stamp read;
+    BOOST_REQUIRE(stamp::Read(dir.path, read));
+    BOOST_CHECK(!read.complete);
+    BOOST_CHECK_EQUAL(read.installer, "1.2.3");
+    BOOST_CHECK_EQUAL(read.date, "2026-11-26 10:00:00");
+    BOOST_CHECK_EQUAL(read.disk, "Install Disk");
+    BOOST_CHECK(read.installing == std::vector<std::string>({"kernel", "fields"}));
+    stamp::Finish(read);
+    BOOST_REQUIRE(stamp::Write(dir.path, read));
+    BOOST_REQUIRE(stamp::Read(dir.path, read));
+    BOOST_CHECK(read.complete);
+    BOOST_CHECK(read.installing.empty());
+    BOOST_CHECK_EQUAL(read.parts["kernel"], stamp::DATA_VERSION);
+    BOOST_CHECK_EQUAL(read.parts["fields"], stamp::DATA_VERSION);
+    BOOST_CHECK(stamp::Outdated(read).empty());
+    BOOST_CHECK(stamp::Problems(dir.path).empty());
+    // Without a file, there is no record.
+    TempDir empty;
+    BOOST_CHECK(!stamp::Read(empty.path, read));
+    bool found = true;
+    BOOST_CHECK(stamp::Problems(empty.path, &found).empty());
+    BOOST_CHECK(!found);
+}
+
+BOOST_AUTO_TEST_CASE(InstallStampReportsUnfinishedAndOldInstallations){
+    namespace stamp = VGears::InstallStamp;
+    TempDir dir;
+    stamp::Stamp record;
+    // A complete installation, then one of other parts that is interrupted.
+    stamp::Start(record, {"kernel"}, "1", "a", "disk");
+    stamp::Finish(record);
+    stamp::Start(record, {"battle-data"}, "1", "b", "disk");
+    BOOST_REQUIRE(stamp::Write(dir.path, record));
+    BOOST_CHECK_EQUAL(stamp::Problems(dir.path).size(), 1u);
+    BOOST_CHECK(stamp::Outdated(record) == std::vector<std::string>({"battle-data"}));
+    // The next installation doesn't install them again: they stay as not installed.
+    stamp::Start(record, {"fields"}, "1", "c", "disk");
+    stamp::Finish(record);
+    BOOST_CHECK_EQUAL(record.parts["battle-data"], 0);
+    BOOST_CHECK(stamp::Outdated(record) == std::vector<std::string>({"battle-data"}));
+    BOOST_CHECK_EQUAL(record.parts["kernel"], stamp::DATA_VERSION);
+    // A part of an older version of the data.
+    record.parts["fields"] = stamp::DATA_VERSION - 1;
+    BOOST_REQUIRE(stamp::Write(dir.path, record));
+    const std::vector<std::string> problems = stamp::Problems(dir.path);
+    BOOST_REQUIRE_EQUAL(problems.size(), 1u);
+    BOOST_CHECK(problems[0].find("battle-data") != std::string::npos);
+    BOOST_CHECK(problems[0].find("fields") != std::string::npos);
+}
+
+BOOST_AUTO_TEST_CASE(VerifierReportsTheRecord){
+    namespace stamp = VGears::InstallStamp;
+    TempDir dir;
+    BOOST_CHECK(HasProblem(VerifyInstallation(dir.Root()), "Installation"));
+    stamp::Stamp record;
+    stamp::Start(record, {"kernel"}, "1", "a", "disk");
+    BOOST_REQUIRE(stamp::Write(dir.path, record));
+    BOOST_CHECK(HasProblem(VerifyInstallation(dir.Root()), "Installation"));
+    stamp::Finish(record);
+    BOOST_REQUIRE(stamp::Write(dir.path, record));
+    BOOST_CHECK(!HasProblem(VerifyInstallation(dir.Root()), "Installation"));
+}