# -*- coding: utf-8; mode: tcl; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:fenc=utf-8:ft=tcl:et:sw=4:ts=4:sts=4

PortSystem          1.0
PortGroup           github 1.0

name                godot
categories          games graphics multimedia
platforms           darwin
license             MIT
maintainers         @jasonliu--

homepage            https://${name}engine.org
description         cross-platform 2-D and 3-D game development \
                    environment
long_description    Godot Engine is a cross-platform game engine for \
                    creating 2-D and 3-D games. Godot aims to offer a \
                    fully integrated game development environment. It \
                    provides a comprehensive set of common tools, and \
                    games can be exported to a number of target \
                    platforms, including major desktop platforms \
                    (Linux, macOS, Windows), as well as mobile \
                    (Android, iOS) and web-based (HTML5) platforms.

if {$subport eq ${name}} {
    PortGroup legacysupport 1.1

    github.setup    ${name}engine ${name} 3.5.3 "" -stable
    revision        1

    github.tarball_from archive

    checksums       rmd160  973ffdca8affa8eba221c1cb9fbfe45d837d2aac \
                    sha256  643366a288fc529564d8bb42a42093d72071c8186f57ff03cae6d5929f81bd1d \
                    size    56501173

    # Godot fails to build for Xcode Clang < 802,
    # but builds fine using MacPorts Clang
    compiler.blacklist-append {clang < 802}

    legacysupport.newest_darwin_requires_legacy 15
    # Using macports-libcxx is needed in order to lower the minimum
    # macOS version specified in -mmacosx-version-min. Otherwise the
    # compile will fail, complaining that 'shared_time_mutex' was
    # introduced in macOS 10.12.
    legacysupport.use_mp_libcxx yes

    patchfiles-append \
                    patch-miniupnpc-18.diff
}

subport ${name}-3.2 {
    PortGroup       obsolete 1.0

    version         3.2.3
    revision        3
    replaced_by     ${name}

    # 2021-12-09: I believe that it would be safe to completely remove
    # this subport without needing to wait for the traditional one-year
    # waiting period. The only reason I originally created this subport
    # was because Godot 3.3+ was failing to compile for macOS <= 10.10.
    # Now that we have been able to get the source code to compile and
    # run successfully on older macOSes, this subport is no longer
    # necessary. In addition, based on the statistics, it looks like
    # no one has ever installed this subport.
}

# Note: We continue to keep the subport syntax, because we will need to
# use it in the future. When Godot 4 is released, we will still need to
# maintain a Godot 3.x subport, because Godot Engine is being rewritten
# to use Vulkan in Godot 4. This means that Godot 4 will only have the
# possibility of being executable back to macOS 10.11, because MoltenVK
# requires Metal, which was introduced in macOS 10.11.

if {${os.platform} eq "darwin" && ${os.major} <= 11} {
    known_fail      yes
    pre-fetch {
        ui_error "${name} @${version} requires macOS 10.8 or later."
        return -code error "incompatible macOS version"
    }
}

depends_build-append    port:scons \
                        port:yasm \
                        port:pkgconfig
depends_lib-append      port:freetype \
                        port:libpng \
                        port:zlib \
                        port:zstd \
                        port:libtheora \
                        port:libogg \
                        port:libvorbis \
                        port:libopus \
                        port:opusfile \
                        port:miniupnpc \
                        port:pcre2
# Some dependencies that are available in MacPorts can't be used. See
# the "Important note" in the build.args-append section below.
#                       port:bullet \
#                       port:assimp \
#                       port:libenet \
#                       port:squish \
#                       port:libvpx \
#                       port:webp \
#                       port:mbedtls \
#                       port:minizip \
#                       port:embree

patchfiles-append       add-external_libs-support.diff \
                        configure-macports-compiler.diff

if {$subport eq "${name}-3.2" && \
    ${os.platform} eq "darwin" && ${os.major} <= 15} \
{
    patchfiles-append legacy-osx-defines.diff
}

if {$subport eq ${name} && ${os.platform} eq "darwin"} {
    # On old versions of macOS <= 10.10, the build seems to think that
    # the value of the preprocessor macro MAC_OS_X_VERSION_MAX_ALLOWED
    # is >= 101200, which is supposed to correspond to macOS 10.12.
    # As discussed in GitHub PR #12269
    # (https://github.com/macports/macports-ports/pull/12269),
    # something is causing the preprocessor to think that values such as
    # 101000, 1090, etc. are >= 101200, which in turn is causing the
    # compiler to try to #include <os/log.h>. This causes a compile
    # error on older macOSes, because this header only exists starting
    # in the macOS 10.12 SDK.
    #
    # This patch file works around the issue by deleting the problematic
    # code. If, in the future, we can discover the real reason why the
    # numerical comparison is behaving incorrectly, and find a fix, then
    # it might be possible to eliminate the need for this patch file.
    if {${os.major} < 15} {
        patchfiles-append macosx-version-log_h-workaround.diff
    }

    # The upstream source code now uses @available, which was introduced
    # to Objective-C starting in Xcode 9. It allows code that has been
    # compiled on newer systems to run on older systems, but it does not
    # have the ability to hide any code from being seen by the compiler.
    # This is causing compiler errors on older macOSes, because
    # 'NSWorkspaceOpenConfiguration' was introduced in macOS 10.15. So,
    # if we are trying to build from source on macOS older than 10.15,
    # we need to modify the upstream source to use a traditional
    # availability macro instead of @available.
    #
    # References:
    # * python/py-matplotlib/files/patch-v34-src-macosx.m.diff in the
    #   py-matplotlib port.
    # * https://github.com/macports/macports-ports/commit/b07e0eb6440b1499bfd2157e19db86fc79984471#comments
    if {${os.major} < 19} {
        patchfiles-append patch-available2macro-os_osx.diff
    }

    # Same as the above, except in a different file and for
    # macOS < 10.14.
    if {${os.major} < 18} {
        patchfiles-append patch-available2macro-camera_osx.diff
    }
}

post-patch {
    reinplace "/yasm_paths =/a\\
\\      \"${prefix}/bin/yasm\",\\
" \
        ${worksrcpath}/modules/webm/libvpx/SCsub

    # Between version 3.5.1 and 3.5.2, the Godot devs modified the
    # #include directives for miniupnpc-related headers. Things were
    # working fine before, and the changes break compilation. The
    # following reinplace restores the directives to what they were in
    # 3.5.1.
    reinplace -E \
        {s,((miniupnpc|miniwget|upnpcommands)\.h),miniupnpc/\1,} \
        ${worksrcpath}/modules/upnp/upnp.h \
        ${worksrcpath}/modules/upnp/upnp.cpp \
        ${worksrcpath}/modules/upnp/upnp_device.cpp
}

if {$subport eq ${name} && \
    ${os.platform} eq "darwin" && ${os.major} <= 15} \
{
    post-patch {
        # Tell the build to use macports-libcxx. We have to do it
        # manually here in the Portfile, because SCons ignores most/all
        # of the environment variables set by MacPorts.
        reinplace "/LINKFLAGS.*isysroot.*MACOS_SDK_PATH/a\\
\\
\\        env.Append(CXXFLAGS=\[\"-nostdinc++\", \"-I${prefix}/include/libcxx/v1\"\])\\
\\        env.Append(LINKFLAGS=\[\"-L${prefix}/lib/libcxx\"\])\\
" \
            ${worksrcpath}/platform/osx/detect.py

        # Lower the minimum macOS version allowed to launch the app
        reinplace \
            "/mmacosx-version-min=10\.12/s/10\.12/${macosx_deployment_target}/" \
            ${worksrcpath}/platform/osx/detect.py
        foreach f [list "osx_tools" "osx_template"] {
            reinplace "s/10\.12/${macosx_deployment_target}/" \
                ${worksrcpath}/misc/dist/${f}.app/Contents/Info.plist
        }

        # The following tests for the case where the macOS 10.12 SDK is
        # installed on a macOS 10.11 machine. If so, then we don't add
        # the AppKit wrapper header.
        set sdks_dir ${developer_dir}/Platforms/MacOSX.platform/Developer/SDKs
        set add_appkit_wrapper yes
        if {![catch {file lstat $sdks_dir/MacOSX10.12.sdk finfo}]} {
            set add_appkit_wrapper no
        }

        if {$add_appkit_wrapper} {
            # Remove the existing AppKit redefines from Godot's source
            # code, so that we can use our AppKit wrapper file instead.
            reinplace "/define NSEventMaskAny/i\\
#define APPKIT_REDEFINES_HAVE_BEEN_REMOVED_BY_MACPORTS\\
" \
                ${worksrcpath}/platform/osx/os_osx.mm
            reinplace {/define NSEventMaskAny/,/define NSWindowStyleMaskBorderless/d} \
                ${worksrcpath}/platform/osx/os_osx.mm

            # Add AppKit wrapper header to compiler library paths
            reinplace "/CCFLAGS.*error=return-type/a\\
\\
\\    env.Prepend(CCFLAGS=\[\"-isystem\", \"${filespath}/old_appkit_compat\"\])\\
" \
                ${worksrcpath}/SConstruct
        }
    }
}

use_configure       no
use_xcode           yes

build.cmd           ${prefix}/bin/scons
build.env-append    BUILD_NAME=macports_build
build.target        platform=osx arch=${build_arch} \
                    target=release_debug verbose=yes warnings=extra
build.args-append   builtin_freetype=no \
                    builtin_libpng=no \
                    builtin_zlib=no \
                    builtin_zstd=no \
                    builtin_libtheora=no \
                    builtin_libogg=no \
                    builtin_libvorbis=no \
                    builtin_opus=no \
                    builtin_miniupnpc=no \
                    builtin_pcre2=no
# Important note: I am only turning off built-in for libraries that
# don't have any references to "godot" in them (i.e.,
# 'grep -Ri godot ${worksrcpath}/thirdparty' doesn't return anything).
# The other libraries have some sort of modification that has been made
# by the Godot devs.
#                   builtin_assimp=no \
#                   builtin_enet=no \
#                   builtin_squish=no \
#                   builtin_libvpx=no \
#                   builtin_libwebp=no \
#                   builtin_mbedtls=no \
#                   builtin_embree=no

compiler.cxx_standard   2014
# Configure the compiler
if {[string match macports-clang-* ${configure.compiler}]} {
    set clang_v [
        string range ${configure.compiler} [
            string length macports-clang-
        ] end
    ]
    build.args-append       macports_clang=${clang_v}
    build.env-append        MACPORTS_PREFIX=${prefix}
}

destroot {
    if {$subport eq "${name}-3.2"} {
        set app_name "Godot 3.2"
        set cliname $subport
    } else {
        set app_name "Godot"
        set cliname ${name}
    }
    copy ${worksrcpath}/misc/dist/osx_tools.app \
         ${destroot}${applications_dir}/${app_name}.app
    xinstall -d ${destroot}${applications_dir}/${app_name}.app/Contents/MacOS
    move ${worksrcpath}/bin/${name}.osx.opt.tools.${build_arch} \
         ${destroot}${applications_dir}/${app_name}.app/Contents/MacOS/Godot
    ln -s ${applications_dir}/${app_name}.app/Contents/MacOS/Godot \
       ${destroot}${prefix}/bin/$cliname
}

if {$subport eq ${name}} {
    livecheck.regex releases/tag/(\\d+\\.\\d+(?:\\.\\d+)*)-stable
} else {
    livecheck.type  none
}
