diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 5548b9ff1d..3cb21991f5 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -44,6 +44,11 @@ elseif(MACOSX OR IOS) cc_set_if_undefined(CC_USE_GLES2 OFF) endif() +set(CC_USE_GLES3 ${CC_USE_GLES3} CACHE INTERNAL "") +set(CC_USE_GLES2 ${CC_USE_GLES2} CACHE INTERNAL "") +set(CC_USE_VULKAN ${CC_USE_VULKAN} CACHE INTERNAL "") +set(CC_USE_METAL ${CC_USE_METAL} CACHE INTERNAL "") + if(USE_SERVER_MODE) set(CC_USE_VULKAN OFF) set(CC_USE_GLES3 OFF) @@ -135,6 +140,10 @@ endif() include(${CMAKE_CURRENT_LIST_DIR}/external/CMakeLists.txt) +if(ANDROID AND SWAPPY_ENABLED) + add_definitions(-DCC_SWAPPY_ENABLED) +endif() + ##### audio if(USE_AUDIO) cocos_source_files( diff --git a/native/cocos/platform/android/AndroidPlatform.cpp b/native/cocos/platform/android/AndroidPlatform.cpp index 1f3a23084c..5744c8fe7d 100644 --- a/native/cocos/platform/android/AndroidPlatform.cpp +++ b/native/cocos/platform/android/AndroidPlatform.cpp @@ -74,4 +74,12 @@ void AndroidPlatform::pollEvent() { _jniNativeGlue->flushTasksOnGameThread(); } -}; // namespace cc \ No newline at end of file +void *AndroidPlatform::getActivity() { + return _jniNativeGlue->getActivity(); +} + +void *AndroidPlatform::getEnv() { + return _jniNativeGlue->getEnv(); +} + +}; // namespace cc diff --git a/native/cocos/platform/android/AndroidPlatform.h b/native/cocos/platform/android/AndroidPlatform.h index 88f734f56a..b9b291e0f8 100644 --- a/native/cocos/platform/android/AndroidPlatform.h +++ b/native/cocos/platform/android/AndroidPlatform.h @@ -36,10 +36,11 @@ public: int32_t run(int argc, const char** argv) override; int getSdkVersion() const override; int32_t loop() override; - + void* getActivity(); + void* getEnv(); private: void waitWindowInitialized(); JniNativeGlue* _jniNativeGlue; }; -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/cocos/platform/android/java/src/com/google/androidgamesdk/ChoreographerCallback.java b/native/cocos/platform/android/java/src/com/google/androidgamesdk/ChoreographerCallback.java new file mode 100644 index 0000000000..64c8db682d --- /dev/null +++ b/native/cocos/platform/android/java/src/com/google/androidgamesdk/ChoreographerCallback.java @@ -0,0 +1,56 @@ +package com.google.androidgamesdk; + +import android.os.Handler; +import android.os.Looper; +import android.view.Choreographer; +import android.util.Log; + + +public class ChoreographerCallback implements Choreographer.FrameCallback { + private static final String LOG_TAG = "ChoreographerCallback"; + private long mCookie; + private LooperThread mLooper; + + private class LooperThread extends Thread { + public Handler mHandler; + + public void run() { + Log.i(LOG_TAG, "Starting looper thread"); + Looper.prepare(); + mHandler = new Handler(); + Looper.loop(); + Log.i(LOG_TAG, "Terminating looper thread"); + } + } + + public ChoreographerCallback(long cookie) { + mCookie = cookie; + mLooper = new LooperThread(); + mLooper.start(); + } + + public void postFrameCallback() { + mLooper.mHandler.post(new Runnable() { + @Override + public void run() { + Choreographer.getInstance().postFrameCallback(ChoreographerCallback.this); + } + }); + } + + public void postFrameCallbackDelayed(long delayMillis) { + Choreographer.getInstance().postFrameCallbackDelayed(this, delayMillis); + } + + public void terminate() { + mLooper.mHandler.getLooper().quit(); + } + + @Override + public void doFrame(long frameTimeNanos) { + nOnChoreographer(mCookie, frameTimeNanos); + } + + public native void nOnChoreographer(long cookie, long frameTimeNanos); + +} diff --git a/native/cocos/platform/android/java/src/com/google/androidgamesdk/GameSdkDeviceInfoJni.java b/native/cocos/platform/android/java/src/com/google/androidgamesdk/GameSdkDeviceInfoJni.java new file mode 100644 index 0000000000..5ba1b5121f --- /dev/null +++ b/native/cocos/platform/android/java/src/com/google/androidgamesdk/GameSdkDeviceInfoJni.java @@ -0,0 +1,55 @@ +package com.google.androidgamesdk; + +/** JNI api for getting device information */ +public class GameSdkDeviceInfoJni { + private static Throwable initializationExceptionOrError; + + static { + try { + System.loadLibrary("game_sdk_device_info_jni"); + } catch(Exception exception) { + // Catch SecurityException, NullPointerException (or any potential unchecked exception) + // as we don't want to crash the app if the library failed to load. + initializationExceptionOrError = exception; + } catch(Error error) { + // Catch UnsatisfiedLinkError (or any potential unchecked error) + // as we don't want to crash the app if the library failed to load. + initializationExceptionOrError = error; + } + } + + /** + * Returns a byte array, which is a serialized proto containing device information, or + * null if the native library "game_sdk_device_info_jni" could not be loaded. + * + * @return Optional with the serialized byte array, representing game sdk device info with errors, + * or null. + */ + public static byte[] tryGetProtoSerialized() { + if (initializationExceptionOrError != null) { + return null; + } + + return getProtoSerialized(); + } + + + /** + * Returns the exception or error that was caught when trying to load the library, if any. + * Otherwise, returns null. + * + * @return The caught Throwable or null. + */ + public static Throwable getInitializationExceptionOrError() { + return initializationExceptionOrError; + } + + /** + * Returns a byte array, which is a serialized proto. + * + * @return serialized byte array, representing game sdk device info with errors. + */ + private static native byte[] getProtoSerialized(); + + private GameSdkDeviceInfoJni() {} +} diff --git a/native/cocos/platform/android/java/src/com/google/androidgamesdk/SwappyDisplayManager.java b/native/cocos/platform/android/java/src/com/google/androidgamesdk/SwappyDisplayManager.java new file mode 100644 index 0000000000..02f09feb3a --- /dev/null +++ b/native/cocos/platform/android/java/src/com/google/androidgamesdk/SwappyDisplayManager.java @@ -0,0 +1,208 @@ +package com.google.androidgamesdk; + +import android.annotation.TargetApi; +import android.app.Activity; +import android.content.ComponentName; +import android.content.pm.ActivityInfo; +import android.content.pm.PackageManager; +import android.hardware.display.DisplayManager; +import android.os.Build; +import android.os.Handler; +import android.os.Looper; +import android.util.Log; +import android.view.Display; +import android.view.Window; +import android.view.WindowManager; + +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +import static android.app.NativeActivity.META_DATA_LIB_NAME; + +public class SwappyDisplayManager implements DisplayManager.DisplayListener { + final private String LOG_TAG = "SwappyDisplayManager"; + final private boolean DEBUG = false; + final private long ONE_MS_IN_NS = 1000000; + final private long ONE_S_IN_NS = ONE_MS_IN_NS * 1000; + + private long mCookie; + private Activity mActivity; + private WindowManager mWindowManager; + private Display.Mode mCurrentMode; + + private LooperThread mLooper; + + private class LooperThread extends Thread { + public Handler mHandler; + private Lock mLock = new ReentrantLock(); + private Condition mCondition = mLock.newCondition(); + + @Override + public void start() { + mLock.lock(); + super.start(); + try { + mCondition.await(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + mLock.unlock(); + + } + + public void run() { + Log.i(LOG_TAG, "Starting looper thread"); + + mLock.lock(); + Looper.prepare(); + mHandler = new Handler(); + mCondition.signal(); + mLock.unlock(); + + Looper.loop(); + + Log.i(LOG_TAG, "Terminating looper thread"); + } + } + + @TargetApi(Build.VERSION_CODES.M) + private boolean modeMatchesCurrentResolution(Display.Mode mode) { + return mode.getPhysicalHeight() == mCurrentMode.getPhysicalHeight() && + mode.getPhysicalWidth() == mCurrentMode.getPhysicalWidth(); + + } + + public SwappyDisplayManager(long cookie, Activity activity) { + // Load the native library for cases where an NDK application is running + // without a java componenet + try { + ActivityInfo ai = activity.getPackageManager().getActivityInfo( + activity.getIntent().getComponent(), PackageManager.GET_META_DATA); + if (ai.metaData != null) { + String nativeLibName = ai.metaData.getString(META_DATA_LIB_NAME); + if (nativeLibName != null) { + System.loadLibrary(nativeLibName); + } + } + } catch (java.lang.Throwable e) { + Log.e(LOG_TAG, e.getMessage()); + } + + mCookie = cookie; + mActivity = activity; + + mWindowManager = mActivity.getSystemService(WindowManager.class); + Display display = mWindowManager.getDefaultDisplay(); + mCurrentMode = display.getMode(); + updateSupportedRefreshRates(display); + + // Register display listener callbacks + DisplayManager dm = mActivity.getSystemService(DisplayManager.class); + + synchronized(this) { + mLooper = new LooperThread(); + mLooper.start(); + dm.registerDisplayListener(this, mLooper.mHandler); + } + } + + private void updateSupportedRefreshRates(Display display) { + Display.Mode[] supportedModes = display.getSupportedModes(); + int totalModes = 0; + for (int i = 0; i < supportedModes.length; i++) { + if (!modeMatchesCurrentResolution(supportedModes[i])) { + continue; + } + totalModes++; + } + + long[] supportedRefreshPeriods = new long[totalModes]; + int[] supportedDisplayModeIds = new int[totalModes]; + totalModes = 0; + for (int i = 0; i < supportedModes.length; i++) { + if (!modeMatchesCurrentResolution(supportedModes[i])) { + continue; + } + supportedRefreshPeriods[totalModes] = + (long) (ONE_S_IN_NS / supportedModes[i].getRefreshRate()); + supportedDisplayModeIds[totalModes] = supportedModes[i].getModeId(); + totalModes++; + + } + // Call down to native to set the supported refresh rates + nSetSupportedRefreshPeriods(mCookie, supportedRefreshPeriods, supportedDisplayModeIds); + } + + public void setPreferredDisplayModeId(final int modeId) { + mActivity.runOnUiThread(new Runnable() { + @Override + public void run() { + Window w = mActivity.getWindow(); + WindowManager.LayoutParams l = w.getAttributes(); + if (DEBUG) { + Log.v(LOG_TAG, "set preferredDisplayModeId to " + modeId); + } + l.preferredDisplayModeId = modeId; + + + w.setAttributes(l); + } + }); + } + + public void terminate() { + mLooper.mHandler.getLooper().quit(); + } + + @Override + public void onDisplayAdded(int displayId) { + + } + + @Override + public void onDisplayRemoved(int displayId) { + + } + + @Override + public void onDisplayChanged(int displayId) { + synchronized(this) { + Display display = mWindowManager.getDefaultDisplay(); + float newRefreshRate = display.getRefreshRate(); + Display.Mode newMode = display.getMode(); + boolean resolutionChanged = + (newMode.getPhysicalWidth() != mCurrentMode.getPhysicalWidth()) | + (newMode.getPhysicalHeight() != mCurrentMode.getPhysicalHeight()); + boolean refreshRateChanged = (newRefreshRate != mCurrentMode.getRefreshRate()); + mCurrentMode = newMode; + + if (resolutionChanged) { + updateSupportedRefreshRates(display); + } + + if (refreshRateChanged) { + final long appVsyncOffsetNanos = display.getAppVsyncOffsetNanos(); + final long vsyncPresentationDeadlineNanos = + mWindowManager.getDefaultDisplay().getPresentationDeadlineNanos(); + + final long vsyncPeriodNanos = (long)(ONE_S_IN_NS / newRefreshRate); + final long sfVsyncOffsetNanos = + vsyncPeriodNanos - (vsyncPresentationDeadlineNanos - ONE_MS_IN_NS); + + nOnRefreshPeriodChanged(mCookie, + vsyncPeriodNanos, + appVsyncOffsetNanos, + sfVsyncOffsetNanos); + } + } + } + + private native void nSetSupportedRefreshPeriods(long cookie, + long[] refreshPeriods, + int[] modeIds); + private native void nOnRefreshPeriodChanged(long cookie, + long refreshPeriod, + long appOffset, + long sfOffset); +} diff --git a/native/cocos/platform/android/jni/JniCocosActivity.cpp b/native/cocos/platform/android/jni/JniCocosActivity.cpp index 2e72db6b50..4310673c3f 100644 --- a/native/cocos/platform/android/jni/JniCocosActivity.cpp +++ b/native/cocos/platform/android/jni/JniCocosActivity.cpp @@ -51,6 +51,9 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosActivity_onCreateNative(JNIEnv *e JNI_NATIVE_GLUE()->setResourceManager(AAssetManager_fromJava(env, assetMgr)); cc::FileUtilsAndroid::setassetmanager(AAssetManager_fromJava(env, assetMgr)); JNI_NATIVE_GLUE()->start(0, nullptr); + + JNI_NATIVE_GLUE()->setEnvGetter(cc::JniHelper::getEnv); + JNI_NATIVE_GLUE()->setActivityGetter(cc::JniHelper::getActivity); } //NOLINTNEXTLINE diff --git a/native/cocos/platform/android/libcocos2dx/proguard-rules.pro b/native/cocos/platform/android/libcocos2dx/proguard-rules.pro index 8029d540bc..420eb53fe9 100644 --- a/native/cocos/platform/android/libcocos2dx/proguard-rules.pro +++ b/native/cocos/platform/android/libcocos2dx/proguard-rules.pro @@ -8,3 +8,6 @@ # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: +-keep public class com.google.androidgamesdk.ChoreographerCallback { *; } +-keep public class com.google.androidgamesdk.SwappyDisplayManager { *; } +-keep public class com.google.androidgamesdk.GameSdkDeviceInfoJni { *; } diff --git a/native/cocos/platform/java/jni/glue/JniNativeGlue.cpp b/native/cocos/platform/java/jni/glue/JniNativeGlue.cpp index 3b7fe6f875..b458a71246 100644 --- a/native/cocos/platform/java/jni/glue/JniNativeGlue.cpp +++ b/native/cocos/platform/java/jni/glue/JniNativeGlue.cpp @@ -62,6 +62,22 @@ void JniNativeGlue::setWindowHandler(NativeWindowType* window) { } } +void JniNativeGlue::setActivityGetter(std::function getter) { + _activityGetter = std::move(getter); +} + +void* JniNativeGlue::getActivity() { + return _activityGetter ? _activityGetter() : nullptr; +} + +void JniNativeGlue::setEnvGetter(std::function getter) { + _envGetter = std::move(getter); +} + +void* JniNativeGlue::getEnv() { + return _envGetter ? _envGetter() : nullptr; +} + void JniNativeGlue::setResourceManager(ResourceManagerType* resourceManager) { _resourceManager = resourceManager; } @@ -293,4 +309,4 @@ int32_t JniNativeGlue::getHeight() const { return height; } -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/cocos/platform/java/jni/glue/JniNativeGlue.h b/native/cocos/platform/java/jni/glue/JniNativeGlue.h index e1cf39387c..6270fab1a1 100644 --- a/native/cocos/platform/java/jni/glue/JniNativeGlue.h +++ b/native/cocos/platform/java/jni/glue/JniNativeGlue.h @@ -25,6 +25,7 @@ #pragma once +#include #include #include #include "base/Macros.h" @@ -45,6 +46,9 @@ using ResourceManagerType = ResourceManager; using NativeWindowType = NativeLayer; #endif +using NativeActivity = void*; //jobject +using NativeEnv = void*; //jnienv + namespace cc { class IEventDispatch; @@ -69,6 +73,12 @@ public: void setWindowHandler(NativeWindowType* window); NativeWindowType* getWindowHandler(); + void setActivityGetter(std::function); + void* getActivity(); + + void setEnvGetter(std::function); + void* getEnv(); + void setResourceManager(ResourceManagerType* resourceManager); ResourceManagerType* getResourceManager(); @@ -125,6 +135,9 @@ private: JniCommand _appState{JniCommand::JNI_CMD_UNKNOW}; IEventDispatch* _eventDispatcher{nullptr}; std::unique_ptr _messagePipe{nullptr}; + + std::function _envGetter; + std::function _activityGetter; }; } // namespace cc diff --git a/native/cocos/renderer/gfx-gles2/GLES2GPUContext.cpp b/native/cocos/renderer/gfx-gles2/GLES2GPUContext.cpp index 49b1cfd397..3360930da8 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2GPUContext.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2GPUContext.cpp @@ -25,6 +25,10 @@ #include "GLES2GPUObjects.h" +#if CC_SWAPPY_ENABLED + #include "swappy/swappyGL.h" +#endif + #define FORCE_DISABLE_VALIDATION 1 namespace cc { @@ -287,6 +291,14 @@ void GLES2GPUContext::makeCurrent(const GLES2GPUSwapchain *drawSwapchain, const } void GLES2GPUContext::present(const GLES2GPUSwapchain *swapchain) { +#if CC_SWAPPY_ENABLED + if (swapchain->swappyEnabled) { + //fallback to normal eglswap if swappy_swap failed + if(SwappyGL_swap(eglDisplay, swapchain->eglSurface)) { + return; + } + } +#endif if (_eglCurrentInterval != swapchain->eglSwapInterval) { if (!eglSwapInterval(eglDisplay, swapchain->eglSwapInterval)) { CC_LOG_ERROR("eglSwapInterval() - FAILED."); diff --git a/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h b/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h index f239716a09..21173fe628 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h +++ b/native/cocos/renderer/gfx-gles2/GLES2GPUObjects.h @@ -147,6 +147,9 @@ using GLES2GPUTextureList = vector; class GLES2GPUSwapchain final : public Object { public: +#if CC_SWAPPY_ENABLED + bool swappyEnabled{false}; +#endif EGLSurface eglSurface{EGL_NO_SURFACE}; EGLint eglSwapInterval{0}; GLuint glFramebuffer{0}; diff --git a/native/cocos/renderer/gfx-gles2/GLES2Swapchain.cpp b/native/cocos/renderer/gfx-gles2/GLES2Swapchain.cpp index 993d4950fc..a3c0991f5c 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Swapchain.cpp +++ b/native/cocos/renderer/gfx-gles2/GLES2Swapchain.cpp @@ -28,6 +28,11 @@ #include "GLES2GPUObjects.h" #include "GLES2Texture.h" +#if CC_SWAPPY_ENABLED + #include "platform/android/AndroidPlatform.h" + #include "swappy/swappyGL.h" +#endif + #if (CC_PLATFORM == CC_PLATFORM_ANDROID) #include "android/native_window.h" #elif CC_PLATFORM == CC_PLATFORM_OHOS @@ -58,6 +63,24 @@ void GLES2Swapchain::doInit(const SwapchainInfo& info) { return; } + #if CC_SWAPPY_ENABLED + bool enableSwappy = true; + auto* platform = static_cast(cc::BasePlatform::getPlatform()); + enableSwappy &= SwappyGL_init(static_cast(platform->getEnv()), static_cast(platform->getActivity())); + int32_t fps = cc::BasePlatform::getPlatform()->getFps(); + if (enableSwappy) { + if (!fps) + SwappyGL_setSwapIntervalNS(SWAPPY_SWAP_60FPS); + else + SwappyGL_setSwapIntervalNS(1000000000L / fps); //ns + enableSwappy &= SwappyGL_setWindow(window); + _gpuSwapchain->swappyEnabled = enableSwappy; + } else { + CC_LOG_ERROR("Failed to enable Swappy in current GL swapchain, fallback instead."); + } + + #endif + auto width = static_cast(info.width); auto height = static_cast(info.height); @@ -105,6 +128,12 @@ void GLES2Swapchain::doInit(const SwapchainInfo& info) { void GLES2Swapchain::doDestroy() { if (!_gpuSwapchain) return; +#if CC_SWAPPY_ENABLED + if (_gpuSwapchain->swappyEnabled) { + SwappyGL_destroy(); + } +#endif + CC_SAFE_DESTROY(_depthStencilTexture) CC_SAFE_DESTROY(_colorTexture) @@ -144,6 +173,13 @@ void GLES2Swapchain::doCreateSurface(void* windowHandle) { auto height = static_cast(_colorTexture->getHeight()); CC_UNUSED_PARAM(width); CC_UNUSED_PARAM(height); + +#if CC_SWAPPY_ENABLED + if (_gpuSwapchain->swappyEnabled) { + _gpuSwapchain->swappyEnabled &= SwappyGL_setWindow(window); + } +#endif + #if CC_PLATFORM == CC_PLATFORM_ANDROID ANativeWindow_setBuffersGeometry(window, width, height, nFmt); #elif CC_PLATFORM == CC_PLATFORM_OHOS diff --git a/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp b/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp index a181178837..2cf225a911 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3GPUContext.cpp @@ -25,6 +25,10 @@ #include "GLES3GPUObjects.h" +#if CC_SWAPPY_ENABLED + #include "swappy/swappyGL.h" +#endif + #define FORCE_DISABLE_VALIDATION 1 namespace cc { @@ -295,10 +299,19 @@ void GLES3GPUContext::makeCurrent(const GLES3GPUSwapchain *drawSwapchain, const } void GLES3GPUContext::present(const GLES3GPUSwapchain *swapchain) { +#if CC_SWAPPY_ENABLED + if (swapchain->swappyEnabled) { + // fallback to normal eglswap if swappy swap failed. + if(SwappyGL_swap(eglDisplay, swapchain->eglSurface)) { + return; + } + } +#endif if (_eglCurrentInterval != swapchain->eglSwapInterval) { if (!eglSwapInterval(eglDisplay, swapchain->eglSwapInterval)) { CC_LOG_ERROR("eglSwapInterval() - FAILED."); } + _eglCurrentInterval = swapchain->eglSwapInterval; } EGL_CHECK(eglSwapBuffers(eglDisplay, swapchain->eglSurface)); diff --git a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h index 16d54211dc..36448f1fb8 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h +++ b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h @@ -164,6 +164,9 @@ using GLES3GPUTextureViewList = vector; class GLES3GPUSwapchain final : public Object { public: +#if CC_SWAPPY_ENABLED + bool swappyEnabled{false}; +#endif EGLSurface eglSurface{EGL_NO_SURFACE}; EGLint eglSwapInterval{0}; GLuint glFramebuffer{0}; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp b/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp index 0f2f0d95f2..32519857df 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Swapchain.cpp @@ -28,6 +28,11 @@ #include "GLES3GPUObjects.h" #include "GLES3Texture.h" +#if CC_SWAPPY_ENABLED + #include "platform/android/AndroidPlatform.h" + #include "swappy/swappyGL.h" +#endif + #if (CC_PLATFORM == CC_PLATFORM_ANDROID) #include "android/native_window.h" #elif CC_PLATFORM == CC_PLATFORM_OHOS @@ -58,6 +63,24 @@ void GLES3Swapchain::doInit(const SwapchainInfo& info) { return; } + #if CC_SWAPPY_ENABLED + bool enableSwappy = true; + auto* platform = static_cast(cc::BasePlatform::getPlatform()); + enableSwappy &= SwappyGL_init(static_cast(platform->getEnv()), static_cast(platform->getActivity())); + int32_t fps = cc::BasePlatform::getPlatform()->getFps(); + if (enableSwappy) { + if (!fps) + SwappyGL_setSwapIntervalNS(SWAPPY_SWAP_60FPS); + else + SwappyGL_setSwapIntervalNS(1000000000L / fps); //ns + enableSwappy &= SwappyGL_setWindow(window); + _gpuSwapchain->swappyEnabled = enableSwappy; + } else { + CC_LOG_ERROR("Failed to enable Swappy in current GL swapchain, fallback instead."); + } + + #endif + auto width = static_cast(info.width); auto height = static_cast(info.height); @@ -105,6 +128,12 @@ void GLES3Swapchain::doInit(const SwapchainInfo& info) { void GLES3Swapchain::doDestroy() { if (!_gpuSwapchain) return; +#if CC_SWAPPY_ENABLED + if (_gpuSwapchain->swappyEnabled) { + SwappyGL_destroy(); + } +#endif + CC_SAFE_DESTROY(_depthStencilTexture) CC_SAFE_DESTROY(_colorTexture) @@ -144,6 +173,13 @@ void GLES3Swapchain::doCreateSurface(void* windowHandle) { auto height = static_cast(_colorTexture->getHeight()); CC_UNUSED_PARAM(width); CC_UNUSED_PARAM(height); + +#if CC_SWAPPY_ENABLED + if (_gpuSwapchain->swappyEnabled) { + _gpuSwapchain->swappyEnabled &= SwappyGL_setWindow(window); + } +#endif + #if CC_PLATFORM == CC_PLATFORM_ANDROID ANativeWindow_setBuffersGeometry(window, width, height, nFmt); #elif CC_PLATFORM == CC_PLATFORM_OHOS diff --git a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp index 8dc78dc411..b4895ca17d 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDevice.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKDevice.cpp @@ -49,6 +49,10 @@ #include "gfx-base/SPIRVUtils.h" +#if CC_SWAPPY_ENABLED + #include "swappy/swappyVk.h" +#endif + CC_DISABLE_WARNINGS() #define VMA_IMPLEMENTATION #include "vk_mem_alloc.h" @@ -146,6 +150,25 @@ bool CCVKDevice::doInit(const DeviceInfo & /*info*/) { _gpuDevice->extensions.resize(availableExtensionCount); VK_CHECK(vkEnumerateDeviceExtensionProperties(_gpuContext->physicalDevice, nullptr, &availableExtensionCount, _gpuDevice->extensions.data())); +#if CC_SWAPPY_ENABLED + uint32_t swappyRequiredExtensionCount = 0; + SwappyVk_determineDeviceExtensions(_gpuContext->physicalDevice, availableExtensionCount, + _gpuDevice->extensions.data(), &swappyRequiredExtensionCount, nullptr); + std::vector swappyRequiredExtensions(swappyRequiredExtensionCount); + std::vector swappyRequiredExtensionsData(swappyRequiredExtensionCount * (VK_MAX_EXTENSION_NAME_SIZE + 1)); + for (uint32_t i = 0; i < swappyRequiredExtensionCount; i++) { + swappyRequiredExtensions[i] = &swappyRequiredExtensionsData[i * (VK_MAX_EXTENSION_NAME_SIZE + 1)]; + } + SwappyVk_determineDeviceExtensions(_gpuContext->physicalDevice, availableExtensionCount, + _gpuDevice->extensions.data(), &swappyRequiredExtensionCount, swappyRequiredExtensions.data()); + vector swappyRequiredExtList(swappyRequiredExtensionCount); + + for (size_t i = 0; i < swappyRequiredExtensionCount; ++i) { + swappyRequiredExtList[i] = swappyRequiredExtensions[i]; + requestedExtensions.push_back(swappyRequiredExtList[i].c_str()); + } +#endif + // just filter out the unsupported layers & extensions for (const char *layer : requestedLayers) { if (isLayerSupported(layer, _gpuDevice->layers)) { @@ -637,6 +660,16 @@ void CCVKDevice::present() { if (!_gpuTransportHub->empty(false)) _gpuTransportHub->packageForFlight(false); if (!_gpuTransportHub->empty(true)) _gpuTransportHub->packageForFlight(true); +#if CC_SWAPPY_ENABLED + // tripple buffer? + // static vector queueFmlIdxBuff(_gpuDevice->backBufferCount); + // std::iota(std::begin(queueFmlIdxBuff), std::end(queueFmlIdxBuff), 0); + SwappyVk_setQueueFamilyIndex(_gpuDevice->vkDevice, queue->gpuQueue()->vkQueue, queue->gpuQueue()->queueFamilyIndex); + auto vkCCPresentFunc = SwappyVk_queuePresent; +#else + auto vkCCPresentFunc = vkQueuePresentKHR; +#endif + if (!vkSwapchains.empty()) { // don't present if not acquired VkPresentInfoKHR presentInfo{VK_STRUCTURE_TYPE_PRESENT_INFO_KHR}; presentInfo.waitSemaphoreCount = utils::toUint(queue->gpuQueue()->lastSignaledSemaphores.size()); @@ -645,7 +678,7 @@ void CCVKDevice::present() { presentInfo.pSwapchains = vkSwapchains.data(); presentInfo.pImageIndices = vkSwapchainIndices.data(); - VkResult res = vkQueuePresentKHR(queue->gpuQueue()->vkQueue, &presentInfo); + VkResult res = vkCCPresentFunc(queue->gpuQueue()->vkQueue, &presentInfo); for (auto *gpuSwapchain : gpuSwapchains) { gpuSwapchain->lastPresentResult = res; } diff --git a/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp b/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp index 79f62f4322..49677476e1 100644 --- a/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKSwapchain.cpp @@ -32,6 +32,12 @@ #include "VKTexture.h" #include "VKUtils.h" +#if CC_SWAPPY_ENABLED + #include "platform/android/AndroidPlatform.h" + #include "swappy/swappyVK.h" + #include "swappy/swappy_common.h" +#endif + namespace cc { namespace gfx { @@ -207,6 +213,22 @@ void CCVKSwapchain::doInit(const SwapchainInfo &info) { initTexture(textureInfo, _depthStencilTexture); checkSwapchainStatus(); + + // Android Game Frame Pacing:swappy +#if CC_SWAPPY_ENABLED + auto * platform = static_cast(cc::BasePlatform::getPlatform()); + int32_t fps = cc::BasePlatform::getPlatform()->getFps(); + + uint64_t frameRefreshIntervalNS; + SwappyVk_initAndGetRefreshCycleDuration(static_cast(platform->getEnv()), + static_cast(platform->getActivity()), + gpuContext->physicalDevice, + gpuDevice->vkDevice, + _gpuSwapchain->vkSwapchain, + &frameRefreshIntervalNS); + SwappyVk_setSwapIntervalNS(gpuDevice->vkDevice, _gpuSwapchain->vkSwapchain, fps ? 1000000000L / fps : frameRefreshIntervalNS); + SwappyVk_setWindow(gpuDevice->vkDevice, _gpuSwapchain->vkSwapchain, static_cast(info.windowHandle)); +#endif } void CCVKSwapchain::doDestroy() { @@ -363,6 +385,10 @@ void CCVKSwapchain::destroySwapchain(const CCVKGPUDevice *gpuDevice) { _gpuSwapchain->swapchainImages.clear(); +#if CC_SWAPPY_ENABLED + SwappyVk_destroySwapchain(gpuDevice->vkDevice, _gpuSwapchain->vkSwapchain); +#endif + vkDestroySwapchainKHR(gpuDevice->vkDevice, _gpuSwapchain->vkSwapchain, nullptr); _gpuSwapchain->vkSwapchain = VK_NULL_HANDLE; } @@ -381,10 +407,14 @@ void CCVKSwapchain::doDestroySurface() { _gpuSwapchain->vkSurface = VK_NULL_HANDLE; } -void CCVKSwapchain::doCreateSurface(void * /*windowHandle*/) { +void CCVKSwapchain::doCreateSurface(void *windowHandle) { // NOLINT if (!_gpuSwapchain || _gpuSwapchain->vkSurface != VK_NULL_HANDLE) return; createVkSurface(); checkSwapchainStatus(); +#if CC_SWAPPY_ENABLED + auto *gpuDevice = CCVKDevice::getInstance()->gpuDevice(); + SwappyVk_setWindow(gpuDevice->vkDevice, _gpuSwapchain->vkSwapchain, static_cast(windowHandle)); +#endif } void CCVKSwapchain::createVkSurface() { diff --git a/native/external-config.json b/native/external-config.json index 96296d00ce..28deaa59f2 100644 --- a/native/external-config.json +++ b/native/external-config.json @@ -4,6 +4,6 @@ "type": "github", "owner": "cocos-creator", "name": "engine-native-external", - "checkout": "v3d-gfx-97" + "checkout": "v3d-gfx-105" } -} +} \ No newline at end of file