cmake_minimum_required(VERSION 3.21)
project(VP2S LANGUAGES C CXX)

# Native port of Valkyrie Profile 2: Silmeria. Links the code recompiled by
# tools/pipeline.py (build/recomp/<input>/) with the PS2Recomp fork runtime.

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

set(VP2S_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/..")
set(VP2S_FORK "${VP2S_ROOT}/external/PS2Recomp" CACHE PATH "PS2Recomp fork checkout to build against")
set(VP2S_RECOMP_DIR "${VP2S_ROOT}/build/recomp" CACHE PATH "Recompiled C++ (tools/pipeline.py output)")
set(VP2S_GENERATED_OPT "/O2 /Ob1" CACHE STRING "MSVC optimization flags for the generated code (Release)")

# PS2Recomp fork: only the runtime and IOP libraries are used.
set(PS2X_BUILD_RECOMP OFF CACHE BOOL "" FORCE)
set(PS2X_BUILD_ANALYZER OFF CACHE BOOL "" FORCE)
set(PS2X_BUILD_TEST OFF CACHE BOOL "" FORCE)
set(PS2X_BUILD_STUDIO OFF CACHE BOOL "" FORCE)
set(PS2X_ENABLE_SCCACHE OFF CACHE BOOL "" FORCE)
# Defaults for this port; override on the cmake command line when needed.
# FFmpeg decodes the MPEG movies (intro, events); on Windows the fork downloads a prebuilt
# LGPL shared build (System233/ffmpeg-msvc-prebuilt) and its DLLs are copied beside vp2s.exe.
option(VP2S_FFMPEG "Decode the game's MPEG movies with FFmpeg" ON)
set(PS2X_ENABLE_FFMPEG ${VP2S_FFMPEG} CACHE BOOL "Enable FFmpeg-backed MPEG video decoding" FORCE)
option(VP2S_DEBUG_UI "Show the runtime debugger (ImGui, F1) in vp2s" ON)
set(PS2X_ENABLE_DEBUG_UI ${VP2S_DEBUG_UI} CACHE BOOL "Build the desktop runtime debug UI" FORCE)
# Aggressive logs make every generated function log its entry.
set(PS2X_ENABLE_AGRESSIVE_LOGS OFF CACHE BOOL "Enable very verbose/agressive PS2 runtime logs")
add_subdirectory("${VP2S_FORK}" ps2recomp EXCLUDE_FROM_ALL)

# Generated code: one directory per recompiled input (main ELF + overlay modules).
# Globbed on each input's .done stamp with CONFIGURE_DEPENDS, so a module recompiled later (one captured at run
# time) reconfigures the build instead of being left out of it.
file(GLOB VP2S_INPUT_STAMPS CONFIGURE_DEPENDS "${VP2S_RECOMP_DIR}/*/.done")
set(VP2S_INPUT_DIRS "")
foreach(stamp IN LISTS VP2S_INPUT_STAMPS)
    get_filename_component(dir "${stamp}" DIRECTORY)
    list(APPEND VP2S_INPUT_DIRS "${dir}")
endforeach()
set(VP2S_GENERATED_DIRS "")
set(VP2S_GENERATED_SOURCES "")
foreach(dir IN LISTS VP2S_INPUT_DIRS)
    if(IS_DIRECTORY "${dir}" AND EXISTS "${dir}/.done")
        list(APPEND VP2S_GENERATED_DIRS "${dir}")
        file(GLOB sources CONFIGURE_DEPENDS "${dir}/*.cpp")
        list(APPEND VP2S_GENERATED_SOURCES ${sources})
    endif()
endforeach()
if(NOT EXISTS "${VP2S_RECOMP_DIR}/main/register_functions.cpp")
    message(FATAL_ERROR "No recompiled main ELF in ${VP2S_RECOMP_DIR}: run tools/pipeline.py first")
endif()
list(LENGTH VP2S_GENERATED_DIRS input_count)
list(LENGTH VP2S_GENERATED_SOURCES source_count)
message(STATUS "VP2S: ${input_count} recompiled inputs, ${source_count} generated sources")

# The flags below apply to this directory only: the fork keeps its own settings.
if(MSVC)
    set(CMAKE_CXX_FLAGS_RELEASE "${VP2S_GENERATED_OPT} /DNDEBUG")
endif()

# Port front end (main, game override, diagnostics, optional debugger) in its own object
# library: its includes, defines and ImGui never reach the generated sources' command line,
# so toggling them does not rebuild the whole game.
add_library(vp2s_frontend OBJECT
    "${CMAKE_CURRENT_SOURCE_DIR}/main.cpp"
    "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_settings.cpp"
    "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_overrides.cpp"
    "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_vu1_hle.cpp"
    "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_textures.cpp"
    "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_loads.cpp"
    "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_models.cpp"
    "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_music.cpp"
    "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_bootstrap.cpp"
    "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_math.cpp"
    "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_ui.cpp"
    "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_minimap.cpp"
    "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_battle_hud.cpp"
    "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_diag_iop.cpp"
    "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_diag_gs.cpp"
    "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_profile.cpp"
)
target_link_libraries(vp2s_frontend PRIVATE ps2_runtime)
# Asynchronous GS rasterization, when the fork checkout provides it.
file(STRINGS "${VP2S_FORK}/ps2xRuntime/include/runtime/gs/gs_cpu_backend.h" VP2S_GS_ASYNC_DECL REGEX "SetAsyncRasterization")
if(VP2S_GS_ASYNC_DECL)
    target_compile_definitions(vp2s_frontend PRIVATE VP2S_GS_ASYNC=1)
endif()
if(VP2S_DEBUG_UI)
    target_sources(vp2s_frontend PRIVATE "${VP2S_FORK}/ps2xRuntime/src/lib/ps2_debug_panel.cpp")
    # The debug panel reads kernel HLE state through Kernel/... includes.
    target_include_directories(vp2s_frontend PRIVATE "${VP2S_FORK}/ps2xRuntime/src/lib")
    target_link_libraries(vp2s_frontend PRIVATE rlImGui imgui)
    target_compile_definitions(vp2s_frontend PRIVATE PS2X_ENABLE_DEBUG_UI=1)
endif()

# VP2's VU1 programs as C++ (tools/vu1_native.py, from the images a run saves with VP2S_VU1_IMAGES): game code like
# the EE output, generated in the build tree, never committed. Each file registers its image (vp2s_vu1_programs.h).
set(VP2S_VU1_NATIVE_DIR "${VP2S_ROOT}/build/vu1_native" CACHE PATH "VU1 programs generated by tools/vu1_native.py")
file(GLOB VP2S_VU1_NATIVE_SOURCES CONFIGURE_DEPENDS "${VP2S_VU1_NATIVE_DIR}/*.cpp")
# The programs too big for one function (MSVC runs out of memory on them): cut into pieces by tools/vu1_split.py, one
# directory a program under split/, built like the others.
file(GLOB VP2S_VU1_NATIVE_SPLIT_SOURCES CONFIGURE_DEPENDS "${VP2S_VU1_NATIVE_DIR}/split/*/*.cpp")
add_library(vp2s_vu1_native OBJECT "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_vu1_programs.cpp" ${VP2S_VU1_NATIVE_SOURCES}
                                   ${VP2S_VU1_NATIVE_SPLIT_SOURCES})
target_include_directories(vp2s_vu1_native PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}")
target_link_libraries(vp2s_vu1_native PRIVATE ps2_runtime)
if(MSVC)
    target_compile_options(vp2s_vu1_native PRIVATE /fp:precise /bigobj)
endif()

# The native version of VP2's mesh microprogram checked against recorded VU1 runs (docs/vp2_vu1.md), and the
# programs as C++ against the same runs.
# VP2's textures converted offline (tools/vp2_textures.py): the GS layout functions run in this tool only.
add_executable(vp2s_texconv "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_texconv.cpp")
target_link_libraries(vp2s_texconv PRIVATE ps2_runtime)

add_executable(vp2s_hle_check "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_hle_check.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_vu1_hle.cpp")
target_link_libraries(vp2s_hle_check PRIVATE ps2_runtime vp2s_vu1_native)
if(MSVC)
    # The programs as C++ keep thousands of locals: their frames are megabytes deep.
    target_link_options(vp2s_hle_check PRIVATE /STACK:536870912)
endif()

add_executable(vp2s ${VP2S_GENERATED_SOURCES})
if(WIN32)
    # The window's and the taskbar's icon (VP2S's variant of The Bozos' logo, docs/branding/make_logo.py vp2s; no game
    # art) and the version information.
    target_sources(vp2s PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/app/vp2s.rc)
    # A windowed program (no console window beside the game); main() stays the entry point. Its output still goes to
    # the files or pipes a launcher redirects it to.
    set_target_properties(vp2s PROPERTIES WIN32_EXECUTABLE TRUE)
    if(MSVC)
        target_link_options(vp2s PRIVATE /ENTRY:mainCRTStartup)
    endif()
endif()
target_include_directories(vp2s PRIVATE ${VP2S_GENERATED_DIRS})
target_link_libraries(vp2s PRIVATE vp2s_frontend vp2s_vu1_native ps2_runtime)

# The music algorithms and numeric tables are compiled/converted offline from
# the user's USA ELF. The linked decoder has no VU execution or VIF input API.
get_filename_component(VP2S_BUILD_ROOT "${VP2S_RECOMP_DIR}" DIRECTORY)
set(VP2S_MUSIC_NATIVE_DIR "${VP2S_BUILD_ROOT}/native_music" CACHE PATH "Native music conversion output")
if(NOT EXISTS "${VP2S_MUSIC_NATIVE_DIR}/codec.cpp")
    message(FATAL_ERROR "Run tools/vp2_music.py --elf <build>/elf/main.elf --out <build>/native_music first")
endif()
add_library(vp2s_music_native OBJECT "${VP2S_MUSIC_NATIVE_DIR}/codec.cpp")
target_include_directories(vp2s_music_native PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}")
if(MSVC)
    target_compile_options(vp2s_music_native PRIVATE /O2 /Ob2 /arch:AVX2 /fp:precise)
endif()
target_link_libraries(vp2s PRIVATE vp2s_music_native)

# Reference algorithms belong to this offline check target only.
add_executable(vp2s_music_check "${VP2S_ROOT}/tools/vp2_music_check.cpp"
    "${VP2S_MUSIC_NATIVE_DIR}/reference/music_6e0.cpp"
    "${VP2S_MUSIC_NATIVE_DIR}/reference/music_1410.cpp"
    "${VP2S_MUSIC_NATIVE_DIR}/reference/music_1690.cpp")
target_include_directories(vp2s_music_check PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}")
target_link_libraries(vp2s_music_check PRIVATE vp2s_music_native ps2_runtime)
if(MSVC)
    target_compile_options(vp2s_music_check PRIVATE /O2 /arch:AVX2 /fp:precise)
    target_link_options(vp2s_music_check PRIVATE /CGTHREADS:16 /LTCG:INCREMENTAL)
endif()

# Startup reference code belongs to this offline check target only.
add_executable(vp2s_bootstrap_check "${VP2S_ROOT}/tools/vp2_bootstrap_check.cpp"
    "${VP2S_BUILD_ROOT}/native_bootstrap/reference.cpp")
target_include_directories(vp2s_bootstrap_check PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}")
target_link_libraries(vp2s_bootstrap_check PRIVATE ps2_runtime)
if(MSVC)
    target_compile_options(vp2s_bootstrap_check PRIVATE /O2 /arch:AVX2 /fp:precise)
    target_link_options(vp2s_bootstrap_check PRIVATE /CGTHREADS:16 /LTCG:INCREMENTAL)
endif()

# Matrix reference code belongs to this offline check target only.
add_executable(vp2s_math_check "${VP2S_ROOT}/tools/vp2_math_check.cpp"
    "${VP2S_BUILD_ROOT}/native_math/reference.cpp")
target_include_directories(vp2s_math_check PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}")
target_link_libraries(vp2s_math_check PRIVATE ps2_runtime)
if(MSVC)
    target_compile_options(vp2s_math_check PRIVATE /O2 /arch:AVX2 /fp:precise)
    target_link_options(vp2s_math_check PRIVATE /CGTHREADS:16 /LTCG:INCREMENTAL)
endif()

# The game's IOP modules recompiled ahead of time (tools/iop_recomp.py on the images PS2X_IOP_DUMP_MODULES writes):
# each file registers its module by hash and base and runs in place of the IOP interpreter under PS2X_IOP_NATIVE=1.
# Game code like the EE output: generated in the build tree, never committed.
set(VP2S_IOP_NATIVE_DIR "${VP2S_ROOT}/build/iop_native" CACHE PATH "IOP modules generated by tools/iop_recomp.py")
file(GLOB VP2S_IOP_NATIVE_SOURCES CONFIGURE_DEPENDS "${VP2S_IOP_NATIVE_DIR}/*.cpp")
target_sources(vp2s PRIVATE ${VP2S_IOP_NATIVE_SOURCES})

# VU1 microcode compiled ahead of time (tools/pipeline.py stage vu, ps2_vu_aot): each fragment
# registers itself and replaces the interpreter while VU1 code memory holds its exact bytes
# (PS2X_VU_AOT=0 turns them off). Built like the runtime's VU1 code (AVX2: blocks with the VU
# registers in host registers); each large file takes MSVC minutes and GBs, hence the job pool.
option(VP2S_VU1_AOT "Link the VU1 microcode compiled ahead of time" ON)
set(VP2S_VU_AOT_DIR "${VP2S_ROOT}/build/vu_aot" CACHE PATH "VU1 fragments generated by ps2_vu_aot")
file(GLOB VP2S_VU1_AOT_SOURCES CONFIGURE_DEPENDS "${VP2S_VU_AOT_DIR}/*/*.cpp")
if(VP2S_VU1_AOT AND VP2S_VU1_AOT_SOURCES)
    list(LENGTH VP2S_VU1_AOT_SOURCES vu1_count)
    message(STATUS "VP2S: ${vu1_count} VU1 microcode files compiled ahead of time")
    set_property(GLOBAL APPEND PROPERTY JOB_POOLS vp2s_vu1_aot=6)
    add_library(vp2s_vu1_aot OBJECT ${VP2S_VU1_AOT_SOURCES})
    target_link_libraries(vp2s_vu1_aot PRIVATE ps2_runtime)
    set_target_properties(vp2s_vu1_aot PROPERTIES UNITY_BUILD OFF JOB_POOL_COMPILE vp2s_vu1_aot)
    if(MSVC)
        # /fp:precise: under /fp:fast the compiler folds products with the constant lanes of VF0 to +0 (the VU gives
        # -0 for a negative operand) and may fuse multiply-adds, which round differently.
        target_compile_options(vp2s_vu1_aot PRIVATE /O2 /Ob2 /Oi /arch:AVX2 /fp:precise /GS- /bigobj /FS)
    endif()
    target_sources(vp2s PRIVATE $<TARGET_OBJECTS:vp2s_vu1_aot>)
    # The fork's VU1 replay tool with this microcode linked in: checks it against runs recorded in
    # the game with PS2X_VU1_RECORD (vp2s_vu1_replay <trace> [repeat] [--ignore-flags]).
    add_executable(vp2s_vu1_replay "${VP2S_FORK}/ps2xRuntime/tools/ps2_vu1_replay.cpp" $<TARGET_OBJECTS:vp2s_vu1_aot>)
    target_link_libraries(vp2s_vu1_replay PRIVATE ps2_runtime)
    if(MSVC)
        # VP2S_PROFILE=<seconds> samples the replay too (symbols from vp2s_vu1_replay.pdb).
        target_sources(vp2s_vu1_replay PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_profile.cpp"
                                               "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_replay_profile.cpp")
        target_link_libraries(vp2s_vu1_replay PRIVATE dbghelp winmm)
        target_link_options(vp2s_vu1_replay PRIVATE /DEBUG /OPT:REF /OPT:ICF /INCREMENTAL:NO /FORCE:MULTIPLE /CGTHREADS:16)
    endif()
endif()
# The fork's GS replay tool with the same runtime build: times the rasterizer on frames recorded with
# PS2X_GS_RECORD (vp2s_gs_replay <trace> [repeat]); VP2S_PROFILE=<seconds> samples it.
add_executable(vp2s_gs_replay "${VP2S_FORK}/ps2xRuntime/tools/ps2_gs_replay.cpp")
target_link_libraries(vp2s_gs_replay PRIVATE ps2_runtime)
if(MSVC)
    target_sources(vp2s_gs_replay PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_profile.cpp"
                                          "${CMAKE_CURRENT_SOURCE_DIR}/vp2s_replay_profile.cpp")
    target_link_libraries(vp2s_gs_replay PRIVATE dbghelp winmm)
    target_link_options(vp2s_gs_replay PRIVATE /DEBUG /OPT:REF /OPT:ICF /INCREMENTAL:NO /FORCE:MULTIPLE /CGTHREADS:16)
endif()
ps2x_stage_ffmpeg_runtime_dlls(vp2s) # no-op without FFmpeg
if(MSVC)
    # Public symbols in vp2s.pdb (no /Zi needed) for the VP2S_PROFILE sampler: only relinks.
    # /CGTHREADS: the runtime is compiled /GL, so each link generates its code (4 threads by default).
    # /LTCG:INCREMENTAL: a relink regenerates only the runtime functions that changed (it was ~2.5 min each time).
    target_link_options(vp2s PRIVATE /DEBUG /OPT:REF /OPT:ICF /INCREMENTAL:NO /CGTHREADS:16 /LTCG:INCREMENTAL)
    target_link_libraries(vp2s PRIVATE dbghelp winmm)
    # Large recompiled functions get huge MSVC frames (up to ~550 KB: one stack slot per SIMD
    # temporary), and guest calls nest as host calls on the game thread. With the default 1 MB
    # the field module overflowed the stack. Reserve 256 MB per thread (committed on demand).
    target_link_options(vp2s PRIVATE /STACK:268435456)
endif()

# Unity groups by input and guest address range (generated file names end with _0x<address>):
# adding or removing a function only changes the translation unit of its range. Positional
# batches would shift every later batch and rebuild the whole game.
set(VP2S_UNITY_RANGE_SHIFT 13 CACHE STRING "Address bits per unity group (13 = 8 KiB of guest code)")
set(VP2S_UNITY_GROUPS "")
foreach(source IN LISTS VP2S_GENERATED_SOURCES)
    get_filename_component(input_dir "${source}" DIRECTORY)
    get_filename_component(input "${input_dir}" NAME)
    if(source MATCHES "_0x([0-9a-fA-F]+)\\.cpp$")
        math(EXPR range "0x${CMAKE_MATCH_1} >> ${VP2S_UNITY_RANGE_SHIFT}" OUTPUT_FORMAT HEXADECIMAL)
        set(group "${input}_${range}")
    else()
        set(group "${input}_misc")
    endif()
    if(NOT DEFINED VP2S_GROUP_${group})
        list(APPEND VP2S_UNITY_GROUPS "${group}")
    endif()
    list(APPEND VP2S_GROUP_${group} "${source}")
endforeach()
foreach(group IN LISTS VP2S_UNITY_GROUPS)
    set_source_files_properties(${VP2S_GROUP_${group}} PROPERTIES UNITY_GROUP "${group}")
endforeach()
list(LENGTH VP2S_UNITY_GROUPS group_count)
message(STATUS "VP2S: ${group_count} unity groups")

set_target_properties(vp2s PROPERTIES
    UNITY_BUILD ON
    UNITY_BUILD_MODE GROUP
)

set(VP2S_RUNTIME_INCLUDE "${VP2S_FORK}/ps2xRuntime/include")
# Only the recomp ABI headers the generated code includes (not ps2_runtime.h): a runtime header change then leaves
# the precompiled header, and so the ~470 unity groups of generated code, untouched.
target_precompile_headers(vp2s PRIVATE
    "${VP2S_RUNTIME_INCLUDE}/ps2_runtime_macros.h"
    "${VP2S_RUNTIME_INCLUDE}/ps2_recomp_calls.h"
)

if(MSVC)
    target_compile_options(vp2s_frontend PRIVATE /FS)
    target_compile_options(vp2s PRIVATE /bigobj /FS)
    # WinAPI vs raylib CloseWindow clash, as for the upstream ps2EntryRunner.
    target_link_options(vp2s PRIVATE /FORCE:MULTIPLE)
endif()
