Sfoglia il codice sorgente

Add original battle cameras, effects and caster auras; enemy skills

Battle effects and cameras now use data extracted from the original game (ff7.exe and the disc's battle files) instead of hand-made values.

Installer
- Extract the battle camera scripts to gamedata/battle_cameras.lua.
- Extract effect camera scripts, morphing meshes and the ice shard meshes from ff7.exe.
- Write the effect sprite frames with the exact .s file layout.
- Fix fuzzy match problems with the installer.

Engine
- BattleManager: get_camera() script binding for the formation camera; effect entities are hidden from /debug_entity.
- CameraManager: upright battle camera, UI compensation scaled with distance. EntityModel: support for the effect models.

Battle camera
- battle_camera.lua interprets the camdat scripts: camera chosen per attack or enemy attack, file chosen by battle layout, randomly picked variants, smooth return to the formation camera.
- effect_camera.lua runs the summon camera scripts.

Effects
- Summons Shiva, Ifrit and Ramuh from the original data: morphing ground/mountain meshes, sprite animations, ice spikes that shatter with the exe's physics, storm, snow, crystals, debris and shake.
- Effect sprites are anchored to the combatant, so they follow the moving camera.
- Caster auras: stacked, expanding light tubes with the original textures and sounds for spells, limits, enemy skills and summons.

Enemy skills
- The E.Skill command lists the skills learned by the equipped Enemy Skill materia and casts them with the pink-aura.
Iñigo Valentin 1 giorno fa
parent
commit
45275938f4

File diff suppressed because it is too large
+ 1146 - 2
data/data/screens/battle/battle_fx.lua


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

@@ -7,6 +7,10 @@
     <script file="gamedata/attacks.lua" />
     <script file="gamedata/attacks.lua" />
     <script file="gamedata/characters.lua" />
     <script file="gamedata/characters.lua" />
     <script file="gamedata/commands.lua" />
     <script file="gamedata/commands.lua" />
+    <script file="gamedata/battle_cameras.lua" />
+    <script file="gamedata/effect_cameras.lua" />
+    <script file="gamedata/effect_meshes.lua" />
+    <script file="gamedata/effect_animations.lua" />
     <script file="gamedata/effect_sprites.lua" />
     <script file="gamedata/effect_sprites.lua" />
     <script file="gamedata/growth.lua" />
     <script file="gamedata/growth.lua" />
     <script file="gamedata/items.lua" />
     <script file="gamedata/items.lua" />
@@ -28,6 +32,10 @@
     <script file="scripts/worldmap/vehicles.lua" />
     <script file="scripts/worldmap/vehicles.lua" />
     <script file="scripts/battle_ai.lua" />
     <script file="scripts/battle_ai.lua" />
     <script file="scripts/battle/battle_ai_vm.lua" />
     <script file="scripts/battle/battle_ai_vm.lua" />
+    <script file="scripts/battle/battle_camera.lua" />
+    <script file="scripts/battle/effect_camera.lua" />
+    <script file="scripts/battle/effect_mesh.lua" />
+    <script file="scripts/battle/effect_sprite.lua" />
     <script file="scripts/menu/menu_helpers.lua" />
     <script file="scripts/menu/menu_helpers.lua" />
     <script file="scripts/menu/menu_lib.lua" />
     <script file="scripts/menu/menu_lib.lua" />
 
 

+ 545 - 0
data/data/scripts/battle/battle_camera.lua

@@ -0,0 +1,545 @@
+--- Camera scripts of the battles (attacks, magic, enemy attacks).
+--
+-- The original game has a small script for the camera of each attack, in the files camdat0.bin,
+-- camdat1.bin and camdat2.bin (the installer writes them to gamedata/battle_cameras.lua). Two points
+-- move in a battle: the camera (position stream) and the point it looks at (look stream), each one
+-- with its own script of bytes, found with (camera id * 3 + variant). The ids are the camera_single
+-- and camera_multiple of the attacks. The interpreters are in ff7.exe (0x5c2341 and 0x5c3f45).
+--
+-- A script is a list of opcodes (0xd5-0xff, other values do nothing) with operands that are bytes or
+-- 16 bit values (little endian, with sign). Positions are in the units of the original game, in a
+-- frame with x to the side, y down and z forward (toward the enemies, for the party), and the ones
+-- that follow an actor are relative to a point of it, the offsets turned with the way it faces if
+-- the stream has "rotate" on. The frame of the scene is converted with
+--
+--   scene = (x, -z, -y) / 255      (a reflection: the original frame is left handed)
+--
+-- (the division is the one the installer uses for every coordinate of the battle). The streams run
+-- one opcode after the other until one of them waits or places the point (the ones that do are
+-- listed in YIELDS), once per tick, 15 ticks per second like the effects.
+--
+-- The state of the battle is read through an environment (see BattleCameraController in
+-- battle_camera_controller.lua): env:actor(ref) gives the position of an actor of the scene, the way it
+-- faces and its height, and env.formation the camera that was in use before the script.
+BattleCamera = {}
+BattleCamera.__index = BattleCamera
+
+--- Scene units for each original unit.
+BattleCamera.UNIT = 1 / 255
+
+--- Ticks of the scripts in a second.
+BattleCamera.TPS = 15
+
+--- Operands (the bytes after the opcode) of each opcode: the numbers are the ones of the installer
+-- (BattleCameraScripts.h).
+BattleCamera.LENGTH = {
+    pos = {
+        [0xd5] = 2, [0xd6] = 0, [0xd7] = 2, [0xd8] = 9, [0xd9] = 0, [0xda] = 0, [0xdb] = 0, [0xdc] = 0,
+        [0xdd] = 1, [0xde] = 1, [0xdf] = 0, [0xe0] = 2, [0xe1] = 0, [0xe2] = 1, [0xe3] = 9, [0xe4] = 8,
+        [0xe5] = 8, [0xe6] = 7, [0xe7] = 8, [0xe9] = 8, [0xeb] = 9, [0xef] = 8, [0xf0] = 7, [0xf1] = 0,
+        [0xf2] = 5, [0xf3] = 5, [0xf4] = 0, [0xf5] = 1, [0xf7] = 7, [0xf8] = 12, [0xf9] = 6, [0xfe] = 0,
+        [0xff] = 0,
+    },
+    look = {
+        [0xd8] = 9, [0xd9] = 0, [0xdb] = 0, [0xdc] = 0, [0xdd] = 1, [0xde] = 1, [0xdf] = 0, [0xe0] = 2,
+        [0xe1] = 0, [0xe2] = 1, [0xe3] = 9, [0xe4] = 8, [0xe5] = 8, [0xe6] = 7, [0xe8] = 8, [0xea] = 8,
+        [0xec] = 9, [0xf0] = 8, [0xf4] = 0, [0xf5] = 1, [0xf8] = 7, [0xf9] = 7, [0xfa] = 6, [0xfe] = 0,
+        [0xff] = 0,
+    },
+}
+
+--- Opcodes that end the processing of a tick (the ones that wait or place the point).
+BattleCamera.YIELDS = {
+    pos = {[0xef] = true, [0xf0] = true, [0xf4] = true, [0xf7] = true, [0xff] = true},
+    look = {[0xf0] = true, [0xf4] = true, [0xf8] = true, [0xf9] = true, [0xff] = true},
+}
+
+--- Maximum opcodes in a tick, in case a script loops without waiting.
+BattleCamera.MAX_OPCODES = 64
+
+--- Gets the bytes of a script.
+--
+-- @param set Number of the camdat file (0 to 2).
+-- @param kind "pos" or "look".
+-- @param id Camera id.
+-- @param variant 0 to 2.
+-- @return The list of bytes, nil if there is none (ids of -1 or 0xffff do nothing).
+function BattleCamera.get_script(set, kind, id, variant)
+    if id == nil or id < 0 or id >= 0xffff then return nil end
+    local data = Game.BattleCameras ~= nil and Game.BattleCameras[set] or nil
+    if data == nil then return nil end
+    local key = data[kind == "pos" and "position" or "look"][id * 3 + (variant or 0) + 1]
+    if key == nil then return nil end
+    return data.scripts[key]
+end
+
+local function vec(x, y, z) return {x, y, z} end
+
+local function new_stream(kind, script)
+    return {
+        kind = kind, script = script, pc = 1, wait = 0, rotate = false, linear = false,
+        pos = vec(0, 0, 0), tasks = {}, finished = script == nil, yielded = false,
+    }
+end
+
+--- Creates the camera of a pair of scripts.
+--
+-- @param position Script of the position (list of bytes, can be nil).
+-- @param look Script of the look at point.
+-- @param env See above.
+function BattleCamera.new(position, look, env)
+    local self = setmetatable({}, BattleCamera)
+    self.env = env
+    self.cam = new_stream("pos", position)
+    self.look = new_stream("look", look)
+    local f = env.formation
+    self.cam.pos = {f.pos[1], f.pos[2], f.pos[3]}
+    self.look.pos = {f.look[1], f.look[2], f.look[3]}
+    return self
+end
+
+--- Is everything of the script done? (the scripts stay on their last opcode forever)
+function BattleCamera:is_finished()
+    return self.cam.finished and self.look.finished and #self.cam.tasks == 0 and #self.look.tasks == 0
+end
+
+-- Operand readers. A "reader" has the script and the position of the next byte.
+local function u8(s)
+    local v = s.script[s.pc]
+    s.pc = s.pc + 1
+    return v or 0
+end
+
+local function s16(s)
+    local lo, hi = u8(s), u8(s)
+    local v = hi * 256 + lo
+    if v >= 32768 then v = v - 65536 end
+    return v
+end
+
+--- Converts a vector of the original frame to the scene, as an offset.
+local function to_scene_offset(x, y, z)
+    local k = BattleCamera.UNIT
+    return x * k, -z * k, -y * k
+end
+
+--- Converts a position of the original frame (absolute) to the scene.
+function BattleCamera:absolute(x, y, z)
+    return vec(to_scene_offset(x, y, z))
+end
+
+--- Position of a point of an actor, plus an offset of the original frame.
+--
+-- @param rotate If the offset turns with the way the actor faces.
+function BattleCamera:anchor(ref, point, ox, oy, oz, rotate)
+    local actor = self.env:actor(ref)
+    if actor == nil then return nil end
+    -- The points of the original are bones. All of the used ones (0 and 10) are near the middle of
+    -- the body, so they are the middle of the actor.
+    local px, py, pz = actor.pos[1], actor.pos[2], actor.pos[3] + actor.height * 0.5
+    local k = BattleCamera.UNIT
+    local dx, dy, dz
+    if rotate then
+        -- x is to the left of the way it faces (reflection), z forward, y down.
+        local fx, fy = actor.forward[1], actor.forward[2]
+        dx = (-fy) * ox * k + fx * oz * k
+        dy = fx * ox * k + fy * oz * k
+        dz = -oy * k
+    else
+        dx, dy, dz = to_scene_offset(ox, oy, oz)
+    end
+    return vec(px + dx, py + dy, pz + dz)
+end
+
+--- The reference of an actor of a script (the byte of the opcodes that take it): 0-2 the party and
+-- 4-9 the enemies.
+local function actor_from_byte(b)
+    if b >= 0 and b <= 2 then return {side = "party", index = b + 1} end
+    if b >= 4 and b <= 9 then return {side = "enemies", index = b - 3} end
+    return "targets"
+end
+
+--- Starts a move to a point in some ticks.
+local function start_move(stream, target, ticks)
+    stream.tasks[#stream.tasks + 1] = {
+        type = "move", start = {stream.pos[1], stream.pos[2], stream.pos[3]}, target = target,
+        ticks = math.max(1, ticks), age = 0, linear = stream.linear,
+    }
+end
+
+--- Starts the follow of an actor for some ticks.
+local function start_follow(stream, ref, point, ox, oy, oz, ticks, rotate)
+    stream.tasks[#stream.tasks + 1] = {
+        type = "follow", ref = ref, point = point, off = {ox, oy, oz}, ticks = math.max(1, ticks),
+        age = 0, rotate = rotate,
+    }
+end
+
+--- Places a stream at a point of an actor, now.
+function BattleCamera:place(stream, ref, point, ox, oy, oz, rotate)
+    local p = self:anchor(ref, point, ox, oy, oz, rotate)
+    if p ~= nil then stream.pos = p end
+end
+
+--- Runs the opcodes of a stream until it waits.
+function BattleCamera:run(stream)
+    local kind = stream.kind
+    local lengths = BattleCamera.LENGTH[kind]
+    local yields = BattleCamera.YIELDS[kind]
+    local env = self.env
+    for _ = 1, BattleCamera.MAX_OPCODES do
+        if stream.finished then return end
+        local op = stream.script[stream.pc]
+        if op == nil then stream.finished = true return end
+        stream.pc = stream.pc + 1
+        local length = lengths[op]
+        if length == nil then
+            -- It isn't an opcode: nothing happens, but the tick is over.
+            return
+        end
+        -- Opcodes that are the same in both streams (the ones with the same number and meaning).
+        if op == 0xff then
+            stream.pc = stream.pc - 1
+            stream.finished = true
+            return
+        elseif op == 0xf5 then
+            local n = u8(stream)
+            if n >= 128 then n = n - 256 end
+            stream.wait = n
+        elseif op == 0xf4 then
+            if stream.wait ~= 0 then
+                stream.wait = stream.wait - 1
+                stream.pc = stream.pc - 1
+                return
+            end
+        elseif op == 0xfe then
+            if stream.wait == 0 and stream.script[stream.pc] == 0xc0 then
+                stream.pc = 1
+                stream.wait = 0
+            end
+        elseif op == 0xdc then
+            stream.rotate = true
+        elseif kind == "pos" and op == 0xf1 then
+            stream.rotate = false
+        elseif kind == "look" and op == 0xdb then
+            stream.rotate = false
+        elseif kind == "pos" and op == 0xda then
+            stream.linear = false
+        elseif kind == "pos" and op == 0xdb then
+            stream.linear = true
+        elseif op == 0xe1 or op == 0xd9 or op == 0xdd then
+            -- The camera that was in use.
+            if op == 0xdd then u8(stream) end
+            local source = kind == "pos" and env.formation.pos or env.formation.look
+            stream.pos = {source[1], source[2], source[3]}
+        elseif op == 0xe2 then
+            local source = kind == "pos" and env.formation.pos or env.formation.look
+            start_move(stream, {source[1], source[2], source[3]}, u8(stream))
+        elseif op == 0xe6 then
+            local x, y, z = s16(stream), s16(stream), s16(stream)
+            start_move(stream, self:absolute(x, y, z), u8(stream))
+        elseif (kind == "pos" and op == 0xf9) or (kind == "look" and op == 0xfa) then
+            local x, y, z = s16(stream), s16(stream), s16(stream)
+            stream.pos = self:absolute(x, y, z)
+        elseif op == 0xe3 or op == 0xd8 or op == 0xe4 or op == 0xe5 then
+            -- Move to a point of an actor, with an offset: actor (e3 and d8), point, x, y, z, ticks.
+            local ref
+            if op == 0xe3 then ref = actor_from_byte(u8(stream))
+            elseif op == 0xd8 then u8(stream) ref = "targets"
+            elseif op == 0xe4 then ref = "attacker"
+            else ref = "current" end
+            local point = u8(stream)
+            local x, y, z = s16(stream), s16(stream), s16(stream)
+            local ticks = u8(stream)
+            local target = self:anchor(ref, point, x, y, z, stream.rotate)
+            if target ~= nil then start_move(stream, target, ticks) end
+        elseif (kind == "pos" and (op == 0xe7 or op == 0xe9 or op == 0xeb))
+          or (kind == "look" and (op == 0xe8 or op == 0xea or op == 0xec)) then
+            -- Follow a point of an actor with an offset, for some ticks.
+            local ref
+            if op == 0xeb or op == 0xec then ref = actor_from_byte(u8(stream))
+            elseif op == 0xe7 or op == 0xe8 then ref = "attacker"
+            else ref = "current" end
+            local point = u8(stream)
+            local x, y, z = s16(stream), s16(stream), s16(stream)
+            local ticks = u8(stream)
+            start_follow(stream, ref, point, x, y, z, ticks, stream.rotate)
+        elseif (kind == "pos" and (op == 0xef or op == 0xf0 or op == 0xf7))
+          or (kind == "look" and (op == 0xf0 or op == 0xf8 or op == 0xf9)) then
+            -- Place at a point of an actor, with an offset.
+            local ref
+            if (kind == "pos" and op == 0xef) or (kind == "look" and op == 0xf0) then ref = actor_from_byte(u8(stream))
+            elseif (kind == "pos" and op == 0xf0) or (kind == "look" and op == 0xf9) then ref = "attacker"
+            else ref = "current" end
+            local point = u8(stream)
+            local x, y, z = s16(stream), s16(stream), s16(stream)
+            self:place(stream, ref, point, x, y, z, stream.rotate)
+        else
+            -- Opcodes that don't change the camera (events of the battle, the orbits f2 and f3, the
+            -- moves to the data of an actor e0, 0xf8 of the position): skip their operands.
+            stream.pc = stream.pc + length
+        end
+        if yields[op] and op ~= 0xff and op ~= 0xf4 then return end
+    end
+end
+
+--- Advances the tasks of a stream one tick.
+function BattleCamera:run_tasks(stream)
+    local alive = {}
+    for _, task in ipairs(stream.tasks) do
+        task.age = task.age + 1
+        if task.type == "move" then
+            if task.age >= task.ticks then
+                stream.pos = {task.target[1], task.target[2], task.target[3]}
+            else
+                local f
+                if task.linear then f = (task.age) / task.ticks
+                else f = (1 - math.cos(math.pi * (task.age - 1) / task.ticks)) / 2 end
+                stream.pos = {
+                    task.start[1] + (task.target[1] - task.start[1]) * f,
+                    task.start[2] + (task.target[2] - task.start[2]) * f,
+                    task.start[3] + (task.target[3] - task.start[3]) * f,
+                }
+            end
+        else
+            local p = self:anchor(task.ref, task.point, task.off[1], task.off[2], task.off[3], task.rotate)
+            if p ~= nil then stream.pos = p end
+        end
+        if task.age < task.ticks then alive[#alive + 1] = task end
+    end
+    stream.tasks = alive
+end
+
+--- Advances the camera one tick.
+function BattleCamera:tick()
+    for _, stream in ipairs({self.cam, self.look}) do
+        self:run(stream)
+        self:run_tasks(stream)
+    end
+end
+
+--- The position of the camera and the point it looks at, in the scene.
+function BattleCamera:get()
+    return self.cam.pos, self.look.pos
+end
+
+--- Controller of the camera of the battle.
+--
+-- Starts the camera of an action when it begins, moves the camera while the action goes on and takes it
+-- back to the camera of the formation when it ends. Nothing moves if the camera is set to manual
+-- in the config menu (see {@see Battle.is_camera_auto}).
+BattleCameraController = {
+    --- Number of the file camdatN.bin that the original uses for each battle layout (0 normal,
+    -- 1 preemptive, 2 back attack, 3 side attack, ... 8 locked): the table at 0x7b8528 of ff7.exe,
+    -- indexed with the type of the battle (byte 0x999e12), that has the same numbers as the layouts.
+    FILE_BY_LAYOUT = {[0] = 0, 0, 1, 2, 2, 2, 2, 2, 0},
+
+    --- Ticks in a second of the way back to the camera of the formation. The movement (half of the
+    -- distance in every tick) is the one of the executable, but its rate isn't known: it was too
+    -- fast with 15, the rate of the scripts, and with 10.
+    RETURN_TPS = 5,
+
+    --- The camera that is running, nil if none.
+    camera = nil,
+
+    --- Seconds that are left to the next tick, and the last two results (for the interpolation).
+    accumulated = 0,
+    previous = nil,
+    current = nil,
+
+    --- Ids that were started for debugging: set to a number to force an id.
+    forced_id = nil,
+}
+
+--- Position of an entity and its height, in the scene.
+local function entity_info(entity)
+    local x, y, z = entity:get_position()
+    local info = BattleCameraController.heights[entity:get_name()]
+    if info == nil then
+        -- The height is the one of the highest bone.
+        local top = z
+        for bone = 0, 24 do
+            local ok, bx, by, bz = pcall(entity.get_bone_position, entity, bone)
+            if ok and bz ~= nil and bz > top then top = bz end
+        end
+        info = math.max(top - z, 1.5)
+        BattleCameraController.heights[entity:get_name()] = info
+    end
+    return x, y, z, info
+end
+BattleCameraController.heights = {}
+
+--- Builds the environment of the camera for an action.
+local function build_env(side, actor, target_side, targets, formation)
+    local ui = UiContainer.BattleUi
+    local function entity_of(s, index)
+        local e = ui:get_entity(s, index)
+        return e
+    end
+    -- Center of the targets (their entities) and of the attacker.
+    local function center_of(s, list)
+        local sx, sy, sz, n = 0, 0, 0, 0
+        local height = 0
+        for _, index in ipairs(list) do
+            local e = entity_of(s, index)
+            if e ~= nil then
+                local x, y, z, h = entity_info(e)
+                sx, sy, sz, n, height = sx + x, sy + y, sz + z, n + 1, math.max(height, h)
+            end
+        end
+        if n == 0 then return nil end
+        return {sx / n, sy / n, sz / n}, height
+    end
+    local attacker_entity = entity_of(side, actor)
+    local attacker_pos, attacker_height
+    if attacker_entity ~= nil then
+        local x, y, z, h = entity_info(attacker_entity)
+        attacker_pos, attacker_height = {x, y, z}, h
+    end
+    local target_pos, target_height = center_of(target_side, targets)
+    local function direction(from, to)
+        if from == nil or to == nil then return {0, -1} end
+        local dx, dy = to[1] - from[1], to[2] - from[2]
+        local l = math.sqrt(dx * dx + dy * dy)
+        if l < 0.0001 then return {0, -1} end
+        return {dx / l, dy / l}
+    end
+    local env = {formation = formation}
+    function env:actor(ref)
+        if ref == "attacker" then
+            if attacker_pos == nil then return nil end
+            return {pos = attacker_pos, height = attacker_height, forward = direction(attacker_pos, target_pos)}
+        elseif ref == "current" or ref == "targets" then
+            if target_pos == nil then return nil end
+            if ref == "current" then
+                -- The first target.
+                local e = entity_of(target_side, targets[1])
+                if e ~= nil then
+                    local x, y, z, h = entity_info(e)
+                    return {pos = {x, y, z}, height = h, forward = direction({x, y, z}, attacker_pos)}
+                end
+            end
+            return {pos = target_pos, height = target_height, forward = direction(target_pos, attacker_pos)}
+        elseif type(ref) == "table" then
+            local e = entity_of(ref.side == "party" and Battle.TargetGroup.PARTY or Battle.TargetGroup.ENEMIES, ref.index)
+            if e == nil then return nil end
+            local x, y, z, h = entity_info(e)
+            local other = ref.side == "party" and target_pos or attacker_pos
+            return {pos = {x, y, z}, height = h, forward = direction({x, y, z}, other)}
+        end
+        return nil
+    end
+    return env
+end
+
+--- Starts the camera of an action.
+--
+-- @param side Side of the actor.
+-- @param actor Index of the actor.
+-- @param target_side Side of the targets.
+-- @param targets List of indexes of the targets.
+-- @param camera_single Id for a single target (nil or 0xffff for none).
+-- @param camera_multiple Id for several targets.
+-- @return True if there is a camera.
+function BattleCameraController:start(side, actor, target_side, targets, camera_single, camera_multiple)
+    self:stop(false)
+    if Battle.is_camera_auto ~= nil and not Battle.is_camera_auto() then return false end
+    if targets == nil or #targets == 0 then return false end
+    local id = #targets > 1 and camera_multiple or camera_single
+    if self.forced_id ~= nil then id = self.forced_id end
+    local variant = math.random(0, 2)
+    local layout = battle_manager:get_layout()
+    local file = self.FILE_BY_LAYOUT[layout] or 0
+    local position = BattleCamera.get_script(file, "pos", id, variant)
+    local look = BattleCamera.get_script(file, "look", id, variant)
+    if position == nil and look == nil then return false end
+    -- A camera that was going back to the one of the formation is replaced by this one (if there is
+    -- none, it goes on: an action with no camera must not leave it where it was).
+    self.returning = nil
+    self.last = nil
+    local index = UiContainer.BattleUi.camera_index or 0
+    local px, py, pz, lx, ly, lz = battle_manager:get_camera(index)
+    local formation = {pos = {px, py, pz}, look = {lx, ly, lz}}
+    local env = build_env(side, actor, target_side, targets, formation)
+    self.camera = BattleCamera.new(position, look, env)
+    self.camera_index = index
+    self.accumulated = 0
+    self.previous = nil
+    self.current = nil
+    print("Battle camera " .. tostring(id) .. " variant " .. tostring(variant) .. " file " .. tostring(file))
+    return true
+end
+
+--- Stops the camera and goes back to the one of the formation.
+--
+-- The original doesn't jump: every tick the camera and the point it looks at cover half of the
+-- distance that is left to the camera of the formation (function 0x5c64cc), until they get there.
+function BattleCameraController:stop(restore)
+    if self.camera == nil then return end
+    self.camera = nil
+    if restore == false or self.last == nil then
+        print("Battle camera: stopped without easing (" .. tostring(restore) .. ", " .. tostring(self.last ~= nil) .. ")")
+        self.returning = nil
+        if restore ~= false then battle_manager:set_camera(self.camera_index or 0) end
+        return
+    end
+    local index = self.camera_index or 0
+    local px, py, pz, lx, ly, lz = battle_manager:get_camera(index)
+    self.returning = {target = {{px, py, pz}, {lx, ly, lz}}, cam = self.last.cam, look = self.last.look, index = index}
+    self.accumulated = 0
+    print("Battle camera: going back to the camera " .. tostring(index))
+end
+
+--- Moves the camera. Call it every frame.
+--
+-- @param dt Seconds since the last call.
+function BattleCameraController:update(dt)
+    if self.returning ~= nil and self.camera == nil then
+        local r = self.returning
+        -- Every tick the points go half of the way (r.to is where they are after the last tick, and
+        -- r.from where they were before), and between ticks they are drawn between the two.
+        if r.from == nil then
+            r.from = {{r.cam[1], r.cam[2], r.cam[3]}, {r.look[1], r.look[2], r.look[3]}}
+            r.to = {{r.cam[1], r.cam[2], r.cam[3]}, {r.look[1], r.look[2], r.look[3]}}
+        end
+        self.accumulated = self.accumulated + dt * self.RETURN_TPS
+        while self.accumulated >= 1 and self.returning ~= nil do
+            self.accumulated = self.accumulated - 1
+            local done = true
+            for i = 1, 2 do
+                for k = 1, 3 do
+                    r.from[i][k] = r.to[i][k]
+                    local diff = (r.target[i][k] - r.to[i][k]) / 2
+                    r.to[i][k] = r.to[i][k] + diff
+                    if math.abs(diff) > BattleCamera.UNIT then done = false end
+                end
+            end
+            if done then
+                self.returning = nil
+                battle_manager:set_camera(r.index)
+                print("Battle camera: back at the camera " .. tostring(r.index))
+            end
+        end
+        if self.returning ~= nil then
+            local f = self.accumulated
+            local function mix(i, k) return r.from[i][k] + (r.to[i][k] - r.from[i][k]) * f end
+            battle_manager:set_camera_position(mix(1, 1), mix(1, 2), mix(1, 3), mix(2, 1), mix(2, 2), mix(2, 3))
+        end
+        return
+    end
+    if self.camera == nil then return end
+    self.accumulated = self.accumulated + dt * BattleCamera.TPS
+    while self.accumulated >= 1 do
+        self.accumulated = self.accumulated - 1
+        self.camera:tick()
+        local cam, look = self.camera:get()
+        self.previous = self.current
+        self.current = {cam = {cam[1], cam[2], cam[3]}, look = {look[1], look[2], look[3]}}
+    end
+    if self.current == nil then return end
+    local c, p, f = self.current, self.previous or self.current, self.accumulated
+    local function mix(a, b) return {p[a][1] + (c[a][1] - p[a][1]) * f, p[a][2] + (c[a][2] - p[a][2]) * f, p[a][3] + (c[a][3] - p[a][3]) * f} end
+    local cam, look = mix("cam"), mix("look")
+    self.last = {cam = {cam[1], cam[2], cam[3]}, look = {look[1], look[2], look[3]}}
+    battle_manager:set_camera_position(cam[1], cam[2], cam[3], look[1], look[2], look[3])
+end

+ 78 - 9
data/data/scripts/battle/battle_ui.lua

@@ -17,7 +17,9 @@ BattleAnimations = {
     -- 18, the root height goes from 673 to 58), 13 and 14 are the run away.
     -- 18, the root height goes from 673 to 58), 13 and 14 are the run away.
     player = {attack_script = 20, hurt_script = 5, death_script = 7, victory_script = 12, escape_script = 13,
     player = {attack_script = 20, hurt_script = 5, death_script = 7, victory_script = 12, escape_script = 13,
         -- Script 29 (17 and 30 are the same): ready the weapon, incantation and release.
         -- Script 29 (17 and 30 are the same): ready the weapon, incantation and release.
-        magic_script = 29},
+        magic_script = 29,
+        -- Script 30 is the same as 29 with the pink aura of the enemy skills.
+        eskill_script = 30},
     models = {},
     models = {},
 }
 }
 
 
@@ -772,6 +774,10 @@ UiContainer.BattleUi = {
         UiContainer.BattleFx:update(now)
         UiContainer.BattleFx:update(now)
         self:update_hides(now)
         self:update_hides(now)
         self:update_action(now)
         self:update_action(now)
+        -- The camera of the attacks.
+        if self.action_executing ~= true then BattleCameraController:stop() end
+        local ok, err = pcall(BattleCameraController.update, BattleCameraController, delta)
+        if not ok then print("Battle camera: " .. tostring(err)) BattleCameraController:stop(false) end
         -- Held ATBs start to fill after some time.
         -- Held ATBs start to fill after some time.
         if (self.party_hold or self.enemy_hold) and now - self.hold_start > self.HOLD_TIME then
         if (self.party_hold or self.enemy_hold) and now - self.hold_start > self.HOLD_TIME then
             self:release_hold()
             self:release_hold()
@@ -2411,7 +2417,9 @@ UiContainer.BattleUi = {
         end
         end
         local script = action.script
         local script = action.script
         if script == nil and actor_side == Battle.TargetGroup.PARTY then
         if script == nil and actor_side == Battle.TargetGroup.PARTY then
-            script = self:get_script_number(actor_side, action.actor, (action.attack_id ~= nil or action.item_id ~= nil) and "magic" or "attack")
+            local script_type = (action.attack_id ~= nil or action.item_id ~= nil) and "magic" or "attack"
+            if action.command == Characters.E_SKILL_COMMAND and action.attack_id ~= nil then script_type = "eskill" end
+            script = self:get_script_number(actor_side, action.actor, script_type)
         end
         end
         -- Using things costs something. If it can't be paid anymore, the action fizzles.
         -- Using things costs something. If it can't be paid anymore, the action fizzles.
         local function fizzle(message)
         local function fizzle(message)
@@ -2449,16 +2457,69 @@ UiContainer.BattleUi = {
         if action.attack_id ~= nil or action.item_id ~= nil then
         if action.attack_id ~= nil or action.item_id ~= nil then
             ui_manager:get_widget("BattleUi.Container.Message.Name"):set_text(attack.name)
             ui_manager:get_widget("BattleUi.Container.Message.Name"):set_text(attack.name)
         end
         end
-        current.pending = 1
+        -- Summons play their own sequence after the cast pose, and the hit lands during it.
+        local summon = action.attack_id ~= nil and UiContainer.BattleFx:has_summon(attack.id)
+        local summon_started = false
+        local function start_summon()
+            if summon_started then do return end end
+            summon_started = true
+            UiContainer.BattleFx:play_summon(
+              attack, actor_side, action.actor, action.target_group, current.targets,
+              function() self:apply_action_hit() end,
+              function() current.pending = current.pending - 1 end
+            )
+        end
+        current.pending = summon and 2 or 1
+        -- The aura of the caster.
+        if action.attack_id ~= nil and actor_side == Battle.TargetGroup.PARTY then
+            local ok, err = pcall(function()
+                UiContainer.BattleFx:start_aura(UiContainer.BattleFx:aura_kind(action, summon), actor_side, action.actor)
+            end)
+            if not ok then print("Battle aura: " .. tostring(err)) end
+        end
+        -- The camera of the attack (summons have their own).
+        if not summon and (action.attack_id ~= nil) then
+            local single, multiple
+            if attack.animation ~= nil then single, multiple = attack.animation.camera_single, attack.animation.camera_multiple end
+            local kernel = attack.id ~= nil and Game.Attacks[attack.id] or nil
+            if single == nil and kernel ~= nil and kernel.camera ~= nil then single, multiple = kernel.camera.single, kernel.camera.multiple end
+            -- The camera of the attack of an enemy overrides the one of the attack.
+            if actor_side == Battle.TargetGroup.ENEMIES then
+                local source = battle_manager:get_enemy(action.actor - 1)
+                for slot = 0, source:get_attack_count() - 1 do
+                    if source:get_attack(slot) == action.attack_id then
+                        local camera = source:get_camera_for_attack(slot)
+                        if camera ~= nil and camera >= 0 and camera < 0xffff then single, multiple = camera, camera end
+                        break
+                    end
+                end
+            end
+            local ok, err = pcall(function()
+                return BattleCameraController:start(actor_side, action.actor, action.target_group, current.targets, single, multiple)
+            end)
+            if not ok then print("Battle camera: " .. tostring(err)) end
+        end
         local played = self:play_script(
         local played = self:play_script(
           actor_side, action.actor, script, false,
           actor_side, action.actor, script, false,
-          function() self:apply_action_hit() end,
-          function() current.pending = current.pending - 1 end,
+          function()
+              if summon then start_summon() else self:apply_action_hit() end
+          end,
+          function()
+              current.pending = current.pending - 1
+              -- A script without a hit mark still ends with the summon.
+              if summon then start_summon() end
+          end,
           current.targets[1] ~= nil and {side = action.target_group, index = current.targets[1]} or nil
           current.targets[1] ~= nil and {side = action.target_group, index = current.targets[1]} or nil
         )
         )
         if not played then
         if not played then
-            -- Nothing to play for the attacker: the hit lands right away.
-            current.pending = 0
+            if summon then
+                -- Nothing to play for the attacker: the summon starts right away.
+                current.pending = 1
+                start_summon()
+            else
+                -- Nothing to play for the attacker: the hit lands right away.
+                current.pending = 0
+            end
         end
         end
         self:update_action(timer:get_game_time_total())
         self:update_action(timer:get_game_time_total())
     end,
     end,
@@ -2672,6 +2733,7 @@ UiContainer.BattleUi = {
         local kind = nil
         local kind = nil
         if list == Battle.Menu.MAGIC then kind = "magic"
         if list == Battle.Menu.MAGIC then kind = "magic"
         elseif list == Battle.Menu.SUMMON then kind = "summon"
         elseif list == Battle.Menu.SUMMON then kind = "summon"
+        elseif list == Battle.Menu.E_SKILL then kind = "eskill"
         elseif list == Battle.Menu.ITEM then kind = "item"
         elseif list == Battle.Menu.ITEM then kind = "item"
         end
         end
         if kind ~= nil then
         if kind ~= nil then
@@ -2693,8 +2755,6 @@ UiContainer.BattleUi = {
             ui_manager:get_widget("BattleUi.Container.Bottom.List"):set_visible(true)
             ui_manager:get_widget("BattleUi.Container.Bottom.List"):set_visible(true)
             cursor:set_default_animation("Position" .. tostring(self.cursor_list))
             cursor:set_default_animation("Position" .. tostring(self.cursor_list))
             cursor:set_visible(true)
             cursor:set_visible(true)
-        elseif (list == Battle.Menu.E_SKILL) then
-            print("Show e. skill list: Not implemented")
         elseif (list == Battle.Menu.THROW) then
         elseif (list == Battle.Menu.THROW) then
             print("Show throw list: Not implemented")
             print("Show throw list: Not implemented")
         elseif (list == Battle.Menu.LIMIT) then
         elseif (list == Battle.Menu.LIMIT) then
@@ -2885,6 +2945,15 @@ UiContainer.BattleUi = {
                 local data = Game.Attacks[spell.id]
                 local data = Game.Attacks[spell.id]
                 table.insert(entries, {name = data.name, attack_id = spell.id, enabled = data.mp <= stats.mp.current})
                 table.insert(entries, {name = data.name, attack_id = spell.id, enabled = data.mp <= stats.mp.current})
             end
             end
+        elseif kind == "eskill" then
+            -- The enemy skills learned with the equipped materia.
+            local learned = Characters.get_abilities(member.character).e_skill
+            for _, id in ipairs(learned) do
+                local data = Game.Attacks[id]
+                if data ~= nil then
+                    table.insert(entries, {name = data.name, attack_id = id, enabled = data.mp <= stats.mp.current})
+                end
+            end
         elseif kind == "summon" then
         elseif kind == "summon" then
             for _, summon in ipairs(member.summon) do
             for _, summon in ipairs(member.summon) do
                 local data = Game.Attacks[summon.id]
                 local data = Game.Attacks[summon.id]

+ 145 - 0
data/data/scripts/battle/effect_camera.lua

@@ -0,0 +1,145 @@
+--- Cameras of the battle effects (summons).
+--
+-- The original game has a small script for the camera of each effect, with the opcodes of a
+-- small interpreter inside ff7.exe (the Shiva one is at 0x58e57d). Two points move in the space
+-- of the effect: the camera (stream 0x40) and the point it looks at (stream 0x80). The script is
+-- a list of 16 bit words: the opcode in the low 6 bits and the stream in bit 0x40 or 0x80.
+--
+--   0, 9  wait N ticks (N)
+--   1     set the position (x, y, z)
+--   2     move to a position in N ticks, in a straight line (N, x, y, z)
+--   3     orbit: the camera goes to a position, but it stays in the line of the look point, and
+--         the distance to the look point changes smoothly (N, x, y, z)
+--   4, 5  accelerated moves, played as the ones of opcode 2 and 3 (not used by Shiva)
+--   6     two arguments, ignored. 8 one argument, ignored. 7 ends the script. A word of -1 ends
+--         the script too.
+--
+-- The interpreter takes a new opcode when one of the two streams has nothing to do, then moves
+-- both points one tick. Units are the ones of the original game (the scene ones are 0.0032 of them).
+EffectCamera = {}
+EffectCamera.__index = EffectCamera
+
+-- Arguments of each opcode.
+EffectCamera.ARGS = {[0] = 1, [1] = 3, [2] = 4, [3] = 4, [4] = 4, [5] = 5, [6] = 2, [7] = 0, [8] = 1, [9] = 1}
+
+local function copy(v) return {v[1], v[2], v[3]} end
+local function length(v) return math.sqrt(v[1] * v[1] + v[2] * v[2] + v[3] * v[3]) end
+
+local function new_stream()
+    return {pos = {0, 0, 0}, dur = 0, mode = 0, delta = {0, 0, 0}, start = {0, 0, 0}, dist = 0, dist_step = 0}
+end
+
+--- Creates the camera of a script.
+--
+-- @param words List of the 16 bit words of the script.
+function EffectCamera.new(words)
+    local self = setmetatable({}, EffectCamera)
+    self.words = words
+    self.index = 1
+    self.finished = false
+    self.cam = new_stream()
+    self.look = new_stream()
+    self.previous = {cam = copy(self.cam.pos), look = copy(self.look.pos)}
+    return self
+end
+
+--- Runs the next opcode of the script.
+function EffectCamera:fetch()
+    local w = self.words[self.index]
+    if w == nil or w == -1 then self.finished = true return end
+    local op = w % 64
+    local count = EffectCamera.ARGS[op]
+    if count == nil then self.finished = true return end
+    local a, b, c, d, e = self.words[self.index + 1], self.words[self.index + 2], self.words[self.index + 3],
+      self.words[self.index + 4], self.words[self.index + 5]
+    self.index = self.index + 1 + count
+    local s, other
+    if (w % 128) >= 64 then s, other = self.cam, self.look else s, other = self.look, self.cam end
+    s.mode = op
+    if op == 0 or op == 9 then
+        s.dur = math.max(0, a or 0)
+    elseif op == 1 then
+        s.pos = {a, b, c}
+        -- Until the camera is placed for the first time, the camera of the battle is the one in use.
+        if s == self.cam then self.started = true end
+    elseif op == 2 or op == 4 then
+        local n = math.max(1, a)
+        s.dur = n
+        s.delta = {(b - s.pos[1]) / n, (c - s.pos[2]) / n, (d - s.pos[3]) / n}
+        s.mode = 2
+    elseif op == 3 or op == 5 then
+        local n = math.max(1, a)
+        local target = op == 3 and {b, c, d} or {c, d, e}
+        s.dur = n
+        s.mode = 3
+        s.start = copy(s.pos)
+        s.delta = {(target[1] - s.pos[1]) / n, (target[2] - s.pos[2]) / n, (target[3] - s.pos[3]) / n}
+        local d0 = length({other.pos[1] - s.pos[1], other.pos[2] - s.pos[2], other.pos[3] - s.pos[3]})
+        -- Where the look point will be at the end, if it's moving in a straight line.
+        local final = copy(other.pos)
+        if other.mode == 2 then
+            for i = 1, 3 do final[i] = other.pos[i] + other.delta[i] * other.dur end
+        end
+        local d1 = length({target[1] - final[1], target[2] - final[2], target[3] - final[3]})
+        s.dist = d0
+        s.dist_step = (d1 - d0) / n
+    elseif op == 7 then
+        self.finished = true
+    end
+end
+
+--- Moves one of the points one tick.
+local function step_stream(s, other)
+    if s.dur <= 0 then return end
+    if s.mode == 2 then
+        for i = 1, 3 do s.pos[i] = s.pos[i] + s.delta[i] end
+    elseif s.mode == 3 then
+        for i = 1, 3 do s.start[i] = s.start[i] + s.delta[i] end
+        s.dist = s.dist + s.dist_step
+        local dir = {other.pos[1] - s.start[1], other.pos[2] - s.start[2], other.pos[3] - s.start[3]}
+        local l = length(dir)
+        if l > 0 then
+            for i = 1, 3 do s.pos[i] = other.pos[i] - dir[i] / l * s.dist end
+        end
+    end
+    s.dur = s.dur - 1
+end
+
+--- Advances the camera one tick of the effect.
+function EffectCamera:tick()
+    self.previous = {cam = copy(self.cam.pos), look = copy(self.look.pos)}
+    local was_started = self.started
+    while not self.finished and (self.cam.dur <= 0 or self.look.dur <= 0) do self:fetch() end
+    -- The camera is moved first, with the look point of the previous tick.
+    step_stream(self.cam, self.look)
+    step_stream(self.look, self.cam)
+    -- The first position doesn't move from nowhere.
+    if self.started and not was_started then
+        self.previous = {cam = copy(self.cam.pos), look = copy(self.look.pos)}
+    end
+end
+
+--- Gets the position of the camera and the look point.
+--
+-- @param fraction How far (0 to 1) we are from the last tick to the next one, to move smoothly.
+-- @return Two tables with x, y, z in the units of the original game.
+function EffectCamera:get(fraction)
+    local cam, look = {}, {}
+    for i = 1, 3 do
+        cam[i] = self.previous.cam[i] + (self.cam.pos[i] - self.previous.cam[i]) * fraction
+        look[i] = self.previous.look[i] + (self.look.pos[i] - self.previous.look[i]) * fraction
+    end
+    return cam, look
+end
+
+--- Gets a camera script.
+--
+-- The scripts are read from ff7.exe by the installer (gamedata/effect_cameras.lua), and they are
+-- named by their address in the executable, like "0x8ae268" (Shiva, one target). Without them
+-- (another version of the executable) the effects play with the camera of the battle.
+--
+-- @param name Name of the script.
+-- @return The list of words, nil if there is no such script.
+function EffectCamera.get_script(name)
+    return Game ~= nil and Game.EffectCameras ~= nil and Game.EffectCameras[name] or nil
+end

+ 243 - 0
data/data/scripts/battle/effect_mesh.lua

@@ -0,0 +1,243 @@
+--- Meshes of the battle effects that change shape, like the ground of Ifrit or the mountain of Ramuh.
+--
+-- The vertices of the original game are in ff7.exe: a mesh has the vertices of its first shape and
+-- a list of key shapes. The vertices move toward a key shape in a straight line over some ticks,
+-- one step per tick, and the triangles don't change. There are two ways to say when each key is
+-- reached:
+--   * every `key_ticks` ticks the next key starts (Ifrit, function 0x594022), or
+--   * a schedule, a list of {key, ticks, hold}: move to the key (a number of the list of keys, from
+--     1) in `ticks` ticks and wait `hold` ticks (Ramuh, function 0x598f74, with the durations of
+--     the table at 0x8ba970).
+--
+-- The data is written by the installer to gamedata/effect_meshes.lua (Game.EffectMeshes) and drawn
+-- with the dynamic meshes of the battle manager: one for the triangles with the texture and one for
+-- the ones with colours at the vertices and no texture.
+EffectMesh = {}
+EffectMesh.__index = EffectMesh
+
+--- Gets the data of a mesh.
+--
+-- @param name Name of the mesh, like "ifrit_ground".
+-- @return The data, nil if it isn't installed.
+function EffectMesh.get_data(name)
+    return Game ~= nil and Game.EffectMeshes ~= nil and Game.EffectMeshes[name] or nil
+end
+
+--- Divides like the original code: whole numbers, rounding toward zero.
+local function divide(a, b)
+    if a >= 0 then return math.floor(a / b) end
+    return -math.floor(-a / b)
+end
+
+--- Gets the moves of a mesh from the durations of the executable (function 0x598f74 of Ramuh).
+--
+-- The function goes through the words T, starting at 0 with nothing to wait: when the wait is over it
+-- takes T[i] as the new wait and, if i is even and the wait is not 0, aims at the shape i / 2 for that
+-- time, and then i goes up. The shape moves only while i is odd (the odd words are the waits between
+-- moves) and the effect ends when i gets to 8.
+--
+-- @param tail The words (16 are kept by the installer).
+-- @return List of {start, ticks, key} (key from 1).
+function EffectMesh.schedule_from_tail(tail)
+    local moves = {}
+    local i, remaining, time = 0, 0, 0
+    while true do
+        while remaining == 0 do
+            if i >= 8 then return moves end
+            remaining = tail[i + 1]
+            if remaining ~= 0 and i % 2 == 0 then
+                moves[#moves + 1] = {start = time, ticks = remaining, key = math.floor(i / 2) + 1}
+            end
+            i = i + 1
+        end
+        time = time + 1
+        remaining = remaining - 1
+    end
+end
+
+--- Creates a mesh.
+--
+-- @param data Data of the mesh (see EffectMesh.get_data).
+-- @param params Table with: texture (name of the image), key_ticks (ticks between key shapes, if there
+-- is no schedule), schedule (list of {key, ticks, hold}), blend (0 opaque, 1 additive, 2 alpha) and uv (position and size of the image in
+-- the texture page of the original game, {u, v, w, h}, 0, 0, 128, 128 by default).
+-- @return The mesh, nil if it couldn't be created.
+function EffectMesh.new(data, params)
+    local name = battle_manager:create_dynamic_mesh(params.texture or "", params.blend or 0)
+    if name == nil or name == "" then return nil end
+    local self = setmetatable({}, EffectMesh)
+    self.data = data
+    self.name = name
+    self.key_ticks = params.key_ticks or 4
+    local uv = params.uv or {}
+    self.uv_u, self.uv_v, self.uv_w, self.uv_h = uv.u or 0, uv.v or 0, uv.w or 128, uv.h or 128
+    -- Triangles with colours at the vertices have a mesh of their own, with no texture.
+    if data.gouraud ~= nil and #data.gouraud > 0 then
+        self.gouraud_name = battle_manager:create_dynamic_mesh("", 0)
+    end
+    -- The schedule is a list of moves with the tick they start.
+    if params.schedule == "tail" then
+        -- The durations are the 16 words that follow the table of key shapes in the executable.
+        self.moves = EffectMesh.schedule_from_tail(data.tail)
+    elseif params.schedule ~= nil then
+        self.moves = {}
+        local start = 0
+        for _, step in ipairs(params.schedule) do
+            self.moves[#self.moves + 1] = {start = start, ticks = step.ticks, key = step.key}
+            start = start + step.ticks + (step.hold or 0)
+        end
+    end
+    self.current = {}
+    self.delta = {}
+    for i = 1, #data.vertices do
+        self.current[i] = data.vertices[i]
+        self.delta[i] = 0
+    end
+    self.ticks = 0
+    return self
+end
+
+--- Sets the step of every vertex to reach a key shape in some ticks.
+function EffectMesh:aim(key, ticks)
+    local target = self.data.keys[key]
+    for i = 1, #self.current do
+        self.delta[i] = divide(target[i] - self.current[i], ticks)
+    end
+end
+
+--- Moves the vertices until the mesh has done a number of ticks.
+--
+-- @param ticks Ticks since the mesh started.
+function EffectMesh:advance(ticks)
+    while self.ticks < ticks do
+        local t = self.ticks
+        local moving = false
+        if self.moves ~= nil then
+            for _, move in ipairs(self.moves) do
+                if t == move.start then self:aim(move.key, move.ticks) end
+                if t >= move.start and t < move.start + move.ticks then moving = true end
+            end
+        elseif t < #self.data.keys * self.key_ticks then
+            if t % self.key_ticks == 0 then self:aim(math.floor(t / self.key_ticks) + 1, self.key_ticks) end
+            moving = true
+        end
+        if moving then
+            for i = 1, #self.current do self.current[i] = self.current[i] + self.delta[i] end
+        end
+        self.ticks = t + 1
+    end
+end
+
+--- Draws the mesh.
+--
+-- @param to_scene Function that gets the position of a point of the mesh in the effect and
+-- returns it in the scene (x, y, z).
+-- @param scale Size of the mesh (1 is the original one): a number, or a table with the factor of x, y
+-- and z (negative to flip an axis).
+-- @param brightness Factor of the grey level of the textured triangles (1 by default).
+function EffectMesh:draw(to_scene, scale, brightness)
+    local current = self.current
+    local sx, sy, sz = scale, scale, scale
+    if type(scale) == "table" then sx, sy, sz = scale[1], scale[2], scale[3] end
+    brightness = brightness or 1
+    local function position(vertex)
+        local v = vertex * 3
+        return to_scene(current[v + 1] * sx, current[v + 2] * sy, current[v + 3] * sz)
+    end
+    -- Triangles with texture. Their grey level is 128 for the original colour.
+    local triangles = self.data.triangles
+    local out, n = {}, 0
+    for t = 0, math.floor(#triangles / 10) - 1 do
+        local b = t * 10
+        local grey = triangles[b + 10] / 128 * brightness
+        for k = 0, 2 do
+            local x, y, z = position(triangles[b + 1 + k])
+            out[n + 1], out[n + 2], out[n + 3] = x, y, z
+            out[n + 4] = (triangles[b + 4 + 2 * k] - self.uv_u) / self.uv_w
+            out[n + 5] = (triangles[b + 5 + 2 * k] - self.uv_v) / self.uv_h
+            out[n + 6], out[n + 7], out[n + 8], out[n + 9] = grey, grey, grey, 1
+            n = n + 9
+        end
+    end
+    battle_manager:set_dynamic_mesh(self.name, out)
+    -- Triangles with colours.
+    if self.gouraud_name ~= nil then
+        local g = self.data.gouraud
+        out, n = {}, 0
+        for t = 0, math.floor(#g / 12) - 1 do
+            local b = t * 12
+            for k = 0, 2 do
+                local x, y, z = position(g[b + 1 + k])
+                out[n + 1], out[n + 2], out[n + 3] = x, y, z
+                out[n + 4], out[n + 5] = 0, 0
+                out[n + 6], out[n + 7], out[n + 8], out[n + 9] = g[b + 4 + 3 * k] / 255, g[b + 5 + 3 * k] / 255, g[b + 6 + 3 * k] / 255, 1
+                n = n + 9
+            end
+        end
+        battle_manager:set_dynamic_mesh(self.gouraud_name, out)
+    end
+end
+
+--- Speed of the shards in the first tick for each unit of the cross product of two edges: 0x60 / 4096
+-- (the code of the executable multiplies by 0x60 and shifts 12 bits, function 0x591455).
+EffectMesh.SHATTER_SPEED = 96 / 4096
+
+--- Draws the shards of a mesh that breaks (the ice of Shiva, function 0x591e14 of the executable).
+--
+-- Only the triangles of the first list (data.shards of them) are kept; the quads disappear when the
+-- ice breaks. Every triangle goes along its normal (the cross product of two of its edges, divided
+-- by 4096 and multiplied by 96 and with the sign changed: that is its speed in the first tick) and it loses an eighth of
+-- the speed every tick, so after n ticks it has moved speed * (1 - 0.875 ^ n) / 0.125.
+--
+-- @param to_scene Function (x, y, z) -> scene, as in draw, for the points after the turn and the flip.
+-- @param scale Size of the mesh.
+-- @param brightness Factor of the grey level.
+-- @param rotation Degrees around X, Y and Z, nil for none (the turn of the whole mesh).
+-- @param ticks Ticks since it started to break, nil if it is whole.
+function EffectMesh:draw_shatter(to_scene, scale, brightness, rotation, ticks)
+    local data = self.data
+    local verts = data.vertices
+    local triangles = data.triangles
+    local count = math.floor(#triangles / 10)
+    local limit = (ticks ~= nil and data.shards ~= nil) and data.shards or count
+    local factor = 0
+    if ticks ~= nil then factor = (1 - 0.875 ^ ticks) / 0.125 end
+    local out, n = {}, 0
+    for t = 0, limit - 1 do
+        local b = t * 10
+        local ids = {triangles[b + 1], triangles[b + 2], triangles[b + 3]}
+        local dx, dy, dz = 0, 0, 0
+        if ticks ~= nil then
+            local function vertex(i) return verts[i * 3 + 1], verts[i * 3 + 2], verts[i * 3 + 3] end
+            local x0, y0, z0 = vertex(ids[1])
+            local x1, y1, z1 = vertex(ids[2])
+            local x2, y2, z2 = vertex(ids[3])
+            local e1x, e1y, e1z, e2x, e2y, e2z = x1 - x0, y1 - y0, z1 - z0, x2 - x1, y2 - y1, z2 - z1
+            local cx, cy, cz = e1y * e2z - e1z * e2y, e1z * e2x - e1x * e2z, e1x * e2y - e1y * e2x
+            local speed = EffectMesh.SHATTER_SPEED
+            dx, dy, dz = -cx * speed * factor, -cy * speed * factor, -cz * speed * factor
+        end
+        local grey = triangles[b + 10] / 128 * brightness
+        for k = 0, 2 do
+            local v = ids[k + 1] * 3
+            local x, y, z = verts[v + 1] + dx, verts[v + 2] + dy, verts[v + 3] + dz
+            if rotation ~= nil then x, y, z = EffectSprite.rotate(x, y, z, rotation[1], rotation[2], rotation[3]) end
+            -- The effect is seen from the other side than the data (a turn of 180 degrees around the
+            -- vertical axis).
+            local px, py, pz = to_scene(-x * scale, y * scale, -z * scale)
+            out[n + 1], out[n + 2], out[n + 3] = px, py, pz
+            out[n + 4] = (triangles[b + 4 + 2 * k] - self.uv_u) / self.uv_w
+            out[n + 5] = (triangles[b + 5 + 2 * k] - self.uv_v) / self.uv_h
+            out[n + 6], out[n + 7], out[n + 8], out[n + 9] = grey, grey, grey, 1
+            n = n + 9
+        end
+    end
+    battle_manager:set_dynamic_mesh(self.name, out)
+end
+
+--- Removes the mesh.
+function EffectMesh:remove()
+    if self.name ~= nil then battle_manager:remove_dynamic_mesh(self.name) end
+    if self.gouraud_name ~= nil then battle_manager:remove_dynamic_mesh(self.gouraud_name) end
+    self.name, self.gouraud_name = nil, nil
+end

+ 101 - 0
data/data/scripts/battle/effect_sprite.lua

@@ -0,0 +1,101 @@
+--- Sprites of the battle effects, made from the sprite files (.SPT) of the original game.
+--
+-- A sprite file is a list of frames, and a frame a list of quads (Game.EffectAnimations, written by
+-- the installer). The quads are not billboards: they lie on a plane of the space of the effect, that
+-- the effect rotates with angles (a spinning lightning is a quad that rotates around the vertical
+-- axis). The corners of a quad are in units of 8 (the draw function, 0x598a7a, shifts them 3 bits).
+--
+-- Quads are drawn with dynamic meshes, one for every texture, that are filled again every frame.
+EffectSprite = {}
+
+--- Gets the frames of a sprite file.
+--
+-- @param name Name of the file, like "summon_lamu_jo_c04".
+-- @return List of frames, nil if it isn't installed.
+function EffectSprite.get_frames(name)
+    return Game ~= nil and Game.EffectAnimations ~= nil and Game.EffectAnimations[name] or nil
+end
+
+--- Rotates a point, with angles in degrees around X, then Y, then Z.
+function EffectSprite.rotate(x, y, z, ax, ay, az)
+    if ax ~= 0 then
+        local c, s = math.cos(math.rad(ax)), math.sin(math.rad(ax))
+        y, z = y * c - z * s, y * s + z * c
+    end
+    if ay ~= 0 then
+        local c, s = math.cos(math.rad(ay)), math.sin(math.rad(ay))
+        x, z = x * c + z * s, -x * s + z * c
+    end
+    if az ~= 0 then
+        local c, s = math.cos(math.rad(az)), math.sin(math.rad(az))
+        x, y = x * c - y * s, x * s + y * c
+    end
+    return x, y, z
+end
+
+EffectSpriteBatch = {}
+EffectSpriteBatch.__index = EffectSpriteBatch
+
+--- Creates a batch of quads that share a texture.
+--
+-- @param texture Name of the image.
+-- @param width Width of the texture of the original game, in pixels.
+-- @param height Height of the texture.
+-- @param blend 1 for additive, 2 for alpha blending, 0 for opaque.
+function EffectSpriteBatch.new(texture, width, height, blend)
+    local name = battle_manager:create_dynamic_mesh(texture, blend or 1)
+    if name == nil or name == "" then return nil end
+    local self = setmetatable({}, EffectSpriteBatch)
+    self.name, self.width, self.height = name, width, height
+    self.list, self.count = {}, 0
+    return self
+end
+
+--- Adds a quad.
+--
+-- @param c1 Corner of the top left, a table with x, y, z in the scene.
+-- @param c2 Top right, c3 bottom left and c4 bottom right.
+-- @param u0 Position in the texture (pixels): left, v0 top, u1 right and v1 bottom.
+-- @param colour Table with r, g, b, a (0 to 1).
+function EffectSpriteBatch:add_quad(c1, c2, c3, c4, u0, v0, u1, v1, colour)
+    local list, n = self.list, self.count
+    local w, h = self.width, self.height
+    local function vertex(c, u, v)
+        list[n + 1], list[n + 2], list[n + 3] = c[1], c[2], c[3]
+        list[n + 4], list[n + 5] = u / w, v / h
+        list[n + 6], list[n + 7], list[n + 8], list[n + 9] = colour[1], colour[2], colour[3], colour[4]
+        n = n + 9
+    end
+    vertex(c1, u0, v0) vertex(c2, u1, v0) vertex(c3, u0, v1)
+    vertex(c2, u1, v0) vertex(c4, u1, v1) vertex(c3, u0, v1)
+    self.count = n
+end
+
+--- Adds a triangle with colours (no texture).
+--
+-- @param c1 First corner, a table with x, y, z in the scene. c2 and c3 the others.
+-- @param colour Table with r, g, b, a (0 to 1).
+function EffectSpriteBatch:add_triangle(c1, c2, c3, colour)
+    local list, n = self.list, self.count
+    for _, c in ipairs({c1, c2, c3}) do
+        list[n + 1], list[n + 2], list[n + 3] = c[1], c[2], c[3]
+        list[n + 4], list[n + 5] = 0, 0
+        list[n + 6], list[n + 7], list[n + 8], list[n + 9] = colour[1], colour[2], colour[3], colour[4]
+        n = n + 9
+    end
+    self.count = n
+end
+
+--- Shows the quads added since the last time, and starts again.
+function EffectSpriteBatch:flush()
+    -- The list can have vertices of a previous frame at the end.
+    for i = self.count + 1, #self.list do self.list[i] = nil end
+    battle_manager:set_dynamic_mesh(self.name, self.list)
+    self.count = 0
+end
+
+--- Removes the mesh of the batch.
+function EffectSpriteBatch:remove()
+    if self.name ~= nil then battle_manager:remove_dynamic_mesh(self.name) end
+    self.name = nil
+end

+ 3 - 3
data/data/scripts/debug_data.lua

@@ -51,10 +51,10 @@ Characters[0].stats.dex.base = 11
 Characters[0].stats.dex.total = 11
 Characters[0].stats.dex.total = 11
 Characters[0].armor.id = 268
 Characters[0].armor.id = 268
 Characters[0].armor.materia = {
 Characters[0].armor.materia = {
-    [0] = {id = 62, ap = 15340},
+    [0] = {id = 75, ap = 15340},
     [2] = {id = 44, ap = 0, skills = {}}, -- E. Skill
     [2] = {id = 44, ap = 0, skills = {}}, -- E. Skill
-    [3] = {id = 78, ap = 520},
-    [4] = {id = 36, ap = 0},
+    [3] = {id = 76, ap = 520},
+    [4] = {id = 77, ap = 0},
     [5] = {id = 36, ap = 50000},
     [5] = {id = 36, ap = 50000},
     [6] = {id = 0, ap = 0},
     [6] = {id = 0, ap = 0},
     [7] = {id = 26, ap = 0},
     [7] = {id = 26, ap = 0},

+ 125 - 3
src/core/BattleManager.cpp

@@ -18,7 +18,11 @@
 #include <iostream>
 #include <iostream>
 #include <cmath>
 #include <cmath>
 #include <OgreEntity.h>
 #include <OgreEntity.h>
+#include <OgreMaterialManager.h>
 #include <OgreRoot.h>
 #include <OgreRoot.h>
+#include <OgreSceneManager.h>
+#include <OgreSceneNode.h>
+#include <OgreTextureManager.h>
 #include <OgreResourceGroupManager.h>
 #include <OgreResourceGroupManager.h>
 #include <OgreViewport.h>
 #include <OgreViewport.h>
 #include "FF7Character.h"
 #include "FF7Character.h"
@@ -96,6 +100,7 @@ void BattleManager::ClearField(){
 }
 }
 
 
 void BattleManager::ClearBattle(){
 void BattleManager::ClearBattle(){
+    ClearDynamicMeshes();
     formation_id_ = -1;
     formation_id_ = -1;
     next_formation_id_ = -1;
     next_formation_id_ = -1;
     // TODO location_ = null;
     // TODO location_ = null;
@@ -299,12 +304,16 @@ std::string BattleManager::ScriptAddEffectModel(
         LOG_ERROR("Tried to add an effect model, but the BattleManager is not in battle mode.");
         LOG_ERROR("Tried to add an effect model, but the BattleManager is not in battle mode.");
         return "";
         return "";
     }
     }
-    const std::string mesh = "effects/" + std::string(model) + ".mesh";
+    // Names with a folder (like attacks/cyvadat for a summon) are used as they are.
+    const std::string mesh = std::string(model).find('/') != std::string::npos
+      ? std::string(model) + ".mesh" : "effects/" + std::string(model) + ".mesh";
     if (!Ogre::ResourceGroupManager::getSingleton().resourceExists("BATTLE_MODELS", mesh)){
     if (!Ogre::ResourceGroupManager::getSingleton().resourceExists("BATTLE_MODELS", mesh)){
         LOG_WARNING("Effect model '" + mesh + "' doesn't exist, reinstall the battle data.");
         LOG_WARNING("Effect model '" + mesh + "' doesn't exist, reinstall the battle data.");
         return "";
         return "";
     }
     }
-    const std::string name = "fx_" + std::string(model) + "_" + std::to_string(next_effect_id_ ++);
+    std::string clean_name = model;
+    for (char& c : clean_name) if (c == '/') c = '_';
+    const std::string name = "fx_" + clean_name + "_" + std::to_string(next_effect_id_ ++);
     const float s = ATTACK_SCALE * scale;
     const float s = ATTACK_SCALE * scale;
     EntityManager::getSingleton().AddEntity(
     EntityManager::getSingleton().AddEntity(
       name, mesh, Ogre::Vector3(x, y, z), Ogre::Degree(0), Ogre::Vector3(s, s, s),
       name, mesh, Ogre::Vector3(x, y, z), Ogre::Degree(0), Ogre::Vector3(s, s, s),
@@ -312,7 +321,11 @@ std::string BattleManager::ScriptAddEffectModel(
     );
     );
     // Effect meshes have no animations, and battle entities look for "xx_00" by default.
     // Effect meshes have no animations, and battle entities look for "xx_00" by default.
     Entity* entity = EntityManager::getSingleton().GetEntity(name);
     Entity* entity = EntityManager::getSingleton().GetEntity(name);
-    if (entity != nullptr) entity->ScriptSetDefaultAnimation("Idle");
+    if (entity != nullptr){
+        entity->ScriptSetDefaultAnimation("Idle");
+        // There are lots of them, they would fill the debug text of the screen.
+        entity->SetDebugHidden(true);
+    }
     return name;
     return name;
 }
 }
 
 
@@ -320,6 +333,104 @@ void BattleManager::ScriptRemoveEffectModel(const char* name){
     EntityManager::getSingleton().RemoveBattleEntity(name);
     EntityManager::getSingleton().RemoveBattleEntity(name);
 }
 }
 
 
+std::string BattleManager::ScriptCreateDynamicMesh(const char* texture, const int blend){
+    if (module_ != Module::BATTLE){
+        LOG_ERROR("Tried to create a dynamic mesh, but the BattleManager is not in battle mode.");
+        return "";
+    }
+    Ogre::SceneManager* scene = Ogre::Root::getSingleton().getSceneManager("Scene");
+    const std::string name = "dyn_mesh_" + std::to_string(next_effect_id_ ++);
+    Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create(name, "BATTLE_MODELS");
+    Ogre::Pass* pass = material->getTechnique(0)->getPass(0);
+    pass->setLightingEnabled(false);
+    pass->setCullingMode(Ogre::CULL_NONE);
+    switch (blend){
+        case 1:
+            pass->setSceneBlending(Ogre::SBT_ADD);
+            pass->setDepthWriteEnabled(false);
+            break;
+        case 2:
+            pass->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);
+            pass->setDepthWriteEnabled(false);
+            break;
+        default:
+            pass->setSceneBlending(Ogre::SBT_REPLACE);
+            pass->setDepthWriteEnabled(true);
+    }
+    const std::string image = texture;
+    if (!image.empty()){
+        // The image can be in the battle models or in the images of the UI.
+        std::string group = "";
+        if (Ogre::ResourceGroupManager::getSingleton().resourceExists("BATTLE_MODELS", image)) group = "BATTLE_MODELS";
+        else if (Ogre::ResourceGroupManager::getSingleton().resourceExists("IMAGES", image)) group = "IMAGES";
+        if (group.empty()){
+            LOG_WARNING("Image '" + image + "' of a dynamic mesh doesn't exist.");
+        }
+        else{
+            Ogre::TextureUnitState* unit = pass->createTextureUnitState();
+            unit->setTexture(Ogre::TextureManager::getSingleton().load(image, group));
+            unit->setTextureAddressingMode(Ogre::TextureUnitState::TAM_CLAMP);
+        }
+    }
+    DynamicMesh mesh;
+    mesh.object = scene->createManualObject(name);
+    mesh.object->setDynamic(true);
+    mesh.material = name;
+    scene->getRootSceneNode()->createChildSceneNode(name)->attachObject(mesh.object);
+    dynamic_meshes_[name] = mesh;
+    return name;
+}
+
+void BattleManager::ScriptSetDynamicMesh(const char* name, std::vector<float> vertices){
+    auto found = dynamic_meshes_.find(name);
+    if (found == dynamic_meshes_.end()) return;
+    DynamicMesh& mesh = found->second;
+    size_t count = vertices.size() / 9;
+    count -= count % 3;
+    if (count == 0){
+        if (mesh.filled){
+            mesh.object->clear();
+            mesh.filled = false;
+        }
+        return;
+    }
+    if (mesh.filled) mesh.object->beginUpdate(0);
+    else mesh.object->begin(mesh.material, Ogre::RenderOperation::OT_TRIANGLE_LIST, "BATTLE_MODELS");
+    for (size_t i = 0; i < count; ++ i){
+        const float* v = &vertices[9 * i];
+        mesh.object->position(v[0], v[1], v[2]);
+        mesh.object->textureCoord(v[3], v[4]);
+        mesh.object->colour(v[5], v[6], v[7], v[8]);
+    }
+    mesh.object->end();
+    mesh.filled = true;
+}
+
+void BattleManager::ScriptRemoveDynamicMesh(const char* name){
+    auto found = dynamic_meshes_.find(name);
+    if (found == dynamic_meshes_.end()) return;
+    Ogre::SceneManager* scene = Ogre::Root::getSingleton().getSceneManager("Scene");
+    scene->getRootSceneNode()->removeAndDestroyChild(found->first);
+    scene->destroyManualObject(found->second.object);
+    Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().getByName(found->second.material, "BATTLE_MODELS");
+    if (material != nullptr) Ogre::MaterialManager::getSingleton().remove(material);
+    dynamic_meshes_.erase(found);
+}
+
+void BattleManager::ClearDynamicMeshes(){
+    while (!dynamic_meshes_.empty()) ScriptRemoveDynamicMesh(dynamic_meshes_.begin()->first.c_str());
+}
+
+void BattleManager::ScriptSetCameraPosition(
+  const float x, const float y, const float z,
+  const float look_x, const float look_y, const float look_z
+){
+    if (module_ != Module::BATTLE) return;
+    CameraManager::getSingleton().SetBattleCameraUpright(
+      Ogre::Vector3(x, y, z), Ogre::Vector3(look_x, look_y, look_z)
+    );
+}
+
 void BattleManager::AddCamera(
 void BattleManager::AddCamera(
   const unsigned int id, const Ogre::Vector3 pos, const Ogre::Vector3 dir
   const unsigned int id, const Ogre::Vector3 pos, const Ogre::Vector3 dir
 ){
 ){
@@ -506,6 +617,17 @@ int BattleManager::ScriptSetCamera(const int index){
     return camera_.size();
     return camera_.size();
 }
 }
 
 
+std::tuple<float, float, float, float, float, float> BattleManager::ScriptGetCamera(const int index){
+    if (index < 0 || index >= static_cast<int>(camera_.size())){
+        return std::make_tuple(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f);
+    }
+    const BattleCamera& camera = camera_.at(index);
+    return std::make_tuple(
+      camera.location.x, camera.location.y, camera.location.z,
+      camera.orientation.x, camera.orientation.y, camera.orientation.z
+    );
+}
+
 void BattleManager::SetInitialCamera(const unsigned int id){
 void BattleManager::SetInitialCamera(const unsigned int id){
     if (module_ != Module::BATTLE){
     if (module_ != Module::BATTLE){
         LOG_ERROR("Tried to set the camera in the BattleManager, but it's not in battle mode.");
         LOG_ERROR("Tried to set the camera in the BattleManager, but it's not in battle mode.");

+ 85 - 1
src/core/BattleManager.h

@@ -15,6 +15,11 @@
 
 
 #pragma once
 #pragma once
 
 
+#include <map>
+#include <string>
+#include <tuple>
+#include <vector>
+#include <OgreManualObject.h>
 #include <OgreSingleton.h>
 #include <OgreSingleton.h>
 #include "Enemy.h"
 #include "Enemy.h"
 #include "Event.h"
 #include "Event.h"
@@ -293,7 +298,8 @@ class BattleManager : public Manager, public Ogre::Singleton<BattleManager>{
          * scaled and blended from the scripts, and should be removed with
          * scaled and blended from the scripts, and should be removed with
          * {@see ScriptRemoveEffectModel} when the effect ends.
          * {@see ScriptRemoveEffectModel} when the effect ends.
          *
          *
-         * @param[in] model Model name, without path or extension, like "magic_faira_1".
+         * @param[in] model Model name, without path or extension, like "magic_faira_1". A name
+         * with a folder, like "attacks/cyvadat" for a summon, is looked for in models/battle.
          * @param[in] x Position, X coordinate.
          * @param[in] x Position, X coordinate.
          * @param[in] y Position, Y coordinate.
          * @param[in] y Position, Y coordinate.
          * @param[in] z Position, Z coordinate.
          * @param[in] z Position, Z coordinate.
@@ -311,6 +317,38 @@ class BattleManager : public Manager, public Ogre::Singleton<BattleManager>{
          */
          */
         void ScriptRemoveEffectModel(const char* name);
         void ScriptRemoveEffectModel(const char* name);
 
 
+        /**
+         * Creates a mesh that the scripts fill with triangles, for the effects that are made of
+         * geometry calculated every frame (like the ground of some summons).
+         *
+         * Use {@see ScriptSetDynamicMesh} to give it triangles and {@see ScriptRemoveDynamicMesh}
+         * to remove it. The meshes that are left are removed when the battle ends.
+         *
+         * @param[in] texture Image to put on the triangles, a name of a resource (like
+         * effects/common_rock_c.png in the battle models, or battle_fx/common_graund.png in the
+         * images). Empty for no texture.
+         * @param[in] blend 0 for opaque triangles, 1 for additive blending and 2 for alpha blending.
+         * @return Name of the mesh, empty if it couldn't be created.
+         */
+        std::string ScriptCreateDynamicMesh(const char* texture, const int blend);
+
+        /**
+         * Sets the triangles of a mesh, replacing the previous ones.
+         *
+         * @param[in] name Name of the mesh.
+         * @param[in] vertices Vertices of the triangles, 9 numbers each, 3 vertices per triangle:
+         * x, y, z (scene position), u, v (position in the texture, 0 to 1), and r, g, b, a (colour,
+         * 0 to 1). Empty to show nothing.
+         */
+        void ScriptSetDynamicMesh(const char* name, std::vector<float> vertices);
+
+        /**
+         * Removes a mesh created with {@see ScriptCreateDynamicMesh}.
+         *
+         * @param[in] name Name of the mesh.
+         */
+        void ScriptRemoveDynamicMesh(const char* name);
+
 
 
         /**
         /**
          * Sets the battle layout.
          * Sets the battle layout.
@@ -549,6 +587,33 @@ class BattleManager : public Manager, public Ogre::Singleton<BattleManager>{
          */
          */
         int ScriptSetCamera(const int index);
         int ScriptSetCamera(const int index);
 
 
+        /**
+         * Gets the position of a camera of the formation and the point it looks at.
+         *
+         * @param index Index of the camera.
+         * @return X, Y and Z of the position and of the point it looks at, all zero if the camera
+         * doesn't exist.
+         */
+        std::tuple<float, float, float, float, float, float> ScriptGetCamera(const int index);
+
+        /**
+         * Places the battle camera at any position, for the cameras of the effects.
+         *
+         * Use {@see ScriptSetCamera} to go back to one of the cameras of the formation.
+         * To be called from Lua scripts.
+         *
+         * @param[in] x Camera position, X coordinate.
+         * @param[in] y Camera position, Y coordinate.
+         * @param[in] z Camera position, Z coordinate.
+         * @param[in] look_x Point the camera looks at, X coordinate.
+         * @param[in] look_y Point the camera looks at, Y coordinate.
+         * @param[in] look_z Point the camera looks at, Z coordinate.
+         */
+        void ScriptSetCameraPosition(
+          const float x, const float y, const float z,
+          const float look_x, const float look_y, const float look_z
+        );
+
         /**
         /**
          * Adds a camera for the next battle.
          * Adds a camera for the next battle.
          *
          *
@@ -567,6 +632,25 @@ class BattleManager : public Manager, public Ogre::Singleton<BattleManager>{
          */
          */
         unsigned int next_effect_id_ = 0;
         unsigned int next_effect_id_ = 0;
 
 
+        /**
+         * A mesh made of triangles that change, with the data needed to destroy it.
+         */
+        struct DynamicMesh{
+            Ogre::ManualObject* object = nullptr;
+            Ogre::String material;
+            bool filled = false;
+        };
+
+        /**
+         * The meshes made by {@see ScriptCreateDynamicMesh}, by name.
+         */
+        std::map<std::string, DynamicMesh> dynamic_meshes_;
+
+        /**
+         * Destroys all the meshes made by {@see ScriptCreateDynamicMesh}.
+         */
+        void ClearDynamicMeshes();
+
 
 
         /**
         /**
          * Loads the party members into the battle.
          * Loads the party members into the battle.

+ 23 - 0
src/core/CameraManager.cpp

@@ -229,6 +229,29 @@ void CameraManager::SetBattleCamera(const Ogre::Vector3 position, const Ogre::Ve
     camera_->move(Ogre::Vector3(0, 0, -4));
     camera_->move(Ogre::Vector3(0, 0, -4));
 }
 }
 
 
+void CameraManager::SetBattleCameraUpright(
+  const Ogre::Vector3 position, const Ogre::Vector3 look_at
+){
+    Ogre::Vector3 direction = look_at - position;
+    if (direction.squaredLength() < 1e-10f) return;
+    direction.normalise();
+    // Camera axes: X to the right, Y up and Z backwards, with the Z axis of the scene up.
+    Ogre::Vector3 right = direction.crossProduct(Ogre::Vector3::UNIT_Z);
+    // Looking straight up or down: any side is the right one.
+    if (right.squaredLength() < 1e-8f) right = Ogre::Vector3::UNIT_X;
+    right.normalise();
+    const Ogre::Vector3 up = right.crossProduct(direction);
+    camera_->resetFrustumExtents();
+    camera_->setFOVy(Ogre::Radian(Ogre::Math::PI / 4.0f));
+    camera_->setPosition(position);
+    camera_->setOrientation(Ogre::Quaternion(right, up, -direction));
+    // Compensation of the battle UI, like the other battle cameras. They move the camera 4 units
+    // down at about 60 units from the scene, so it's proportional to the distance here, because
+    // the cameras of the effects go from very far to very close.
+    const float distance = (look_at - position).length();
+    camera_->move(Ogre::Vector3(0, 0, -0.066f * distance));
+}
+
 void CameraManager::EndBattleCamera(){
 void CameraManager::EndBattleCamera(){
     /*std::cout << "CAMERA BATTLE END: " << camera_->getPosition().x << ", "
     /*std::cout << "CAMERA BATTLE END: " << camera_->getPosition().x << ", "
       << camera_->getPosition().y << ", " << camera_->getPosition().z << ", "
       << camera_->getPosition().y << ", " << camera_->getPosition().z << ", "

+ 11 - 0
src/core/CameraManager.h

@@ -184,6 +184,17 @@ class CameraManager : public Manager, public Ogre::Singleton<CameraManager>{
          */
          */
         void SetBattleCamera(const Ogre::Vector3 position, const Ogre::Vector3 orientation);
         void SetBattleCamera(const Ogre::Vector3 position, const Ogre::Vector3 orientation);
 
 
+        /**
+         * Sets the battle camera, always with the Z axis of the scene pointing up.
+         *
+         * {@see SetBattleCamera} is only upright for cameras looking toward negative X, so this
+         * one is for the cameras of the effects, that can look anywhere.
+         *
+         * @param[in] position Camera position.
+         * @param[in] look_at Point the camera looks at.
+         */
+        void SetBattleCameraUpright(const Ogre::Vector3 position, const Ogre::Vector3 look_at);
+
         /**
         /**
          * Projects a point of the scene into the coordinates of the UI.
          * Projects a point of the scene into the coordinates of the UI.
          *
          *

+ 5 - 2
src/core/Entity.cpp

@@ -76,7 +76,8 @@ Entity::Entity(const Ogre::String& name, Ogre::SceneNode* node):
   animation_play_type_(Entity::PLAY_LOOPED),
   animation_play_type_(Entity::PLAY_LOOPED),
   is_character_(false),
   is_character_(false),
   character_id_(-1),
   character_id_(-1),
-  is_line_(false)
+  is_line_(false),
+  debug_hidden_(false)
 {
 {
     model_root_node_ = scene_node_->createChildSceneNode();
     model_root_node_ = scene_node_->createChildSceneNode();
     model_node_ = model_root_node_->createChildSceneNode();
     model_node_ = model_root_node_->createChildSceneNode();
@@ -128,8 +129,10 @@ void Entity::Update() {
     }
     }
 }
 }
 
 
+void Entity::SetDebugHidden(const bool hidden){debug_hidden_ = hidden;}
+
 void Entity::UpdateDebug(){
 void Entity::UpdateDebug(){
-    int debug = cv_debug_entity.GetI();
+    int debug = debug_hidden_ ? 0 : cv_debug_entity.GetI();
     direction_node_->setVisible(debug > 0);
     direction_node_->setVisible(debug > 0);
     solid_collision_node_->setVisible(debug > 0 && solid_);
     solid_collision_node_->setVisible(debug > 0 && solid_);
     talk_collision_node_->setVisible(debug > 0 && talkable_);
     talk_collision_node_->setVisible(debug > 0 && talkable_);

+ 34 - 0
src/core/Entity.h

@@ -351,6 +351,25 @@ class Entity{
          */
          */
         virtual void ScriptSetAlpha(const float alpha){}
         virtual void ScriptSetAlpha(const float alpha){}
 
 
+        /**
+         * Puts an image on the model, for the effect meshes that have no texture in the files because
+         * the code of the original effect chooses it. Call it before {@see ScriptSetAlpha}.
+         *
+         * @param[in] texture Name of the image, a resource of the battle models or of the images.
+         */
+        virtual void ScriptSetTexture(const char* texture){}
+
+        /**
+         * Gets the position in the scene of a bone of the skeleton of the model, for the effects that
+         * start from a part of a creature. Bones are called bone0, bone1...
+         *
+         * @param[in] bone Number of the bone.
+         * @return X, Y and Z in the scene (0, 0, 0 if there is no such bone).
+         */
+        virtual std::tuple<float, float, float> ScriptGetBonePosition(const int bone){
+            return std::make_tuple(0.0f, 0.0f, 0.0f);
+        }
+
         /**
         /**
          * Frees the resources that were created for the entity, before it is removed.
          * Frees the resources that were created for the entity, before it is removed.
          */
          */
@@ -1161,6 +1180,16 @@ class Entity{
          */
          */
         void ScriptSetDefaultAnimation(const char* animation);
         void ScriptSetDefaultAnimation(const char* animation);
 
 
+        /**
+         * Hides the debug information of the entity (see the config variable debug_entity).
+         *
+         * For entities that are created in large numbers while the game runs, like the meshes of
+         * the effects of the battles, so they don't fill the debug text of the screen.
+         *
+         * @param[in] hidden True to not show any debug information.
+         */
+        void SetDebugHidden(const bool hidden);
+
         /**
         /**
          * Adds the entity's animation to the sync queue.
          * Adds the entity's animation to the sync queue.
          *
          *
@@ -1541,5 +1570,10 @@ class Entity{
          */
          */
         bool is_line_;
         bool is_line_;
 
 
+        /**
+         * Indicates if the debug information of the entity is never shown.
+         */
+        bool debug_hidden_;
+
 };
 };
 
 

+ 52 - 9
src/core/EntityModel.cpp

@@ -17,11 +17,14 @@
 #include <algorithm>
 #include <algorithm>
 #include <OgreEntity.h>
 #include <OgreEntity.h>
 #include <OgreSubEntity.h>
 #include <OgreSubEntity.h>
+#include <OgreBone.h>
+#include <OgreSkeletonInstance.h>
 #include <OgreMaterialManager.h>
 #include <OgreMaterialManager.h>
 #include <OgreResourceGroupManager.h>
 #include <OgreResourceGroupManager.h>
 #include <OgreTechnique.h>
 #include <OgreTechnique.h>
 #include <OgrePass.h>
 #include <OgrePass.h>
 #include <OgreRoot.h>
 #include <OgreRoot.h>
+#include <OgreTextureManager.h>
 #include "core/EntityModel.h"
 #include "core/EntityModel.h"
 #include "core/EntityManager.h"
 #include "core/EntityManager.h"
 #include "core/Logger.h"
 #include "core/Logger.h"
@@ -81,21 +84,61 @@ unsigned int EntityModel::GetAnimationCount() const{
 
 
 Ogre::Entity* EntityModel::GetModel(){return model_;}
 Ogre::Entity* EntityModel::GetModel(){return model_;}
 
 
+Ogre::MaterialPtr EntityModel::OwnMaterial(Ogre::SubEntity* sub_entity){
+    Ogre::MaterialPtr material = sub_entity->getMaterial();
+    if (std::find(own_materials_.begin(), own_materials_.end(), material->getName()) == own_materials_.end()){
+        const Ogre::String own_name = material->getName() + "/" + name_;
+        Ogre::MaterialPtr own = Ogre::MaterialManager::getSingleton().getByName(own_name, material->getGroup());
+        if (own == nullptr) own = material->clone(own_name);
+        own_materials_.push_back(own_name);
+        sub_entity->setMaterial(own);
+        material = own;
+    }
+    return material;
+}
+
+void EntityModel::ScriptSetTexture(const char* texture){
+    const Ogre::String image(texture);
+    Ogre::String group;
+    if (Ogre::ResourceGroupManager::getSingleton().resourceExists("BATTLE_MODELS", image)) group = "BATTLE_MODELS";
+    else if (Ogre::ResourceGroupManager::getSingleton().resourceExists("IMAGES", image)) group = "IMAGES";
+    else{
+        LOG_WARNING("Image '" + image + "' for the model '" + name_ + "' doesn't exist.");
+        return;
+    }
+    Ogre::TexturePtr loaded = Ogre::TextureManager::getSingleton().load(image, group);
+    for (unsigned int s = 0; s < model_->getNumSubEntities(); ++ s){
+        Ogre::MaterialPtr material = OwnMaterial(model_->getSubEntity(s));
+        for (unsigned short t = 0; t < material->getNumTechniques(); ++ t){
+            Ogre::Technique* technique = material->getTechnique(t);
+            for (unsigned short p = 0; p < technique->getNumPasses(); ++ p){
+                Ogre::Pass* pass = technique->getPass(p);
+                pass->removeAllTextureUnitStates();
+                pass->createTextureUnitState()->setTexture(loaded);
+                pass->setLightingEnabled(false);
+            }
+        }
+    }
+}
+
+std::tuple<float, float, float> EntityModel::ScriptGetBonePosition(const int bone){
+    Ogre::SkeletonInstance* skeleton = model_->getSkeleton();
+    const Ogre::String name = "bone" + std::to_string(bone);
+    if (skeleton == nullptr || !skeleton->hasBone(name)) return std::make_tuple(0.0f, 0.0f, 0.0f);
+    // Bring the skeleton to the current frame of the animation.
+    model_->_updateAnimation();
+    const Ogre::Vector3 position
+      = model_->_getParentNodeFullTransform() * skeleton->getBone(name)->_getDerivedPosition();
+    return std::make_tuple(position.x, position.y, position.z);
+}
+
 void EntityModel::ScriptSetBlend(const int blend){
 void EntityModel::ScriptSetBlend(const int blend){
     if (blend == blend_) return;
     if (blend == blend_) return;
     blend_ = blend;
     blend_ = blend;
     for (unsigned int s = 0; s < model_->getNumSubEntities(); ++ s){
     for (unsigned int s = 0; s < model_->getNumSubEntities(); ++ s){
         Ogre::SubEntity* sub_entity = model_->getSubEntity(s);
         Ogre::SubEntity* sub_entity = model_->getSubEntity(s);
         // Materials are shared among all the entities of a mesh, so use one of its own.
         // Materials are shared among all the entities of a mesh, so use one of its own.
-        Ogre::MaterialPtr material = sub_entity->getMaterial();
-        if (std::find(own_materials_.begin(), own_materials_.end(), material->getName()) == own_materials_.end()){
-            const Ogre::String own_name = material->getName() + "/" + name_;
-            Ogre::MaterialPtr own = Ogre::MaterialManager::getSingleton().getByName(own_name, material->getGroup());
-            if (own == nullptr) own = material->clone(own_name);
-            own_materials_.push_back(own_name);
-            sub_entity->setMaterial(own);
-            material = own;
-        }
+        Ogre::MaterialPtr material = OwnMaterial(sub_entity);
         for (unsigned short t = 0; t < material->getNumTechniques(); ++ t){
         for (unsigned short t = 0; t < material->getNumTechniques(); ++ t){
             Ogre::Technique* technique = material->getTechnique(t);
             Ogre::Technique* technique = material->getTechnique(t);
             for (unsigned short p = 0; p < technique->getNumPasses(); ++ p){
             for (unsigned short p = 0; p < technique->getNumPasses(); ++ p){

+ 10 - 0
src/core/EntityModel.h

@@ -70,6 +70,10 @@ class EntityModel : public Entity{
 
 
         virtual void ScriptSetAlpha(const float alpha);
         virtual void ScriptSetAlpha(const float alpha);
 
 
+        virtual void ScriptSetTexture(const char* texture);
+
+        virtual std::tuple<float, float, float> ScriptGetBonePosition(const int bone);
+
         virtual void ReleaseResources();
         virtual void ReleaseResources();
 
 
         /**
         /**
@@ -102,6 +106,12 @@ class EntityModel : public Entity{
 
 
     private:
     private:
 
 
+        /**
+         * Gets the material of a part of the model that only this model uses, making it from the shared
+         * one the first time.
+         */
+        Ogre::MaterialPtr OwnMaterial(Ogre::SubEntity* sub_entity);
+
         /**
         /**
          * Constructor.
          * Constructor.
          */
          */

+ 7 - 0
src/core/ScriptManagerBinds.h

@@ -137,6 +137,8 @@ void ScriptManager::InitBinds(){
       "set_model_rotation", &Entity::ScriptSetModelRotation,
       "set_model_rotation", &Entity::ScriptSetModelRotation,
       "set_blend", &Entity::ScriptSetBlend,
       "set_blend", &Entity::ScriptSetBlend,
       "set_alpha", &Entity::ScriptSetAlpha,
       "set_alpha", &Entity::ScriptSetAlpha,
+      "set_texture", &Entity::ScriptSetTexture,
+      "get_bone_position", &Entity::ScriptGetBonePosition,
       "is_visible", &Entity::IsVisible,
       "is_visible", &Entity::IsVisible,
       "set_move_auto_speed", &Entity::SetMoveAutoSpeed,
       "set_move_auto_speed", &Entity::SetMoveAutoSpeed,
       "get_move_auto_speed", &Entity::GetMoveAutoSpeed,
       "get_move_auto_speed", &Entity::GetMoveAutoSpeed,
@@ -233,6 +235,11 @@ void ScriptManager::InitBinds(){
       "remove_effect_model", &BattleManager::ScriptRemoveEffectModel,
       "remove_effect_model", &BattleManager::ScriptRemoveEffectModel,
       "has_attack", &BattleManager::HasAttackData,
       "has_attack", &BattleManager::HasAttackData,
       "set_camera", &BattleManager::ScriptSetCamera,
       "set_camera", &BattleManager::ScriptSetCamera,
+      "set_camera_position", &BattleManager::ScriptSetCameraPosition,
+      "get_camera", &BattleManager::ScriptGetCamera,
+      "create_dynamic_mesh", &BattleManager::ScriptCreateDynamicMesh,
+      "set_dynamic_mesh", &BattleManager::ScriptSetDynamicMesh,
+      "remove_dynamic_mesh", &BattleManager::ScriptRemoveDynamicMesh,
       "get_layout", &BattleManager::ScriptGetLayout,
       "get_layout", &BattleManager::ScriptGetLayout,
       "get_attack", [](BattleManager& manager, const int id, sol::this_state state) -> sol::object{
       "get_attack", [](BattleManager& manager, const int id, sol::this_state state) -> sol::object{
           sol::state_view view(state);
           sol::state_view view(state);

+ 224 - 0
src/installer/BattleCameraScripts.h

@@ -0,0 +1,224 @@
+/*
+ * Copyright (C) 2026 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
+ * the 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#pragma once
+
+#include <cstdint>
+#include <cstring>
+#include <fstream>
+#include <iterator>
+#include <map>
+#include <ostream>
+#include <string>
+#include <vector>
+
+/**
+ * Reads the camera scripts of the battles (camdat0.bin, camdat1.bin and camdat2.bin of data/battle).
+ *
+ * The files have four pointers (the PSX memory address 0x801a0000 plus the offset in the file). The
+ * first points to a list of scripts for the position of the camera, indexed by (camera id * 3 +
+ * variant), and the second to the same for the point it looks at. The camera ids are the ones of
+ * the attacks (camera_single and camera_multiple) and of the enemy attacks. Several entries share
+ * the same script.
+ *
+ * Scripts are lists of bytes: an opcode (0xd5 to 0xff, other values do nothing) followed by its
+ * operands (bytes and 16 bit values). The lengths of the operands for each opcode of the two kinds
+ * of scripts were found in the interpreter of ff7.exe (0x5c2341 for the position, 0x5c3f45 for the
+ * point it looks at). A script ends with 0xff, or with 0xfe followed by 0xc0 (loop).
+ */
+namespace BattleCameraScripts{
+
+    /**
+     * A file: for each kind of script, the list of the entries (the key of the script it uses), and
+     * the scripts by the offset in the file.
+     */
+    struct Set{
+        std::vector<uint32_t> position;
+        std::vector<uint32_t> look;
+        std::map<uint32_t, std::vector<uint8_t>> scripts;
+    };
+
+    /**
+     * Operands of the opcodes of the position scripts (-1 if it isn't an opcode).
+     */
+    inline int PositionLength(const uint8_t op){
+        switch (op){
+            case 0xd5: return 2;
+            case 0xd6: return 0;
+            case 0xd7: return 2;
+            case 0xd8: return 9;
+            case 0xd9: case 0xda: case 0xdb: case 0xdc: return 0;
+            case 0xdd: case 0xde: return 1;
+            case 0xdf: return 0;
+            case 0xe0: return 2;
+            case 0xe1: return 0;
+            case 0xe2: return 1;
+            case 0xe3: return 9;
+            case 0xe4: case 0xe5: return 8;
+            case 0xe6: return 7;
+            case 0xe7: case 0xe9: return 8;
+            case 0xeb: return 9;
+            case 0xef: return 8;
+            case 0xf0: return 7;
+            case 0xf1: return 0;
+            case 0xf2: case 0xf3: return 5;
+            case 0xf4: return 0;
+            case 0xf5: return 1;
+            case 0xf7: return 7;
+            case 0xf8: return 12;
+            case 0xf9: return 6;
+            case 0xfe: case 0xff: return 0;
+            default: return -1;
+        }
+    }
+
+    /**
+     * Operands of the opcodes of the look at scripts (-1 if it isn't an opcode).
+     */
+    inline int LookLength(const uint8_t op){
+        switch (op){
+            case 0xd8: return 9;
+            case 0xd9: case 0xdb: case 0xdc: return 0;
+            case 0xdd: case 0xde: return 1;
+            case 0xdf: return 0;
+            case 0xe0: return 2;
+            case 0xe1: return 0;
+            case 0xe2: return 1;
+            case 0xe3: return 9;
+            case 0xe4: case 0xe5: return 8;
+            case 0xe6: return 7;
+            case 0xe8: case 0xea: return 8;
+            case 0xec: return 9;
+            case 0xf0: return 8;
+            case 0xf4: return 0;
+            case 0xf5: return 1;
+            case 0xf8: case 0xf9: return 7;
+            case 0xfa: return 6;
+            case 0xfe: case 0xff: return 0;
+            default: return -1;
+        }
+    }
+
+    inline uint32_t ReadU32(const std::vector<uint8_t>& d, const size_t o){
+        uint32_t v = 0;
+        if (o + 4 <= d.size()) std::memcpy(&v, &d[o], 4);
+        return v;
+    }
+
+    /**
+     * Reads the script that starts at an offset.
+     *
+     * @return False if it doesn't end before the end of the file.
+     */
+    inline bool ReadScript(
+      const std::vector<uint8_t>& d, const uint32_t start, const bool position, std::vector<uint8_t>& out
+    ){
+        out.clear();
+        size_t o = start;
+        while (o < d.size()){
+            const uint8_t op = d[o];
+            const int n = position ? PositionLength(op) : LookLength(op);
+            if (n < 0){
+                // Bytes that aren't opcodes do nothing.
+                out.push_back(op);
+                ++ o;
+                continue;
+            }
+            if (o + 1 + n > d.size()) return false;
+            for (int i = 0; i <= n; ++ i) out.push_back(d[o + i]);
+            o += 1 + n;
+            if (op == 0xff) return true;
+            if (op == 0xfe && o < d.size() && d[o] == 0xc0){
+                out.push_back(0xc0);
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Reads a file.
+     *
+     * @return False if it isn't a valid file.
+     */
+    inline bool ReadFile(const std::string& path, Set& set){
+        set = Set();
+        std::ifstream file(path, std::ios::binary);
+        if (!file) return false;
+        const std::vector<uint8_t> d((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
+        if (d.size() < 0x20) return false;
+        const uint32_t base = 0x801a0000;
+        const uint32_t first = ReadU32(d, 0) - base;
+        const uint32_t second = ReadU32(d, 4) - base;
+        if (first >= d.size() || second >= d.size() || second <= first) return false;
+        const size_t count = (second - first) / 4;
+        for (int kind = 0; kind < 2; ++ kind){
+            const bool position = kind == 0;
+            const uint32_t table = position ? first : second;
+            std::vector<uint32_t>& list = position ? set.position : set.look;
+            for (size_t i = 0; i < count; ++ i){
+                const uint32_t offset = ReadU32(d, table + 4 * i) - base;
+                if (offset >= d.size()) return false;
+                list.push_back(offset);
+                // The key has the kind, because the opcodes are different.
+                std::vector<uint8_t> script;
+                if (!ReadScript(d, offset, position, script)) return false;
+                const uint32_t key = offset * 2 + (position ? 0 : 1);
+                set.scripts[key] = script;
+                list.back() = key;
+            }
+        }
+        return true;
+    }
+
+    /**
+     * Writes the sets to a Lua file. Game.BattleCameras[file] has the list "position" and "look"
+     * (index = camera id * 3 + variant + 1, the value is the name of a script), and the table
+     * "scripts" with the bytes of each one.
+     */
+    inline void WriteLua(std::ostream& out, const std::map<int, Set>& sets){
+        out << "-- Camera scripts of the battles, read from camdat0.bin, camdat1.bin and camdat2.bin.\n"
+            << "-- Game.BattleCameras[file].position[camera id * 3 + variant + 1] is the name of a script in\n"
+            << "-- Game.BattleCameras[file].scripts (the bytes of the script), the same for .look (the point\n"
+            << "-- the camera looks at). See scripts/battle/battle_camera.lua for the format.\n"
+            << "Game.BattleCameras = Game.BattleCameras or {}\n";
+        for (const auto& item : sets){
+            const Set& set = item.second;
+            const std::string name = "Game.BattleCameras[" + std::to_string(item.first) + "]";
+            out << name << " = {position = {}, look = {}, scripts = {}}\n";
+            for (int kind = 0; kind < 2; ++ kind){
+                const std::vector<uint32_t>& list = kind == 0 ? set.position : set.look;
+                out << name << "." << (kind == 0 ? "position" : "look") << " = {";
+                for (size_t i = 0; i < list.size(); ++ i){
+                    if (i % 16 == 0) out << "\n    ";
+                    out << list[i] << ", ";
+                }
+                out << "\n}\n";
+            }
+            for (const auto& script : set.scripts){
+                out << name << ".scripts[" << script.first << "] = {";
+                for (size_t i = 0; i < script.second.size(); ++ i){
+                    if (i % 24 == 0) out << "\n    ";
+                    out << static_cast<int>(script.second[i]) << ", ";
+                }
+                out << "\n}\n";
+            }
+        }
+    }
+
+}

+ 111 - 29
src/installer/BattleDataInstaller.cpp

@@ -28,6 +28,9 @@
 #include <boost/filesystem.hpp>
 #include <boost/filesystem.hpp>
 #include <OgreMesh.h>
 #include <OgreMesh.h>
 #include "BattleDataInstaller.h"
 #include "BattleDataInstaller.h"
+#include "BattleCameraScripts.h"
+#include "ExeEffectCameras.h"
+#include "ExeEffectMeshes.h"
 #include "ModelMaterials.h"
 #include "ModelMaterials.h"
 #include "TexFile.h"
 #include "TexFile.h"
 #include "data/VGearsHRCFileManager.h"
 #include "data/VGearsHRCFileManager.h"
@@ -768,16 +771,64 @@ void BattleDataInstaller::WriteEffectModels(){
     }
     }
     file << "}\n";
     file << "}\n";
     WriteEffectSprites();
     WriteEffectSprites();
+    WriteEffectCameras();
+    WriteEffectMeshes();
+    WriteBattleCameras();
+}
+
+void BattleDataInstaller::WriteBattleCameras(){
+    // The scripts of the cameras of the battles (see BattleCameraScripts.h).
+    std::map<int, BattleCameraScripts::Set> sets;
+    for (int i = 0; i < 3; ++ i){
+        const std::string name = "data/battle/camdat" + std::to_string(i) + ".bin";
+        auto path = const_cast<DiskImage&>(disk_image_).filePath(name);
+        BattleCameraScripts::Set set;
+        if (path != nullptr && BattleCameraScripts::ReadFile(*path, set)) sets[i] = set;
+        else std::cerr << "[WARNING] Can't read " << name << "." << std::endl;
+    }
+    std::ofstream file(data_dir_ + "gamedata/battle_cameras.lua");
+    BattleCameraScripts::WriteLua(file, sets);
+}
+
+void BattleDataInstaller::WriteEffectMeshes(){
+    // The meshes of the effects that are in the data of ff7.exe, like the ground of Ifrit and the
+    // mountain of Ramuh (see ExeEffectMeshes.h). Names are the address of the block in the executable.
+    std::map<uint32_t, ExeEffectMeshes::Mesh> meshes;
+    auto exe_path = const_cast<DiskImage&>(disk_image_).filePath("ff7.exe");
+    if (exe_path == nullptr || !ExeEffectMeshes::Extract(*exe_path, meshes)){
+        std::cerr << "[WARNING] Can't read the meshes of the effects from ff7.exe." << std::endl;
+    }
+    std::ofstream file(data_dir_ + "gamedata/effect_meshes.lua");
+    ExeEffectMeshes::WriteLua(file, meshes);
+}
+
+void BattleDataInstaller::WriteEffectCameras(){
+    // The scripts of the cameras are in the data of ff7.exe, and are found from the code that
+    // uses them. Names are the address of the script in memory.
+    std::map<uint32_t, std::vector<int16_t>> scripts;
+    auto exe_path = const_cast<DiskImage&>(disk_image_).filePath("ff7.exe");
+    if (exe_path == nullptr || !ExeEffectCameras::Extract(*exe_path, scripts)){
+        std::cerr << "[WARNING] Can't read the camera scripts of the effects from ff7.exe." << std::endl;
+    }
+    std::ofstream file(data_dir_ + "gamedata/effect_cameras.lua");
+    file << "-- Camera scripts of the battle effects, read from ff7.exe. Game.EffectCameras[name] is a list\n"
+         << "-- of 16 bit words, with the address of the script in the executable as the name (like\n"
+         << "-- 0x8ae268). See scripts/battle/effect_camera.lua for the format.\n"
+         << "Game.EffectCameras = Game.EffectCameras or {}\n";
+    for (const auto& script : scripts){
+        file << "Game.EffectCameras[\"0x" << std::hex << script.first << std::dec << "\"] = {";
+        for (size_t i = 0; i < script.second.size(); ++ i){
+            if (i % 16 == 0) file << "\n    ";
+            file << script.second[i] << ", ";
+        }
+        file << "\n}\n";
+    }
 }
 }
 
 
 void BattleDataInstaller::WriteEffectSprites(){
 void BattleDataInstaller::WriteEffectSprites(){
-    // The sprite files (.s) are lists of quads of a sprite sheet, after an 8 byte header ("# " and
-    // the number of frames). Layout found by comparing files, not documented. A quad has:
-    //   flags (4 bytes, plus 4 if the second 16 bit value is not 0),
-    //   draw offset X and Y, signed 16 bit, normally half of the size (centered),
-    //   position of the quad in the texture, U and V, 16 bit,
-    //   4 unknown bytes,
-    //   size of the quad in the texture, width and height in bytes (twice).
+    // The sprite files (.s) are lists of frames, and every frame a list of quads of a sprite sheet (see
+    // the layout below). They are written twice: all the quads one after the other (the first format,
+    // used by the Cure effect) and the frames with their quads (effect_animations.lua).
     // Textures are converted too, with the name of the effect folder as a prefix (common_ for the
     // Textures are converted too, with the name of the effect folder as a prefix (common_ for the
     // archive root), to images/battle_fx, so they can be used as images of sprites.
     // archive root), to images/battle_fx, so they can be used as images of sprites.
     const std::string key_prefix = "ff7/data/battle/";
     const std::string key_prefix = "ff7/data/battle/";
@@ -792,6 +843,13 @@ void BattleDataInstaller::WriteEffectSprites(){
          << "-- (ox, oy) and the flags. The names are the folder and the file, like common_iyashi.\n"
          << "-- (ox, oy) and the flags. The names are the folder and the file, like common_iyashi.\n"
          << "-- Textures are in images/battle_fx, like common_iyashi00.png.\n"
          << "-- Textures are in images/battle_fx, like common_iyashi00.png.\n"
          << "Game.EffectSprites = Game.EffectSprites or {}\n";
          << "Game.EffectSprites = Game.EffectSprites or {}\n";
+    // (The list has the quads of all the frames in order, with the position of the corner as ox, oy.)
+    std::ofstream animations(data_dir_ + "gamedata/effect_animations.lua");
+    animations << "-- Frames of the sprite files (.SPT) of magic.lgp. Game.EffectAnimations[name] is a list of frames and\n"
+               << "-- every frame a list of quads: {x, y, u, v, w, h}, with the position of the corner and the size of the\n"
+               << "-- quad in units of 8 of the effect, and the place in the texture in pixels. The names are the folder\n"
+               << "-- and the file, like common_houden_2.\n"
+               << "Game.EffectAnimations = Game.EffectAnimations or {}\n";
     const std::string dir = output_dir_ + "temp/effects/";
     const std::string dir = output_dir_ + "temp/effects/";
     boost::filesystem::create_directories(data_dir_ + "images/battle_fx/");
     boost::filesystem::create_directories(data_dir_ + "images/battle_fx/");
     for (size_t f = 0; f < magic_lgp_files_.size(); f ++){
     for (size_t f = 0; f < magic_lgp_files_.size(); f ++){
@@ -822,34 +880,58 @@ void BattleDataInstaller::WriteEffectSprites(){
             for (size_t b = 0; b < size; b ++) bytes[b] = sprite_file.readU8();
             for (size_t b = 0; b < size; b ++) bytes[b] = sprite_file.readU8();
             // Only the files with the header of sprite lists.
             // Only the files with the header of sprite lists.
             if (bytes[0] != 0x23 || bytes[1] != 0x20) continue;
             if (bytes[0] != 0x23 || bytes[1] != 0x20) continue;
-            // Each quad has 4 bytes of flags, 4 more if the second 16 bit value is not 0, and then 16
-            // bytes of data. The header count is of frames, not quads, so it's not used.
-            struct Quad{int ox, oy, u, v, w, h;};
-            std::vector<Quad> quads;
+            // After the header (the two characters, and the number of frames as a 32 bit value, at 4)
+            // there are the frames. Each one has two 16 bit values, the second is the number of quads,
+            // and then 20 bytes for every quad: flags (4 bytes), the position of the corner (x and y,
+            // 16 bits), the place in the texture (u and v, 16 bits), 4 more bytes, and the width
+            // (8 bits, twice) and the height (8 bits, twice). Positions and sizes are in units of 8 of
+            // the effect. Layout found in the code that draws them (0x598a7a), and all the files of
+            // magic.lgp end exactly where their last frame ends.
+            struct Quad{int x, y, u, v, w, h;};
+            std::vector<std::vector<Quad>> frames;
+            const uint32_t frame_count = bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (static_cast<uint32_t>(bytes[7]) << 24);
             size_t p = 8;
             size_t p = 8;
             bool valid = true;
             bool valid = true;
-            while (p < size){
+            for (uint32_t fr = 0; fr < frame_count && valid; ++ fr){
                 if (p + 4 > size){valid = false; break;}
                 if (p + 4 > size){valid = false; break;}
-                const bool extra = (bytes[p + 2] | (bytes[p + 3] << 8)) != 0;
-                const size_t q = p + 4 + (extra ? 4 : 0);
-                if (q + 16 > size){valid = false; break;}
-                Quad quad;
-                quad.ox = static_cast<int16_t>(bytes[q] | (bytes[q + 1] << 8));
-                quad.oy = static_cast<int16_t>(bytes[q + 2] | (bytes[q + 3] << 8));
-                quad.u = bytes[q + 4] | (bytes[q + 5] << 8);
-                quad.v = bytes[q + 6] | (bytes[q + 7] << 8);
-                quad.w = bytes[q + 12];
-                quad.h = bytes[q + 13];
-                quads.push_back(quad);
-                p = q + 16;
+                const int count = static_cast<int16_t>(bytes[p + 2] | (bytes[p + 3] << 8));
+                p += 4;
+                if (count < 0 || p + static_cast<size_t>(count) * 20 > size){valid = false; break;}
+                std::vector<Quad> quads;
+                for (int q = 0; q < count; ++ q, p += 20){
+                    Quad quad;
+                    quad.x = static_cast<int16_t>(bytes[p + 4] | (bytes[p + 5] << 8));
+                    quad.y = static_cast<int16_t>(bytes[p + 6] | (bytes[p + 7] << 8));
+                    quad.u = static_cast<int16_t>(bytes[p + 8] | (bytes[p + 9] << 8));
+                    quad.v = static_cast<int16_t>(bytes[p + 10] | (bytes[p + 11] << 8));
+                    quad.w = bytes[p + 16];
+                    quad.h = bytes[p + 18];
+                    quads.push_back(quad);
+                }
+                frames.push_back(quads);
             }
             }
-            if (!valid || quads.empty()) continue;
-            file << "Game.EffectSprites[\"" << key << "_" << EffectSafeName(EffectStem(name)) << "\"] = {\n";
-            for (const Quad& quad : quads){
-                file << "    {u = " << quad.u << ", v = " << quad.v << ", w = " << quad.w << ", h = " << quad.h
-                     << ", ox = " << quad.ox << ", oy = " << quad.oy << "},\n";
+            if (!valid || p != size || frames.empty()) continue;
+            const std::string sprite_name = key + "_" + EffectSafeName(EffectStem(name));
+            // All the quads one after the other, for the effects that pick them by number.
+            file << "Game.EffectSprites[\"" << sprite_name << "\"] = {\n";
+            for (const std::vector<Quad>& quads : frames){
+                for (const Quad& quad : quads){
+                    file << "    {u = " << quad.u << ", v = " << quad.v << ", w = " << quad.w << ", h = " << quad.h
+                         << ", ox = " << quad.x << ", oy = " << quad.y << "},\n";
+                }
             }
             }
             file << "}\n";
             file << "}\n";
+            // The frames, with their quads.
+            animations << "Game.EffectAnimations[\"" << sprite_name << "\"] = {\n";
+            for (const std::vector<Quad>& quads : frames){
+                animations << "    {";
+                for (size_t q = 0; q < quads.size(); ++ q){
+                    animations << (q > 0 ? ", " : "") << "{" << quads[q].x << ", " << quads[q].y << ", " << quads[q].u << ", "
+                               << quads[q].v << ", " << quads[q].w << ", " << quads[q].h << "}";
+                }
+                animations << "},\n";
+            }
+            animations << "}\n";
         }
         }
     }
     }
 }
 }

+ 19 - 0
src/installer/BattleDataInstaller.h

@@ -158,6 +158,25 @@ class BattleDataInstaller{
          */
          */
         void WriteEffectSprites();
         void WriteEffectSprites();
 
 
+        /**
+         * Reads the camera scripts of the battle effects from ff7.exe and writes them to
+         * gamedata/effect_cameras.lua. Called by {@see WriteEffectModels}.
+         */
+        void WriteEffectCameras();
+
+        /**
+         * Reads the camera scripts of the battles (camdat0-2.bin) and writes them to
+         * gamedata/battle_cameras.lua. Called by {@see WriteEffectModels}.
+         */
+        void WriteBattleCameras();
+
+        /**
+         * Reads the meshes of the battle effects that are in the data of ff7.exe (the ground of Ifrit,
+         * the mountain of Ramuh...) and writes them to gamedata/effect_meshes.lua. Called by
+         * {@see WriteEffectModels}.
+         */
+        void WriteEffectMeshes();
+
         /**
         /**
          * Writes enemy data to files.
          * Writes enemy data to files.
          */
          */

+ 15 - 2
src/installer/DiskImage.cpp

@@ -938,6 +938,7 @@ std::unique_ptr<std::string> DiskImage::filePath(std::string file_path) {
     if (requested_segments.isEmpty()) {
     if (requested_segments.isEmpty()) {
         return nullptr;
         return nullptr;
     }
     }
+    std::unique_ptr<std::string> fuzzy_match;
     QDirIterator it(base_dir, QDir::Files, QDirIterator::Subdirectories);
     QDirIterator it(base_dir, QDir::Files, QDirIterator::Subdirectories);
     while (it.hasNext()) {
     while (it.hasNext()) {
         const QString file_full_path = it.next();
         const QString file_full_path = it.next();
@@ -948,18 +949,30 @@ std::unique_ptr<std::string> DiskImage::filePath(std::string file_path) {
         }
         }
 
 
         bool all_segments_match = true;
         bool all_segments_match = true;
+        bool exact = true;
         const int offset = actual_segments.size() - requested_segments.size();
         const int offset = actual_segments.size() - requested_segments.size();
         for (int i = 0; i < requested_segments.size(); ++i) {
         for (int i = 0; i < requested_segments.size(); ++i) {
             if (!segment_matches(requested_segments[i], actual_segments[offset + i])) {
             if (!segment_matches(requested_segments[i], actual_segments[offset + i])) {
                 all_segments_match = false;
                 all_segments_match = false;
                 break;
                 break;
             }
             }
+            if (requested_segments[i] != actual_segments[offset + i]) {
+                exact = false;
+            }
         }
         }
         if (all_segments_match) {
         if (all_segments_match) {
-            return std::make_unique<std::string>(QFileInfo(file_full_path).absoluteFilePath().toStdString());
+            const std::string found = QFileInfo(file_full_path).absoluteFilePath().toStdString();
+            // A file with the same name wins. The names that only begin the same way (like FF7INST.EXE
+            // for ff7.exe) are used only if there is no other one.
+            if (exact) {
+                return std::make_unique<std::string>(found);
+            }
+            if (!fuzzy_match) {
+                fuzzy_match = std::make_unique<std::string>(found);
+            }
         }
         }
     }
     }
-    return nullptr;
+    return fuzzy_match;
 }
 }
 
 
 const std::string DiskImage::getPath(){
 const std::string DiskImage::getPath(){

+ 248 - 0
src/installer/ExeEffectCameras.h

@@ -0,0 +1,248 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <cstdint>
+#include <cstring>
+#include <fstream>
+#include <iterator>
+#include <map>
+#include <string>
+#include <vector>
+
+/**
+ * Reads the camera scripts of the battle effects from ff7.exe.
+ *
+ * Each effect that moves the camera has its own copy of a small script interpreter in the code of
+ * the game, and a pair of scripts (for one target and for several) in the data. The copies are
+ * found by the code of their opcode decoder, the function that registers each one by the push of
+ * its address, and the scripts by the calls to that function: the address of the script is the
+ * last thing pushed before the call.
+ *
+ * A script is a list of 16 bit words. The opcode is the low 6 bits of a word, and bits 0x40 and
+ * 0x80 are the stream it affects (0x40 the camera, 0x80 the point it looks at). The opcodes with
+ * the number of words that follow them are: 0 wait (1), 1 set (3), 2 move (4), 3 orbit (4),
+ * 4 accelerated move (4), 5 eased orbit (5), 6 (2), 7 end (0), 8 (1) and 9 wait (1). A word of -1
+ * ends the script. Found by reading the code of the interpreter of the Shiva effect (0x58e57d in
+ * the 1998 build).
+ *
+ * Only scripts that are made of valid opcodes until their end are kept, so other versions of the
+ * executable don't give garbage, just fewer scripts (or none).
+ */
+namespace ExeEffectCameras{
+
+    /**
+     * Sections of the executable.
+     */
+    struct Section{
+        uint32_t address; ///< Address in memory.
+        uint32_t size; ///< Size in memory.
+        uint32_t file_offset; ///< Position in the file.
+        uint32_t file_size; ///< Size in the file.
+        bool code; ///< True if it has code.
+    };
+
+    /**
+     * Reads a value, little endian.
+     */
+    template<typename T> inline T Read(const std::vector<uint8_t>& data, const size_t offset){
+        T value = 0;
+        if (offset + sizeof(T) <= data.size()) std::memcpy(&value, &data[offset], sizeof(T));
+        return value;
+    }
+
+    /**
+     * Gets the position in the file of an address in memory.
+     *
+     * @return -1 if the address is not in any section.
+     */
+    inline int64_t FileOffset(const std::vector<Section>& sections, const uint32_t address){
+        for (const Section& s : sections){
+            if (address >= s.address && address < s.address + s.file_size){
+                return static_cast<int64_t>(s.file_offset) + (address - s.address);
+            }
+        }
+        return -1;
+    }
+
+    /**
+     * Number of words after each opcode.
+     *
+     * @return -1 for the opcodes that don't exist.
+     */
+    inline int OpcodeArguments(const int opcode){
+        static const int arguments[10] = {1, 3, 4, 4, 4, 5, 2, 0, 1, 1};
+        return (opcode >= 0 && opcode < 10) ? arguments[opcode] : -1;
+    }
+
+    /**
+     * Reads a script.
+     *
+     * @param[in] data The executable.
+     * @param[in] offset Position of the script in the file.
+     * @return The words of the script, empty if it isn't a valid one.
+     */
+    inline std::vector<int16_t> ReadScript(const std::vector<uint8_t>& data, const size_t offset){
+        std::vector<int16_t> words;
+        size_t position = offset;
+        while (words.size() < 1024 && position + 2 <= data.size()){
+            const int16_t word = Read<int16_t>(data, position);
+            if (word == -1){
+                words.push_back(word);
+                return words;
+            }
+            const int opcode = word & 0x3f;
+            const int stream = word & 0xc0;
+            const int arguments = OpcodeArguments(opcode);
+            // Ending, and the opcodes that don't depend on a stream, don't have one.
+            const bool no_stream = opcode == 6 || opcode == 7 || opcode == 8;
+            if (arguments < 0 || (stream != 0x40 && stream != 0x80 && !no_stream)) return {};
+            if (position + 2 * (1 + arguments) > data.size()) return {};
+            for (int i = 0; i <= arguments; ++ i) words.push_back(Read<int16_t>(data, position + 2 * i));
+            position += 2 * (1 + arguments);
+            if (opcode == 7) return words;
+        }
+        return {};
+    }
+
+    /**
+     * Finds the start of the function that has an address.
+     *
+     * @return 0 if there is no function start near.
+     */
+    inline uint32_t FunctionStart(
+      const std::vector<uint8_t>& data, const Section& code, const uint32_t address
+    ){
+        size_t index = address - code.address;
+        for (size_t steps = 0; steps < 0x4000 && index >= 4; ++ steps, -- index){
+            const size_t o = code.file_offset + index;
+            if (data[o] == 0x55 && data[o + 1] == 0x8b && data[o + 2] == 0xec
+              && (data[o - 1] == 0xc3 || data[o - 1] == 0xcc || data[o - 1] == 0x90)){
+                return code.address + static_cast<uint32_t>(index);
+            }
+        }
+        return 0;
+    }
+
+    /**
+     * The executable loaded in memory: its bytes, sections and the first one with code.
+     */
+    struct Image{
+        std::vector<uint8_t> data;
+        std::vector<Section> sections;
+        Section code = {0, 0, 0, 0, false};
+    };
+
+    /**
+     * Reads the executable and its sections.
+     *
+     * @param[in] path Path to ff7.exe.
+     * @param[out] image The executable.
+     * @return False if the file couldn't be read or it isn't a 32 bit executable.
+     */
+    inline bool LoadImage(const std::string& path, Image& image){
+        image = Image();
+        std::ifstream file(path, std::ios::binary);
+        if (!file) return false;
+        image.data.assign((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
+        const std::vector<uint8_t>& data = image.data;
+        if (data.size() < 0x100 || data[0] != 'M' || data[1] != 'Z') return false;
+        const uint32_t pe = Read<uint32_t>(data, 0x3c);
+        if (Read<uint32_t>(data, pe) != 0x00004550 || Read<uint16_t>(data, pe + 4) != 0x14c) return false;
+        const uint16_t section_count = Read<uint16_t>(data, pe + 6);
+        const uint16_t optional_size = Read<uint16_t>(data, pe + 20);
+        const uint32_t image_base = Read<uint32_t>(data, pe + 24 + 28);
+        for (uint16_t i = 0; i < section_count; ++ i){
+            const size_t h = pe + 24 + optional_size + 40 * i;
+            Section s;
+            s.size = Read<uint32_t>(data, h + 8);
+            s.address = image_base + Read<uint32_t>(data, h + 12);
+            s.file_size = Read<uint32_t>(data, h + 16);
+            s.file_offset = Read<uint32_t>(data, h + 20);
+            s.code = (Read<uint32_t>(data, h + 36) & 0x20) != 0;
+            if (s.file_offset + s.file_size > data.size()) return false;
+            image.sections.push_back(s);
+            if (s.code && image.code.file_size == 0) image.code = s;
+        }
+        return image.code.file_size >= 0x1000;
+    }
+
+    /**
+     * Extracts the camera scripts of the effects.
+     *
+     * @param[in] path Path to ff7.exe.
+     * @param[out] scripts The scripts, by the address in memory they have in the executable.
+     * @return False if the file couldn't be read or it isn't a 32 bit executable.
+     */
+    inline bool Extract(const std::string& path, std::map<uint32_t, std::vector<int16_t>>& scripts){
+        scripts.clear();
+        Image image;
+        if (!LoadImage(path, image)) return false;
+        const std::vector<uint8_t>& data = image.data;
+        const std::vector<Section>& sections = image.sections;
+        const Section& code = image.code;
+
+        // Signature of the opcode decoder of the interpreter:
+        //   movsx ecx, word [ebp-X] ; and cl, 0x3f ; mov edx, [Y] ; mov [edx], cx
+        static const uint8_t signature[] = {
+          0x0f, 0xbf, 0x8d, 0, 0, 0, 0, 0x80, 0xe1, 0x3f, 0x8b, 0x15, 0, 0, 0, 0, 0x66, 0x89, 0x0a
+        };
+        static const bool wildcard[] = {
+          false, false, false, true, true, true, true, false, false, false, false, false,
+          true, true, true, true, false, false, false
+        };
+        const size_t signature_size = sizeof(signature);
+
+        // All the calls, to find the ones to the functions that register the interpreters.
+        struct Call{uint32_t address; uint32_t target;};
+        std::vector<Call> calls;
+        for (size_t i = 5; i + 5 <= code.file_size; ++ i){
+            if (data[code.file_offset + i] != 0xe8) continue;
+            const int32_t relative = Read<int32_t>(data, code.file_offset + i + 1);
+            const uint32_t address = code.address + static_cast<uint32_t>(i);
+            calls.push_back({address, address + 5 + static_cast<uint32_t>(relative)});
+        }
+
+        for (size_t i = 0; i + signature_size <= code.file_size; ++ i){
+            bool match = true;
+            for (size_t k = 0; k < signature_size && match; ++ k){
+                if (!wildcard[k] && data[code.file_offset + i + k] != signature[k]) match = false;
+            }
+            if (!match) continue;
+            const uint32_t interpreter = FunctionStart(data, code, code.address + static_cast<uint32_t>(i));
+            if (interpreter == 0) continue;
+            // The function that registers the interpreter pushes its address.
+            for (size_t j = 0; j + 5 <= code.file_size; ++ j){
+                if (data[code.file_offset + j] != 0x68 || Read<uint32_t>(data, code.file_offset + j + 1) != interpreter) continue;
+                const uint32_t registration = FunctionStart(data, code, code.address + static_cast<uint32_t>(j));
+                if (registration == 0) continue;
+                // Its calls have the address of the script as the last argument pushed.
+                for (const Call& call : calls){
+                    if (call.target != registration) continue;
+                    const size_t o = code.file_offset + (call.address - code.address);
+                    if (data[o - 5] != 0x68) continue;
+                    const uint32_t script = Read<uint32_t>(data, o - 4);
+                    const int64_t offset = FileOffset(sections, script);
+                    if (offset < 0 || scripts.count(script) > 0) continue;
+                    const std::vector<int16_t> words = ReadScript(data, static_cast<size_t>(offset));
+                    if (!words.empty()) scripts[script] = words;
+                }
+            }
+        }
+        return true;
+    }
+
+}

+ 399 - 0
src/installer/ExeEffectMeshes.h

@@ -0,0 +1,399 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <cstdlib>
+#include <map>
+#include <ostream>
+#include <string>
+#include <vector>
+#include "ExeEffectCameras.h"
+
+/**
+ * Reads the meshes of the battle effects that are in ff7.exe, like the ground of Ifrit or the
+ * mountain of Ramuh.
+ *
+ * The initialization code of the effect copies a block of the data of the executable to the place it
+ * is used from (mov ecx, size/4 ; mov esi, source ; mov edi, destination ; rep movsd), and the block
+ * is a mesh: the size of its vertices in bytes (u32), the vertices (x, y, z and a padding, signed 16
+ * bits each, y goes down), and four lists of polygons: textured triangles (16 bytes each), textured
+ * quads (20), triangles with colours (20) and quads with colours (24). Every list begins with the
+ * number of polygons and a word of flags (both s16). The polygons use the vertices by their position
+ * in bytes. The blocks that fit exactly (the lists end where the copied block ends) are meshes.
+ *
+ * The effect moves the vertices to key shapes: arrays of vertices of the same size, one after the
+ * other, in a table of pointers somewhere in the data. The 16 words that follow the table are
+ * kept too, because some effects have the durations of their moves there.
+ *
+ * Found by reading the functions 0x594022 (Ifrit) and 0x598f74 (Ramuh) of the 1998 executable.
+ */
+namespace ExeEffectMeshes{
+
+    /**
+     * A mesh of the executable.
+     */
+    struct Mesh{
+        std::vector<int16_t> vertices; ///< x, y, z of every vertex.
+        std::vector<std::vector<int16_t>> keys; ///< x, y, z of the vertices of every key shape.
+        std::vector<int16_t> tail; ///< 16 words after the table of key shapes.
+        std::vector<int16_t> triangles; ///< 10 numbers each: 3 vertices, 3 pairs of UV, grey level.
+        std::vector<int16_t> gouraud; ///< 12 numbers each: 3 vertices, 3 colours (r, g, b).
+        size_t shards = 0; ///< Shard meshes: how many of the triangles are the ones of the first list.
+    };
+
+    /**
+     * Reads a block as a mesh.
+     *
+     * @return False if it doesn't fit exactly.
+     */
+    inline bool ParseBlock(
+      const ExeEffectCameras::Image& image, const uint32_t address, const uint32_t bytes, Mesh& mesh
+    ){
+        using ExeEffectCameras::Read;
+        const std::vector<uint8_t>& data = image.data;
+        const int64_t start = ExeEffectCameras::FileOffset(image.sections, address);
+        if (start < 0 || static_cast<size_t>(start) + bytes > data.size()) return false;
+        const uint32_t vertex_bytes = Read<uint32_t>(data, start);
+        if (vertex_bytes == 0 || vertex_bytes % 8 != 0 || vertex_bytes + 4 > bytes) return false;
+        mesh = Mesh();
+        for (uint32_t i = 0; i < vertex_bytes / 8; ++ i){
+            for (int c = 0; c < 3; ++ c) mesh.vertices.push_back(Read<int16_t>(data, start + 4 + 8 * i + 2 * c));
+        }
+        size_t position = start + 4 + vertex_bytes;
+        const size_t end = start + bytes;
+        static const int strides[4] = {16, 20, 20, 24};
+        for (int list = 0; list < 4; ++ list){
+            if (position + 4 > end) return false;
+            const int16_t count = Read<int16_t>(data, position);
+            position += 4;
+            if (count < 0 || position + static_cast<size_t>(count) * strides[list] > end) return false;
+            for (int i = 0; i < count; ++ i, position += strides[list]){
+                // The vertices are positions in bytes of the array, of 8 bytes each.
+                int vertices[4];
+                const int number = (list == 0 || list == 2) ? 3 : 4;
+                for (int v = 0; v < number; ++ v){
+                    vertices[v] = Read<int16_t>(data, position + 2 * v);
+                    if (vertices[v] < 0 || vertices[v] % 8 != 0 || vertices[v] / 8 >= static_cast<int>(vertex_bytes / 8)) return false;
+                    vertices[v] /= 8;
+                }
+                if (list == 0){
+                    // 3 vertices, grey at +6, UV of the vertices at +8, +12 and +14.
+                    mesh.triangles.insert(mesh.triangles.end(), {
+                      static_cast<int16_t>(vertices[0]), static_cast<int16_t>(vertices[1]), static_cast<int16_t>(vertices[2]),
+                      data[position + 8], data[position + 9], data[position + 12], data[position + 13],
+                      data[position + 14], data[position + 15], data[position + 6]
+                    });
+                }
+                else if (list == 1){
+                    // 4 vertices, UV at +8, +12, +14 and +16, grey at +18. Two triangles.
+                    const int16_t uv[4][2] = {
+                      {data[position + 8], data[position + 9]}, {data[position + 12], data[position + 13]},
+                      {data[position + 14], data[position + 15]}, {data[position + 16], data[position + 17]}
+                    };
+                    const int order[2][3] = {{0, 1, 2}, {1, 3, 2}};
+                    for (int t = 0; t < 2; ++ t){
+                        mesh.triangles.push_back(static_cast<int16_t>(vertices[order[t][0]]));
+                        mesh.triangles.push_back(static_cast<int16_t>(vertices[order[t][1]]));
+                        mesh.triangles.push_back(static_cast<int16_t>(vertices[order[t][2]]));
+                        for (int v = 0; v < 3; ++ v){
+                            mesh.triangles.push_back(uv[order[t][v]][0]);
+                            mesh.triangles.push_back(uv[order[t][v]][1]);
+                        }
+                        mesh.triangles.push_back(data[position + 18]);
+                    }
+                }
+                else{
+                    // Colours (r, g, b and a code) at +8, +12, +16 (and +20 for quads).
+                    const int offsets[4] = {8, 12, 16, 20};
+                    auto colour = [&](const int v){
+                        for (int c = 0; c < 3; ++ c) mesh.gouraud.push_back(data[position + offsets[v] + c]);
+                    };
+                    const int order[2][3] = {{0, 1, 2}, {1, 3, 2}};
+                    const int triangles = list == 2 ? 1 : 2;
+                    for (int t = 0; t < triangles; ++ t){
+                        for (int v = 0; v < 3; ++ v) mesh.gouraud.push_back(static_cast<int16_t>(vertices[order[t][v]]));
+                        for (int v = 0; v < 3; ++ v) colour(order[t][v]);
+                    }
+                }
+            }
+        }
+        // The lists have to end where the block ends.
+        return position == end;
+    }
+
+    /**
+     * Reads a block of the shards of Shiva's ice (the ones the ice breaks into, at 0x8aa590 and the
+     * next ones of the 1998 executable): the size of the vertices, the vertices, a list of
+     * triangles with texture of 20 bytes (flags 172) and a list of quads with texture of 24 bytes
+     * (flags 0). Triangles: 3 vertices (positions in bytes), the colour word at +8 (r, g, b and a
+     * code), the UV of the vertices at +12, +16 and +18. Quads: 4 vertices, the colour word at +8,
+     * the UV at +12, +16, +18 and +20. The effect breaks only the triangles (function 0x591455).
+     *
+     * @param size Size in bytes of the block, if it is one.
+     * @return False if it isn't a block of this kind.
+     */
+    inline bool ParseShardBlock(
+      const ExeEffectCameras::Image& image, const uint32_t address, Mesh& mesh, uint32_t& size
+    ){
+        using ExeEffectCameras::Read;
+        const std::vector<uint8_t>& data = image.data;
+        const int64_t start = ExeEffectCameras::FileOffset(image.sections, address);
+        if (start < 0 || static_cast<size_t>(start) + 16 > data.size()) return false;
+        const uint32_t vertex_bytes = Read<uint32_t>(data, start);
+        if (vertex_bytes == 0 || vertex_bytes % 8 != 0 || vertex_bytes < 64 || vertex_bytes > 64000) return false;
+        const uint32_t vertices = vertex_bytes / 8;
+        size_t position = static_cast<size_t>(start) + 4 + vertex_bytes;
+        if (position + 4 > data.size()) return false;
+        const int16_t triangles = Read<int16_t>(data, position);
+        if (triangles < 8 || triangles > 1500 || Read<int16_t>(data, position + 2) != 172) return false;
+        position += 4;
+        if (position + static_cast<size_t>(triangles) * 20 + 4 > data.size()) return false;
+        mesh = Mesh();
+        for (uint32_t i = 0; i < vertices; ++ i){
+            for (int c = 0; c < 3; ++ c) mesh.vertices.push_back(Read<int16_t>(data, start + 4 + 8 * i + 2 * c));
+        }
+        auto vertex = [&](const size_t at, const int number, int* out){
+            for (int v = 0; v < number; ++ v){
+                const int value = Read<int16_t>(data, at + 2 * v);
+                if (value < 0 || value % 8 != 0 || value / 8 >= static_cast<int>(vertices)) return false;
+                out[v] = value / 8;
+            }
+            return true;
+        };
+        for (int i = 0; i < triangles; ++ i, position += 20){
+            int v[3];
+            if (!vertex(position, 3, v)) return false;
+            mesh.triangles.insert(mesh.triangles.end(), {
+              static_cast<int16_t>(v[0]), static_cast<int16_t>(v[1]), static_cast<int16_t>(v[2]),
+              data[position + 12], data[position + 13], data[position + 16], data[position + 17],
+              data[position + 18], data[position + 19], data[position + 8]
+            });
+        }
+        mesh.shards = triangles;
+        const int16_t quads = Read<int16_t>(data, position);
+        if (quads < 0 || quads > 400 || Read<int16_t>(data, position + 2) != 0) return false;
+        position += 4;
+        if (position + static_cast<size_t>(quads) * 24 > data.size()) return false;
+        for (int i = 0; i < quads; ++ i, position += 24){
+            int v[4];
+            if (!vertex(position, 4, v)) return false;
+            const int16_t uv[4][2] = {
+              {data[position + 12], data[position + 13]}, {data[position + 16], data[position + 17]},
+              {data[position + 18], data[position + 19]}, {data[position + 20], data[position + 21]}
+            };
+            const int order[2][3] = {{0, 1, 2}, {1, 3, 2}};
+            for (int t = 0; t < 2; ++ t){
+                for (int k = 0; k < 3; ++ k) mesh.triangles.push_back(static_cast<int16_t>(v[order[t][k]]));
+                for (int k = 0; k < 3; ++ k){
+                    mesh.triangles.push_back(uv[order[t][k]][0]);
+                    mesh.triangles.push_back(uv[order[t][k]][1]);
+                }
+                mesh.triangles.push_back(data[position + 8]);
+            }
+        }
+        size = static_cast<uint32_t>(position - start);
+        return true;
+    }
+
+    /**
+     * Gets the size of a block of a mesh that starts at an address, walking its lists of polygons.
+     *
+     * @return 0 if it isn't a mesh (the sizes or the vertices of the polygons are not valid).
+     */
+    inline uint32_t BlockSize(const ExeEffectCameras::Image& image, const uint32_t address){
+        using ExeEffectCameras::Read;
+        const std::vector<uint8_t>& data = image.data;
+        const int64_t start = ExeEffectCameras::FileOffset(image.sections, address);
+        if (start < 0 || static_cast<size_t>(start) + 8 > data.size()) return 0;
+        const uint32_t vertex_bytes = Read<uint32_t>(data, start);
+        if (vertex_bytes == 0 || vertex_bytes % 8 != 0 || vertex_bytes > 64000) return 0;
+        const int vertices = vertex_bytes / 8;
+        size_t position = static_cast<size_t>(start) + 4 + vertex_bytes;
+        static const int strides[4] = {16, 20, 20, 24};
+        static const int numbers[4] = {3, 4, 3, 4};
+        int total = 0;
+        for (int list = 0; list < 4; ++ list){
+            if (position + 4 > data.size()) return 0;
+            const int16_t count = Read<int16_t>(data, position);
+            position += 4;
+            if (count < 0 || count > 4000 || position + static_cast<size_t>(count) * strides[list] > data.size()) return 0;
+            for (int i = 0; i < count; ++ i){
+                for (int v = 0; v < numbers[list]; ++ v){
+                    const int vertex = Read<int16_t>(data, position + static_cast<size_t>(i) * strides[list] + 2 * v);
+                    if (vertex < 0 || vertex % 8 != 0 || vertex / 8 >= vertices) return 0;
+                }
+            }
+            position += static_cast<size_t>(count) * strides[list];
+            total += count;
+        }
+        // Small blocks are too easy to find by chance.
+        if (vertices < 8 || total < 8) return 0;
+        return static_cast<uint32_t>(position - start);
+    }
+
+    /**
+     * Gets the data of an image, to know if it looks like the vertices of a mesh.
+     */
+    inline bool LooksLike(
+      const ExeEffectCameras::Image& image, const Mesh& mesh, const uint32_t address
+    ){
+        using ExeEffectCameras::Read;
+        const int64_t start = ExeEffectCameras::FileOffset(image.sections, address);
+        const size_t count = mesh.vertices.size() / 3;
+        if (start < 0 || static_cast<size_t>(start) + count * 8 > image.data.size()) return false;
+        size_t matching = 0;
+        for (size_t i = 0; i < count; ++ i){
+            const int x = Read<int16_t>(image.data, start + 8 * i);
+            const int z = Read<int16_t>(image.data, start + 8 * i + 4);
+            const int pad = Read<int16_t>(image.data, start + 8 * i + 6);
+            if (pad == 0 && std::abs(x - mesh.vertices[3 * i]) < 300 && std::abs(z - mesh.vertices[3 * i + 2]) < 500) ++ matching;
+        }
+        return matching * 2 >= count;
+    }
+
+    /**
+     * Extracts the meshes of the effects.
+     *
+     * @param[in] path Path to ff7.exe.
+     * @param[out] meshes The meshes, by the address of their block in the executable.
+     * @return False if the file couldn't be read or it isn't a 32 bit executable.
+     */
+    inline bool Extract(const std::string& path, std::map<uint32_t, Mesh>& meshes){
+        using ExeEffectCameras::Read;
+        meshes.clear();
+        ExeEffectCameras::Image image;
+        if (!ExeEffectCameras::LoadImage(path, image)) return false;
+        const std::vector<uint8_t>& data = image.data;
+        const ExeEffectCameras::Section& code = image.code;
+        // mov ecx, N ; mov esi, S ; mov edi, D ; rep movsd
+        std::vector<uint32_t> copies; // The places the blocks are copied to: working copies, not meshes.
+        for (size_t i = 0; i + 17 <= code.file_size; ++ i){
+            const size_t o = code.file_offset + i;
+            if (data[o] != 0xb9 || data[o + 5] != 0xbe || data[o + 10] != 0xbf || data[o + 15] != 0xf3 || data[o + 16] != 0xa5) continue;
+            const uint32_t count = Read<uint32_t>(data, o + 1);
+            const uint32_t source = Read<uint32_t>(data, o + 6);
+            copies.push_back(Read<uint32_t>(data, o + 11));
+            Mesh mesh;
+            if (count < 64 || !ParseBlock(image, source, count * 4, mesh) || mesh.vertices.empty()) continue;
+            // The table of the key shapes, in a section of data that isn't code.
+            const size_t vertices = mesh.vertices.size() / 3;
+            const uint32_t vertex_bytes = static_cast<uint32_t>(vertices * 8);
+            bool found = false;
+            for (const ExeEffectCameras::Section& section : image.sections){
+                if (section.code || found) continue;
+                for (uint32_t k = 0; k + 8 <= section.file_size && !found; k += 4){
+                    const size_t entry = section.file_offset + k;
+                    const uint32_t first = Read<uint32_t>(data, entry);
+                    if (first == source || !LooksLike(image, mesh, first)) continue;
+                    // The shapes are one after the other.
+                    std::vector<uint32_t> table = {first};
+                    while (entry + 4 * (table.size() + 1) <= data.size()){
+                        const uint32_t next = Read<uint32_t>(data, entry + 4 * table.size());
+                        // Only the first one has to be like the mesh: some shapes aren't used.
+                        if (next != table.back() + vertex_bytes) break;
+                        const int64_t at_next = ExeEffectCameras::FileOffset(image.sections, next);
+                        if (at_next < 0 || static_cast<size_t>(at_next) + vertex_bytes > data.size()) break;
+                        table.push_back(next);
+                    }
+                    if (table.size() < 2) continue;
+                    // The first one can be followed by shapes that aren't in the table: the table is
+                    // what is a pointer at a position of the section.
+                    found = true;
+                    for (const uint32_t pointer : table){
+                        const int64_t at = ExeEffectCameras::FileOffset(image.sections, pointer);
+                        std::vector<int16_t> shape;
+                        for (size_t v = 0; v < vertices; ++ v){
+                            for (int c = 0; c < 3; ++ c) shape.push_back(Read<int16_t>(data, at + 8 * v + 2 * c));
+                        }
+                        mesh.keys.push_back(shape);
+                    }
+                    for (int w = 0; w < 16; ++ w) mesh.tail.push_back(Read<int16_t>(data, entry + 4 * table.size() + 2 * w));
+                }
+            }
+            if (found) meshes[source] = mesh;
+        }
+        // The meshes that don't change, that aren't copied by the code: blocks of the data that fit
+        // exactly. The working copies of the others have the same polygons as their template.
+        for (const ExeEffectCameras::Section& section : image.sections){
+            if (section.code) continue;
+            for (uint32_t k = 0; k + 16 <= section.file_size;){
+                const uint32_t address = section.address + k;
+                const uint32_t size = BlockSize(image, address);
+                if (size == 0){
+                    k += 4;
+                    continue;
+                }
+                bool is_copy = false;
+                for (const uint32_t copy : copies) is_copy = is_copy || copy == address;
+                Mesh mesh;
+                if (!is_copy && meshes.count(address) == 0 && ParseBlock(image, address, size, mesh)) meshes[address] = mesh;
+                k += size;
+            }
+        }
+        // The shards of the ice of Shiva.
+        for (const ExeEffectCameras::Section& section : image.sections){
+            if (section.code) continue;
+            for (uint32_t k = 0; k + 16 <= section.file_size; k += 4){
+                const uint32_t address = section.address + k;
+                if (meshes.count(address) != 0) continue;
+                Mesh mesh;
+                uint32_t size = 0;
+                if (ParseShardBlock(image, address, mesh, size)) meshes[address] = mesh;
+            }
+        }
+        return true;
+    }
+
+    /**
+     * Writes the meshes as Lua tables: Game.EffectMeshes["0x8af9b0"] = {...}.
+     */
+    inline void WriteLua(std::ostream& out, const std::map<uint32_t, Mesh>& meshes){
+        auto list = [&](const std::vector<int16_t>& values, const size_t per_line){
+            for (size_t i = 0; i < values.size(); ++ i){
+                if (i % per_line == 0) out << "\n        ";
+                out << values[i] << ", ";
+            }
+        };
+        out << "-- Meshes of the battle effects that are in the data of ff7.exe, with the vertices of the key shapes\n"
+            << "-- they change through. Game.EffectMeshes[address] has the vertices of the first shape (x, y, z, in\n"
+            << "-- the units of the effects, y goes down), the key shapes, the 16 words that follow the table of\n"
+            << "-- shapes (some effects have the durations of the moves there), the triangles with texture (3 vertex\n"
+            << "-- numbers, the UV of each vertex in bytes of the texture page and the grey level, 128 is 1.0) and the\n"
+            << "-- triangles with colours (3 vertex numbers and the r, g, b of each vertex).\n"
+            << "Game.EffectMeshes = Game.EffectMeshes or {}\n";
+        for (const auto& item : meshes){
+            const Mesh& m = item.second;
+            out << "Game.EffectMeshes[\"0x" << std::hex << item.first << std::dec << "\"] = {\n    vertices = {";
+            list(m.vertices, 24);
+            out << "\n    },\n    keys = {\n";
+            for (const std::vector<int16_t>& key : m.keys){
+                out << "        {";
+                list(key, 24);
+                out << "\n        },\n";
+            }
+            out << "    },\n    tail = {";
+            list(m.tail, 16);
+            out << "\n    },\n    triangles = {";
+            list(m.triangles, 20);
+            out << "\n    },\n    gouraud = {";
+            list(m.gouraud, 24);
+            out << "\n    },\n";
+            if (m.shards > 0) out << "    shards = " << m.shards << ",\n";
+            out << "}\n";
+        }
+    }
+
+}

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