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

# Twisted Metal: Black (USA, SCUS-97101) static recompilation on top of PS2Recomp.
#
# Build the tools first (scripts/build_tools.sh), generate code (scripts/recomp.sh),
# then configure this project to get the `ps2EntryRunner` executable with the
# recompiled game linked in.

set(TMB_GENERATED_DIR "${CMAKE_SOURCE_DIR}/generated" CACHE PATH
    "Directory containing the output of ps2_recomp for the game ELF")

# Only the runtime is needed here; the recompiler/analyzer are built separately.
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)

# The runner as a PC game (the fork's ps2_app.h): its window title, the per-user folder (%APPDATA%\TMB_Recomp,
# $XDG_DATA_HOME/tmb_recomp) for the memory cards, input.ini, video.ini, the log and crash reports, and with no argument
# the game data in game/ next to the runner (or in the user folder). No console window (a GUI-subsystem runner: the
# output goes to the log, and to the terminal it was started from).
set(PS2X_APP_TITLE "Twisted Metal: Black" CACHE STRING "" FORCE)
set(PS2X_APP_FOLDER "TMB_Recomp" CACHE STRING "" FORCE)
set(PS2X_APP_XDG_FOLDER "tmb_recomp" CACHE STRING "" FORCE)
set(PS2X_APP_BOOT_ELF "SCUS_971.01" CACHE STRING "" FORCE)
set(PS2X_APP_DATA_FOLDER "game" CACHE STRING "" FORCE)
set(PS2X_SHOW_WINDOWS_CONSOLE OFF CACHE BOOL "" FORCE)

add_subdirectory(PS2Recomp)

# The runner's icon and version information (runtime/app: a placeholder icon, no game art).
if(WIN32)
    enable_language(RC)
    target_sources(ps2EntryRunner PRIVATE "${CMAKE_SOURCE_DIR}/runtime/app/tmb.rc")
endif()

file(GLOB TMB_GENERATED_SOURCES CONFIGURE_DEPENDS "${TMB_GENERATED_DIR}/*.cpp")
if(NOT TMB_GENERATED_SOURCES)
    message(FATAL_ERROR
        "No generated sources in ${TMB_GENERATED_DIR}. Run scripts/recomp.sh first.")
endif()

# The runtime ships a placeholder register_functions.cpp that defines the same
# function-table globals as the generated one; drop it from the runner.
get_target_property(_runner_sources ps2EntryRunner SOURCES)
list(FILTER _runner_sources EXCLUDE REGEX "src/runner/register_functions\\.cpp$")
set_property(TARGET ps2EntryRunner PROPERTY SOURCES ${_runner_sources})

file(GLOB TMB_RUNTIME_SOURCES CONFIGURE_DEPENDS "${CMAKE_SOURCE_DIR}/runtime/*.cpp")
# The native texture pack scripts/recomp.sh converts from the disc (runtime/tmb_textures.cpp loads it).
target_compile_definitions(ps2EntryRunner PRIVATE TMB_TEXTURE_PACK="${TMB_GENERATED_DIR}/tmb_textures.pack")
# The native mesh pack it converts from the disc's NGP files (tools/tmb_mesh_pack.py).
target_compile_definitions(ps2EntryRunner PRIVATE TMB_MESH_PACK="${TMB_GENERATED_DIR}/tmb_meshes.pack")

# IOP modules recompiled to native C++ by the fork's tools/iop_recomp.py (989snd, libsd; PS2X_IOP_NATIVE=1 runs them;
# scripts/iop_recomp.sh writes them, derived from the game's IRX files like the rest of generated/): their own object
# library, outside the unity batches (each file's names are its own), without debug info.
file(GLOB TMB_IOP_NATIVE_SOURCES CONFIGURE_DEPENDS "${TMB_GENERATED_DIR}/iop/*.cpp")
if(TMB_IOP_NATIVE_SOURCES)
    add_library(tmb_iop_native OBJECT ${TMB_IOP_NATIVE_SOURCES})
    target_link_libraries(tmb_iop_native PRIVATE ps2x::iop)
    set_target_properties(tmb_iop_native PROPERTIES UNITY_BUILD OFF)
    if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
        target_compile_options(tmb_iop_native PRIVATE -O2 -g0)
    endif()
    target_sources(ps2EntryRunner PRIVATE $<TARGET_OBJECTS:tmb_iop_native>)
endif()
# The host OS layer includes <windows.h>, which clashes with raylib names: outside the unity batches and the PCH.
set_source_files_properties("${CMAKE_SOURCE_DIR}/runtime/tmb_host.cpp" PROPERTIES
    SKIP_UNITY_BUILD_INCLUSION ON SKIP_PRECOMPILE_HEADERS ON)

# VU1 microcode compiled ahead of time by ps2_vu_aot (scripts/recomp.sh): an object library both executables
# link, so it compiles once. -O3 unrolls the operand loops over each pair's constexpr decode; debug info is of no
# use for it and triples its build time. Each file takes GCC several GB: at most 4 compile at once.
file(GLOB TMB_VU1_AOT_SOURCES CONFIGURE_DEPENDS "${TMB_GENERATED_DIR}/vu1/*.cpp")
if(TMB_VU1_AOT_SOURCES)
    set_property(GLOBAL APPEND PROPERTY JOB_POOLS tmb_vu1_aot=4)
    # With it, microcode loops lifted to native code by hand (runtime/vu1, VU1Interpreter::registerLiftedEntry).
    file(GLOB TMB_VU1_LIFTED_SOURCES CONFIGURE_DEPENDS "${CMAKE_SOURCE_DIR}/runtime/vu1/*.cpp")
    add_library(tmb_vu1_aot OBJECT ${TMB_VU1_AOT_SOURCES} ${TMB_VU1_LIFTED_SOURCES})
    target_link_libraries(tmb_vu1_aot PRIVATE ps2_runtime)
    set_target_properties(tmb_vu1_aot PROPERTIES UNITY_BUILD OFF JOB_POOL_COMPILE tmb_vu1_aot)
    # TMB_VU1_AOT_LINES=ON: line tables only (-g1), so a profile of the replay maps samples to the jit helpers.
    option(TMB_VU1_AOT_LINES "Line tables in the compiled VU1 microcode, for profiling" OFF)
    if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
        if(TMB_VU1_AOT_LINES)
            target_compile_options(tmb_vu1_aot PRIVATE -O3 -g1)
        else()
            target_compile_options(tmb_vu1_aot PRIVATE -O3 -g0)
        endif()
    endif()
    target_sources(ps2EntryRunner PRIVATE $<TARGET_OBJECTS:tmb_vu1_aot>)
endif()

# The reference harness (docs/REFERENCE_HARNESS.md): the game's library and kernel stubs (the generated code's stub
# list, ps2_recompiled_stubs.h: name_0xaddress) whose calls PS2X_REFERENCE records, and the build's name (the two
# repositories' commits when configured), as a source in the build tree.
set(_tmb_stub_list "${TMB_GENERATED_DIR}/ps2_recompiled_stubs.h")
set(_tmb_call_names "")
set(_tmb_call_count 0)
if(EXISTS "${_tmb_stub_list}")
    set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${_tmb_stub_list}")
    file(STRINGS "${_tmb_stub_list}" _tmb_stub_lines REGEX "^void [A-Za-z0-9_]+_0x[0-9a-fA-F]+\\(")
    foreach(_tmb_line IN LISTS _tmb_stub_lines)
        if(_tmb_line MATCHES "^void ([A-Za-z0-9_]+)_0x([0-9a-fA-F]+)\\(")
            string(APPEND _tmb_call_names "    {0x${CMAKE_MATCH_2}u, \"${CMAKE_MATCH_1}\"},\n")
            math(EXPR _tmb_call_count "${_tmb_call_count} + 1")
        endif()
    endforeach()
endif()
if(_tmb_call_count EQUAL 0)
    set(_tmb_call_names "    {0u, \"\"},\n")
endif()
find_package(Git QUIET)
set(_tmb_commit "unknown")
set(_tmb_fork_commit "unknown")
if(GIT_FOUND)
    execute_process(COMMAND "${GIT_EXECUTABLE}" rev-parse --short HEAD WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
                    OUTPUT_VARIABLE _tmb_commit OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)
    execute_process(COMMAND "${GIT_EXECUTABLE}" rev-parse --short HEAD WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}/PS2Recomp"
                    OUTPUT_VARIABLE _tmb_fork_commit OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)
endif()
file(WRITE "${CMAKE_BINARY_DIR}/tmb_call_names.cpp.in"
"// Generated by CMakeLists.txt from ${_tmb_stub_list}: do not edit.
#include \"runtime/ps2_reference.h\"
#include <cstddef>

namespace tmb
{
    extern const char *const kBuildName;
    extern const ps2x::reference::CallName kCallNames[];
    extern const size_t kCallNameCount;
    const char *const kBuildName = \"TMB_Recomp ${_tmb_commit} fork ${_tmb_fork_commit}\";
    const ps2x::reference::CallName kCallNames[] = {
${_tmb_call_names}    };
    const size_t kCallNameCount = ${_tmb_call_count};
}
")
configure_file("${CMAKE_BINARY_DIR}/tmb_call_names.cpp.in" "${CMAKE_BINARY_DIR}/tmb_call_names.cpp" COPYONLY)
set_source_files_properties("${CMAKE_BINARY_DIR}/tmb_call_names.cpp" PROPERTIES
    SKIP_UNITY_BUILD_INCLUSION ON SKIP_PRECOMPILE_HEADERS ON)
message(STATUS "TMB_Recomp: ${_tmb_call_count} stub addresses for the reference records")

target_sources(ps2EntryRunner PRIVATE ${TMB_GENERATED_SOURCES} ${TMB_RUNTIME_SOURCES} "${CMAKE_BINARY_DIR}/tmb_call_names.cpp")
target_include_directories(ps2EntryRunner PRIVATE "${TMB_GENERATED_DIR}")

list(LENGTH TMB_GENERATED_SOURCES _tmb_count)
message(STATUS "TMB_Recomp: linking ${_tmb_count} generated source files from ${TMB_GENERATED_DIR}")

# The VU1 replay tool with the compiled microcode linked in: checks it against runs recorded with
# PS2X_VU1_RECORD (build/game/tmb_vu1_replay <trace> [repeat]).
if(TMB_VU1_AOT_SOURCES)
    add_executable(tmb_vu1_replay PS2Recomp/ps2xRuntime/tools/ps2_vu1_replay.cpp $<TARGET_OBJECTS:tmb_vu1_aot>)
    target_link_libraries(tmb_vu1_replay PRIVATE ps2_runtime)
    if(WIN32)
        # PS2X_PROFILE=<seconds>: the fork's sampling profiler, to see where the compiled microcode spends its time.
        target_sources(tmb_vu1_replay PRIVATE PS2Recomp/ps2xRuntime/src/profiling/sampling_profiler.cpp)
        target_link_libraries(tmb_vu1_replay PRIVATE raylib winmm) # raylib first: winmm has a PlaySound too
    endif()
endif()

# Profile-guided optimization (GCC) of the runtime, the IOP and the compiled VU1 microcode, the code the frame time
# goes to; the generated game code keeps its flags (it would all rebuild). scripts/pgo.sh: GENERATE, a training run
# into the match, then USE. The profile is specific to this build tree and machine, never committed.
set(TMB_PGO "OFF" CACHE STRING "Profile-guided optimization: OFF, GENERATE or USE (scripts/pgo.sh)")
set_property(CACHE TMB_PGO PROPERTY STRINGS OFF GENERATE USE)
set(TMB_PGO_DIR "${CMAKE_BINARY_DIR}/pgo-profile" CACHE PATH "Where TMB_PGO=GENERATE writes the profile USE reads")
if(NOT TMB_PGO STREQUAL "OFF" AND CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
    if(TMB_PGO STREQUAL "GENERATE")
        set(_tmb_pgo_flags "-fprofile-generate=${TMB_PGO_DIR}" -fprofile-update=atomic)
        target_link_options(ps2EntryRunner PRIVATE "-fprofile-generate=${TMB_PGO_DIR}")
        target_sources(ps2EntryRunner PRIVATE "${CMAKE_SOURCE_DIR}/runtime/pgo/tmb_pgo_train.cpp")
        set_source_files_properties("${CMAKE_SOURCE_DIR}/runtime/pgo/tmb_pgo_train.cpp" PROPERTIES
            SKIP_UNITY_BUILD_INCLUSION ON SKIP_PRECOMPILE_HEADERS ON)
    else()
        set(_tmb_pgo_flags "-fprofile-use=${TMB_PGO_DIR}" -fprofile-partial-training -fprofile-correction -Wno-missing-profile)
    endif()
    foreach(_tmb_pgo_target ps2_runtime ps2_iop tmb_vu1_aot)
        if(TARGET ${_tmb_pgo_target})
            target_compile_options(${_tmb_pgo_target} PRIVATE ${_tmb_pgo_flags})
        endif()
    endforeach()
    if(TMB_PGO STREQUAL "GENERATE" AND TARGET tmb_vu1_replay)
        target_link_options(tmb_vu1_replay PRIVATE "-fprofile-generate=${TMB_PGO_DIR}")
    endif()
    message(STATUS "TMB_Recomp: profile-guided optimization ${TMB_PGO} (${TMB_PGO_DIR})")
endif()
