cmake_minimum_required(VERSION 3.20)

set(PSXRECOMP_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/psxrecomp" CACHE PATH
    "Path to psxrecomp")
if(NOT EXISTS "${PSXRECOMP_ROOT}/runtime/runtime.cmake")
    message(FATAL_ERROR
        "PSXRecomp runtime is missing: ${PSXRECOMP_ROOT}/runtime/runtime.cmake\n"
        "Run: git submodule update --init --recursive\n"
        "or set -DPSXRECOMP_ROOT=<path-to-psxrecomp>.")
endif()

# macOS: portable binaries by default, for release builds
# (tools/package_release.sh) and local ones. Use the static SDL3 psxrecomp
# pins rather than a Homebrew dylib, skip recomp-ui's optional
# FreeType/HarfBuzz (emoji stay outline glyphs), and target a macOS older than
# the build machine.
# Cache defaults, so a local -D still overrides them.
if(APPLE)
    set(CMAKE_OSX_DEPLOYMENT_TARGET "11.0" CACHE STRING "Minimum macOS version")
    set(CMAKE_DISABLE_FIND_PACKAGE_SDL3 ON CACHE BOOL
        "Use psxrecomp's pinned static SDL3, not a system dylib")
    set(CMAKE_DISABLE_FIND_PACKAGE_Freetype ON CACHE BOOL
        "Skip optional FreeType/HarfBuzz (Homebrew dylibs)")
endif()

project(RidgeRacerType4Recomp LANGUAGES C CXX)

# Developer tests. OFF by default: they need tests/, tools/ and the local disc,
# and release builds never run them. Configure with -DR4_BUILD_TESTS=ON to get
# them.
option(R4_BUILD_TESTS "Register R4's developer tests (needs tests/ and tools/)" OFF)
if(R4_BUILD_TESTS)
    include(CTest)
    add_executable(r4_controller_policy_test "${PSXRECOMP_ROOT}/runtime/tests/test_controller_type.cpp")
    target_include_directories(r4_controller_policy_test PRIVATE "${PSXRECOMP_ROOT}/runtime/include")
    target_compile_features(r4_controller_policy_test PRIVATE cxx_std_17)
    add_test(NAME r4_controller_policy COMMAND r4_controller_policy_test)
    find_package(Python3 3.11 REQUIRED COMPONENTS Interpreter)
    add_test(NAME r4_windows_delivery
        COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_windows_delivery.py")
    add_test(NAME r4_static_overlays
        COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/check_static_overlays.py")
endif()

# --- Opt-in product surfaces (OFF by default in the framework) -------------
# PSX_NETPLAY must be set BEFORE runtime.cmake is included: that is where
# recomp-net / the lobby client / rbengine are wired. ENABLE_NETPLAY_IF_PRESENT
# below is only supplemental.
if(EXISTS "${PSXRECOMP_ROOT}/lib/recomp-net/CMakeLists.txt")
    set(PSX_NETPLAY ON CACHE BOOL
        "Link recomp-net rollback/delay-sync netplay (needs recomp-net)" FORCE)
endif()
# Disc region: USA (SLUS-00797, the default) or PAL (SCES-01706, see
# pal/README.md). PAL builds from game_pal.toml and generated_pal/ (generated
# locally from your own disc by pal/tools/regen_pal.sh), with the src/mods
# plugins copied into the build tree and their addresses translated USA -> PAL.
set(R4_REGION "USA" CACHE STRING "Target disc: USA or PAL")
set_property(CACHE R4_REGION PROPERTY STRINGS USA PAL)
if(R4_REGION STREQUAL "PAL")
    set(R4_GAME_TOML "game_pal.toml")
    set(R4_GEN_STEM "generated_pal/SCES_017.06")
    # The setup wizard prepares the USA disc (codegen_setup.c); PAL is set up by hand.
    set(PSX_SETUP_WIZARD OFF CACHE BOOL
        "First-run setup wizard in recomp-ui (the disc picker of a full build)" FORCE)
elseif(R4_REGION STREQUAL "USA")
    set(R4_GAME_TOML "game.toml")
    set(R4_GEN_STEM "generated/SLUS_007.97")
    set(PSX_SETUP_WIZARD ON CACHE BOOL
        "First-run setup wizard in recomp-ui (the disc picker of a full build)" FORCE)
else()
    message(FATAL_ERROR "R4_REGION must be USA or PAL, not '${R4_REGION}'")
endif()
# R4 owns the title layer of its custom in-game menu.
set(R4L_TITLE_SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/launcher/title_r4.cpp" CACHE FILEPATH
    "R4 custom menu title layer" FORCE)
include("${PSXRECOMP_ROOT}/runtime/runtime.cmake")

# This project's own mod catalog. The FRAMEWORK stages it -- together with its
# builtin psx.* packages -- into <exe-dir>/mods/bundled. Never copy it by hand
# (see psxrecomp/docs/MOD_PACKAGES.md, "How bundled/ gets staged").
set(R4_PRELOADED_MODS "${CMAKE_CURRENT_SOURCE_DIR}/mods/preloaded")

# PGXP hook build (psxrecomp docs/ENHANCEMENTS.md G1.11): the runtime carries
# the value-propagation hooks, so psx.enhancement.pgxp (on by default for R4)
# tracks the sub-pixel position of 99.8% of R4's polygon vertices. With PGXP
# switched off the guest runs exactly as in the base build. Savestates from a
# build with the other setting are refused. OFF builds the base flavor, for
# A/B and identity checks.
option(R4_PGXP "Build the runtime with the PGXP hooks" ON)
set(R4_RUNTIME_FLAVOR)
if(R4_PGXP)
    set(R4_RUNTIME_FLAVOR PGXP)
endif()

# Trusted, statically linked mod plugins (src/mods/README.md), selected by the
# packages in mods/preloaded/packages.
file(GLOB R4_MOD_PLUGIN_SOURCES CONFIGURE_DEPENDS
    "${CMAKE_CURRENT_SOURCE_DIR}/src/mods/*.c"
    "${CMAKE_CURRENT_SOURCE_DIR}/src/mods/*.cpp")
if(R4_REGION STREQUAL "PAL")
    # src/mods is copied to the build tree with every USA address literal
    # translated to PAL (pal/tools/translate_mods.py); the PAL-only plugins of
    # pal/mods are added as they are.
    find_package(Python3 REQUIRED COMPONENTS Interpreter)
    set(R4_PAL_MODS_DIR "${CMAKE_BINARY_DIR}/mods_pal")
    file(GLOB R4_MOD_ALL_SOURCES CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/mods/*")
    execute_process(
        COMMAND "${Python3_EXECUTABLE}" -I "${CMAKE_CURRENT_SOURCE_DIR}/pal/tools/translate_mods.py"
                "${CMAKE_CURRENT_SOURCE_DIR}/src/mods" "${R4_PAL_MODS_DIR}"
                "${CMAKE_CURRENT_SOURCE_DIR}/generated" "${CMAKE_CURRENT_SOURCE_DIR}/disc/SCES_017.06"
                "${CMAKE_CURRENT_SOURCE_DIR}/pal/manual_addresses.txt"
        RESULT_VARIABLE _r4_pal_mods_rc)
    if(NOT _r4_pal_mods_rc EQUAL 0)
        message(FATAL_ERROR "Could not translate the R4 plugins to PAL (pal/tools/translate_mods.py)")
    endif()
    set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
        ${R4_MOD_ALL_SOURCES} "${CMAKE_CURRENT_SOURCE_DIR}/pal/manual_addresses.txt")
    file(GLOB R4_MOD_PLUGIN_SOURCES "${R4_PAL_MODS_DIR}/*.c" "${R4_PAL_MODS_DIR}/*.cpp"
         "${CMAKE_CURRENT_SOURCE_DIR}/pal/mods/*.c" "${CMAKE_CURRENT_SOURCE_DIR}/pal/mods/*.cpp")
    # Packages: the upstream ones retargeted to SCES-01706, plus the PAL-only ones.
    set(R4_PRELOADED_PAL "${CMAKE_BINARY_DIR}/preloaded_pal")
    file(REMOVE_RECURSE "${R4_PRELOADED_PAL}")
    file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/mods/preloaded/" DESTINATION "${R4_PRELOADED_PAL}")
    file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/pal/mods/packages/" DESTINATION "${R4_PRELOADED_PAL}/packages")
    file(GLOB_RECURSE _r4_pal_manifests "${R4_PRELOADED_PAL}/packages/*/manifest.toml")
    foreach(_m ${_r4_pal_manifests})
        file(READ "${_m}" _txt)
        string(REPLACE "game_id = \"SLUS-00797\"" "game_id = \"SCES-01706\"" _txt "${_txt}")
        # HD HUD: PAL-only measured choice. Its texture lookups saturated the
        # render thread in races on the PAL build (27 fps measured), so it is
        # offered but off by default there. USA keeps the upstream default.
        if(_m MATCHES "r4\.enhancement\.ui-fonts")
            string(REPLACE "default_enabled = true" "default_enabled = false" _txt "${_txt}")
        endif()
        # Max Detail: the car model distance table, USA 0x8009F228..0x8009F245 =
        # PAL 0x8009F04C (same bytes). Left untranslated, its byte guard
        # rejected the WHOLE mod plan at boot ("booting unmodified").
        if(_m MATCHES "r4\.enhancement\.max-detail")
            foreach(_p F228:F04C F22E:F052 F234:F058 F23A:F05E F240:F064)
                string(SUBSTRING "${_p}" 0 4 _usa)
                string(SUBSTRING "${_p}" 5 4 _pal)
                string(REPLACE "address = 0x8009${_usa}" "address = 0x8009${_pal}" _txt "${_txt}")
            endforeach()
        endif()
        file(WRITE "${_m}" "${_txt}")
    endforeach()
    file(GLOB_RECURSE _r4_pal_pkg_files CONFIGURE_DEPENDS
        "${CMAKE_CURRENT_SOURCE_DIR}/mods/preloaded/*.toml" "${CMAKE_CURRENT_SOURCE_DIR}/pal/mods/packages/*.toml")
    set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${_r4_pal_pkg_files})
    set(R4_PRELOADED_MODS "${R4_PRELOADED_PAL}")
endif()

set(R4_WIZARD_ARGS)
if(PSX_SETUP_WIZARD)
    set(R4_WIZARD_ARGS ENABLE_SETUP_WIZARD
        CODEGEN_SETUP_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/codegen_setup.c")
endif()
psxrecomp_add_game_runtime(psx-runtime
    GAME_OVERLAY_STATIC_C "${CMAKE_CURRENT_SOURCE_DIR}/generated/overlays_static.c"
    ${R4_RUNTIME_FLAVOR}
    PRELOADED_MODS_DIR "${R4_PRELOADED_MODS}"
    ENABLE_NETPLAY_IF_PRESENT
    NETPLAY_LOBBY_URL "ws://netplay.retcomm.net:8765"
    WINDOW_TITLE "Ridge Racer Type 4 Remixed"
    EXE_NAME "r4-runtime"
    DEBUG_PORT 4797
    DEFAULT_GAME_CONFIG_PATH "game.toml"
    MAX_PLAYERS 4
    LAUNCHER_BOXART "${CMAKE_CURRENT_SOURCE_DIR}/recomp/launcher/boxart.tga"
    APP_ICON "${CMAKE_CURRENT_SOURCE_DIR}/assets/psxrecomp.ico"
    GEN_MARKER "${R4_GEN_STEM}_dispatch.c"
    GEN_FULL_GLOB "${R4_GEN_STEM}_full_*.c"
    ${R4_WIZARD_ARGS}
    EXTRAS_SOURCES ${R4_MOD_PLUGIN_SOURCES}
)

# R4's complete private render passes support resolution-independent rewind.
set_property(SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/psxrecomp/runtime/src/main.cpp"
    APPEND PROPERTY COMPILE_DEFINITIONS PSX_REWIND_COMMANDS_DEFAULT=1)

if(R4_REGION STREQUAL "PAL")
    # Mods and the title layer test R4_REGION_PAL; pal/mods/r4_pal_ntsc.h
    # declares the PAL-only helpers (r4_pal_message_language()).
    target_compile_definitions(psx-runtime PRIVATE R4_REGION_PAL=1)
    target_include_directories(psx-runtime PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/pal/mods")
endif()


# Launcher translations of this project (launcher/i18n/<code>.json), staged
# next to recomp-ui's own. Select one with -DR4L_UI_LANGUAGE=fr or the
# R4L_LANGUAGE environment variable.
add_custom_command(TARGET psx-runtime POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_CURRENT_SOURCE_DIR}/launcher/i18n"
        "$<TARGET_FILE_DIR:psx-runtime>/assets/i18n"
    COMMENT "Staging launcher translations" VERBATIM)

# Optional post-processing preset (postfx/r4_2026/), staged next to the exe
# when the directory exists.
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/postfx/r4_2026")
    add_custom_command(TARGET psx-runtime POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_CURRENT_SOURCE_DIR}/postfx/r4_2026"
            "$<TARGET_FILE_DIR:psx-runtime>/postfx/r4_2026"
        COMMENT "Staging postfx/r4_2026" VERBATIM)
endif()

# Stage runtime configs next to the exe for direct build/ launches. Only copy
# files that exist -- never fail POST_BUILD when game_options.toml is absent.
foreach(_R4_RUNTIME_CONFIG ${R4_GAME_TOML} game_options.toml)
    set(_R4_STAGED_NAME "${_R4_RUNTIME_CONFIG}")
    if(_R4_RUNTIME_CONFIG STREQUAL R4_GAME_TOML)
        set(_R4_STAGED_NAME "game.toml")   # the runtime reads game.toml next to the exe
    endif()
    if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${_R4_RUNTIME_CONFIG}")
        add_custom_command(TARGET psx-runtime POST_BUILD
            COMMAND ${CMAKE_COMMAND} -E copy_if_different
                "${CMAKE_CURRENT_SOURCE_DIR}/${_R4_RUNTIME_CONFIG}"
                "$<TARGET_FILE_DIR:psx-runtime>/${_R4_STAGED_NAME}"
            COMMENT "Staging ${_R4_RUNTIME_CONFIG}"
            VERBATIM)
    endif()
endforeach()

# Developer tests (R4_BUILD_TESTS above): ctest --test-dir build -R r4_
# Every path is behind its own if(EXISTS ...), so a checkout without tests/ or
# tools/ still configures (none of them ship).
if(R4_BUILD_TESTS AND BUILD_TESTING)
    if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_hide_rear_view_mirror.c")
        add_executable(r4-hide-rear-view-mirror-tests EXCLUDE_FROM_ALL
            "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_hide_rear_view_mirror.c")
        target_include_directories(r4-hide-rear-view-mirror-tests PRIVATE
            "${CMAKE_CURRENT_SOURCE_DIR}/src/mods")
        add_test(NAME r4_hide_rear_view_mirror_build
                 COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR}
                         --target r4-hide-rear-view-mirror-tests)
        add_test(NAME r4_hide_rear_view_mirror COMMAND r4-hide-rear-view-mirror-tests)
        set_tests_properties(r4_hide_rear_view_mirror PROPERTIES
                             DEPENDS r4_hide_rear_view_mirror_build)
    endif()
    if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_camera_look.c")
        add_executable(r4-camera-look-tests
            "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_camera_look.c")
        target_include_directories(r4-camera-look-tests PRIVATE
            "${CMAKE_CURRENT_SOURCE_DIR}/src/mods")
        if(NOT MSVC)
            target_link_libraries(r4-camera-look-tests PRIVATE m)
        endif()
        add_test(NAME r4_camera_look_helpers COMMAND r4-camera-look-tests)
        add_executable(r4-camera-look-plugin-tests tests/test_r4_camera_look_plugin.c)
        target_include_directories(r4-camera-look-plugin-tests PRIVATE
            "${CMAKE_CURRENT_SOURCE_DIR}/src/mods" "${PSXRECOMP_ROOT}/runtime/include")
        if(NOT MSVC)
            target_link_libraries(r4-camera-look-plugin-tests PRIVATE m)
        endif()
        add_test(NAME r4_camera_look_redraw COMMAND r4-camera-look-plugin-tests)
    endif()
    if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_link_netplay.c")
        add_executable(r4-link-netplay-tests
            "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_link_netplay.c")
        target_include_directories(r4-link-netplay-tests PRIVATE
            "${PSXRECOMP_ROOT}/runtime/include")
        add_test(NAME r4_link_netplay_setup COMMAND r4-link-netplay-tests)
    endif()
    # Pure widescreen helpers, no game data needed.
    if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_widescreen.c")
        add_executable(r4-widescreen-tests
            "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_widescreen.c")
        target_include_directories(r4-widescreen-tests PRIVATE
            "${CMAKE_CURRENT_SOURCE_DIR}/src/mods")
        add_test(NAME r4_widescreen_helpers COMMAND r4-widescreen-tests)
    endif()
    # R4 mod plugin tests, pure C (no runtime or disc needed). The executables are
    # built on demand by the *_build tests, so a plain
    #   ctest --test-dir build -R r4_ --output-on-failure
    # builds and runs them.
    function(r4_plugin_test name)
        add_executable(test_${name} EXCLUDE_FROM_ALL ${ARGN})
        target_include_directories(test_${name} PRIVATE
            "${CMAKE_CURRENT_SOURCE_DIR}/src/mods" "${PSXRECOMP_ROOT}/runtime/include")
        add_test(NAME ${name}_build
                 COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR}
                         --target test_${name})
        add_test(NAME ${name} COMMAND test_${name})
        set_tests_properties(${name} PROPERTIES DEPENDS ${name}_build)
    endfunction()
    r4_plugin_test(r4_interp "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_interp.c")
    r4_plugin_test(r4_interp_plugin
        "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_interp_plugin.c"
        "${CMAKE_CURRENT_SOURCE_DIR}/src/mods/r4_interp.c")
    r4_plugin_test(r4_effects_clock "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_effects_clock.cpp")
    r4_plugin_test(r4_race_state "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_race_state.c")
    # Assertions are the checks even in a Release developer build.
    if(MSVC)
        target_compile_options(test_r4_race_state PRIVATE /UNDEBUG)
    else()
        target_compile_options(test_r4_race_state PRIVATE -UNDEBUG)
        target_link_libraries(test_r4_race_state PRIVATE m)
    endif()
    if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_jogcon_compat.c")
        r4_plugin_test(r4_jogcon_compat
            "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_jogcon_compat.c"
            "${CMAKE_CURRENT_SOURCE_DIR}/src/mods/r4_jogcon_compat.c")
    endif()
    # R4 Max Detail: option parsing, car tables, the shared course-list merge
    # (r4_pvs.h, also the widescreen plugin's) and the plugin against a mock
    # mod API.
    if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_max_detail.c")
        r4_plugin_test(r4_max_detail
            "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_max_detail.c"
            "${CMAKE_CURRENT_SOURCE_DIR}/src/mods/r4_max_detail_plugin.c")
    endif()
    # R4 Controls (Modern scheme) pad transform against a mock mod API.
    if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_modern_rumble.c")
        r4_plugin_test(r4_modern_rumble
            "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_modern_rumble.c"
            "${CMAKE_CURRENT_SOURCE_DIR}/src/mods/r4_modern_rumble.c")
    endif()
    if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_modern_controls.c")
        r4_plugin_test(r4_modern_controls
            "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_modern_controls.c"
            "${CMAKE_CURRENT_SOURCE_DIR}/src/mods/r4_modern_controls.c")
    endif()
    find_package(Python3 QUIET COMPONENTS Interpreter)
    if(Python3_FOUND)
        # game.toml's [widescreen.cull] lists must match a fresh scan of the
        # local disc. The scan reads the boot EXE and R4.BIN from disc/*.bin
        # (no regen or extracted EXE needed), so it is registered whenever the
        # disc is there, and says so when it is not.
        if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tools/r4_ws_scan.py")
            file(GLOB _R4_DISC_BINS "${CMAKE_CURRENT_SOURCE_DIR}/disc/*.bin")
            if(_R4_DISC_BINS)
                if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/generated/SLUS_007.97_full.ranges")
                    add_test(NAME r4_widescreen_cull_sites
                        COMMAND "${Python3_EXECUTABLE}"
                            "${CMAKE_CURRENT_SOURCE_DIR}/tools/r4_ws_scan.py"
                            --check "${CMAKE_CURRENT_SOURCE_DIR}/game.toml"
                        WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")
                endif()
            else()
                message(WARNING "R4_BUILD_TESTS: no disc/*.bin, so r4_widescreen_cull_sites "
                    "(game.toml [widescreen.cull] vs the disc) is not registered")
            endif()
        endif()
        # PGXP defaults: the default-on override of the framework's
        # psx.enhancement.pgxp, the [video] tuning keys, and the runtime
        # flavor R4_PGXP selects (no disc needed).
        if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_pgxp.py")
            add_test(NAME r4_pgxp_defaults
                COMMAND "${Python3_EXECUTABLE}"
                    "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_pgxp.py"
                    --build-dir "${CMAKE_BINARY_DIR}"
                WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")
        endif()
        # PGXP at boot: the built runtime, headless, from an isolated copy of
        # its directory: on by default and when saved settings enable it
        # (geometry, texture, culling). PGXP is never booted off, not even as
        # a reference. Guards the framework's session-start arming end to end.
        # Needs the debug server and the disc.
        file(GLOB _R4_DISC_CUES "${CMAKE_CURRENT_SOURCE_DIR}/disc/*.cue")
        if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_pgxp_boot.py")
            if(_R4_DISC_CUES AND PSX_DEBUG_TOOLS)
                list(GET _R4_DISC_CUES 0 _R4_DISC_CUE)
                add_test(NAME r4_pgxp_boot
                    COMMAND "${Python3_EXECUTABLE}"
                        "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_pgxp_boot.py"
                        --build-dir "${CMAKE_BINARY_DIR}"
                        --disc "${_R4_DISC_CUE}"
                    WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")
                set_tests_properties(r4_pgxp_boot PROPERTIES TIMEOUT 600)
            else()
                message(WARNING "R4_BUILD_TESTS: r4_pgxp_boot needs the disc "
                    "(disc/*.cue) and PSX_DEBUG_TOOLS, so it is not registered")
            endif()
        endif()
        # R4 Max Detail's manifest: on by default at the most detail (owner
        # decision), every option with a Stock choice, and car patches that are
        # exactly r4_max_detail.h's tables. No disc needed.
        if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tools/r4_detail_scan.py")
            add_test(NAME r4_max_detail_manifest
                COMMAND "${Python3_EXECUTABLE}"
                    "${CMAKE_CURRENT_SOURCE_DIR}/tools/r4_detail_scan.py" --check-manifest
                WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")
        endif()
        # game.toml's [[draw_distance.clamp]] sites, R4 Max Detail's car-table
        # patches and the course-list lookup the plugins hook must match the
        # boot EXE (read from the disc image, like the cull-site check).
        if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tools/r4_detail_scan.py")
            file(GLOB _R4_DISC_BINS "${CMAKE_CURRENT_SOURCE_DIR}/disc/*.bin")
            if(_R4_DISC_BINS)
                add_test(NAME r4_max_detail_sites
                    COMMAND "${Python3_EXECUTABLE}"
                        "${CMAKE_CURRENT_SOURCE_DIR}/tools/r4_detail_scan.py"
                        --check "${CMAKE_CURRENT_SOURCE_DIR}/game.toml"
                    WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")
            else()
                message(WARNING "R4_BUILD_TESTS: no disc/*.bin, so r4_max_detail_sites "
                    "(game.toml [[draw_distance.clamp]] vs the disc) is not registered")
            endif()
        endif()
        # R4's on-by-default display settings (manifests, game.toml) and the
        # tools/mod_state.py switches scripted runs use to turn them off.
        if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_defaults.py")
            add_test(NAME r4_defaults
                COMMAND "${Python3_EXECUTABLE}"
                    "${CMAKE_CURRENT_SOURCE_DIR}/tests/test_r4_defaults.py"
                WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")
            set_tests_properties(r4_defaults PROPERTIES SKIP_RETURN_CODE 77)
        endif()
        # The pinned psxrecomp reads every game.toml [video] key. Skipped
        # (with the list) while R4 is ahead of its pin; the strict form
        # refuses that state for a release (tools/package_release.sh).
        if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tools/check_pin_keys.py")
            add_test(NAME r4_pin_keys
                COMMAND "${Python3_EXECUTABLE}"
                    "${CMAKE_CURRENT_SOURCE_DIR}/tools/check_pin_keys.py" --ctest
                WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")
            set_tests_properties(r4_pin_keys PROPERTIES SKIP_RETURN_CODE 77)
        endif()
    endif()
endif()
