cmake_minimum_required(VERSION 4.2)
project(burnout2 VERSION 1.14.0 LANGUAGES C CXX)

if((NOT WIN32 AND NOT APPLE AND NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") OR NOT CMAKE_SIZEOF_VOID_P EQUAL 8 OR
   (NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(AMD64|amd64|x86_64)$" AND NOT (APPLE AND CMAKE_SYSTEM_PROCESSOR MATCHES "^(arm64|aarch64)$")))
    message(FATAL_ERROR "Supported platforms are Windows x64, Linux x86-64 and macOS Intel/Apple Silicon.")
endif()
set(b2_portable_default OFF)
if(APPLE AND CMAKE_SYSTEM_PROCESSOR MATCHES "^(arm64|aarch64)$")
    set(b2_portable_default ON)
endif()
option(B2_PORTABLE_CPU "Use native C++ instruction helpers for ARM (also available for x86 validation)" ${b2_portable_default})
if(b2_portable_default AND NOT B2_PORTABLE_CPU)
    message(FATAL_ERROR "Apple Silicon requires the portable native instruction helpers.")
endif()
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_SCAN_FOR_MODULES OFF)
option(B2_PROFILE_GENERATE "Collect LLVM profiles for native game optimization" OFF)
option(B2_AVX2 "Build native code for an AVX2-capable CPU and operating system" OFF)
set(B2_LINK_JOBS 6 CACHE STRING "Maximum parallel LLVM link optimization jobs")
if(NOT B2_LINK_JOBS MATCHES "^[1-9][0-9]*$")
    message(FATAL_ERROR "B2_LINK_JOBS must be a positive integer.")
endif()
set(B2_PROFILE_USE "" CACHE FILEPATH "LLVM indexed profile for native game optimization")
if(B2_PROFILE_GENERATE AND B2_PROFILE_USE)
    message(FATAL_ERROR "Choose profile collection or profile use, not both.")
endif()
if((B2_PROFILE_GENERATE OR B2_PROFILE_USE) AND NOT CMAKE_CXX_COMPILER_ID MATCHES "^(Clang|AppleClang)$")
    message(FATAL_ERROR "Native profiling requires the Clang toolchain.")
endif()
if(B2_PROFILE_USE AND NOT EXISTS "${B2_PROFILE_USE}")
    message(FATAL_ERROR "B2_PROFILE_USE must name an existing llvm-profdata indexed profile.")
endif()
include(CheckIPOSupported)
check_ipo_supported(RESULT b2_ipo_supported LANGUAGES CXX)
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
    "${CMAKE_CURRENT_SOURCE_DIR}/knowledge/supported_target.json"
    "${CMAKE_CURRENT_SOURCE_DIR}/knowledge/facts.json")

file(READ "${CMAKE_CURRENT_SOURCE_DIR}/knowledge/supported_target.json" target_json)
foreach(field IN ITEMS target_id file_size file_sha256)
    string(JSON B2_${field} GET "${target_json}" targets 0 ${field})
endforeach()

configure_file(cmake/target.h.in generated/target.h @ONLY)
file(READ "${CMAKE_CURRENT_SOURCE_DIR}/knowledge/facts.json" facts_json)
string(JSON kernel_name_count LENGTH "${facts_json}" executable KERNEL_EXPORT_NAMES value items)
math(EXPR kernel_name_last "${kernel_name_count} - 1")
set(kernel_names "")
foreach(index RANGE ${kernel_name_last})
    string(JSON ordinal GET "${facts_json}" executable KERNEL_EXPORT_NAMES value items ${index} 0)
    string(JSON name GET "${facts_json}" executable KERNEL_EXPORT_NAMES value items ${index} 1)
    string(APPEND kernel_names "    case ${ordinal}: return \"${name}\";\n")
endforeach()
configure_file(cmake/kernel_names.h.in generated/kernel_names.h @ONLY)

include(FetchContent)
set(ZYDIS_BUILD_TOOLS OFF CACHE BOOL "" FORCE)
set(ZYDIS_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
set(ZYDIS_BUILD_DOXYGEN OFF CACHE BOOL "" FORCE)
set(ZYDIS_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(ZYDIS_BUILD_SHARED_LIB OFF CACHE BOOL "" FORCE)
set(ZYDIS_FEATURE_ENCODER OFF CACHE BOOL "" FORCE)
FetchContent_Declare(zydis
    GIT_REPOSITORY https://github.com/zyantific/zydis.git
    GIT_TAG a2278f1d254e492f6a6b39f6cb5d1f5d515659dc
    GIT_SUBMODULES dependencies/zycore
    GIT_PROGRESS FALSE)
FetchContent_MakeAvailable(zydis)

# Bounded Lua mod sandbox. Original game code remains compiled ahead of time.
FetchContent_Declare(b2_lua
    URL https://www.lua.org/ftp/lua-5.4.9.tar.gz
    URL_HASH SHA256=2335b6c582a52654f94612bf10d2f4672805d05329aa6568b1d8cd9e5c6fb8e6
    DOWNLOAD_EXTRACT_TIMESTAMP FALSE)
FetchContent_MakeAvailable(b2_lua)
set(lua_sources "")
foreach(name IN ITEMS lapi lcode lctype ldebug ldo ldump lfunc lgc llex lmem lobject lopcodes lparser lstate lstring ltable ltm lundump lvm lzio lauxlib lbaselib lmathlib)
    list(APPEND lua_sources "${b2_lua_SOURCE_DIR}/src/${name}.c")
endforeach()
add_library(b2-lua STATIC ${lua_sources})
target_include_directories(b2-lua PUBLIC "${b2_lua_SOURCE_DIR}/src")
if(NOT WIN32)
    target_link_libraries(b2-lua PRIVATE m)
endif()

add_library(b2-core STATIC src/file.cpp src/disc.cpp src/mods.cpp src/mod_scripts.cpp src/xbe.cpp src/assets.cpp src/tracks.cpp src/effects.cpp src/crypto.cpp src/performance.cpp src/achievements.cpp)
target_link_libraries(b2-core PRIVATE b2-lua)
target_include_directories(b2-core PUBLIC src PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/generated")
if(WIN32)
    target_sources(b2-core PRIVATE src/diagnostics.cpp src/host_windows.cpp)
    target_link_libraries(b2-core PRIVATE bcrypt iphlpapi)
    target_compile_definitions(b2-core PUBLIC WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE)
else()
    if(APPLE)
        include(cmake/macos.cmake)
    else()
        include(cmake/linux.cmake)
    endif()
    target_sources(b2-core PRIVATE src/host_posix.cpp src/diagnostics_posix.cpp)
    target_link_libraries(b2-core PUBLIC b2-platform)
    if(APPLE)
        enable_language(ASM)
        target_sources(b2-core PRIVATE src/fiber_context.S)
    endif()
    if(B2_PORTABLE_CPU)
        include(cmake/portable-cpu.cmake)
        target_link_libraries(b2-core PUBLIC b2-portable-cpu)
    endif()
endif()

add_library(b2-graphics STATIC src/render.cpp src/render_checks.cpp src/texture_packs.cpp src/vertex_program.cpp src/shaders.cpp src/gpu.cpp src/frame_processing.cpp src/antialiasing.cpp src/ambient_occlusion.cpp src/hdr.cpp src/ui_art.cpp)
target_link_libraries(b2-graphics PUBLIC b2-core)
if(WIN32)
    target_link_libraries(b2-graphics PRIVATE d3d11 dxgi windowscodecs ole32)
else()
    target_link_libraries(b2-graphics PRIVATE b2-d3d11 PNG::PNG JPEG::JPEG)
    if(APPLE)
        target_sources(b2-graphics PRIVATE src/metal.m)
        set_source_files_properties(src/metal.m PROPERTIES COMPILE_OPTIONS "-fobjc-arc")
        target_link_libraries(b2-graphics PRIVATE "-framework Foundation" "-framework Metal")
    endif()
endif()

add_executable(b2-tool src/tool.cpp src/decoder.cpp src/recompiler.cpp src/batch.cpp src/dsp_compiler.cpp src/shader_compiler.cpp)
target_include_directories(b2-tool PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/generated")
target_link_libraries(b2-tool PRIVATE b2-core b2-graphics Zydis)
if(WIN32)
    target_link_libraries(b2-tool PRIVATE d3dcompiler)
else()
    target_link_libraries(b2-tool PRIVATE b2-hlsl)
endif()
add_custom_command(TARGET b2-tool POST_BUILD
    COMMAND "${CMAKE_COMMAND}" -E copy_if_different
        "${CMAKE_CURRENT_SOURCE_DIR}/THIRD_PARTY_NOTICES.txt" "$<TARGET_FILE_DIR:b2-tool>/THIRD_PARTY_NOTICES.txt"
    VERBATIM)

set(B2_XBE "" CACHE FILEPATH "Verified local executable for native CPU diagnostics")
if(B2_XBE)
    if(NOT EXISTS "${B2_XBE}")
        message(FATAL_ERROR "B2_XBE does not exist; extract default.xbe with b2-tool first.")
    endif()
    if(WIN32)
    enable_language(ASM_MASM RC)
    if(CMAKE_GENERATOR MATCHES "^Ninja")
        # Use relative assembly inputs; MASM still uses legacy path encoding.
        set(CMAKE_ASM_MASM_COMPILE_OBJECT "<CMAKE_ASM_MASM_COMPILER> <DEFINES> <INCLUDES> /c /Fo<OBJECT> <FLAGS>")
    endif()
    # MASM uses legacy path encoding; relative inputs also work in Unicode folders.
    foreach(assembly IN ITEMS src/cpu_floating.asm src/cpu_reference.asm)
        file(RELATIVE_PATH assembly_input "${CMAKE_CURRENT_BINARY_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/${assembly}")
        set_source_files_properties("${assembly}" PROPERTIES VS_SETTINGS
            "CommandLineTemplate=ml64.exe /c [AllOptions] [AdditionalOptions] /Ta\"${assembly_input}\"")
        if(CMAKE_GENERATOR MATCHES "^Ninja")
            set_source_files_properties("${assembly}" PROPERTIES COMPILE_OPTIONS "/Ta${assembly_input}")
        endif()
    endforeach()
    set(b2_floating_assembly src/cpu_floating.asm)
    set(b2_reference_assembly src/cpu_reference.asm)
    set(b2_generated_assembly .asm)
    else()
        enable_language(ASM)
        set(b2_floating_assembly src/cpu_floating.S)
        set(b2_reference_assembly src/cpu_reference.S)
        set(b2_generated_assembly .S)
    endif()
    set(b2_batch_options "")
    if(B2_PORTABLE_CPU)
        set(b2_floating_assembly "")
        set(b2_generated_assembly .helpers.cpp)
        set(b2_batch_options --portable)
    endif()
    if(APPLE AND CMAKE_SYSTEM_PROCESSOR MATCHES "^(arm64|aarch64)$")
        set(b2_reference_assembly "")
    endif()
    foreach(option IN ITEMS SDL_SHARED SDL_TEST_LIBRARY SDL_TESTS SDL_EXAMPLES SDL_INSTALL SDL_GPU SDL_RENDER SDL_OPENGL SDL_OPENGLES SDL_VULKAN)
        set(${option} OFF CACHE BOOL "" FORCE)
    endforeach()
    if(WIN32)
        set(SDL_STATIC ON CACHE BOOL "" FORCE)
    else()
        # DXVK's SDL3 WSI and the application must use the same SDL instance.
        set(SDL_STATIC OFF CACHE BOOL "" FORCE)
        set(SDL_SHARED ON CACHE BOOL "" FORCE)
        if(APPLE)
            set(SDL_METAL ON CACHE BOOL "" FORCE)
        else()
            set(SDL_VULKAN ON CACHE BOOL "" FORCE)
        endif()
    endif()
    FetchContent_Declare(sdl3
        URL https://github.com/libsdl-org/SDL/archive/829a65d769d935c4852f8159e964312c0957260a.tar.gz
        URL_HASH SHA256=48E15CF1A6928453D77AFA955D1FDFBBCA9169E2BC3D76D111ACB9B8BB076D66
        DOWNLOAD_EXTRACT_TIMESTAMP FALSE)
    FetchContent_MakeAvailable(sdl3)
    if(NOT WIN32)
        if(NOT TARGET SDL3::SDL3-static)
            add_library(SDL3::SDL3-static ALIAS SDL3-shared)
        endif()
        target_link_libraries(b2-graphics PRIVATE SDL3::SDL3-shared)
    endif()
    # Keep non-ASCII installation paths out of CMake's ANSI-encoded MSVC PCH header.
    if(WIN32)
        set_property(TARGET SDL3-static PROPERTY PRECOMPILE_HEADERS "<SDL_internal.h>")
    endif()
    FetchContent_Declare(imgui
        URL https://github.com/ocornut/imgui/archive/c1aaac65e896a45f81f47a4d68f9959e0f86c859.tar.gz
        URL_HASH SHA256=B3D8F99838BB3FF05E14185562345F85E00C032DA4D8FC277608D7898D847114
        DOWNLOAD_EXTRACT_TIMESTAMP FALSE)
    FetchContent_MakeAvailable(imgui)
    include(cmake/imgui-shaders.cmake)
    add_library(b2-ui STATIC
        "${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" "${CMAKE_CURRENT_BINARY_DIR}/generated/imgui_impl_dx11.cpp")
    target_include_directories(b2-ui PUBLIC "${imgui_SOURCE_DIR}" "${imgui_SOURCE_DIR}/backends")
    target_include_directories(b2-ui PRIVATE src)
    target_link_libraries(b2-ui PRIVATE SDL3::SDL3-static b2-core)
    if(WIN32)
        target_link_libraries(b2-ui PRIVATE d3d11)
    else()
        target_link_libraries(b2-ui PRIVATE b2-d3d11)
    endif()
    add_library(b2-input STATIC src/input.cpp src/audio.cpp src/custom_music.cpp)
    target_include_directories(b2-input PUBLIC src)
    target_link_libraries(b2-input PRIVATE SDL3::SDL3-static b2-core)
    if(WIN32)
        target_link_libraries(b2-input PRIVATE mfplat mfreadwrite mf mfuuid ole32 delayimp)
        target_link_options(b2-input INTERFACE /DELAYLOAD:mfplat.dll /DELAYLOAD:mfreadwrite.dll /DELAYLOAD:mf.dll)
    endif()
    add_library(b2-cpu STATIC src/cpu.cpp src/presentation.cpp src/xbox.cpp src/floating.cpp ${b2_floating_assembly})
    target_include_directories(b2-cpu PUBLIC src)
    target_link_libraries(b2-cpu PUBLIC b2-core PRIVATE b2-input b2-graphics)
    if(WIN32)
        target_link_libraries(b2-cpu PRIVATE iphlpapi)
    endif()
    set(B2_EFFECTS "${CMAKE_CURRENT_SOURCE_DIR}/data/local/b2distfx.bin" CACHE FILEPATH "Local Xbox audio effects image")
    if(NOT EXISTS "${B2_EFFECTS}")
        message(FATAL_ERROR "B2_EFFECTS is missing; use b2-tool extract ISO data/b2distfx.bin OUTPUT first.")
    endif()
    set(native_effects "${CMAKE_CURRENT_BINARY_DIR}/generated/$<CONFIG>/native_effects.cpp")
    add_custom_command(OUTPUT "${native_effects}"
        COMMAND b2-tool compile-effects "${B2_EFFECTS}" "${native_effects}" --replace
        DEPENDS b2-tool "${B2_EFFECTS}"
        VERBATIM)
    target_sources(b2-cpu PRIVATE src/dsp.cpp src/spatial.cpp "${native_effects}")
    set(B2_DISCORD_APPLICATION_ID "1566600235583807578" CACHE STRING "Discord Rich Presence application ID")
    if(B2_DISCORD_APPLICATION_ID AND NOT B2_DISCORD_APPLICATION_ID MATCHES "^[0-9]+$")
        message(FATAL_ERROR "B2_DISCORD_APPLICATION_ID must contain decimal digits only.")
    endif()
    add_library(b2-app STATIC src/app.cpp src/discord.cpp)
    target_compile_definitions(b2-app PRIVATE B2_DISCORD_APPLICATION_ID="${B2_DISCORD_APPLICATION_ID}")
    target_link_libraries(b2-app PRIVATE b2-core b2-graphics b2-cpu b2-ui SDL3::SDL3-static)
    if(WIN32)
        target_link_libraries(b2-app PRIVATE comdlg32)
    else()
        if(NOT APPLE)
            find_package(Fontconfig REQUIRED)
            target_link_libraries(b2-app PRIVATE Fontconfig::Fontconfig)
        endif()
        configure_file(resources/b2.png "${CMAKE_CURRENT_BINARY_DIR}/resources/b2.png" COPYONLY)
        configure_file(resources/achievement-unlocked.wav "${CMAKE_CURRENT_BINARY_DIR}/resources/achievement-unlocked.wav" COPYONLY)
    endif()
    string(JSON finite_address GET "${facts_json}" title TITLE_FLOAT_FINITE_CHECK_ADDRESS value)
    string(JSON compare_address GET "${facts_json}" title TITLE_FIXED_WIDTH_COMPARE_ADDRESS value)
    string(JSON main_loop_address GET "${facts_json}" title TITLE_MAIN_LOOP_ENTRY_ADDRESS value)
    target_compile_definitions(b2-cpu PRIVATE B2_MAIN_ADDRESS=${main_loop_address})
    string(JSON constructor_start GET "${facts_json}" title TITLE_CRT_CONSTRUCTOR_TABLE_START_ADDRESS value)
    string(JSON constructor_end GET "${facts_json}" title TITLE_CRT_CONSTRUCTOR_TABLE_END_ADDRESS value)
    string(JSON pair_count LENGTH "${facts_json}" title PHASE7_FUNCTION_PAIR_TABLE value)
    math(EXPR last_pair "${pair_count} - 1")
    set(startup_pair_seeds "")
    foreach(pair RANGE ${last_pair})
        foreach(slot RANGE 1)
            string(JSON pair_address GET "${facts_json}" title PHASE7_FUNCTION_PAIR_TABLE value ${pair} ${slot})
            string(APPEND startup_pair_seeds "${pair_address}\n")
        endforeach()
    endforeach()
    set(startup_table_seeds "")
    string(JSON title_fact_count LENGTH "${facts_json}" title)
    math(EXPR title_fact_last "${title_fact_count} - 1")
    foreach(index RANGE ${title_fact_last})
        string(JSON field MEMBER "${facts_json}" title ${index})
        if(field MATCHES "^PHASE7_.*_VTABLE_ENTRIES$")
            string(REGEX REPLACE "_ENTRIES$" "" table_field "${field}")
            string(JSON table_address GET "${facts_json}" title ${table_field} value)
            string(JSON table_count LENGTH "${facts_json}" title ${field} value)
            math(EXPR table_end "${table_address} + ${table_count} * 4")
            # The native generator reads and validates the original file-backed entries.
            string(APPEND startup_table_seeds "table ${table_address} ${table_end}\n")
        elseif(field STREQUAL "PHASE7_LEVEL_LOAD_MANAGER_VTABLES")
            string(JSON table_rows LENGTH "${facts_json}" title ${field} value)
            math(EXPR table_last "${table_rows} - 1")
            foreach(row RANGE ${table_last})
                string(JSON table_address GET "${facts_json}" title ${field} value ${row} 0)
                string(JSON table_count LENGTH "${facts_json}" title ${field} value ${row} 1)
                math(EXPR table_end "${table_address} + ${table_count} * 4")
                string(APPEND startup_table_seeds "table ${table_address} ${table_end}\n")
            endforeach()
        elseif(field STREQUAL "PHASE7_CAPTURED_VTABLE_SLOT_BINDINGS")
            string(JSON binding_rows LENGTH "${facts_json}" title ${field} value items)
            math(EXPR binding_last "${binding_rows} - 1")
            foreach(row RANGE ${binding_last})
                string(JSON binding_count LENGTH "${facts_json}" title ${field} value items ${row} 1)
                math(EXPR binding_end "${binding_count} - 1")
                foreach(binding RANGE ${binding_end})
                    string(JSON slot_address GET "${facts_json}" title ${field} value items ${row} 1 ${binding} 0)
                    math(EXPR slot_end "${slot_address} + 4")
                    string(APPEND startup_table_seeds "table ${slot_address} ${slot_end}\n")
                endforeach()
            endforeach()
        endif()
    endforeach()
    configure_file(cmake/cpu-seeds.txt.in generated/cpu-seeds.txt @ONLY)
    set(native_cpu "${CMAKE_CURRENT_BINARY_DIR}/generated/$<CONFIG>/native_cpu.cpp")
    # MASM does not create nested object directories on a fresh Visual Studio build.
    foreach(config IN LISTS CMAKE_CONFIGURATION_TYPES)
        set_source_files_properties("${CMAKE_CURRENT_BINARY_DIR}/generated/${config}/native_cpu.cpp.asm"
            PROPERTIES OBJECT_NAME native_cpu_assembly VS_SETTINGS
            "CommandLineTemplate=ml64.exe /c [AllOptions] [AdditionalOptions] /Ta\"generated/${config}/native_cpu.cpp.asm\"")
        if(CMAKE_GENERATOR MATCHES "^Ninja")
            set_source_files_properties("${CMAKE_CURRENT_BINARY_DIR}/generated/${config}/native_cpu.cpp.asm"
                PROPERTIES COMPILE_OPTIONS "/Tagenerated/${config}/native_cpu.cpp.asm")
        endif()
    endforeach()
    set(native_shards "")
    foreach(index RANGE 0 511)
        if(index LESS 10)
            set(suffix "0${index}")
        else()
            set(suffix "${index}")
        endif()
        list(APPEND native_shards "${native_cpu}.${suffix}.cpp")
    endforeach()
    set(native_stamp "${native_cpu}.stamp")
    add_custom_command(OUTPUT "${native_stamp}"
        BYPRODUCTS "${native_cpu}" "${native_cpu}${b2_generated_assembly}" "${native_cpu}.h" "${native_cpu}.json" ${native_shards}
        COMMAND b2-tool batch "${B2_XBE}" "${CMAKE_CURRENT_BINARY_DIR}/generated/cpu-seeds.txt"
            65536 4096 "${native_cpu}" --replace --allow-partial ${b2_batch_options} --shards 512 --report "${native_cpu}.json"
        COMMAND "${CMAKE_COMMAND}" -E touch "${native_stamp}"
        DEPENDS b2-tool "${B2_XBE}" "${CMAKE_CURRENT_BINARY_DIR}/generated/cpu-seeds.txt"
        VERBATIM)
    add_custom_target(b2-native-generated DEPENDS "${native_stamp}")
    set(native_shaders "${CMAKE_CURRENT_BINARY_DIR}/generated/$<CONFIG>/native_shaders.cpp")
    # The generator preserves unchanged source timestamps; stamp completed work.
    set(native_shader_stamp "${native_shaders}.stamp")
    # COMMAND orders the tool build. Only shader-generation inputs invalidate
    # its output; changes to the shared renderer do not require recompiling HLSL.
    add_custom_command(OUTPUT "${native_shader_stamp}"
        BYPRODUCTS "${native_shaders}"
        COMMAND b2-tool compile-shaders "${B2_XBE}" "${native_shaders}" --replace
        COMMAND "${CMAKE_COMMAND}" -E touch "${native_shader_stamp}"
        DEPENDS "${B2_XBE}" "${CMAKE_CURRENT_BINARY_DIR}/generated/gui_shaders.h"
            ${b2_shader_compiler_inputs}
            "${CMAKE_CURRENT_BINARY_DIR}/generated/target.h"
            "${CMAKE_CURRENT_BINARY_DIR}/generated/kernel_names.h"
            src/file.h src/xbe.h src/shaders.h src/vertex_program.h src/ambient_occlusion.h
            src/tool.cpp src/shader_compiler.cpp src/shaders.cpp src/ambient_occlusion.cpp src/vertex_program.cpp src/xbe.cpp src/file.cpp
        VERBATIM)
    add_custom_target(b2-shaders-generated DEPENDS "${native_shader_stamp}")
    add_executable(b2 WIN32 src/main.cpp src/cpu_checks.cpp src/prediction_checks.cpp ${b2_reference_assembly} "${native_cpu}" "${native_cpu}${b2_generated_assembly}" ${native_shards} "${native_shaders}")
    # Keep the same argc/argv diagnostics entry without allocating a console.
    if(WIN32)
        target_sources(b2 PRIVATE resources/b2.rc resources/b2.manifest)
        target_link_options(b2 PRIVATE /ENTRY:mainCRTStartup)
    else()
        if(APPLE)
            set_target_properties(b2 b2-tool PROPERTIES BUILD_RPATH "@loader_path")
        else()
            set_target_properties(b2 b2-tool PROPERTIES BUILD_RPATH "$ORIGIN;${b2_dxvk_library_dir}")
        endif()
        add_custom_command(TARGET b2 POST_BUILD COMMAND "${CMAKE_COMMAND}" -E copy_directory
            "${CMAKE_CURRENT_BINARY_DIR}/resources" "$<TARGET_FILE_DIR:b2>/resources")
    endif()
    # Share the CPU header across all shards without embedding installation paths.
    target_precompile_headers(b2 PRIVATE "$<$<COMPILE_LANGUAGE:CXX>:<cpu.h$<ANGLE-R>>")
    # File-specific object paths split /MP batches; schedule them through two
    # shared compiler workers instead of starting each compilation in sequence.
    set_target_properties(b2 PROPERTIES
        VS_GLOBAL_UseMultiToolTask true
        VS_GLOBAL_EnableClServerMode true
        VS_GLOBAL_EnforceProcessCountAcrossBuilds true
        VS_GLOBAL_MultiProcMaxCount 2)
    target_include_directories(b2 PRIVATE "$<$<COMPILE_LANGUAGE:RC>:${CMAKE_CURRENT_SOURCE_DIR}/resources>")
    add_dependencies(b2 b2-native-generated b2-shaders-generated)
    target_link_libraries(b2 PRIVATE b2-core b2-graphics b2-cpu b2-app SDL3::SDL3-static)
    target_compile_definitions(b2 PRIVATE B2_FINITE_ADDRESS=${finite_address} B2_COMPARE_ADDRESS=${compare_address})
else()
    file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/generated/gui_shaders.h"
        "#pragma once\n#include <string_view>\nnamespace b2 {inline constexpr std::string_view gui_vertex_source{},gui_pixel_source{};}\n")
endif()

foreach(target IN ITEMS b2-core b2-portable-cpu b2-cpu b2-input b2-graphics b2-app b2-tool b2)
    if(NOT TARGET ${target})
        continue()
    endif()
    if(MSVC)
        target_compile_options(${target} PRIVATE "$<$<COMPILE_LANGUAGE:CXX>:/W4;/permissive-;/Zc:__cplusplus;/utf-8>")
        if(B2_AVX2 AND NOT b2_portable_default)
            target_compile_options(${target} PRIVATE "$<$<AND:$<CONFIG:Release>,$<COMPILE_LANGUAGE:CXX>>:/arch:AVX2>")
        endif()
        if(target STREQUAL "b2")
            if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
                target_compile_options(${target} PRIVATE "$<$<COMPILE_LANGUAGE:CXX>:/MP2>")
            endif()
            target_link_options(${target} PRIVATE "$<$<CONFIG:Release>:/DEBUG:FULL;/OPT:REF;/OPT:ICF>")
        endif()
    endif()
    if(WIN32 AND CMAKE_CXX_COMPILER_ID STREQUAL "Clang" AND CMAKE_LINKER_TYPE STREQUAL "LLD" AND
       target MATCHES "^b2(-tool)?$")
        target_link_options(${target} PRIVATE
            "$<$<CONFIG:Release>:/opt:lldlto=3>"
            "$<$<CONFIG:Release>:/opt:lldltojobs=${B2_LINK_JOBS}>"
            "$<$<CONFIG:Release>:/threads:${B2_LINK_JOBS}>"
            "$<$<CONFIG:Release>:/lldltocache:lto-cache/${target}/Release>"
            "$<$<CONFIG:Release>:/lldltocachepolicy:cache_size_bytes=3g>")
    endif()
    if(NOT WIN32)
        target_compile_options(${target} PRIVATE "$<$<COMPILE_LANGUAGE:CXX>:-fms-extensions;-Wno-ignored-attributes>")
        if(B2_AVX2 AND NOT b2_portable_default)
            target_compile_options(${target} PRIVATE "$<$<AND:$<CONFIG:Release>,$<COMPILE_LANGUAGE:CXX>>:-mavx2>")
        endif()
        if(NOT APPLE AND CMAKE_CXX_COMPILER_ID STREQUAL "Clang" AND CMAKE_LINKER_TYPE STREQUAL "LLD" AND target MATCHES "^b2(-tool)?$")
            target_link_options(${target} PRIVATE
                "$<$<CONFIG:Release>:LINKER:--thinlto-jobs=${B2_LINK_JOBS}>"
                "$<$<CONFIG:Release>:LINKER:--thinlto-cache-dir=lto-cache/${target}/Release>"
                "$<$<CONFIG:Release>:LINKER:--thinlto-cache-policy=cache_size_bytes=3g>")
        endif()
    endif()
endforeach()

if(B2_PROFILE_GENERATE OR B2_PROFILE_USE)
    if(B2_PROFILE_GENERATE)
        if(WIN32)
        set(b2_profile_option "/clang:-fprofile-generate=${CMAKE_CURRENT_BINARY_DIR}/pgo")
        execute_process(COMMAND "${CMAKE_CXX_COMPILER}" -print-resource-dir
            OUTPUT_VARIABLE b2_clang_resources OUTPUT_STRIP_TRAILING_WHITESPACE COMMAND_ERROR_IS_FATAL ANY)
        if(NOT EXISTS "${b2_clang_resources}/lib/windows/clang_rt.profile-x86_64.lib")
            message(FATAL_ERROR "Clang's x64 profile runtime is missing.")
        endif()
        foreach(target IN ITEMS b2 b2-tool)
            if(TARGET ${target})
                target_link_directories(${target} PRIVATE "${b2_clang_resources}/lib/windows")
            endif()
        endforeach()
        else()
            set(b2_profile_option "-fprofile-generate=${CMAKE_CURRENT_BINARY_DIR}/pgo")
            foreach(target IN ITEMS b2 b2-tool)
                if(TARGET ${target})
                    target_link_options(${target} PRIVATE "$<$<CONFIG:Release>:${b2_profile_option}>")
                endif()
            endforeach()
        endif()
    else()
        if(WIN32)
            set(b2_profile_option "/clang:-fprofile-use=${B2_PROFILE_USE}")
        else()
            set(b2_profile_option "-fprofile-use=${B2_PROFILE_USE}")
        endif()
    endif()
    foreach(target IN ITEMS b2-core b2-portable-cpu b2-cpu b2-input b2-graphics b2-app b2-tool b2)
        if(TARGET ${target})
            target_compile_options(${target} PRIVATE "$<$<AND:$<CONFIG:Release>,$<COMPILE_LANGUAGE:CXX>>:${b2_profile_option}>")
        endif()
    endforeach()
endif()

if(b2_ipo_supported)
    foreach(target IN ITEMS b2-core b2-portable-cpu b2-cpu b2-input b2-graphics b2-app b2-tool b2)
        if(TARGET ${target})
            set_property(TARGET ${target} PROPERTY INTERPROCEDURAL_OPTIMIZATION_RELEASE TRUE)
        endif()
    endforeach()
endif()
