# Copyright (C) 2018-2020 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#

cmake_minimum_required(VERSION 3.10)

# Multi config generators such as Visual Studio ignore CMAKE_BUILD_TYPE. Multi config generators are configured with
# CMAKE_CONFIGURATION_TYPES, but limiting options in it completely removes such build options
get_property(GENERATOR_IS_MULTI_CONFIG_VAR GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
if(NOT GENERATOR_IS_MULTI_CONFIG_VAR AND NOT DEFINED CMAKE_BUILD_TYPE)
    message(STATUS "CMAKE_BUILD_TYPE not defined, 'Release' will be used")
    # Setting CMAKE_BUILD_TYPE as CACHE must go before project(). Otherwise project() sets its value and set() doesn't take an effect
    set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel ...")
endif()

project(Demos)

option(ENABLE_PYTHON "Whether to build extension modules for Python demos" OFF)
option(MULTICHANNEL_DEMO_USE_TBB "Use TBB-based threading in multichannel demos" OFF)
option(MULTICHANNEL_DEMO_USE_NATIVE_CAM "Use native camera api in multichannel demos" OFF)

if(NOT BIN_FOLDER)
    string(TOLOWER ${CMAKE_SYSTEM_PROCESSOR} ARCH)
    if(ARCH STREQUAL "x86_64" OR ARCH STREQUAL "amd64") # Windows detects Intel's 64-bit CPU as AMD64
        set(ARCH intel64)
    elseif(ARCH STREQUAL "i386")
        set(ARCH ia32)
    endif()

    set(BIN_FOLDER ${ARCH})
endif()

foreach(artifact IN ITEMS ARCHIVE COMPILE_PDB LIBRARY PDB RUNTIME)
    set("CMAKE_${artifact}_OUTPUT_DIRECTORY" "${CMAKE_CURRENT_BINARY_DIR}/${BIN_FOLDER}/$<CONFIG>")
endforeach()

if(WIN32)
    if(NOT "${CMAKE_SIZEOF_VOID_P}" EQUAL "8")
        message(FATAL_ERROR "Only 64-bit supported on Windows")
    endif()

    add_definitions(-DNOMINMAX)
endif()

if(MSVC)
    add_compile_options(/wd4251 /wd4275 /wd4267  # disable some warnings
                        /W3  # Specify the level of warnings to be generated by the compiler
                        /EHsc)  # Enable standard C++ stack unwinding, assume functions with extern "C" never throw
endif()

if(CMAKE_CXX_COMPILER_ID MATCHES "^GNU|(Apple)?Clang$")
    set(COMPILER_IS_GCC_LIKE TRUE)
    add_compile_options(-Wall)
else()
    set(COMPILER_IS_GCC_LIKE FALSE)
endif()

if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(arm64.*|aarch64.*|AARCH64.*)")
  set(AARCH64 ON)
elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "^(arm.*|ARM.*)")
  set(ARM ON)
endif()
if(ARM AND NOT CMAKE_CROSSCOMPILING)
    add_compile_options(-march=armv7-a)
endif()

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)

function(add_demos_to_build)
    # check each passed demo subdirectory
    foreach(dir ${ARGN})
        if(IS_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/${dir})
            # check if a subdirectory contains CMakeLists.txt. In this case we can build it.
            file(GLOB sub_dirs ${CMAKE_CURRENT_SOURCE_DIR}/${dir}/*)
            foreach(sub_dir ${sub_dirs})
                if(EXISTS "${sub_dir}/CMakeLists.txt")
                    # check if specified demo is found.
                    if(BUILD_SAMPLE_NAME)
                        list(FIND BUILD_SAMPLE_NAME ${dir} index)
                    endif()
                    if(index EQUAL -1)
                        message(STATUS "${dir} SKIPPED")
                    else()
                        # Include subdirectory to the project.
                        add_subdirectory(${sub_dir})
                    endif()
                endif()
            endforeach()
        endif()
    endforeach()
endfunction()

include(CMakeParseArguments)

# add_demo(NAME <target name>
#     SOURCES <source files>
#     [HEADERS <header files>]
#     [INCLUDE_DIRECTORIES <include dir>]
#     [OPENCV_VERSION_REQUIRED <X.Y.Z>]
#     [DEPENDENCIES <dependencies>])
macro(add_demo)
    set(oneValueArgs NAME OPENCV_VERSION_REQUIRED)
    set(multiValueArgs SOURCES HEADERS DEPENDENCIES INCLUDE_DIRECTORIES)
    cmake_parse_arguments(OMZ_DEMO "${options}" "${oneValueArgs}"
                          "${multiValueArgs}" ${ARGN})

    if(OMZ_DEMO_OPENCV_VERSION_REQUIRED AND OpenCV_VERSION VERSION_LESS OMZ_DEMO_OPENCV_VERSION_REQUIRED)
        message(WARNING "${OMZ_DEMO_NAME} is disabled; required OpenCV version ${OMZ_DEMO_OPENCV_VERSION_REQUIRED}, provided ${OpenCV_VERSION}")
        return()
    endif()

    # Create named folders for the sources within the .vcproj
    # Empty name lists them directly under the .vcproj
    source_group("src" FILES ${OMZ_DEMO_SOURCES})
    if(OMZ_DEMO_HEADERS)
        source_group("include" FILES ${OMZ_DEMO_HEADERS})
    endif()

    # Create executable file from sources
    add_executable(${OMZ_DEMO_NAME} ${OMZ_DEMO_SOURCES} ${OMZ_DEMO_HEADERS})

    if(WIN32)
        set_target_properties(${OMZ_DEMO_NAME} PROPERTIES COMPILE_PDB_NAME ${OMZ_DEMO_NAME})
    endif()

    if(OMZ_DEMO_INCLUDE_DIRECTORIES)
        target_include_directories(${OMZ_DEMO_NAME} PRIVATE ${OMZ_DEMO_INCLUDE_DIRECTORIES})
    endif()

    target_link_libraries(${OMZ_DEMO_NAME} PRIVATE ${OpenCV_LIBRARIES} openvino::runtime
                                                    ${OMZ_DEMO_DEPENDENCIES} utils gflags)

    if(UNIX)
        target_link_libraries(${OMZ_DEMO_NAME} PRIVATE pthread)
    endif()
endmacro()

find_package(OpenCV REQUIRED COMPONENTS core highgui videoio imgproc imgcodecs)
find_package(OpenVINO REQUIRED COMPONENTS Runtime)

add_subdirectory(thirdparty/gflags)
add_subdirectory(common/cpp)
# TODO: remove wrapping if after OpenCV3 is dropped
if(OpenCV_VERSION VERSION_GREATER_EQUAL 4.5.3)
    find_package(OpenCV REQUIRED COMPONENTS gapi)
    add_subdirectory(common/cpp_gapi)
endif()
add_subdirectory(multi_channel_common/cpp)

# collect all samples subdirectories
file(GLOB samples_dirs RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *)
# skip building of unnecessary subdirectories
list(REMOVE_ITEM samples_dirs common thirdparty multi_channel_common)
add_demos_to_build(${samples_dirs})

if(ENABLE_PYTHON)
    find_package(PythonInterp 3.6 REQUIRED)
    find_package(PythonLibs "${PYTHON_VERSION_STRING}" EXACT REQUIRED)

    execute_process(
    COMMAND "${PYTHON_EXECUTABLE}" -c "import numpy; print(numpy.get_include())"
    OUTPUT_VARIABLE NUMPY_INCLUDE_DIR
    OUTPUT_STRIP_TRAILING_WHITESPACE
    RESULT_VARIABLE NUMPY_NOT_FOUND)
    if(NUMPY_NOT_FOUND)
        message(FATAL_ERROR "NumPy headers not found")
    endif()

    add_subdirectory(human_pose_estimation_3d_demo/python/pose_extractor)
    add_subdirectory(common/python/monitors_extension)
    add_subdirectory(speech_recognition_deepspeech_demo/python/ctcdecode-numpy)
endif()
