cmake_minimum_required (VERSION 3.29)

project(VulkanEngine)

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

# Find all package dependencies
find_package( glfw3 REQUIRED )
find_package( glm REQUIRED )
find_package( VulkanMemoryAllocator CONFIG REQUIRED )
find_package( fmt REQUIRED )

# fastgltf because it's not in nixpkgs
include(FetchContent)

FetchContent_Declare(
    fastgltf
    GIT_REPOSITORY https://github.com/spnda/fastgltf.git
    GIT_TAG v0.8.0
)
FetchContent_MakeAvailable(fastgltf)

# Enables LTO
include(CheckIPOSupported)
check_ipo_supported(RESULT LTO_SUPPORTED OUTPUT LTO_ERROR)

if(LTO_SUPPORTED AND CMAKE_BUILD_TYPE STREQUAL "Release")
  message(STATUS "LTO activated")
  set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
else()
  message(WARNING "LTO not supported : ${LTO_ERROR}")
endif()

# A function to automate executables aditions

function ( addBinary BINARY_NAME )
  cmake_parse_arguments ( BINARY "" "SHADER" "LIBS;TEXTURES;MODELS" ${ARGN} )
  add_executable ( ${BINARY_NAME} src/${BINARY_NAME}.cpp )
  # Sets the output dir to have clear separation between binaries
  set_target_properties ( ${BINARY_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${BINARY_NAME} )
  set_target_properties ( ${BINARY_NAME} PROPERTIES CXX_STANDARD 20 ) # Uses C++20

  # Define VULKAN_HPP_HANDLE_ERROR_OUT_OF_DATE_AS_SUCCESS to treat VK_ERROR_OUT_OF_DATE_KHR as a success code
  target_compile_definitions ( ${BINARY_NAME} PRIVATE "VULKAN_HPP_HANDLE_ERROR_OUT_OF_DATE_AS_SUCCESS" )



  if (DEFINED BINARY_LIBS)
    target_link_libraries ( ${BINARY_NAME} ${BINARY_LIBS} )
  endif()

  if (DEFINED BINARY_MODELS) # Adds the 3D models in the binary folder
    set(RESOLVED_MODELS "")
    foreach(MODEL_PATTERN ${BINARY_MODELS})
      file(GLOB MATCHED_MODELS CONFIGURE_DEPENDS
        "${CMAKE_SOURCE_DIR}/assets/models/${MODEL_PATTERN}"
      )
      list(APPEND RESOLVED_MODELS ${MATCHED_MODELS})
    endforeach()

    if (RESOLVED_MODELS)
      file(COPY ${RESOLVED_MODELS} DESTINATION ${CMAKE_BINARY_DIR}/${BINARY_NAME}/models)
    endif()
  endif()

  if (DEFINED BINARY_TEXTURES) # Adds the textures in the binary folder
    set(RESOLVED_TEXTURES "")
    foreach(TEX_PATTERN ${BINARY_TEXTURES})
      file(GLOB MATCHED_TEXTURES CONFIGURE_DEPENDS
        "${CMAKE_SOURCE_DIR}/assets/textures/${TEX_PATTERN}"
      )
      list(APPEND RESOLVED_TEXTURES ${MATCHED_TEXTURES})
    endforeach()

    if (RESOLVED_TEXTURES)
      file(COPY ${RESOLVED_TEXTURES} DESTINATION ${CMAKE_BINARY_DIR}/${BINARY_NAME}/textures)
    endif()
  endif ()
endfunction()

# Adds the main binary

addBinary (
  main

  LIBS glfw fmt
)
