# Maintainer (arch): Sven-Hendrik Haase <svenstaro@archlinux.org>
# Maintainer (arch32): Andreas Baumann <mail@andreasbaumann.cc>
# Maintainer (archarm): Kevin Mihelich <kevin@archlinuxarm.org>
# Contributor: John Sowiak <john@archlinux.org>
# Contributor: tobias <tobias@archlinux.org>
# Contributor: Andreas Grapentin <andreas@grapentin.org>
# Contributor: Márcio Silva <coadde@hyperbola.info>
# Contributor: bill-auger <bill-auger@programmer.net>
# Maintainer: Parabola Hackers <dev@lists.parabola.nu>


# parabola changes and rationale:
# - removed support for non-free CUDA and optix
# - set OS type string to GNU/Linux-libre
# - pin to tightly-coupled dependency versions

# NOTE: This PKGBUILD is kept in-sync, as closely as possible,
#       with arch{,arm,32}, for the sake of documentation and cleaner diffs.
#       That also helps to identify which changes were made by Parabola vs upstream.
#       Therefore, this PKGBUILD may declare blacklisted dependencies, non-free sources,
#       or include code for anti-features; but those will be filtered-out subsequently.
#       Any code which implements an anti-feature should be commented-out;
#       and include an 'anti-feature' comment, for clarity.
#       Any blacklisted dependencies and non-free sources should be filtered,
#       and include a 'non-free' comment, for clarity.
#       Without those over-rides, the resulting program may not be FSDG-fit.
#       Do not circumvent those over-rides, if compiling for the Parabola repos.


pkgname=blender
pkgver=3.4.1
[[ "${CARCH}" == 'i686' ]] && pkgver=3.1.2
pkgrel=12
pkgrel+=.parabola1
epoch=17
pkgdesc="A fully integrated 3D graphics creation suite"
arch=('x86_64')
arch+=('armv7h' 'i686')
license=('GPL')
url="https://www.blender.org"
depends=('libpng' 'libtiff' 'openexr' 'python' 'desktop-file-utils' 'python-requests' 'potrace'
         'shared-mime-info' 'hicolor-icon-theme' 'xdg-utils' 'glew' 'openjpeg2' 'python-numpy'
         'freetype2' 'openal' 'ffmpeg' 'fftw' 'boost-libs' 'opencollada' 'alembic' 'openxr'
         'openimageio' 'libsndfile' 'jack' 'opencolorio' 'openshadinglanguage' 'openimagedenoise'
         'jemalloc' 'libspnav' 'ptex' 'opensubdiv' 'openvdb' 'log4cplus' 'sdl2' 'embree' 'libharu'
         'draco' 'openpgl')
[[ "${CARCH}" != x86_64 ]] && depends=( ${depends[*]/openimagedenoise/} ) # unavailable for armv7h and i686
[[ "${CARCH}" == armv7h ]] && depends=( ${depends[*]/embree/}           ) # unavailable for armv7h
[[ "${CARCH}" == i686   ]] && depends=( ${depends[*]/jack/pipewire-jack} ) # (arch32) FS32#297: unable to satisfy dependency 'libcelt0.so=2-32' required by jack2
makedepends=('cmake' 'boost' 'mesa' 'git' 'llvm' 'cuda' 'ninja' 'wayland-protocols' 'libxkbcommon'
             'libdecor')
makedepends=( ${makedepends[*]/cuda/} ) # non-free
[[ "${CARCH}" == i686 ]] && makedepends+=( boost178-libs clang13 )
makedepends+=( libepoxy ) # FIXME: Could NOT find Epoxy (missing: Epoxy_LIBRARY Epoxy_INCLUDE_DIR)
optdepends=('libdecor: wayland support')
options=(!strip)
source=("git+https://git.blender.org/blender.git#tag=v$pkgver"
        "git+https://git.blender.org/blender-addons.git"
        "git+https://git.blender.org/blender-addons-contrib.git"
        "git+https://git.blender.org/blender-translations.git"
        "git+https://git.blender.org/blender-dev-tools.git"
        https://developer.download.nvidia.com/redist/optix/v7.5/OptiX-7.5-Include.zip
        force-draco1.patch
        force-draco2.patch)
source=( ${source[*]/*optix*/dummy-source} ) # non-free
source_i686=(no-sse2.patch
             blender-idprop_create-static-assert-float.patch)
sha512sums=('SKIP'
            'SKIP'
            'SKIP'
            'SKIP'
            'SKIP'
            'SKIP' # dummy-source for non-free optix
            'e239da4f3906f1b54265435181cf770bae3d269c8d915df9a73861e6ee71ec70bf2339426e7c81a91e5a567273b3b3742d7a99feefd3398d821b26e1ff3a56d0'
            '527ab66e5eace777de0043c1ca5787a488f6471450ce67fd6d08137ad0ef56177bc0c17696f30a5fca23fa55d8ca9c3f30cb7b17550dba2dbd8e89ca0b361990')
sha512sums_i686=('87da2bedb90af6dee559ef9d1eb83262ba75fb412aba83dcb2b88fe9c0740ff75ad336331033fec7a14ad6ecc3dd70f8f4742f147594e8dc530197dd51922c01'
                 '36b98ec7e53402909a9e531c30b444b1afc22cc597c5bb3393c73862929dcc6275b00a53de6171a81af3c8804d233359d2e797886d0b776e7a9b29b23ce24e3b')


_version_constraint() # (dep_pkgname [precision])
{
  Log() { [[ "${FUNCNAME[2]}" == package ]] && echo "$@" >&2 || : ; }


  local dep_pkgname=$1
  declare -i req_precision=$2
  local full_version=$(pacman -S --print-format='%v' ${dep_pkgname} 2> /dev/null | tail -n 1)
  local n_dots=$(tmp=${full_version%-*} ; tmp=${tmp//[^\.]} ; echo "${#tmp}" ;)
  local def_precision=$(( n_dots + 1 ))
  local is_prec_valid=$(( req_precision > 0 && req_precision <= def_precision ))
  local precision=$((( is_prec_valid )) && echo ${req_precision} || echo ${def_precision})
  local pkgver_rx='[0-9A-Za-z_]+'
  pkgver_rx=$(sed 's|\]|\+]|' <<<${pkgver_rx}) # according to the wiki, '+' is not allowed,
                                               # but some pkgver have it (eg: 5.15.10+kde+r130)
  local subver_rx='\.'${pkgver_rx}
  local pkgrel_rx='[0-9]+'
  local garbage_rx='[^0-9].*'
  local capture_rx=${pkgver_rx}
  for (( n_dots=1 ; n_dots < precision ; ++n_dots )) ; do capture_rx+=${subver_rx} ; done ;
  local version pkgrel has_dot_char version_min version_max constraint_string
  declare -i subver subver_inc pkgrel_inc

  if   [[ "${full_version}" =~ ^(${capture_rx})(${subver_rx})*-(${pkgrel_rx}).*$ ]]
  then version=${BASH_REMATCH[1]} # pkgver cut to the requested precision
       #unused=${BASH_REMATCH[2]} # discarded pkgver segments
       pkgrel=${BASH_REMATCH[3]}  # pkgrel with non-numerics right-trimmed
       has_dot_char=$([[ "${version}" =~ \. ]] ; echo $(( ! $? )) ; )
       subver=$(sed "s|${garbage_rx}||" <<<${version##*.}) # right-trim from any non-numeric
       version=$( (( has_dot_char )) && echo ${version%.*}.${subver} || echo ${subver} )
       subver_inc=$(( subver + 1 ))
       pkgrel_inc=$(( pkgrel + 1 ))
       version_min=$(   (( ! is_prec_valid    )) && echo ${full_version%-*}-${pkgrel} || \
                                                    echo ${version}                      )
       version_max=$( ( (( ! is_prec_valid    )) && echo ${full_version%-*}-${pkgrel_inc} ) || \
                      ( [[ "${version}" =~ \. ]] && echo ${version%.*}.${subver_inc}      ) || \
                                                    echo ${subver_inc}                         )
       constraint_string="${dep_pkgname}>=${version_min} ${dep_pkgname}<${version_max}"

       Log "Applied version constraint: '${constraint_string}'"
  else Log "ERROR: in _version_constraint() parsing: dep_pkgname='${dep_pkgname}' full_version='${full_version}'"
       exit 1
  fi

  unset -f Log

  echo -n "${constraint_string}"
}


prepare() {
  cd "$pkgname"

  git submodule init
  git config submodule."release/scripts/addons".url "${srcdir}/blender-addons"
  git config submodule."release/scripts/addons_contrib".url "${srcdir}/blender-addons-contrib"
  git config submodule."release/datafiles/locale".url "${srcdir}/blender-translations"
  git config submodule."source/tools".url "${srcdir}/blender-dev-tools"
  git -c protocol.file.allow=always submodule update
  git submodule foreach git checkout v${pkgver}


  ## technical patching ##

  # fix build with boost 1.81.0
  git format-patch -1 --stdout 79837c5ed4b5 | patch -Np1

  patch -p1 -i "$srcdir"/force-draco1.patch
  patch -p1 -d release/scripts/addons -i "$srcdir"/force-draco2.patch

  # arch-specific technical patching
  case "${CARCH}" in
  armv7h)
    ;;
  i686)
    patch -Np1 -i "$srcdir"/no-sse2.patch

    # float_t is a long double on 32-bit, but it's a primitive in all cases anyway
    # (seems to be in a part of the blendkernel on i686 only..)
    patch -Np1 -i "$srcdir"/blender-idprop_create-static-assert-float.patch


    # FIXME: error: implicit declaration of function ‘atomic_add_and_fetch_uint64’;
    #               did you mean ‘atomic_add_and_fetch_uint32’? [-Werror=implicit-function-declaration]
    #               this is known upstream
    local sed_cmd='s| atomic_add_and_fetch_uint64(| atomic_add_and_fetch_uint32(|'
    local target_file=source/blender/blenlib/intern/session_uuid.c
    sed -i "${sed_cmd}" ${target_file} ; ! grep ' atomic_add_and_fetch_uint64(|' ${target_file} ;

    # FIXME: intern/cycles/kernel/../util/transform_inverse.h:15:9: error: ‘ssef’ does not name a type
    #        -- SSE2 SIMD instructions enabled
    sed_cmd='s|if(NOT DEFINED SUPPORT_SSE2_BUILD|& AND FALSE|'
    target_file=build_files/cmake/macros.cmake
    sed -i "${sed_cmd}" ${target_file} ; grep 'if(NOT DEFINED SUPPORT_SSE2_BUILD AND FALSE' ${target_file} ;
    # the above change corrects 'SSE2 SIMD instructions enabled'; but the original 'ssef' error persists
    sed_cmd='s|#  set(COMPILER_SSE2_FLAG)|  unset(COMPILER_SSE2_FLAG)|'
    target_file=CMakeLists.txt
    sed -i "${sed_cmd}" ${target_file} ; ! grep '#  set(COMPILER_SSE2_FLAG)' ${target_file} ;
    # the original 'ssef' error persists - fixed by adding pkgver=3.1.2 and makedepends+=( boost178-libs clang13 )
    # but then fails with: /usr/lib/gcc/i686-pc-linux-gnu/12.2.0/include/emmintrin.h:1586:1: error: inlining failed in call to ‘always_inline’ ‘__m128 _mm_castsi128_ps(__m128i)’: target specific option mismatch
    # that is the same error as the recent mozilla - the option --disable-webrtc fix that; but that does not apply to blender
    ;;
  x86_64)
    ;;
  esac


  ## libre patching ##

  # set OS type string
  sed -i 's|BUILD_PLATFORM;|"GNU/Linux-libre";|' 'source/creator/buildinfo.c'
}

get_pyver() {
  python -c 'import sys; print(str(sys.version_info[0]) + "." + str(sys.version_info[1]))'
}

build() {
  cd "$pkgname"

  local PYTHON_VER="$(get_pyver)"

  # libre configuration
  local _parabola_opts=( -DWITH_CYCLES_CUDA_BINARIES=OFF \
                         -DWITH_CYCLES_DEVICE_CUDA=OFF   \
                         -DWITH_CYCLES_DEVICE_OPTIX=OFF  )
  # arch-specific configuration
  case "${CARCH}" in
  'armv7h') _parabola_opts+=( -DWITH_CYCLES_EMBREE=OFF   ) ;;
  'i686'  ) _parabola_opts+=( -DWITH_RAYOPTIMIZATION=OFF ) ;;
  esac

  # FIXME: /usr/lib/gcc/i686-pc-linux-gnu/12.2.0/include/emmintrin.h:1586:1: error: inlining failed in call to ‘always_inline’ ‘__m128 _mm_castsi128_ps(__m128i)’: target specific option mismatch
  [[ "${CARCH}" == 'i686'   ]] && _parabola_opts+=( DWITH_CYCLES=OFF ) # did not help

  cmake \
    -Bbuild \
    -GNinja \
    -Cbuild_files/cmake/config/blender_release.cmake \
    -C precache \
    ${_parabola_opts[@]} \
    -DCMAKE_INSTALL_PREFIX=/usr \
    -DCMAKE_BUILD_TYPE=Release \
    -DWITH_INSTALL_PORTABLE=OFF \
    -DWITH_PYTHON_INSTALL=OFF \
    -DPYTHON_VERSION="$PYTHON_VER" \
    -DPYTHON_LIBPATH=/usr/lib \
    -DPYTHON_LIBRARY="python$PYTHON_VER" \
    -DPYTHON_INCLUDE_DIRS="/usr/include/python$PYTHON_VER" \
    -DCMAKE_CXX_FLAGS="-I /usr/include/python$PYTHON_VER"
  cmake --build build
}

package() {
  cd "$pkgname"

  # pin to tightly-coupled dependency versions
  # NOTE: indirect sodeps may still be unsatisfyable:
  #       libboost_filesystem.so <- openimageio,
  #       libboost_thread.so     <- openshadinglanguage,
  #       libboost_iostreams.so  <- openvdb
  depends+=( libboost_locale.so )
  depends=( ${depends[*]/opencolorio/}         $(_version_constraint opencolorio         2) ) # eg: libOpenColorIO.so.2.1
  depends=( ${depends[*]/openexr/}             $(_version_constraint openexr             2) ) # eg: libHalf.so.12
  depends=( ${depends[*]/openimageio/}         $(_version_constraint openimageio         2) ) # eg: libOpenImageIO.so.2.0
  depends=( ${depends[*]/openshadinglanguage/} $(_version_constraint openshadinglanguage 2) ) # eg: liboslcomp.so.1.10
  depends=( ${depends[*]/opensubdiv/}          $(_version_constraint opensubdiv          3) ) # eg: libosdGPU.so.3.3.3
  depends=( ${depends[*]/openvdb/}             $(_version_constraint openvdb             2) ) # eg: libopenvdb.so.6.2
  depends=( ${depends[*]/python/}              $(_version_constraint python              2) ) # eg: libpython3.6.so.1.0

  DESTDIR="${pkgdir}" cmake --install build
  install -Dm755 release/bin/blender-softwaregl "${pkgdir}/usr/bin/blender-softwaregl"
  python -m compileall "${pkgdir}/usr/share/blender"
  python -O -m compileall "${pkgdir}/usr/share/blender"

  install -Dm644 release/freedesktop/org.blender.Blender.appdata.xml "${pkgdir}/usr/share/metainfo/org.blender.Blender.appdata.xml"

  # Manually install additional scripts (See FS#69351)
  cp -r release/scripts/addons_contrib/* "${pkgdir}"/usr/share/blender/3*/scripts/addons_contrib/

  # Manually install draco bindings (See FS#73415)
  mkdir -p "${pkgdir}/usr/lib/python$(get_pyver)"/
  mv "${pkgdir}"/usr/share/blender/3*/python/lib/* "${pkgdir}"/usr/lib/
  rm -r "${pkgdir}"/usr/share/blender/3*/python
}
