cmake_minimum_required(VERSION 3.20)
project(MyGameRecomp
    VERSION 0.1.0
    LANGUAGES C CXX
    DESCRIPTION "Recompiled PS3 game project (ps3recomp)"
)

# ---------------------------------------------------------------------------
# Standards
# ---------------------------------------------------------------------------
set(CMAKE_C_STANDARD 17)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# Prefer Ninja if available
if(NOT CMAKE_GENERATOR MATCHES "Ninja" AND NOT DEFINED ENV{CMAKE_GENERATOR})
    message(STATUS "Tip: use -G Ninja for faster builds")
endif()

# ---------------------------------------------------------------------------
# The two directories this project is built from
# ---------------------------------------------------------------------------
# PS3RECOMP_DIR is the toolkit checkout: include/, runtime/, libs/, tools/.
# RECOMP_DIR is where the lifter's output for THIS game lives. They are
# separate on purpose -- a port keeps its generated code in its own tree and
# points at whatever toolkit checkout it is building against:
#
#   cmake -B build -G Ninja \
#         -DPS3RECOMP_DIR=/path/to/ps3recomp \
#         -DRECOMP_DIR=/path/to/my_game/recompiled
#
if(NOT DEFINED PS3RECOMP_DIR)
    # Default: this project is still sitting inside ps3recomp/templates/project/
    get_filename_component(PS3RECOMP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../" ABSOLUTE)
endif()
get_filename_component(PS3RECOMP_DIR "${PS3RECOMP_DIR}" ABSOLUTE)

set(RECOMP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/recompiled" CACHE PATH
    "Directory holding the lifter's output: ppu_recomp.h and the lifted sources")
get_filename_component(RECOMP_DIR "${RECOMP_DIR}" ABSOLUTE)

message(STATUS "ps3recomp SDK:   ${PS3RECOMP_DIR}")
message(STATUS "Lifted output:   ${RECOMP_DIR}")

if(NOT EXISTS "${RECOMP_DIR}/ppu_recomp.h")
    message(FATAL_ERROR
        "No ppu_recomp.h in ${RECOMP_DIR}.\n"
        "That header and the lifted sources beside it are what "
        "tools/ppu_lifter.py writes. Run the lifter, drop its output there, "
        "or point -DRECOMP_DIR= at wherever it already is.")
endif()

# The lifted translation units. A game's lift is hundreds of generated files,
# so they are globbed rather than listed; re-run CMake after a fresh lift.
file(GLOB RECOMP_SOURCES CONFIGURE_DEPENDS
    "${RECOMP_DIR}/*.c"
    "${RECOMP_DIR}/*.cpp"
)
if(NOT RECOMP_SOURCES)
    message(FATAL_ERROR
        "${RECOMP_DIR} has a ppu_recomp.h but no .c or .cpp beside it. The "
        "lifted functions and the function table live in those; without them "
        "there is nothing to run.")
endif()
list(LENGTH RECOMP_SOURCES RECOMP_SOURCE_COUNT)
message(STATUS "Lifted sources:  ${RECOMP_SOURCE_COUNT} file(s)")

# ---------------------------------------------------------------------------
# ps3recomp runtime library
# ---------------------------------------------------------------------------
# Built from source as a subdirectory rather than imported as a prebuilt
# archive. A static library carries none of its own link requirements, so an
# imported one arrives without SDL2, pthreads, the Metal frameworks or the
# Winsock/XInput imports -- the link then fails on every platform for a
# different reason. add_subdirectory hands all of that over with the target.
add_subdirectory("${PS3RECOMP_DIR}" "${CMAKE_BINARY_DIR}/ps3recomp_sdk"
                 EXCLUDE_FROM_ALL)

# ---------------------------------------------------------------------------
# The HLE NID table
# ---------------------------------------------------------------------------
# Maps each firmware import NID onto the handler in the runtime that answers
# it. A port may keep a hand-curated one beside its lift; otherwise generate
# the canonical every-module table, which is what the toolkit's own boot
# harness uses.
if(EXISTS "${RECOMP_DIR}/ppu_hle_nids.cpp")
    set(HLE_NID_TABLE "${RECOMP_DIR}/ppu_hle_nids.cpp")
    message(STATUS "HLE NID table:   ${HLE_NID_TABLE}")
else()
    find_package(Python3 COMPONENTS Interpreter REQUIRED)
    set(HLE_NID_TABLE "${CMAKE_CURRENT_BINARY_DIR}/ppu_hle_nids.cpp")
    # The table is scanned from the library sources: a new export needs a
    # regenerated table, or its import falls through to the unresolved stub.
    file(GLOB HLE_LIB_SOURCES CONFIGURE_DEPENDS "${PS3RECOMP_DIR}/libs/*/*.c")
    add_custom_command(
        OUTPUT "${HLE_NID_TABLE}"
        COMMAND "${Python3_EXECUTABLE}"
                "${PS3RECOMP_DIR}/tools/gen_hle_nids.py"
                --out "${HLE_NID_TABLE}" --all
        DEPENDS "${PS3RECOMP_DIR}/tools/gen_hle_nids.py"
                "${PS3RECOMP_DIR}/tools/nid_database.py"
                ${HLE_LIB_SOURCES}
        COMMENT "Generating the HLE NID -> handler table")
    message(STATUS "HLE NID table:   generated (every module)")
endif()

# ---------------------------------------------------------------------------
# The game executable
# ---------------------------------------------------------------------------
# The PPU boot scaffold is compiled here rather than taken from the runtime
# library: every one of these files #includes the lifter's per-game
# ppu_recomp.h, so they can only be built against a particular lift.
set(PS3RECOMP_SCAFFOLD
    "${PS3RECOMP_DIR}/runtime/ppu/ppu_loader.cpp"
    "${PS3RECOMP_DIR}/runtime/ppu/ppu_hle.cpp"
    "${PS3RECOMP_DIR}/runtime/ppu/ppu_fs.cpp"
    "${PS3RECOMP_DIR}/runtime/ppu/ppu_sysprx.cpp"
)
# MinGW: g_trampoline_fn lives in its own unit, which tools/ppu_cxx.sh hands
# to the lifted code's compiler (see the file for why).
if(MINGW)
    list(APPEND PS3RECOMP_SCAFFOLD "${PS3RECOMP_DIR}/runtime/ppu/ppu_trampoline_tls.cpp")
endif()

# ---------------------------------------------------------------------------
# Lifted SPU images (optional)
# ---------------------------------------------------------------------------
# A title that runs SPU work gets its images lifted into <SPU_DIR>/<image>/ by
# tools/spu_lifter.py, with a registration TU generated by
# tools/build_spu_workloads.py. cellSpurs dispatches them by content
# fingerprint, so the generated table is keyed to the images THIS build ships:
# a table generated from another release registers signatures that can never
# match, which is worse than shipping none. Both the table and the job-module
# registry self-register from constructors and are therefore optional -- a tree
# that has not lifted its SPU images yet configures and links without them.
set(SPU_DIR "${CMAKE_CURRENT_SOURCE_DIR}/spu" CACHE PATH
    "Directory holding the lifted SPU images (<SPU_DIR>/<image>/spu_recomp.c)")
option(PORT_ENABLE_SPU "Compile and register the title's lifted SPU images" ON)

set(SPU_SOURCES "")
if(PORT_ENABLE_SPU)
    file(GLOB SPU_LIFTED CONFIGURE_DEPENDS "${SPU_DIR}/*/spu_recomp.c")
    if(SPU_LIFTED)
        list(LENGTH SPU_LIFTED SPU_IMAGE_COUNT)
        message(STATUS "Lifted SPU:      ${SPU_IMAGE_COUNT} image(s)")
        # The musttail indirect-branch fast path. Excluded from the runtime
        # library on purpose (see the SDK root CMakeLists): it must be built
        # here, by clang, or the tail call degrades to a plain call and a guest
        # loop that branches indirectly walks the thread stack off its guard
        # page a few thousand iterations in.
        # spu_cold.c: the target of the lifted code's register-preserving
        # cold calls (SPU_COLD_THUNK, runtime/spu/spu_context.h). It runs the
        # header's float fix-ups, so it is built with the same -march.
        list(APPEND SPU_SOURCES ${SPU_LIFTED}
             "${PS3RECOMP_DIR}/runtime/spu/spu_dispatch_mt.c"
             "${PS3RECOMP_DIR}/runtime/spu/spu_cold.c")
        # The hand-written SPU jobs (ec5f_native.c: the render-list job's main,
        # natively; it runs on the SPU's float helpers, so it is built like a
        # lifted TU). SSE/AVX intrinsics, so x86-64 only; each registers itself
        # from a constructor over the lifted job, so a host without them (macOS
        # arm64) runs the lifted SPU code instead.
        if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$")
            set(PORT_SPU_NATIVE ON)
            list(APPEND SPU_SOURCES
                 "${CMAKE_CURRENT_SOURCE_DIR}/ec5f_native.c"
                 "${CMAKE_CURRENT_SOURCE_DIR}/job2025_native.c"
                 "${CMAKE_CURRENT_SOURCE_DIR}/edge_kernels_native.c"
                 "${CMAKE_CURRENT_SOURCE_DIR}/jobbc11_native.c"
                 "${CMAKE_CURRENT_SOURCE_DIR}/job207_native.c"
                 "${CMAKE_CURRENT_SOURCE_DIR}/job220_native.c")
        else()
            set(PORT_SPU_NATIVE OFF)
            message(STATUS "  (${CMAKE_SYSTEM_PROCESSOR}: the hand-written SPU jobs are x86-64 only -- lifted SPU code)")
        endif()
        # The animation kernels' bodies are generated from the lifted job
        # module (game code, so not in the repository): tools/gen_anim_kernels.sh.
        set(_anim_bin "${SPU_DIR}/jobmods/jobmod_2025343b09d0_eFE70.bin")
        if(PORT_SPU_NATIVE AND EXISTS "${_anim_bin}")
            set(ANIM_GEN_DIR "${CMAKE_CURRENT_BINARY_DIR}/anim_gen")
            add_custom_command(
                OUTPUT "${ANIM_GEN_DIR}/job2025_kernels_gen.h" "${ANIM_GEN_DIR}/job2025_kernels_wide.h"
                COMMAND ${CMAKE_COMMAND} -E make_directory "${ANIM_GEN_DIR}"
                COMMAND sh "${CMAKE_CURRENT_SOURCE_DIR}/tools/gen_anim_kernels.sh" "${_anim_bin}"
                        "${PS3RECOMP_DIR}" "${ANIM_GEN_DIR}"
                DEPENDS "${_anim_bin}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/gen_anim_kernels.sh"
                        "${CMAKE_CURRENT_SOURCE_DIR}/tools/kgen.py" "${CMAKE_CURRENT_SOURCE_DIR}/tools/kwide.py"
                        "${CMAKE_CURRENT_SOURCE_DIR}/tools/kabi.py"
                VERBATIM)
            list(APPEND SPU_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/job2025_kernels_native.c")
        else()
            message(STATUS "  (no ${_anim_bin} -- animation kernels left out)")
        endif()
        # Generated beside the lift; each is present only once its generator
        # has been run, so each is included only if it is actually here.
        foreach(gen IN ITEMS spu_workloads.c spu_elf_workloads.c jobmods_register.c taskset_policy_bytes.c)
            if(EXISTS "${SPU_DIR}/${gen}")
                list(APPEND SPU_SOURCES "${SPU_DIR}/${gen}")
            else()
                message(STATUS "  (no ${gen} -- not registered)")
            endif()
        endforeach()
    else()
        message(STATUS "Lifted SPU:      none found in ${SPU_DIR}")
    endif()
endif()

# Lifted SPU side of firmware modules (tools/lift_firmware_spu.py): libsre's SPURS
# kernel and the code bodies it streams into local store, so they run lifted
# instead of on the SPU interpreter when the firmware's own libsre is used.
set(FIRMWARE_SPU_DIR "" CACHE PATH
    "Directory of lifted firmware SPU code (<dir>/<image>/spu_recomp.c + *_spu_register.c)")
if(PORT_ENABLE_SPU AND FIRMWARE_SPU_DIR)
    file(GLOB FIRMWARE_SPU CONFIGURE_DEPENDS
         "${FIRMWARE_SPU_DIR}/*/spu_recomp.c" "${FIRMWARE_SPU_DIR}/*_spu_register.c")
    list(LENGTH FIRMWARE_SPU FIRMWARE_SPU_COUNT)
    message(STATUS "Firmware SPU:    ${FIRMWARE_SPU_COUNT} file(s) from ${FIRMWARE_SPU_DIR}")
    list(APPEND SPU_SOURCES ${FIRMWARE_SPU})
    if(NOT "${PS3RECOMP_DIR}/runtime/spu/spu_dispatch_mt.c" IN_LIST SPU_SOURCES)
        list(APPEND SPU_SOURCES "${PS3RECOMP_DIR}/runtime/spu/spu_dispatch_mt.c")
    endif()
endif()

add_executable(${PROJECT_NAME}
    main.cpp
    crash_report.cpp        # a report for a fatal signal, beside the run's log
    settings.cpp
    modpatch.cpp            # data patches of mods (docs/MODDING.md)
    modfmt.cpp              # community mods in the Mod Manager's format (docs/MODS.md)
    modfmt_ui.cpp
    ui.cpp
    stubs.cpp
    port_cpu_check.c
    native_passes.c
    re_trace.c
    watch_emutls.c          # PS3_WATCH_EMUTLS: hardware write watchpoints (diagnostic)
    prof_main.c             # PS3_PROF_MAIN: sampling profiler of the main PPU thread (diagnostic)
    ppu_native.cpp          # native stand-ins for lifted PPU code (tools/ppu_native_entries.py)
    ${PS3RECOMP_SCAFFOLD}
    ${HLE_NID_TABLE}
    ${RECOMP_SOURCES}
    ${SPU_SOURCES}
)

# ---------------------------------------------------------------------------
# The co-op / split-screen mod (optional, off by default)
# ---------------------------------------------------------------------------
# A mod, not part of the port: -DINFAMOUS_COOP=ON compiles port/coop*.c and
# the few hooks the rest of the port has for it (main.cpp's coop_call_* shims
# and coop_start, ui.cpp's split-screen shape, ec5f_native.c's split probe).
# OFF, none of that is in the binary and the PS3RECOMP_COOP_* variables do
# nothing. The lift's PPU_NATIVE_HOOKs for coop's addresses
# (tools/ppu_native_entries.py PROBES) stay either way: with nothing
# registered each is one null test, and the lift does not change with the mod.
#
# INFAMOUS_COOP=1 goes on the hooked sources only, never on the target: a
# definition on the target changes every lifted TU's compile command (tens of
# minutes of rebuild for a switch they never read). docs/coop/MOD_BUILD.md.
option(INFAMOUS_COOP "Build the co-op / split-screen mod (port/coop*.c)" OFF)
set(COOP_SOURCES "")
set(COOP_HOOKED_SOURCES main.cpp ui.cpp settings.cpp)
if(INFAMOUS_COOP)
    foreach(src IN ITEMS coop.c coop_net.c coop_follow.c coop_netplay.c coop_video.c coop_session.c
                         coop_audio.c coop_auth.c coop_netui.cpp coop_join.cpp coop_ally.c)
        if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${src}")
            list(APPEND COOP_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/${src}")
        endif()
    endforeach()
    target_sources(${PROJECT_NAME} PRIVATE ${COOP_SOURCES})
    if(WIN32)
        target_link_libraries(${PROJECT_NAME} PRIVATE ws2_32)
    endif()
    # Online co-op video (coop_video.c, docs/coop/REMOTE_VIDEO.md): H.264 through FFmpeg's
    # libavcodec when pkg-config finds it. Without it coop_video.c still builds (the session
    # links against it) and logs why there is no video. The include directories and the
    # define go on coop_video.c alone, the libraries on the link line: nothing else's
    # compile command changes. COOP_HAVE_VIDEO tells the other coop sources it is linked.
    set(_cv "${CMAKE_CURRENT_SOURCE_DIR}/coop_video.c")
    if(_cv IN_LIST COOP_SOURCES)
        set_property(SOURCE ${COOP_SOURCES} APPEND PROPERTY COMPILE_DEFINITIONS COOP_HAVE_VIDEO=1)
        find_package(PkgConfig QUIET)
        if(PKG_CONFIG_FOUND)
            pkg_check_modules(COOP_FFMPEG QUIET libavcodec libavutil)
        endif()
        if(COOP_FFMPEG_FOUND)
            set_property(SOURCE "${_cv}" APPEND PROPERTY COMPILE_DEFINITIONS COOP_HAVE_FFMPEG=1)
            if(COOP_FFMPEG_INCLUDE_DIRS)
                set_property(SOURCE "${_cv}" APPEND PROPERTY INCLUDE_DIRECTORIES ${COOP_FFMPEG_INCLUDE_DIRS})
            endif()
            target_link_libraries(${PROJECT_NAME} PRIVATE ${COOP_FFMPEG_LINK_LIBRARIES})
            message(STATUS "Co-op video:     H.264 via FFmpeg libavcodec ${COOP_FFMPEG_libavcodec_VERSION}")
        else()
            message(STATUS "Co-op video:     no FFmpeg (pkg-config libavcodec libavutil): online co-op without video")
        endif()
    endif()
    # The game's sound for the friend (coop_audio.c, docs/coop/REMOTE_AUDIO.md): Opus through
    # pkg-config; the mix comes from the toolkit's libs/audio/audio_tap.h (include path on this
    # source only). Without libopus it builds and says so.
    set(_ca "${CMAKE_CURRENT_SOURCE_DIR}/coop_audio.c")
    if(_ca IN_LIST COOP_SOURCES)
        set_property(SOURCE ${COOP_SOURCES} APPEND PROPERTY COMPILE_DEFINITIONS COOP_HAVE_AUDIO=1)
        set_property(SOURCE "${_ca}" APPEND PROPERTY INCLUDE_DIRECTORIES "${PS3RECOMP_DIR}/libs/audio")
        find_package(PkgConfig QUIET)
        if(PKG_CONFIG_FOUND)
            pkg_check_modules(COOP_OPUS QUIET opus)
        endif()
        if(COOP_OPUS_FOUND)
            set_property(SOURCE "${_ca}" APPEND PROPERTY COMPILE_DEFINITIONS COOP_HAVE_OPUS=1)
            set_property(SOURCE "${_ca}" APPEND PROPERTY INCLUDE_DIRECTORIES ${COOP_OPUS_INCLUDE_DIRS})
            target_link_libraries(${PROJECT_NAME} PRIVATE ${COOP_OPUS_LINK_LIBRARIES})
            message(STATUS "Co-op audio:     Opus ${COOP_OPUS_VERSION}")
        else()
            message(STATUS "Co-op audio:     no libopus (pkg-config opus): the friend gets no sound")
        endif()
    endif()
    # Online co-op session (coop_session.c, docs/coop/REMOTE_SESSION.md). It compares build ids
    # with the friend's: the commit this tree was configured at. ui.cpp's JOIN window shows
    # coop_video's picture when it is linked.
    set(PORT_BUILD_ID "dev")
    find_package(Git QUIET)
    if(GIT_FOUND)
        execute_process(COMMAND "${GIT_EXECUTABLE}" rev-parse --short=10 HEAD
                        WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
                        OUTPUT_VARIABLE _git_head OUTPUT_STRIP_TRAILING_WHITESPACE
                        RESULT_VARIABLE _git_rc ERROR_QUIET)
        if(_git_rc EQUAL 0 AND _git_head)
            set(PORT_BUILD_ID "${_git_head}")
        endif()
    endif()
    message(STATUS "Co-op online:    build id ${PORT_BUILD_ID}")
    # The JOIN window's overlay: ImGui's SDL_Renderer backend, over coop_video's SDL_Renderer.
    # The SDL headers on this one source only: on the target they would change every lifted
    # TU's compile command.
    get_target_property(_rt_defs ps3recomp_runtime INTERFACE_COMPILE_DEFINITIONS)
    set(_sdlr "${PS3RECOMP_DIR}/libs/thirdparty/imgui/backends/imgui_impl_sdlrenderer2.cpp")
    if(EXISTS "${_sdlr}" AND _rt_defs AND "PS3RECOMP_UI" IN_LIST _rt_defs)
        find_package(SDL2 QUIET)
        target_sources(${PROJECT_NAME} PRIVATE "${_sdlr}")
        if(TARGET SDL2::SDL2)
            set_property(SOURCE "${_sdlr}" APPEND PROPERTY INCLUDE_DIRECTORIES
                         "$<TARGET_PROPERTY:SDL2::SDL2,INTERFACE_INCLUDE_DIRECTORIES>")
        elseif(SDL2_INCLUDE_DIRS)
            set_property(SOURCE "${_sdlr}" APPEND PROPERTY INCLUDE_DIRECTORIES "${SDL2_INCLUDE_DIRS}")
        endif()
    endif()
    if("${CMAKE_CURRENT_SOURCE_DIR}/ec5f_native.c" IN_LIST SPU_SOURCES)
        list(APPEND COOP_HOOKED_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/ec5f_native.c")
    endif()
    list(LENGTH COOP_SOURCES _coop_n)
    message(STATUS "Co-op mod:       ON (${_coop_n} source(s))")
    # The friend's JOIN-only client, from the co-op's sources alone (no lift, no runtime): the
    # one binary of this tree that can be given away (docs/coop/JOIN_CLIENT.md).
    include("${CMAKE_CURRENT_SOURCE_DIR}/join/join.cmake")
    infamous_add_join(PORT_DIR "${CMAKE_CURRENT_SOURCE_DIR}"
                      IMGUI_DIR "${PS3RECOMP_DIR}/libs/thirdparty/imgui" BUILD_ID "${PORT_BUILD_ID}")
else()
    message(STATUS "Co-op mod:       off (-DINFAMOUS_COOP=ON builds it)")
endif()

# ---------------------------------------------------------------------------
# The remaster mod (optional, on by default; docs/REMASTER.md)
# ---------------------------------------------------------------------------
# Picture options beyond the PS3's: sharper shadows and reflection, a wider
# shadow filter, 16x AF, full-resolution particles, a longer draw distance,
# texture packs and shader patches. All of it is environment variables the
# renderer reads (and treats as off when unset); this mod is what sets them
# from [mod.remaster] in settings.ini, plus its Mods-tab block. OFF, nothing
# sets them and the picture is the PS3's. The define goes on its two hooked
# sources only (settings.cpp's export, ui.cpp's Mods tab), as for co-op, in
# the block after ui.cpp's own properties below.
option(INFAMOUS_MOD_REMASTER "Build the remaster mod (port/mods/remaster)" ON)
if(INFAMOUS_MOD_REMASTER)
    target_sources(${PROJECT_NAME} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/mods/remaster/remaster_mod.cpp")
    message(STATUS "Remaster mod:    ON")
else()
    message(STATUS "Remaster mod:    off (-DINFAMOUS_MOD_REMASTER=ON builds it)")
endif()

# ---------------------------------------------------------------------------
# The skip-cutscenes mod (optional, on by default; docs/MODS.md)
# ---------------------------------------------------------------------------
# Hold START to end a Bink video, the game's own "Pular vídeo" in the pause
# menu of every cutscene, no boot logo video: through the game's own ways of
# ending them (rpi/skip-cutscenes/REQUEST.md). Switched by [mods] skipcut. The
# define goes on its hooked sources only (settings.cpp's export, ui.cpp's Mods
# tab and hint), in the block after ui.cpp's own properties below.
option(INFAMOUS_MOD_SKIPCUT "Build the skip-cutscenes mod (port/mods/skipcut)" ON)
if(INFAMOUS_MOD_SKIPCUT)
    target_sources(${PROJECT_NAME} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/mods/skipcut/skipcut_mod.cpp")
    message(STATUS "Skip-cutscenes:  ON")
else()
    message(STATUS "Skip-cutscenes:  off (-DINFAMOUS_MOD_SKIPCUT=ON builds it)")
endif()

# ---------------------------------------------------------------------------
# The temporal upscaler mod (optional, on by default, off at run time until [mods] upscale = 1; docs/UPSCALERS.md)
# ---------------------------------------------------------------------------
# Motion vectors from the depth buffer and the game's camera, projection
# jitter, and FSR 2 (vendored, MIT: mods/upscale/third_party/fsr2) in the
# present chain; DLSS and XeSS only with the player's own SDK given below,
# never in the repository. The renderer's hooks are in the toolkit
# (libs/video/rsx_upscale_hooks.h) and do nothing until this mod installs
# them, which it does when `[mods] upscale = 1`. Vulkan only. The define goes
# on main.cpp, settings.cpp and ui.cpp alone, as for the other mods.
option(INFAMOUS_MOD_UPSCALE "Build the temporal upscaler mod (port/mods/upscale)" ON)
set(INFAMOUS_UPSCALE_DLSS_SDK "" CACHE PATH "The NVIDIA DLSS SDK (include/nvsdk_ngx_vk.h, lib/...): builds the DLSS path")
set(INFAMOUS_UPSCALE_DLSS_LIB "" CACHE FILEPATH "NGX's static library, when not under the SDK's lib/ (libnvsdk_ngx.a)")
set(INFAMOUS_UPSCALE_XESS_SDK "" CACHE PATH "The Intel XeSS SDK (inc/xess/xess_vk.h): builds the XeSS path, the library loads at run time")
if(INFAMOUS_MOD_UPSCALE AND NOT PS3RECOMP_RSX_VULKAN)
    message(STATUS "Upscaler mod:    off (needs -DPS3RECOMP_RSX_VULKAN=ON)")
    set(INFAMOUS_MOD_UPSCALE OFF)
endif()
if(INFAMOUS_MOD_UPSCALE)
    set(_ups "${CMAKE_CURRENT_SOURCE_DIR}/mods/upscale")
    set(_ups_c "${_ups}/upscale_mod.c" "${_ups}/upscale_vk.c" "${_ups}/upscale_xess.c")
    # FSR 4 (upscale_fsr4.cpp) loads AMD's DLLs (and, on Linux, the ffx-vk-linux
    # bridge) at run time: nothing is linked, so with the mod off it costs nothing.
    set(_ups_cxx "${_ups}/upscale_fsr2.cpp" "${_ups}/upscale_dlss.cpp" "${_ups}/upscale_fsr4.cpp")
    # Its settings and Mods-tab block need the built-in mods' keys in settings.h
    # (port_mod_opt); without them the mod is switched by PS3RECOMP_MOD_UPSCALE alone.
    file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/settings.h" _ups_api REGEX "port_mod_opt_set")
    if(_ups_api)
        list(APPEND _ups_cxx "${_ups}/upscale_ui.cpp")
    endif()
    set(_ups_ffx "${_ups}/third_party/fsr2/ffx_fsr2.cpp" "${_ups}/third_party/fsr2/vk/ffx_fsr2_vk.cpp")
    target_sources(${PROJECT_NAME} PRIVATE ${_ups_c} ${_ups_cxx} ${_ups_ffx})
    set_property(SOURCE ${_ups_c} ${_ups_cxx} ${_ups_ffx} APPEND PROPERTY INCLUDE_DIRECTORIES
                 "${_ups}" "${PS3RECOMP_DIR}/libs/video" "${PS3RECOMP_VULKAN_INCLUDE_DIR}"
                 "${PS3RECOMP_DIR}/libs/thirdparty/imgui")
    # The vendored SDK as AMD ships it, with what it assumes of MSVC supplied.
    set_property(SOURCE ${_ups_ffx} APPEND PROPERTY INCLUDE_DIRECTORIES
                 "${_ups}/third_party/fsr2" "${_ups}/third_party/fsr2/vk" "${_ups}/third_party/fsr2/vk/shaders")
    set_property(SOURCE ${_ups_ffx} "${_ups}/upscale_fsr2.cpp" APPEND PROPERTY COMPILE_OPTIONS
                 -include "${_ups}/upscale_fsr2_compat.h" -w)
    # FSR 3.1 (FidelityFX SDK 1.1.4, vendored subset, MIT), same way: its
    # Vulkan backend and component unedited, upscale_fsr3_compat.h first.
    set(_ups_sdk "${_ups}/third_party/ffx_sdk/sdk")
    set(_ups_ffx3 "${_ups_sdk}/src/backends/vk/ffx_vk.cpp" "${_ups_sdk}/src/components/fsr3upscaler/ffx_fsr3upscaler.cpp"
                  "${_ups_sdk}/src/shared/ffx_message.cpp" "${_ups_sdk}/src/shared/ffx_object_management.cpp"
                  "${_ups_sdk}/src/shared/ffx_breadcrumbs_list.cpp")
    target_sources(${PROJECT_NAME} PRIVATE ${_ups_ffx3} "${_ups}/upscale_fsr3.cpp")
    set_property(SOURCE ${_ups_ffx3} "${_ups}/upscale_fsr3.cpp" APPEND PROPERTY INCLUDE_DIRECTORIES
                 "${_ups}" "${PS3RECOMP_VULKAN_INCLUDE_DIR}" "${_ups_sdk}/include" "${_ups_sdk}/src/shared"
                 "${_ups_sdk}/src/components" "${_ups_sdk}/src/backends/shared" "${_ups_sdk}/src/backends/vk")
    set_property(SOURCE ${_ups_ffx3} "${_ups}/upscale_fsr3.cpp" APPEND PROPERTY COMPILE_OPTIONS
                 -include "${_ups}/upscale_fsr3_compat.h" -w)
    set(_ups_status "FSR 2.2, FSR 3.1, FSR 4 (AMD's DLLs loaded at run time)")
    if(NOT WIN32)
        target_link_libraries(${PROJECT_NAME} PRIVATE ${CMAKE_DL_LIBS})
    endif()
    if(INFAMOUS_UPSCALE_DLSS_SDK)
        set(_ngx_lib "${INFAMOUS_UPSCALE_DLSS_LIB}")
        if(NOT _ngx_lib)
            file(GLOB _ngx_lib LIST_DIRECTORIES false "${INFAMOUS_UPSCALE_DLSS_SDK}/lib/Linux_x86_64/libnvsdk_ngx.a"
                 "${INFAMOUS_UPSCALE_DLSS_SDK}/lib/Linux_x86_64/release/libnvsdk_ngx.a")
        endif()
        if(EXISTS "${INFAMOUS_UPSCALE_DLSS_SDK}/include/nvsdk_ngx_vk.h" AND _ngx_lib)
            list(GET _ngx_lib 0 _ngx_lib)
            set_property(SOURCE "${_ups}/upscale_dlss.cpp" "${_ups}/upscale_vk.c" APPEND PROPERTY
                         COMPILE_DEFINITIONS UPS_HAVE_DLSS=1)
            set_property(SOURCE "${_ups}/upscale_dlss.cpp" APPEND PROPERTY INCLUDE_DIRECTORIES
                         "${INFAMOUS_UPSCALE_DLSS_SDK}/include")
            target_link_libraries(${PROJECT_NAME} PRIVATE "${_ngx_lib}" ${CMAKE_DL_LIBS})
            string(APPEND _ups_status ", DLSS (${_ngx_lib})")
        else()
            message(WARNING "INFAMOUS_UPSCALE_DLSS_SDK=${INFAMOUS_UPSCALE_DLSS_SDK} has no include/nvsdk_ngx_vk.h "
                            "or libnvsdk_ngx.a (set INFAMOUS_UPSCALE_DLSS_LIB): DLSS left out")
        endif()
    endif()
    if(INFAMOUS_UPSCALE_XESS_SDK)
        if(EXISTS "${INFAMOUS_UPSCALE_XESS_SDK}/inc/xess/xess_vk.h")
            set_property(SOURCE "${_ups}/upscale_xess.c" "${_ups}/upscale_vk.c" APPEND PROPERTY
                         COMPILE_DEFINITIONS UPS_HAVE_XESS=1)
            set_property(SOURCE "${_ups}/upscale_xess.c" APPEND PROPERTY INCLUDE_DIRECTORIES
                         "${INFAMOUS_UPSCALE_XESS_SDK}/inc")
            target_link_libraries(${PROJECT_NAME} PRIVATE ${CMAKE_DL_LIBS})
            string(APPEND _ups_status ", XeSS (loaded at run time)")
        else()
            message(WARNING "INFAMOUS_UPSCALE_XESS_SDK=${INFAMOUS_UPSCALE_XESS_SDK} has no inc/xess/xess_vk.h: XeSS left out")
        endif()
    endif()
    message(STATUS "Upscaler mod:    ON (${_ups_status})")
else()
    message(STATUS "Upscaler mod:    off (-DINFAMOUS_MOD_UPSCALE=ON builds it)")
endif()

# The lifted SPU sources use bare #include "spu_context.h". Scope that include
# directory (and their flags) to those TUs alone: adding it to the whole target
# changes the compile command of every lifted PPU TU, and those are large enough
# that the needless rebuild is measured in tens of minutes.
#   SPU_USE_DISPATCH_MT -- route SPU_IB_DISPATCH through the musttail path.
#   -O2                 -- the SPU sources are small and decode-hot; -O2 with
#                          the inlining parameter below. The last -O on the
#                          line wins.
#   -march=PORT_SPU_MARCH -- x86-64 only. runtime/spu/spu_helpers.h has vector
#                          forms of the hot SPU ops for SSE4.1/AVX2 (and AVX-512):
#                          the float ops, the byte permutes, the conversions,
#                          the LS byte swap. On the baseline every one of them
#                          is a per-lane scalar loop. Empty keeps the baseline;
#                          port_cpu_check.c stops an x86-64-vN build with a
#                          message on a CPU below that level.
option(PORT_SPU_LS_DEBUG "Keep the SPU local-store debug hooks in the lifted code" OFF)
set(PORT_SPU_MARCH "x86-64-v3" CACHE STRING
    "-march for the lifted SPU sources on x86-64 (empty: compiler default)")
if(SPU_SOURCES)
    set(_spu_defs "SPU_USE_DISPATCH_MT;SPU_WRCH_INLINE")
    if(NOT PORT_SPU_LS_DEBUG)
        list(APPEND _spu_defs "SPU_LS_NO_DEBUG")
    endif()
    set_source_files_properties(${SPU_SOURCES} PROPERTIES
        INCLUDE_DIRECTORIES "${PS3RECOMP_DIR}/runtime/spu"
        # SPU_WRCH_INLINE: the MFC parameter channel writes inline
        # (spu_wrch_fast, runtime/spu/spu_helpers.h).
        # SPU_LS_NO_DEBUG: no local-store debug hooks in the lifted code
        # (runtime/spu/spu_context.h); PORT_SPU_LS_DEBUG=ON keeps them.
        COMPILE_DEFINITIONS "${_spu_defs}")
    if(NOT MSVC OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
        set(_spu_opts "-O2")
        if(PORT_SPU_MARCH AND CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$")
            list(APPEND _spu_opts "-march=${PORT_SPU_MARCH}")
        endif()
        # A lifted SPU TU is a few huge functions calling hundreds of small
        # helpers; GCC stops inlining once the unit has grown 40%, and the
        # rest become calls that pass every 128-bit register through rdx:rax
        # (inFAMOUS 2's hottest job plugin loop: 144 calls -> 1).
        if(CMAKE_C_COMPILER_ID STREQUAL "GNU")
            list(APPEND _spu_opts "--param=inline-unit-growth=1000")
        endif()
        set_source_files_properties(${SPU_SOURCES} PROPERTIES COMPILE_OPTIONS "${_spu_opts}")
    endif()
endif()
if(ANIM_GEN_DIR)
    set_property(SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/job2025_kernels_native.c" APPEND PROPERTY
                 INCLUDE_DIRECTORIES "${ANIM_GEN_DIR}")
    set_property(SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/job2025_kernels_native.c" APPEND PROPERTY
                 OBJECT_DEPENDS "${ANIM_GEN_DIR}/job2025_kernels_gen.h;${ANIM_GEN_DIR}/job2025_kernels_wide.h")
endif()
if(PORT_SPU_MARCH MATCHES "^x86-64-v[234]$" AND SPU_SOURCES)
    set_source_files_properties(port_cpu_check.c PROPERTIES
        COMPILE_DEFINITIONS "PORT_SPU_ISA_LEVEL=\"${PORT_SPU_MARCH}\"")
endif()

# app.rc carries the icon, the version block and the manifest, and needs a
# resource compiler. Listing it as a source on a host that has none is not a
# link error, it is a "no rule to make" for a file nothing can consume.
if(WIN32 AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/app.rc")
    target_sources(${PROJECT_NAME} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/app.rc")
endif()

target_include_directories(${PROJECT_NAME} PRIVATE
    "${RECOMP_DIR}"                            # the generated ppu_recomp.h
    "${PS3RECOMP_DIR}/include"
    "${PS3RECOMP_DIR}/runtime/ppu"
    "${PS3RECOMP_DIR}/runtime/spu"
    "${PS3RECOMP_DIR}/runtime/memory"
    "${PS3RECOMP_DIR}/runtime/syscalls"
    "${PS3RECOMP_DIR}/runtime/prx"             # prx_loader.h, for lifted PRX modules
    "${PS3RECOMP_DIR}/runtime/platform"        # win32_compat.h and friends
    "${PS3RECOMP_DIR}/libs/video"
    "${CMAKE_CURRENT_SOURCE_DIR}"
)

target_link_libraries(${PROJECT_NAME} PRIVATE
    ps3recomp_runtime
)

# The start screen's background is the disc's own PIC1.PNG, read with libpng
# when the system has it (Fedora: libpng-devel); without it, a gradient. The
# library's path only, and the define on ui.cpp alone: an include directory or
# a definition on the target would change every lifted TU's compile command.
# modfmt.cpp reads the zips of the Mod Manager's mods with zlib.
find_package(ZLIB REQUIRED)
# the library only: the imported target would add -isystem /usr/include and reorder the search (as for PNG below)
target_link_libraries(${PROJECT_NAME} PRIVATE ${ZLIB_LIBRARIES})
find_package(PNG QUIET)
if(PNG_FOUND)
    target_link_libraries(${PROJECT_NAME} PRIVATE ${PNG_LIBRARIES})
    # A cross sysroot's own include dir (MinGW: <root>/include, where zlib.h
    # and png.h sit) must not be passed again: as a later -isystem it reorders
    # the search and libstdc++'s #include_next <stdlib.h> finds nothing.
    set(_png_inc ${PNG_INCLUDE_DIRS})
    foreach(_root ${CMAKE_FIND_ROOT_PATH})
        list(REMOVE_ITEM _png_inc "${_root}/include")
    endforeach()
    set_source_files_properties(ui.cpp PROPERTIES
        COMPILE_DEFINITIONS PORT_HAVE_PNG=1
        INCLUDE_DIRECTORIES "${_png_inc}")
endif()

# After every set_source_files_properties above: those replace a source's
# COMPILE_DEFINITIONS (ui.cpp's PORT_HAVE_PNG, the SPU sources' list), this
# appends to them.
if(INFAMOUS_COOP)
    set_property(SOURCE ${COOP_HOOKED_SOURCES} ${COOP_SOURCES} APPEND PROPERTY
                 COMPILE_DEFINITIONS INFAMOUS_COOP=1)
    set_property(SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/coop_session.c" APPEND PROPERTY
                 COMPILE_DEFINITIONS "PORT_BUILD_ID=\"${PORT_BUILD_ID}\"")
    # ui.cpp's JOIN window shows coop_video's picture when it is linked (here, after ui.cpp's
    # PORT_HAVE_PNG replaced its definitions).
    if("${CMAKE_CURRENT_SOURCE_DIR}/coop_video.c" IN_LIST COOP_SOURCES)
        set_property(SOURCE ui.cpp APPEND PROPERTY COMPILE_DEFINITIONS COOP_HAVE_VIDEO=1)
    endif()
endif()
if(INFAMOUS_MOD_REMASTER)
    # The game's target only: the co-op JOIN client builds settings.cpp too, without the mod.
    set_property(SOURCE settings.cpp ui.cpp APPEND PROPERTY COMPILE_DEFINITIONS
                 "$<$<STREQUAL:$<TARGET_PROPERTY:NAME>,${PROJECT_NAME}>:INFAMOUS_MOD_REMASTER=1>")
endif()
if(INFAMOUS_MOD_SKIPCUT)
    # As above: the game's target only.
    set_property(SOURCE settings.cpp ui.cpp APPEND PROPERTY COMPILE_DEFINITIONS
                 "$<$<STREQUAL:$<TARGET_PROPERTY:NAME>,${PROJECT_NAME}>:INFAMOUS_MOD_SKIPCUT=1>")
endif()
if(INFAMOUS_MOD_UPSCALE)
    # As above: the game's target only (the JOIN client builds settings.cpp and ui.cpp too).
    set_property(SOURCE main.cpp APPEND PROPERTY COMPILE_DEFINITIONS
                 "$<$<STREQUAL:$<TARGET_PROPERTY:NAME>,${PROJECT_NAME}>:INFAMOUS_MOD_UPSCALE=1>")
    if(_ups_api)
        set_property(SOURCE settings.cpp ui.cpp APPEND PROPERTY COMPILE_DEFINITIONS
                     "$<$<STREQUAL:$<TARGET_PROPERTY:NAME>,${PROJECT_NAME}>:INFAMOUS_MOD_UPSCALE=1>")
    endif()
endif()

# The runtime is C++, and on Apple also Objective-C. Letting CMake infer the
# link language from the generated C would leave the C++ standard library out.
set_target_properties(${PROJECT_NAME} PROPERTIES LINKER_LANGUAGE CXX)

# Windows system import libraries. dbghelp symbolizes crash-handler addresses
# against the PDB, user32 and gdi32 are what the backend's window and its GDI
# present are made of, and winmm is timeBeginPeriod. None of the four names
# anything a POSIX linker can find; the D3D12 backend's own imports come in
# through the #pragma comment(lib) in libs/video/rsx_d3d12_backend.c.
if(WIN32)
    target_link_libraries(${PROJECT_NAME} PRIVATE
        dbghelp
        user32
        gdi32
        winmm
        synchronization   # WaitOnAddress / WakeByAddressSingle: the futex of rsx_be_thread.c
    )
endif()

# MinGW: libgcc, libstdc++ and winpthread linked in, so the .exe does not need
# libgcc_s_seh-1.dll, libstdc++-6.dll or libwinpthread-1.dll beside it. -static
# only changes how -l names resolve; the libraries CMake found by full path
# (SDL2, libpng, zlib: their .dll.a import libraries) stay DLL imports.
if(MINGW)
    target_link_options(${PROJECT_NAME} PRIVATE -static)
endif()

# ---------------------------------------------------------------------------
# Compiler-specific flags
# ---------------------------------------------------------------------------
if(CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU")
    target_compile_options(${PROJECT_NAME} PRIVATE
        -Wall -Wextra -Wno-unused-parameter
        -fno-strict-aliasing
        # The lift spells PPC arithmetic as signed C arithmetic, which must wrap;
        # without this, clang exploits overflow UB (e.g. folds "x*x < 0" to false).
        -fwrapv
    )
elseif(MSVC)
    target_compile_options(${PROJECT_NAME} PRIVATE
        /W3 /wd4100 /wd4244 /wd4267
        /Zc:__cplusplus         # report correct __cplusplus value
        # ppu_recomp.h defines PPU_FENCE, the lowering of the guest's
        # sync/lwsync/eieio/isync, and in C that is <stdatomic.h>. The lifter
        # writes C++ by default, but --single-file writes ppu_recomp.c, and a
        # port that took it would not compile without this. The runtime's own
        # build already carries the same flag for the same reason.
        /experimental:c11atomics
    )
    target_compile_definitions(${PROJECT_NAME} PRIVATE
        _CRT_SECURE_NO_WARNINGS
    )
endif()

# The lifted translation units are machine-generated and can run to hundreds of
# thousands of lines each, so they get their own flags:
#
#   - warnings off. They are about generated code and nobody will act on them,
#     and at this volume they bury the diagnostics that matter.
#   - no floating-point contraction. arm64 fuses a multiply and an add by
#     default; a PPC fmadd is spelt as one where the lifter means one.
#   - /bigobj on MSVC. A single lifted file routinely passes the 65,536-section
#     limit of the default object format.
#   - -march=PORT_PPU_MARCH on x86-64. ppu_vmx.h has four-lane forms of the
#     hottest VMX float ops (vmaddfp, vnmsubfp, vaddfp, vsubfp) for FMA and
#     SSE4.1; the baseline runs them a lane at a time through libm's fmaf.
#     Both give the same bits. port_cpu_check.c stops a build on a CPU below
#     the level with a message.
#   - scripts/build.sh sets CMAKE_CXX_COMPILER_LAUNCHER to tools/ppu_cxx.sh,
#     which hands these units to clang++: with the lifter's __restrict context
#     it keeps guest registers in host registers across guest memory accesses
#     (see docs/NOTES.md). PORT_PPU_GCC=1 in the environment keeps GCC.
set(PORT_PPU_MARCH "x86-64-v3" CACHE STRING
    "-march for the lifted PPU sources on x86-64 (empty: compiler default)")
if(MSVC)
    set_source_files_properties(${RECOMP_SOURCES} PROPERTIES
        COMPILE_OPTIONS "/w;/bigobj")
else()
    set(_ppu_opts "-w;-ffp-contract=off")
    if(PORT_PPU_MARCH AND CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$")
        list(APPEND _ppu_opts "-march=${PORT_PPU_MARCH}")
    endif()
    # Profile-guided optimisation of the lifted code (clang only: tools/ppu_cxx.sh
    # hands these units to clang++; PORT_PPU_GCC=1 builds ignore it). Front-end
    # instrumentation (-fprofile-instr-*), not the IR-level -fprofile-generate: the
    # counters key on the source's own control flow, so one profile collected on
    # Linux also applies to the MinGW build. docs/NOTES.md, "PGO of the lifted code".
    #   off  nothing (default when there is no profile)
    #   gen  instrumented build: run scripts/pgo-collect.sh, it writes pgo/ppu.profdata
    #   use  -fprofile-instr-use=PORT_PPU_PGO_FILE
    #   auto use when the profile file exists, else off
    set(PORT_PPU_PGO "auto" CACHE STRING "PGO of the lifted PPU sources: off | gen | use | auto")
    set(PORT_PPU_PGO_FILE "${CMAKE_CURRENT_SOURCE_DIR}/pgo/ppu.profdata" CACHE FILEPATH
        "The merged clang profile the 'use' mode reads")
    set(_pgo "${PORT_PPU_PGO}")
    if(_pgo STREQUAL "auto")
        if(EXISTS "${PORT_PPU_PGO_FILE}" AND "$ENV{PORT_PPU_GCC}" STREQUAL "")
            set(_pgo "use")
        else()
            set(_pgo "off")
        endif()
    endif()
    if(_pgo STREQUAL "gen")
        list(APPEND _ppu_opts "-fprofile-instr-generate")
        execute_process(COMMAND clang --print-resource-dir OUTPUT_VARIABLE _clang_res
                        OUTPUT_STRIP_TRAILING_WHITESPACE)
        target_sources(${PROJECT_NAME} PRIVATE pgo_dump.c)
        target_link_libraries(${PROJECT_NAME} PRIVATE
            "${_clang_res}/lib/x86_64-redhat-linux-gnu/libclang_rt.profile.a")
    elseif(_pgo STREQUAL "use")
        if(NOT EXISTS "${PORT_PPU_PGO_FILE}")
            message(FATAL_ERROR "PORT_PPU_PGO=use but ${PORT_PPU_PGO_FILE} does not exist")
        endif()
        list(APPEND _ppu_opts "-fprofile-instr-use=${PORT_PPU_PGO_FILE}")
        set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${PORT_PPU_PGO_FILE}")
    endif()
    message(STATUS "PPU PGO:         ${_pgo}")
    set_source_files_properties(${RECOMP_SOURCES} PROPERTIES COMPILE_OPTIONS "${_ppu_opts}"
        COMPILE_DEFINITIONS PPU_INLINE_STORES)
endif()
if(PORT_PPU_MARCH MATCHES "^x86-64-v[234]$")
    set_property(SOURCE port_cpu_check.c APPEND PROPERTY
        COMPILE_DEFINITIONS "PORT_PPU_ISA_LEVEL=\"${PORT_PPU_MARCH}\"")
elseif(PORT_PPU_MARCH)
    message(WARNING "PORT_PPU_MARCH=${PORT_PPU_MARCH} is not an x86-64-vN level: "
                    "port_cpu_check.c cannot test for it, and a CPU without it gets a bare SIGILL")
endif()

# ---------------------------------------------------------------------------
# Install
# ---------------------------------------------------------------------------
install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION bin)
