# Maintainer: Alexey Pavlov <alexpux@gmail.com>

_realname=embree
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=4.4.0
pkgrel=1
pkgdesc="High Performance Ray Tracing Kernels Intel Corporation (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://www.embree.org/"
msys2_repository_url="https://github.com/embree/embree"
msys2_references=(
  'archlinux: embree'
)
license=("spdx:Apache-2.0")
depends=("${MINGW_PACKAGE_PREFIX}-cc-libs"
         "${MINGW_PACKAGE_PREFIX}-tbb")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ispc"
             "${MINGW_PACKAGE_PREFIX}-ninja")
source=(https://github.com/embree/embree/archive/v${pkgver}/${_realname}-${pkgver}.tar.gz
        001-build-fixes.patch
        002-arm64-no-mm-malloc.patch)
sha256sums=('acb517b0ea0f4b442235d5331b69f96192c28da6aca5d5dde0cbe40799638d5c'
            '2da422a4c8cb8ea80e4d10262a30b1c3a64f1d38d5b1d03461e5cde128f061f4'
            'e6b6ea48699fc2b4a4318914a2934f29c8747cf5a72b465de0e9ff2807424517')
prepare() {
  cd "${srcdir}"/${_realname}-${pkgver}
  patch -p1 -i "${srcdir}"/001-build-fixes.patch

  # no _mm_malloc with clangarm64, so just use _aligned_malloc everywhere
  patch -p1 -i "${srcdir}"/002-arm64-no-mm-malloc.patch
}

build() {
  mkdir -p build-${MSYSTEM} && cd build-${MSYSTEM}

  declare -a extra_config
  if check_option "debug" "n"; then
    extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  if [[ "${CARCH}" == "x86_64" ]]; then
    extra_config+=("-DEMBREE_ISA_AVX512=ON" "-DEMBREE_MAX_ISA=AVX512SKX")
  else
    extra_config+=("-DEMBREE_ISA_AVX512=OFF")
  fi

  if [[ "${CARCH}" == "aarch64" ]]; then
    extra_config+=("-DEMBREE_ARM=ON")
  else
    extra_config+=("-DEMBREE_ARM=OFF")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe -Wno-dev \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DEMBREE_STATIC_LIB=OFF \
    -DEMBREE_ISPC_SUPPORT=ON \
    -DEMBREE_STACK_PROTECTOR=ON \
    -DEMBREE_TUTORIALS=OFF \
    -DBUILD_TESTING=OFF \
    -DEMBREE_INSTALL_DEPENDENCIES=OFF \
    ${extra_config[@]} \
    ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake --build .
}

package() {
  cd "${srcdir}"/build-${MSYSTEM}
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --install .
  install -Dm644 "${srcdir}"/${_realname}-${pkgver}/LICENSE.txt "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}
