Browse Source

Add world map module: field-to-world transition, story situations, scripted scenery

World script decompiler:
- Add opcodes 0x11d, 0x31b, 0x33c, 0x355 and 0x01b; fix Write(Read(N), v) stores and bank address collisions between locals, bytes, words and bits.
- Fixes the animated world map models script decompilation.

World map module:
- World memory shares the field memory banks, so story counter and vehicle flags set by field scripts are visible to the world scripts.
- Pick the world situation from the story and flags (Midgar-era, cannon destroyed, Ultimate killed, etc.) instead of a debug value.
- Hide vehicles the story has not given; use script positions as spawns.
- Place scenery models from the world scripts.
- Add get_animation_name, play_animation_index and set_default_animation_index script bindings.
- Entering from a field: which selects the map and the player spawn from the world init script.
- Reload vehicles.lua on entering the world.
- Installer writes world map exist locations.
Iñigo Valentin 17 hours ago
parent
commit
d14db179d3
36 changed files with 2327 additions and 121 deletions
  1. 6 2
      data/data/screens/begin_menu/begin_menu.xml
  2. 3 0
      data/data/scripts/_scripts.xml
  3. 41 0
      data/data/scripts/debug_data.lua
  4. 7 1
      data/data/scripts/field.lua
  5. 23 3
      data/data/scripts/menu/begin_menu.lua
  6. 95 0
      data/data/scripts/worldmap/script_stubs.lua
  7. 127 0
      data/data/scripts/worldmap/triangle_triggers.lua
  8. 1 10
      data/data/scripts/worldmap/vehicles.lua
  9. 102 0
      data/data/scripts/worldmap/world_model_table.lua
  10. 290 0
      data/data/scripts/worldmap/world_vm.lua
  11. 2 0
      data/data/texts/english/menu.xml
  12. 20 0
      src/core/Entity.cpp
  13. 22 0
      src/core/Entity.h
  14. 33 0
      src/core/EntityModel.cpp
  15. 30 0
      src/core/EntityModel.h
  16. 16 3
      src/core/ScriptManagerBinds.h
  17. 33 0
      src/installer/FieldDataInstaller.cpp
  18. 5 0
      src/installer/FieldDataInstaller.h
  19. 4 1
      src/installer/InstallVerifier.cpp
  20. 39 11
      src/installer/WorldInstaller.cpp
  21. 162 0
      src/installer/WorldModelTable.h
  22. 14 1
      src/installer/decompiler/CodeGenerator.cpp
  23. 12 0
      src/installer/decompiler/CodeGenerator.h
  24. 18 0
      src/installer/decompiler/world/WorldCodeGenerator.cpp
  25. 12 0
      src/installer/decompiler/world/WorldCodeGenerator.h
  26. 28 1
      src/installer/decompiler/world/WorldDisassembler.cpp
  27. 14 0
      src/installer/decompiler/world/WorldEngine.cpp
  28. 44 0
      src/installer/decompiler/world/WorldEngine.h
  29. 3 2
      src/installer/decompiler/world/instruction/WorldBinaryEqualStackInstruction.cpp
  30. 32 25
      src/installer/decompiler/world/instruction/WorldKernelCallInstruction.cpp
  31. 16 1
      src/installer/decompiler/world/instruction/WorldLoadBankInstruction.cpp
  32. 2 1
      src/installer/decompiler/world/instruction/WorldNoOutputInstruction.cpp
  33. 17 1
      src/installer/decompiler/world/instruction/WorldStoreInstruction.cpp
  34. 47 28
      src/installer/decompiler/world/instruction/WorldSubStackInstruction.cpp
  35. 769 28
      src/modules/worldmap/WorldmapModule.cpp
  36. 238 2
      src/modules/worldmap/WorldmapModule.h

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

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

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

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

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

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

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

@@ -366,7 +366,13 @@ System["MapChanger"] = {
         if self.map_name ~= "" then
             player_lock(true) -- disable menu and pc movement while load map
             script:request_end_sync(Script.UI, "Fade", "fade_out", 0)
-            map(self.map_name)
+            -- The fields go to the world map as "wm<n>", n being the FIELD.TBL record of the exit.
+            local world_record = tonumber(string.match(self.map_name, "^wm(%d+)$"))
+            if world_record then
+                enter_world_map(world_record, self.point_name)
+            else
+                map(self.map_name)
+            end
             player_lock(false) -- enable menu and pc movement after load map
             self.current_map_name = self.map_name
             self.map_name = ""

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

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

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

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

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

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

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

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

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

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

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

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

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

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

+ 20 - 0
src/core/Entity.cpp

@@ -726,6 +726,26 @@ const Ogre::String& Entity::GetCurrentAnimationName() const{return animation_cur
 
 Entity::AnimationState Entity::GetAnimationState() const{return animation_state_;}
 
+Ogre::String Entity::GetAnimationName(const unsigned int) const{return "";}
+
+void Entity::ScriptPlayAnimationIndex(const unsigned int index){
+    const Ogre::String name = GetAnimationName(index);
+    if (name.empty()){
+        LOG_ERROR("There is no animation number " + std::to_string(index) + ".");
+        return;
+    }
+    PlayAnimation(name, Entity::REQUESTED_ANIMATION, Entity::PLAY_DEFAULT, 0, -1);
+}
+
+void Entity::ScriptSetDefaultAnimationIndex(const unsigned int index){
+    const Ogre::String name = GetAnimationName(index);
+    if (name.empty()){
+        LOG_ERROR("There is no animation number " + std::to_string(index) + ".");
+        return;
+    }
+    animation_default_ = name;
+}
+
 void Entity::ScriptPlayAnimation(const char* name){
     PlayAnimation(Ogre::String(name), Entity::REQUESTED_ANIMATION, Entity::PLAY_DEFAULT, 0, -1);
 }

+ 22 - 0
src/core/Entity.h

@@ -549,6 +549,28 @@ class Entity{
          */
         virtual unsigned int GetAnimationCount() const;
 
+        /**
+         * Gets the name of an animation by its position, in the order they were added to the model.
+         *
+         * @param[in] index Position of the animation, starting at 0.
+         * @return The name, empty if there is no such animation.
+         */
+        virtual Ogre::String GetAnimationName(const unsigned int index) const;
+
+        /**
+         * Plays, looped, the animation at a position (see GetAnimationName).
+         *
+         * @param[in] index Position of the animation, starting at 0.
+         */
+        void ScriptPlayAnimationIndex(const unsigned int index);
+
+        /**
+         * Sets the default animation to the one at a position (see GetAnimationName).
+         *
+         * @param[in] index Position of the animation, starting at 0.
+         */
+        void ScriptSetDefaultAnimationIndex(const unsigned int index);
+
         /**
          * Retrieves the duration of an animation.
          *

+ 33 - 0
src/core/EntityModel.cpp

@@ -89,6 +89,12 @@ unsigned int EntityModel::GetAnimationCount() const{
     return states->getAnimationStates().size();
 }
 
+Ogre::String EntityModel::GetAnimationName(const unsigned int index) const{
+    Ogre::SkeletonInstance* skeleton = model_->getSkeleton();
+    if (skeleton == nullptr || index >= skeleton->getNumAnimations()) return "";
+    return skeleton->getAnimation(index)->getName();
+}
+
 Ogre::Entity* EntityModel::GetModel(){return model_;}
 
 Ogre::MaterialPtr EntityModel::OwnMaterial(Ogre::SubEntity* sub_entity){
@@ -336,6 +342,33 @@ void EntityModel::PlayAnimationContinue(const Ogre::String& animation){
     }
 }
 
+void EntityModel::StopAnimation(){
+    if (animation_current_ != nullptr){
+        animation_current_->setEnabled(false);
+        animation_current_ = nullptr;
+    }
+    animation_current_name_.clear();
+}
+
+void EntityModel::PlayAnimationPaused(const Ogre::String& animation){
+    if (!HasAnimation(animation)) return;
+    if (animation_frozen_ && animation_current_name_ == animation) return;
+    PlayAnimation(animation, Entity::AUTO_ANIMATION, Entity::PLAY_LOOPED, 0, -1);
+    animation_speed_ = 0.0f;
+    animation_frozen_ = true;
+}
+
+void EntityModel::UnfreezeAnimation(){
+    if (!animation_frozen_) return;
+    animation_speed_ = 1.0f;
+    animation_frozen_ = false;
+}
+
+bool EntityModel::HasAnimation(const Ogre::String& animation) const{
+    return model_->getAllAnimationStates() != nullptr
+      && model_->getAllAnimationStates()->hasAnimationState(animation);
+}
+
 void EntityModel::UpdateAnimation(const float delta){
     if (animation_current_ != nullptr){
         float delta_mod = delta * animation_speed_;

+ 30 - 0
src/core/EntityModel.h

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

+ 16 - 3
src/core/ScriptManagerBinds.h

@@ -174,7 +174,10 @@ void ScriptManager::InitBinds(){
       ),
       "get_animation_length", &Entity::ScriptGetAnimationLength,
       "get_animation_count", &Entity::GetAnimationCount,
-      "set_default_animation", &Entity::ScriptSetDefaultAnimation
+      "get_animation_name", &Entity::GetAnimationName,
+      "play_animation_index", &Entity::ScriptPlayAnimationIndex,
+      "set_default_animation", &Entity::ScriptSetDefaultAnimation,
+      "set_default_animation_index", &Entity::ScriptSetDefaultAnimationIndex
     );
     sol::table entity_type = lua["Entity"];
     BindYielding(entity_type, "move_sync", &Entity::ScriptMoveSync);
@@ -626,14 +629,24 @@ void ScriptManager::InitBinds(){
     // Commands to initiate modules
     lua.new_usertype<VGears::WorldmapModule>(
       "world_map_module",
-      "init", &VGears::WorldmapModule::Init,
+      "init", sol::overload(
+        [](VGears::WorldmapModule& module){module.Init(0);},
+        [](VGears::WorldmapModule& module, const int map_id){module.Init(map_id);}
+      ),
       "suspend", &VGears::WorldmapModule::Suspend,
       "clear_vehicle_terrains", &VGears::WorldmapModule::ClearVehicleTerrains,
       "add_vehicle_terrain", &VGears::WorldmapModule::AddVehicleTerrain,
       "get_terrain_type_under_entity", &VGears::WorldmapModule::GetTerrainTypeUnderEntity,
       "get_terrain_triangle_under_entity", &VGears::WorldmapModule::GetTerrainTriangleUnderEntity,
       "unboard_vehicle", &VGears::WorldmapModule::UnboardVehicle,
-      "set_encounters_locked", &VGears::WorldmapModule::SetEncountersLocked
+      "set_encounters_locked", &VGears::WorldmapModule::SetEncountersLocked,
+      "set_model_orientation", &VGears::WorldmapModule::SetModelOrientation,
+      "set_model_offset", &VGears::WorldmapModule::SetModelOffset,
+      "set_entity_altitude", &VGears::WorldmapModule::SetEntityAltitude,
+      "enter", &VGears::WorldmapModule::Enter,
+      "set_spawn", &VGears::WorldmapModule::SetSpawn,
+      "set_vehicle_hidden", &VGears::WorldmapModule::SetVehicleHidden,
+      "add_world_model", &VGears::WorldmapModule::AddWorldModelFromScript
     );
 
     // Register all command handlers

+ 33 - 0
src/installer/FieldDataInstaller.cpp

@@ -14,6 +14,7 @@
  */
 
 #include <string>
+#include <fstream>
 #include <algorithm>
 #include <boost/filesystem.hpp>
 #include <QtCore/QDir>
@@ -288,7 +289,39 @@ void FieldDataInstaller::LoadInstalledFields(){
     }
 }
 
+void FieldDataInstaller::WriteWorldArrivals(){
+    // The exits to the world map ("wm<N>") have no field to write the spawn points into, so the coordinates
+    // that each exit gives (world units) are written for the world map scripts, by spawn point name.
+    std::string output = "-- Generated by the installer: where each field exit puts the player in the world map.\n"
+      "WorldArrivals = {\n";
+    for (const auto& entry : spawn_points_){
+        if (entry.first >= map_list_.size()) continue;
+        const std::string& target = map_list_[entry.first];
+        if (target.size() < 3 || target.compare(0, 2, "wm") != 0
+          || target.find_first_not_of("0123456789", 2) != std::string::npos) continue;
+        for (const SpawnPointDb::Record& record : entry.second.gateways_to_this_field){
+            std::string name;
+            if (record.from_script){
+                name = map_list_.at(record.field_id) + "_" + record.entity_name + "_" + record.script_function_name
+                  + "_addr_" + std::to_string(record.gateway_index_or_map_jump_address);
+            }
+            else{
+                name = "Spawn_" + map_list_.at(record.field_id) + "_"
+                  + std::to_string(record.gateway_index_or_map_jump_address);
+            }
+            output += "    [\"" + name + "\"] = {x = " + std::to_string(record.gateway.destination.x)
+              + ", y = " + std::to_string(record.gateway.destination.y)
+              + ", dir = " + std::to_string(record.gateway.dir) + "},\n";
+        }
+    }
+    output += "}\n";
+    boost::filesystem::create_directories(data_dir_ + "scripts/worldmap");
+    std::ofstream file(data_dir_ + "scripts/worldmap/world_arrivals.lua");
+    file << output;
+}
+
 void FieldDataInstaller::Convert(int field_index){
+    if (field_index == 0) WriteWorldArrivals();
     // Do the full conversion with the collated data.
     if (field_index >= flevel_file_list_->size()){
         // TODO: Show invalid index.

+ 5 - 0
src/installer/FieldDataInstaller.h

@@ -393,6 +393,11 @@ class FieldDataInstaller{
          */
         void CollectSpawnAndScaleFactors(int field_index);
 
+        /**
+         * Writes the coordinates of the exits to the world map (scripts/worldmap/world_arrivals.lua).
+         */
+        void WriteWorldArrivals();
+
         /**
          * Converts FFVII PC fields to V-Gears format.
          *

+ 4 - 1
src/installer/InstallVerifier.cpp

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

+ 39 - 11
src/installer/WorldInstaller.cpp

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

+ 162 - 0
src/installer/WorldModelTable.h

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

File diff suppressed because it is too large
+ 769 - 28
src/modules/worldmap/WorldmapModule.cpp


+ 238 - 2
src/modules/worldmap/WorldmapModule.h

@@ -18,6 +18,8 @@
 #include <OgreFrameListener.h>
 #include <OgreSingleton.h>
 #include <OgreVector3.h>
+#include <map>
+#include <set>
 #include <vector>
 #include "common/TypeDefine.h"
 
@@ -47,8 +49,11 @@ namespace VGears {
 
             /**
              * Initializes the world map module
+             *
+             * @param[in] map_id 0 is the overworld (WM0), 1 is WM2 and 2 is WM3. If another map
+             * was already loaded, it is replaced.
              */
-            void Init();
+            void Init(const int map_id = 0);
             void Suspend();
 
             bool frameStarted(const Ogre::FrameEvent& event) override;
@@ -77,6 +82,83 @@ namespace VGears {
              */
             void SetEncountersLocked(const bool locked);
 
+            /**
+             * Sets the orientation of the model of a world map entity, in degrees. It's the
+             * orientation of the model itself, so the heading of the entity is added to it. It is
+             * for finding the right orientation of a model.
+             *
+             * @param[in] entity_name Name of the entity, like "WorldMapHighwind".
+             * @param[in] x Rotation in X.
+             * @param[in] y Rotation in Y.
+             * @param[in] z Rotation in Z.
+             */
+            /**
+             * Moves the model of a world map entity up or down, in world units, without moving
+             * the entity. It is for finding the right height of a model.
+             *
+             * @param[in] entity_name Name of the entity, like "WorldMapSubmarine".
+             * @param[in] y Height of the model. Negative is down, 0 is the position of the entity.
+             */
+            void SetModelOffset(const char* entity_name, const float y);
+
+            /**
+             * Puts a world map entity at a fixed height of the world, keeping its x and z.
+             *
+             * @param[in] entity_name Name of the entity, like "WorldMapemerald_30".
+             * @param[in] y Height in world units, not relative to the ground.
+             */
+            void SetEntityAltitude(const char* entity_name, const float y);
+
+            /**
+             * Sets where an entity of the overworld appears when the map is loaded, instead of its
+             * default spawn point. It is used by the debug data, see debug_data.lua.
+             *
+             * @param[in] entity_name Name of the entity: "Cloud", "Chocobo", "Highwind", "Buggy",
+             * "Submarine" or "TinyBronco".
+             * @param[in] x Position in X, in world units.
+             * @param[in] z Position in Z, in world units.
+             */
+            void SetSpawn(const char* entity_name, const float x, const float z);
+
+            /**
+             * Hides a vehicle of the overworld that the story hasn't given yet: it is not visible,
+             * solid nor talkable, so it can't be boarded. Has to be called before the map is created.
+             *
+             * @param[in] entity_name Name of the vehicle: "Chocobo", "Highwind", "Buggy",
+             * "Submarine" or "TinyBronco".
+             */
+            void SetVehicleHidden(const char* entity_name);
+
+            /**
+             * Enters a world map from a field: the map is always built again (its entities, scripts and
+             * models are for the story of now), unlike Init, which keeps the one that was suspended.
+             *
+             * @param[in] map_id Map to enter, 0 WM0, 1 WM2, 2 WM3.
+             */
+            void Enter(const int map_id);
+
+            /**
+             * Creates a model of the world that the scripts place (scenery like the rocket or the
+             * Gold Saucer), at a position of the world. The model is not solid.
+             *
+             * @param[in] name Name of the entity, without the prefix "WorldMap".
+             * @param[in] hrc Name of the HRC file of the model, like "cfc".
+             * @param[in] x Position in X, in world units.
+             * @param[in] z Position in Z, in world units.
+             * @param[in] raw_scale Scale that the game stores with the model: 0x200 is 1.
+             * @param[in] direction Direction that the script gives, from 0 to 255 for a full turn.
+             * @param[in] rotation_x Rotation of the model itself in X, in degrees.
+             * @param[in] rotation_y Rotation of the model itself in Y, in degrees.
+             * @param[in] rotation_z Rotation of the model itself in Z, in degrees.
+             */
+            void AddWorldModelFromScript(
+              const char* name, const char* hrc, const float x, const float z, const int raw_scale,
+              const int direction, const float rotation_x, const float rotation_y,
+              const float rotation_z
+            );
+
+            void SetModelOrientation(const char* entity_name, const float x, const float y, const float z);
+
         private:
 
             struct TerrainTriangle{
@@ -102,6 +184,43 @@ namespace VGears {
                 uint16 words[15];
             };
 
+            void DestroyWorldMap();
+            /**
+             * State of an entity of the overworld, kept while another map is loaded.
+             */
+            struct EntityState{
+                Ogre::String name;
+                Ogre::Vector3 position;
+                Ogre::Quaternion orientation;
+                bool visible;
+                bool solid;
+                bool talkable;
+            };
+
+            /**
+             * Saves the state of the entities of the overworld, to restore it when it is loaded
+             * again.
+             */
+            void SaveOverworldSnapshot();
+
+            /**
+             * Puts the entities of the overworld where they were when the snapshot was saved.
+             */
+            void RestoreOverworldSnapshot();
+
+            /**
+             * Gets the spawn point of an entity: the one that the debug data sets, or the default.
+             */
+            Ogre::Vector3 GetSpawn(
+              const Ogre::String& entity_name, const Ogre::Vector3& default_spawn
+            ) const;
+
+            /// Spawn points that replace the default ones.
+            std::map<Ogre::String, Ogre::Vector2> spawn_overrides_;
+
+            /// Vehicles that the story hasn't given.
+            std::set<Ogre::String> hidden_vehicles_;
+
             void CreateWorldMap(Ogre::SceneManager* scene_manager);
             void CreatePlayer();
                         void CreateCompanionModels();
@@ -110,7 +229,8 @@ namespace VGears {
                             const Ogre::Vector3& desired_position, Ogre::Real target_size,
                             const Ogre::Quaternion& orientation,
                             Ogre::Real collision_radius_scale = 1.0f,
-                            bool talkable = false
+                            bool talkable = false,
+                            Ogre::Real explicit_scale = 0.0f
                         );
             void UpdateCamera(Ogre::Real delta_time, bool snap_to_player);
             bool FindWalkableSurface(
@@ -120,6 +240,75 @@ namespace VGears {
                             size_t* triangle_index = nullptr
             ) const;
             bool IsActiveTerrainAllowed(uint8 walkability_type) const;
+            /**
+             * Runs the function of a triangle when it is entered, if it changed.
+             */
+            void EnterTriangle(const TerrainTriangle& triangle);
+
+            /**
+             * Plays the animation that each vehicle has in its state: parked, boarded, or boarded
+             * and moving.
+             *
+             * @param[in] moving True if the active entity is moving.
+             */
+            void UpdateVehicleAnimations(const bool moving);
+
+            /**
+             * Takes the submarine from WM0 to WM2, if it is over deep water inside the underwater
+             * map. It keeps the position and the heading.
+             *
+             * @param[in] submarine The submarine. The entities are replaced if it dives.
+             * @return True if it dived.
+             */
+            bool DiveToUnderwaterMap(EntityModel* submarine);
+
+            /**
+             * Takes the submarine from WM2 back to WM0, if the same position is deep water in
+             * WM0. It keeps the position and the heading.
+             *
+             * @param[in] submarine The submarine. The entities are replaced if it surfaces.
+             * @return True if it surfaced.
+             */
+            bool SurfaceToOverworld(EntityModel* submarine);
+
+            /**
+             * Starts the animation of a dive or a surfacing: the submarine goes under the surface
+             * (or up), the screen fades to black, the map changes, and the screen fades back while
+             * the submarine arrives. The request of the dive or the surfacing has to be set.
+             *
+             * @param[in] dive True for a dive from WM0 to WM2, false for a surfacing.
+             * @param[in] submarine The submarine.
+             */
+            void BeginTransition(const bool dive, EntityModel* submarine);
+
+            /**
+             * Moves the animation of the dive or the surfacing forward. It changes the map in the
+             * middle of it.
+             *
+             * @param[in] delta_time Seconds since the last frame.
+             */
+            void UpdateTransition(const Ogre::Real delta_time);
+
+            /**
+             * Ends the animation: the screen is shown and the player can move again.
+             */
+            void EndTransition();
+
+            /**
+             * Puts the submarine at the position of a surfacing and makes it the one in control.
+             */
+            void PlaceSurfacedSubmarine();
+
+            /**
+             * Moves a flying vehicle: forward with the action button, left and right turn, up and
+             * down change the height.
+             *
+             * @param[in] entity The vehicle.
+             * @param[in] delta_time Seconds since the last frame.
+             * @param[in] highwind True for the Highwind, false for the submarine of WM2.
+             */
+            void UpdateFlight(EntityModel* entity, const Ogre::Real delta_time, const bool highwind);
+
             void TriggerTriangleFunction(const TerrainTriangle& triangle);
             void LoadEncounters();
             void UpdateEncounters(const float delta_time, const TerrainTriangle& triangle);
@@ -146,9 +335,56 @@ namespace VGears {
             Ogre::Real player_height_offset_;
             int active_function_mesh_index_;
             int active_function_id_;
+            /// Loaded map ID, -1 if none.
+            int map_id_;
+            /// Size of the map in blocks.
+            size_t grid_width_;
+            size_t grid_height_;
+            /// Rotation of the camera around the active entity, in radians. Positive is to the right.
+            float camera_yaw_;
+            /// True while the active entity is a flying vehicle.
+            bool flight_active_;
+            /// Flying vehicle that the flight state belongs to.
+            EntityModel* flight_entity_;
+            /// Rotation of the vehicle around the vertical axis, in radians.
+            float flight_heading_;
+            /// Height of the vehicle.
+            float flight_y_;
+            /// Position of the first block of the map in the 9x7 block grid of the world.
+            size_t origin_x_;
+            size_t origin_y_;
             bool initialized_;
             bool frame_listener_attached_;
             bool cancel_was_pressed_;
+            bool confirm_was_pressed_;
+            enum class TransitionStage{
+                /// No animation going on.
+                NONE,
+                /// The submarine moves away, in the map where it was.
+                LEAVING,
+                /// The screen goes black.
+                FADING_OUT,
+                /// The submarine comes into the new map and the screen is shown again.
+                ARRIVING
+            };
+            TransitionStage transition_stage_;
+            /// True for a dive, false for a surfacing.
+            bool transition_dive_;
+            float transition_timer_;
+            /// Heights where the submarine is moving between in the current stage.
+            float transition_start_y_;
+            float transition_target_y_;
+            /// State of the entities of WM0 while WM2 is loaded.
+            std::vector<EntityState> overworld_snapshot_;
+            /// A surfacing to WM0 is going on: the submarine appears at the position and heading
+            /// below.
+            bool surface_requested_;
+            Ogre::Vector3 surface_position_;
+            float surface_heading_;
+            /// A dive to WM2 is going on: the submarine appears at the position and heading below.
+            bool dive_requested_;
+            Ogre::Vector3 dive_position_;
+            float dive_heading_;
     };
 
 }

Some files were not shown because too many files changed in this diff