Merge branch 'v3.4.2' into v3.5.0_merge_v3.4.2

Conflicts:
	cocos/platform/android/jni/JniCocosActivity.cpp
	cocos/platform/apple/JsbBridgeWrapper.mm
	cocos/platform/ohos/jni/JniCocosAbility.cpp
	cocos/renderer/gfx-metal/MTLCommandBuffer.mm
	external/config.json
This commit is contained in:
minggo
2022-01-24 15:01:01 +08:00
43 changed files with 513 additions and 658 deletions
+30
View File
@@ -228,3 +228,33 @@ jobs:
cmake --build . --config Debug -- -jobs $NUM_OF_CORES CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO
fi
echo "Compile iOS Done!"
compile_wgpu_mac:
name: "Emscripten"
runs-on: macos-latest
if: contains( github.event.head_commit.message, 'WGPU_CI_ON' )
steps:
- uses: actions/checkout@v2
- name: Download external libraries
shell: bash
run: |
EXT_VERSION=`grep version external/config.json |awk -F'"' '{print $4}'`
rm external/config.json
git clone --branch $EXT_VERSION --depth 1 https://github.com/cocos-creator/engine-native-external external
- name: Setup Emscripten
run: |
git clone https://github.com/emscripten-core/emsdk.git ../emsdk
cd ../emsdk
./emsdk install latest
./emsdk activate latest
source ./emsdk_env.sh
emcc -v
- name: Compile
env:
COCOS_ENGINE_DEV: 1
run: |
COCOS2DX_ROOT=$GITHUB_WORKSPACE
cd $COCOS2DX_ROOT/cocos/renderer/gfx-wgpu
$COCOS2DX_ROOT/../emsdk/upstream/emscripten/emcmake cmake .
$COCOS2DX_ROOT/../emsdk/upstream/emscripten/emmake make
echo "Compile WGPU by ems on MacOS Done!"
@@ -24,9 +24,9 @@
****************************************************************************/
#include "cocos/bindings/manual/JavaScriptJavaBridge.h"
#include "cocos/application/ApplicationManager.h"
#include "cocos/base/UTF8.h"
#include "cocos/bindings/manual/jsb_conversions.h"
#include "cocos/application/ApplicationManager.h"
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <android/log.h>
@@ -44,7 +44,7 @@
#ifndef ORG_JAVABRIDGE_CLASS_NAME
#define ORG_JAVABRIDGE_CLASS_NAME com_cocos_lib_CocosJavascriptJavaBridge
#endif
#define JNI_JSJAVABRIDGE(FUNC) JNI_METHOD1(ORG_JAVABRIDGE_CLASS_NAME, FUNC)
#define JNI_JSJAVABRIDGE(FUNC) JNI_METHOD1(ORG_JAVABRIDGE_CLASS_NAME, FUNC)
#define JSJ_ERR_OK (0)
#define JSJ_ERR_TYPE_NOT_SUPPORT (-1)
#define JSJ_ERR_INVALID_SIGNATURES (-2)
@@ -81,10 +81,9 @@ public:
class CallInfo {
public:
CallInfo(const char *className, const char *methodName, const char *methodSig)
: _mClassName(className),
_mMethodName(methodName),
_mMethodSig(methodSig)
{
: _mClassName(className),
_mMethodName(methodName),
_mMethodSig(methodSig) {
memset(&_mRet, 0, sizeof(_mRet));
_mValid = validateMethodSig() && getMethodInfo();
}
@@ -126,7 +125,7 @@ public:
}
}
JNIEnv *getEnv() const{
JNIEnv *getEnv() const {
return _mEnv;
}
@@ -173,17 +172,17 @@ public:
};
static bool convertReturnValue(ReturnValue retValue, ValueType type, se::Value *ret);
};
using JsCallback = std::function<void(const std::string&, const std::string&)>;
class ScriptNativeBridge{
using JsCallback = std::function<void(const std::string &, const std::string &)>;
class ScriptNativeBridge {
public:
void callByNative(const std::string& arg0, const std::string& arg1);
inline void setCallback(const JsCallback& cb){
void callByNative(const std::string &arg0, const std::string &arg1);
inline void setCallback(const JsCallback &cb) {
_callback = cb;
}
static ScriptNativeBridge* bridgeCxxInstance;
se::Value jsCb;
static ScriptNativeBridge *bridgeCxxInstance;
se::Value jsCb;
private:
JsCallback _callback{nullptr}; // NOLINT(readability-identifier-naming)
};
@@ -216,10 +215,12 @@ Java_com_cocos_lib_JsbBridge_nativeSendToScript(JNIEnv *env, jclass clazz, jstri
}
} // extern "C"
ScriptNativeBridge* ScriptNativeBridge::bridgeCxxInstance{nullptr};
ScriptNativeBridge *ScriptNativeBridge::bridgeCxxInstance{nullptr};
JavaScriptJavaBridge::CallInfo::~CallInfo() {
_mEnv->DeleteLocalRef(_mClassID);
if (_mReturnType == ValueType::STRING && _mRet.stringValue) {
_mEnv->DeleteLocalRef(_mRetjstring);
delete _mRet.stringValue;
}
}
@@ -612,8 +613,7 @@ static bool JavaScriptJavaBridge_callStaticMethod(se::State &s) { //NOLINT(reada
}
SE_BIND_FUNC(JavaScriptJavaBridge_callStaticMethod)
static bool ScriptNativeBridge_getCallback(se::State &s){ //NOLINT(readability-identifier-naming)
static bool ScriptNativeBridge_getCallback(se::State &s) { //NOLINT(readability-identifier-naming)
auto *cobj = static_cast<ScriptNativeBridge *>(s.nativeThisObject());
assert(cobj == ScriptNativeBridge::bridgeCxxInstance);
s.rval() = cobj->jsCb;
@@ -622,31 +622,30 @@ static bool ScriptNativeBridge_getCallback(se::State &s){ //NOLINT(readability-i
}
SE_BIND_PROP_GET(ScriptNativeBridge_getCallback)
static bool ScriptNativeBridge_setCallback(se::State &s){ //NOLINT(readability-identifier-naming)
static bool ScriptNativeBridge_setCallback(se::State &s) { //NOLINT(readability-identifier-naming)
auto *cobj = static_cast<ScriptNativeBridge *>(s.nativeThisObject());
assert(cobj == ScriptNativeBridge::bridgeCxxInstance);
const auto &args = s.args();
se::Value jsFunc = args[0];
cobj->jsCb = jsFunc;
if(jsFunc.isNullOrUndefined())
{
const auto &args = s.args();
se::Value jsFunc = args[0];
cobj->jsCb = jsFunc;
if (jsFunc.isNullOrUndefined()) {
cobj->setCallback(nullptr);
}
else{
} else {
assert(jsFunc.isObject() && jsFunc.toObject()->isFunction());
s.thisObject()->attachObject(jsFunc.toObject());
cobj->setCallback([jsFunc](const std::string& arg0, const std::string& arg1){
cobj->setCallback([jsFunc](const std::string &arg0, const std::string &arg1) {
se::AutoHandleScope hs;
se::ValueArray args;
se::ValueArray args;
args.push_back(se::Value(arg0));
if(!arg1.empty()) {
if (!arg1.empty()) {
args.push_back(se::Value(arg1));
}
jsFunc.toObject()->call(args, nullptr);
});
}
return true;
}SE_BIND_PROP_SET(ScriptNativeBridge_setCallback)
}
SE_BIND_PROP_SET(ScriptNativeBridge_setCallback)
static bool ScriptNativeBridge_sendToNative(se::State &s) { //NOLINT(readability-identifier-naming)
const auto &args = s.args();
@@ -716,12 +715,10 @@ bool register_script_native_bridge(se::Object *obj) { //NOLINT(readability-ident
return true;
}
void callPlatformStringMethod(const std::string &arg0, const std::string &arg1) {
cc::JniHelper::callStaticVoidMethod(
"com/cocos/lib/JsbBridge", "callByScript", arg0, arg1);
cc::JniHelper::callStaticVoidMethod(
"com/cocos/lib/JsbBridge", "callByScript", arg0, arg1);
}
void ScriptNativeBridge::callByNative(const std::string& arg0, const std::string& arg1){
void ScriptNativeBridge::callByNative(const std::string &arg0, const std::string &arg1) {
_callback(arg0, arg1);
}
@@ -70,9 +70,6 @@ int32_t AndroidPlatform::loop() {
void AndroidPlatform::pollEvent() {
_jniNativeGlue->execCommand();
if (!_jniNativeGlue->isPause()) {
std::this_thread::yield();
}
_jniNativeGlue->flushTasksOnGameThread();
}
@@ -434,7 +434,7 @@ public class CocosEditBoxActivity extends Activity {
Native functions invoked by UI.
**************************************************************************************/
private void onKeyboardInput(String text) {
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
CocosEditBoxActivity.onKeyboardInputNative(text);
@@ -443,7 +443,7 @@ public class CocosEditBoxActivity extends Activity {
}
private void onKeyboardComplete(String text) {
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
CocosEditBoxActivity.onKeyboardCompleteNative(text);
@@ -452,7 +452,7 @@ public class CocosEditBoxActivity extends Activity {
}
private void onKeyboardConfirm(String text) {
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
CocosEditBoxActivity.onKeyboardConfirmNative(text);
@@ -1,27 +1,27 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package com.cocos.lib;
@@ -58,8 +58,11 @@ import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Queue;
import java.util.concurrent.locks.ReentrantLock;
public class CocosHelper {
@@ -77,7 +80,7 @@ public class CocosHelper {
private static BatteryReceiver sBatteryReceiver = new BatteryReceiver();
public static final int NETWORK_TYPE_NONE = 0;
public static final int NETWORK_TYPE_LAN = 1;
public static final int NETWORK_TYPE_LAN = 1;
public static final int NETWORK_TYPE_WWAN = 2;
// The absolute path to the OBB if it exists.
@@ -86,8 +89,26 @@ public class CocosHelper {
// The OBB file
private static ZipResourceFile sOBBFile = null;
private static List<Runnable> sTaskOnGameThread = Collections.synchronizedList(new ArrayList<>());
static class LockedTaskQ {
private final Object readMtx = new Object();
private Queue<Runnable> sTaskQ = new LinkedList<>();
public synchronized void addTask(Runnable runnable) {
sTaskQ.add(runnable);
}
public void runTasks(){
Queue<Runnable> tmp;
synchronized (readMtx) {
tmp = sTaskQ;
sTaskQ = new LinkedList<>();
}
for(Runnable runnable : tmp){
runnable.run();
}
}
}
private static LockedTaskQ sTaskQOnGameThread = new LockedTaskQ();
private static LockedTaskQ sForegroundTaskQOnGameThread = new LockedTaskQ();
/**
* Battery receiver to getting battery level.
*/
@@ -119,17 +140,20 @@ public class CocosHelper {
context.unregisterReceiver(sBatteryReceiver);
}
//Run on game thread forever, no matter foreground or background
public static void runOnGameThread(final Runnable runnable) {
sTaskOnGameThread.add(runnable);
sTaskQOnGameThread.addTask(runnable);
}
static void flushTasksOnGameThread() {
while(sTaskOnGameThread.size() > 0) {
Runnable r = sTaskOnGameThread.remove(0);
if(r != null) {
r.run();
}
}
sTaskQOnGameThread.runTasks();
}
public static void runOnGameThreadAtForeground(final Runnable runnable) {
sForegroundTaskQOnGameThread.addTask(runnable);
}
static void flushTasksOnGameThreadAtForeground() {
sForegroundTaskQOnGameThread.runTasks();
}
public static int getNetworkType() {
@@ -159,10 +183,11 @@ public class CocosHelper {
// ===========================================================
private static boolean sInited = false;
public static void init(final Activity activity) {
sActivity = activity;
if (!sInited) {
CocosHelper.sVibrateService = (Vibrator)activity.getSystemService(Context.VIBRATOR_SERVICE);
CocosHelper.sVibrateService = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE);
CocosHelper.initObbFilePath();
CocosHelper.initializeOBBFile();
@@ -170,20 +195,30 @@ public class CocosHelper {
}
}
public static float getBatteryLevel() { return sBatteryReceiver.sBatteryLevel; }
public static String getObbFilePath() { return CocosHelper.sObbFilePath; }
public static float getBatteryLevel() {
return sBatteryReceiver.sBatteryLevel;
}
public static String getObbFilePath() {
return CocosHelper.sObbFilePath;
}
public static String getWritablePath() {
return sActivity.getFilesDir().getAbsolutePath();
}
public static String getCurrentLanguage() {
return Locale.getDefault().getLanguage();
}
public static String getCurrentLanguageCode() {
return Locale.getDefault().toString();
}
public static String getDeviceModel(){
public static String getDeviceModel() {
return Build.MODEL;
}
public static String getSystemVersion() {
return Build.VERSION.RELEASE;
}
@@ -193,7 +228,7 @@ public class CocosHelper {
if (sVibrateService != null && sVibrateService.hasVibrator()) {
if (android.os.Build.VERSION.SDK_INT >= 26) {
Class<?> vibrationEffectClass = Class.forName("android.os.VibrationEffect");
if(vibrationEffectClass != null) {
if (vibrationEffectClass != null) {
final int DEFAULT_AMPLITUDE = CocosReflectionHelper.<Integer>getConstantValue(vibrationEffectClass,
"DEFAULT_AMPLITUDE");
//VibrationEffect.createOneShot(long milliseconds, int amplitude)
@@ -201,10 +236,10 @@ public class CocosHelper {
new Class[]{Long.TYPE, Integer.TYPE});
Class<?> type = method.getReturnType();
Object effect = method.invoke(vibrationEffectClass,
Object effect = method.invoke(vibrationEffectClass,
new Object[]{(long) (duration * 1000), DEFAULT_AMPLITUDE});
//sVibrateService.vibrate(VibrationEffect effect);
CocosReflectionHelper.invokeInstanceMethod(sVibrateService,"vibrate",
CocosReflectionHelper.invokeInstanceMethod(sVibrateService, "vibrate",
new Class[]{type}, new Object[]{(effect)});
}
} else {
@@ -228,11 +263,11 @@ public class CocosHelper {
return ret;
}
public static void copyTextToClipboard(final String text){
public static void copyTextToClipboard(final String text) {
sActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
ClipboardManager myClipboard = (ClipboardManager)sActivity.getSystemService(Context.CLIPBOARD_SERVICE);
ClipboardManager myClipboard = (ClipboardManager) sActivity.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData myClip = ClipData.newPlainText("text", text);
myClipboard.setPrimaryClip(myClip);
}
@@ -246,8 +281,8 @@ public class CocosHelper {
if (descriptor != null) {
try {
ParcelFileDescriptor parcel = descriptor.getParcelFileDescriptor();
Method method = parcel.getClass().getMethod("getFd", new Class[] {});
array[0] = (Integer)method.invoke(parcel);
Method method = parcel.getClass().getMethod("getFd", new Class[]{});
array[0] = (Integer) method.invoke(parcel);
array[1] = descriptor.getStartOffset();
array[2] = descriptor.getLength();
} catch (NoSuchMethodException e) {
@@ -313,14 +348,14 @@ public class CocosHelper {
do {
Object windowInsectObj = GlobalObject.getActivity().getWindow().getDecorView().getRootWindowInsets();
if(windowInsectObj == null) break;
if (windowInsectObj == null) break;
Class<?> windowInsets = WindowInsets.class;
try {
Method wiGetDisplayCutout = windowInsets.getMethod("getDisplayCutout");
Object cutout = wiGetDisplayCutout.invoke(windowInsectObj);
if(cutout == null) break;
if (cutout == null) break;
Class<?> displayCutout = cutout.getClass();
Method dcGetLeft = displayCutout.getMethod("getSafeInsetLeft");
@@ -342,15 +377,15 @@ public class CocosHelper {
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}while(false);
} while (false);
}
return new float[]{0,0,0,0};
return new float[]{0, 0, 0, 0};
}
public static void setKeepScreenOn(boolean keepScreenOn) {
if(keepScreenOn) {
if (keepScreenOn) {
sActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}else {
} else {
sActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
@@ -50,7 +50,7 @@ public class CocosKeyCodeHandler {
case KeyEvent.KEYCODE_ENTER:
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
case KeyEvent.KEYCODE_DPAD_CENTER:
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
handleKeyDown(keyCode);
@@ -73,7 +73,7 @@ public class CocosKeyCodeHandler {
case KeyEvent.KEYCODE_ENTER:
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
case KeyEvent.KEYCODE_DPAD_CENTER:
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
handleKeyUp(keyCode);
@@ -49,7 +49,7 @@ public class CocosOrientationHelper extends OrientationEventListener {
int curOrientation = CocosHelper.getDeviceRotation();
if (curOrientation != mCurrentOrientation) {
mCurrentOrientation = CocosHelper.getDeviceRotation();
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
nativeOnOrientationChanged(mCurrentOrientation);
@@ -41,7 +41,7 @@ public class CocosSurfaceView extends SurfaceView {
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
nativeOnSizeChanged(w, h);
@@ -60,7 +60,7 @@ public class CocosTouchHandler {
final int idPointerDown = pMotionEvent.getPointerId(indexPointerDown);
final float xPointerDown = pMotionEvent.getX(indexPointerDown);
final float yPointerDown = pMotionEvent.getY(indexPointerDown);
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
handleActionDown(idPointerDown, xPointerDown, yPointerDown);
@@ -79,7 +79,7 @@ public class CocosTouchHandler {
final float xDown = xs[0];
final float yDown = ys[0];
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
handleActionDown(idDown, xDown, yDown);
@@ -89,7 +89,7 @@ public class CocosTouchHandler {
break;
case MotionEvent.ACTION_MOVE:
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
handleActionMove(ids, xs, ys);
@@ -103,7 +103,7 @@ public class CocosTouchHandler {
final int idPointerUp = pMotionEvent.getPointerId(indexPointUp);
final float xPointerUp = pMotionEvent.getX(indexPointUp);
final float yPointerUp = pMotionEvent.getY(indexPointUp);
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
handleActionUp(idPointerUp, xPointerUp, yPointerUp);
@@ -117,7 +117,7 @@ public class CocosTouchHandler {
final int idUp = pMotionEvent.getPointerId(0);
final float xUp = xs[0];
final float yUp = ys[0];
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
handleActionUp(idUp, xUp, yUp);
@@ -127,7 +127,7 @@ public class CocosTouchHandler {
break;
case MotionEvent.ACTION_CANCEL:
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
handleActionCancel(ids, xs, ys);
@@ -170,7 +170,7 @@ public class CocosVideoHelper {
@Override
public void onVideoEvent(int tag,int event) {
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
nativeExecuteVideoCallback(tag, event);
@@ -282,7 +282,7 @@ public class CocosVideoHelper {
CocosVideoView videoView = sVideoViews.get(key);
if (videoView != null) {
videoView.setFullScreenEnabled(false);
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
nativeExecuteVideoCallback(key, KeyEventBack);
@@ -109,7 +109,7 @@ import java.util.concurrent.CountDownLatch;
try {
URI uri = URI.create(urlString);
if (uri != null && uri.getScheme().equals(mJSScheme)) {
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
CocosWebViewHelper._onJsCallback(mViewTag, urlString);
@@ -141,7 +141,7 @@ import java.util.concurrent.CountDownLatch;
public void onPageFinished(WebView view, final String url) {
super.onPageFinished(view, url);
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
CocosWebViewHelper._didFinishLoading(mViewTag, url);
@@ -153,7 +153,7 @@ import java.util.concurrent.CountDownLatch;
public void onReceivedError(WebView view, int errorCode, String description, final String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
CocosWebViewHelper._didFailLoading(mViewTag, failingUrl);
@@ -22,10 +22,10 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "JsbBridgeWrapper.h"
#include <iostream>
#include <string>
#include "JsbBridge.h"
#include "JsbBridgeWrapper.h"
@implementation JsbBridgeWrapper {
JsbBridge* jb;
+2 -1
View File
@@ -57,7 +57,6 @@
} \
} while (false)
struct android_app;
namespace cc {
@@ -283,6 +282,7 @@ public:
#ifndef __OHOS__
ccDeleteLocalRef(t.env, t.classID);
#endif
ccDeleteLocalRef(t.env, array);
deleteLocalRefs(t.env, &localRefs);
return &ret[0];
}
@@ -313,6 +313,7 @@ public:
#ifndef __OHOS__
ccDeleteLocalRef(t.env, t.classID);
#endif
ccDeleteLocalRef(t.env, array);
deleteLocalRefs(t.env, &localRefs);
} else {
reportError(className, methodName, signature);
@@ -124,6 +124,11 @@ void flushTasksOnGameThreadJNI() {
"flushTasksOnGameThread");
}
void flushTasksOnGameThreadAtForegroundJNI() {
cc::JniHelper::callStaticVoidMethod(JCLS_HELPER,
"flushTasksOnGameThreadAtForeground");
}
void setAccelerometerEnabledJNI(bool isEnabled) {
JniHelper::callStaticVoidMethod(JCLS_SENSOR, "setAccelerometerEnabled", isEnabled);
}
+1
View File
@@ -42,6 +42,7 @@ extern float * getSafeAreaEdgeJNI();
extern int getDeviceRotationJNI();
extern float getBatteryLevelJNI();
extern void flushTasksOnGameThreadJNI();
extern void flushTasksOnGameThreadAtForegroundJNI();
extern void setAccelerometerEnabledJNI(bool isEnabled);
extern void setAccelerometerIntervalJNI(float interval);
extern float * getDeviceMotionValueJNI();
@@ -104,9 +104,11 @@ bool JniNativeGlue::isRunning() const {
}
void JniNativeGlue::flushTasksOnGameThread() const {
// Handle java events send by UI thread. Input events are handled here too.
flushTasksOnGameThreadJNI();
if (_animating) {
// Handle java events send by UI thread. Input events are handled here too.
flushTasksOnGameThreadJNI();
flushTasksOnGameThreadAtForegroundJNI();
}
}
@@ -128,6 +130,28 @@ int JniNativeGlue::readCommand(CommandMsg* msg) {
return _messagePipe->readCommand(msg, sizeof(CommandMsg));
}
int JniNativeGlue::readCommandWithTimeout(CommandMsg* cmd, int delayMS) {
if (delayMS > 0) {
static fd_set fdSet;
static timeval timeout;
timeout = {delayMS / 1000, (delayMS % 1000) * 1000};
FD_ZERO(&fdSet);
FD_SET(pipeRead, &fdSet);
auto ret = select(pipeRead + 1, &fdSet, nullptr, nullptr, &timeout);
if (ret < 0) {
LOGV("failed to run select(..): %s\n", strerror(errno));
return ret;
}
if (ret == 0) {
return 0;
}
}
return readCommand(cmd);
}
void JniNativeGlue::setEventDispatch(IEventDispatch* eventDispatcher) {
_eventDispatcher = eventDispatcher;
}
@@ -168,7 +192,10 @@ void JniNativeGlue::onLowMemory() {
void JniNativeGlue::execCommand() {
static CommandMsg msg;
if (readCommand(&msg) > 0) {
static bool runInLowRate{false};
runInLowRate = !_animating || APP_CMD_PAUSE == _appState;
if (readCommandWithTimeout(&msg, runInLowRate ? 50 : 0) > 0) {
preExecCmd(msg.cmd);
engineHandleCmd(msg.cmd);
postExecCmd(msg.cmd);
@@ -89,6 +89,7 @@ public:
void writeCommandAsync(JniCommand cmd);
void writeCommandSync(JniCommand cmd);
int readCommand(CommandMsg* msg);
int readCommandWithTimeout(CommandMsg* cmd, int delayMS);
void setEventDispatch(IEventDispatch* eventDispatcher);
void dispatchEvent(const OSEvent& ev);
@@ -1,237 +0,0 @@
/****************************************************************************
Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "platform/ohos/jni/JniInteraction.h"
#include <android/asset_manager_jni.h>
#include <android/log.h>
#include <android/native_window_jni.h>
#include <android_native_app_glue.h>
#include <fcntl.h>
#include <jni.h>
#include <unistd.h>
#include <thread>
#include <vector>
#include "JniCocosActivity.h"
#include "cocos/bindings/event/CustomEventTypes.h"
#include "cocos/bindings/event/EventDispatcher.h"
#include "platform/android/FileUtils-android.h"
#include "platform/android/jni/JniCocosActivity.h"
#include "platform/java/jni/JniHelper.h"
namespace cc {
JniInteraction::JniInteraction() = default;
JniInteraction* JniInteraction::getInstance() {
static JniInteraction cocosInstaction;
return &cocosInstaction;
}
void JniInteraction::init() {
}
void JniInteraction::setObbPath(const std::string& path) {
_obbPath = path;
}
void JniInteraction::setAAssetManager(AAssetManager* assetManager) {
_assetManager = assetManager;
}
void JniInteraction::setResourceManager(ResourceManager* assetManager) {
_resourceManager = assetManager;
}
void JniInteraction::setWindow(ANativeWindow* window) {
std::unique_lock<std::mutex> lk(_mutex);
if (_pendingWindow) {
writeCommand(APP_CMD_TERM_WINDOW);
}
_pendingWindow = window;
if (window) {
writeCommand(APP_CMD_INIT_WINDOW);
}
while (_window != _pendingWindow) {
_cond.wait(lk);
}
}
void JniInteraction::preExecCmd(int8_t cmd) {
switch (cmd) {
case APP_CMD_INIT_WINDOW: {
LOGV("APP_CMD_INIT_WINDOW");
std::unique_lock<std::mutex> lk(_mutex);
_window = _pendingWindow;
lk.unlock();
_cond.notify_all();
setAnimating(true);
} break;
case APP_CMD_TERM_WINDOW:
LOGV("APP_CMD_TERM_WINDOW");
setAnimating(false);
_cond.notify_all();
break;
case APP_CMD_RESUME:
LOGV("APP_CMD_RESUME");
handlePauseResume(cmd);
break;
case APP_CMD_PAUSE:
LOGV("APP_CMD_PAUSE");
handlePauseResume(cmd);
break;
default:
break;
}
}
void JniInteraction::postExecCmd(int8_t cmd) {
switch (cmd) {
case APP_CMD_TERM_WINDOW: {
std::unique_lock<std::mutex> lk(_mutex);
_window = nullptr;
lk.unlock();
_cond.notify_all();
} break;
default:
break;
}
}
void JniInteraction::setAppState(int8_t cmd) {
std::unique_lock<std::mutex> lk(_mutex);
writeCommand(cmd);
while (_appState != cmd) {
_cond.wait(lk);
}
}
void JniInteraction::handlePauseResume(int8_t cmd) {
LOGV("appState=%d", cmd);
std::unique_lock<std::mutex> lk(_mutex);
_appState = static_cast<uint8_t>(cmd);
lk.unlock();
_cond.notify_all();
}
void JniInteraction::flushTasksOnGameThread() const {
if (getAnimating()) {
// Handle java events send by UI thread. Input events are handled here too.
flushTasksOnGameThreadJNI();
}
}
void JniInteraction::setRunning(bool isRunning) {
std::unique_lock<std::mutex> lk(_mutex);
_running = isRunning;
lk.unlock();
_cond.notify_all();
//_systemWindow = _platform->getInterfaces<SystemWindow>();
}
void JniInteraction::waitRunning() {
std::unique_lock<std::mutex> lk(_mutex);
while (!_running) {
_cond.wait(lk);
}
}
bool JniInteraction::isRunning() {
std::unique_lock<std::mutex> lk(_mutex);
return _running;
}
ANativeWindow* JniInteraction::getWindowHandle() {
std::unique_lock<std::mutex> lk(_mutex);
return _window;
}
void JniInteraction::execCommand() {
int8_t cmd = 0;
if (readCommand(cmd) > 0) {
preExecCmd(cmd);
engineHandleCmd(cmd);
postExecCmd(cmd);
}
}
bool JniInteraction::isPause() const {
if (!getAnimating()) {
return true;
}
if (_appState == APP_CMD_PAUSE) {
return true;
}
return false;
}
void JniInteraction::engineHandleCmd(int cmd) {
static bool isWindowInitialized = false;
// Handle CMD here if needed.
switch (cmd) {
case APP_CMD_INIT_WINDOW: {
if (!isWindowInitialized) {
isWindowInitialized = true;
return;
}
cc::CustomEvent event;
event.name = EVENT_RECREATE_WINDOW;
event.args->ptrVal = reinterpret_cast<void*>(getWindowHandle());
dispatchEvent(event);
} break;
case APP_CMD_TERM_WINDOW: {
cc::CustomEvent event;
event.name = EVENT_DESTROY_WINDOW;
event.args->ptrVal = reinterpret_cast<void*>(getWindowHandle());
dispatchEvent(event);
} break;
case APP_CMD_RESUME: {
WindowEvent ev;
ev.type = WindowEvent::Type::SHOW;
dispatchEvent(ev);
} break;
case APP_CMD_PAUSE: {
WindowEvent ev;
ev.type = WindowEvent::Type::HIDDEN;
dispatchEvent(ev);
} break;
case APP_CMD_DESTROY: {
LOGV("APP_CMD_DESTROY");
WindowEvent ev;
ev.type = WindowEvent::Type::CLOSE;
dispatchEvent(ev);
} break;
case APP_CMD_LOW_MEMORY: {
DeviceEvent ev;
ev.type = DeviceEvent::Type::DEVICE_MEMORY;
dispatchEvent(ev);
break;
}
default:
break;
}
}
} // namespace cc
@@ -1,224 +0,0 @@
/****************************************************************************
Copyright (c) 2020-2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "platform/android/jni/glue/JniNativeGlue.h"
#include <android/asset_manager_jni.h>
#include <android/log.h>
#include <android/native_window_jni.h>
#include <android_native_app_glue.h>
#include <fcntl.h>
#include <jni.h>
#include <unistd.h>
#include <thread>
#include <vector>
#include "cocos/bindings/event/CustomEventTypes.h"
#include "platform/android/jni/JniCocosActivity.h"
#include "cocos/bindings/event/EventDispatcher.h"
#include "platform/android/FileUtils-android.h"
#include "platform/android/jni/JniCocosActivity.h"
#include "platform/java/jni/JniHelper.h"
namespace cc {
JniInteraction::JniInteraction() = default;
JniInteraction* JniInteraction::getInstance() {
static JniInteraction cocosInstaction;
return &cocosInstaction;
}
void JniInteraction::init() {
}
void JniInteraction::setObbPath(const std::string& path) {
_obbPath = path;
}
void JniInteraction::setAAssetManager(AAssetManager* assetManager) {
_assetManager = assetManager;
}
void JniInteraction::setWindow(ANativeWindow* window) {
if (_pendingWindow) {
writeCommandSync(ABILITY_CMD_TERM_WINDOW);
}
_pendingWindow = window;
}
void JniInteraction::initWithPendingWindow() {
if (_pendingWindow) {
writeCommandSync(ABILITY_CMD_INIT_WINDOW);
}
}
void JniInteraction::preExecCmd(int8_t cmd) {
switch (cmd) {
case ABILITY_CMD_INIT_WINDOW: {
LOGV("ABILITY_CMD_INIT_WINDOW");
_window = _pendingWindow;
setAnimating(true);
} break;
case ABILITY_CMD_TERM_WINDOW:
LOGV("ABILITY_CMD_TERM_WINDOW");
setAnimating(false);
break;
case ABILITY_CMD_RESUME:
LOGV("ABILITY_CMD_RESUME");
handlePauseResume(cmd);
break;
case ABILITY_CMD_PAUSE:
LOGV("ABILITY_CMD_PAUSE");
handlePauseResume(cmd);
break;
case ABILITY_CMD_DESTROY:
LOGV("ABILITY_CMD_DESTROY");
cc::cocosApp.destroyRequested = true;
break;
default:
break;
}
}
void JniInteraction::postExecCmd(int8_t cmd) {
switch (cmd) {
case ABILITY_CMD_TERM_WINDOW: {
_window = nullptr;
_pendingWindow = nullptr;
} break;
default:
break;
}
}
void JniInteraction::setAppState(int8_t cmd) {
/*
std::unique_lock<std::mutex> lk(_mutex);
writeCommand(cmd);
while (_appState != cmd) {
_cond.wait(lk);
}
*/
writeCommandSync(cmd);
}
void JniInteraction::handlePauseResume(int8_t cmd) {
LOGV("appState=%d", cmd);
_appState = static_cast<uint8_t>(cmd);
}
void JniInteraction::flushTasksOnGameThread() const {
if (getAnimating()) {
// Handle java events send by UI thread. Input events are handled here too.
flushTasksOnGameThreadJNI();
}
}
void JniInteraction::setRunning(bool isRunning) {
_ThreadPromise.set_value();
_running = isRunning;
//_systemWindow = _platform->getInterfaces<SystemWindow>();
}
void JniInteraction::waitRunning() {
_ThreadPromise.get_future().get();
}
bool JniInteraction::isRunning() {
return _running;
}
ANativeWindow* JniInteraction::getWindowHandle() {
return _window;
}
void JniInteraction::execCommand() {
CommandMsg msg;
if (readCommand(&msg) > 0) {
preExecCmd(msg.cmd);
engineHandleCmd(msg.cmd);
postExecCmd(msg.cmd);
}
}
bool JniInteraction::isPause() const {
if (!getAnimating()) {
return true;
}
if (_appState == APP_CMD_PAUSE) {
return true;
}
return false;
}
void JniInteraction::engineHandleCmd(int cmd) {
static bool isWindowInitialized = false;
// Handle CMD here if needed.
switch (cmd) {
case APP_CMD_INIT_WINDOW: {
if (!isWindowInitialized) {
isWindowInitialized = true;
return;
}
cc::CustomEvent event;
event.name = EVENT_RECREATE_WINDOW;
event.args->ptrVal = reinterpret_cast<void*>(getWindowHandle());
dispatchEvent(event);
} break;
case APP_CMD_TERM_WINDOW: {
cc::CustomEvent event;
event.name = EVENT_DESTROY_WINDOW;
event.args->ptrVal = reinterpret_cast<void*>(getWindowHandle());
dispatchEvent(event);
} break;
case APP_CMD_RESUME: {
WindowEvent ev;
ev.type = WindowEvent::Type::SHOW;
dispatchEvent(ev);
} break;
case APP_CMD_PAUSE: {
WindowEvent ev;
ev.type = WindowEvent::Type::HIDDEN;
dispatchEvent(ev);
} break;
case APP_CMD_DESTROY: {
LOGV("APP_CMD_DESTROY");
WindowEvent ev;
ev.type = WindowEvent::Type::CLOSE;
dispatchEvent(ev);
} break;
case APP_CMD_LOW_MEMORY: {
DeviceEvent ev;
ev.type = DeviceEvent::Type::DEVICE_MEMORY;
dispatchEvent(ev);
break;
}
default:
break;
}
}
} // namespace cc
@@ -152,7 +152,7 @@ public class CocosAbilitySlice extends AbilitySlice implements SurfaceOps.Callba
mSurfaceProvider.setTouchEventListener(this);
mSurfaceProvider.setLayoutRefreshedListener(component -> {
// dispatch resize event
CocosHelper.runOnGameThread(()->{
CocosHelper.runOnGameThreadAtForeground(()->{
onOrientationChangedNative(getDisplayOrientation(), component.getWidth(), component.getHeight());
});
});
@@ -397,19 +397,19 @@ public class CocosEditBoxAbility extends AbilitySlice {
Native functions invoked by UI.
**************************************************************************************/
private void onKeyboardInput(String text) {
CocosHelper.runOnGameThread(() ->
CocosHelper.runOnGameThreadAtForeground(() ->
CocosEditBoxAbility.onKeyboardInputNative(text)
);
}
private void onKeyboardComplete(String text) {
CocosHelper.runOnGameThread(() ->
CocosHelper.runOnGameThreadAtForeground(() ->
CocosEditBoxAbility.onKeyboardCompleteNative(text)
);
}
private void onKeyboardConfirm(String text) {
CocosHelper.runOnGameThread(() ->
CocosHelper.runOnGameThreadAtForeground(() ->
CocosEditBoxAbility.onKeyboardConfirmNative(text)
);
}
@@ -80,8 +80,26 @@ public class CocosHelper {
private static String sObbFilePath = "";
private static List<Runnable> sTaskOnGameThread = Collections.synchronizedList(new ArrayList<>());
static class LockedTaskQ {
private final Object readMtx = new Object();
private Queue<Runnable> sTaskQ = new LinkedList<>();
public synchronized void addTask(Runnable runnable) {
sTaskQ.add(runnable);
}
public void runTasks(){
Queue<Runnable> tmp;
synchronized (readMtx) {
tmp = sTaskQ;
sTaskQ = new LinkedList<>();
}
for(Runnable runnable : tmp){
runnable.run();
}
}
}
private static LockedTaskQ sTaskQOnGameThread = new LockedTaskQ();
private static LockedTaskQ sForegroundTaskQOnGameThread = new LockedTaskQ();
/**
* Battery receiver to getting battery level.
*/
@@ -130,18 +148,20 @@ public class CocosHelper {
}
}
//Run on game thread forever, no matter foreground or background
public static void runOnGameThread(final Runnable runnable) {
sTaskOnGameThread.add(runnable);
sTaskQOnGameThread.addTask(runnable);
}
@SuppressWarnings("unused")
static void flushTasksOnGameThread() {
while (sTaskOnGameThread.size() > 0) {
Runnable r = sTaskOnGameThread.remove(0);
if (r != null) {
r.run();
}
}
sTaskQOnGameThread.runTasks();
}
public static void runOnGameThreadAtForeground(final Runnable runnable) {
sForegroundTaskQOnGameThread.addTask(runnable);
}
@SuppressWarnings("unused")
static void flushTasksOnGameThreadAtForeground() {
sForegroundTaskQOnGameThread.runTasks();
}
@SuppressWarnings("unused")
@@ -51,7 +51,7 @@ public class CocosKeyCodeHandler {
case KeyEvent.KEY_ENTER:
case KeyEvent.KEY_MEDIA_PLAY_PAUSE:
case KeyEvent.KEY_DPAD_CENTER:
CocosHelper.runOnGameThread(() -> handleKeyDown(keyCode));
CocosHelper.runOnGameThreadAtForeground(() -> handleKeyDown(keyCode));
return true;
default:
return false;
@@ -69,7 +69,7 @@ public class CocosKeyCodeHandler {
case KeyEvent.KEY_ENTER:
case KeyEvent.KEY_MEDIA_PLAY_PAUSE:
case KeyEvent.KEY_DPAD_CENTER:
CocosHelper.runOnGameThread(() -> handleKeyDown(keyCode));
CocosHelper.runOnGameThreadAtForeground(() -> handleKeyDown(keyCode));
return true;
default:
return false;
@@ -63,7 +63,7 @@ public class CocosOrientationHelper implements ICategoryOrientationDataCallback
final int curOrientation = CocosHelper.getDeviceRotation();
if (curOrientation != mCurrentOrientation) {
mCurrentOrientation = curOrientation;
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
nativeOnOrientationChanged(mCurrentOrientation);
@@ -69,7 +69,7 @@ public class CocosTouchHandler {
MmiPoint pos = pMotionEvent.getPointerPosition(indexPointerDown);
final float xPointerDown = pos.getX();
final float yPointerDown = pos.getY();
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
handleActionDown(idPointerDown, xPointerDown, yPointerDown);
@@ -78,7 +78,7 @@ public class CocosTouchHandler {
break;
case TouchEvent.POINT_MOVE:
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
handleActionMove(ids, xs, ys);
@@ -95,7 +95,7 @@ public class CocosTouchHandler {
MmiPoint posUP = pMotionEvent.getPointerPosition(indexPointUp);
final float xPointerUp = posUP.getX();
final float yPointerUp = posUP.getY();
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
handleActionUp(idPointerUp, xPointerUp, yPointerUp);
@@ -105,7 +105,7 @@ public class CocosTouchHandler {
break;
case TouchEvent.CANCEL:
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
handleActionCancel(ids, xs, ys);
@@ -171,7 +171,7 @@ public class CocosVideoHelper {
@Override
public void onVideoEvent(int tag,int event) {
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
nativeExecuteVideoCallback(tag, event);
@@ -294,7 +294,7 @@ public class CocosVideoHelper {
CocosVideoView videoView = sVideoViews.get(key);
if (videoView != null) {
videoView.setFullScreenEnabled(false);
CocosHelper.runOnGameThread(new Runnable() {
CocosHelper.runOnGameThreadAtForeground(new Runnable() {
@Override
public void run() {
nativeExecuteVideoCallback(key, KeyEventBack);
@@ -78,7 +78,7 @@ public class CocosWebView extends WebView {
try {
URI uri = new URI(request.getRequestUrl().toString());
if (uri.getScheme().equals(mJSScheme)) {
CocosHelper.runOnGameThread(
CocosHelper.runOnGameThreadAtForeground(
() -> CocosWebViewHelper._onJsCallback(mViewTag, urlString)
);
return true;
@@ -92,7 +92,7 @@ public class CocosWebView extends WebView {
);
// run worker on cocos thread
CocosHelper.runOnGameThread(shouldStartLoadingCB);
CocosHelper.runOnGameThreadAtForeground(shouldStartLoadingCB);
// wait for result from cocos thread
try {
@@ -109,7 +109,7 @@ public class CocosWebView extends WebView {
public void onPageLoaded(WebView view, final String url) {
super.onPageLoaded(view, url);
CocosHelper.runOnGameThread(
CocosHelper.runOnGameThreadAtForeground(
() -> CocosWebViewHelper._didFinishLoading(mViewTag, url)
);
}
@@ -118,7 +118,7 @@ public class CocosWebView extends WebView {
public void onError(WebView view, ResourceRequest request, ResourceError error) {
super.onError(view, request, error);
final String failingUrl = request.getRequestUrl().toString();
CocosHelper.runOnGameThread(
CocosHelper.runOnGameThreadAtForeground(
() -> CocosWebViewHelper._didFailLoading(mViewTag, failingUrl)
);
}
@@ -0,0 +1,109 @@
/****************************************************************************
Copyright (c) 2018-2021 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package com.cocos.lib;
import java.util.ArrayList;
import java.util.HashMap;
public class JsbBridgeWrapper {
//Interface for listener, should be implemented and dispatched
public interface OnScriptEventListener {
void onScriptEvent(String arg);
}
/**
* Get the instance of JsbBridgetWrapper
*/
public static JsbBridgeWrapper getInstance() {
if (instance == null) {
instance = new JsbBridgeWrapper();
}
return instance;
}
/**
* Add a listener to specified event, if the event does not exist, the wrapper will create one. Concurrent listener will be ignored
*/
public void addScriptEventListener(String eventName, OnScriptEventListener listener) {
if (eventMap.get(eventName) == null) {
eventMap.put(eventName, new ArrayList<OnScriptEventListener>());
}
eventMap.get(eventName).add(listener);
}
/**
* Remove listener for specified event, concurrent event will be deleted. Return false only if the event does not exist
*/
public boolean removeScriptEventListener(String eventName, OnScriptEventListener listener) {
ArrayList<OnScriptEventListener> arr = eventMap.get(eventName);
if (arr == null) {
return false;
}
arr.remove(listener);
return true;
}
/**
* Remove all listener for event specified.
*/
public void removeAllListenersForEvent(String eventName) {
this.eventMap.remove(eventName);
}
/**
* Remove all event registered. Use it carefully!
*/
public void removeAllListeners() {
this.eventMap.clear();
}
/**
* Dispatch the event with argument, the event should be registered in javascript, or other script language in future.
*/
public void dispatchEventToScript(String eventName, String arg) {
JsbBridge.sendToScript(eventName, arg);
}
/**
* Dispatch the event which is registered in javascript, or other script language in future.
*/
public void dispatchEventToScript(String eventName) {
JsbBridge.sendToScript(eventName);
}
private JsbBridgeWrapper() {
JsbBridge.setCallback(new JsbBridge.ICallback() {
@Override
public void onScript(String arg0, String arg1) {
triggerEvents(arg0, arg1);
}
});
}
private final HashMap<String, ArrayList<OnScriptEventListener>> eventMap = new HashMap<>();
private static JsbBridgeWrapper instance;
private void triggerEvents(String eventName, String arg) {
ArrayList<OnScriptEventListener> arr = eventMap.get(eventName);
if (arr == null)
return;
for (OnScriptEventListener m : arr) {
m.onScriptEvent(arg);
}
}
}
@@ -29,6 +29,7 @@
#import <Metal/MTLCommandQueue.h>
#import <MetalKit/MTKView.h>
#include <bitset>
#include "MTLComputeCommandEncoder.h"
#include "MTLGPUObjects.h"
#include "MTLRenderCommandEncoder.h"
@@ -94,7 +95,7 @@ protected:
void bindDescriptorSets();
void updateDepthStencilState(uint32_t subPassIndex, MTLRenderPassDescriptor *descriptor);
static bool isRenderingEntireDrawable(const Rect &rect, const CCMTLFramebuffer *renderPass);
id<MTLCommandBuffer> getMTLCommandBuffer();
vector<CCMTLGPUDescriptorSet *> _GPUDescriptorSets; // NOLINT(bugprone-reserved-identifier)
@@ -112,8 +113,10 @@ protected:
MTLPrimitiveType _mtlPrimitiveType = MTLPrimitiveType::MTLPrimitiveTypeTriangle;
CCMTLGPUCommandBufferObject *_gpuCommandBufferObj = nullptr;
CCMTLSemaphore* _texCopySemaphore = nullptr;
CCMTLSemaphore *_texCopySemaphore = nullptr;
std::bitset<MAX_COLORATTACHMENTS> _colorAppearedBefore;
};
} // namespace gfx
@@ -126,6 +126,8 @@ void CCMTLCommandBuffer::begin(RenderPass *renderPass, uint subpass, Framebuffer
_firstDirtyDescriptorSet = UINT_MAX;
_commandBufferBegan = true;
_firstRenderPass = true;
_colorAppearedBefore.reset();
}
void CCMTLCommandBuffer::end() {
@@ -162,6 +164,7 @@ void CCMTLCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb
// if not rendering to full framebuffer(eg. left top area), draw a quad to pretend viewport clear.
bool renderingFullFramebuffer = isRenderingEntireDrawable(renderArea, static_cast<CCMTLFramebuffer *>(fbo));
bool needPartialClear = false;
if (subpasses.empty()) {
if (dsTexture) {
auto *ccMtlTexture = static_cast<CCMTLTexture *>(dsTexture);
@@ -181,10 +184,16 @@ void CCMTLCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb
ccMtlRenderPass->setColorAttachment(i, ccMtlTexture, 0);
mtlRenderPassDescriptor.colorAttachments[i].clearColor = mu::toMTLClearColor(colors[i]);
if(!renderingFullFramebuffer) {
mtlRenderPassDescriptor.colorAttachments[i].loadAction = _firstRenderPass ? MTLLoadActionClear : MTLLoadActionLoad;
if(!_colorAppearedBefore[i]) {
mtlRenderPassDescriptor.colorAttachments[i].loadAction = mu::toMTLLoadAction(colorAttachments[i].loadOp);
} else {
mtlRenderPassDescriptor.colorAttachments[i].loadAction = MTLLoadActionLoad;
needPartialClear = colorAttachments[i].loadOp == LoadOp::CLEAR;
}
} else {
mtlRenderPassDescriptor.colorAttachments[i].loadAction = mu::toMTLLoadAction(colorAttachments[i].loadOp);
}
_colorAppearedBefore.set(i);
mtlRenderPassDescriptor.colorAttachments[i].storeAction = mu::isFramebufferFetchSupported() ? mu::toMTLStoreAction(colorAttachments[i].storeOp) : MTLStoreActionStore;
}
}
@@ -211,12 +220,18 @@ void CCMTLCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb
ccMtlRenderPass->setColorAttachment(color, ccMtlTexture, 0);
mtlRenderPassDescriptor.colorAttachments[color].clearColor = mu::toMTLClearColor(colors[color]);
if(!renderingFullFramebuffer) {
mtlRenderPassDescriptor.colorAttachments[color].loadAction = _firstRenderPass ? MTLLoadActionClear : MTLLoadActionLoad;
if(!_colorAppearedBefore[color]) {
mtlRenderPassDescriptor.colorAttachments[color].loadAction = mu::toMTLLoadAction(colorAttachments[color].loadOp);
} else {
mtlRenderPassDescriptor.colorAttachments[color].loadAction = MTLLoadActionLoad;
needPartialClear = colorAttachments[color].loadOp == LoadOp::CLEAR;
}
} else {
mtlRenderPassDescriptor.colorAttachments[color].loadAction = mu::toMTLLoadAction(colorAttachments[color].loadOp);
}
mtlRenderPassDescriptor.colorAttachments[color].storeAction = mu::isFramebufferFetchSupported() ? mu::toMTLStoreAction(colorAttachments[color].storeOp) : MTLStoreActionStore;
visited[color] = true;
_colorAppearedBefore.set(color);
if (subpasses[i].resolves.size() > j) {
uint32_t resolve = subpasses[i].resolves[j];
auto * resolveTex = static_cast<CCMTLTexture *>(colorTextures[resolve]);
@@ -259,7 +274,7 @@ void CCMTLCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *fb
//[_renderEncoder.getMTLEncoder() memoryBarrierWithScope:MTLBarrierScopeTextures afterStages:MTLRenderStageFragment beforeStages:MTLRenderStageFragment];
}
if (!renderingFullFramebuffer) {
if (!renderingFullFramebuffer && needPartialClear) {
//Metal doesn't apply the viewports and scissors to renderpass load-action clearing.
mu::clearRenderArea(_mtlDevice, _renderEncoder.getMTLEncoder(), renderPass, renderArea, colors, depth, stencil);
}
@@ -369,6 +384,22 @@ void CCMTLCommandBuffer::updateDepthStencilState(uint32_t index, MTLRenderPassDe
}
}
} else if(curRenderPass->getDepthStencilAttachment().format != Format::UNKNOWN) {
if(index == 0) {
descriptor.depthAttachment.loadAction = dsAttachment.depthLoadOp == LoadOp::LOAD ? MTLLoadActionLoad : MTLLoadActionClear;
descriptor.stencilAttachment.loadAction = dsAttachment.stencilLoadOp == LoadOp::LOAD ? MTLLoadActionLoad : MTLLoadActionClear;
} else {
descriptor.depthAttachment.loadAction = MTLLoadActionLoad;
descriptor.stencilAttachment.loadAction = MTLLoadActionLoad;
}
//storeop
if(index == subpasses.size() - 1) {
descriptor.depthAttachment.storeAction = dsAttachment.depthStoreOp == StoreOp::STORE ? MTLStoreActionStore : MTLStoreActionDontCare;
descriptor.stencilAttachment.storeAction = dsAttachment.stencilStoreOp == StoreOp::STORE ? MTLStoreActionStore : MTLStoreActionDontCare;
} else {
descriptor.depthAttachment.storeAction = MTLStoreActionStore;
descriptor.stencilAttachment.storeAction = MTLStoreActionStore;
}
}
}
@@ -475,8 +506,9 @@ void CCMTLCommandBuffer::nextSubpass() {
const auto colorAttachmentCount = colorAttachments.size();
const SubpassInfoList &subpasses = curRenderPass->getSubpasses();
for (size_t slot = 0U; slot < colorAttachmentCount; slot++) {
mtlRenderPassDescriptor.colorAttachments[slot].loadAction = MTLLoadActionLoad; // mu::toMTLLoadAction(colorAttachments[slot].loadOp);
mtlRenderPassDescriptor.colorAttachments[slot].loadAction = _colorAppearedBefore[slot] ? MTLLoadActionLoad : mu::toMTLLoadAction(colorAttachments[slot].loadOp);
mtlRenderPassDescriptor.colorAttachments[slot].storeAction = curSubpassIndex == subpasses.size() - 1 ? mu::toMTLStoreAction(colorAttachments[slot].storeOp) : MTLStoreActionStore;
_colorAppearedBefore.set(slot);
}
updateDepthStencilState(curSubpassIndex, mtlRenderPassDescriptor);
_renderEncoder.initialize(getMTLCommandBuffer(), ccRenderpass->getMTLRenderPassDescriptor());
@@ -34,8 +34,8 @@
#import <QuartzCore/CAMetalLayer.h>
#import "../../base/Utils.h"
#import "MTLConfig.h"
#import "MTLUtils.h"
#import "MTLDevice.h"
#import "MTLUtils.h"
namespace cc {
namespace gfx {
class CCMTLBuffer;
@@ -53,6 +53,8 @@ namespace {
constexpr size_t MegaBytesToBytes = 1024 * 1024;
}
constexpr size_t MAX_COLORATTACHMENTS = 16u;
class CCMTLGPUDescriptorSetLayout : public Object {
public:
DescriptorSetLayoutBindingList bindings;
@@ -106,8 +108,8 @@ public:
NSString *shaderSrc = nil;
bool specializeColor = true;
uint32_t bufferIndex = 0;
uint32_t bufferIndex = 0;
uint32_t samplerIndex = 0;
};
@@ -269,9 +269,14 @@ void CCMTLTexture::doResize(uint width, uint height, uint size) {
CC_LOG_ERROR("CCMTLTexture: create MTLTexture failed when try to resize the texture.");
return;
}
CCMTLDevice::getInstance()->getMemoryStatus().textureSize += size;
// texture is a wrapper of drawable when _swapchain is active, drawable is not a resource alloc by gfx,
// but the system so skip here.
if(!_swapchain) {
CCMTLDevice::getInstance()->getMemoryStatus().textureSize -= oldSize;
CCMTLDevice::getInstance()->getMemoryStatus().textureSize += size;
}
if (oldMTLTexture) {
std::function<void(void)> destroyFunc = [=]() {
if (oldMTLTexture) {
@@ -282,7 +287,6 @@ void CCMTLTexture::doResize(uint width, uint height, uint size) {
};
//gpu object only
CCMTLGPUGarbageCollectionPool::getInstance()->collect(destroyFunc);
CCMTLDevice::getInstance()->getMemoryStatus().textureSize -= oldSize;
}
}
@@ -310,4 +314,4 @@ void CCMTLTexture::deleteDefaultTexture(){
} // namespace gfx
} // namespace cc
} // namespace cc
+43 -9
View File
@@ -314,24 +314,58 @@ bool isASTCFormat(Format format) {
}
}
gfx::Shader *createShader(CCMTLDevice *device) {
gfx::Shader *createShader(CCMTLDevice *device, CCMTLRenderPass* renderPass) {
String vs = R"(
layout(location = 0) in vec2 a_position;
void main() {
gl_Position = vec4(a_position, 1.0, 1.0);
}
)";
// String fs = R"(
// precision mediump float;
// layout(set = 0, binding = 0) uniform Color {
// vec4 u_color;
// };
// layout(location = 0) out vec4 o_color;
//
// void main() {
// o_color = u_color;
// }
// )";
String fs = R"(
precision mediump float;
layout(set = 0, binding = 0) uniform Color {
vec4 u_color;
};
layout(location = 0) out vec4 o_color;
void main() {
o_color = u_color;
}
)";
//TODO_Zeqiang: gather info in framegraph.
if(renderPass->getSubpasses().empty()) {
for (size_t i = 0; i < renderPass->getColorAttachments().size(); ++i) {
fs += "\n layout(location = " + std::to_string(i) + ") out vec4 o_color" + std::to_string(i) + ";";
}
fs += "\nvoid main() {\n o_color0 = u_color;\n";
for (size_t i = 1; i < renderPass->getColorAttachments().size(); ++i) {
fs += " o_color" + std::to_string(i) + " = vec4(0.0);\n";
}
} else {
const auto& subpasses = renderPass->getSubpasses();
for (size_t i = 0; i < subpasses[renderPass->getCurrentSubpassIndex()].colors.size(); ++i) {
fs += "\n layout(location = " + std::to_string(i) + ") out vec4 o_color" + std::to_string(i) + ";";
}
fs += "\nvoid main() {\n o_color0 = u_color;\n";
for (size_t i = 1; i < subpasses[renderPass->getCurrentSubpassIndex()].colors.size(); ++i) {
fs += " o_color" + std::to_string(i) + " = vec4(0.0);\n";
}
}
fs += "}";
gfx::ShaderStageList shaderStageList;
gfx::ShaderStage vertexShaderStage;
vertexShaderStage.stage = gfx::ShaderStageFlagBit::VERTEX;
@@ -367,7 +401,7 @@ CCMTLGPUPipelineState *getClearRenderPassPipelineState(CCMTLDevice *device, Rend
gfx::Attribute position = {"a_position", gfx::Format::RG32F, false, 0, false};
gfx::PipelineStateInfo pipelineInfo;
pipelineInfo.primitive = gfx::PrimitiveMode::TRIANGLE_LIST;
pipelineInfo.shader = createShader(device);
pipelineInfo.shader = createShader(device, static_cast<CCMTLRenderPass*>(curPass));
pipelineInfo.inputState = {{position}};
pipelineInfo.renderPass = curPass;
@@ -877,7 +911,7 @@ bool mu::isImageBlockSupported() {
if(!mu::isFramebufferFetchSupported()) {
return false;
}
#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) || TARGET_CPU_ARM64
#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) //|| TARGET_CPU_ARM64
return true;
#else
return false;
@@ -885,7 +919,7 @@ bool mu::isImageBlockSupported() {
}
bool mu::isFramebufferFetchSupported() {
#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) || TARGET_CPU_ARM64
#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS) //|| TARGET_CPU_ARM64
return true;
#else
return false;
@@ -608,7 +608,6 @@ void cmdFuncCCVKCreateRenderPass(CCVKDevice *device, CCVKGPURenderPass *gpuRende
// first, gather necessary statistics for each attachment
auto updateLifeCycle = [](AttachmentStatistics &statistics, uint32_t index, VkImageLayout layout, AttachmentStatistics::SubpassUsage usage) {
if (statistics.records.count(index)) {
CC_ASSERT(statistics.records[index].layout == layout);
statistics.records[index].usage |= usage;
} else {
statistics.records[index] = {layout, usage};
@@ -229,8 +229,10 @@ void ClusterLightCulling::updateLights() {
break;
}
}
// the count of lights is set to cc_lightDir[0].w
_lightBufferData[3 * 4 + 3] = static_cast<float>(validLightCount);
if (validLightCount > 0) {
// the count of lights is set to cc_lightDir[0].w
_lightBufferData[3 * 4 + 3] = static_cast<float>(validLightCount);
}
}
void ClusterLightCulling::initBuildingSatge() {
@@ -661,6 +663,7 @@ void ClusterLightCulling::clusterLightCulling(scene::Camera* camera) {
if (!_initialized || _pipeline->getPipelineUBO()->getCurrentCameraUBOOffset() != 0) return;
_camera = camera;
update(); // update ubo and light data
if (_validLights.empty()) return;
struct DataClusterBuild {
framegraph::BufferHandle clusterBuffer; // cluster build storage buffer
@@ -161,10 +161,10 @@ void PipelineUBO::updateCameraUBOView(const RenderPipeline *pipeline, float *out
output[UBOCamera::GLOBAL_NEAR_FAR_OFFSET + 0] = static_cast<float>(camera->nearClip);
output[UBOCamera::GLOBAL_NEAR_FAR_OFFSET + 1] = static_cast<float>(camera->farClip);
output[UBOCamera::GLOBAL_VIEW_PORT_OFFSET + 0] = camera->viewPort.x;
output[UBOCamera::GLOBAL_VIEW_PORT_OFFSET + 1] = camera->viewPort.y;
output[UBOCamera::GLOBAL_VIEW_PORT_OFFSET + 2] = camera->viewPort.z;
output[UBOCamera::GLOBAL_VIEW_PORT_OFFSET + 3] = camera->viewPort.w;
output[UBOCamera::GLOBAL_VIEW_PORT_OFFSET + 0] = sharedData->shadingScale * camera->window->getWidth() * camera->viewPort.x;
output[UBOCamera::GLOBAL_VIEW_PORT_OFFSET + 1] = sharedData->shadingScale * camera->window->getHeight() * camera->viewPort.y;
output[UBOCamera::GLOBAL_VIEW_PORT_OFFSET + 2] = sharedData->shadingScale * camera->window->getWidth() * camera->viewPort.z;
output[UBOCamera::GLOBAL_VIEW_PORT_OFFSET + 3] = sharedData->shadingScale * camera->window->getHeight() * camera->viewPort.w;
}
void PipelineUBO::updateShadowUBOView(const RenderPipeline *pipeline, std::array<float, UBOShadow::COUNT> *bufferView, const scene::Camera *camera) {
@@ -34,9 +34,9 @@
#include "gfx-base/GFXCommandBuffer.h"
#include "gfx-base/GFXDevice.h"
#include "gfx-base/GFXShader.h"
#include "scene/AABB.h"
#include "scene/Model.h"
#include "scene/RenderScene.h"
#include "scene/AABB.h"
namespace cc {
namespace pipeline {
@@ -109,7 +109,7 @@ void PlanarShadowQueue::recordCommandBuffer(gfx::Device *device, gfx::RenderPass
const PipelineSceneData * sceneData = _pipeline->getPipelineSceneData();
const scene::PipelineSharedSceneData *sharedData = sceneData->getSharedData();
const scene::Shadow * shadowInfo = sharedData->shadow;
if (!shadowInfo->enabled || shadowInfo->shadowType != scene::ShadowType::PLANAR) {
if (!shadowInfo->enabled || shadowInfo->shadowType != scene::ShadowType::PLANAR || shadowInfo->normal.length() < 0.000001F) {
return;
}
@@ -25,6 +25,7 @@
#include "DeferredPipeline.h"
#include "../SceneCulling.h"
#include "../helper/Utils.h"
#include "../shadow/ShadowFlow.h"
#include "MainFlow.h"
#include "gfx-base/GFXBuffer.h"
@@ -34,7 +35,6 @@
#include "gfx-base/GFXDevice.h"
#include "gfx-base/GFXSwapchain.h"
#include "gfx-base/states/GFXTextureBarrier.h"
#include "../helper/Utils.h"
namespace cc {
namespace pipeline {
@@ -50,7 +50,6 @@ namespace pipeline {
framegraph::StringHandle DeferredPipeline::fgStrHandleGbufferTexture[GBUFFER_COUNT] = {
framegraph::FrameGraph::stringToHandle("gbufferAlbedoTexture"),
framegraph::FrameGraph::stringToHandle("gbufferPositionTexture"),
framegraph::FrameGraph::stringToHandle("gbufferNormalTexture"),
framegraph::FrameGraph::stringToHandle("gbufferEmissiveTexture")};
@@ -31,8 +31,8 @@
#include "gfx-base/GFXBuffer.h"
#include "gfx-base/GFXInputAssembler.h"
#include "pipeline/ClusterLightCulling.h"
#include "pipeline/RenderPipeline.h"
#include "pipeline/Enum.h"
#include "pipeline/RenderPipeline.h"
#include "scene/RenderWindow.h"
namespace cc {
@@ -69,7 +69,7 @@ private:
ClusterLightCulling *_clusterComp{nullptr};
public:
static constexpr uint GBUFFER_COUNT = 4;
static constexpr uint GBUFFER_COUNT = 3;
// deferred resource names
static framegraph::StringHandle fgStrHandleGbufferTexture[GBUFFER_COUNT];
@@ -146,8 +146,8 @@ void GbufferStage::render(scene::Camera *camera) {
framegraph::TextureHandle depth;
};
auto *pipeline = static_cast<DeferredPipeline *>(_pipeline);
float shadingScale{_pipeline->getPipelineSceneData()->getSharedData()->shadingScale};
auto *pipeline = static_cast<DeferredPipeline *>(_pipeline);
float shadingScale{_pipeline->getPipelineSceneData()->getSharedData()->shadingScale};
_renderArea = RenderPipeline::getRenderArea(camera);
auto gbufferSetup = [&](framegraph::PassNodeBuilder &builder, RenderData &data) {
@@ -169,7 +169,7 @@ void GbufferStage::render(scene::Camera *camera) {
static_cast<uint>(pipeline->getHeight() * shadingScale),
};
for (int i = 0; i < DeferredPipeline::GBUFFER_COUNT - 1; ++i) {
if (i != 0) { // positions & normals need more precision
if (i != 0) { // normals need more precision
data.gbuffer[i] = builder.create(DeferredPipeline::fgStrHandleGbufferTexture[i], gbufferInfoFloat);
} else {
data.gbuffer[i] = builder.create(DeferredPipeline::fgStrHandleGbufferTexture[i], gbufferInfo);
@@ -178,10 +178,10 @@ void GbufferStage::render(scene::Camera *camera) {
auto subpassEnabled = _device->hasFeature(gfx::Feature::INPUT_ATTACHMENT_BENEFIT);
if (subpassEnabled) {
// when subpass enabled, the color result (gles2/gles3) will write to gbuffer[3] and the blit to color texture, so the format should be RGBA16F
data.gbuffer[3] = builder.create(DeferredPipeline::fgStrHandleGbufferTexture[3], gbufferInfoFloat);
// when subpass enabled, the color result (gles2/gles3) will write to gbuffer[2] and the blit to color texture, so the format should be RGBA16F
data.gbuffer[2] = builder.create(DeferredPipeline::fgStrHandleGbufferTexture[2], gbufferInfoFloat);
} else {
data.gbuffer[3] = builder.create(DeferredPipeline::fgStrHandleGbufferTexture[3], gbufferInfo);
data.gbuffer[2] = builder.create(DeferredPipeline::fgStrHandleGbufferTexture[2], gbufferInfo);
}
gfx::Color clearColor{0.0, 0.0, 0.0, 0.0};
@@ -320,7 +320,7 @@ void LightingStage::fgLightingPass(scene::Camera *camera) {
}
struct RenderData {
framegraph::TextureHandle gbuffer[4]; // read from gbuffer stage
framegraph::TextureHandle gbuffer[3]; // read from gbuffer stage
framegraph::TextureHandle outputTex; // output texture
framegraph::TextureHandle depth;
framegraph::BufferHandle lightBuffer; // light storage buffer
@@ -338,30 +338,29 @@ void LightingStage::fgLightingPass(scene::Camera *camera) {
builder.subpass(true);
// read gbuffer
for (int i = 0; i < 4; i++) {
for (int i = 0; i < 3; i++) {
data.gbuffer[i] = builder.read(framegraph::TextureHandle(builder.readFromBlackboard(DeferredPipeline::fgStrHandleGbufferTexture[i])));
builder.writeToBlackboard(DeferredPipeline::fgStrHandleGbufferTexture[i], data.gbuffer[i]);
}
// read depth, as an attachment
framegraph::RenderTargetAttachment::Descriptor depthAttachmentInfo;
depthAttachmentInfo.usage = framegraph::RenderTargetAttachment::Usage::DEPTH_STENCIL;
depthAttachmentInfo.loadOp = gfx::LoadOp::LOAD;
depthAttachmentInfo.beginAccesses = {gfx::AccessType::DEPTH_STENCIL_ATTACHMENT_WRITE};
depthAttachmentInfo.endAccesses = {gfx::AccessType::DEPTH_STENCIL_ATTACHMENT_WRITE};
data.depth = framegraph::TextureHandle(builder.readFromBlackboard(RenderPipeline::fgStrHandleOutDepthTexture));
data.depth = builder.write(data.depth, depthAttachmentInfo);
data.depth = builder.read(data.depth);
builder.writeToBlackboard(RenderPipeline::fgStrHandleOutDepthTexture, data.depth);
if (_pipeline->getClusterEnabled()) {
// read cluster and light info
data.lightBuffer = framegraph::BufferHandle(builder.readFromBlackboard(fgStrHandleClusterLightBuffer));
builder.read(data.lightBuffer);
if (data.lightBuffer.isValid()) {
builder.read(data.lightBuffer);
}
data.lightIndexBuffer = framegraph::BufferHandle(builder.readFromBlackboard(fgStrHandleClusterLightIndexBuffer));
builder.read(data.lightIndexBuffer);
if (data.lightIndexBuffer.isValid()) {
builder.read(data.lightIndexBuffer);
}
data.lightGridBuffer = framegraph::BufferHandle(builder.readFromBlackboard(fgStrHandleClusterLightGridBuffer));
builder.read(data.lightGridBuffer);
if (data.lightGridBuffer.isValid()) {
builder.read(data.lightGridBuffer);
}
}
// write to lighting output
@@ -407,12 +406,20 @@ void LightingStage::fgLightingPass(scene::Camera *camera) {
pass->getDescriptorSet()->bindTexture(i, table.getRead(data.gbuffer[i]));
pass->getDescriptorSet()->bindSampler(i, _defaultSampler);
}
pass->getDescriptorSet()->bindTexture(3, table.getRead(data.depth));
pass->getDescriptorSet()->bindSampler(3, _defaultSampler);
if (_pipeline->getClusterEnabled()) {
// cluster buffer bind
pass->getDescriptorSet()->bindBuffer(CLUSTER_LIGHT_BINDING, table.getRead(data.lightBuffer));
pass->getDescriptorSet()->bindBuffer(CLUSTER_LIGHT_INDEX_BINDING, table.getRead(data.lightIndexBuffer));
pass->getDescriptorSet()->bindBuffer(CLUSTER_LIGHT_GRID_BINDING, table.getRead(data.lightGridBuffer));
if (data.lightBuffer.isValid()) {
pass->getDescriptorSet()->bindBuffer(CLUSTER_LIGHT_BINDING, table.getRead(data.lightBuffer));
}
if (data.lightIndexBuffer.isValid()) {
pass->getDescriptorSet()->bindBuffer(CLUSTER_LIGHT_INDEX_BINDING, table.getRead(data.lightIndexBuffer));
}
if (data.lightGridBuffer.isValid()) {
pass->getDescriptorSet()->bindBuffer(CLUSTER_LIGHT_GRID_BINDING, table.getRead(data.lightGridBuffer));
}
}
pass->getDescriptorSet()->update();
@@ -492,8 +499,11 @@ void LightingStage::fgTransparent(scene::Camera *camera) {
auto *pipeline = static_cast<DeferredPipeline *>(_pipeline);
auto *cmdBuff = pipeline->getCommandBuffers()[0];
vector<uint> dynamicOffsets = {0};
cmdBuff->bindDescriptorSet(localSet, _descriptorSet, dynamicOffsets);
// no need to bind localSet in cluster
if (!_pipeline->getClusterEnabled()) {
vector<uint> dynamicOffsets = {0};
cmdBuff->bindDescriptorSet(localSet, _descriptorSet, dynamicOffsets);
}
const std::array<uint, 1> globalOffsets = {pipeline->getPipelineUBO()->getCurrentCameraUBOOffset()};
cmdBuff->bindDescriptorSet(globalSet, pipeline->getDescriptorSet(), utils::toUint(globalOffsets.size()), globalOffsets.data());
@@ -534,8 +544,7 @@ void LightingStage::putTransparentObj2Queue() {
// TODO(xwx): need to fallback unlit and gizmo material.
if (pass->getPhase() != _phaseID) continue;
for (k = 0; k < _renderQueues.size(); k++) {
_isTransparentQueueEmpty = false;
_renderQueues[k]->insertRenderPass(ro, m, p);
if (_renderQueues[k]->insertRenderPass(ro, m, p)) _isTransparentQueueEmpty = false;
}
p++;
}
+9 -1
View File
@@ -326,7 +326,15 @@ void removeKeyboardEventLisnters() {
}
- (void)keyboardWillHide:(NSNotification *)notification {
cc::EditBox::hide();
NSDictionary *info = [notification userInfo];
CGRect beginKeyboardRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
CGRect endKeyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
CGFloat yOffset = endKeyboardRect.origin.y - beginKeyboardRect.origin.y;
if (yOffset <= 0) {
cc::EditBox::hide();
}
}
@end
+2 -2
View File
@@ -1,9 +1,9 @@
{
"version": "v3d-gfx-85",
"version": "v3d-gfx-88",
"from": {
"type": "github",
"owner": "cocos-creator",
"name": "engine-native-external",
"checkout": "v3d-gfx-85"
"checkout": "v3d-gfx-88"
}
}