cmake_minimum_required(VERSION 3.20)
project(mw2recomp CXX)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE Release)
endif()

# Android brings its own window, input and audio (runtime/android/), so SDL is
# off there whatever the cache says -- and a default the Gradle build does not
# have to repeat.
if(ANDROID)
    set(MW2_USE_SDL OFF CACHE BOOL "Use SDL3 (not on Android)" FORCE)
endif()
option(MW2_USE_SDL "Use SDL3 for gamepad input (and later window/audio)" ON)
option(MW2_TRACE_INDIRECT "Report indirect calls with no recompiled target instead of jumping to null" ON)
option(MW2_LOGGING "Emit the runtime's log" ON)
option(MW2_PORTABLE "Link the C++ runtime statically, for a binary that runs on other machines" OFF)
option(MW2_DIAGNOSTICS "Build the traces, dumps, statistics, reports and test harness (runtime/diagnostics.h)" ON)

# ---- which executable ------------------------------------------------------
# The disc carries two: default.xex (the campaign and special ops) and
# default_mp.xex (the multiplayer). Each is recompiled into its own tree by
# build.sh (TITLE=sp|mp), and the runtime names the title's functions through
# runtime/title.h, which this definition selects.
set(MW2_TITLE "sp" CACHE STRING "Which executable to build: sp (default.xex) or mp (default_mp.xex)")
if(MW2_TITLE STREQUAL "sp")
    set(MW2_PPC_DIR "${CMAKE_SOURCE_DIR}/ppc")
elseif(MW2_TITLE STREQUAL "mp")
    set(MW2_PPC_DIR "${CMAKE_SOURCE_DIR}/ppc_mp")
    add_compile_definitions(MW2_TITLE_MP=1)
else()
    message(FATAL_ERROR "MW2_TITLE must be sp or mp, not '${MW2_TITLE}'")
endif()
# And which version of it: the one title update 6 makes of the disc's (tu6),
# or the disc's own (tu0), recompiled into ppc_tu0/ and ppc_mp_tu0/.
# On Android the TU dimension of android/app/build.gradle.kts picks this with
# -DMW2_VERSION=tu6; tu0 is the default. TU6 trees are generated on the CI
# runner (build.sh VERSION=tu6 regenerates ppc//ppc_mp/, or ppc_tu6//ppc_mp_tu6/
# when those names are used); a tu6 configure without a TU6 tree fails below
# at the empty-tree check rather than miscompiling the disc's tree as TU6.
if(ANDROID)
    set(MW2_VERSION "tu0" CACHE STRING "Which version of the executable: tu6 (title update 6) or tu0 (the disc's)")
    if(MW2_VERSION STREQUAL "tu0")
        add_compile_definitions(MW2_VERSION_TU0=1)
        if(EXISTS "${MW2_PPC_DIR}_tu0")
            set(MW2_PPC_DIR "${MW2_PPC_DIR}_tu0")
        endif()
    elseif(MW2_VERSION STREQUAL "tu6")
        if(EXISTS "${MW2_PPC_DIR}_tu6")
            set(MW2_PPC_DIR "${MW2_PPC_DIR}_tu6")
        endif()
    else()
        message(FATAL_ERROR "MW2_VERSION must be tu6 or tu0, not '${MW2_VERSION}'")
    endif()
else()
    set(MW2_VERSION "tu6" CACHE STRING "Which version of the executable: tu6 (title update 6) or tu0 (the disc's)")
    if(MW2_VERSION STREQUAL "tu0")
        if(EXISTS "${MW2_PPC_DIR}_tu0")
            set(MW2_PPC_DIR "${MW2_PPC_DIR}_tu0")
        endif()
        add_compile_definitions(MW2_VERSION_TU0=1)
    elseif(NOT MW2_VERSION STREQUAL "tu6")
        message(FATAL_ERROR "MW2_VERSION must be tu6 or tu0, not '${MW2_VERSION}'")
    endif()
endif()

# ---- recompiled guest code -------------------------------------------------
# Guard: a TU6 tree's entry point differs from the disc's (SP 0x82370940 vs
# 0x82370938, MP 0x823A90C8 vs 0x823A7FE0), and the mapping names it. A build
# whose tree is the other version's fails here instead of miscompiling it.
if((MW2_VERSION STREQUAL "tu6" AND MW2_TITLE STREQUAL "sp") OR
   (MW2_VERSION STREQUAL "tu0" AND MW2_TITLE STREQUAL "sp" AND ANDROID))
    file(READ "${MW2_PPC_DIR}/ppc_func_mapping.cpp" _mw2_mapping)
    string(TOLOWER "${_mw2_mapping}" _mw2_mapping)
    if(MW2_VERSION STREQUAL "tu6" AND NOT _mw2_mapping MATCHES "0x82370940")
        message(FATAL_ERROR "${MW2_PPC_DIR} is not a TU6 campaign tree -- run TITLE=sp VERSION=tu6 ./build.sh first")
    elseif(MW2_VERSION STREQUAL "tu0" AND NOT _mw2_mapping MATCHES "0x82370938")
        message(FATAL_ERROR "${MW2_PPC_DIR} is not a TU0 campaign tree")
    endif()
endif()
if((MW2_VERSION STREQUAL "tu6" AND MW2_TITLE STREQUAL "mp") OR
   (MW2_VERSION STREQUAL "tu0" AND MW2_TITLE STREQUAL "mp" AND ANDROID))
    file(READ "${MW2_PPC_DIR}/ppc_func_mapping.cpp" _mw2_mapping)
    string(TOLOWER "${_mw2_mapping}" _mw2_mapping)
    if(MW2_VERSION STREQUAL "tu6" AND NOT _mw2_mapping MATCHES "0x823a90c8")
        message(FATAL_ERROR "${MW2_PPC_DIR} is not a TU6 multiplayer tree -- run TITLE=mp VERSION=tu6 ./build.sh first")
    elseif(MW2_VERSION STREQUAL "tu0" AND NOT _mw2_mapping MATCHES "0x823a7fe0")
        message(FATAL_ERROR "${MW2_PPC_DIR} is not a TU0 multiplayer tree")
    endif()
endif()
file(GLOB PPC_SOURCES CONFIGURE_DEPENDS "${MW2_PPC_DIR}/ppc_recomp.*.cpp")
list(APPEND PPC_SOURCES "${MW2_PPC_DIR}/ppc_func_mapping.cpp")
if(NOT PPC_SOURCES)
    message(FATAL_ERROR "${MW2_PPC_DIR} is empty -- run TITLE=${MW2_TITLE} VERSION=${MW2_VERSION} ./build.sh first to generate it")
endif()

add_library(ppc_recomp STATIC ${PPC_SOURCES})
set(SIMDE_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/XenonRecomp/thirdparty/simde")
if(NOT EXISTS "${SIMDE_INCLUDE_DIR}/simde/simde-common.h" AND EXISTS "${CMAKE_SOURCE_DIR}/third_party/simde/simde/simde-common.h")
    set(SIMDE_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/third_party/simde")
endif()
target_include_directories(ppc_recomp PUBLIC
    "${MW2_PPC_DIR}"
    "${SIMDE_INCLUDE_DIR}"
    "${SIMDE_INCLUDE_DIR}/simde")
# The generated code is machine output; its warnings are noise.
target_compile_options(ppc_recomp PRIVATE -w)
# The console's hardware registers are plain memory in this address space. The
# recompiler marks the stores that address them (eieio follows), and this header
# routes those through a hook so the XMA decoder sees its kick, lock and clear
# registers written. Force-included: ppc/ is regenerated by build.sh.
target_compile_options(ppc_recomp PRIVATE -include "${CMAKE_SOURCE_DIR}/runtime/mmio_hook.h")
if(NOT MW2_LOGGING)
    # Compiles every LOGI/LOGW/LOGE/LOGK call to nothing, warnings included.
    add_compile_definitions(MW2_NO_LOGGING=1)
endif()

if(MW2_TRACE_INDIRECT)
    target_compile_definitions(ppc_recomp PUBLIC MW2_TRACE_INDIRECT=1)
endif()

# ---- runtime ---------------------------------------------------------------
file(GLOB RUNTIME_SOURCES CONFIGURE_DEPENDS
     "${CMAKE_SOURCE_DIR}/runtime/*.cpp"
     "${CMAKE_SOURCE_DIR}/runtime/kernel/*.cpp"
     "${CMAKE_SOURCE_DIR}/runtime/gpu/*.cpp"
     "${CMAKE_SOURCE_DIR}/runtime/apu/*.cpp"
     "${CMAKE_SOURCE_DIR}/runtime/install/*.cpp"
     "${CMAKE_SOURCE_DIR}/runtime/gpu/vulkan/*.cpp")

if(ANDROID)
    # The window, the touch pad, the AAudio sink, the driver loader and the
    # JNI surface the app talks to (docs/android.md).
    file(GLOB ANDROID_SOURCES CONFIGURE_DEPENDS "${CMAKE_SOURCE_DIR}/runtime/android/*.cpp")
    list(APPEND RUNTIME_SOURCES ${ANDROID_SOURCES} "${CMAKE_SOURCE_DIR}/launcher/disc.cpp")
    # The title-update package reader (dependency-free STFS): the TU6 apps
    # apply the update on the device after copying the disc.
    list(APPEND RUNTIME_SOURCES "${CMAKE_SOURCE_DIR}/launcher/package.cpp")
    # XenonRecomp's patcher, which turns the disc's executables into the
    # update's. Present when the tree was recompiled on this machine (build.sh
    # clones it); absent for a bare checkout, where TU6 apps report that the
    # APK must come from CI instead of failing to link.
    set(XENON "${CMAKE_SOURCE_DIR}/XenonRecomp")
    if(EXISTS "${XENON}/XenonUtils/xex_patcher.cpp" AND EXISTS "${XENON}/XenonUtils/xex_patcher.h")
        list(APPEND RUNTIME_SOURCES
            "${XENON}/XenonUtils/xex_patcher.cpp"
            "${XENON}/XenonUtils/memory_mapped_file.cpp"
            "${XENON}/thirdparty/libmspack/libmspack/mspack/lzxd.c"
            "${XENON}/thirdparty/tiny-AES-c/aes.c")
        set(MW2_XENON_INCLUDES
            "${XENON}/XenonUtils"
            "${XENON}/thirdparty/simde"
            "${XENON}/thirdparty/libmspack/libmspack/mspack"
            "${XENON}/thirdparty/tiny-AES-c"
            "${XENON}/thirdparty/TinySHA1")
    endif()
endif()

# The glue build.sh generates from the recompiled output -- a stub for every
# kernel import the runtime lacks, a tracing hook for every D3D9 entry point --
# lives beside that output, since it is different for each title.
# ---- online service --------------------------------------------------------
# What the title's network calls reach (runtime/online/service.h): "none" keeps
# system link on this machine, "lan" is plain UDP between machines, "steam" is
# Steam, with lan behind it for when Steam is not running. A backend is the one
# file runtime/online/<name>.cpp; the runtime tries them in service.cpp's order.
set(MW2_ONLINE "none" CACHE STRING "Online service: none, lan or steam")
if(MW2_ONLINE STREQUAL "none")
    set(MW2_ONLINE_BACKENDS "")
elseif(MW2_ONLINE STREQUAL "lan")
    set(MW2_ONLINE_BACKENDS lan)
elseif(MW2_ONLINE STREQUAL "steam")
    set(MW2_ONLINE_BACKENDS steam lan)
else()
    message(FATAL_ERROR "MW2_ONLINE=${MW2_ONLINE}: none, lan or steam")
endif()
set(MW2_ONLINE_SOURCES "")
set(MW2_ONLINE_DEFINITIONS "")
foreach(backend ${MW2_ONLINE_BACKENDS})
    list(APPEND MW2_ONLINE_SOURCES "${CMAKE_SOURCE_DIR}/runtime/online/${backend}.cpp")
    string(TOUPPER "${backend}" backend_upper)
    list(APPEND MW2_ONLINE_DEFINITIONS "MW2_ONLINE_${backend_upper}=1")
endforeach()
message(STATUS "Online service: ${MW2_ONLINE}")

# On Android there is no process of ours to be the executable: the app's
# activity is the process, and this is what it loads (libmw2.so, System
# .loadLibrary("mw2"), runtime/android/jni.cpp). Everywhere else it is the
# program itself.
if(ANDROID)
    add_library(mw2 SHARED ${RUNTIME_SOURCES}
        "${CMAKE_SOURCE_DIR}/runtime/online/service.cpp"
        ${MW2_ONLINE_SOURCES}
        "${MW2_PPC_DIR}/stubs_generated.cpp")
else()
    add_executable(mw2 ${RUNTIME_SOURCES}
        "${CMAKE_SOURCE_DIR}/runtime/online/service.cpp"
        ${MW2_ONLINE_SOURCES}
        "${MW2_PPC_DIR}/stubs_generated.cpp")
endif()
target_link_libraries(mw2 PRIVATE ppc_recomp)
target_compile_definitions(mw2 PRIVATE ${MW2_ONLINE_DEFINITIONS})
if(MW2_DIAGNOSTICS)
    target_compile_definitions(mw2 PRIVATE MW2_DIAGNOSTICS=1)
else()
    target_compile_definitions(mw2 PRIVATE MW2_DIAGNOSTICS=0)
endif()
target_include_directories(mw2 PRIVATE "${CMAKE_SOURCE_DIR}/runtime")
if(MW2_XEX_SHA256_SP AND MW2_XEX_SHA256_MP)
    # CMake's regexes have no {n} repetition -- "{64}" would be matched as
    # those four characters -- so the length is counted separately.
    foreach(given SP MP)
        set(hash "${MW2_XEX_SHA256_${given}}")
        string(LENGTH "${hash}" hash_length)
        if(NOT hash_length EQUAL 64 OR NOT hash MATCHES "^[0-9a-fA-F]+$")
            message(FATAL_ERROR
                "MW2_XEX_SHA256_${given} is not a sha256 (64 hex characters, got"
                " ${hash_length}): ${hash}")
        endif()
    endforeach()
    if(NOT MW2_DISC_SHA256_SP)
        set(MW2_DISC_SHA256_SP "${MW2_XEX_SHA256_SP}")
        set(MW2_DISC_SHA256_MP "${MW2_XEX_SHA256_MP}")
    endif()
    set(MW2_HASH_DEFINITIONS
        MW2_XEX_SHA256_SP="${MW2_XEX_SHA256_SP}" MW2_XEX_SHA256_MP="${MW2_XEX_SHA256_MP}"
        MW2_DISC_SHA256_SP="${MW2_DISC_SHA256_SP}" MW2_DISC_SHA256_MP="${MW2_DISC_SHA256_MP}")
    # The TU fastfiles a TU6 install verifies its downloaded update against.
    # TU6 CI passes all three; without them a TU6 build refuses to apply the
    # update on the device (empty define) rather than trusting any bytes.
    foreach(_ff PATCH_MP DLC1_UI_MP DLC2_UI_MP)
        if(MW2_UPDATE_SHA256_${_ff})
            list(APPEND MW2_HASH_DEFINITIONS MW2_UPDATE_SHA256_${_ff}="${MW2_UPDATE_SHA256_${_ff}}")
        else()
            list(APPEND MW2_HASH_DEFINITIONS MW2_UPDATE_SHA256_${_ff}="")
        endif()
    endforeach()
    target_compile_definitions(mw2 PRIVATE ${MW2_HASH_DEFINITIONS})
    if(MW2_XENON_INCLUDES)
        target_include_directories(mw2 PRIVATE ${MW2_XENON_INCLUDES})
        target_compile_definitions(mw2 PRIVATE MW2_HAVE_XEX_PATCHER=1)
    endif()
    message(STATUS "XEX hashes given on the command line; mw2/ is not needed")
else()
    if(MW2_VERSION STREQUAL "tu0")
        set(MW2_XEX_DIR "${CMAKE_SOURCE_DIR}/mw2/tu0")
    else()
        set(MW2_XEX_DIR "${CMAKE_SOURCE_DIR}/mw2")
    endif()
    function(mw2_sha256 variable path)
        if(NOT EXISTS "${path}")
            message(FATAL_ERROR "${path} is missing -- build.sh makes it from the ISO and the title update")
        endif()
        set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${path}")
        file(SHA256 "${path}" hash)
        set(${variable} "${hash}" PARENT_SCOPE)
    endfunction()
    if(EXISTS "${MW2_XEX_DIR}/default.xex")
        mw2_sha256(MW2_XEX_SHA256_SP  "${MW2_XEX_DIR}/default.xex")
        mw2_sha256(MW2_XEX_SHA256_MP  "${MW2_XEX_DIR}/default_mp.xex")
    elseif(EXISTS "${CMAKE_SOURCE_DIR}/mw2/default.xex")
        mw2_sha256(MW2_XEX_SHA256_SP  "${CMAKE_SOURCE_DIR}/mw2/default.xex")
        mw2_sha256(MW2_XEX_SHA256_MP  "${CMAKE_SOURCE_DIR}/mw2/default_mp.xex")
    else()
        set(MW2_XEX_SHA256_SP "990e640d3a92544f9d585e71faf1ab65082d37ec6f5865b2599335fa123bf6ff")
        set(MW2_XEX_SHA256_MP "aacc47aff3221f3bd9129e80827fd3bcd74aa43bf74bb5c5ddbd0597c0d5fcde")
    endif()
    if(EXISTS "${CMAKE_SOURCE_DIR}/mw2/tu0/default.xex")
        mw2_sha256(MW2_DISC_SHA256_SP "${CMAKE_SOURCE_DIR}/mw2/tu0/default.xex")
        mw2_sha256(MW2_DISC_SHA256_MP "${CMAKE_SOURCE_DIR}/mw2/tu0/default_mp.xex")
    else()
        set(MW2_DISC_SHA256_SP "${MW2_XEX_SHA256_SP}")
        set(MW2_DISC_SHA256_MP "${MW2_XEX_SHA256_MP}")
    endif()
    set(MW2_HASH_DEFINITIONS
        MW2_XEX_SHA256_SP="${MW2_XEX_SHA256_SP}" MW2_XEX_SHA256_MP="${MW2_XEX_SHA256_MP}"
        MW2_DISC_SHA256_SP="${MW2_DISC_SHA256_SP}" MW2_DISC_SHA256_MP="${MW2_DISC_SHA256_MP}")
    if(NOT MW2_VERSION STREQUAL "tu0" AND EXISTS "${CMAKE_SOURCE_DIR}/mw2/update/patch_mp.ff")
        mw2_sha256(MW2_UPDATE_SHA256_PATCH_MP   "${CMAKE_SOURCE_DIR}/mw2/update/patch_mp.ff")
        mw2_sha256(MW2_UPDATE_SHA256_DLC1_UI_MP "${CMAKE_SOURCE_DIR}/mw2/update/dlc1_ui_mp.ff")
        mw2_sha256(MW2_UPDATE_SHA256_DLC2_UI_MP "${CMAKE_SOURCE_DIR}/mw2/update/dlc2_ui_mp.ff")
        list(APPEND MW2_HASH_DEFINITIONS
            MW2_UPDATE_SHA256_PATCH_MP="${MW2_UPDATE_SHA256_PATCH_MP}"
            MW2_UPDATE_SHA256_DLC1_UI_MP="${MW2_UPDATE_SHA256_DLC1_UI_MP}"
            MW2_UPDATE_SHA256_DLC2_UI_MP="${MW2_UPDATE_SHA256_DLC2_UI_MP}")
    endif()
    target_compile_definitions(mw2 PRIVATE ${MW2_HASH_DEFINITIONS})
endif()
if(WIN32)
    # One executable with nothing beside it: the C++ runtime and the threads
    # linked in. The recompiled code nests deep on the host stack, and a thread
    # Windows starts gets the size the executable asks for: 16 MB, where Linux
    # gives 8.
    target_link_libraries(mw2 PRIVATE ws2_32 iphlpapi winmm bcrypt)
    target_link_options(mw2 PRIVATE -static -Wl,--stack,16777216)
    # A player's build opens no console window (runtime/platform.cpp).
    if(NOT MW2_DIAGNOSTICS)
        target_link_options(mw2 PRIVATE -mwindows)
    endif()
elseif(ANDROID)
    include(cmake/android.cmake)
else()
    # -rdynamic so backtrace_symbols can resolve the sub_XXXXXXXX guest functions.
    set_target_properties(mw2 PROPERTIES ENABLE_EXPORTS ON)
    target_link_options(mw2 PRIVATE -rdynamic)
    if(MW2_PORTABLE)
        target_link_options(mw2 PRIVATE -static-libstdc++ -static-libgcc)
    endif()
endif()

if(MW2_USE_SDL)
    include(FetchContent)
    FetchContent_Declare(SDL3
        GIT_REPOSITORY https://github.com/libsdl-org/SDL.git
        GIT_TAG release-3.2.8
        GIT_SHALLOW TRUE)
    set(SDL_SHARED OFF CACHE BOOL "" FORCE)
    set(SDL_STATIC ON  CACHE BOOL "" FORCE)
    set(SDL_TEST   OFF CACHE BOOL "" FORCE)
    FetchContent_MakeAvailable(SDL3)
    target_link_libraries(mw2 PRIVATE SDL3::SDL3-static)
    target_compile_definitions(mw2 PRIVATE MW2_USE_SDL=1)
endif()

# ---- XMA decoder ----------------------------------------------------------
add_subdirectory(third_party/ffmpeg-xenia)
target_link_libraries(mw2 PRIVATE ffmpeg_xma)

# ---- Vulkan ----------------------------------------------------------------
# Loaded through the loader rather than linked to a driver, so a machine without
# a device still builds and runs; the presenter falls back to headless.
if(WIN32)
    include(cmake/vulkan-windows.cmake)
    add_dependencies(mw2 vulkan_import_library)
elseif(ANDROID)
    # The NDK's sysroot carries the headers and a libvulkan.so, but this build
    # links neither: which Vulkan the process talks to is decided while it
    # runs -- the system's, or a driver the player imported
    # (runtime/gpu/vulkan/loader.cpp, runtime/android/driver.cpp). Setting
    # this here keeps the Vulkan block below as it is.
    set(Vulkan_FOUND TRUE)
    set(Vulkan_LIBRARY "loaded at run time")
else()
    find_package(Vulkan)
endif()
if(Vulkan_FOUND)
    if(NOT ANDROID)
        target_link_libraries(mw2 PRIVATE Vulkan::Vulkan)
    endif()
    target_compile_definitions(mw2 PRIVATE MW2_HAVE_VULKAN=1)
    message(STATUS "Vulkan found: ${Vulkan_LIBRARY}")
else()
    message(STATUS "Vulkan not found -- building without a window")
endif()

if(NOT WIN32 AND NOT ANDROID)
    target_link_libraries(mw2 PRIVATE pthread)
endif()

# The two tools below are for working on the renderer, on Linux.
if(NOT ANDROID)
# ---- offline shader translation -------------------------------------------
# The translator has to live in the runtime, because the title hands the GPU
# microcode while it runs. Building it as a tool too gives a fast loop against
# captured shaders and spirv-val, without launching the game.
add_executable(translate-shader
    "${CMAKE_SOURCE_DIR}/tools/translate_shader.cpp"
    "${CMAKE_SOURCE_DIR}/runtime/gpu/vulkan/shader_translator.cpp"
    "${CMAKE_SOURCE_DIR}/runtime/gpu/vulkan/pipeline.cpp"
    "${CMAKE_SOURCE_DIR}/runtime/gpu/vulkan/spirv.cpp")
target_include_directories(translate-shader PRIVATE "${CMAKE_SOURCE_DIR}/runtime")
# --compile puts a translated module in front of the real driver, which is a
# stronger check than spirv-val: it is the compiler that would run the shader.
if(Vulkan_FOUND)
    target_link_libraries(translate-shader PRIVATE Vulkan::Vulkan)
    target_compile_definitions(translate-shader PRIVATE MW2_HAVE_VULKAN=1)
endif()

# ---- offline texture upload ------------------------------------------------
# The upload hands the driver the guest's own block bytes, so reading the image
# back returns exactly what went in. That is a test, and it needs neither the
# game nor a picture -- unlike the untiler, which needs both.
add_executable(upload-texture
    "${CMAKE_SOURCE_DIR}/tools/upload_texture.cpp"
    "${CMAKE_SOURCE_DIR}/runtime/gpu/texture.cpp"
    "${CMAKE_SOURCE_DIR}/runtime/gpu/vulkan/texture_cache.cpp"
    "${CMAKE_SOURCE_DIR}/runtime/gpu/vulkan/bc_decoder.cpp"
    "${CMAKE_SOURCE_DIR}/runtime/gpu/vulkan/image_memory.cpp"
    "${CMAKE_SOURCE_DIR}/runtime/gpu/vulkan/texture_formats.cpp"
    "${CMAKE_SOURCE_DIR}/runtime/gpu/vulkan/pipeline.cpp"
    "${CMAKE_SOURCE_DIR}/runtime/gpu/vulkan/shader_translator.cpp"
    "${CMAKE_SOURCE_DIR}/runtime/gpu/vulkan/spirv.cpp")
target_include_directories(upload-texture PRIVATE "${CMAKE_SOURCE_DIR}/runtime")
if(Vulkan_FOUND)
    target_link_libraries(upload-texture PRIVATE Vulkan::Vulkan)
    target_compile_definitions(upload-texture PRIVATE MW2_HAVE_VULKAN=1)
endif()
endif()

# ---- launcher --------------------------------------------------------------
# What a player opens (launcher/): it installs the game and starts it. One
# executable with nothing beside it, like the game's: Dear ImGui on SDL's own
# renderer, the fonts as arrays, and XenonRecomp's patcher, which applies the
# title update, compiled in from its checkout.
if(MW2_USE_SDL)
    enable_language(C)
    FetchContent_Declare(imgui
        GIT_REPOSITORY https://github.com/ocornut/imgui.git
        GIT_TAG v1.91.9b
        GIT_SHALLOW TRUE)
    FetchContent_MakeAvailable(imgui)

    # third_party/fonts/*.ttf as C arrays.
    set(MW2_FONTS_SOURCE "${CMAKE_BINARY_DIR}/launcher_fonts.cpp")
    set(fonts_text "// Generated by CMake from third_party/fonts/.\n")
    foreach(font "Menu=BarlowCondensed-Regular" "Heading=BarlowCondensed-Medium" "Body=BarlowSemiCondensed-Regular")
        string(REPLACE "=" ";" font "${font}")
        list(GET font 0 font_name)
        list(GET font 1 font_file)
        set(font_path "${CMAKE_SOURCE_DIR}/third_party/fonts/${font_file}.ttf")
        set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${font_path}")
        file(READ "${font_path}" font_hex HEX)
        string(LENGTH "${font_hex}" font_length)
        math(EXPR font_size "${font_length} / 2")
        string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," font_bytes "${font_hex}")
        string(APPEND fonts_text "extern const unsigned char kFont${font_name}[] = { ${font_bytes} };\n"
                                 "extern const unsigned kFont${font_name}Size = ${font_size};\n")
    endforeach()
    # The window's icon the same way (tools/launcher_icon.py makes it).
    set(icon_path "${CMAKE_SOURCE_DIR}/launcher/icon/launcher.bmp")
    set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${icon_path}")
    file(READ "${icon_path}" icon_hex HEX)
    string(LENGTH "${icon_hex}" icon_length)
    math(EXPR icon_size "${icon_length} / 2")
    string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," icon_bytes "${icon_hex}")
    string(APPEND fonts_text "extern const unsigned char kIcon[] = { ${icon_bytes} };\n"
                             "extern const unsigned kIconSize = ${icon_size};\n")
    file(GENERATE OUTPUT "${MW2_FONTS_SOURCE}" CONTENT "${fonts_text}")

    # The game draws its sign-in screen (runtime/signin.cpp) with the same
    # fonts, rasterised by the stb_truetype that comes with Dear ImGui.
    target_sources(mw2 PRIVATE "${MW2_FONTS_SOURCE}")
    target_include_directories(mw2 PRIVATE "${imgui_SOURCE_DIR}")
    target_compile_definitions(mw2 PRIVATE MW2_SIGNIN_PICTURE=1)

    set(XENON "${CMAKE_SOURCE_DIR}/XenonRecomp")
    file(GLOB LAUNCHER_SOURCES CONFIGURE_DEPENDS "${CMAKE_SOURCE_DIR}/launcher/*.cpp")
    add_executable(launcher ${LAUNCHER_SOURCES}
        "${MW2_FONTS_SOURCE}"
        "${CMAKE_SOURCE_DIR}/runtime/install/crypto.cpp"
        "${CMAKE_SOURCE_DIR}/runtime/install/xex.cpp"
        "${CMAKE_SOURCE_DIR}/runtime/install/spawn.cpp"
        "${imgui_SOURCE_DIR}/imgui.cpp"
        "${imgui_SOURCE_DIR}/imgui_draw.cpp"
        "${imgui_SOURCE_DIR}/imgui_tables.cpp"
        "${imgui_SOURCE_DIR}/imgui_widgets.cpp"
        "${imgui_SOURCE_DIR}/backends/imgui_impl_sdl3.cpp"
        "${imgui_SOURCE_DIR}/backends/imgui_impl_sdlrenderer3.cpp"
        "${XENON}/XenonUtils/xex_patcher.cpp"
        "${XENON}/XenonUtils/memory_mapped_file.cpp"
        "${XENON}/thirdparty/libmspack/libmspack/mspack/lzxd.c"
        "${XENON}/thirdparty/tiny-AES-c/aes.c")
    set_target_properties(launcher PROPERTIES OUTPUT_NAME mw2-launcher)
    target_include_directories(launcher PRIVATE
        "${imgui_SOURCE_DIR}" "${imgui_SOURCE_DIR}/backends"
        "${XENON}/XenonUtils" "${XENON}/thirdparty/simde"
        "${XENON}/thirdparty/libmspack/libmspack/mspack"
        "${XENON}/thirdparty/tiny-AES-c" "${XENON}/thirdparty/TinySHA1")
    target_compile_definitions(launcher PRIVATE ${MW2_HASH_DEFINITIONS} NOMINMAX)
    # What release this is, for the launcher to look for a newer one: the
    # release workflow gives the tag. A build without one does not update.
    set(MW2_RELEASE_TAG "" CACHE STRING "The release tag this build is published as, e.g. v0.3.0")
    if(WIN32)
        set(MW2_RELEASE_KIND "windows-${MW2_ONLINE}")
    else()
        set(MW2_RELEASE_KIND "linux-${MW2_ONLINE}")
    endif()
    set_source_files_properties("${CMAKE_SOURCE_DIR}/launcher/update.cpp" PROPERTIES COMPILE_DEFINITIONS
        "MW2_RELEASE_TAG=\"${MW2_RELEASE_TAG}\";MW2_RELEASE_KIND=\"${MW2_RELEASE_KIND}\"")
    # The decoder the game has for its sound, for the menu sounds (launcher/sound.cpp).
    target_link_libraries(launcher PRIVATE SDL3::SDL3-static ffmpeg_xma)
    if(WIN32)
        # The program's icon, as Explorer and the taskbar show it.
        enable_language(RC)
        target_sources(launcher PRIVATE "${CMAKE_SOURCE_DIR}/launcher/icon/launcher.rc")
        target_include_directories(launcher PRIVATE "${CMAKE_SOURCE_DIR}/launcher/compat")
        target_link_libraries(launcher PRIVATE urlmon)
        target_link_options(launcher PRIVATE -static)
        if(NOT MW2_DIAGNOSTICS)
            target_link_options(launcher PRIVATE -mwindows)
        endif()
    else()
        target_link_libraries(launcher PRIVATE pthread)
        if(MW2_PORTABLE)
            target_link_options(launcher PRIVATE -static-libstdc++ -static-libgcc)
        endif()
    endif()
endif()
