cmake_minimum_required(VERSION 3.21)
project(Steambot_Chronicles_Recomp LANGUAGES CXX)

# Steambot Chronicles (NTSC-U, SLUS-21344) on BozoEngine: the game's EE code recompiled by bozo-recomp, every library and
# kernel call answered natively by the engine's runtime. No PS2 hardware model.
# The ELF and the overlay modules come from the player's own disc (scripts/extract_iso.sh puts them in game/).
# The pipeline is Onimusha_Recomp's (one generated image per code overlay) with Amplitude_Recomp's symbol map (the ELF is
# stripped).

if(NOT CMAKE_BUILD_TYPE)
  set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
endif()
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_SCAN_FOR_MODULES OFF)

set(SBC_GAME_DIR "${CMAKE_SOURCE_DIR}/game" CACHE PATH "User-owned extracted disc files")
set(SBC_ISO "${CMAKE_SOURCE_DIR}/Steambot Chronicles (USA).iso" CACHE FILEPATH "User-owned NTSC-U disc image")
# BozoEngine: the release cmake/bozo_engine.json pins, fetched into BozoEngine/ (cmake/bozo_engine_fetch.cmake), unless
# BOZO_ENGINE_DIR names another tree (development: a BozoEngine checkout, for engine work not released yet).
set(BOZO_ENGINE_DIR "" CACHE PATH "BozoEngine's source tree (default: the release cmake/bozo_engine.json pins, in BozoEngine/)")
if(NOT BOZO_ENGINE_DIR OR BOZO_ENGINE_DIR STREQUAL "${CMAKE_SOURCE_DIR}/BozoEngine")
  include("${CMAKE_SOURCE_DIR}/cmake/bozo_engine_fetch.cmake")
  set(BOZO_ENGINE_DIR "${bozo_engine_tree}")
  set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${CMAKE_SOURCE_DIR}/cmake/bozo_engine.json")
endif()
message(STATUS "BozoEngine: ${BOZO_ENGINE_DIR}")
option(SBC_WINDOW "Build the SDL3 native game window (steambot) next to sbc-headless" ON)
set(BOZO_APP ${SBC_WINDOW} CACHE BOOL "" FORCE)
set(BOZO_BUILD_TOOLS OFF CACHE BOOL "" FORCE)
set(BOZO_REQUIRE_FFMPEG OFF CACHE BOOL "The movies need native decoding (not wired up yet)")
add_subdirectory("${BOZO_ENGINE_DIR}" BozoEngine)
find_package(Python3 REQUIRED COMPONENTS Interpreter)

set(sbc_elf ${SBC_GAME_DIR}/SLUS_213.44)
set(sbc_symbols ${CMAKE_SOURCE_DIR}/recomp/sbc_symbols.txt)
# sbc_prep: the prepared images and lists (tools/sbc_prepare.py, the externals, the module registration);
# sbc_gen: bozo-recomp's output only (it removes any other <prefix>_* file there).
set(sbc_prep ${CMAKE_BINARY_DIR}/sbc_prep)
set(sbc_gen ${CMAKE_BINARY_DIR}/sbc_gen)
file(MAKE_DIRECTORY ${sbc_prep} ${sbc_gen})
if(NOT EXISTS ${sbc_elf})
  message(FATAL_ERROR "${sbc_elf} not found: run scripts/extract_iso.sh <iso> first")
endif()

# The resident image and the 55 overlay modules (INST, MENU, maps) are prepared at configure time: the list of modules
# comes from the disc, and every module is its own generated image. Re-run cmake after changing tools/sbc_prepare.py.
execute_process(
  COMMAND ${Python3_EXECUTABLE} -I ${CMAKE_SOURCE_DIR}/tools/sbc_prepare.py ${SBC_GAME_DIR} ${sbc_prep}
  RESULT_VARIABLE sbc_prepare_result OUTPUT_VARIABLE sbc_prepare_output ERROR_VARIABLE sbc_prepare_error)
if(NOT sbc_prepare_result EQUAL 0)
  message(FATAL_ERROR "tools/sbc_prepare.py failed:\n${sbc_prepare_output}${sbc_prepare_error}")
endif()
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
  ${CMAKE_SOURCE_DIR}/tools/sbc_prepare.py ${CMAKE_SOURCE_DIR}/tools/wrap_elf.py ${sbc_elf})
include(${sbc_prep}/sbc_modules.cmake)
file(GLOB sbc_port_sources CONFIGURE_DEPENDS ${CMAKE_SOURCE_DIR}/runtime/sbc_*.cpp)

# The externals: library and kernel functions named by the symbol map become stubs the runtime answers; every address
# the port registers (tools/sbc_overrides_list.py scans runtime/) becomes an override or a native site. The names the
# game's own code keeps (recomp/sbc_guest_names.txt) are left out of the map it reads. The overlays share the resident
# program's stubs and overrides (never an override inside an overlay slot: modules share addresses).
set(sbc_externals ${sbc_prep}/sbc_externals.txt)
set(sbc_guest_names ${CMAKE_SOURCE_DIR}/recomp/sbc_guest_names.txt)
set(sbc_symbols_native ${sbc_prep}/sbc_symbols_native.txt)
add_custom_command(OUTPUT ${sbc_externals}
  COMMAND ${Python3_EXECUTABLE} -I ${CMAKE_SOURCE_DIR}/tools/sbc_overrides_list.py ${CMAKE_SOURCE_DIR}/runtime ${sbc_prep}/sbc_overrides.txt
  COMMAND ${Python3_EXECUTABLE} -I ${CMAKE_SOURCE_DIR}/tools/sbc_symbols_native.py ${sbc_symbols} ${sbc_guest_names} ${sbc_symbols_native}
  COMMAND bozo-externals ${sbc_prep}/sbc.elf ${sbc_externals} --symbols ${sbc_symbols_native} --overrides ${sbc_prep}/sbc_overrides.txt
  DEPENDS bozo-externals ${sbc_prep}/sbc.elf ${sbc_symbols} ${sbc_guest_names} ${CMAKE_SOURCE_DIR}/tools/sbc_symbols_native.py
          ${CMAKE_SOURCE_DIR}/tools/sbc_overrides_list.py ${sbc_port_sources}
  COMMENT "Listing the externals of SLUS_213.44")
set(sbc_overlay_externals ${sbc_prep}/sbc_overlay_externals.txt)
add_custom_command(OUTPUT ${sbc_overlay_externals}
  COMMAND ${Python3_EXECUTABLE} -I ${CMAKE_SOURCE_DIR}/tools/sbc_overlay_externals.py ${sbc_externals} ${sbc_overlay_externals}
  DEPENDS ${sbc_externals} ${CMAKE_SOURCE_DIR}/tools/sbc_overlay_externals.py)

set(sbc_sources)
set(sbc_chunks 32)
foreach(image sbc ${sbc_modules})
  if(image STREQUAL "sbc")
    set(chunks ${sbc_chunks})
    set(image_options --externals ${sbc_externals} --symbols ${sbc_symbols})
    set(image_externals ${sbc_externals} ${sbc_symbols})
    if(EXISTS ${CMAKE_SOURCE_DIR}/recomp/sbc_entries.txt)
      list(APPEND image_options --entries ${CMAKE_SOURCE_DIR}/recomp/sbc_entries.txt)
      list(APPEND image_externals ${CMAKE_SOURCE_DIR}/recomp/sbc_entries.txt)
    endif()
  else()
    set(chunks 1)
    set(image_options --symbol-prefix ${image}_ --externals ${sbc_overlay_externals})
    set(image_externals ${sbc_overlay_externals})
  endif()
  set(files ${sbc_gen}/${image}_functions.h ${sbc_gen}/${image}_table.cpp)
  math(EXPR last "${chunks} - 1")
  foreach(i RANGE ${last})
    if(i LESS 10)
      list(APPEND files ${sbc_gen}/${image}_00${i}.cpp)
    else()
      list(APPEND files ${sbc_gen}/${image}_0${i}.cpp)
    endif()
  endforeach()
  add_custom_command(OUTPUT ${files}
    COMMAND bozo-recomp ${sbc_prep}/${image}.elf ${sbc_gen} --prefix ${image} --files ${chunks} --no-comments
            ${image_options} --report ${sbc_prep}/${image}_report.txt
    DEPENDS bozo-recomp ${sbc_prep}/${image}.elf ${image_externals}
    COMMENT "Recompiling ${image}")
  list(APPEND sbc_sources ${files})
endforeach()

# The overlay registration: every module's tables, its identity and its address range (tools/sbc_modules_gen.py).
set(sbc_modules_cpp ${sbc_prep}/modules.cpp)
add_custom_command(OUTPUT ${sbc_modules_cpp}
  COMMAND ${Python3_EXECUTABLE} -I ${CMAKE_SOURCE_DIR}/tools/sbc_modules_gen.py ${sbc_prep}/sbc_modules.txt ${sbc_prep} ${sbc_modules_cpp}
  DEPENDS ${sbc_prep}/sbc_modules.txt ${CMAKE_SOURCE_DIR}/tools/sbc_modules_gen.py
  COMMENT "Listing the overlay modules")
list(APPEND sbc_sources ${sbc_modules_cpp})
add_custom_target(sbc_generate DEPENDS ${sbc_sources})

add_library(sbc_game STATIC ${sbc_sources})
target_link_libraries(sbc_game PUBLIC bozo_runtime_headers)
target_include_directories(sbc_game PUBLIC ${sbc_gen})
target_compile_options(sbc_game PRIVATE -O1 -w -ffp-contract=off)

# The IOP modules, statically compiled from the player's disc (tools/sbc_bozo_audio.py, docs/native-irx.md in
# BozoEngine): Sony's LIBSD, SDRDRV, MODHSYN, MODMIDI, MODSESQ2, MODSEIN, the CD streamer CDVDSTM and Irem's IREMSND.
set(sbc_audio_gen ${CMAKE_BINARY_DIR}/sbc_audio_gen)
set(sbc_audio_names LIBSD SDRDRV MODHSYN MODMIDI MODSESQ2 MODSEIN CDVDSTM IREMSND)
set(sbc_audio_outputs ${sbc_audio_gen}/sbc_audio_modules.h)
set(sbc_audio_code)
foreach(module ${sbc_audio_names})
  string(TOLOWER "${module}" lower)
  list(APPEND sbc_audio_outputs ${sbc_audio_gen}/${lower}_iop.cpp)
  list(APPEND sbc_audio_code ${sbc_audio_gen}/${lower}_iop.cpp)
endforeach()
add_custom_command(OUTPUT ${sbc_audio_outputs}
  COMMAND ${Python3_EXECUTABLE} -I ${CMAKE_SOURCE_DIR}/tools/sbc_bozo_audio.py ${SBC_GAME_DIR} ${sbc_audio_gen} ${BOZO_ENGINE_DIR}
  DEPENDS ${SBC_GAME_DIR}/IOP/IOP.DAT ${CMAKE_SOURCE_DIR}/tools/sbc_bozo_audio.py ${CMAKE_SOURCE_DIR}/tools/sbc_fat.py
          ${BOZO_ENGINE_DIR}/tools/native_irx/relocate.py ${BOZO_ENGINE_DIR}/tools/native_irx/recompile.py
  COMMENT "Statically recompiling the IOP modules")
add_custom_target(sbc_native_audio DEPENDS ${sbc_audio_outputs})
add_library(sbc_audio_code OBJECT ${sbc_audio_code})
target_link_libraries(sbc_audio_code PRIVATE bozo_runtime_headers)
target_compile_options(sbc_audio_code PRIVATE -O1 -w)

set(sbc_runtime_sources ${sbc_port_sources} $<TARGET_OBJECTS:sbc_audio_code>)
list(FILTER sbc_runtime_sources EXCLUDE REGEX "sbc_main\\.cpp$")

add_executable(sbc-headless runtime/sbc_main.cpp ${sbc_runtime_sources})
target_link_libraries(sbc-headless PRIVATE sbc_game bozo_host)
target_include_directories(sbc-headless PRIVATE ${CMAKE_SOURCE_DIR}/runtime ${sbc_audio_gen})
add_dependencies(sbc-headless sbc_native_audio)
target_compile_definitions(sbc-headless PRIVATE SBC_DEFAULT_ELF="${sbc_prep}/sbc.elf" SBC_DEFAULT_ISO="${SBC_ISO}"
                                                SBC_SYMBOL_MAP="${sbc_symbols}")
if(MINGW)
  target_link_options(sbc-headless PRIVATE -static)
endif()

# The game in a window (SDL3, OpenGL 3.3): the same port, the PC's pads and sound.
if(SBC_WINDOW)
  add_executable(steambot runtime/sbc_main.cpp runtime/app/sbc_cheats_ui.cpp ${sbc_runtime_sources})
  target_link_libraries(steambot PRIVATE sbc_game bozo_host bozo_app)
  target_include_directories(steambot PRIVATE ${CMAKE_SOURCE_DIR}/runtime ${sbc_audio_gen})
  add_dependencies(steambot sbc_native_audio)
  target_compile_definitions(steambot PRIVATE SBC_WITH_WINDOW SBC_DEFAULT_ELF="${sbc_prep}/sbc.elf"
                                              SBC_DEFAULT_ISO="${SBC_ISO}" SBC_SYMBOL_MAP="${sbc_symbols}")
  if(WIN32)
    # The window's icon (docs/branding/make_logo.py sbc: the Bozos clown as a steampunk inventor; no game art), the
    # UTF-8 manifest and the version information.
    enable_language(RC)
    set_source_files_properties(runtime/app/steambot.rc PROPERTIES OBJECT_DEPENDS
      "${CMAKE_SOURCE_DIR}/runtime/app/steambot.ico;${CMAKE_SOURCE_DIR}/runtime/app/steambot.manifest")
    target_sources(steambot PRIVATE runtime/app/steambot.rc)
  endif()
  if(MINGW)
    target_link_options(steambot PRIVATE -static)
    get_filename_component(sbc_toolchain_bin "${CMAKE_CXX_COMPILER}" DIRECTORY)
    add_custom_command(TARGET steambot POST_BUILD
      COMMAND ${CMAKE_COMMAND} -DEXE=$<TARGET_FILE:steambot> -DSEARCH=${sbc_toolchain_bin}
              -P ${CMAKE_SOURCE_DIR}/cmake/copy_runtime_dlls.cmake)
  endif()
endif()
