# The checks `ctest` runs: the durable write, the log's repeat counting, the
# software block-compressed decoder and the DemonWare lobby stand-in. They are
# defined in a project of their own
# so they can be configured on a tree that cannot build the runtime -- the root
# CMakeLists refuses to configure without the recompiled guest code, which is
# made from the disc's executables and is in no repository, so a CI runner has
# none of it (.github/workflows/tests.yml). The root includes this same file,
# so a local `ctest` runs exactly what CI runs:
#
#   cmake -S tests -B build-tests -G Ninja
#   ctest --test-dir build-tests --output-on-failure
#
# Nothing here needs a disc, a game file, a GPU or the guest image: each check
# depends on one source file and the headers around it.
if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
    cmake_minimum_required(VERSION 3.20)
    project(mw2checks CXX)
    set(CMAKE_CXX_STANDARD 20)
    set(CMAKE_CXX_STANDARD_REQUIRED ON)
    if(NOT CMAKE_BUILD_TYPE)
        set(CMAKE_BUILD_TYPE Release)
    endif()
    enable_testing()
endif()

set(MW2_RUNTIME "${CMAKE_CURRENT_SOURCE_DIR}/../runtime")

# bc_decoder.cpp includes <vulkan/vulkan.h> for the format constants it answers
# with. It opens no device and calls into no driver, so the headers are all it
# needs; Windows has none to find and fetches them as the root build does. The
# root build has already done this when it includes this file, hence the test
# for the target rather than for the platform alone.
if(NOT TARGET Vulkan::Vulkan)
    if(WIN32)
        include("${CMAKE_CURRENT_SOURCE_DIR}/../cmake/vulkan-windows.cmake")
    else()
        find_package(Vulkan)
    endif()
endif()

# ---- durable writes --------------------------------------------------------
# Unlike the tools in ../tools, which are harnesses to be read, this asserts:
# a save survives losing the process part-way, a replacement leaves the previous
# contents whole, a successful write leaves no `.tmp`, one left by a dead run is
# not mistaken for the target, and sizes round-trip across block boundaries.
add_executable(durable-test
    "${CMAKE_CURRENT_SOURCE_DIR}/durable_test.cpp"
    "${MW2_RUNTIME}/kernel/durable.cpp")
target_include_directories(durable-test PRIVATE "${MW2_RUNTIME}")
add_test(NAME durable COMMAND durable-test)

# ---- the log's repeat counting ---------------------------------------------
# The rule that keeps a run readable when it logs one thing a thousand times
# (runtime/log.h): a line is written as it doubles with the count beside it, two
# lines differing only by an address are one kind, and a repetition in progress
# cannot flood.
add_executable(log-test
    "${CMAKE_CURRENT_SOURCE_DIR}/log_repeat_test.cpp")
target_include_directories(log-test PRIVATE "${MW2_RUNTIME}")
add_test(NAME log COMMAND log-test)

# ---- the software block-compressed decoder ---------------------------------
# What a GPU without native BC support samples (bc_decoder.cpp), checked against
# a decoder written from the formats themselves -- so a wrong index bit order,
# an endpoint swap or a row stride fails here rather than looking like a bad
# texture on one phone.
add_executable(bc-test
    "${CMAKE_CURRENT_SOURCE_DIR}/bc_decoder_test.cpp"
    "${MW2_RUNTIME}/gpu/vulkan/bc_decoder.cpp")
target_include_directories(bc-test PRIVATE "${MW2_RUNTIME}")
if(TARGET Vulkan::Vulkan)
    target_link_libraries(bc-test PRIVATE Vulkan::Vulkan)
    target_compile_definitions(bc-test PRIVATE MW2_HAVE_VULKAN=1)
elseif(Vulkan_INCLUDE_DIR)
    # The headers without the loader (tools/ci_toolchain.sh): FindVulkan
    # calls that not found, but nothing here calls into the loader, so the
    # headers are all the check needs.
    target_include_directories(bc-test PRIVATE "${Vulkan_INCLUDE_DIR}")
    target_compile_definitions(bc-test PRIVATE MW2_HAVE_VULKAN=1)
endif()
add_test(NAME bc COMMAND bc-test)

# ---- volume textures -------------------------------------------------------
# Where every level of a 3D texture lives in guest memory (runtime/gpu/texture.cpp),
# checked against Xenia's GetGuestTextureLayout transcribed for the comparison:
# the spans, the level offsets, and that untiling a volume reads each level from
# its own place. The depth term of a volume's level stride is what the code
# called unchecked.
add_executable(volume-test
    "${CMAKE_CURRENT_SOURCE_DIR}/texture_volume_test.cpp"
    "${MW2_RUNTIME}/gpu/texture.cpp")
target_include_directories(volume-test PRIVATE "${MW2_RUNTIME}")
add_test(NAME volume COMMAND volume-test)

# ---- release tag order -----------------------------------------------------
# launcher/version.h decides whether a release is newer than the running build
# (launcher/update.cpp). A tag it cannot read means the launcher never offers
# that release -- which is what happened to this project's own -alpha tags --
# so the order and the refusals are checked here, with no network or launcher.
add_executable(version-test
    "${CMAKE_CURRENT_SOURCE_DIR}/version_test.cpp")
target_include_directories(version-test PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/../launcher")
add_test(NAME version COMMAND version-test)

# ---- what a run's first frames look like -----------------------------------
# The three numbers the app judges a driver's first frames by
# (runtime/gpu/vulkan/picture_probe.h): one colour, noise, a picture. The
# presenter's copy needs a device; what is made of the copy does not.
add_executable(picture-probe-test
    "${CMAKE_CURRENT_SOURCE_DIR}/picture_probe_test.cpp")
target_include_directories(picture-probe-test PRIVATE "${MW2_RUNTIME}/gpu/vulkan")
add_test(NAME picture-probe COMMAND picture-probe-test)

# ---- how the frame sits on the panel ---------------------------------------
# The swapchain's transform and what the log says of it
# (runtime/gpu/vulkan/surface_transform.h): the warning that the picture may be
# rotated only where the surface refuses identity.
add_executable(surface-transform-test
    "${CMAKE_CURRENT_SOURCE_DIR}/surface_transform_test.cpp")
target_include_directories(surface-transform-test PRIVATE "${MW2_RUNTIME}/gpu/vulkan")
add_test(NAME surface-transform COMMAND surface-transform-test)

# ---- which record of the display the presenter follows ----------------------
# runtime/gpu/vulkan/present_clock.h: never VK_KHR_present_wait under Android's
# loader, whose swapchain the driver does not know (Mali SIGBUS, C0099).
add_executable(present-clock-test
    "${CMAKE_CURRENT_SOURCE_DIR}/present_clock_test.cpp")
target_include_directories(present-clock-test PRIVATE "${MW2_RUNTIME}/gpu/vulkan")
add_test(NAME present-clock COMMAND present-clock-test)

# ---- what the processor reads of a transfer's buffer ------------------------
# runtime/gpu/vulkan/host_read.h: the transfer-to-host barrier Advanced
# Warfare's luminance read-back needs on a command stream Mali (aw #9/#19,
# C0081). The headers only, as for bc-test.
add_executable(host-read-test
    "${CMAKE_CURRENT_SOURCE_DIR}/host_read_test.cpp")
target_include_directories(host-read-test PRIVATE "${MW2_RUNTIME}/gpu/vulkan")
if(TARGET Vulkan::Vulkan)
    target_link_libraries(host-read-test PRIVATE Vulkan::Vulkan)
elseif(Vulkan_INCLUDE_DIR)
    target_include_directories(host-read-test PRIVATE "${Vulkan_INCLUDE_DIR}")
endif()
add_test(NAME host-read COMMAND host-read-test)

# ---- what the driver self-test asks of a driver -----------------------------
# Its pixel shaders (runtime/gpu/vulkan/selftest.cpp): each the texture
# indexing of one form the renderer's own take, nothing more.
add_executable(selftest-shaders-test
    "${CMAKE_CURRENT_SOURCE_DIR}/selftest_shaders_test.cpp")
target_include_directories(selftest-shaders-test PRIVATE "${MW2_RUNTIME}/gpu/vulkan")
add_test(NAME selftest-shaders COMMAND selftest-shaders-test)

# ---- the console's gamma curve ----------------------------------------------
# The numbers the shader translator emits for a gamma target's colour and for
# a resolve's copy read back through a fetch that says `gamma`
# (runtime/gpu/vulkan/pwl_gamma.h): against Xenia's, that what is drawn is
# what is read, and how far an sRGB view is from it. Which titles read their
# copies back that way (bindings::kPiecewiseReadBack): one that is not as
# listed here does not compile. And what the translator emits after a fetch,
# run on a pixel shader written for it (pwl_readback_shader_test.cpp): with
# the handle's bit clear the texel is the sampler's bit for bit, with it set
# the colour is the curve's and the alpha untouched.
add_executable(pwl-gamma-test
    "${CMAKE_CURRENT_SOURCE_DIR}/pwl_gamma_test.cpp")
target_include_directories(pwl-gamma-test PRIVATE "${MW2_RUNTIME}/gpu/vulkan")
add_test(NAME pwl-gamma COMMAND pwl-gamma-test)
function(pwl_readback_title name expected)
    add_library(pwl-readback-${name} OBJECT "${CMAKE_CURRENT_SOURCE_DIR}/pwl_readback_titles.cpp")
    target_include_directories(pwl-readback-${name} PRIVATE "${MW2_RUNTIME}/gpu/vulkan")
    target_compile_definitions(pwl-readback-${name} PRIVATE PWL_EXPECT_READBACK=${expected} ${ARGN})
endfunction()
pwl_readback_title(mw2 1)
pwl_readback_title(mw3 1 PWL_AS_MW3=1)
pwl_readback_title(cod4 0 PWL_AS_COD4=1)
pwl_readback_title(aw 0 PWL_AS_AW=1)
pwl_readback_title(bo3 0 PWL_AS_BO3=1)
add_executable(pwl-readback-shader-test
    "${CMAKE_CURRENT_SOURCE_DIR}/pwl_readback_shader_test.cpp"
    "${MW2_RUNTIME}/gpu/vulkan/shader_translator.cpp"
    "${MW2_RUNTIME}/gpu/vulkan/spirv.cpp")
target_include_directories(pwl-readback-shader-test PRIVATE "${MW2_RUNTIME}/gpu/vulkan")
add_test(NAME pwl-readback-shader COMMAND pwl-readback-shader-test)

# ---- a pixel program without the alpha test --------------------------------
# A draw with the alpha test off is drawn, on a Mali, with its pixel program
# built without the test: no discard, so the depth is tested and written
# before the program runs. With the test the module is what it was.
add_executable(untested-program-test
    "${CMAKE_CURRENT_SOURCE_DIR}/untested_program_test.cpp"
    "${MW2_RUNTIME}/gpu/vulkan/shader_translator.cpp"
    "${MW2_RUNTIME}/gpu/vulkan/spirv.cpp")
target_include_directories(untested-program-test PRIVATE "${MW2_RUNTIME}/gpu/vulkan")
add_test(NAME untested-program COMMAND untested-program-test)

add_executable(relaxed-pixels-test
    "${CMAKE_CURRENT_SOURCE_DIR}/relaxed_pixels_test.cpp"
    "${MW2_RUNTIME}/gpu/vulkan/shader_translator.cpp"
    "${MW2_RUNTIME}/gpu/vulkan/spirv.cpp")
target_include_directories(relaxed-pixels-test PRIVATE "${MW2_RUNTIME}/gpu/vulkan")
add_test(NAME relaxed-pixels COMMAND relaxed-pixels-test)

# ---- the sequencer's own loops are structured loops ---------------------------
# Through the dispatcher a Mali's compiler took 87 to 114 s over Call of Duty
# 4's water (three loop_start ... loop_end), and every pipeline waited behind it.
add_executable(sequencer-loops-test
    "${CMAKE_CURRENT_SOURCE_DIR}/sequencer_loops_test.cpp"
    "${MW2_RUNTIME}/gpu/vulkan/shader_translator.cpp"
    "${MW2_RUNTIME}/gpu/vulkan/spirv.cpp")
target_include_directories(sequencer-loops-test PRIVATE "${MW2_RUNTIME}/gpu/vulkan")
add_test(NAME sequencer-loops COMMAND sequencer-loops-test)

# ---- a NaN vertex position is clipped where asked --------------------------
# A title computes a NaN position to throw a vertex away; a Mali's compiler at
# r32p1 aborts the process on the constant NaN it folds to (aw-recomp #2).
# With finitePosition the module clips it; without, it is what it was.
add_executable(vertex-position-test
    "${CMAKE_CURRENT_SOURCE_DIR}/vertex_position_test.cpp"
    "${MW2_RUNTIME}/gpu/vulkan/shader_translator.cpp"
    "${MW2_RUNTIME}/gpu/vulkan/spirv.cpp")
target_include_directories(vertex-position-test PRIVATE "${MW2_RUNTIME}/gpu/vulkan")
add_test(NAME vertex-position COMMAND vertex-position-test)

# ---- a predicated setp ------------------------------------------------------
# The console does not run an instruction whose predicate fails, so a scalar
# setp in one leaves the predicate as it was: the translator stores it under
# the instruction's condition like any other write (Call of Duty 4's sun
# shadow, Blackout's white bushes).
add_executable(predicated-setp-test
    "${CMAKE_CURRENT_SOURCE_DIR}/predicated_setp_test.cpp"
    "${MW2_RUNTIME}/gpu/vulkan/shader_translator.cpp"
    "${MW2_RUNTIME}/gpu/vulkan/spirv.cpp")
target_include_directories(predicated-setp-test PRIVATE "${MW2_RUNTIME}/gpu/vulkan")
add_test(NAME predicated-setp COMMAND predicated-setp-test)

# ---- what a device sustains ------------------------------------------------
# The rule that holds a run to the frame rate its device keeps and gives it
# the sun's shadows when its frames have room for them (runtime/adaptive.h):
# checked on windows of play as a phone would measure them, since the phones
# it is for -- every chip but the two the project owns -- are not here.
add_executable(adaptive-test
    "${CMAKE_CURRENT_SOURCE_DIR}/adaptive_test.cpp"
    "${MW2_RUNTIME}/adaptive_governor.cpp")
target_include_directories(adaptive-test PRIVATE "${MW2_RUNTIME}")
add_test(NAME adaptive COMMAND adaptive-test)

# What paces a frame-rate limit (runtime/frame_rate.h): the console's blank
# at 60, 30 and 20, the display at its own rate, the limiter for the rest.
add_executable(frame-rate-test
    "${CMAKE_CURRENT_SOURCE_DIR}/frame_rate_test.cpp")
target_include_directories(frame-rate-test PRIVATE "${MW2_RUNTIME}")
add_test(NAME frame-rate COMMAND frame-rate-test)

# ---- the DemonWare lobby stand-in ------------------------------------------
# What MW3's multiplayer logs on to instead of its publisher's servers
# (runtime/online/demonware.cpp): the stream's framing, the player's files read
# back whole and kept in the player's own folder, the playlists as the
# aggregate the title inflates, and that bytes which are not the protocol end
# the connection or the task without a read past them or a file written.
add_executable(demonware-test
    "${CMAKE_CURRENT_SOURCE_DIR}/demonware_test.cpp"
    "${MW2_RUNTIME}/online/demonware.cpp"
    "${MW2_RUNTIME}/kernel/durable.cpp")
target_include_directories(demonware-test PRIVATE "${MW2_RUNTIME}" "${CMAKE_CURRENT_SOURCE_DIR}/stubs")
add_test(NAME demonware COMMAND demonware-test)
# The same as Advanced Warfare's title update 17 builds it, which asks for the
# publisher's files under names of its own (social_tu20.cfg,
# playlists_tu20.aggr).
add_executable(demonware-aw17-test
    "${CMAKE_CURRENT_SOURCE_DIR}/demonware_test.cpp"
    "${MW2_RUNTIME}/online/demonware.cpp"
    "${MW2_RUNTIME}/kernel/durable.cpp")
target_include_directories(demonware-aw17-test PRIVATE "${MW2_RUNTIME}" "${CMAKE_CURRENT_SOURCE_DIR}/stubs")
target_compile_definitions(demonware-aw17-test PRIVATE AW_TITLE_MP=1 AW_TITLE_TU17=1)
add_test(NAME demonware-aw17 COMMAND demonware-aw17-test)
# And as Black Ops III builds it: the stream, and the public profile the title
# asks for before it opens Calling Cards, which is one that is not kept.
add_executable(demonware-bo3-test
    "${CMAKE_CURRENT_SOURCE_DIR}/demonware_test.cpp"
    "${MW2_RUNTIME}/online/demonware.cpp"
    "${MW2_RUNTIME}/kernel/durable.cpp")
target_include_directories(demonware-bo3-test PRIVATE "${MW2_RUNTIME}" "${CMAKE_CURRENT_SOURCE_DIR}/stubs")
target_compile_definitions(demonware-bo3-test PRIVATE BO3_TITLE=1)
add_test(NAME demonware-bo3 COMMAND demonware-bo3-test)

# ---- the pipeline cache between runs ---------------------------------------
# Whether the driver's pipeline cache is kept for the next run, by GPU and Mali
# driver release, and that a blob read back reaches the driver only when its
# VkPipelineCacheHeaderVersionOne names this device
# (runtime/gpu/vulkan/pipeline_cache_rules.h): no Mali phone is here to say so.
add_executable(pipeline-cache-test
    "${CMAKE_CURRENT_SOURCE_DIR}/pipeline_cache_test.cpp")
target_include_directories(pipeline-cache-test PRIVATE "${MW2_RUNTIME}")
add_test(NAME pipeline-cache COMMAND pipeline-cache-test)

# ---- the executables a disc must have --------------------------------------
# The installer in the runtime (CMakeLists.txt), the Android app's check of a
# disc (android/app/build.gradle.kts) and the release workflow name them
# apart; a disc one accepts and another refuses reaches a player as a
# refusal the app's own check never gave. A script, with no build.
add_test(NAME xex-hashes
    COMMAND "${CMAKE_COMMAND}" -P "${CMAKE_CURRENT_SOURCE_DIR}/xex_hashes_test.cmake")

# ---- a warning a frame repeats is said once per thing ----------------------
# A draw asks every frame for a pipeline whose shaders are not loaded; the
# warning about it is written once per pipeline (runtime/said_once.h).
add_executable(said-once-test
    "${CMAKE_CURRENT_SOURCE_DIR}/said_once_test.cpp")
target_include_directories(said-once-test PRIVATE "${MW2_RUNTIME}")
find_package(Threads REQUIRED)
target_link_libraries(said-once-test PRIVATE Threads::Threads)
add_test(NAME said-once COMMAND said-once-test)

# ---- how a crash reaches the system's handler ------------------------------
# The last fault handler calls the one before it from the crashing thread
# (runtime/signal_forward.h), and another thread's write to a page the GPU
# watch keeps read-only is still the watch's while it runs: the system then
# records the crash, not that write (case C0009). Signals as POSIX has them:
# not on Windows, whose crash.cpp is a vectored exception handler.
if(NOT WIN32)
    add_executable(signal-forward-test
        "${CMAKE_CURRENT_SOURCE_DIR}/signal_forward_test.cpp")
    target_include_directories(signal-forward-test PRIVATE "${MW2_RUNTIME}")
    find_package(Threads REQUIRED)
    target_link_libraries(signal-forward-test PRIVATE Threads::Threads)
    add_test(NAME signal-forward COMMAND signal-forward-test)
endif()

# ---- a stack walk that faults -----------------------------------------------
# A fault inside a walk of a thread's stack ends the walk, not the process
# (runtime/unwind_guard.h): on a processor that traps a failed pointer
# authentication, the unwinder's check of a stopped thread's return address
# took SIGILL and MW3 died of the stall watch's diagnostic (case C0062).
if(NOT WIN32)
    add_executable(unwind-guard-test
        "${CMAKE_CURRENT_SOURCE_DIR}/unwind_guard_test.cpp")
    target_include_directories(unwind-guard-test PRIVATE "${MW2_RUNTIME}")
    find_package(Threads REQUIRED)
    target_link_libraries(unwind-guard-test PRIVATE Threads::Threads)
    add_test(NAME unwind-guard COMMAND unwind-guard-test)
endif()

# ---- exit() by someone else -------------------------------------------------
# Once armed, exit() from anywhere runs the report and ends the process with
# the armed status, without the destructors registered before the latest arm
# (runtime/exit_guard.h): on a phone, a driver's compiler that called exit()
# left the audio client's binder thread reading a destroyed table (C0057).
# The test runs itself as a child for each case, so it ends real processes.
add_executable(exit-guard-test
    "${CMAKE_CURRENT_SOURCE_DIR}/exit_guard_test.cpp"
    "${MW2_RUNTIME}/exit_guard.cpp")
target_include_directories(exit-guard-test PRIVATE "${MW2_RUNTIME}")
add_test(NAME exit-guard COMMAND exit-guard-test)

# ---- which copy of a save folder a copy is ----------------------------------
# The player's XUIDs are the folder's profile plus this number
# (runtime/online/copy_lock.h). It is counted in the folder: a copy alone in
# its folder is the same player in every run, whatever else the machine runs,
# and only a second copy of the same folder is a second player.
add_executable(copy-lock-test
    "${CMAKE_CURRENT_SOURCE_DIR}/copy_lock_test.cpp")
target_include_directories(copy-lock-test PRIVATE "${MW2_RUNTIME}")
add_test(NAME copy-lock COMMAND copy-lock-test)

# ---- a game left in the background ------------------------------------------
# The gate the frame loop and the mixer stop at while the app is not in front
# (runtime/pause_gate.h): Modern Warfare 3's multiplayer went on at 240% of
# the processor on an AYN Thor behind another app. A closed gate holds every thread that reaches
# it until it opens or the run ends, and an opening is never missed.
add_executable(pause-gate-test
    "${CMAKE_CURRENT_SOURCE_DIR}/pause_gate_test.cpp")
target_include_directories(pause-gate-test PRIVATE "${MW2_RUNTIME}")
find_package(Threads REQUIRED)
target_link_libraries(pause-gate-test PRIVATE Threads::Threads)
add_test(NAME pause-gate COMMAND pause-gate-test)
set_tests_properties(pause-gate PROPERTIES TIMEOUT 60)

# ---- a stall is not a pause --------------------------------------------------
# The watchdog that dumps every thread when the title's frames stop
# (runtime/stall_watch.h) leaves out the time the app's pause held the run, and
# times again from the resume; a real stall after it still fires.
add_executable(stall-watch-test
    "${CMAKE_CURRENT_SOURCE_DIR}/stall_watch_test.cpp")
target_include_directories(stall-watch-test PRIVATE "${MW2_RUNTIME}")
add_test(NAME stall-watch COMMAND stall-watch-test)

# ---- progress read as unlocked, saved as earned -----------------------------
# The rule of a value the menus read where it lives (runtime/unlock_raised.h):
# raised between the title's reads and writes, the player's own to a script
# that decides what is recorded and to the save, so a mission finished with
# everything unlocked is recorded as it would be without.
add_executable(unlock-raised-test
    "${CMAKE_CURRENT_SOURCE_DIR}/unlock_raised_test.cpp")
target_include_directories(unlock-raised-test PRIVATE "${MW2_RUNTIME}")
add_test(NAME unlock-raised COMMAND unlock-raised-test)


if(WIN32)
    # The same rule the game is linked with: no C++ runtime beside the
    # executable. Without it a check that pulls in one more libstdc++ symbol
    # than the shell's PATH can supply -- a std::filesystem one, say -- fails at
    # process start (0xc0000139) instead of failing on the code under test, and
    # a check that never starts looks like a check that never ran.
    target_link_options(durable-test PRIVATE -static)
    target_link_options(log-test PRIVATE -static)
    target_link_options(bc-test PRIVATE -static)
    target_link_options(volume-test PRIVATE -static)
    target_link_options(version-test PRIVATE -static)
    target_link_options(picture-probe-test PRIVATE -static)
    target_link_options(selftest-shaders-test PRIVATE -static)
    target_link_options(pwl-gamma-test PRIVATE -static)
    target_link_options(pwl-readback-shader-test PRIVATE -static)
    target_link_options(adaptive-test PRIVATE -static)
    target_link_options(demonware-test PRIVATE -static)
    target_link_options(demonware-aw17-test PRIVATE -static)
    target_link_options(pipeline-cache-test PRIVATE -static)
    target_link_options(exit-guard-test PRIVATE -static)
    target_link_options(copy-lock-test PRIVATE -static)
    target_link_options(pause-gate-test PRIVATE -static)
    target_link_options(unlock-raised-test PRIVATE -static)
endif()
