# Asura's Wrath para PC: el juego recompilado (build/recomp) + el runtime.
#
#   cmake -S . -B build/cmake -G Ninja -DCMAKE_BUILD_TYPE=Release
#   cmake --build build/cmake
#
# build/recomp lo genera setup.sh a partir de tu copia del juego.
cmake_minimum_required(VERSION 3.20)
project(asura_port CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE Release)
endif()
if(NOT CMAKE_CXX_COMPILER_ID MATCHES "Clang")
    message(FATAL_ERROR "compila con clang (en Windows, la terminal MSYS2 CLANG64)")
endif()

# x86-64-v3 (AVX2 + FMA, procesadores de 2013 en adelante): fma() en hardware
set(ASURA_ARCH "x86-64-v3" CACHE STRING "valor de -march")
set(ASURA_GEN_OPT "-O2" CACHE STRING "optimización del código recompilado")
set(RECOMP_DIR "${CMAKE_SOURCE_DIR}/build/recomp" CACHE PATH "C++ generado por tools/recomp")

file(GLOB GEN_SRC CONFIGURE_DEPENDS "${RECOMP_DIR}/ppu_*.cpp")
if(NOT GEN_SRC)
    message(FATAL_ERROR "no hay código recompilado en ${RECOMP_DIR}: ejecuta antes ./setup.sh")
endif()

# el juego: muchos archivos grandes, sin avisos y sin contraer a*b+c en fma
add_library(asura_juego STATIC ${GEN_SRC})
target_include_directories(asura_juego PRIVATE runtime "${RECOMP_DIR}")
# -fno-finite-loops: un bucle sin efectos (una espera activa del juego) no se puede quitar
target_compile_options(asura_juego PRIVATE ${ASURA_GEN_OPT} -march=${ASURA_ARCH} -ffp-contract=off -fno-strict-aliasing -fno-finite-loops -w)

file(GLOB RT_SRC CONFIGURE_DEPENDS runtime/*.cpp)
# programas SPU traducidos a C++ ("asura --generar-spu" a partir de spu_cache, ver runtime/spu_aot.cpp)
file(GLOB SPU_GEN CONFIGURE_DEPENDS "${CMAKE_SOURCE_DIR}/build/spu_gen/*.cpp")
set_source_files_properties(${SPU_GEN} PROPERTIES COMPILE_OPTIONS "-O2;-w")
add_executable(asura ${RT_SRC} ${SPU_GEN})
target_include_directories(asura PRIVATE runtime "${RECOMP_DIR}")
target_compile_options(asura PRIVATE -march=${ASURA_ARCH} -ffp-contract=off -fno-strict-aliasing -Wall -Wno-unused-function)
target_link_libraries(asura PRIVATE asura_juego)
# zlib: los paquetes del juego van comprimidos (en la PS3 los descomprime Edge zlib)
if(WIN32)
    set(ZLIB_USE_STATIC_LIBS ON)   # que asura.exe no dependa de zlib1.dll
endif()
find_package(ZLIB REQUIRED)
target_link_libraries(asura PRIVATE ZLIB::ZLIB)
# SDL3: la ventana, los mandos y el teclado
find_package(SDL3 CONFIG)
if(NOT SDL3_FOUND)
    message(FATAL_ERROR "falta SDL3 (en MSYS2 CLANG64: pacman -S mingw-w64-clang-x86_64-sdl3)")
endif()
target_link_libraries(asura PRIVATE SDL3::SDL3)
if(WIN32)
    target_link_options(asura PRIVATE -Wl,--stack,16777216)
    target_link_libraries(asura PRIVATE shell32 winmm)
    # SDL3.dll al lado de asura.exe (en build/cmake y en la carpeta del proyecto)
    add_custom_command(TARGET asura POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_FILE:SDL3::SDL3> $<TARGET_FILE_DIR:asura>
        COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_FILE:SDL3::SDL3> ${CMAKE_SOURCE_DIR})
else()
    find_package(Threads REQUIRED)
    target_link_libraries(asura PRIVATE Threads::Threads)
endif()

# Optimización guiada por perfil (PGO), la lleva tools/compilar.sh:
#   medir: el juego apunta qué código se usa y cuánto (va más lento) y lo guarda en pgo/*.profraw;
#   usar:  se compila con lo apuntado (pgo/asura.profdata): el compilador pone juntos y en línea los
#          caminos que más se usan y ordena los saltos según lo que de verdad pasa al jugar.
# Vacío: como siempre.
set(ASURA_PGO "" CACHE STRING "optimización guiada por perfil: vacío, medir o usar")
if(ASURA_PGO STREQUAL "medir")
    target_compile_options(asura_juego PRIVATE -fprofile-generate)
    target_compile_options(asura PRIVATE -fprofile-generate)
    target_compile_definitions(asura PRIVATE ASURA_PGO_MEDIR)
    target_link_options(asura PRIVATE -fprofile-generate)
elseif(ASURA_PGO STREQUAL "usar")
    set(PGO_DATOS "${CMAKE_SOURCE_DIR}/pgo/asura.profdata")
    if(NOT EXISTS "${PGO_DATOS}")
        message(FATAL_ERROR "ASURA_PGO=usar sin ${PGO_DATOS}")
    endif()
    set(PGO_OPC "-fprofile-use=${PGO_DATOS}" -Wno-profile-instr-unprofiled -Wno-profile-instr-out-of-date -Wno-backend-plugin)
    target_compile_options(asura_juego PRIVATE ${PGO_OPC})
    target_compile_options(asura PRIVATE ${PGO_OPC})
    # con un perfil nuevo, todo se vuelve a compilar
    set_property(SOURCE ${GEN_SRC} ${RT_SRC} ${SPU_GEN} APPEND PROPERTY OBJECT_DEPENDS "${PGO_DATOS}")
elseif(NOT ASURA_PGO STREQUAL "")
    message(FATAL_ERROR "ASURA_PGO tiene que ser vacío, medir o usar")
endif()
message(STATUS "PGO: '${ASURA_PGO}'")
