cmake_minimum_required(VERSION 3.20)

# Turok: Evolution, statically recompiled on the xboxrecomp toolkit.
#
# Build with scripts/build.py, which lifts the game first. The generated
# sources in src/recomp/gen/ come from your own copy of the game and are
# never committed.

project(turok_recomp C CXX)

set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)

add_compile_definitions(
    WIN32_LEAN_AND_MEAN
    NOMINMAX
)

set(XBOXRECOMP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/xboxrecomp" CACHE PATH
    "Path to the xboxrecomp toolkit (the submodule by default)")

if(NOT EXISTS "${XBOXRECOMP_DIR}/CMakeLists.txt")
    message(FATAL_ERROR "xboxrecomp not found at ${XBOXRECOMP_DIR}. "
        "Run: git submodule update --init --recursive")
endif()

# Checks that every call preserves ebx/esi/edi and esp. Set before
# add_subdirectory: the check is emitted into the generated game code but
# its logger lives in xbox_kernel. See the toolkit's templates/new-game.
option(RECOMP_ABI_CHECK "Verify callee-saved registers across every call" OFF)
if(RECOMP_ABI_CHECK)
    add_compile_definitions(RECOMP_ABI_CHECK)
endif()

# The project's own icon on the game and the launcher (cmake/title_icon.cmake).
set(XBOXRECOMP_TITLE_ICON "${CMAKE_CURRENT_SOURCE_DIR}/assets/launcher/icon.ico")

add_subdirectory(${XBOXRECOMP_DIR} ${CMAKE_BINARY_DIR}/xboxrecomp)

# CONFIGURE_DEPENDS so a re-lift that adds or removes a chunk is picked up
# without a manual re-configure.
file(GLOB RECOMP_GEN_SOURCES CONFIGURE_DEPENDS "src/recomp/gen/*.c")
if(NOT RECOMP_GEN_SOURCES)
    message(FATAL_ERROR "No generated sources in src/recomp/gen. "
        "Lift the game first: py -3 scripts/build.py")
endif()

# On Android the engine is libmain.so, built into the APK, and the game is
# libgame.so, which the device compiles from the player's disc and libmain.so
# loads (the toolkit's cmake/android.cmake). main() is renamed for it to call.
if(ANDROID)
    add_library(${PROJECT_NAME} OBJECT src/main.c src/recomp_manual.c ${RECOMP_GEN_SOURCES})
    set_target_properties(${PROJECT_NAME} PROPERTIES POSITION_INDEPENDENT_CODE ON)
    set_source_files_properties(src/main.c PROPERTIES
        COMPILE_DEFINITIONS main=recomp_title_main)
    xboxrecomp_android_libraries(${PROJECT_NAME})
else()
    add_executable(${PROJECT_NAME}
        src/main.c
        src/recomp_manual.c
        ${RECOMP_GEN_SOURCES}
    )
endif()
# A windowed program on Windows (WinMain, no console); a plain executable
# elsewhere, whose main() hands the game its own thread (host_main_posix).
if(WIN32)
    set_target_properties(${PROJECT_NAME} PROPERTIES WIN32_EXECUTABLE ON)
endif()

target_link_libraries(${PROJECT_NAME} PRIVATE xboxrecomp)

target_include_directories(${PROJECT_NAME} PRIVATE
    ${CMAKE_CURRENT_SOURCE_DIR}/src
    ${CMAKE_CURRENT_SOURCE_DIR}/src/recomp
    ${XBOXRECOMP_DIR}/include
)

# Off Windows the runtime libraries bring their own host libraries (pthreads,
# dl, SDL3, OpenSSL).
if(WIN32)
    target_link_libraries(${PROJECT_NAME} PRIVATE
        d3d11
        dxgi
        dxguid
        xinput
        winmm
        dbghelp     # lets the crash handler name the generated function that faulted
    )
else()
    # The POSIX fault report names a host pc with dladdr, which sees only
    # exported symbols: export the generated functions.
    set_target_properties(${PROJECT_NAME} PROPERTIES ENABLE_EXPORTS ON)
endif()

if(MSVC)
    # /DEBUG: a PDB in every configuration, so a crash names sub_XXXXXXXX.
    target_link_options(${PROJECT_NAME} PRIVATE /LARGEADDRESSAWARE /DEBUG)
    target_compile_options(${PROJECT_NAME} PRIVATE /bigobj /MP)
    # Lifted code reads ebp before writing it by design (fpo_leaf functions
    # inherit the caller's frame), which /RTC1 aborts on through a message box.
    string(REGEX REPLACE "/RTC[1csu]+" "" CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG}")
endif()

# Turok has no 16:9 mode of its own (no widescreen flag at CreateDevice, no
# read of the console's video flags), so widescreen means Hor+: its vertex
# programs take oPos.x from c96, the first row of the model-view-projection
# the game builds for each object, and the toolkit scales it on screen draws.
# The front end and the movies are shown 4:3 (src/recomp_manual.c).
if(COMMAND recomp_title_widescreen)
    recomp_title_widescreen(HOR_PLUS REGISTER 96 187)
endif()

# Turok steps its game by a QueryPerformanceCounter delta (sub_00028B60), so
# it plays at the right speed at any frame rate: capped and uncapped runs of
# the same scripted walk and jump match at the same wall-clock moments. Its
# launcher and F10 offer caps above 60 and uncapped; adaptive 60 stays the
# default.
if(COMMAND recomp_title_timing)
    recomp_title_timing(DELTA)
endif()

# The settings window: video options, input bindings, then starts the game.
# In the look of the project's own artwork (assets/launcher, by Daniel
# Freitas): a front page with the logo and Play, green motes rising.
if(COMMAND recomp_add_launcher)
    recomp_add_launcher(${PROJECT_NAME}_launcher ${PROJECT_NAME}.exe
        BRAND_BACKGROUND assets/launcher/background.jpg
        BRAND_LOGO       assets/launcher/logo.png
        BRAND_ACCENT     2E9B45
        BRAND_MOTES      4DFF7C
        BRAND_TITLE      "Turok Evolution Recomp"
        BRAND_FOOTER     "Fan project, not affiliated with Acclaim or the owners of Turok."
        BRAND_NEWS_TITLE "Turok: Evolution, USA (NTSC)"
        BRAND_NEWS_TEXT  "Built from your own disc on your own computer. What each new version brings shows here when the launcher is online."
        BRAND_UPDATE_REPO danfreitas97/turok-evolution-recomp)
endif()

# Keep the same branded icon beside the executables for Windows shortcuts.
if(WIN32)
    add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E copy_if_different
            "${CMAKE_CURRENT_SOURCE_DIR}/assets/launcher/icon.ico"
            "$<TARGET_FILE_DIR:${PROJECT_NAME}>/turok.ico")
endif()
