cmake_minimum_required(VERSION 3.25)
# A static library on the link line once, where the linker rescans archives
# (Apple's, which warns of each repeat, and Windows'), keeping the first.
foreach(POLICY_ID CMP0156 CMP0179)
    if(POLICY ${POLICY_ID})
        cmake_policy(SET ${POLICY_ID} NEW)
    endif()
endforeach()

# Else the build machine's macOS, which locks out every older one. MoltenVK's
# own floor.
set(CMAKE_OSX_DEPLOYMENT_TARGET "12.0" CACHE STRING "Oldest macOS the game runs on")

project(GHClassic LANGUAGES C CXX)
# SDL's Cocoa backend is Objective-C, and a subproject cannot enable it.
if(APPLE)
    enable_language(OBJC)
endif()

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# Output of ps2_recomp, written by scripts/build.sh. The target below only
# exists once it is populated, so a fresh tree can configure and build the
# tools first.
set(GHC_GENERATED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/build/recomp/output"
    CACHE PATH "Directory holding the recompiler's generated C++")

# Relinking 12k functions with LTO costs about 90s. Off while iterating.
option(GHC_ENABLE_LTO "Link-time optimisation for release builds" ON)

# Runtime only. The analyzer and recompiler are host tools, built by
# scripts/build.sh as a top-level build of lib/PS2Recomp, which their CMake
# assumes.
set(PS2X_BUILD_RECOMP OFF CACHE BOOL "" FORCE)
set(PS2X_BUILD_ANALYZER OFF CACHE BOOL "" FORCE)
set(PS2X_BUILD_TEST OFF CACHE BOOL "" FORCE)
set(PS2X_BUILD_STUDIO OFF CACHE BOOL "" FORCE)
set(PS2X_ENABLE_DEBUG_UI OFF CACHE BOOL "" FORCE)
# Movies decode through libmpeg2 (below), so no FFmpeg to find or ship.
set(PS2X_ENABLE_FFMPEG OFF CACHE BOOL "" FORCE)

# The runtime's logs are on upstream. With them on, song select misses a
# press every run. Off unless asked for with -D.
set(PS2X_ENABLE_RUNTIME_LOGS OFF CACHE BOOL "")
set(PS2X_ENABLE_AGRESSIVE_LOGS OFF CACHE BOOL "")
set(PS2X_ENABLE_IOP_RPC_TRACE OFF CACHE BOOL "")

# A dev unit's 128MB rather than retail's 32MB. GH2 sizes its own heaps and
# leaves the rest to libc, so the extra room keeps later additions out of
# the out-of-memory paths retail runs close to.
set(PS2X_EE_RAM_MB 128 CACHE STRING "" FORCE)

# The runtime reads .chd images when chdr-static exists, so libchdr comes
# first. EXCLUDE_FROM_ALL builds only the static library it links.
set(CHDR_WANT_TESTS OFF CACHE BOOL "" FORCE)
# Its miniz also deflates save.bin, so it keeps the compressor.
set(MINIZ_DEFLATE_APIS ON CACHE BOOL "" FORCE)
add_subdirectory(lib/libchdr EXCLUDE_FROM_ALL)
target_include_directories(miniz INTERFACE lib/libchdr/deps/miniz-3.1.2)

# EXCLUDE_FROM_ALL keeps upstream's own ps2EntryRunner out of the default
# build, leaving GHClassic and what it links.
add_subdirectory(lib/PS2Recomp EXCLUDE_FROM_ALL)

# The runtime and the generated code use SSE4.1 intrinsics (_mm_extract_epi32),
# which x86_64 compilers other than MSVC leave off by default. Here, so the
# runtime builds without generated code too (CI).
if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$" AND NOT MSVC)
    set(GHC_X86_FLAGS -msse4.1)
    target_compile_options(ps2_runtime PRIVATE ${GHC_X86_FLAGS})
endif()

set(PS2X_RUNTIME_DIR "${CMAKE_CURRENT_SOURCE_DIR}/lib/PS2Recomp/ps2xRuntime")

# The host: SDL3 for the window, Vulkan (MoltenVK on macOS) for the picture.
# All fetched at pinned versions, so every platform builds the same libraries
# and nothing comes from the system. Vulkan is never linked: SDL loads the
# driver's loader (MoltenVK on macOS) and volk resolves the calls from it.
include(FetchContent)
set(SDL_SHARED OFF CACHE BOOL "" FORCE)
set(SDL_STATIC ON CACHE BOOL "" FORCE)
set(SDL_TEST_LIBRARY OFF CACHE BOOL "" FORCE)
set(VOLK_PULL_IN_VULKAN OFF CACHE BOOL "" FORCE)
set(ENABLE_OPT OFF CACHE BOOL "" FORCE)
set(ENABLE_HLSL OFF CACHE BOOL "" FORCE)
set(GLSLANG_TESTS OFF CACHE BOOL "" FORCE)
set(GLSLANG_ENABLE_INSTALL OFF CACHE BOOL "" FORCE)
# SYSTEM: their headers' warnings are not ours to fix.
FetchContent_Declare(SDL3
    GIT_REPOSITORY https://github.com/libsdl-org/SDL.git
    GIT_TAG release-3.4.16
    GIT_SHALLOW TRUE
    SYSTEM)
FetchContent_Declare(VulkanHeaders
    GIT_REPOSITORY https://github.com/KhronosGroup/Vulkan-Headers.git
    GIT_TAG v1.4.357
    GIT_SHALLOW TRUE
    SYSTEM)
FetchContent_Declare(volk
    GIT_REPOSITORY https://github.com/zeux/volk.git
    GIT_TAG vulkan-sdk-1.4.357.0
    GIT_SHALLOW TRUE
    SYSTEM)
FetchContent_Declare(vk-bootstrap
    GIT_REPOSITORY https://github.com/charles-lunarg/vk-bootstrap.git
    GIT_TAG v1.4.357
    SYSTEM)
FetchContent_Declare(VulkanMemoryAllocator
    GIT_REPOSITORY https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator.git
    GIT_TAG v3.4.0
    SYSTEM)
FetchContent_Declare(glslang
    GIT_REPOSITORY https://github.com/KhronosGroup/glslang.git
    GIT_TAG 16.6.0
    GIT_SHALLOW TRUE
    SYSTEM)
# Headers first: vk-bootstrap and volk take Vulkan::Headers when it exists.
FetchContent_MakeAvailable(VulkanHeaders)
FetchContent_MakeAvailable(SDL3 volk vk-bootstrap VulkanMemoryAllocator glslang)
target_link_libraries(volk PUBLIC Vulkan::Headers)
if(APPLE)
    FetchContent_Declare(MoltenVK
        URL https://github.com/KhronosGroup/MoltenVK/releases/download/v1.4.2/MoltenVK-macos.tar
        URL_HASH SHA256=f95765a6229cb7b915990a2890ce12ebe36a730b021545d3d52ae69ce4c4024e)
    FetchContent_MakeAvailable(MoltenVK)
endif()

# MPEG-2 video for the movies: libmpeg2 (GPL-2.0-or-later), its portable C
# only, with no CPU detection or assembly. Upstream builds with autotools, so
# it is built here; the commit is 0.5.1 plus fixes, past the last tag.
FetchContent_Declare(libmpeg2
    GIT_REPOSITORY https://code.videolan.org/videolan/libmpeg2.git
    GIT_TAG 946bf4b518aacc224f845e73708f99e394744499)
FetchContent_MakeAvailable(libmpeg2)
file(CONFIGURE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/libmpeg2/config.h"
    CONTENT "#define ATTRIBUTE_ALIGNED_MAX 64\n#define HAVE_BUILTIN_EXPECT 1\n")
add_library(mpeg2 STATIC)
foreach(MPEG2_SOURCE alloc cpu_accel cpu_state decode header idct motion_comp slice)
    target_sources(mpeg2 PRIVATE "${libmpeg2_SOURCE_DIR}/libmpeg2/${MPEG2_SOURCE}.c")
endforeach()
target_include_directories(mpeg2 SYSTEM PUBLIC "${libmpeg2_SOURCE_DIR}/include")
target_include_directories(mpeg2 PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/libmpeg2")
set_target_properties(mpeg2 PROPERTIES C_STANDARD 99)

# The save code's round trips, which need no disc and no game.
add_executable(save_test EXCLUDE_FROM_ALL
    tests/save_test.cpp
    src/save/gh2_stream.cpp
    src/save/gh2_text.cpp
    src/save/ps2_card.cpp
    src/save/store.cpp
)
target_include_directories(save_test PRIVATE src)
target_link_libraries(save_test PRIVATE miniz)

# Which release the game offers as an update.
add_executable(releases_test EXCLUDE_FROM_ALL tests/releases_test.cpp src/host/releases.cpp)
target_include_directories(releases_test PRIVATE src)

# Ogg Vorbis for 360 GH2's .mogg audio: libogg and libvorbis (BSD-3-Clause),
# the decoder and vorbisfile only. Their own CMake wants an older CMake and
# an installed Ogg, so their sources are built here (the lists in their
# CMakeLists.txt); SOURCE_SUBDIR names no CMakeLists.txt, so MakeAvailable
# only fetches. raylib's bundled stb_vorbis rules that one out: its symbols
# would clash.
FetchContent_Declare(ogg
    GIT_REPOSITORY https://github.com/xiph/ogg.git
    GIT_TAG e1774cd77f471443541596e09078e78fdc342e4f # v1.3.5
    SOURCE_SUBDIR none)
FetchContent_Declare(vorbis
    GIT_REPOSITORY https://github.com/xiph/vorbis.git
    GIT_TAG 0657aee69dec8508a0011f47f3b69d7538e9d262 # v1.3.7
    SOURCE_SUBDIR none)
FetchContent_MakeAvailable(ogg vorbis)
file(CONFIGURE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/ogg/ogg/config_types.h"
    CONTENT "#ifndef __CONFIG_TYPES_H__\n#define __CONFIG_TYPES_H__\n#include <stdint.h>\n\
typedef int16_t ogg_int16_t;\ntypedef uint16_t ogg_uint16_t;\ntypedef int32_t ogg_int32_t;\n\
typedef uint32_t ogg_uint32_t;\ntypedef int64_t ogg_int64_t;\ntypedef uint64_t ogg_uint64_t;\n#endif\n")
add_library(vorbisfile STATIC)
target_sources(vorbisfile PRIVATE "${ogg_SOURCE_DIR}/src/bitwise.c" "${ogg_SOURCE_DIR}/src/framing.c")
foreach(VORBIS_SOURCE mdct smallft block envelope window lsp lpc analysis synthesis psy info floor1 floor0
        res0 mapping0 registry codebook sharedbook lookup bitrate vorbisfile)
    target_sources(vorbisfile PRIVATE "${vorbis_SOURCE_DIR}/lib/${VORBIS_SOURCE}.c")
endforeach()
target_include_directories(vorbisfile SYSTEM PUBLIC
    "${ogg_SOURCE_DIR}/include" "${CMAKE_CURRENT_BINARY_DIR}/ogg" "${vorbis_SOURCE_DIR}/include")
target_include_directories(vorbisfile PRIVATE "${vorbis_SOURCE_DIR}/lib")
set_target_properties(vorbisfile PROPERTIES C_STANDARD 99)

# Without a disc's generated code, everything above still builds: what CI
# checks (tools/ghc.py ci).
file(GLOB GHC_GENERATED_SOURCES CONFIGURE_DEPENDS
    "${GHC_GENERATED_DIR}/*.cpp"
)
if(NOT GHC_GENERATED_SOURCES)
    message(STATUS "No generated code in ${GHC_GENERATED_DIR}; GHClassic target skipped")
    return()
endif()

# The game layer: GH2's hooks, installed through the runtime's override
# registry, and the host window and renderer they draw through.
set(GHC_GAME_SOURCES
    src/main.cpp
    src/build_info.cpp
    src/game.cpp
    src/frame_step.cpp
    src/lefty_guitarist.cpp
    src/note_speed.cpp
    src/script.cpp
    src/sustain_release.cpp
    src/track_start.cpp
    src/whammy_hold.cpp
    src/worker.cpp
    src/content/band.cpp
    src/content/campaigns.cpp
    src/content/card.cpp
    src/content/crowd_cards.cpp
    src/content/focus.cpp
    src/content/floor_spot.cpp
    src/content/encores.cpp
    src/content/quickplay.cpp
    src/content/games.cpp
    src/content/heaps.cpp
    src/content/locale.cpp
    src/content/mogg.cpp
    src/content/hidden_guitars.cpp
    src/content/outfits.cpp
    src/content/payouts.cpp
    src/content/setlists.cpp
    src/content/songs.cpp
    src/content/status_line.cpp
    src/content/tour_or_higher.cpp
    src/dev/cheats.cpp
    src/dev/draw_dump.cpp
    src/dev/mesh_packet.cpp
    src/dev/null_rnd.cpp
    src/dev/scenario.cpp
    src/dev/seed.cpp
    src/dev/timing.cpp
    src/dev/transplant.cpp
    src/disc/ark.cpp
    src/disc/crypt.cpp
    src/disc/disc.cpp
    src/disc/sha1.cpp
    src/disc/volume.cpp
    src/formats/bitmap.cpp
    src/formats/dtb.cpp
    src/formats/dtb_text.cpp
    src/formats/dxt.cpp
    src/formats/midi.cpp
    src/gh1/band.cpp
    src/gh1/cameras.cpp
    src/gh1/career.cpp
    src/gh1/clip_set.cpp
    src/gh1/clips.cpp
    src/gh1/crowd.cpp
    src/gh1/face.cpp
    src/gh1/guitars.cpp
    src/gh1/install.cpp
    src/gh1/look.cpp
    src/gh1/menu_scripts.cpp
    src/gh1/menus.cpp
    src/gh1/rig.cpp
    src/gh1/scene.cpp
    src/gh1/screen.cpp
    src/gh1/screen_gh2.cpp
    src/gh1/screen_objects.cpp
    src/gh1/screen_pictures.cpp
    src/gh1/screen_widgets.cpp
    src/gh1/screens.cpp
    src/gh1/scripts.cpp
    src/gh1/sound.cpp
    src/gh1/songs.cpp
    src/gh1/venue_scene.cpp
    src/gh1/venues.cpp
    src/gh2x/classes.cpp
    src/gh2x/focus.cpp
    src/gh2x/install.cpp
    src/gh2x/models.cpp
    src/gh2x/scene.cpp
    src/gh2x/shadows.cpp
    src/gh2x/textures.cpp
    src/gh2x/track.cpp
    src/gh80s/install.cpp
    src/milo/milo.cpp
    src/milo/objects.cpp
    src/movie/movie.cpp
    src/movie/pss.cpp
    src/movie/screen.cpp
    src/save/card.cpp
    src/save/gh1_stream.cpp
    src/save/gh2_stream.cpp
    src/save/gh2_text.cpp
    src/save/ps2_card.cpp
    src/save/save.cpp
    src/save/store.cpp
    src/settings/latency.cpp
    src/settings/settings.cpp
    src/settings/video_options.cpp
    src/streak/counter.cpp
    src/streak/counter_motion.cpp
    src/streak/counter_scene.cpp
    src/streak/note_streak.cpp
    src/synth/module.cpp
    src/synth/reverb.cpp
    src/synth/spu.cpp
    src/synth/synth.cpp
    src/ui/fast_boot.cpp
    src/ui/locale.cpp
    src/ui/help_bar.cpp
    src/ui/menus.cpp
    src/ui/meta_music.cpp
    src/ui/photo_mode.cpp
    src/ui/slider_scale.cpp
    src/host/audio.cpp
    src/host/bind.cpp
    src/host/bindings.cpp
    src/host/input.cpp
    src/host/pad.cpp
    src/host/perf.cpp
    src/host/profiles.cpp
    src/host/record.cpp
    src/host/releases.cpp
    src/host/update.cpp
    src/host/vulkan_frontend.cpp
    src/host/vma.cpp
    src/host/scene_renderer.cpp
    src/render/camera.cpp
    src/render/frame.cpp
    src/render/look.cpp
    src/render/char_lod.cpp
    src/render/font_bake.cpp
    src/render/mesh_capture.cpp
    src/render/native_cull.cpp
    src/render/native_environ.cpp
    src/render/native_mat.cpp
    src/render/native_mesh.cpp
    src/render/native_particles.cpp
    src/render/native_points.cpp
    src/render/native_rect.cpp
    src/render/native_rnd.cpp
    src/render/texture_capture.cpp
    src/render/texture_store.cpp
    src/render/vector_fonts.cpp
)

add_executable(GHClassic
    ${GHC_GENERATED_SOURCES}
    ${GHC_GAME_SOURCES}
)

# Shaders compile to SPIR-V headers, each a uint32_t array named after it
# (mesh.vert -> kMeshVert in mesh_vert.h).
set(GHC_SHADER_DIR "${CMAKE_CURRENT_BINARY_DIR}/shaders")
file(MAKE_DIRECTORY "${GHC_SHADER_DIR}")
set(GHC_SHADER_HEADERS)
foreach(SHADER mesh.vert mesh.frag x360.vert x360.frag post.vert post.frag motion.vert motion.frag)
    string(REPLACE "." "_" SHADER_ID "${SHADER}")
    string(REPLACE "." ";" SHADER_PARTS "${SHADER}")
    set(SHADER_VAR "k")
    foreach(PART ${SHADER_PARTS})
        string(SUBSTRING "${PART}" 0 1 FIRST)
        string(SUBSTRING "${PART}" 1 -1 REST)
        string(TOUPPER "${FIRST}" FIRST)
        string(APPEND SHADER_VAR "${FIRST}${REST}")
    endforeach()
    set(SHADER_HEADER "${GHC_SHADER_DIR}/${SHADER_ID}.h")
    add_custom_command(
        OUTPUT "${SHADER_HEADER}"
        COMMAND glslang-standalone -V --vn "${SHADER_VAR}" -o "${SHADER_HEADER}"
                "${CMAKE_CURRENT_SOURCE_DIR}/src/host/shaders/${SHADER}"
        DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/host/shaders/${SHADER}" glslang-standalone
        VERBATIM)
    list(APPEND GHC_SHADER_HEADERS "${SHADER_HEADER}")
endforeach()
# post.frag again, reading a multisampled depth buffer (kPostMsFrag).
add_custom_command(
    OUTPUT "${GHC_SHADER_DIR}/post_ms_frag.h"
    COMMAND glslang-standalone -V -DMULTISAMPLED --vn kPostMsFrag -o "${GHC_SHADER_DIR}/post_ms_frag.h"
            "${CMAKE_CURRENT_SOURCE_DIR}/src/host/shaders/post.frag"
    DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/host/shaders/post.frag" glslang-standalone
    VERBATIM)
list(APPEND GHC_SHADER_HEADERS "${GHC_SHADER_DIR}/post_ms_frag.h")
add_custom_target(GHClassic_shaders DEPENDS ${GHC_SHADER_HEADERS})
add_dependencies(GHClassic GHClassic_shaders)
target_include_directories(GHClassic PRIVATE "${GHC_SHADER_DIR}")

# The port's own game scripts, compiled in as strings (dta.h); editing one
# reconfigures.
set(GHC_DTA_DIR "${CMAKE_CURRENT_BINARY_DIR}/dta")
file(READ src/ui/dta/lag_panel.dta GHC_LAG_PANEL_DTA)
file(READ src/ui/dta/highscore_panel.dta GHC_HIGHSCORE_PANEL_DTA)
file(READ src/ui/dta/main_menu.dta GHC_MAIN_MENU_DTA)
file(READ src/ui/dta/fast_boot.dta GHC_FAST_BOOT_DTA)
file(READ src/ui/dta/locale.dta GHC_LOCALE_DTA)
file(READ src/ui/dta/crowd.dta GHC_CROWD_DTA)
file(READ src/ui/dta/sel_character.dta GHC_SEL_CHARACTER_DTA)
file(READ src/ui/dta/quickplay.dta GHC_QUICKPLAY_DTA)
file(READ src/ui/dta/campaigns.dta GHC_CAMPAIGNS_DTA)
file(READ src/gh1/menus.dta GHC_GH1_MENUS_DTA)
file(READ src/gh1/scripts.dta GHC_GH1_SCRIPTS_DTA)
file(READ src/content/guitar_copy.dta GHC_GUITAR_COPY_DTA)
file(READ src/ui/dta/picker.dta GHC_PICKER_DTA)
file(READ src/ui/dta/quickplay_pickers.dta GHC_QUICKPLAY_PICKERS_DTA)
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
    src/ui/dta/lag_panel.dta src/ui/dta/highscore_panel.dta src/ui/dta/main_menu.dta src/ui/dta/fast_boot.dta
    src/ui/dta/locale.dta src/ui/dta/crowd.dta src/ui/dta/sel_character.dta src/ui/dta/quickplay.dta
    src/ui/dta/campaigns.dta src/gh1/menus.dta src/gh1/scripts.dta src/ui/dta/picker.dta src/ui/dta/quickplay_pickers.dta
    src/content/guitar_copy.dta src/ui/dta/game_settings.dta src/ui/dta/photo_mode.dta src/ui/dta/box.dta
    src/ui/dta/note_streak.dta src/ui/dta/streak_counter.dta)
file(READ src/ui/dta/box.dta GHC_BOX_DTA)
file(READ src/ui/dta/note_streak.dta GHC_NOTE_STREAK_DTA)
file(READ src/ui/dta/streak_counter.dta GHC_STREAK_COUNTER_DTA)
file(READ src/ui/dta/game_settings.dta GHC_GAME_SETTINGS_DTA)
file(READ src/ui/dta/photo_mode.dta GHC_PHOTO_MODE_DTA)
configure_file(src/ui/dta/dta.h.in "${GHC_DTA_DIR}/dta.h" @ONLY)
file(READ config/settings.template.ini GHC_SETTINGS_TEMPLATE)
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS config/settings.template.ini)
configure_file(src/settings/settings_template.h.in "${GHC_DTA_DIR}/settings_template.h" @ONLY)
# The old Flying V layout's texel table (gh1/guitars.h), as a byte array.
file(READ src/gh1/flyingv_old_layout.bin GHC_FLYINGV_OLD_LAYOUT HEX)
string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," GHC_FLYINGV_OLD_LAYOUT "${GHC_FLYINGV_OLD_LAYOUT}")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS src/gh1/flyingv_old_layout.bin)
configure_file(src/gh1/flyingv_old_layout.h.in "${GHC_DTA_DIR}/flyingv_old_layout.h" @ONLY)
# The vector fonts text is drawn from (render/vector_fonts.h), tools/fontpack.py's pack.
file(READ fonts/vector_fonts.bin GHC_VECTOR_FONTS_PACK HEX)
string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," GHC_VECTOR_FONTS_PACK "${GHC_VECTOR_FONTS_PACK}")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS fonts/vector_fonts.bin)
configure_file(src/render/vector_fonts_pack.h.in "${GHC_DTA_DIR}/vector_fonts_pack.h" @ONLY)
target_include_directories(GHClassic PRIVATE "${GHC_DTA_DIR}")

# What the build is (src/build_info.h), from tools/ghc.py: the tag it was made
# from, whether that is the experimental track's, and when it was configured.
set(GHC_VERSION "dev" CACHE STRING "The release this build is")
string(TIMESTAMP GHC_BUILT "%Y-%m-%d %H:%M")
option(GHC_EXPERIMENTAL "The experimental track: its own name, saves and settings" OFF)
set(GHC_EXPERIMENTAL_VALUE 0)
set(GHC_BUNDLE_NAME "GH Classic")
set(GHC_BUNDLE_ID com.noahbaxter.ghclassic)
if(GHC_EXPERIMENTAL)
    set(GHC_EXPERIMENTAL_VALUE 1)
    set(GHC_BUNDLE_NAME "GH Classic Experimental")
    set(GHC_BUNDLE_ID com.noahbaxter.ghclassic.experimental)
endif()
set_source_files_properties(src/build_info.cpp PROPERTIES
    COMPILE_DEFINITIONS "GHC_VERSION=\"${GHC_VERSION}\";GHC_BUILT=\"${GHC_BUILT}\";GHC_EXPERIMENTAL=${GHC_EXPERIMENTAL_VALUE}")

# Every supported release in config/executables.toml (role engine or
# content) as {game, serial} for content/games.cpp, a PS2 serial as
# SYSTEM.CNF boots it (SLUS-21224 is SLUS_212.24); editing it reconfigures.
file(STRINGS config/executables.toml GHC_TOML_LINES)
set(GHC_RELEASES "")
set(GHC_RELEASE_KIND "")
foreach(LINE IN LISTS GHC_TOML_LINES ITEMS "[[end]]")
    if(LINE MATCHES "^\\[\\[(.*)\\]\\]$")
        set(GHC_NEXT_KIND "${CMAKE_MATCH_1}")
        if(GHC_RELEASE_KIND STREQUAL "release" AND GHC_RELEASE_ROLE MATCHES "^(engine|content)$")
            string(REGEX REPLACE "^([A-Z]+)-([0-9][0-9][0-9])([0-9][0-9])$" "\\1_\\2.\\3"
                GHC_RELEASE_SERIAL "${GHC_RELEASE_SERIAL}")
            string(APPEND GHC_RELEASES "    {\"${GHC_RELEASE_GAME}\", \"${GHC_RELEASE_SERIAL}\"},\n")
        endif()
        set(GHC_RELEASE_KIND "${GHC_NEXT_KIND}")
        set(GHC_RELEASE_GAME "")
        set(GHC_RELEASE_SERIAL "")
        set(GHC_RELEASE_ROLE "")
    elseif(LINE MATCHES "^(game|serial|role) = \"(.*)\"$")
        string(TOUPPER "${CMAKE_MATCH_1}" GHC_FIELD)
        if(GHC_FIELD STREQUAL "GAME")
            set(GHC_RELEASE_GAME "${CMAKE_MATCH_2}")
        elseif(GHC_FIELD STREQUAL "SERIAL")
            set(GHC_RELEASE_SERIAL "${CMAKE_MATCH_2}")
        else()
            set(GHC_RELEASE_ROLE "${CMAKE_MATCH_2}")
        endif()
    endif()
endforeach()
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS config/executables.toml)
file(CONFIGURE OUTPUT "${GHC_DTA_DIR}/releases.inc" CONTENT "${GHC_RELEASES}")

# The window icons, where SDL_GetBasePath finds them. On macOS the game is an
# app bundle, so other apps (Finder, audio mixers) see its icon too, and the
# base path is the bundle's Resources.
if(APPLE)
    # MoltenVK rides in the bundle, where vulkan_frontend.cpp points SDL.
    set(GHC_MOLTENVK "${moltenvk_SOURCE_DIR}/MoltenVK/dynamic/dylib/macOS/libMoltenVK.dylib")
    target_sources(GHClassic PRIVATE assets/icon.icns assets/icon_macos.png "${GHC_MOLTENVK}")
    set_source_files_properties(assets/icon.icns assets/icon_macos.png
        PROPERTIES MACOSX_PACKAGE_LOCATION Resources)
    set_source_files_properties("${GHC_MOLTENVK}" PROPERTIES MACOSX_PACKAGE_LOCATION Frameworks)
    set_target_properties(GHClassic PROPERTIES
        MACOSX_BUNDLE TRUE
        MACOSX_BUNDLE_BUNDLE_NAME "${GHC_BUNDLE_NAME}"
        MACOSX_BUNDLE_GUI_IDENTIFIER ${GHC_BUNDLE_ID}
        MACOSX_BUNDLE_ICON_FILE icon.icns)
else()
    configure_file(assets/icon.png "${CMAKE_CURRENT_BINARY_DIR}/icon.png" COPYONLY)
endif()

# Unity batches are for the generated code; game files stay separate units.
set_source_files_properties(${GHC_GAME_SOURCES} PROPERTIES SKIP_UNITY_BUILD_INCLUSION ON)

# miniz comes with libchdr; its target leaves out its own include path.
target_include_directories(GHClassic PRIVATE "${GHC_GENERATED_DIR}" src lib/libchdr/deps/miniz-3.1.2)
target_link_libraries(GHClassic PRIVATE
    miniz
    ps2_runtime
    SDL3::SDL3
    volk::volk
    vk-bootstrap::vk-bootstrap
    GPUOpen::VulkanMemoryAllocator
    mpeg2
    vorbisfile
    miniz # libchdr's, for save.bin
)
# Calls go through volk's pointers, never a linked loader.
target_compile_definitions(GHClassic PRIVATE VK_NO_PROTOTYPES)

# The game runs the executable off the player's disc, which must be the one
# the generated code came from (disc/disc.cpp).
set(GHC_RETAIL_ELF "${GHC_GENERATED_DIR}/../retail.elf" CACHE FILEPATH "The ELF the generated code came from")
if(NOT EXISTS "${GHC_RETAIL_ELF}")
    message(FATAL_ERROR "No ${GHC_RETAIL_ELF}; run tools/ghc.py build")
endif()
file(SHA1 "${GHC_RETAIL_ELF}" GHC_RETAIL_SHA1)
target_compile_definitions(GHClassic PRIVATE GHC_RETAIL_SHA1="${GHC_RETAIL_SHA1}")

# Upstream sets its platform setup (sse2neon on ARM) at directory scope, so it
# reaches only targets inside lib/PS2Recomp. Generated code needs it too.
foreach(PROP INCLUDE_DIRECTORIES COMPILE_DEFINITIONS COMPILE_OPTIONS)
    get_property(PS2X_DIR_${PROP} DIRECTORY lib/PS2Recomp PROPERTY ${PROP})
endforeach()
target_include_directories(GHClassic PRIVATE ${PS2X_DIR_INCLUDE_DIRECTORIES})
target_compile_definitions(GHClassic PRIVATE ${PS2X_DIR_COMPILE_DEFINITIONS})
target_compile_options(GHClassic PRIVATE ${PS2X_DIR_COMPILE_OPTIONS})

target_compile_options(GHClassic PRIVATE ${GHC_X86_FLAGS})
# Unity batches outgrow COFF's 32k sections. A static runtime leaves the exe
# needing nothing of llvm-mingw's beside it, and -mwindows no console window
# beside the game's (output goes to GHClassic.log, main.cpp).
if(MINGW)
    target_compile_options(GHClassic PRIVATE -Wa,-mbig-obj)
    target_link_options(GHClassic PRIVATE -static -mwindows)
endif()
# The C++ runtime linked in, so the release (built on Ubuntu 22.04) asks a
# distro for glibc no newer than 2.35 and nothing of its libstdc++.
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
    target_link_options(GHClassic PRIVATE -static-libstdc++ -static-libgcc)
endif()

# Same batching and precompiled headers upstream uses for its runner. Without
# them a cold build of the generated code takes several times longer.
set_target_properties(GHClassic PROPERTIES
    UNITY_BUILD ON
    UNITY_BUILD_BATCH_SIZE 32
)
target_precompile_headers(GHClassic PRIVATE
    "${PS2X_RUNTIME_DIR}/include/ps2_runtime_macros.h"
    "${PS2X_RUNTIME_DIR}/include/ps2_runtime.h"
    "${GHC_GENERATED_DIR}/ps2_recompiled_functions.h"
    "${GHC_GENERATED_DIR}/ps2_recompiled_stubs.h"
    "${PS2X_RUNTIME_DIR}/include/ps2_syscalls.h"
    "${PS2X_RUNTIME_DIR}/include/ps2_stubs.h"
)

if(GHC_ENABLE_LTO AND CMAKE_BUILD_TYPE STREQUAL "Release")
    # EnableFastReleaseMode reads IPO_SUPPORTED, which upstream sets only in
    # its own directory scope. Without this check LTO is silently skipped.
    include(CheckIPOSupported)
    check_ipo_supported(RESULT IPO_SUPPORTED LANGUAGES CXX)
    EnableFastReleaseMode(GHClassic)
endif()
