cmake_minimum_required(VERSION 3.20)

# ============================================================================
# Ninja Gaiden Black - static recompilation (xboxrecomp)
#
# Native Linux (x86-64), Windows, macOS (arm64) and Android (arm64, packaging/android) builds. The generated code comes from the
# xboxrecomp pipeline (see README.md); it is not checked in.
# ============================================================================

project(ninja_gaiden_black C CXX)
if(APPLE AND NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(arm64|aarch64)$")
    message(FATAL_ERROR "The macOS port currently supports Apple Silicon only")
endif()
if(WIN32)
    enable_language(RC)   # the program's icon (packaging/windows/ngb.rc)
endif()   # CXX: the GPU renderer links VMA

set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
    set(CMAKE_BUILD_TYPE Release CACHE STRING "" FORCE)
endif()

add_compile_definitions(WIN32_LEAN_AND_MEAN NOMINMAX)

# Bring-up build: record every indirect-branch target the title reaches, so
# tools/feedback.sh can reseed function detection with them. Applies to the
# toolkit too (its icall_feedback.c compiles to nothing without it).
option(NGB_ICALL_FEEDBACK "Record indirect-branch targets (bring-up builds)" OFF)
if(NGB_ICALL_FEEDBACK)
    add_compile_definitions(RECOMP_ICALL_FEEDBACK)
endif()

# The GPU: xemu's NV2A model with its Vulkan renderer (xboxrecomp nv2a_vk).
option(NGB_NV2A_VK "Render with the NV2A Vulkan model" ON)
set(XBOXRECOMP_NV2A_VK ${NGB_NV2A_VK} CACHE BOOL "" FORCE)
set(XBOXRECOMP_SDL_BACKENDS ON CACHE BOOL "" FORCE)   # Windows: same SDL audio/input as Linux
set(XBOXRECOMP_WIN_VCPU ON CACHE BOOL "" FORCE)        # Windows: one virtual CPU, as on Linux

# x86-64: the plain instruction set whatever CFLAGS say (a distribution's -march=native, x86-64-v3): the GPU's
# registers are read and written by faulting into a decoder of the instructions (nv2a_runtime.c mmio_emulate),
# which knows no VEX encodings -- a BMI2 shift reading a register crashed at the start (#190).
# (GCC turns -march=native into one flag a feature, which a later -march does not undo: each named off.)
if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$" AND NOT MSVC)
    add_compile_options(-march=x86-64 -mtune=generic -mno-avx -mno-bmi -mno-bmi2 -mno-popcnt -mno-lzcnt -mno-movbe
                        -mno-sse3)
    include(CheckCCompilerFlag)
    check_c_compiler_flag(-mno-apxf NGB_HAS_MNO_APXF)
    if(NGB_HAS_MNO_APXF)
        add_compile_options(-mno-apxf)
    endif()
endif()

# Optimisation: the level every target compiles at (the targets' own setting: CMake's Release -O3 comes
# before it), and profile-guided optimisation -- NGB_PGO=generate builds a binary that records where its
# time goes (LLVM_PROFILE_FILE), NGB_PGO=<file.profdata> one built with that profile (docs/TECHNICAL.md).
set(NGB_OPT_LEVEL "-O2" CACHE STRING "optimisation level for every target (-O2, -O3)")
set(NGB_PGO "" CACHE STRING "profile-guided optimisation: empty, generate, or a .profdata file")
if(NGB_PGO STREQUAL "generate")
    add_compile_options(-fprofile-instr-generate)
    add_compile_definitions(NGB_PGO_GENERATE)   # src/main.c: the profile written on SIGINT/SIGTERM
    add_link_options(-fprofile-instr-generate)
elseif(NGB_PGO)
    add_compile_options(-fprofile-instr-use=${NGB_PGO} -Wno-profile-instr-unprofiled -Wno-profile-instr-out-of-date
                        -Wno-backend-plugin)
endif()

set(XBOXRECOMP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/xboxrecomp" CACHE PATH
    "Path to the xboxrecomp toolkit root directory")
add_subdirectory(${XBOXRECOMP_DIR} ${CMAKE_BINARY_DIR}/xboxrecomp)

# ── Recompiled code ─────────────────────────────────────────────

# CONFIGURE_DEPENDS: a regenerated tree can add or drop chunks.
file(GLOB RECOMP_GEN_SOURCES CONFIGURE_DEPENDS "src/recomp/gen/*.c")
if(NOT RECOMP_GEN_SOURCES)
    message(FATAL_ERROR "src/recomp/gen is empty: run the recomp pipeline first (README.md)")
endif()

# The generated chunks are ~2 MB of C each. They are an object library so
# their flags can differ from the hand-written code, and so a host change
# never recompiles them.
# Fonts (SIL Open Font License, assets/fonts) built into the program: the
# pause menu's pages until the game's own letters are loaded and its key labels
# (src/pause_tab.c).
set(NGB_FONTS
    "EBGaramond-ExtraBoldItalic.ttf\;ngb_font_tab"
    "LiberationSerif-Regular.ttf\;ngb_font_body"
    "LiberationSerif-Bold.ttf\;ngb_font_label")
set(NGB_FONT_SOURCES)
foreach(entry ${NGB_FONTS})
    list(GET entry 0 file)
    list(GET entry 1 name)
    set(out ${CMAKE_BINARY_DIR}/fonts/${name}.c)
    add_custom_command(OUTPUT ${out}
        COMMAND ${CMAKE_COMMAND} -DIN=${CMAKE_CURRENT_SOURCE_DIR}/assets/fonts/${file}
                -DOUT=${out} -DNAME=${name} -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/embed.cmake
        DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/assets/fonts/${file}
                ${CMAKE_CURRENT_SOURCE_DIR}/cmake/embed.cmake
        VERBATIM)
    list(APPEND NGB_FONT_SOURCES ${out})
endforeach()

# The touch controls' stand-in pieces (Kenney's Mobile Controls, CC0: assets/touch/License-Kenney.txt), shown
# only when the game's own art cannot be read (src/touch_pad.c): each embedded, and a table of them by file name.
# The button prompts have no files: they are made from the game's art, or typed (src/game_prompts.c, pause_tab.c).
if(ANDROID)
    file(GLOB NGB_TOUCH_PNGS ${CMAKE_CURRENT_SOURCE_DIR}/assets/touch/*.png)
    set(touch_decls "")
    set(touch_rows "")
    list(LENGTH NGB_TOUCH_PNGS touch_count)
    foreach(png ${NGB_TOUCH_PNGS})
        get_filename_component(stem ${png} NAME_WE)
        string(MAKE_C_IDENTIFIER "ngb_png_${stem}" sym)
        set(out ${CMAKE_BINARY_DIR}/touch/${sym}.c)
        add_custom_command(OUTPUT ${out}
            COMMAND ${CMAKE_COMMAND} -DIN=${png} -DOUT=${out} -DNAME=${sym}
                    -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/embed.cmake
            DEPENDS ${png} ${CMAKE_CURRENT_SOURCE_DIR}/cmake/embed.cmake
            VERBATIM)
        list(APPEND NGB_FONT_SOURCES ${out})
        string(APPEND touch_decls "extern const unsigned char ${sym}[]; extern const unsigned int ${sym}_len;\n")
        string(APPEND touch_rows "    { \"${stem}\", ${sym}, &${sym}_len },\n")
    endforeach()
    file(WRITE ${CMAKE_BINARY_DIR}/touch/touch_table.c.in
         "/* Generated by CMakeLists.txt: the embedded touch pieces by name. */\n${touch_decls}"
         "const struct { const char *name; const unsigned char *data; const unsigned int *len; } ngb_touch_pngs[] = {\n"
         "${touch_rows}};\nconst int ngb_touch_png_count = ${touch_count};\n")
    configure_file(${CMAKE_BINARY_DIR}/touch/touch_table.c.in ${CMAKE_BINARY_DIR}/touch/touch_table.c COPYONLY)
    list(APPEND NGB_FONT_SOURCES ${CMAKE_BINARY_DIR}/touch/touch_table.c)
endif()

# The port's version, shown in the main menu's corner (src/fps_text.c): the Android manifest's versionName,
# the number each release sets.
file(STRINGS ${CMAKE_CURRENT_SOURCE_DIR}/packaging/android/AndroidManifest.xml NGB_VERSION_LINE
     REGEX "android:versionName=")
string(REGEX REPLACE ".*android:versionName=\"([^\"]+)\".*" "\\1" NGB_VERSION "${NGB_VERSION_LINE}")
set_property(SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/src/fps_text.c ${CMAKE_CURRENT_SOURCE_DIR}/src/game_prompts.c APPEND PROPERTY
             COMPILE_DEFINITIONS NGB_VERSION="${NGB_VERSION}")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
             ${CMAKE_CURRENT_SOURCE_DIR}/packaging/android/AndroidManifest.xml)

# The program's icon built in (src/app_icon.c: the window's, and Linux's desktop files), from the .ico the Windows
# program carries (tools/make_icon.py).
set(NGB_ICON_FILE ${CMAKE_CURRENT_SOURCE_DIR}/packaging/windows/ngb.ico)
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${NGB_ICON_FILE})
file(READ ${NGB_ICON_FILE} NGB_ICON_HEX HEX)
file(SIZE ${NGB_ICON_FILE} NGB_ICON_SIZE)
string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," NGB_ICON_HEX "${NGB_ICON_HEX}")
file(CONFIGURE OUTPUT ${CMAKE_BINARY_DIR}/ngb_icon_data.c CONTENT
     "#include <stdint.h>\nconst uint8_t ngb_icon_ico[] = {${NGB_ICON_HEX}};\nconst uint32_t ngb_icon_ico_size = ${NGB_ICON_SIZE};\n")

add_library(ngb_gen OBJECT ${RECOMP_GEN_SOURCES}
    ${CMAKE_BINARY_DIR}/ngb_icon_data.c
    # Hand-written replacements in the generated code's style.
    ${CMAKE_CURRENT_SOURCE_DIR}/src/movie_skip.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/costume_menu.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/pc_menu.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/pause_tab.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/game_prompts.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/app_icon.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/menu_mouse.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/menu_font.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/fps_text.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/hud.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/intercept.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/ut_charge.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/cutscene_skip.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/talisman.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/responsive.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/fiber_delete.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/kitetsu_levels.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/sound_boot.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/d3d/gpu_regs.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/render_list.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/playtime.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/save_slots.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/quick_select.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/main_menu.c
    # The Direct3D hooks (docs/renderer.md, tools/take_d3d.py).
    ${CMAKE_CURRENT_SOURCE_DIR}/src/d3d/d3d.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/cheats.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/camera.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/d3d/d3d_hooks.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/d3d/d3d_orig.c
    # The DirectSound hooks (src/audio, tools/take_dsound.py).
    ${CMAKE_CURRENT_SOURCE_DIR}/src/audio/dsound.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/audio/dsound_hooks.c
    ${CMAKE_CURRENT_SOURCE_DIR}/src/audio/dsound_orig.c
    ${NGB_FONT_SOURCES})
target_include_directories(ngb_gen PRIVATE
    ${XBOXRECOMP_DIR}/third_party/stb
    ${CMAKE_CURRENT_SOURCE_DIR}/src/recomp/gen
    ${XBOXRECOMP_DIR}/include
    ${XBOXRECOMP_DIR}/src
    ${XBOXRECOMP_DIR}/src/kernel
)
target_link_libraries(ngb_gen PRIVATE platform)
if(NGB_NV2A_VK)
    target_compile_definitions(ngb_gen PRIVATE NGB_NV2A_VK)   # (src/d3d/gpu_regs.h: the GPU model is there)
    find_package(SDL2 REQUIRED)   # SDL's key codes (src/pause_tab.c's key prompts)
    target_include_directories(ngb_gen PRIVATE $<TARGET_PROPERTY:SDL2::SDL2,INTERFACE_INCLUDE_DIRECTORIES>)
endif()

if(MSVC)
    target_compile_options(ngb_gen PRIVATE /bigobj /O2)
else()
    # The guest memory model aliases freely through MEM32/MEMF; strict
    # aliasing would let the optimiser reorder guest loads and stores.
    # Lifted code is one big function per guest routine, so the flags that
    # make a function's codegen superlinear are capped.
    target_compile_options(ngb_gen PRIVATE
        ${NGB_OPT_LEVEL} -fno-strict-aliasing -fwrapv
        -Wno-unused-label -Wno-unused-variable -Wno-unused-but-set-variable
        -Wno-parentheses-equality -Wno-tautological-compare
        -Wno-incompatible-pointer-types-discards-qualifiers
    )
endif()

# ── The Direct3D renderer (docs/renderer.md, src/d3d/NOTICE) ────

if(NGB_NV2A_VK)
    if(APPLE OR ANDROID)
        find_package(glslang CONFIG REQUIRED)
    endif()
    set(XRTP ${XBOXRECOMP_DIR}/third_party)
    add_library(ngb_d3d OBJECT
        src/d3d/hle.cpp
        src/d3d/vk/backend.cpp
        src/d3d/vk/spirv.cpp
        src/d3d/gpu/shaders.cpp
        src/d3d/gpu/vertex.cpp
        src/d3d/gpu/texture.cpp
        src/d3d/gpu/threaded.cpp)
    target_include_directories(ngb_d3d PRIVATE
        src
        src/d3d src/d3d/compat ${XBOXRECOMP_DIR}/src ${XBOXRECOMP_DIR}/src/nv2a_vk/host
        ${XRTP}/Vulkan-Headers/include ${XRTP}/volk ${XRTP}/VulkanMemoryAllocator/include)
    target_compile_definitions(ngb_d3d PRIVATE VK_NO_PROTOTYPES
        VMA_STATIC_VULKAN_FUNCTIONS=0 VMA_DYNAMIC_VULKAN_FUNCTIONS=0)
    # the virtual CPU on Windows (platform's XBOX_WIN_VCPU, without its wait wrappers): the render thread's frame
    # wait hands it over there too (src/d3d/gpu/threaded.cpp)
    if(WIN32 AND XBOXRECOMP_WIN_VCPU)
        target_compile_definitions(ngb_d3d PRIVATE XBOX_WIN_VCPU)
    endif()
    if(APPLE OR ANDROID)
        target_link_libraries(ngb_d3d PRIVATE glslang::glslang glslang::glslang-default-resource-limits)
    endif()
    target_compile_features(ngb_d3d PRIVATE cxx_std_20)
    target_compile_options(ngb_d3d PRIVATE ${NGB_OPT_LEVEL} -fno-strict-aliasing)
endif()

# ── DirectSound on a host mixer (src/audio, src/audio/NOTICE) ────

find_package(SDL2 REQUIRED)
add_library(ngb_audio OBJECT src/audio/dsound_hle.cpp)
target_include_directories(ngb_audio PRIVATE src/audio src/d3d/compat
    $<TARGET_PROPERTY:SDL2::SDL2,INTERFACE_INCLUDE_DIRECTORIES>
    ${XBOXRECOMP_DIR}/src)
target_compile_features(ngb_audio PRIVATE cxx_std_20)
target_compile_options(ngb_audio PRIVATE ${NGB_OPT_LEVEL} -fno-strict-aliasing)

# ── Executable ──────────────────────────────────────────────────

set(NGB_MAIN_SOURCES
    src/main.c
    src/recomp_manual.c
    src/fibers.c
    $<$<BOOL:${NGB_NV2A_VK}>:${CMAKE_CURRENT_SOURCE_DIR}/src/launcher.c>
    $<$<BOOL:${NGB_NV2A_VK}>:${CMAKE_CURRENT_SOURCE_DIR}/src/ingame_menu.c>
    $<$<BOOL:${NGB_NV2A_VK}>:${CMAKE_CURRENT_SOURCE_DIR}/src/quick_ui.c>
    $<$<BOOL:${NGB_NV2A_VK}>:${CMAKE_CURRENT_SOURCE_DIR}/src/keyboard.c>
    $<$<BOOL:${NGB_NV2A_VK}>:${CMAKE_CURRENT_SOURCE_DIR}/src/bindings.c>
    src/install.c
    src/launch.c
    $<$<PLATFORM_ID:Android>:${CMAKE_CURRENT_SOURCE_DIR}/src/android_main.c>
    $<$<PLATFORM_ID:Android>:${CMAKE_CURRENT_SOURCE_DIR}/src/touch_pad.c>
    $<$<PLATFORM_ID:Android>:${CMAKE_CURRENT_SOURCE_DIR}/src/android_install.c>
    $<$<PLATFORM_ID:Android>:${CMAKE_CURRENT_SOURCE_DIR}/src/android_gpu.c>
    $<TARGET_OBJECTS:ngb_gen>
    $<$<BOOL:${NGB_NV2A_VK}>:$<TARGET_OBJECTS:ngb_d3d>>
    $<TARGET_OBJECTS:ngb_audio>
    $<$<PLATFORM_ID:Windows>:${CMAKE_CURRENT_SOURCE_DIR}/packaging/windows/ngb.rc>
)
if(ANDROID)   # SDL's Java activity loads the game as libmain.so and calls its SDL_main (packaging/android)
    add_library(${PROJECT_NAME} SHARED ${NGB_MAIN_SOURCES})
else()
    add_executable(${PROJECT_NAME} ${NGB_MAIN_SOURCES})
endif()
target_link_libraries(${PROJECT_NAME} PRIVATE xboxrecomp)
if(WIN32)   # the resource script includes these: rebuilt when they change, not only ngb.rc
    set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/packaging/windows/ngb.rc PROPERTIES OBJECT_DEPENDS
        "${CMAKE_CURRENT_SOURCE_DIR}/packaging/windows/ngb.manifest;${CMAKE_CURRENT_SOURCE_DIR}/packaging/windows/ngb.ico")
endif()
if(NGB_NV2A_VK)
    target_link_libraries(${PROJECT_NAME} PRIVATE xbox_nv2a_vk)
    target_compile_definitions(${PROJECT_NAME} PRIVATE NGB_NV2A_VK)
endif()
target_include_directories(${PROJECT_NAME} PRIVATE
    ${CMAKE_CURRENT_SOURCE_DIR}/src
    ${CMAKE_CURRENT_SOURCE_DIR}/src/recomp/gen
    ${XBOXRECOMP_DIR}/include
    ${XBOXRECOMP_DIR}/src
)

if(WIN32)
    # A GUI program (no console window); main() attaches to a parent console.
    set_target_properties(${PROJECT_NAME} PROPERTIES OUTPUT_NAME NinjaGaidenBlack
                          WIN32_EXECUTABLE TRUE)
    target_link_libraries(${PROJECT_NAME} PRIVATE
        winmm dbghelp comdlg32 comctl32 shell32 ole32)
    if(MSVC)
        target_link_options(${PROJECT_NAME} PRIVATE /LARGEADDRESSAWARE)
    endif()
elseif(ANDROID)
    set_target_properties(${PROJECT_NAME} PROPERTIES OUTPUT_NAME main)
    # -Bsymbolic: the library's calls to its own functions go straight there, not through the PLT (exported, they
    # could be replaced by another library's; nothing does): 3% of the game thread on a Pixel 4a
    target_link_options(${PROJECT_NAME} PRIVATE -Wl,-Bsymbolic)
    target_link_libraries(${PROJECT_NAME} PRIVATE android log m SDL2::SDL2)
    # libadrenotools (Turnip loaded for this app: src/android_gpu.c), from packaging/android/build.sh
    find_library(NGB_ADRENOTOOLS adrenotools REQUIRED)
    find_library(NGB_LINKERNSBYPASS linkernsbypass REQUIRED)
    find_path(NGB_ADRENOTOOLS_INCLUDE adrenotools/driver.h REQUIRED)
    target_include_directories(${PROJECT_NAME} PRIVATE ${NGB_ADRENOTOOLS_INCLUDE})
    target_link_libraries(${PROJECT_NAME} PRIVATE ${NGB_ADRENOTOOLS} ${NGB_LINKERNSBYPASS})
else()
    set_target_properties(${PROJECT_NAME} PROPERTIES OUTPUT_NAME NinjaGaidenBlack)
    # -rdynamic: the crash handler names the faulting sub_XXXXXXXX via dladdr.
    target_link_options(${PROJECT_NAME} PRIVATE -rdynamic)
    target_link_libraries(${PROJECT_NAME} PRIVATE ${CMAKE_DL_LIBS} m)
endif()

# ── First-run setup window (Qt) ─────────────────────────────────
# ngb-setup asks for the player's disc and installs it (src/install.c); the
# game runs it from beside itself when it finds no game files. Optional:
# without Qt the game asks through zenity/kdialog.
# ── The arcade Ninja Gaiden the cabinet and the main menu launch (#18, src/trilogy/main.c) ──
# NinjaTrilogy.xbe is the English build, NinjaTomoe.xbe the Japanese one (the game picks it when its
# text is set to Japanese): one program each, from tools/pipeline_trilogy.sh [tomoe]. Each is built
# when its code has been generated. They draw with the GPU model's own NV2A renderer, so they need it.
# On Android each is a library beside libmain.so (libtrilogy.so, libtomoe.so) with the same start as the game's
# (src/android_main.c) and its touch controls: the app's process starts again into it (src/launch.c).

function(ngb_arcade_program target output gen_dir xbe dsound)
    file(GLOB gen_sources CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/recomp/${gen_dir}/*.c")
    if(NOT gen_sources OR NOT NGB_NV2A_VK)
        return()
    endif()
    # with its DirectSound hooks (src/audio, tools/take_dsound.py trilogy|tomoe)
    add_library(${target}_gen OBJECT ${gen_sources}
        ${CMAKE_CURRENT_SOURCE_DIR}/src/audio/dsound.c
        ${CMAKE_CURRENT_SOURCE_DIR}/src/audio/dsound_hooks_arcade.c
        ${CMAKE_CURRENT_SOURCE_DIR}/src/audio/dsound_orig_${dsound}.c)
    target_include_directories(${target}_gen PRIVATE
        ${CMAKE_CURRENT_SOURCE_DIR}/src/audio
        ${CMAKE_CURRENT_SOURCE_DIR}/src/recomp/${gen_dir}
        ${XBOXRECOMP_DIR}/include
        ${XBOXRECOMP_DIR}/src
        ${XBOXRECOMP_DIR}/src/kernel)
    target_link_libraries(${target}_gen PRIVATE platform)
    if(NGB_TRILOGY_ABI_CHECK)   # log every call that returns with ebx/esi/edi changed or the stack unbalanced
        target_compile_definitions(${target}_gen PRIVATE RECOMP_ABI_CHECK)
    endif()
    if(MSVC)
        target_compile_options(${target}_gen PRIVATE /bigobj /O2)
    else()
        target_compile_options(${target}_gen PRIVATE
            ${NGB_OPT_LEVEL} -fno-strict-aliasing -fwrapv
            -Wno-unused-label -Wno-unused-variable -Wno-unused-but-set-variable
            -Wno-parentheses-equality -Wno-tautological-compare
            -Wno-incompatible-pointer-types-discards-qualifiers)
    endif()
    set(sources
        src/trilogy/main.c
        src/launch.c
        src/recomp_manual.c
        src/fps_text.c              # Show FPS: the presenter's own letters here (no pause_tab.c)
        ${NGB_FONT_SOURCES}
        $<TARGET_OBJECTS:${target}_gen>
        $<TARGET_OBJECTS:ngb_audio>
        $<$<PLATFORM_ID:Windows>:${CMAKE_CURRENT_SOURCE_DIR}/packaging/windows/ngb.rc>)
    if(ANDROID)
        add_library(${target} SHARED ${sources} src/android_main.c src/android_gpu.c src/touch_pad.c)
    else()
        add_executable(${target} ${sources})
    endif()
    target_link_libraries(${target} PRIVATE xboxrecomp xbox_nv2a_vk)
    target_compile_definitions(${target} PRIVATE NGB_NV2A_VK TRILOGY_XBE="${xbe}")
    if(NGB_TRILOGY_ABI_CHECK)
        target_compile_definitions(${target} PRIVATE NGB_TRILOGY_ABI_CHECK)
    endif()
    target_include_directories(${target} PRIVATE
        ${CMAKE_CURRENT_SOURCE_DIR}/src
        ${CMAKE_CURRENT_SOURCE_DIR}/src/recomp/${gen_dir}
        ${XBOXRECOMP_DIR}/include
        ${XBOXRECOMP_DIR}/src
        ${XBOXRECOMP_DIR}/src/nv2a_vk/host
        ${XBOXRECOMP_DIR}/third_party/stb)
    set_target_properties(${target} PROPERTIES OUTPUT_NAME ${output})
    if(ANDROID)   # (as libmain.so, above)
        string(TOLOWER ${gen_dir} lib)
        string(REPLACE "gen_" "" lib ${lib})
        set_target_properties(${target} PROPERTIES OUTPUT_NAME ${lib})
        target_link_options(${target} PRIVATE -Wl,-Bsymbolic)
        target_include_directories(${target} PRIVATE ${NGB_ADRENOTOOLS_INCLUDE})
        target_link_libraries(${target} PRIVATE android log m SDL2::SDL2 ${NGB_ADRENOTOOLS} ${NGB_LINKERNSBYPASS})
    elseif(WIN32)
        set_target_properties(${target} PROPERTIES WIN32_EXECUTABLE TRUE)
        target_link_libraries(${target} PRIVATE winmm dbghelp shell32 ole32)
    else()
        target_link_libraries(${target} PRIVATE ${CMAKE_DL_LIBS} m)
    endif()
    message(STATUS "${output}: ${CMAKE_CURRENT_SOURCE_DIR}/src/recomp/${gen_dir}")
endfunction()
ngb_arcade_program(ninja_trilogy NinjaTrilogy gen_trilogy NinjaTrilogy.xbe trilogy)
ngb_arcade_program(ninja_tomoe NinjaTomoe gen_tomoe NinjaTomoe.xbe tomoe)

if(NOT WIN32 AND NOT ANDROID)
    find_package(Qt6 QUIET COMPONENTS Widgets)
    if(Qt6_FOUND)
        set(CMAKE_AUTORCC ON)
        add_executable(ngb-setup src/setup/ngb_setup.cpp src/setup/setup.qrc src/install.c)
        target_link_libraries(ngb-setup PRIVATE Qt6::Widgets)
        set_target_properties(ngb-setup PROPERTIES CXX_STANDARD 17
            RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
        message(STATUS "ngb-setup: Qt ${Qt6_VERSION}")
    else()
        message(STATUS "ngb-setup: no Qt6 Widgets, not built")
    endif()
endif()
