ohos android x86_64

This commit is contained in:
helloworldlv
2024-07-12 11:44:27 +08:00
parent c02f490671
commit 7031e1dd61
2507 changed files with 445054 additions and 21928 deletions
+2
View File
@@ -39,3 +39,5 @@ liblaya.so
.gradle
*.d
*.bc
Conch/build/build
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
OHOS_NDK_CMAKE_PATH="E:/huawei/devecostudio-windows-5.0.3.200/sdk/WinSDK/HarmonyOS-NEXT-DP2/base/native/build-tools/cmake/bin"
OHOS_NDK_CMAKE_TOOLCHAIN_PATH="E:/huawei/devecostudio-windows-5.0.3.200/sdk/WinSDK/HarmonyOS-NEXT-DP2/base/native/build/cmake/ohos.toolchain.cmake"
#export PATH=${OHOS_NDK_CMAKE_PATH}:$PATH
mkdir build
cd build
${OHOS_NDK_CMAKE_PATH}/cmake.exe -G "Ninja" -DCMAKE_BUILD_TYPE=Release \ -DOHOS_STL=c++_shared -DCMAKE_TOOLCHAIN_FILE=${OHOS_NDK_CMAKE_TOOLCHAIN_PATH} ../conch/proj.ohos
${OHOS_NDK_CMAKE_PATH}/cmake.exe --build .
# 如果需要编译静态库则需要设置 cmake 变量 -DBUILD_SHARED_LIBS=OFF
# 可以通过-DCMAKE_INSTALL_PREFIX=xxx 设置库的安装目录
# 编译 arm32 -DOHOS_ARCH=armeabi-v7a
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
export PATH=/Users/joychina/Desktop/lvfulong/android-ndk-r21e:$PATH
export NDK_DIR=/Users/joychina/Desktop/lvfulong/android-ndk-r21e
./buildAll-android.sh
+48
View File
@@ -0,0 +1,48 @@
@echo off
set ANDROID_SDK_TOOLS=D:/Program Files/androidStudioSDK/tools
set ANDROID_NDK_ROOT=D:/BaiduNetdiskDownload/android-ndk-r21e-windows-x86_64/android-ndk-r21e
set PATH=%ANDROID_SDK_TOOLS%;%ANDROID_NDK_ROOT%
REM 进入common模块的jni目录并执行ndk-build
cd /d common\proj.android_studio\jni
ndk-build
cd /d ..\..\..\
REM 进入render模块的jni目录并执行ndk-build
cd /d render\proj.android_studio\jni
ndk-build
cd /d ..\..\..\
REM 复制common模块的库文件到指定目录
xcopy common\proj.android_studio\obj\local\armeabi-v7a\libcommon.a ..\libs\android-armv7\ /Y
xcopy render\proj.android_studio\obj\local\armeabi-v7a\librender.a ..\libs\android-armv7\ /Y
REM xcopy webglPlus\proj.android_studio\obj\local\armeabi-v7a\libwebglPlus.a ..\libs\android-armv7\ /Y
REM 复制库文件到android-arm64目录
xcopy common\proj.android_studio\obj\local\arm64-v8a\libcommon.a ..\libs\android-arm64\ /Y
xcopy render\proj.android_studio\obj\local\arm64-v8a\librender.a ..\libs\android-arm64\ /Y
REM xcopy webglPlus\proj.android_studio\obj\local\arm64-v8a\libwebglPlus.a ..\libs\android-arm64\ /Y
REM 复制库文件到android-x86目录
xcopy common\proj.android_studio\obj\local\x86\libcommon.a ..\libs\android-x86\ /Y
xcopy render\proj.android_studio\obj\local\x86\librender.a ..\libs\android-x86\ /Y
REM xcopy webglPlus\proj.android_studio\obj\local\x86\libwebglPlus.a ..\libs\android-x86\ /Y
REM 触碰JCConch.cpp, 触发重建
REM echo. > ..\source\conch\JCConch.cpp
REM 编译conch模块
cd /d conch\proj.android_studio\jni
ndk-build
cd /d ..\..\..\
REM 复制获得的liblayaair.so文件到指定目录
xcopy conch\proj.android_studio\libs\arm64-v8a\liblayaair.so conch\proj.android_studio\conch5\libs\arm64-v8a\ /Y
xcopy conch\proj.android_studio\libs\armeabi-v7a\liblayaair.so conch\proj.android_studio\conch5\libs\armeabi-v7a\ /Y
xcopy conch\proj.android_studio\libs\x86\liblayaair.so conch\proj.android_studio\conch5\libs\x86\ /Y
REM 递归复制libs目录到conch5
xcopy conch\proj.android_studio\libs\ conch\proj.android_studio\conch5\ /E /I /Y
+5
View File
@@ -22,6 +22,10 @@ cp render/proj.android_studio/obj/local/x86/librender.a ../libs/android-x86/
#cp common/proj.android_studio/obj/local/armeabi/libcommon.a ../libs/android-arm/
#cp render/proj.android_studio/obj/local/armeabi/librender.a ../libs/android-arm/
cp common/proj.android_studio/obj/local/x86_64/libcommon.a ../libs/android-x86_64/
cp render/proj.android_studio/obj/local/x86_64/librender.a ../libs/android-x86_64/
touch ../source/conch/JCConch.cpp
cd conch/proj.android_studio/jni/
ndk-build
@@ -29,5 +33,6 @@ cd ../../../
cp conch/proj.android_studio/libs/arm64-v8a/liblayaair.so conch/proj.android_studio/conch5/libs/arm64-v8a/liblayaair.so
cp conch/proj.android_studio/libs/armeabi-v7a/liblayaair.so conch/proj.android_studio/conch5/libs/armeabi-v7a/liblayaair.so
cp conch/proj.android_studio/libs/x86/liblayaair.so conch/proj.android_studio/conch5/libs/x86/liblayaair.so
cp conch/proj.android_studio/libs/x86_64/liblayaair.so conch/proj.android_studio/conch5/libs/x86_64/liblayaair.so
cp conch/proj.android_studio/libs/ conch/proj.android_studio/conch5/ -f -R
@@ -17,7 +17,7 @@ LOCAL_CFLAGS := \
-DBT_USE_DOUBLE_PRECISION \
-frtti
LOCAL_CPPFLAGS += -std=c++11
LOCAL_CPPFLAGS += -std=c++17
ifeq ($(APP_PERFTEST),1)
LOCAL_CFLAGS += -DPERFTEST
@@ -63,6 +63,7 @@ LOCAL_SRC_FILES := \
../../../../source/common/util/JCZlib.cpp \
../../../../source/common/util/Log.cpp \
../../../../source/common/util/JCFlog.cpp \
../../../../source/common/util/ColorParser.cpp \
../../../../source/common/math/JCBoundingBox.cpp \
../../../../source/common/math/JCBoundingFrustum.cpp \
../../../../source/common/math/JCBoundingSphere.cpp \
@@ -81,7 +82,7 @@ LOCAL_SRC_FILES := \
LOCAL_C_INCLUDES := ../../../../../ThirdParty/curl/include/android \
../../../../../ThirdParty/png/include/android \
../../../../../ThirdParty/jpeg/include/android \
../../../../../ThirdParty/jpeg-turbo/include/android \
../../../../../ThirdParty/freetype/include/android \
../../../../../ThirdParty/zip/include/android \
../../../../../ThirdParty/ogg/include/android \
@@ -3,5 +3,5 @@ APP_PLATFORM := android-21
NDK_TOOLCHAIN_VERSION := 4.9
APP_STL := c++_shared
APP_OPTIM := release
#使用硬件fp
APP_ABI :=armeabi-v7a arm64-v8a x86
#ʹӲfp
APP_ABI :=armeabi-v7a arm64-v8a x86 x86_64
@@ -11,6 +11,7 @@
24760D802081C3E600594375 /* JCFontInfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 24760D792081C3E500594375 /* JCFontInfo.cpp */; };
24760D812081C3E600594375 /* JCFontManager.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 24760D7C2081C3E500594375 /* JCFontManager.cpp */; };
5E6806501D7D504C002A7575 /* JCHttpHeader.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 5E68064E1D7D504C002A7575 /* JCHttpHeader.cpp */; };
8A23427F2C0D6EEB00960E8E /* ColorParser.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 8A23427D2C0D6EEB00960E8E /* ColorParser.cpp */; };
8A4296901B6757DB0072C3F7 /* libcommon.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 8A4296841B6757DB0072C3F7 /* libcommon.a */; };
8AEDB763288FBFDD00EE4A31 /* JCArrayBufferManager.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 8AEDB762288FBFDD00EE4A31 /* JCArrayBufferManager.cpp */; };
8AEDB767288FBFFE00EE4A31 /* JCWebGLPlus.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 8AEDB765288FBFFE00EE4A31 /* JCWebGLPlus.cpp */; };
@@ -87,6 +88,8 @@
24760D7D2081C3E500594375 /* JCFreeTypeRender.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JCFreeTypeRender.h; sourceTree = "<group>"; };
5E68064E1D7D504C002A7575 /* JCHttpHeader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = JCHttpHeader.cpp; sourceTree = "<group>"; };
5E68064F1D7D504C002A7575 /* JCHttpHeader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JCHttpHeader.h; sourceTree = "<group>"; };
8A23427D2C0D6EEB00960E8E /* ColorParser.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ColorParser.cpp; sourceTree = "<group>"; };
8A23427E2C0D6EEB00960E8E /* ColorParser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ColorParser.h; sourceTree = "<group>"; };
8A4296841B6757DB0072C3F7 /* libcommon.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libcommon.a; sourceTree = BUILT_PRODUCTS_DIR; };
8A42968F1B6757DB0072C3F7 /* commonTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = commonTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
8A4296951B6757DB0072C3F7 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
@@ -408,6 +411,8 @@
8A42A0671B675CEF0072C3F7 /* util */ = {
isa = PBXGroup;
children = (
8A23427D2C0D6EEB00960E8E /* ColorParser.cpp */,
8A23427E2C0D6EEB00960E8E /* ColorParser.h */,
A242E3E91D813D420013CCF0 /* JCFlog.cpp */,
A242E3EA1D813D420013CCF0 /* JCFlog.h */,
A2D11A001D0C2D65004C229D /* JCIniFile.cpp */,
@@ -634,6 +639,7 @@
A2D117861D0B9BB0004C229D /* JCCurlWrap.cpp in Sources */,
A2D117BE1D0B9C20004C229D /* JCLayaThreadPool.cpp in Sources */,
A2D117791D0B9B8B004C229D /* JCBuffer.cpp in Sources */,
8A23427F2C0D6EEB00960E8E /* ColorParser.cpp in Sources */,
A2D117811D0B9B9B004C229D /* JCServerFileCache.cpp in Sources */,
A2D117A61D0B9BF5004C229D /* JCImageRW.cpp in Sources */,
A2FBA970270432F900846E17 /* JCPlane.cpp in Sources */,
@@ -748,10 +754,11 @@
8A4296991B6757DB0072C3F7 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_CXX_LANGUAGE_STANDARD = "c++17";
CLANG_CXX_LIBRARY = "libc++";
OTHER_CFLAGS = (
"-I../../../../ThirdParty/freetype/include/ios",
"-I../../../../ThirdParty/jpeg/include/ios",
"-I../../../../ThirdParty/jpeg-turbo/include/ios",
"-I../../../../ThirdParty/zip/include/ios",
"-I../../../../ThirdParty/curl/include/ios",
"-I../../../../ThirdParty/png/include/ios",
@@ -770,12 +777,13 @@
8A42969A1B6757DB0072C3F7 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_CXX_LANGUAGE_STANDARD = "c++17";
CLANG_CXX_LIBRARY = "libc++";
DEBUG_INFORMATION_FORMAT = dwarf;
GCC_GENERATE_DEBUGGING_SYMBOLS = NO;
OTHER_CFLAGS = (
"-I../../../../ThirdParty/freetype/include/ios",
"-I../../../../ThirdParty/jpeg/include/ios",
"-I../../../../ThirdParty/jpeg-turbo/include/ios",
"-I../../../../ThirdParty/zip/include/ios",
"-I../../../../ThirdParty/curl/include/ios",
"-I../../../../ThirdParty/png/include/ios",
@@ -0,0 +1,67 @@
cmake_minimum_required(VERSION 3.6)
project(common)
set(common_src
../../../source/common/buffer/JCBuffer.cpp
../../../source/common/downloadCache/JCFileTable.cpp
../../../source/common/downloadCache/JCServerFileCache.cpp
../../../source/common/downloadMgr/JCCurlWrap.cpp
../../../source/common/downloadMgr/JCHttpHeader.cpp
../../../source/common/downloadMgr/JCDownloadMgr.cpp
../../../source/common/manager/JCArrayBufferManager.cpp
../../../source/common/event/JCEmitter.cpp
../../../source/common/event/JCEventBase.cpp
../../../source/common/fileSystem/JCFileSystem.cpp
../../../source/common/fontMgr/JCFreeTypeRender.cpp
../../../source/common/imageLib/JCImageRW.cpp
../../../source/common/imageLib/JCJpegImg.cpp
../../../source/common/imageLib/JCPngImg.cpp
../../../source/common/imageLib/JCGifImg.cpp
../../../source/common/math/Matrix32.cpp
../../../source/common/misc/JCGetClockExact.cpp
../../../source/common/misc/JCLayaThreadPool.cpp
../../../source/common/misc/JCWorkerThread.cpp
../../../source/common/misc/JCWorkSemaphore.cpp
../../../source/common/util/JCColor.cpp
../../../source/common/util/JCCommonMethed.cpp
../../../source/common/util/JCCrypto.cpp
../../../source/common/util/JCJson.cpp
../../../source/common/util/JCIniFile.cpp
../../../source/common/util/JCLayaUrl.cpp
../../../source/common/util/JCMemorySurvey.cpp
../../../source/common/util/JCXml.cpp
../../../source/common/util/JCZipFile.cpp
../../../source/common/util/JCZlib.cpp
../../../source/common/util/Log.cpp
../../../source/common/util/JCFlog.cpp
../../../source/common/math/JCBoundingBox.cpp
../../../source/common/math/JCBoundingFrustum.cpp
../../../source/common/math/JCBoundingSphere.cpp
../../../source/common/math/JCPlane.cpp
../../../source/common/webglplus/JCWebGLPlus.cpp
../../../source/common/resource/Audio/JCAudioWavplayer-openharmony.cpp
../../../source/common/resource/Audio/JCOggParser.cpp
../../../source/common/resource/Audio/JCWaveInfo.cpp
../../../source/common/resource/Audio/JCWaveParser.cpp
../../../source/common/fontMgr/JCFontInfo.cpp
../../../source/common/fontMgr/JCFontManager.cpp
../../../source/common/resource/JCFileResManager.cpp
../../../source/common/resource/JCResManager.cpp
../../../source/common/resource/JCResource.cpp
)
add_library(common STATIC ${common_src})
target_include_directories(common PUBLIC
../../../../ThirdParty/curl/include/ohos
../../../../ThirdParty/png/include/ohos
../../../../ThirdParty/jpeg-turbo/include/ohos
../../../../ThirdParty/freetype/include/ohos
../../../../ThirdParty/zip/include/ohos
../../../../ThirdParty/ogg/include/ohos
../../../../ThirdParty/zlib/include/ohos
../../../../ThirdParty/openal/include/ohos
../../../../Conch/source
)
set(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} -std=c++11")
target_compile_options(common PRIVATE -DV8_COMPRESS_POINTERS)
set(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} -DV8_COMPRESS_POINTERS")
target_compile_options(common PRIVATE -O3)
@@ -2821,7 +2821,7 @@ class GLCommandEncoder {
if (supports("GL_OES_depth_texture") || supports("GL_ARB_depth_texture") || supports("GL_ANGLE_depth_texture"))
result.push("WEBGL_depth_texture");
if (version.indexOf("OpenGL ES 3.") != -1) {
if (conchConfig.getOS() == "Conch-android") {
if (conchConfig.getOS() == "Conch-android" || conchConfig.getOS() == "Conch-ohos") {
result.push("WEBGL_compressed_texture_etc");
}
}
@@ -2949,7 +2949,7 @@ class GLCommandEncoder {
else if (name.indexOf('WEBGL_depth_texture') != -1 && ((supports("GL_OES_depth_texture") || supports("GL_ARB_depth_texture") || supports("GL_ANGLE_depth_texture")))) {
return { UNSIGNED_INT_24_8_WEBGL: 34042 };
}
else if (name.indexOf('WEBGL_compressed_texture_astc') != -1 && (extention.indexOf('GL_OES_texture_compression_astc') != -1 || extention.indexOf('GL_KHR_texture_compression_astc') != -1 || (conchConfig.getOS() == "Conch-android" && version.indexOf("OpenGL ES 3.") != -1 && version.indexOf("OpenGL ES 3.0") == -1))) {
else if (name.indexOf('WEBGL_compressed_texture_astc') != -1 && (extention.indexOf('GL_OES_texture_compression_astc') != -1 || extention.indexOf('GL_KHR_texture_compression_astc') != -1 || ((conchConfig.getOS() == "Conch-android" || conchConfig.getOS() == "Conch-ohos") && version.indexOf("OpenGL ES 3.") != -1 && version.indexOf("OpenGL ES 3.0") == -1))) {
return {
COMPRESSED_RGBA_ASTC_4x4_KHR: 0x93B0,
COMPRESSED_RGBA_ASTC_5x4_KHR: 0x93B1,
@@ -2981,7 +2981,7 @@ class GLCommandEncoder {
COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: 0x93DD,
};
}
else if (name.indexOf('WEBGL_compressed_texture_etc') != -1 && conchConfig.getOS() == "Conch-android" && version.indexOf("OpenGL ES 3.") != -1) {
else if (name.indexOf('WEBGL_compressed_texture_etc') != -1 && (conchConfig.getOS() == "Conch-android" || conchConfig.getOS() == "Conch-ohos") && version.indexOf("OpenGL ES 3.") != -1) {
return {
COMPRESSED_R11_EAC: 0x9270,
COMPRESSED_SIGNED_R11_EAC: 0x9271,
@@ -59,7 +59,7 @@ function initFreeType() {
if (sOS == "Conch-window") {
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile("C:/Windows/Fonts/simhei.ttf");
}
else if (sOS == "Conch-android") {
else if (sOS == "Conch-android" || sOS == "Conch-ohos") {
var fSystemVersion = navigator.sv;
if (fSystemVersion >= 2.0 && fSystemVersion < 5.0) {
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile("/system/fonts/DFHEIA5A.ttf");
@@ -19,7 +19,7 @@ LOCAL_CFLAGS := \
-DBT_USE_DOUBLE_PRECISION \
-DAL_ALEXT_PROTOTYPES \
LOCAL_CPPFLAGS += -std=c++11
LOCAL_CPPFLAGS += -std=c++17
ifeq ($(APP_PERFTEST),1)
LOCAL_CFLAGS += -DPERFTEST
endif
@@ -30,6 +30,12 @@ ifeq ($(TARGET_ARCH),arm64)
LOCAL_CFLAGS += -DV8_COMPRESS_POINTERS
LOCAL_CPPFLAGS += -DV8_COMPRESS_POINTERS
endif
ifeq ($(TARGET_ARCH),x86_64)
LOCAL_CFLAGS += -DV8_COMPRESS_POINTERS
LOCAL_CPPFLAGS += -DV8_COMPRESS_POINTERS
endif
LOCAL_SRC_FILES := \
../../../../source/conch/JSWrapper/v8debug/debug-agent.cpp \
../../../../source/conch/JSWrapper/v8debug/V8WSSv.cpp \
@@ -88,10 +94,10 @@ LOCAL_SRC_FILES := \
LOCAL_C_INCLUDES := ../../../../../ThirdParty/curl/include/android \
../../../../../ThirdParty/png/include/android \
../../../../../ThirdParty/jpeg/include/android \
../../../../../ThirdParty/jpeg-turbo/include/android \
../../../../../ThirdParty/freetype/include/android \
../../../../../ThirdParty/zip/include/android \
../../../../../ThirdParty/v8_8.8/include \
../../../../../ThirdParty/v8/include/android \
../../../../../ThirdParty/ogg/include/android \
../../../../../ThirdParty/websockets/include/android \
../../../../../ThirdParty/openssl/include/android \
@@ -107,16 +113,19 @@ ifeq ($(TARGET_ARCH),arm64)
LOCAL_IS64:=arm64
else ifeq ($(TARGET_ARCH),x86)
LOCAL_IS64:=x86
else ifeq ($(TARGET_ARCH),x86_64)
LOCAL_IS64:=x86_64
endif
LOCAL_DISABLE_FATAL_LINKER_WARNINGS := true
LOCAL_LDLIBS := -lOpenSLES -llog -lGLESv3 -landroid -ljnigraphics -lm -lz -lc++ \
../../../../libs/android-$(LOCAL_IS64)/librender.a \
../../../../libs/android-$(LOCAL_IS64)/libcommon.a \
../../../../../ThirdParty/curl/lib/android-$(LOCAL_IS64)/libcurl.a \
../../../../../ThirdParty/v8_8.8/lib/android-$(LOCAL_IS64)/libv8_monolith.a \
../../../../../ThirdParty/v8_8.8/lib/android-$(LOCAL_IS64)/libinspector.a \
../../../../../ThirdParty/v8/lib/android/$(LOCAL_IS64)/libv8_monolith.a \
../../../../../ThirdParty/v8/lib/android/$(LOCAL_IS64)/libinspector.a \
../../../../../ThirdParty/websockets/lib/android-$(LOCAL_IS64)/libwebsockets.a \
../../../../../ThirdParty/jpeg/lib/android-$(LOCAL_IS64)/libjpeg.a \
../../../../../ThirdParty/jpeg-turbo/lib/android/$(LOCAL_IS64)/libjpeg.a \
../../../../../ThirdParty/jpeg-turbo/lib/android/$(LOCAL_IS64)/libturbojpeg.a \
../../../../../ThirdParty/png/lib/android-$(LOCAL_IS64)/libpng.a \
../../../../../ThirdParty/freetype/lib/android-$(LOCAL_IS64)/libfreetype.a \
../../../../../ThirdParty/zip/lib/android-$(LOCAL_IS64)/libzip.a \
@@ -9,4 +9,4 @@ APP_OPTIM := release
APP_PERFTEST := 1
#使用硬件fp
APP_ABI :=armeabi-v7a arm64-v8a x86
APP_ABI :=armeabi-v7a arm64-v8a x86 x86_64
@@ -694,7 +694,7 @@
FRAMEWORK_SEARCH_PATHS = "$(inherited)";
GCC_PREPROCESSOR_DEFINITIONS = BT_USE_DOUBLE_PRECISION;
INFOPLIST_FILE = LayaBox/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 7.0;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
LIBRARY_SEARCH_PATHS = (
../../../../ThirdParty/zlib/lib/ios,
@@ -705,7 +705,7 @@
../../../../ThirdParty/websockets/lib/ios,
../../../../ThirdParty/openssl/lib/ios,
../../../../ThirdParty/ogg/lib/ios,
../../../../ThirdParty/jpeg/lib/ios,
"../../../../ThirdParty/jpeg-turbo/lib/ios",
../../../../ThirdParty/freetype/lib/ios,
../../../../ThirdParty/curl/lib/ios,
../../../../ThirdParty/bullet/lib/ios,
@@ -731,6 +731,7 @@
"-lBulletDynamics",
"-lBulletCollision",
"-lLinearMath",
"-lturbojpeg",
"-lBulletSoftBody",
);
PRODUCT_BUNDLE_IDENTIFIER = com.layabox.conch6;
@@ -754,7 +755,7 @@
GCC_GENERATE_DEBUGGING_SYMBOLS = NO;
GCC_PREPROCESSOR_DEFINITIONS = BT_USE_DOUBLE_PRECISION;
INFOPLIST_FILE = LayaBox/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 7.0;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
LIBRARY_SEARCH_PATHS = (
../../../../ThirdParty/zlib/lib/ios,
@@ -765,7 +766,7 @@
../../../../ThirdParty/websockets/lib/ios,
../../../../ThirdParty/openssl/lib/ios,
../../../../ThirdParty/ogg/lib/ios,
../../../../ThirdParty/jpeg/lib/ios,
"../../../../ThirdParty/jpeg-turbo/lib/ios",
../../../../ThirdParty/freetype/lib/ios,
../../../../ThirdParty/curl/lib/ios,
../../../../ThirdParty/bullet/lib/ios,
@@ -791,6 +792,7 @@
"-lBulletDynamics",
"-lBulletCollision",
"-lLinearMath",
"-lturbojpeg",
"-lBulletSoftBody",
);
PRODUCT_BUNDLE_IDENTIFIER = com.layabox.conch6;
@@ -2821,7 +2821,7 @@ class GLCommandEncoder {
if (supports("GL_OES_depth_texture") || supports("GL_ARB_depth_texture") || supports("GL_ANGLE_depth_texture"))
result.push("WEBGL_depth_texture");
if (version.indexOf("OpenGL ES 3.") != -1) {
if (conchConfig.getOS() == "Conch-android") {
if (conchConfig.getOS() == "Conch-android" || conchConfig.getOS() == "Conch-ohos") {
result.push("WEBGL_compressed_texture_etc");
}
}
@@ -2949,7 +2949,7 @@ class GLCommandEncoder {
else if (name.indexOf('WEBGL_depth_texture') != -1 && ((supports("GL_OES_depth_texture") || supports("GL_ARB_depth_texture") || supports("GL_ANGLE_depth_texture")))) {
return { UNSIGNED_INT_24_8_WEBGL: 34042 };
}
else if (name.indexOf('WEBGL_compressed_texture_astc') != -1 && (extention.indexOf('GL_OES_texture_compression_astc') != -1 || extention.indexOf('GL_KHR_texture_compression_astc') != -1 || (conchConfig.getOS() == "Conch-android" && version.indexOf("OpenGL ES 3.") != -1 && version.indexOf("OpenGL ES 3.0") == -1))) {
else if (name.indexOf('WEBGL_compressed_texture_astc') != -1 && (extention.indexOf('GL_OES_texture_compression_astc') != -1 || extention.indexOf('GL_KHR_texture_compression_astc') != -1 || ((conchConfig.getOS() == "Conch-android" || conchConfig.getOS() == "Conch-ohos") && version.indexOf("OpenGL ES 3.") != -1 && version.indexOf("OpenGL ES 3.0") == -1))) {
return {
COMPRESSED_RGBA_ASTC_4x4_KHR: 0x93B0,
COMPRESSED_RGBA_ASTC_5x4_KHR: 0x93B1,
@@ -2981,7 +2981,7 @@ class GLCommandEncoder {
COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: 0x93DD,
};
}
else if (name.indexOf('WEBGL_compressed_texture_etc') != -1 && conchConfig.getOS() == "Conch-android" && version.indexOf("OpenGL ES 3.") != -1) {
else if (name.indexOf('WEBGL_compressed_texture_etc') != -1 && (conchConfig.getOS() == "Conch-android" || conchConfig.getOS() == "Conch-ohos") && version.indexOf("OpenGL ES 3.") != -1) {
return {
COMPRESSED_R11_EAC: 0x9270,
COMPRESSED_SIGNED_R11_EAC: 0x9271,
@@ -59,7 +59,7 @@ function initFreeType() {
if (sOS == "Conch-window") {
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile("C:/Windows/Fonts/simhei.ttf");
}
else if (sOS == "Conch-android") {
else if (sOS == "Conch-android" || sOS == "Conch-ohos") {
var fSystemVersion = navigator.sv;
if (fSystemVersion >= 2.0 && fSystemVersion < 5.0) {
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile("/system/fonts/DFHEIA5A.ttf");
+135
View File
@@ -0,0 +1,135 @@
cmake_minimum_required(VERSION 3.6)
set(CMAKE_CXX_STANDARD 14)
project(layaair)
set(LAYA_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}/../../../..)
set(OHOS true)
add_definitions(-DOHOS)
add_definitions(-DJS_V8)
add_definitions(-fexceptions)
add_definitions(-DIN_LIBRARY)
add_definitions(-D_GLIBCXX_PERMIT_BACKWARD_HASH)
add_definitions(-DOHOS_ARM_NEON=TRUE)
add_definitions(-DOHOS_STL=c++_shared)
add_definitions(-DOHOS_TOOLCHAIN=clang)
add_definitions(-fno-rtti)
add_definitions(-DBT_USE_DOUBLE_PRECISION)
add_definitions(-DAL_ALEXT_PROTOTYPES)
add_subdirectory(../../common/proj.ohos common)
add_subdirectory(../../render/proj.ohos render)
set(${PROJECT_NAME}_src
../../../source/conch/JSWrapper/v8debug/debug-agent.cpp
../../../source/conch/JSWrapper/v8debug/V8WSSv.cpp
../../../source/conch/JSWrapper/JSInterface/JSInterface.cpp
../../../source/conch/JSWrapper/JSInterface/V8/JSEnv.cpp
../../../source/conch/JSWrapper/JSInterface/V8/JsBinder.cpp
../../../source/conch/JSWrapper/JSInterface/V8/JSArrayBuffer.cpp
../../../source/conch/JSWrapper/JSInterface/V8/IsolateData.cpp
../../../source/conch/JSWrapper/JSInterface/JSObjBase.cpp
../../../source/conch/JSWrapper/LayaWrap/JSArrayBufferRef.cpp
../../../source/conch/JSWrapper/LayaWrap/JSOhosEditBox.cpp
../../../source/conch/JSWrapper/LayaWrap/JSAppCache.cpp
../../../source/conch/JSWrapper/LayaWrap/JSAudio.cpp
../../../source/conch/JSWrapper/LayaWrap/JSConchConfig.cpp
../../../source/conch/JSWrapper/LayaWrap/JSConsole.cpp
../../../source/conch/JSWrapper/LayaWrap/JSDOMParser.cpp
../../../source/conch/JSWrapper/LayaWrap/JSFile.cpp
../../../source/conch/JSWrapper/LayaWrap/JSFileReader.cpp
../../../source/conch/JSWrapper/LayaWrap/JSFileSystem.cpp
../../../source/conch/JSWrapper/LayaWrap/JSGlobalExportCFun.cpp
../../../source/conch/JSWrapper/LayaWrap/JSHistory.cpp
../../../source/conch/JSWrapper/LayaWrap/JSImage.cpp
../../../source/conch/JSWrapper/LayaWrap/JSInput.cpp
../../../source/conch/JSWrapper/LayaWrap/JSLayaGL.cpp
../../../source/conch/JSWrapper/LayaWrap/JSNotify.cpp
../../../source/conch/JSWrapper/LayaWrap/JSRuntime.cpp
../../../source/conch/JSWrapper/LayaWrap/JSTextMemoryCanvas.cpp
../../../source/conch/JSWrapper/LayaWrap/JSWebSocket.cpp
../../../source/conch/JSWrapper/LayaWrap/JSXmlAttr.cpp
../../../source/conch/JSWrapper/LayaWrap/JSXmlNode.cpp
../../../source/conch/JSWrapper/LayaWrap/JSZip.cpp
../../../source/conch/JSWrapper/LayaWrap/JSShaderActiveInfo.cpp
../../../source/conch/JSWrapper/LayaWrap/JSTextBitmapInfo.cpp
../../../source/conch/JSWrapper/LayaWrap/XMLHttpRequest.cpp
../../../source/conch/JSWrapper/LayaWrap/JSShaderPrecisionFormat.cpp
../../../source/conch/JSWrapper/LayaWrap/JSCallbackFuncObj.cpp
../../../source/conch/JSWrapper/LayaWrap/JSWebGLPlus.cpp
../../../source/conch/JSWrapper/LayaWrap/JSPromiseRejectionEvent.cpp
../../../source/conch/Audio/ohos/JCAudioMp3Player.cpp
../../../source/conch/Audio/JCAudioManager.cpp
../../../source/conch/WebSocket/WebSocket.cpp
../../../source/conch/WebSocket/Uri.cpp
../../../source/conch/JCConch.cpp
../../../source/conch/JCConchRender.cpp
../../../source/conch/JCThreadCmdMgr.cpp
../../../source/conch/JCScriptRuntime.cpp
../../../source/conch/JCSystemConfig.cpp
../../../source/conch/JSWrapper/LayaWrap/Bullet/LayaBulletExport.cpp
../../../source/conch/JSWrapper/LayaWrap/Bullet/LayaBulletExportImp.cpp
../../../source/conch/JSWrapper/LayaWrap/Video/JSVideo_CommonImpl.cpp
../../../source/conch/JSWrapper/LayaWrap/Video/JSVideo_OHOSImpl.cpp
../../../source/conch/JSWrapper/LayaWrap/Video/VideoCache.cpp
../../../source/conch/Bridge/JCConchBridge.cpp
../../../source/napi/helper/NapiHelper.cpp
../../../source/napi/plugin_manager.cpp
../../../source/napi/WorkerMessageQueue.cpp
../../../source/napi/render/plugin_render.cpp
../../../source/napi/render/egl_core.cpp
../../../source/napi/modules/TouchesNapi.cpp
../../../source/napi/modules/VideoPlayerNapi.cpp
)
add_library(${PROJECT_NAME} SHARED ${${PROJECT_NAME}_src})
include_directories(${LAYA_ROOT_PATH}/Conch/source)
include_directories(${LAYA_ROOT_PATH}/Conch/source/common)
include_directories(${LAYA_ROOT_PATH}/Conch/source/napi)
include_directories(${LAYA_ROOT_PATH}/Conch/source/resource)
add_subdirectory(${LAYA_ROOT_PATH}/ThirdParty thirdParty)
#target_link_libraries(${PROJECT_NAME} thirdParty)
find_library(EGL-lib EGL)
find_library(GLESv3-lib GLESv3)
find_library(hilog-lib hilog_ndk.z)
find_library(libace-lib ace_ndk.z)
find_library(libnapi-lib ace_napi.z)
find_library(libuv-lib uv)
find_library(rawfile-lib rawfile.z)
find_library(Drawing-lib native_drawing)
set(OHOS_ARM64_MACROS
V8_31BIT_SMIS_ON_64BIT_ARCH
V8_DEPRECATION_WARNINGS
V8_IMMINENT_DEPRECATION_WARNINGS
V8_TARGET_ARCH_ARM64
V8_HAVE_TARGET_OS
V8_TARGET_OS_LINUX
V8_COMPRESS_POINTERS
)
set_property(TARGET v8_monolith
APPEND PROPERTY INTERFACE_COMPILE_DEFINITIONS ${OHOS_ARM64_MACROS}
)
target_link_libraries(${PROJECT_NAME} ${EGL-lib} ${GLESv3-lib} ${hilog-lib} ${libuv-lib} ${Drawing-lib} ${libace-lib} ${libnapi-lib} ${rawfile-lib}
libohaudio.so libavplayer.so common render v8_monolith thirdParty)
set(LOCAL_IS64 arm64)
set(LOCAL_DISABLE_FATAL_LINKER_WARNINGS true)
target_include_directories(${PROJECT_NAME} PUBLIC
../../../include/common
../../../include/render
../../../include/webglPlus
../../../include/msgpack/include
)
target_compile_options(${PROJECT_NAME} PRIVATE -O3)
target_compile_options(${PROJECT_NAME} PRIVATE -DV8_COMPRESS_POINTERS)
set(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} -DV8_COMPRESS_POINTERS")
@@ -811,6 +811,7 @@
A2EE05631C8A77B700A35FB6 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_CXX_LANGUAGE_STANDARD = "c++17";
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
@@ -842,6 +843,7 @@
A2EE05641C8A77B700A35FB6 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_CXX_LANGUAGE_STANDARD = "c++17";
GCC_GENERATE_DEBUGGING_SYMBOLS = NO;
GCC_PREPROCESSOR_DEFINITIONS = (
JS_JSC,
@@ -130,13 +130,9 @@
+(void) postCmdToMainThread:(id)param;
+(void) postCmdToEditBox:(id)param;
+(char*)fontDataForCGFont:(CGFontRef)cgFont size:(long&)p_nSize;
+(void) showExternalWebview:(id)param;
+(void) setScreenWakeLock:(id)param;
+(NSString*) callMethod:(id)param;
+(void) runtimeJSCallWebviewJS:(id)param;
+(void) captureScreen:(id)param;
+(void) setWebViewRect:(id)param;
+(void) setWebViewPercent:(id)param;
//-----------------------------------------------------------------
void reflectionCallback(const std::string& jsonret);
@@ -25,7 +25,6 @@
#import "LayaEditBox.h"
#import "TouchFilter.h"
#import "Audio/JCMp3Player.h"
#import "LayaWebView.h"
#import "LayaAlert.h"
#import "LayaDeviceSensor.h"
#import "LayaScreenShotter.h"
@@ -284,35 +283,6 @@ static uint32_t CalcTableDataRefCheckSum(CFDataRef dataRef)
postCmdToEditBoxParam* _param = (postCmdToEditBoxParam*)param;
ObjectCOperateEditBox(_param->cmd, _param->nParam1,_param->nParam2,_param->bParam2,_param->sParam3);
}
+(void) showExternalWebview:(id)param
{
postCmdString4IntParam* _param = (postCmdString4IntParam*)param;
NSLog(@">>>>showExternalWebview url=%s",_param->sBuffer.c_str());
NSString* nsString = [NSString stringWithUTF8String:_param->sBuffer.c_str()];
conchRuntime* pConchRuntime = [conchRuntime GetIOSConchRuntime];
int x = _param->iParam0;
int y = _param->iParam1;
int w = _param->iParam2;
int h = _param->iParam3;
bool bShowCloseButton = _param->bParam4;
[pConchRuntime->m_pWebView showWebView:nsString posx:x posy:y width:w height:h showCloseButton:bShowCloseButton];
}
+(void) closeWebview
{
[[conchRuntime GetIOSConchRuntime]->m_pWebView closeWebView];
}
+(void) showWebview:(id)param
{
postCmdParam* _param = (postCmdParam*)param;
if( _param->bParam == true )
{
[[conchRuntime GetIOSConchRuntime]->m_pWebView->m_pWebView setHidden:NO];
}
else
{
[[conchRuntime GetIOSConchRuntime]->m_pWebView->m_pWebView setHidden:YES];
}
}
+(void) setScreenWakeLock:(id)param
{
postCmdParam* _param = (postCmdParam*)param;
@@ -341,26 +311,6 @@ static uint32_t CalcTableDataRefCheckSum(CFDataRef dataRef)
assert(pReflection != nil && "pReflection should not be nil");
return [pReflection callMethod:_param->iObjID className:className methodName:methodName param:sParam];
}
+(void) runtimeJSCallWebviewJS:(id)param
{
postCmd3StringParam* _param = (postCmd3StringParam*)param;
LOGE("****runtimeJSCallWebviewJS [%s] [%s] [%s]",_param->sParam0.c_str(),_param->sParam1.c_str(),_param->sParam2.c_str());
if ([conchRuntime GetIOSConchRuntime]->m_pWebView != nil && ![conchRuntime GetIOSConchRuntime]->m_pWebView->m_pWebView.isHidden){
[[conchRuntime GetIOSConchRuntime]->m_pWebView callWebviewJS:[NSString stringWithUTF8String:_param->sParam0.c_str()]
para:[NSString stringWithUTF8String:_param->sParam1.c_str()]
callback:[NSString stringWithUTF8String:_param->sParam2.c_str()]];
}
else{
NSMutableString *js = [[NSMutableString alloc] init];
[js appendFormat:@"%@(\"%@\");",
[NSString stringWithUTF8String:_param->sParam0.c_str()],
[NSString stringWithUTF8String:_param->sParam1.c_str()]];
[[NSNotificationCenter defaultCenter] postNotificationName:@"conchCallLayaBroswerJS"
object:js];
}
}
+(void) setSensorAble:(id)param
{
postCmdParam* _param = (postCmdParam*)param;
@@ -812,26 +762,6 @@ std::string CToObjectCGetDeviceInfo()
}
return "{ \"guid\" : \"unknow\", \"os\" : \"ios\", \"resolution\" : \"unkown\", \"phonename\" : \"unknow\", \"osversion\" : \"unknow\", \"phonemodel\" : \"unknow\", \"retinavalue\" : \"1.000000\", \"imei\" : \"imeixxx\", \"imsi\" : \"imsixxx\", \"localmodel\" : \"unknow\"}";
}
void CToObjectCShowWebView()
{
postCmdParam* pParam = [[postCmdParam alloc] init:true i:0 f:0 s:nullptr];
[CToObjectCIOS performSelectorOnMainThread:@selector(showWebview:) withObject:pParam waitUntilDone:NO];
}
void CToObjectCHideWebView()
{
postCmdParam* pParam = [[postCmdParam alloc] init:false i:0 f:0 s:nullptr];
[CToObjectCIOS performSelectorOnMainThread:@selector(showWebview:) withObject:pParam waitUntilDone:NO];
}
void CToObjectCSetExternalLink( const char* p_sUrl,int x,int y,int w,int h,bool bShowCloseButton )
{
postCmdString4IntParam* pParam = [[postCmdString4IntParam alloc] init:p_sUrl _p0:x _p1:y _p2:w _p3:h _p4:bShowCloseButton];
[CToObjectCIOS performSelectorOnMainThread:@selector(showExternalWebview:) withObject:pParam waitUntilDone:NO];
}
void CToObjectCCloseExternalLink()
{
[CToObjectCIOS performSelectorOnMainThread:@selector(closeWebview) withObject:nil waitUntilDone:NO];
}
void CToObjectCSetScreenWakeLock( bool p_bWakeLock )
{
postCmdParam* pParam = [[postCmdParam alloc] init:p_bWakeLock i:0 f:0 s:""];
@@ -930,12 +860,6 @@ void reflectionCallback(const std::string& jsonret)
NSLog(@"%@", [[NSString alloc] initWithUTF8String:jsonret.c_str()]);
}
void CToObjectCCallWebviewJS(const char* functionName, const char* jsonParam, const char* callback)
{
postCmd3StringParam* pParam = [[postCmd3StringParam alloc] init:functionName _p1:jsonParam _p2:callback];
[CToObjectCIOS performSelectorOnMainThread:@selector(runtimeJSCallWebviewJS:) withObject:pParam waitUntilDone:NO];
}
void CToObjectCSetSensorAble(bool p_bAble)
{
postCmdParam* pParam = [[postCmdParam alloc] init:p_bAble i:0 f:0 s:""];
@@ -16,7 +16,6 @@ typedef char* (*HandleFileData)(const char* data, int& len);
class JCTouchFilter;
@class LayaReachability;
@class JCMp3Player;
@class LayaWebView;
@class LayaEditBox;
@class LayaEditBoxDelegate;
@class LayaAlert;
@@ -60,11 +59,6 @@ class JCTouchFilter;
JCMp3Player* m_pMp3Player; //MP3播放器
//界面相关的
//-----------------------------------------------------------------
LayaWebView* m_pWebView; //webView
LayaReachability* m_pNetworkListener; //网络监听
//-----------------------------------------------------------------
@@ -13,7 +13,6 @@
#import "LayaEditBox.h"
#import "TouchFilter.h"
#import "Audio/JCMp3Player.h"
#import "LayaWebView.h"
#import "Reachability/Reachability.h"
#import "LayaAlert.h"
#import "CToObjectCIOS.h"
@@ -78,7 +77,6 @@ laya::JCConch* m_pConchEngine = NULL;
m_pEditBox = NULL;
m_pEditBoxDelegate = NULL;
m_pMp3Player = NULL;
m_pWebView = NULL;
m_pNetworkListener = NULL;
m_fRetinaValue = 1;
m_nsRootResourcePath = nil;
@@ -158,8 +156,6 @@ laya::JCConch* m_pConchEngine = NULL;
m_pEditBox = [[LayaEditBox alloc]initWithParentView:m_pGLKView EditBoxDelegate:m_pEditBoxDelegate ScreenRatio:m_fRetinaValue ];
m_pMp3Player = [[JCMp3Player alloc] init];
[self initExternalWebview];
// 注册监听键盘弹出的事件
[[NSNotificationCenter defaultCenter] addObserver:m_pEditBoxDelegate
selector:@selector(keyboardWasShown:)
@@ -265,11 +261,6 @@ void AudioEngineInterruptionListenerCallback(void* user_data, UInt32 interruptio
laya::JCScriptRuntime::s_JSRT->onVSyncEvent(vsyncTmMs);
}
}
-(void) initExternalWebview
{
m_pWebView = [[LayaWebView alloc] init];
[m_pGLKView addSubview:m_pWebView->m_pWebView];
}
-(void) initNetworkListener
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:LayakReachabilityChangedNotification object:nil];
@@ -16,7 +16,7 @@ LOCAL_CFLAGS := \
-DBT_USE_DOUBLE_PRECISION \
-frtti
LOCAL_CPPFLAGS += -std=c++11
LOCAL_CPPFLAGS += -std=c++17
ifeq ($(APP_PERFTEST),1)
LOCAL_CFLAGS += -DPERFTEST
@@ -44,7 +44,7 @@ LOCAL_SRC_FILES := \
LOCAL_C_INCLUDES := ../../../../../ThirdParty/curl/include/android \
../../../../../ThirdParty/png/include/android \
../../../../../ThirdParty/jpeg/include/android \
../../../../../ThirdParty/jpeg-turbo/include/android \
../../../../../ThirdParty/freetype/include/android \
../../../../../ThirdParty/zip/include/android \
../../../../include/common \
@@ -6,4 +6,4 @@ APP_PLATFORM := android-21
NDK_TOOLCHAIN_VERSION := 4.9
#APP_STL := gnustl_static
APP_OPTIM := release
APP_ABI :=armeabi-v7a arm64-v8a x86
APP_ABI :=armeabi-v7a arm64-v8a x86 x86_64
@@ -350,6 +350,7 @@
A2D1183A1D0BB25E004C229D /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_CXX_LANGUAGE_STANDARD = "c++17";
OTHER_CFLAGS = (
"-I../../../include/common",
"-I../../../../ThirdParty/freetype/include/ios",
@@ -370,6 +371,7 @@
A2D1183B1D0BB25E004C229D /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_CXX_LANGUAGE_STANDARD = "c++17";
GCC_GENERATE_DEBUGGING_SYMBOLS = NO;
OTHER_CFLAGS = (
"-I../../../include/common",
@@ -0,0 +1,31 @@
cmake_minimum_required(VERSION 3.6)
project(render)
set(render_src
../../../source/render/RenderEx/JCGpuProgram.cpp
../../../source/render/RenderEx/JCGlobalValue.cpp
../../../source/render/RenderEx/JCRegister.cpp
../../../source/render/Image/JCImage.cpp
../../../source/render/Image/JCVideo.cpp
../../../source/render/Image/JCImageManager.cpp
../../../source/render/Performance/JCPerfHUD.cpp
../../../source/render/Performance/JCVBOManager.cpp
../../../source/render/LayaGL/JCIDGenerator.cpp
../../../source/render/LayaGL/JCLayaGL.cpp
../../../source/render/LayaGL/JCLayaGLDispatch.cpp
)
add_library(render STATIC ${render_src})
target_include_directories(render PUBLIC
../../../../ThirdParty/curl/include/ohos
../../../../ThirdParty/png/include/ohos
../../../../ThirdParty/jpeg-turbo/include/ohos
../../../../ThirdParty/freetype/include/ohos
../../../../ThirdParty/zip/include/ohos
../../../include/common
../../../include/webglPlus
../../../include/conch
)
set(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} -std=c++11")
target_compile_options(${PROJECT_NAME} PRIVATE -DV8_COMPRESS_POINTERS)
set(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} -DV8_COMPRESS_POINTERS")
@@ -0,0 +1,123 @@
#ifndef __JCOHOSFileSource_H__
#define __JCOHOSFileSource_H__
#include "JCFileSource.h"
#include <rawfile/raw_file_manager.h>
#include "../../napi/common/native_common.h"
#include "../util/Log.h"
#include "../util/JCZipFile.h"
namespace laya{
class JCOHOSFileSource : public JCFileSource{
private:
NativeResourceManager* nativeResourceManager_;
char *m_pszRoot;
public:
JCOHOSFileSource(){
m_pszRoot=0;
LOGI("JCOHOSFileSource::constructor ");
}
~JCOHOSFileSource(){
if(0!=m_pszRoot){
delete[] m_pszRoot;
m_pszRoot = 0;
}
}
bool Init(NativeResourceManager* nativeResourceManager, const char *p_pszRoot){
if(0!=m_pszRoot){
delete[] m_pszRoot;
m_pszRoot = 0;
}
int len;
if(0!=p_pszRoot&&0!=(len = strlen(p_pszRoot))){
m_pszRoot = new char[len+1];
memcpy(m_pszRoot,p_pszRoot,len+1);
if('\\'==m_pszRoot[len-1]|| '/'==m_pszRoot[len-1]){
m_pszRoot[len-1]=0;
}
}
nativeResourceManager_ = nativeResourceManager;
return ((0!=nativeResourceManager_)&&(0!=m_pszRoot));
}
public:
virtual bool isFileExistInZipAPKExpansion(const char *sFileName){return false;}
virtual bool isFileExist(const char *p_pszFile){
char szName[512];
char *pathfile = (char *)p_pszFile;
if(m_pszRoot){
sprintf(szName,"%s/%s",m_pszRoot,p_pszFile);
pathfile = szName;
}
RawFile *fp = OH_ResourceManager_OpenRawFile(nativeResourceManager_,pathfile);
if(fp){
LOGI("JCOHOSFileSource::isFileExist() - open %{public}s success", p_pszFile);
OH_ResourceManager_CloseRawFile(fp);
return true;
}
return false;
}
virtual unsigned int getFileSize(const char *p_pszFile)
{
char szName[512];
char *pathfile = (char *)p_pszFile;
if(m_pszRoot){
sprintf(szName, "%s%s", m_pszRoot, p_pszFile);
pathfile = szName;
}
RawFile *fp = OH_ResourceManager_OpenRawFile(nativeResourceManager_, pathfile);
LOGI("JSOHOSFileSource::getFileSize ============================> doGetFileData %{public}s",p_pszFile);
long size = OH_ResourceManager_GetRawFileSize(fp);
OH_ResourceManager_CloseRawFile(fp);
if(size!=-1){
return size;
}
return size;
}
virtual bool loadFileContent(const char *p_pszFile, char *&p_pBuff, int &p_iBuffSize){
p_iBuffSize = 0;
char szName[512];
char *pathfile = (char *)p_pszFile;
if(m_pszRoot){
sprintf(szName,"%s/%s",m_pszRoot,p_pszFile);
pathfile = szName;
}
RawFile *fp = OH_ResourceManager_OpenRawFile(nativeResourceManager_,pathfile);
if(!fp){
LOGI("JCOHOSFileSource::loadFileContent1 fp is nullptr");
return false;
}
p_iBuffSize = OH_ResourceManager_GetRawFileSize(fp);
p_pBuff = new char[p_iBuffSize+1];
int readsize = OH_ResourceManager_ReadRawFile(fp,p_pBuff,p_iBuffSize);
OH_ResourceManager_CloseRawFile(fp);
if(readsize<p_iBuffSize){
return false;
}
p_pBuff[p_iBuffSize]=0;
return true;
}
virtual bool loadFileContent(const char *p_pszFile,ALLOCMEM alloc,void *pUserData, int &p_iBuffSize){
p_iBuffSize = 0;
char szName[512];
char *pathfile = (char *)p_pszFile;
if(m_pszRoot){
sprintf(szName,"%s/%s",m_pszRoot,p_pszFile);
pathfile = szName;
}
RawFile *fp = OH_ResourceManager_OpenRawFile(nativeResourceManager_,pathfile);
if(!fp){
LOGI("JCOHOSFileSource::loadFileContent2 fp is nullptr %s",p_pszFile);
return false;
}
p_iBuffSize = OH_ResourceManager_GetRawFileSize(fp);
unsigned char *pBuff = alloc(p_iBuffSize,pUserData);
int readsize = OH_ResourceManager_ReadRawFile(fp,pBuff,p_iBuffSize);
OH_ResourceManager_CloseRawFile(fp);
if(readsize<p_iBuffSize){
return false;
}
return true;
}
};
}
#endif //__JCOHOSFileSource_H__
+11 -11
View File
@@ -21,7 +21,7 @@
#ifdef WIN32
extern void SetNameInternal(unsigned int thread_id, const char* name);
#elif ANDROID
#elif ANDROID || OHOS
#include <sys/syscall.h>
#include <unistd.h>
#define gettidv1() syscall(__NR_gettid)
@@ -42,9 +42,9 @@ namespace laya
void ___datathread_onthreadstop(const char* threadname);
template<class _Tp>
/**
* @brief 线线
* threadpool的
* TODO
* @brief 线线
* threadpool的
* TODO
*/
class JCDataThread{
public:
@@ -67,7 +67,7 @@ namespace laya
Stop();
}
m_ThreadFunc = p_pfnThreadFunc;
//TODO m_Semaphore 的stop标记现在不是原子的。
//TODO m_Semaphore 的stop标记现在不是原子的。
//std::interprocess::ipcdetail::atomic_write32( &m_bWantToStop, 0 );
m_pThread = new std::thread(std::bind(&JCDataThread::__ThreadEntry,this));
if( 0 == m_pThread )
@@ -120,10 +120,10 @@ namespace laya
}
/**
* join
* true表示成功join了
* timeout
* traStopWorker true表示希望停止尝试
* join
* true表示成功join了
* timeout
* traStopWorker true表示希望停止尝试
*/
typedef bool (*tryStopWorker)(int,void*);
bool tryStop(int timeout, tryStopWorker func, void* userdata) {
@@ -135,7 +135,7 @@ namespace laya
m_Datas.clear();
}
//必须在启动线程前设置。
//必须在启动线程前设置。
void setName(const char* p_pszName){
m_strName = p_pszName;
}
@@ -190,7 +190,7 @@ namespace laya
}
}
//发送到任务最少的线程中
//发送到任务最少的线程中
bool sendToThread(_DataType p_dt) {
if (m_nThreadNum <= 0)
return false;
@@ -0,0 +1,80 @@
#ifndef __JCAudioWavPlayer_OHOS_H__
#define __JCAudioWavPlayer_OHOS_H__
#include <stdio.h>
#include <thread>
#include "../../util/JCCommonMethod.h"
#include "JCWaveInfo.h"
#include "JCAudioInterface.h"
#include <unordered_map>
#include <vector>
#include <ohaudio/native_audiostreambuilder.h>
#include <ohaudio/native_audiorenderer.h>
namespace laya{
class JCFileResManager;
class OHAudioRenderInfo
{
public:
OH_AudioRenderer* _audioRender;
OH_AudioStreamBuilder* _builder;
JCAudioInterface* m_pAudio; //Audio 为了回调使用
bool m_bPlaying; //是否为播放状态
const char* pcmBuffer;
int32_t m_pBufferSize;
int32_t writeOffset = 0;
std::function<int32_t(OH_AudioRenderer* renderer, void* userData, void* buffer, int32_t bufferLen)> writeDataCallback;
public:
void operator=(const OHAudioRenderInfo &other){
m_bPlaying = other.m_bPlaying;
_audioRender = other._audioRender;
m_pAudio = other.m_pAudio;
}
};
class JCAudioWavPlayer{
public:
typedef std::unordered_map<std::string, JCWaveInfo*> MapWaveInfo;
typedef MapWaveInfo::iterator MapWaveInfoIter;
public:
JCAudioWavPlayer(JCFileResManager* pFileResManager);
~JCAudioWavPlayer();
void Release();
public:
OHAudioRenderInfo* playAudio(JCAudioInterface* p_pAudio, const std::string& p_sSrc, bool bIsOgg);
void delAudio(JCAudioInterface* p_pAudio);
OHAudioRenderInfo* playAudioFromBuffer(JCAudioInterface* p_pAudio, const char* p_pBuffer, unsigned int p_nBufferSize, int p_nRate, int p_nBitsPerSample, int nChannels);
void setVolume(OHAudioRenderInfo* pAudioRenderInfo, float p_nVolume);
void stop(OHAudioRenderInfo* pAudioRenderInfo);
void setAllVolume(float p_nVolume);
void stopAll();
void checkWavePlayEnd();
void pause();
void resume();
static int32_t AudioRendererOnWriteData(OH_AudioRenderer *renderer, void *userData, void *buffer, int32_t bufferLen);
public:
/**
* @brief
* @return
*/
JCWaveInfo *AddWaveInfo(const std::string &p_sUrl, unsigned char *p_pBuffer, int p_nSize, const char *p_sFilePath, void *p_pExternalMark, bool p_bIsOgg);
/**
* @brief ulid
* @param[in] ulid
* @return
*/
JCWaveInfo* FindWaveInfo(const std::string& p_sUrl);
/**
* @brief
*/
bool ClearAllWaveInfo(void);
void autoGarbageCollection();
public:
static int s_nGarbageCollectionTime;
MapWaveInfo m_vWaveInfos; //wave的信息
public:
JCFileResManager* m_pFileResManager;
OH_AudioRenderer *audioRenderer;
std::vector<OHAudioRenderInfo*> m_pAudioRenderSource; //播放声音用的
};
}
#endif //__JCAudioWavPlayer_H__
+8
View File
@@ -0,0 +1,8 @@
#ifndef __ColorParser_H__
#define __ColorParser_H__
#include <string>
namespace laya
{
bool parseRGBAFromString(const char *str, uint32_t &r, uint32_t &g, uint32_t &b, uint32_t &a);
} // namespace laya
#endif
+16
View File
@@ -14,6 +14,15 @@
#ifdef WIN32
#pragma execution_character_set("utf-8")
#endif
#ifdef OHOS
enum OHOSLogLevel {
Warn,
Error,
Debug,
Info,
Runtime,
};
#else
//通用的日志函数。
enum LogLevel {
Warn,
@@ -22,6 +31,7 @@ enum LogLevel {
Info,
Runtime,
};
#endif
extern void(*gLayaLog)(int level, const char* file, int line, const char* fmt,...);
//如果知道没有参数就不用做%的转换了。
extern void(*gLayaLogNoParam)(int level, const char* file, int line, const char* msg);
@@ -55,6 +65,12 @@ void alert(const char* fmt, ...);
#define LOGI(...) {if(g_nDebugLevel >= 3){if(gLayaLog){gLayaLog(Info,__FILE__,__LINE__,__VA_ARGS__);}else{__android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__);}}}
#define LOGW(...) {if(g_nDebugLevel >= 2){if(gLayaLog){gLayaLog(Warn,__FILE__,__LINE__,__VA_ARGS__);}else{__android_log_print(ANDROID_LOG_WARN,LOG_TAG,__VA_ARGS__);}}if(g_nDebugLevel >= 5){alert(__VA_ARGS__);}}
#define LOGE(...) {if(g_nDebugLevel >= 1){if(gLayaLog){gLayaLog(Error,__FILE__,__LINE__,__VA_ARGS__);}else{__android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__);}}if(g_nDebugLevel >= 4){alert(__VA_ARGS__);}}
#elif OHOS
#include <hilog/log.h>
#define LOG_TAG "LayaBox"
#define LOGI(...) {if(g_nDebugLevel >= 3){if(gLayaLog){gLayaLog(Info,__FILE__,__LINE__,__VA_ARGS__);}else{OH_LOG_Print(LOG_APP,LOG_INFO,LOG_DOMAIN,LOG_TAG,__VA_ARGS__);}}}
#define LOGW(...) {if(g_nDebugLevel >= 2){if(gLayaLog){gLayaLog(Warn,__FILE__,__LINE__,__VA_ARGS__);}else{OH_LOG_Print(LOG_APP,LOG_WARN,LOG_DOMAIN,LOG_TAG,__VA_ARGS__);}}if(g_nDebugLevel >= 5){alert(__VA_ARGS__);}}
#define LOGE(...) {if(g_nDebugLevel >= 1){if(gLayaLog){gLayaLog(Error,__FILE__,__LINE__,__VA_ARGS__);}else{OH_LOG_Print(LOG_APP,LOG_ERROR,LOG_DOMAIN,LOG_TAG,__VA_ARGS__);}}if(g_nDebugLevel >= 4){alert(__VA_ARGS__);}}
#elif WIN32
#define LOGI(...) { if(g_nDebugLevel >= 3){if(gLayaLog){gLayaLog(Info,__FILE__,__LINE__,__VA_ARGS__);}else{ printf(__VA_ARGS__);printf("\n");}}}
#define LOGW(...) { if(g_nDebugLevel >= 2){if(gLayaLog){gLayaLog(Warn,__FILE__,__LINE__,__VA_ARGS__);}else{ printf(__VA_ARGS__);printf("\n");}}if(g_nDebugLevel >= 5){alert(__VA_ARGS__);}}
@@ -0,0 +1,100 @@
/*
File: Reachability.h
Abstract: Basic demonstration of how to use the SystemConfiguration Reachablity APIs.
Version: 3.5
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
Inc. ("Apple") in consideration of your agreement to the following
terms, and your use, installation, modification or redistribution of
this Apple software constitutes acceptance of these terms. If you do
not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may
be used to endorse or promote products derived from the Apple Software
without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or
implied, are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or by other
works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2014 Apple Inc. All Rights Reserved.
*/
#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <netinet/in.h>
typedef enum : NSInteger {
NotReachable = 0,
ReachableViaWiFi,
ReachableViaWWAN
} LayaNetworkStatus;
extern NSString *LayakReachabilityChangedNotification;
@interface LayaReachability : NSObject
/*!
* Use to check the reachability of a given host name.
*/
+ (instancetype)reachabilityWithHostName:(NSString *)hostName;
/*!
* Use to check the reachability of a given IP address.
*/
+ (instancetype)reachabilityWithAddress:(const struct sockaddr_in *)hostAddress;
/*!
* Checks whether the default route is available. Should be used by applications that do not connect to a particular host.
*/
+ (instancetype)reachabilityForInternetConnection;
/*!
* Checks whether a local WiFi connection is available.
*/
+ (instancetype)reachabilityForLocalWiFi;
/*!
* Start listening for reachability notifications on the current run loop.
*/
- (BOOL)startNotifier;
- (void)stopNotifier;
- (LayaNetworkStatus)currentReachabilityStatus;
/*!
* WWAN may be available, but not active until a connection has been established. WiFi may require a connection for VPN on Demand.
*/
- (BOOL)connectionRequired;
@end
@@ -16,7 +16,6 @@ typedef char* (*HandleFileData)(const char* data, int& len);
class JCTouchFilter;
@class LayaReachability;
@class JCMp3Player;
@class LayaWebView;
@class LayaEditBox;
@class LayaEditBoxDelegate;
@class LayaAlert;
@@ -60,11 +59,6 @@ class JCTouchFilter;
JCMp3Player* m_pMp3Player; //MP3播放器
//界面相关的
//-----------------------------------------------------------------
LayaWebView* m_pWebView; //webView
LayaReachability* m_pNetworkListener; //网络监听
//-----------------------------------------------------------------
@@ -0,0 +1,123 @@
#ifndef __JCOHOSFileSource_H__
#define __JCOHOSFileSource_H__
#include "JCFileSource.h"
#include <rawfile/raw_file_manager.h>
#include "../../napi/common/native_common.h"
#include "../util/Log.h"
#include "../util/JCZipFile.h"
namespace laya{
class JCOHOSFileSource : public JCFileSource{
private:
NativeResourceManager* nativeResourceManager_;
char *m_pszRoot;
public:
JCOHOSFileSource(){
m_pszRoot=0;
LOGI("JCOHOSFileSource::constructor ");
}
~JCOHOSFileSource(){
if(0!=m_pszRoot){
delete[] m_pszRoot;
m_pszRoot = 0;
}
}
bool Init(NativeResourceManager* nativeResourceManager, const char *p_pszRoot){
if(0!=m_pszRoot){
delete[] m_pszRoot;
m_pszRoot = 0;
}
int len;
if(0!=p_pszRoot&&0!=(len = strlen(p_pszRoot))){
m_pszRoot = new char[len+1];
memcpy(m_pszRoot,p_pszRoot,len+1);
if('\\'==m_pszRoot[len-1]|| '/'==m_pszRoot[len-1]){
m_pszRoot[len-1]=0;
}
}
nativeResourceManager_ = nativeResourceManager;
return ((0!=nativeResourceManager_)&&(0!=m_pszRoot));
}
public:
virtual bool isFileExistInZipAPKExpansion(const char *sFileName){return false;}
virtual bool isFileExist(const char *p_pszFile){
char szName[512];
char *pathfile = (char *)p_pszFile;
if(m_pszRoot){
sprintf(szName,"%s/%s",m_pszRoot,p_pszFile);
pathfile = szName;
}
RawFile *fp = OH_ResourceManager_OpenRawFile(nativeResourceManager_,pathfile);
if(fp){
LOGI("JCOHOSFileSource::isFileExist() - open %{public}s success", p_pszFile);
OH_ResourceManager_CloseRawFile(fp);
return true;
}
return false;
}
virtual unsigned int getFileSize(const char *p_pszFile)
{
char szName[512];
char *pathfile = (char *)p_pszFile;
if(m_pszRoot){
sprintf(szName, "%s%s", m_pszRoot, p_pszFile);
pathfile = szName;
}
RawFile *fp = OH_ResourceManager_OpenRawFile(nativeResourceManager_, pathfile);
LOGI("JSOHOSFileSource::getFileSize ============================> doGetFileData %{public}s",p_pszFile);
long size = OH_ResourceManager_GetRawFileSize(fp);
OH_ResourceManager_CloseRawFile(fp);
if(size!=-1){
return size;
}
return size;
}
virtual bool loadFileContent(const char *p_pszFile, char *&p_pBuff, int &p_iBuffSize){
p_iBuffSize = 0;
char szName[512];
char *pathfile = (char *)p_pszFile;
if(m_pszRoot){
sprintf(szName,"%s/%s",m_pszRoot,p_pszFile);
pathfile = szName;
}
RawFile *fp = OH_ResourceManager_OpenRawFile(nativeResourceManager_,pathfile);
if(!fp){
LOGI("JCOHOSFileSource::loadFileContent1 fp is nullptr");
return false;
}
p_iBuffSize = OH_ResourceManager_GetRawFileSize(fp);
p_pBuff = new char[p_iBuffSize+1];
int readsize = OH_ResourceManager_ReadRawFile(fp,p_pBuff,p_iBuffSize);
OH_ResourceManager_CloseRawFile(fp);
if(readsize<p_iBuffSize){
return false;
}
p_pBuff[p_iBuffSize]=0;
return true;
}
virtual bool loadFileContent(const char *p_pszFile,ALLOCMEM alloc,void *pUserData, int &p_iBuffSize){
p_iBuffSize = 0;
char szName[512];
char *pathfile = (char *)p_pszFile;
if(m_pszRoot){
sprintf(szName,"%s/%s",m_pszRoot,p_pszFile);
pathfile = szName;
}
RawFile *fp = OH_ResourceManager_OpenRawFile(nativeResourceManager_,pathfile);
if(!fp){
LOGI("JCOHOSFileSource::loadFileContent2 fp is nullptr %s",p_pszFile);
return false;
}
p_iBuffSize = OH_ResourceManager_GetRawFileSize(fp);
unsigned char *pBuff = alloc(p_iBuffSize,pUserData);
int readsize = OH_ResourceManager_ReadRawFile(fp,pBuff,p_iBuffSize);
OH_ResourceManager_CloseRawFile(fp);
if(readsize<p_iBuffSize){
return false;
}
return true;
}
};
}
#endif //__JCOHOSFileSource_H__
@@ -24,8 +24,11 @@
#ifdef ANDROID
#include "../downloadCache/JCAndroidFileSource.h"
#else
#elif __APPLE__
#include "../downloadCache/JCIosFileSource.h"
#elif OHOS
#include "../downloadCache/JCOHOSFileSource.h"
#include "napi/plugin_manager.h"
#endif
#define PATH_SOURCEID "sourceid"
#define ERROR_FILE_C_R_W (-6)
@@ -40,6 +43,9 @@ extern std::string gRedistPath;
std::string gAPKExpansionPatchPath="";
#elif __APPLE__
extern std::string gAssetRootPath;
#elif OHOS
NativeResourceManager* g_pAssetManager = nullptr;
std::string gAssetRootPath="";
#else
std::string gAssetRootPath="d:/temp/myassets";
#endif
@@ -328,8 +334,10 @@ namespace laya
/*
#ifdef ANDROID
m_pAssets = new JCAndroidFileSource();
#else
#elif __APPLE__
m_pAssets = new JCIosFileSource();
#elif OHOS
m_pAssets = new JCOHOSFileSource();
#endif
*/
m_pFileTable=NULL;
@@ -451,10 +459,14 @@ namespace laya
delete pfr;
}
}
#else
#elif __APPLE__
JCIosFileSource* pAssets = new JCIosFileSource();
pAssets->Init(assetsPath.c_str());
pFileReader = pAssets;
#elif OHOS
JCOHOSFileSource* pAssets = new JCOHOSFileSource();
pAssets->Init((NativeResourceManager*)g_pAssetManager, assetsPath.c_str());
pFileReader = pAssets;
#endif
setAssets( pFileReader);
@@ -545,6 +557,8 @@ namespace laya
bool hasAssets = hasAssetsFt || hasAssetsID ;
if(hasAssets && (cachedAssetsID.length()==0 || assetsidLen != cachedAssetsID.length()|| strcmp(assetsid, cachedAssetsID.c_str())!=0) ){
//清理文件缓存
clearAllCachedFile();
//先获取资源中的filteTable
char* pFileTableBuf=NULL;
int nFileTableLen = 0;
+11 -11
View File
@@ -21,7 +21,7 @@
#ifdef WIN32
extern void SetNameInternal(unsigned int thread_id, const char* name);
#elif ANDROID
#elif ANDROID || OHOS
#include <sys/syscall.h>
#include <unistd.h>
#define gettidv1() syscall(__NR_gettid)
@@ -42,9 +42,9 @@ namespace laya
void ___datathread_onthreadstop(const char* threadname);
template<class _Tp>
/**
* @brief 线线
* threadpool的
* TODO
* @brief 线线
* threadpool的
* TODO
*/
class JCDataThread{
public:
@@ -67,7 +67,7 @@ namespace laya
Stop();
}
m_ThreadFunc = p_pfnThreadFunc;
//TODO m_Semaphore 的stop标记现在不是原子的。
//TODO m_Semaphore 的stop标记现在不是原子的。
//std::interprocess::ipcdetail::atomic_write32( &m_bWantToStop, 0 );
m_pThread = new std::thread(std::bind(&JCDataThread::__ThreadEntry,this));
if( 0 == m_pThread )
@@ -120,10 +120,10 @@ namespace laya
}
/**
* join
* true表示成功join了
* timeout
* traStopWorker true表示希望停止尝试
* join
* true表示成功join了
* timeout
* traStopWorker true表示希望停止尝试
*/
typedef bool (*tryStopWorker)(int,void*);
bool tryStop(int timeout, tryStopWorker func, void* userdata) {
@@ -135,7 +135,7 @@ namespace laya
m_Datas.clear();
}
//必须在启动线程前设置。
//必须在启动线程前设置。
void setName(const char* p_pszName){
m_strName = p_pszName;
}
@@ -190,7 +190,7 @@ namespace laya
}
}
//发送到任务最少的线程中
//发送到任务最少的线程中
bool sendToThread(_DataType p_dt) {
if (m_nThreadNum <= 0)
return false;
+7 -2
View File
@@ -51,7 +51,12 @@ void SetNameInternal(unsigned int thread_id, const char* name)
#elif ANDROID
#include <sys/syscall.h>
#define gettidv1() syscall(__NR_gettid)
#define gettidv2() syscall(SYS_gettid)
#define gettidv2() syscall(SYS_gettid)
#elif OHOS
#include <sys/syscall.h>
#include "unistd.h"
#define gettidv1() syscall(__NR_gettid)
#define gettidv2() syscall(SYS_gettid)
#endif
namespace laya{
@@ -152,7 +157,7 @@ namespace laya{
LOGI("start thread:%s,%d", m_strName.c_str(), thid);
//threadInfoLog("start thread:%s,%d", m_strName.c_str(), thid);
}
#elif ANDROID
#elif ANDROID || OHOS
{
LOGI("start thread:%s,%d", m_strName.c_str(), (int)gettidv1());
//threadInfoLog("start thread:%s,%ld", m_strName.c_str(), gettidv1());
@@ -0,0 +1,251 @@
#include "JCAudioWavPlayer-openharmony.h"
#include "../../util/JCCommonMethod.h"
#include "../../util/Log.h"
#include "JCWaveParser.h"
#include "JCOggParser.h"
#include "../JCFileResManager.h"
namespace laya{
int JCAudioWavPlayer::s_nGarbageCollectionTime = 30000;//30秒
JCAudioWavPlayer::JCAudioWavPlayer(JCFileResManager* pFileResManager){
m_pFileResManager = pFileResManager;
m_pAudioRenderSource.reserve(128);
}
JCAudioWavPlayer::~JCAudioWavPlayer(){
Release();
}
void JCAudioWavPlayer::checkWavePlayEnd(){
}
OHAudioRenderInfo* JCAudioWavPlayer::playAudio(JCAudioInterface* p_pAudio, const std::string& p_sSrc, bool bIsOgg){
JCWaveInfo* pInfo = NULL;
MapWaveInfoIter iter = m_vWaveInfos.find(p_sSrc);
if(iter != m_vWaveInfos.end()){
pInfo = iter->second;
}else{
JCFileRes* pRes = m_pFileResManager->getRes(p_sSrc.c_str());
JCBuffer kBuffer;
if(pRes && pRes->loadFromCache(kBuffer,false)){
pInfo = AddWaveInfo(p_sSrc,(unsigned char*)kBuffer.m_pPtr,kBuffer.m_nLen,NULL,p_pAudio,bIsOgg);
}else{
LOGE("JCAudioWavPlayer::playAudio load res error");
}
}
if(pInfo!=NULL){
pInfo -> m_nTouchTime = tmGetCurms();
WAVE_FORMAT* pFormat = &(pInfo->m_kFmtBlock.wavFormat);
return playAudioFromBuffer(p_pAudio,(char*)(pInfo->m_pData),pInfo->m_nRealDataSize,pFormat->dwSamplesPerSec,pFormat->wBitsPerSample,pFormat->wChannels);
}
return NULL;
}
void JCAudioWavPlayer::delAudio(JCAudioInterface* p_pAudio){
int m_ohAudioCount = m_pAudioRenderSource.size();
for(int i = 0; i <m_ohAudioCount; i++){
if(m_pAudioRenderSource[i]->m_pAudio==p_pAudio){
m_pAudioRenderSource[i]->m_pAudio = NULL;
}
}
}
//----------------------------------------------------------------------------------
OHAudioRenderInfo* JCAudioWavPlayer::playAudioFromBuffer(JCAudioInterface* p_pAudio,const char* p_pBuffer, unsigned int p_nBufferSize,
int p_nRate, int nBitsPerSample, int nChannels){
OHAudioRenderInfo* audioRenderInfo = new OHAudioRenderInfo;
OH_AudioStream_Result ret;
OH_AudioStream_Type type = AUDIOSTREAM_TYPE_RENDERER;
OH_AudioStreamBuilder* _builder;
ret = OH_AudioStreamBuilder_Create(&_builder, type);
if(ret != AUDIOSTREAM_SUCCESS){
return nullptr;
}
OH_AudioStreamBuilder_SetSamplingRate(_builder, p_nRate);
OH_AudioStreamBuilder_SetChannelCount(_builder, nChannels);
OH_AudioStream_SampleFormat nFormat;
switch (nBitsPerSample)
{
case 8:
nFormat = AUDIOSTREAM_SAMPLE_U8;
break;
case 16:
nFormat = AUDIOSTREAM_SAMPLE_S16LE;
break;
default:
LOGE("JCAudioWavPlayer::playAudioFromBuffer sound bitsPerSample error, only support 8 or 16");
nFormat = AUDIOSTREAM_SAMPLE_S16LE;
break;
}
OH_AudioStreamBuilder_SetSampleFormat(_builder, nFormat);
//设置低时延模式
OH_AudioStreamBuilder_SetLatencyMode(_builder, AUDIOSTREAM_LATENCY_MODE_FAST);
OH_AudioStreamBuilder_SetRendererInfo(_builder, AUDIOSTREAM_USAGE_GAME);
OH_AudioRenderer_Callbacks callbacks;
callbacks.OH_AudioRenderer_OnWriteData = AudioRendererOnWriteData;
ret = OH_AudioStreamBuilder_SetRendererCallback(_builder, callbacks, (void *)audioRenderInfo);
if(ret!=AUDIOSTREAM_SUCCESS){
return nullptr;
}
ret = OH_AudioStreamBuilder_GenerateRenderer(_builder, &audioRenderer);
if(ret!=AUDIOSTREAM_SUCCESS){
return nullptr;
}
audioRenderInfo->_audioRender=audioRenderer;
audioRenderInfo->_builder = _builder;
audioRenderInfo->m_pAudio = p_pAudio;
audioRenderInfo->m_bPlaying = true;
audioRenderInfo->pcmBuffer = p_pBuffer;
audioRenderInfo->m_pBufferSize = p_nBufferSize;
m_pAudioRenderSource.push_back(audioRenderInfo);
ret = OH_AudioRenderer_Start(audioRenderer);
return audioRenderInfo;
}
int32_t JCAudioWavPlayer::AudioRendererOnWriteData(OH_AudioRenderer *renderer, void *userData, void *buffer, int32_t bufferLen){
OHAudioRenderInfo *audioRenderInfo = (OHAudioRenderInfo *)userData;
const char *dataBuffer = audioRenderInfo->pcmBuffer;
if(dataBuffer == nullptr){
return 0;
}
int32_t writeBytes = audioRenderInfo->m_pBufferSize - audioRenderInfo->writeOffset >bufferLen?bufferLen: audioRenderInfo->m_pBufferSize - audioRenderInfo->writeOffset;
if(writeBytes<=0){
if(audioRenderInfo->m_bPlaying ==false){
return 0;
}
if(audioRenderInfo->m_pAudio !=NULL){
audioRenderInfo->m_pAudio->onPlayEnd();
audioRenderInfo->m_pAudio=NULL;
}
if(audioRenderInfo->_audioRender!=nullptr){
OH_AudioRenderer_Stop(audioRenderInfo->_audioRender);
OH_AudioRenderer_Release(audioRenderInfo->_audioRender);
}
if(audioRenderInfo->_builder != nullptr){
OH_AudioStreamBuilder_Destroy(audioRenderInfo->_builder);
}
audioRenderInfo->m_pAudio = NULL;
audioRenderInfo->m_bPlaying = false;
return 0;
}
memcpy(buffer,dataBuffer+audioRenderInfo->writeOffset,writeBytes);
audioRenderInfo->writeOffset += writeBytes;
return 0;
}
void JCAudioWavPlayer::stopAll(){
int m_ohAudioCount = m_pAudioRenderSource.size();
for (int i = 0; i < m_ohAudioCount; i++)
{
if(m_pAudioRenderSource[i]->m_bPlaying == true){
OHAudioRenderInfo *pAudioRenderInfo = m_pAudioRenderSource[i];
if(pAudioRenderInfo->_audioRender != nullptr){
OH_AudioRenderer_Stop(pAudioRenderInfo->_audioRender);
OH_AudioRenderer_Release(pAudioRenderInfo->_audioRender);
}
if(pAudioRenderInfo->_builder != nullptr){
OH_AudioStreamBuilder_Destroy(pAudioRenderInfo->_builder);
}
pAudioRenderInfo->m_bPlaying = false;
}
}
}
void JCAudioWavPlayer::pause(){
int32_t m_ohAudioCount = m_pAudioRenderSource.size();
for(int i=0; i< m_ohAudioCount; i++){
if(m_pAudioRenderSource[i]->_audioRender != nullptr){
OH_AudioRenderer_Pause(m_pAudioRenderSource[i]->_audioRender);
}
}
}
void JCAudioWavPlayer::resume(){
int m_ohAudioCount = m_pAudioRenderSource.size();
for(int i=0; i< m_ohAudioCount; i++){
if(m_pAudioRenderSource[i]->_audioRender != nullptr){
OH_AudioRenderer_Start(m_pAudioRenderSource[i]->_audioRender);
}
}
}
void JCAudioWavPlayer::setAllVolume(float p_nVolume){
int m_ohAudioCount = m_pAudioRenderSource.size();
for(int i=0; i< m_ohAudioCount; i++){
if(m_pAudioRenderSource[i]->_audioRender != nullptr){
//todo OHAudio设置音量接口暂不支持 后续补充
}
}
}
void JCAudioWavPlayer::stop(OHAudioRenderInfo * pAudioRenderInfo){
if(pAudioRenderInfo->m_bPlaying==true){
if(pAudioRenderInfo->_audioRender!=nullptr){
OH_AudioRenderer_Stop(pAudioRenderInfo->_audioRender);
OH_AudioRenderer_Release(pAudioRenderInfo->_audioRender);
}
if(pAudioRenderInfo->_builder!=nullptr){
OH_AudioStreamBuilder_Destroy(pAudioRenderInfo->_builder);
}
pAudioRenderInfo->m_pAudio = NULL;
pAudioRenderInfo->m_bPlaying = false;
}
}
void JCAudioWavPlayer::setVolume(OHAudioRenderInfo * pAudioRenderInfo, float p_nVolume){
//todo OHAudio设置音量接口暂不支持,后续补充
}
void JCAudioWavPlayer::Release(){
for(int i=0; i< m_pAudioRenderSource.size(); i++){
delete m_pAudioRenderSource[i];
}
}
JCWaveInfo *JCAudioWavPlayer::AddWaveInfo(const std::string &p_sUrl, unsigned char *p_pBuffer, int p_nSize, const char *p_sFilePath, void *p_pExternalMark, bool p_bIsOgg){
JCWaveInfo *pInfo = FindWaveInfo(p_sUrl);
if(pInfo == NULL){
if(p_bIsOgg == false){
pInfo= JCWaveParser::GetInstance()->GetWaveInfoFromBuffer(p_pBuffer,p_nSize);
}else{
pInfo = JCOggParser::GetInstance()->GetWaveInfo(p_sFilePath,p_pBuffer,p_nSize);
}
if(pInfo!=NULL){
pInfo->m_sUrl = p_sUrl;
pInfo->m_nTouchTime = tmGetCurms();
pInfo->m_pExternalMark = p_pExternalMark;
m_vWaveInfos[p_sUrl] = pInfo;
}else{
LOGE("JCAudioWavPlayer::AddWaveInfo wave paser err");
}
}
return pInfo;
}
void JCAudioWavPlayer::autoGarbageCollection(){
if (m_vWaveInfos.size()<=0)
return;
double nCurrentTime = tmGetCurms();
for(MapWaveInfoIter iter = m_vWaveInfos.begin(); iter!= m_vWaveInfos.end();){
JCWaveInfo *pInfo = iter->second;
if(pInfo&&(nCurrentTime- pInfo->m_nTouchTime > s_nGarbageCollectionTime)){
delete pInfo;
pInfo = NULL;
iter = m_vWaveInfos.erase(iter);
}else{
iter++;
}
}
}
JCWaveInfo *JCAudioWavPlayer::FindWaveInfo(const std::string &p_sUrl){
MapWaveInfoIter iter = m_vWaveInfos.find(p_sUrl);
if(iter!=m_vWaveInfos.end()){
return iter->second;
}
return NULL;
}
bool JCAudioWavPlayer::ClearAllWaveInfo(void){
for(MapWaveInfoIter iter = m_vWaveInfos.begin();iter!=m_vWaveInfos.end();iter++){
JCWaveInfo *pInfo = NULL;
pInfo = iter->second;
if(pInfo!=NULL){
delete pInfo;
pInfo = NULL;
}
}
m_vWaveInfos.clear();
return true;
}
}
@@ -0,0 +1,80 @@
#ifndef __JCAudioWavPlayer_OHOS_H__
#define __JCAudioWavPlayer_OHOS_H__
#include <stdio.h>
#include <thread>
#include "../../util/JCCommonMethod.h"
#include "JCWaveInfo.h"
#include "JCAudioInterface.h"
#include <unordered_map>
#include <vector>
#include <ohaudio/native_audiostreambuilder.h>
#include <ohaudio/native_audiorenderer.h>
namespace laya{
class JCFileResManager;
class OHAudioRenderInfo
{
public:
OH_AudioRenderer* _audioRender;
OH_AudioStreamBuilder* _builder;
JCAudioInterface* m_pAudio; //Audio 为了回调使用
bool m_bPlaying; //是否为播放状态
const char* pcmBuffer;
int32_t m_pBufferSize;
int32_t writeOffset = 0;
std::function<int32_t(OH_AudioRenderer* renderer, void* userData, void* buffer, int32_t bufferLen)> writeDataCallback;
public:
void operator=(const OHAudioRenderInfo &other){
m_bPlaying = other.m_bPlaying;
_audioRender = other._audioRender;
m_pAudio = other.m_pAudio;
}
};
class JCAudioWavPlayer{
public:
typedef std::unordered_map<std::string, JCWaveInfo*> MapWaveInfo;
typedef MapWaveInfo::iterator MapWaveInfoIter;
public:
JCAudioWavPlayer(JCFileResManager* pFileResManager);
~JCAudioWavPlayer();
void Release();
public:
OHAudioRenderInfo* playAudio(JCAudioInterface* p_pAudio, const std::string& p_sSrc, bool bIsOgg);
void delAudio(JCAudioInterface* p_pAudio);
OHAudioRenderInfo* playAudioFromBuffer(JCAudioInterface* p_pAudio, const char* p_pBuffer, unsigned int p_nBufferSize, int p_nRate, int p_nBitsPerSample, int nChannels);
void setVolume(OHAudioRenderInfo* pAudioRenderInfo, float p_nVolume);
void stop(OHAudioRenderInfo* pAudioRenderInfo);
void setAllVolume(float p_nVolume);
void stopAll();
void checkWavePlayEnd();
void pause();
void resume();
static int32_t AudioRendererOnWriteData(OH_AudioRenderer *renderer, void *userData, void *buffer, int32_t bufferLen);
public:
/**
* @brief
* @return
*/
JCWaveInfo *AddWaveInfo(const std::string &p_sUrl, unsigned char *p_pBuffer, int p_nSize, const char *p_sFilePath, void *p_pExternalMark, bool p_bIsOgg);
/**
* @brief ulid
* @param[in] ulid
* @return
*/
JCWaveInfo* FindWaveInfo(const std::string& p_sUrl);
/**
* @brief
*/
bool ClearAllWaveInfo(void);
void autoGarbageCollection();
public:
static int s_nGarbageCollectionTime;
MapWaveInfo m_vWaveInfos; //wave的信息
public:
JCFileResManager* m_pFileResManager;
OH_AudioRenderer *audioRenderer;
std::vector<OHAudioRenderInfo*> m_pAudioRenderSource; //播放声音用的
};
}
#endif //__JCAudioWavPlayer_H__
+418
View File
@@ -0,0 +1,418 @@
#include "ColorParser.h"
#include <regex>
#include <unordered_map>
#include "Log.h"
#include <algorithm>
namespace laya
{
static const std::unordered_map<std::string, uint32_t> namedColors = {
{"transparent", 0xFFFFFF00},
{"aliceblue", 0xF0F8FFFF},
{"antiquewhite", 0xFAEBD7FF},
{"aqua", 0x00FFFFFF},
{"aquamarine", 0x7FFFD4FF},
{"azure", 0xF0FFFFFF},
{"beige", 0xF5F5DCFF},
{"bisque", 0xFFE4C4FF},
{"black", 0x000000FF},
{"blanchedalmond", 0xFFEBCDFF},
{"blue", 0x0000FFFF},
{"blueviolet", 0x8A2BE2FF},
{"brown", 0xA52A2AFF},
{"burlywood", 0xDEB887FF},
{"cadetblue", 0x5F9EA0FF},
{"chartreuse", 0x7FFF00FF},
{"chocolate", 0xD2691EFF},
{"coral", 0xFF7F50FF},
{"cornflowerblue", 0x6495EDFF},
{"cornsilk", 0xFFF8DCFF},
{"crimson", 0xDC143CFF},
{"cyan", 0x00FFFFFF},
{"darkblue", 0x00008BFF},
{"darkcyan", 0x008B8BFF},
{"darkgoldenrod", 0xB8860BFF},
{"darkgray", 0xA9A9A9FF},
{"darkgreen", 0x006400FF},
{"darkgrey", 0xA9A9A9FF},
{"darkkhaki", 0xBDB76BFF},
{"darkmagenta", 0x8B008BFF},
{"darkolivegreen", 0x556B2FFF},
{"darkorange", 0xFF8C00FF},
{"darkorchid", 0x9932CCFF},
{"darkred", 0x8B0000FF},
{"darksalmon", 0xE9967AFF},
{"darkseagreen", 0x8FBC8FFF},
{"darkslateblue", 0x483D8BFF},
{"darkslategray", 0x2F4F4FFF},
{"darkslategrey", 0x2F4F4FFF},
{"darkturquoise", 0x00CED1FF},
{"darkviolet", 0x9400D3FF},
{"deeppink", 0xFF1493FF},
{"deepskyblue", 0x00BFFFFF},
{"dimgray", 0x696969FF},
{"dimgrey", 0x696969FF},
{"dodgerblue", 0x1E90FFFF},
{"firebrick", 0xB22222FF},
{"floralwhite", 0xFFFAF0FF},
{"forestgreen", 0x228B22FF},
{"fuchsia", 0xFF00FFFF},
{"gainsboro", 0xDCDCDCFF},
{"ghostwhite", 0xF8F8FFFF},
{"gold", 0xFFD700FF},
{"goldenrod", 0xDAA520FF},
{"gray", 0x808080FF},
{"green", 0x008000FF},
{"greenyellow", 0xADFF2FFF},
{"grey", 0x808080FF},
{"honeydew", 0xF0FFF0FF},
{"hotpink", 0xFF69B4FF},
{"indianred", 0xCD5C5CFF},
{"indigo", 0x4B0082FF},
{"ivory", 0xFFFFF0FF},
{"khaki", 0xF0E68CFF},
{"lavender", 0xE6E6FAFF},
{"lavenderblush", 0xFFF0F5FF},
{"lawngreen", 0x7CFC00FF},
{"lemonchiffon", 0xFFFACDFF},
{"lightblue", 0xADD8E6FF},
{"lightcoral", 0xF08080FF},
{"lightcyan", 0xE0FFFFFF},
{"lightgoldenrodyellow", 0xFAFAD2FF},
{"lightgray", 0xD3D3D3FF},
{"lightgreen", 0x90EE90FF},
{"lightgrey", 0xD3D3D3FF},
{"lightpink", 0xFFB6C1FF},
{"lightsalmon", 0xFFA07AFF},
{"lightseagreen", 0x20B2AAFF},
{"lightskyblue", 0x87CEFAFF},
{"lightslategray", 0x778899FF},
{"lightslategrey", 0x778899FF},
{"lightsteelblue", 0xB0C4DEFF},
{"lightyellow", 0xFFFFE0FF},
{"lime", 0x00FF00FF},
{"limegreen", 0x32CD32FF},
{"linen", 0xFAF0E6FF},
{"magenta", 0xFF00FFFF},
{"maroon", 0x800000FF},
{"mediumaquamarine", 0x66CDAAFF},
{"mediumblue", 0x0000CDFF},
{"mediumorchid", 0xBA55D3FF},
{"mediumpurple", 0x9370DBFF},
{"mediumseagreen", 0x3CB371FF},
{"mediumslateblue", 0x7B68EEFF},
{"mediumspringgreen", 0x00FA9AFF},
{"mediumturquoise", 0x48D1CCFF},
{"mediumvioletred", 0xC71585FF},
{"midnightblue", 0x191970FF},
{"mintcream", 0xF5FFFAFF},
{"mistyrose", 0xFFE4E1FF},
{"moccasin", 0xFFE4B5FF},
{"navajowhite", 0xFFDEADFF},
{"navy", 0x000080FF},
{"oldlace", 0xFDF5E6FF},
{"olive", 0x808000FF},
{"olivedrab", 0x6B8E23FF},
{"orange", 0xFFA500FF},
{"orangered", 0xFF4500FF},
{"orchid", 0xDA70D6FF},
{"palegoldenrod", 0xEEE8AAFF},
{"palegreen", 0x98FB98FF},
{"paleturquoise", 0xAFEEEEFF},
{"palevioletred", 0xDB7093FF},
{"papayawhip", 0xFFEFD5FF},
{"peachpuff", 0xFFDAB9FF},
{"peru", 0xCD853FFF},
{"pink", 0xFFC0CBFF},
{"plum", 0xDDA0DDFF},
{"powderblue", 0xB0E0E6FF},
{"purple", 0x800080FF},
{"rebeccapurple", 0x663399FF} // Source: CSS Color Level 4 draft
,
{"red", 0xFF0000FF},
{"rosybrown", 0xBC8F8FFF},
{"royalblue", 0x4169E1FF},
{"saddlebrown", 0x8B4513FF},
{"salmon", 0xFA8072FF},
{"sandybrown", 0xF4A460FF},
{"seagreen", 0x2E8B57FF},
{"seashell", 0xFFF5EEFF},
{"sienna", 0xA0522DFF},
{"silver", 0xC0C0C0FF},
{"skyblue", 0x87CEEBFF},
{"slateblue", 0x6A5ACDFF},
{"slategray", 0x708090FF},
{"slategrey", 0x708090FF},
{"snow", 0xFFFAFAFF},
{"springgreen", 0x00FF7FFF},
{"steelblue", 0x4682B4FF},
{"tan", 0xD2B48CFF},
{"teal", 0x008080FF},
{"thistle", 0xD8BFD8FF},
{"tomato", 0xFF6347FF},
{"turquoise", 0x40E0D0FF},
{"violet", 0xEE82EEFF},
{"wheat", 0xF5DEB3FF},
{"white", 0xFFFFFFFF},
{"whitesmoke", 0xF5F5F5FF},
{"yellow", 0xFFFF00FF},
{"yellowgreen", 0x9ACD32FF}};
static int hex2int(char c)
{
switch (c)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return c - '0';
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
return (c - 'a') + 10;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
return (c - 'A') + 10;
}
return 0;
}
static bool RGBAFromHex8String(const char *str, uint32_t &r, uint32_t &g, uint32_t &b, uint32_t &a)
{
r = (hex2int(str[0]) << 4) + hex2int(str[1]);
g = (hex2int(str[2]) << 4) + hex2int(str[3]);
b = (hex2int(str[4]) << 4) + hex2int(str[5]);
a = (hex2int(str[6]) << 4) + hex2int(str[7]);
return true;
}
static bool RGBAFromHex6String(const char *str, uint32_t &r, uint32_t &g, uint32_t &b, uint32_t &a)
{
r = (hex2int(str[0]) << 4) + hex2int(str[1]);
g = (hex2int(str[2]) << 4) + hex2int(str[3]);
b = (hex2int(str[4]) << 4) + hex2int(str[5]);
a = 255;
return true;
}
static bool RGBAFromHex4String(const char *str, uint32_t &r, uint32_t &g, uint32_t &b, uint32_t &a)
{
r = (hex2int(str[0]) << 4) + hex2int(str[0]);
g = (hex2int(str[1]) << 4) + hex2int(str[1]);
b = (hex2int(str[2]) << 4) + hex2int(str[2]);
a = (hex2int(str[3]) << 4) + hex2int(str[3]);
return true;
}
static bool RGBAFromHex3String(const char *str, uint32_t &r, uint32_t &g, uint32_t &b, uint32_t &a)
{
r = (hex2int(str[0]) << 4) + hex2int(str[0]);
g = (hex2int(str[1]) << 4) + hex2int(str[1]);
b = (hex2int(str[2]) << 4) + hex2int(str[2]);
a = 255;
return true;
}
static bool RGBAFromHexString(const char *str, uint32_t &r, uint32_t &g, uint32_t &b, uint32_t &a)
{
size_t len = strlen(str);
switch (len)
{
case 8:
return RGBAFromHex8String(str, r, g, b, a);
case 6:
return RGBAFromHex6String(str, r, g, b, a);
case 4:
return RGBAFromHex4String(str, r, g, b, a);
case 3:
return RGBAFromHex3String(str, r, g, b, a);
}
return false;
}
template <typename parsed_t> static bool parseInteger(const char **pStr, parsed_t *pParsed)
{
parsed_t &c = *pParsed;
const char *&str = *pStr;
int8_t sign = 1;
c = 0;
if (*str == '-')
{
sign = -1;
++str;
}
else if (*str == '+')
++str;
if (*str >= '0' && *str <= '9')
{
do
{
c *= 10;
c += *str++ - '0';
} while (*str >= '0' && *str <= '9');
}
else
{
return false;
}
if (sign < 0)
c = -c;
return true;
}
static bool parseRGBChannel(const char **pStr, uint8_t *pChannel)
{
int channel;
if (parseInteger(pStr, &channel))
{
*pChannel = (uint8_t)(std::clamp(channel, 0, 255));
return true;
}
return false;
}
#define CHANNEL(NAME) \
if (!parseRGBChannel(&str, &NAME)) \
return false;
#define SKIP_WHITESPACE \
while (' ' == *str) \
++str;
#define SKIP_WHITESPACE_OR_COMMA \
while (' ' == *str || ',' == *str) \
++str;
#define ALPHA(NAME) \
if (*str >= '1' && *str <= '9') \
{ \
NAME = 1; \
} \
else \
{ \
if ('0' == *str) \
{ \
NAME = 0; \
++str; \
} \
if ('.' == *str) \
{ \
++str; \
NAME = 0; \
float n = .1f; \
while (*str >= '0' && *str <= '9') \
{ \
NAME += (*str++ - '0') * n; \
n *= .1f; \
} \
} \
} \
do \
{ \
} while (0)
static bool RGBAFromRGBString(const char *str, uint32_t &r, uint32_t &g, uint32_t &b, uint32_t &a)
{
if (str == strstr(str, "rgb("))
{
str += 4;
SKIP_WHITESPACE;
uint8_t r1 = 0, g1 = 0, b1 = 0;
CHANNEL(r1);
SKIP_WHITESPACE_OR_COMMA;
CHANNEL(g1);
SKIP_WHITESPACE_OR_COMMA;
CHANNEL(b1);
SKIP_WHITESPACE;
r = r1;
g = g1;
b = b1;
a = 255u;
return true;
}
return false;
}
static bool RGBAFromRGBAString(const char *str, uint32_t &r, uint32_t &g, uint32_t &b, uint32_t &a)
{
if (str == strstr(str, "rgba("))
{
str += 5;
SKIP_WHITESPACE;
uint8_t r1 = 0, g1 = 0, b1 = 0;
float a1 = 1.f;
CHANNEL(r1);
SKIP_WHITESPACE_OR_COMMA;
CHANNEL(g1);
SKIP_WHITESPACE_OR_COMMA;
CHANNEL(b1);
SKIP_WHITESPACE_OR_COMMA;
ALPHA(a1);
SKIP_WHITESPACE;
r = r1;
g = g1;
b = b1;
a = (uint32_t)(a1 * 255);
return true;
}
return false;
}
static bool RGBAFromNameString(const char *str, uint32_t &r, uint32_t &g, uint32_t &b, uint32_t &a)
{
std::string lowered(str);
std::transform(lowered.begin(), lowered.end(), lowered.begin(), tolower);
auto color = namedColors.find(lowered);
if (color != namedColors.end())
{
uint32_t rgba = color->second;
r = rgba >> 24 & 0xff;
g = rgba >> 16 & 0xff;
b = rgba >> 8 & 0xff;
a = rgba & 0xff;
return true;
}
return false;
}
static bool RGBAFromHSLAString(const char *str, uint32_t &r, uint32_t &g, uint32_t &b, uint32_t &a)
{
LOGE("color HSLA not implemented %s", str);
return false;
}
static bool RGBAFromHSLString(const char *str, uint32_t &r, uint32_t &g, uint32_t &b, uint32_t &a)
{
LOGE("color HSL not implemented %s", str);
return false;
}
bool parseRGBAFromString(const char *str, uint32_t &r, uint32_t &g, uint32_t &b, uint32_t &a)
{
if ('#' == str[0])
return RGBAFromHexString(++str, r, g, b, a);
if (str == strstr(str, "rgba"))
return RGBAFromRGBAString(str, r, g, b, a);
if (str == strstr(str, "rgb"))
return RGBAFromRGBString(str, r, g, b, a);
if (str == strstr(str, "hsla"))
return RGBAFromHSLAString(str, r, g, b, a);
if (str == strstr(str, "hsl"))
return RGBAFromHSLString(str, r, g, b, a);
return RGBAFromNameString(str, r, g, b, a);
}
} // namespace laya
+8
View File
@@ -0,0 +1,8 @@
#ifndef __ColorParser_H__
#define __ColorParser_H__
#include <string>
namespace laya
{
bool parseRGBAFromString(const char *str, uint32_t &r, uint32_t &g, uint32_t &b, uint32_t &a);
} // namespace laya
#endif
+6 -3
View File
@@ -19,7 +19,7 @@
#include <sys/time.h>
#include <time.h>
#include <mach/mach_time.h>
#elif ANDROID
#elif ANDROID || OHOS
#include <time.h>
#elif WIN32
#include <windows.h>
@@ -68,7 +68,10 @@ namespace laya
ret+=(c<<off);
off+=4;
}
c=*(--pCur);
if ((long)pCur>(long)str)
c=*(--pCur);
else
--pCur;
}
return ret;
}
@@ -657,7 +660,7 @@ namespace laya
int64_t nanosec = mach_absolute_time()*info.numer / info.denom;
return (nanosec / 1e6);
#elif ANDROID
#elif ANDROID || OHOS
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
return now.tv_sec * 1000.0 + now.tv_nsec / 1e6;
+16
View File
@@ -14,6 +14,15 @@
#ifdef WIN32
#pragma execution_character_set("utf-8")
#endif
#ifdef OHOS
enum OHOSLogLevel {
Warn,
Error,
Debug,
Info,
Runtime,
};
#else
//通用的日志函数。
enum LogLevel {
Warn,
@@ -22,6 +31,7 @@ enum LogLevel {
Info,
Runtime,
};
#endif
extern void(*gLayaLog)(int level, const char* file, int line, const char* fmt,...);
//如果知道没有参数就不用做%的转换了。
extern void(*gLayaLogNoParam)(int level, const char* file, int line, const char* msg);
@@ -55,6 +65,12 @@ void alert(const char* fmt, ...);
#define LOGI(...) {if(g_nDebugLevel >= 3){if(gLayaLog){gLayaLog(Info,__FILE__,__LINE__,__VA_ARGS__);}else{__android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__);}}}
#define LOGW(...) {if(g_nDebugLevel >= 2){if(gLayaLog){gLayaLog(Warn,__FILE__,__LINE__,__VA_ARGS__);}else{__android_log_print(ANDROID_LOG_WARN,LOG_TAG,__VA_ARGS__);}}if(g_nDebugLevel >= 5){alert(__VA_ARGS__);}}
#define LOGE(...) {if(g_nDebugLevel >= 1){if(gLayaLog){gLayaLog(Error,__FILE__,__LINE__,__VA_ARGS__);}else{__android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__);}}if(g_nDebugLevel >= 4){alert(__VA_ARGS__);}}
#elif OHOS
#include <hilog/log.h>
#define LOG_TAG "LayaBox"
#define LOGI(...) {if(g_nDebugLevel >= 3){if(gLayaLog){gLayaLog(Info,__FILE__,__LINE__,__VA_ARGS__);}else{OH_LOG_Print(LOG_APP,LOG_INFO,LOG_DOMAIN,LOG_TAG,__VA_ARGS__);}}}
#define LOGW(...) {if(g_nDebugLevel >= 2){if(gLayaLog){gLayaLog(Warn,__FILE__,__LINE__,__VA_ARGS__);}else{OH_LOG_Print(LOG_APP,LOG_WARN,LOG_DOMAIN,LOG_TAG,__VA_ARGS__);}}if(g_nDebugLevel >= 5){alert(__VA_ARGS__);}}
#define LOGE(...) {if(g_nDebugLevel >= 1){if(gLayaLog){gLayaLog(Error,__FILE__,__LINE__,__VA_ARGS__);}else{OH_LOG_Print(LOG_APP,LOG_ERROR,LOG_DOMAIN,LOG_TAG,__VA_ARGS__);}}if(g_nDebugLevel >= 4){alert(__VA_ARGS__);}}
#elif WIN32
#define LOGI(...) { if(g_nDebugLevel >= 3){if(gLayaLog){gLayaLog(Info,__FILE__,__LINE__,__VA_ARGS__);}else{ printf(__VA_ARGS__);printf("\n");}}}
#define LOGW(...) { if(g_nDebugLevel >= 2){if(gLayaLog){gLayaLog(Warn,__FILE__,__LINE__,__VA_ARGS__);}else{ printf(__VA_ARGS__);printf("\n");}}if(g_nDebugLevel >= 5){alert(__VA_ARGS__);}}
+43 -4
View File
@@ -65,6 +65,25 @@ namespace laya
JCAudioWavPlayer* pWavPlayer = m_sAudioManager->m_pWavPlayer;
if( pWavPlayer != NULL )
{
#ifdef OHOS
int nALCount = pWavPlayer->m_pAudioRenderSource.size();
for (int i = 0; i < nALCount; i++)
{
if( pWavPlayer->m_pAudioRenderSource[i]->m_bPlaying == true ) {
OHAudioRenderInfo* pAudioRenderInfo = pWavPlayer->m_pAudioRenderSource[i];
if(pAudioRenderInfo->_audioRender != nullptr) {
OH_AudioRenderer_Stop(pAudioRenderInfo->_audioRender);
OH_AudioRenderer_Release(pAudioRenderInfo->_audioRender);
}
if(pAudioRenderInfo->_builder != nullptr) {
OH_AudioStreamBuilder_Destroy(pAudioRenderInfo->_builder);
}
pAudioRenderInfo->m_pAudio = NULL;
pAudioRenderInfo->m_bPlaying = false;
}
}
#else
int nALCount = pWavPlayer->m_pOpenALSource.size();
for (int i = 0; i < nALCount; i++)
{
@@ -75,6 +94,7 @@ namespace laya
pWavPlayer->m_pOpenALSource[i]->m_bPlaying = false;
}
}
#endif
pWavPlayer->ClearAllWaveInfo();
}
m_sAudioManager->ClearAllAudioBufferPlay();
@@ -100,6 +120,8 @@ namespace laya
m_pMp3Player = new JCAudioMp3Player();
#elif ANDROID
m_pMp3Player = new JCAudioMp3Media();
#elif OHOS
m_pMp3Player = new JCAudioMp3Player();
#elif __APPLE__
m_pMp3Player = new JCAudioMp3Player();
#endif
@@ -196,6 +218,21 @@ namespace laya
}
}
//------------------------------------------------------------------------------
#ifdef OHOS
OHAudioRenderInfo* JCAudioManager::playWav(JCAudioInterface* p_pAudio, const std::string& p_sUrl, bool bIsOgg)
{
return m_pWavPlayer->playAudio(p_pAudio, p_sUrl, bIsOgg);
}
void JCAudioManager::stopWav(OHAudioRenderInfo* audioRenderInfo)
{
m_pWavPlayer->stop(audioRenderInfo);
}
void JCAudioManager::setWavVolume(OHAudioRenderInfo* audioRenderInfo, float nVolume)
{
m_pWavPlayer->setVolume(audioRenderInfo, nVolume);
}
#else
OpenALSourceInfo* JCAudioManager::playWav(JCAudioInterface* p_pAudio, const std::string& p_sUrl, bool bIsOgg)
{
return m_pWavPlayer->playAudio(p_pAudio, p_sUrl, bIsOgg);
@@ -204,13 +241,15 @@ namespace laya
{
m_pWavPlayer->stop(pOpenALInfo);
}
void JCAudioManager::stopAllWav()
{
m_pWavPlayer->stopAll();
}
void JCAudioManager::setWavVolume(OpenALSourceInfo* pOpenALInfo, float nVolume)
{
m_pWavPlayer->setVolume(pOpenALInfo, nVolume);
}
#endif
void JCAudioManager::stopAllWav()
{
m_pWavPlayer->stopAll();
}
void JCAudioManager::setAllWavVolume(float nVolume)
{
+18 -2
View File
@@ -16,9 +16,15 @@
#include "windows/JCAudioMp3Player.h"
#elif __APPLE__
#include "ios/JCAudioMp3Player.h"
#elif OHOS
#include "ohos/JCAudioMp3Player.h"
#endif
#ifdef OHOS
#include "resource/Audio/JCAudioWavPlayer-openharmony.h"
#else
#include "resource/Audio/JCAudioWavPlayer.h"
#endif
#include <map>
#include <vector>
#include "resource/Audio/JCWaveInfo.h"
@@ -90,21 +96,31 @@ namespace laya
*/
bool ClearAllAudioBufferPlay( void );
#ifdef OHOS
OHAudioRenderInfo* playWav(JCAudioInterface* p_pAudio, const std::string& p_sUrl,bool bIsOgg);
void setWavVolume(OHAudioRenderInfo* audioRenderInfo,float nVolume );
void stopWav(OHAudioRenderInfo* audioRenderInfo );
#else
/** @brief 播放声音
* @param[in] interface
*/
OpenALSourceInfo* playWav(JCAudioInterface* p_pAudio, const std::string& p_sUrl,bool bIsOgg);
void setWavVolume(OpenALSourceInfo* pOpenALInfo,float nVolume );
void stopWav(OpenALSourceInfo* pOpenALInfo );
#endif
/** @brief 删除wav
* @param[in] interface
*/
void delWav(JCAudioInterface* p_pAudio);
void stopWav(OpenALSourceInfo* pOpenALInfo );
void stopAllWav();
void setWavVolume(OpenALSourceInfo* pOpenALInfo,float nVolume );
void setAllWavVolume( float nVolume );
@@ -0,0 +1,61 @@
#include <vector>
#include "JCAudioMp3Player.h"
#include "util/Log.h"
#include "aki/jsbind.h"
#include "helper/NapiHelper.h"
namespace laya{
JCAudioMp3Player::JCAudioMp3Player(){
m_nCurrentVolume = 1.0;
m_pJSAudio = NULL;
}
JCAudioMp3Player::~JCAudioMp3Player(void){
m_pJSAudio = NULL;
}
void JCAudioMp3Player::play(const char* p_sUrl, int p_nTimes, float nCurrentTime, JCAudioInterface* p_pJSAudio){
m_pJSAudio = p_pJSAudio;
NapiHelper::GetInstance()->playBackgroundMusic(p_sUrl, p_nTimes, (int)(nCurrentTime*1000));
}
void JCAudioMp3Player::delAudio(JCAudioInterface* p_pJSAudio){
if(m_pJSAudio == p_pJSAudio){
m_pJSAudio = NULL;
}
}
void JCAudioMp3Player::pause(){
NapiHelper::GetInstance()->pauseBackgroundMusic();
}
void JCAudioMp3Player::stop(){
NapiHelper::GetInstance()->stopBackgroundMusic();
m_pJSAudio = NULL;
}
void JCAudioMp3Player::resume(){
NapiHelper::GetInstance()->resumeBackgroundMusic();
}
void JCAudioMp3Player::setVolume(float p_nVolume){
m_nCurrentVolume = p_nVolume;
NapiHelper::GetInstance()->setBackgroundMusicVolume(p_nVolume);
}
void JCAudioMp3Player::setMute(bool p_bMute){
if(p_bMute == true){
float nTemp = m_nCurrentVolume;
setVolume(0.0f);
m_nCurrentVolume = nTemp;
}else{
setVolume(m_nCurrentVolume);
}
}
void JCAudioMp3Player::onPlayEnd(){
if(m_pJSAudio){
m_pJSAudio->onPlayEnd();
}
}
void JCAudioMp3Player::setCurrentTime(double nCurrentTime){
NapiHelper::GetInstance()->setCurrentTime(nCurrentTime);
}
double JCAudioMp3Player::getCurrentTime(){
return NapiHelper::GetInstance()->getCurrentTime();
}
double JCAudioMp3Player::getDuration(){
return NapiHelper::GetInstance()->getDuration();
}
}
@@ -0,0 +1,36 @@
#ifndef __JCAudioMp3Player_H__
#define __JCAudioMp3Player_H__
#include <stdio.h>
#include <string>
#include <string.h>
#include "resource/Audio/JCMp3Interface.h"
namespace laya{
/**
* @brief
*/
class JCAudioMp3Player : public JCMp3Interface{
public:
// 构造函数
JCAudioMp3Player();
// 析构函数
~JCAudioMp3Player(void);
void play(const char* p_sUrl, int p_nTimes, float nCurrentTime, JCAudioInterface* p_pJSAudio);
void delAudio(JCAudioInterface* p_pJSAudio);
void pause();
void stop();
void resume();
void setVolume(float p_nVolume);
void setMute(bool p_bMute);
void onPlayEnd();
void setCurrentTime(double nCurrentTime);
double getCurrentTime();
double getDuration();
private:
JCAudioInterface* m_pJSAudio;
float m_nCurrentVolume;
};
}
#endif //__JCAudioMp3Play_H__
-3
View File
@@ -183,9 +183,6 @@ void CToObjectCSetScreenWakeLock( bool p_bWakeLock );
void CToObjectCShowToast( const char* p_sInfo );
void CToObjectCOpenAppStoreUrl( const char* p_sAppID );
std::string CToObjectCCallMethod(int objid,bool isSync, const char*clsName, const char* methodName, const char* paramStr);//
void CToObjectCCallWebviewJS(const char* functionName, const char* jsonParam, const char* callback);
void CToObjectCShowWebView();
void CToObjectCHideWebView();
void CToObjectCSetSensorAble(bool p_bAble);
void CToObjectCRunJS(const std::string& script);
void CToObjectCCaptureScreen();
+4
View File
@@ -33,6 +33,8 @@
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#elif OHOS
#include "helper/NapiHelper.h"
#elif __APPLE__
#include "CToObjectC.h"
#include "pthread.h"
@@ -62,6 +64,8 @@ namespace laya
#ifdef ANDROID
CToJavaBridge::JavaRet kRet;
CToJavaBridge::GetInstance()->callMethod(CToJavaBridge::JavaClass.c_str(), "vibrate", kRet);
#elif OHOS
NapiHelper::GetInstance()->startVibration(0.1f);
#endif
}
JCConch::JCConch(int nDownloadThreadNum, JS_DEBUG_MODE nJSDebugMode, int nJSDebugPort)
+4
View File
@@ -22,6 +22,8 @@
#include "JSWrapper/LayaWrap/JSAndroidEditBox.h"
#elif __APPLE__
#include "JSWrapper/LayaWrap/JSIOSEditBox.h"
#elif OHOS
#include "JSWrapper/LayaWrap/JSOHOSEditBox.h"
#endif
#include <util/JCIThreadCmdMgr.h>
@@ -259,6 +261,8 @@ namespace laya
JSAndroidEditBox* m_pCurEditBox;
#elif __APPLE__
JSIOSEditBox * m_pCurEditBox;
#elif OHOS
JSOHOSEditBox * m_pCurEditBox;
#endif
#ifdef JS_V8
DebuggerAgent* m_pDbgAgent;
@@ -102,9 +102,15 @@ namespace laya{
v8::Local<v8::ArrayBuffer> createJSAB(char* pData, int len) {
v8::Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), len);
v8::ArrayBuffer::Contents contents = ab->GetContents();// ab->Externalize();
char* pPtr = (char*)contents.Data();
//#ifdef OHOS
std::shared_ptr<BackingStore> contents = ab->GetBackingStore();// ab->Externalize();
char* pPtr = (char*)contents->Data();
memcpy(pPtr, pData, len);
//#else
//v8::ArrayBuffer::Contents contents = ab->GetContents();// ab->Externalize();
//char* pPtr = (char*)contents.Data();
//memcpy(pPtr, pData, len);
//#endif
//Externalize 以后会减去内存占用,导致不能正确GC,所以再给加回来。不知道管理ArrayBuffer的正确方法是什么。
//v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(len);
return ab;
@@ -113,9 +119,15 @@ namespace laya{
v8::Local<v8::ArrayBuffer> createJSABAligned(char* pData, int len) {
int asz = (len + 3) & 0xfffffffc;
v8::Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), asz);
v8::ArrayBuffer::Contents contents = ab->GetContents();// ab->Externalize();
char* pPtr = (char*)contents.Data();
memcpy(pPtr, pData, len);
//#ifdef OHOS
std::shared_ptr<BackingStore> contents = ab->GetBackingStore();
char* pPtr = (char*)contents->Data();
memcpy(pPtr, pData, len);
//#else
//v8::ArrayBuffer::Contents contents = ab->GetContents();// ab->Externalize();
//char* pPtr = (char*)contents.Data();
//memcpy(pPtr, pData, len);
//#endif
//ArrayBuffer 自己已经初始化为0了
//Externalize 以后会减去内存占用,导致不能正确GC,所以再给加回来。不知道管理ArrayBuffer的正确方法是什么。
//v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(asz);
@@ -128,15 +140,26 @@ namespace laya{
v8::Local<v8::ArrayBufferView> abv = v8::Local<v8::ArrayBufferView>::Cast(jsval);
len = abv->ByteLength();
ab = abv->Buffer();
v8::ArrayBuffer::Contents contents = ab->GetContents();
//len = contents.ByteLength(); 这种情况下,用view的长度,因为可能多个view公用一个大buffer
data = (char*)contents.Data()+abv->ByteOffset();
//#ifdef OHOS
std::shared_ptr<BackingStore> contents = ab->GetBackingStore();
data = (char*)contents->Data()+abv->ByteOffset();
//#else
//v8::ArrayBuffer::Contents contents = ab->GetContents();
////len = contents.ByteLength(); 这种情况下,用view的长度,因为可能多个view公用一个大buffer
//data = (char*)contents.Data()+abv->ByteOffset();
//#endif
}
else if (jsval->IsArrayBuffer()) {
ab = v8::Local<v8::ArrayBuffer>::Cast(jsval);
v8::ArrayBuffer::Contents contents = ab->GetContents();
len = contents.ByteLength();
data = (char*)contents.Data();
//#ifdef OHOS
std::shared_ptr<BackingStore> contents = ab->GetBackingStore();
len = contents->ByteLength();
data = (char*)contents->Data();
//#else
//v8::ArrayBuffer::Contents contents = ab->GetContents();
//len = contents.ByteLength();
//data = (char*)contents.Data();
//#endif
}
else {
data = NULL;
@@ -18,6 +18,7 @@
#include "../../CToJavaBridge.h"
#endif
#include "util/JCColor.h"
#include <util/ColorParser.h>
namespace laya
{
@@ -235,7 +236,13 @@ void JSAndroidEditBox::blur()
//------------------------------------------------------------------------------
void JSAndroidEditBox::setColor( const char* p_sColor )
{
int nColor = JCColor::getColorUintFromString( p_sColor );
uint32_t colorR{0};
uint32_t colorG{0};
uint32_t colorB{0};
uint32_t colorA{0};
parseRGBAFromString(p_sColor, colorR, colorG, colorB, colorA);
int nColor = colorA << 24 | colorR << 16 | colorG << 8 | colorB;
CToJavaBridge::JavaRet kRet;
CToJavaBridge::GetInstance()->callMethod(CToJavaBridge::JavaClass.c_str(), "setEditBoxColor", nColor, kRet);
}
@@ -44,7 +44,11 @@ namespace laya
m_sLocalFileName = "";
m_bIsOgg = false;
m_bDownloaded = false;
#ifdef OHOS
audioRenderInfo = NULL;
#else
m_pOpenALInfo = NULL;
#endif
AdjustAmountOfExternalAllocatedMemory( 534 );
JCMemorySurvey::GetInstance()->newClass( "audio",534,this );
m_CallbackRef.reset(new int(1));
@@ -106,10 +110,17 @@ namespace laya
}
else if( m_nType == 1 )
{
#ifdef OHOS
if (audioRenderInfo && audioRenderInfo->m_pAudio == this)
{
JCAudioManager::GetInstance()->setWavVolume(audioRenderInfo, m_bMuted ? 0 : m_nVolume);
}
#else
if (m_pOpenALInfo && m_pOpenALInfo->m_pAudio == this)
{
JCAudioManager::GetInstance()->setWavVolume(m_pOpenALInfo, m_bMuted ? 0 : m_nVolume);
}
#endif
}
}
//------------------------------------------------------------------------------
@@ -329,10 +340,17 @@ namespace laya
}
else if( m_nType == 1 )
{
#ifdef OHOS
if (audioRenderInfo && audioRenderInfo->m_pAudio == this)
{
JCAudioManager::GetInstance()->setWavVolume(audioRenderInfo,m_nVolume);
}
#else
if (m_pOpenALInfo && m_pOpenALInfo->m_pAudio == this)
{
JCAudioManager::GetInstance()->setWavVolume(m_pOpenALInfo,m_nVolume);
}
#endif
}
}
//------------------------------------------------------------------------------
@@ -363,11 +381,19 @@ namespace laya
}
else if( m_nType == 1 )
{
#ifdef OHOS
audioRenderInfo = JCAudioManager::GetInstance()->playWav( this,m_sSrc, m_bIsOgg);
if (audioRenderInfo)
{
JCAudioManager::GetInstance()->setWavVolume(audioRenderInfo, m_nVolume);
}
#else
m_pOpenALInfo = JCAudioManager::GetInstance()->playWav( this,m_sSrc, m_bIsOgg);
if (m_pOpenALInfo)
{
JCAudioManager::GetInstance()->setWavVolume(m_pOpenALInfo, m_nVolume);
}
#endif
}
}
//------------------------------------------------------------------------------
@@ -380,11 +406,19 @@ namespace laya
}
else
{
#ifdef OHOS
if (audioRenderInfo && audioRenderInfo->m_pAudio == this)
{
JCAudioManager::GetInstance()->stopWav(audioRenderInfo);
audioRenderInfo = NULL;
}
#else
if (m_pOpenALInfo && m_pOpenALInfo->m_pAudio == this)
{
JCAudioManager::GetInstance()->stopWav(m_pOpenALInfo);
m_pOpenALInfo = NULL;
}
#endif
}
}
//------------------------------------------------------------------------------
@@ -396,11 +430,19 @@ namespace laya
}
else
{
#ifdef OHOS
if (audioRenderInfo && audioRenderInfo->m_pAudio == this)
{
JCAudioManager::GetInstance()->stopWav(audioRenderInfo);
audioRenderInfo = NULL;
}
#else
if (m_pOpenALInfo && m_pOpenALInfo->m_pAudio == this)
{
JCAudioManager::GetInstance()->stopWav(m_pOpenALInfo);
m_pOpenALInfo = NULL;
}
#endif
}
}
void JSAudio::setCurrentTime(double nCurrentTime)
@@ -21,7 +21,11 @@
*/
namespace laya
{
#ifdef OHOS
class OHAudioRenderInfo;
#else
class OpenALSourceInfo;
#endif
class JSAudio : public JsObjBase, public JSObjNode,JCAudioInterface
{
public:
@@ -114,7 +118,12 @@ namespace laya
JsObjHandle m_pJSFunctionAudioEnd; //JS的回调
JsObjHandle m_pJSFunctionCanPlay; //JS的回调
JsObjHandle m_pJSFunctionError; //JS的回调
#ifdef OHOS
OHAudioRenderInfo* audioRenderInfo;
#else
OpenALSourceInfo* m_pOpenALInfo; //openAL的指针
#endif
private:
@@ -18,6 +18,10 @@
#include <Windows.h>
#elif __APPLE__
#include "../../CToObjectC.h"
#elif OHOS
#include "aki/jsbind.h"
#include <string>
#include "helper/NapiHelper.h"
#endif
#include "downloadMgr/JCDownloadMgr.h"
#include "util/Log.h"
@@ -25,7 +29,11 @@
#include "../../JCConchRender.h"
#include "../../JCConch.h"
#include "../../WebSocket/WebSocket.h"
#ifdef OHOS
#include <resource/Audio/JCAudioWavPlayer-openharmony.h>
#else
#include <resource/Audio/JCAudioWavPlayer.h>
#endif
#include "../../Audio/JCAudioManager.h"
#include <LayaGL/JCLayaGL.h>
#include <LayaGL/JCLayaGLDispatch.h>
@@ -107,6 +115,8 @@ namespace laya
return CToObjectCGetUsedMem();
#elif WIN32
return getAppUsedMem();
#elif OHOS
return NapiHelper::GetInstance()->getUsedMem();
#endif
return 0;
}
@@ -119,6 +129,8 @@ namespace laya
return (int)(kRet.floatRet);
}
return 0;
#elif OHOS
return NapiHelper::GetInstance()->getAvalidMem();
#elif WIN32
MEMORYSTATUSEX statex;
statex.dwLength = sizeof(statex);
@@ -138,6 +150,8 @@ namespace laya
return kRet.floatRet;
}
return 0;
#elif OHOS
return NapiHelper::GetInstance()->getScreenInch();
#elif WIN32
return 0;
#elif __APPLE__
@@ -193,6 +207,30 @@ namespace laya
MoveWindow(g_hWnd, 0, 0, g_nInnerWidth, g_nInnerHeight, true);
#elif __APPLE__
CToObjectCSetScreenOrientation(p_nOrientation);
#elif OHOS
int orientation = 0;
if(p_nOrientation == landscape) {
orientation = 2;
} else if(p_nOrientation == portrait) {
orientation = 1;
} else if(p_nOrientation == user) {
orientation = 0;
} else if(p_nOrientation == behind) {
orientation = 5;
} else if(p_nOrientation == nosensor) {
orientation = 11;
} else if(p_nOrientation == sensor_landscape) {
orientation = 7;
} else if(p_nOrientation == sensor_portrait) {
orientation = 6;
} else if(p_nOrientation == reverse_landscape) {
orientation = 4;
} else if(p_nOrientation == reverse_portrait) {
orientation = 3;
} else if(p_nOrientation == sensor || p_nOrientation == full_sensor) {
orientation = 3;
}
NapiHelper::GetInstance()->setPreferredOrientation(orientation);
#endif
}
@@ -218,6 +256,8 @@ namespace laya
return 1;
#elif __APPLE__
return CToObjectCGetNetworkType();
#elif OHOS
return NapiHelper::GetInstance()->getNetworkType();
#endif
return 0;
}
@@ -302,6 +342,8 @@ namespace laya
return "Conch-android";
#elif WIN32
return "Conch-window";
#elif OHOS
return "Conch-ohos";
#endif
}
const char* JSConchConfig::getBrowserInfo()
@@ -312,6 +354,8 @@ namespace laya
return "Conch-android";
#elif WIN32
return "Conch-window";
#elif OHOS
return "Conch-ohos";
#endif
}
const char* JSConchConfig::getGuid()
@@ -334,11 +378,13 @@ namespace laya
const char* JSConchConfig::getRuntimeVersion()
{
#ifdef __APPLE__
return "ios-conch6-release-2.13.4";
return "ios-conch6-release-2.13.5.1";
#elif ANDROID
return "android-conch6-release-2.13.4";
return "android-conch6-release-2.13.5.1";
#elif OHOS
return "ohos-conch6-release-2.13.5.1";
#elif WIN32
return "window-conch6-release-2.13.4";
return "window-conch6-release-2.13.5.1";
#endif
}
const char* JSConchConfig::getAppVersion()
@@ -354,6 +400,9 @@ namespace laya
return m_sAppVersion.c_str();
}
return "";
#elif OHOS
m_sAppVersion = NapiHelper::GetInstance()->getAppVersion();
return m_sAppVersion.c_str();
#elif WIN32
return "2.0";
#endif
@@ -371,6 +420,9 @@ namespace laya
return m_sAppLocalVersion.c_str();
}
return "";
#elif OHOS
m_sAppLocalVersion = NapiHelper::GetInstance()->getAppLocalVersion();
return m_sAppLocalVersion.c_str();
#elif WIN32
return "2.0";
#endif
@@ -401,6 +453,9 @@ namespace laya
}
LOGI("getDeviceInfo::get_Value=%s", m_sDeviceInfo.c_str());
return m_sDeviceInfo.c_str();
#elif OHOS
m_sDeviceInfo = NapiHelper::GetInstance()->getDeviceInfo();
return m_sDeviceInfo.c_str();
#elif WIN32
return "{\"resolution\":\"1920*1080\", \"guid\":\"xxxxxxxxx\",\"imei\":[\"imeixxx\"],\"imsi\":[\"imsixxx\"],\"os\":\"windows\",\"osversion\":\"windows7 64\",\"phonemodel\":\"Wintel\" }";
#endif
@@ -30,6 +30,10 @@
#ifdef ANDROID
#include "JSAndroidEditBox.h"
#include "../../CToJavaBridge.h"
#elif OHOS
#include "JSOHOSEditBox.h"
#include "aki/jsbind.h"
#include "helper/NapiHelper.h"
#elif WIN32
#include <Windows.h>
#include "JSWindowEditBox.h"
@@ -65,6 +69,8 @@ extern bool g_bGLCanvasSizeChanged;
int g_bEnableTouch = true;
#elif __APPLE__
int g_bEnableTouch = true;
#elif OHOS
int g_bEnableTouch = true;
#endif
std::string g_sExePath = "";
@@ -245,6 +251,8 @@ namespace laya
CToJavaBridge::GetInstance()->callMethod(CToJavaBridge::JavaClass.c_str(), "alert", strBuffer.c_str(), kRet);
#elif __APPLE__
CToObjectCAlert(p_sBuffer);
#elif OHOS
NapiHelper::GetInstance()->showDialog(p_sBuffer);
#endif
}
void JSAlert(const char* p_sBuffer)
@@ -268,6 +276,8 @@ namespace laya
return 1.0;
#elif ANDROID
return 1.0;
#elif OHOS
return 1.0;
#elif __APPLE__
return 1.0;// CToObjectCGetDevicePixelRatio();
#endif
@@ -461,6 +471,8 @@ namespace laya
JSAndroidEditBox::exportJS();
#elif __APPLE__
JSIOSEditBox::exportJS();
#elif OHOS
JSOHOSEditBox::exportJS();
#endif
//JSTextCanvas
JSTextBitmapInfo::exportJS();
@@ -13,8 +13,9 @@
#include <util/JCColor.h>
#include "../../CToObjectC.h"
#include "../../JCScriptRuntime.h"
namespace laya
#include <util/ColorParser.h>
namespace laya
{
ADDJSCLSINFO(JSIOSEditBox, JSObjNode);
//------------------------------------------------------------------------------
@@ -207,7 +208,12 @@ void JSIOSEditBox::blur()
//------------------------------------------------------------------------------
void JSIOSEditBox::setColor( const char* p_sColor )
{
int nColor = JCColor::getColorUintFromString( p_sColor );
uint32_t colorR{0};
uint32_t colorG{0};
uint32_t colorB{0};
uint32_t colorA{0};
parseRGBAFromString(p_sColor, colorR, colorG, colorB, colorA);
int nColor = colorA << 24 | colorR << 16 | colorG << 8 | colorB;
CToObjectCSetEditBoxColor( nColor );
}
//------------------------------------------------------------------------------
@@ -0,0 +1,263 @@
#include "JSOHOSEditBox.h"
#include "aki/jsbind.h"
#include "../../JCScriptRuntime.h"
#include "util/Log.h"
#include "util/JCColor.h"
namespace laya{
static int curIndex = 0;
ADDJSCLSINFO(JSOHOSEditBox,JSObjNode);
JSOHOSEditBox::JSOHOSEditBox(){
m_tag = curIndex;
curIndex++;
m_nLeft = 0;
m_nTop = 0;
m_nWidth = 0;
m_nHeight = 0;
m_fOpacity = 1;
m_sStyle = "";
m_sValue = "";
m_sType = "type";
m_nFontSize = 12;
m_nScaleX = 1;
m_nScaleY = 1;
m_bForbidEdit = false;
m_CallbackRef.reset(new int(1));
AdjustAmountOfExternalAllocatedMemory(256);
JCMemorySurvey::GetInstance()->newClass("OHOSEditBox",256,this);
aki::JSBind::GetJSFunction("EditBox.create")->Invoke<void>(m_tag);
}
JSOHOSEditBox::~JSOHOSEditBox(){
JCMemorySurvey::GetInstance()->releaseClass("OHOSEditBox",this);
aki::JSBind::GetJSFunction("EditBox.remove")->Invoke<void>(m_tag);
}
void JSOHOSEditBox::addEventListener(const char* p_sName, JSValueAsParam p_pFunction){
if(strcmp(p_sName,"input")==0){
m_pJSFunctionOnInput.set(0,this,p_pFunction);
} else if(strcmp(p_sName, "keydown")==0){
//m_pJSFunctionOnKeydown = p_pFunction;
}
}
int JSOHOSEditBox::set_Left(int p_nLeft){
m_nLeft = p_nLeft;
aki::JSBind::GetJSFunction("EditBox.setPos")->Invoke<void>(m_tag, m_nLeft, m_nTop);
return m_nLeft;
}
int JSOHOSEditBox::get_Left(){
return m_nLeft;
}
int JSOHOSEditBox::set_Top(int p_nTop){
m_nTop = p_nTop;
aki::JSBind::GetJSFunction("EditBox.setPos")->Invoke<void>(m_tag, m_nLeft, m_nTop);
return m_nTop;
}
int JSOHOSEditBox::get_Top(){
return m_nTop;
}
int JSOHOSEditBox::set_Width(int p_nWidth){
m_nWidth = p_nWidth;
aki::JSBind::GetJSFunction("EditBox.setSize")->Invoke<void>(m_tag,(int)(m_nWidth * m_nScaleX), (int)(m_nHeight * m_nScaleY));
return m_nWidth;
}
int JSOHOSEditBox::get_Width(){
return m_nWidth;
}
int JSOHOSEditBox::set_Height(int p_nHeight){
m_nHeight = p_nHeight;
aki::JSBind::GetJSFunction("EditBox.setSize")->Invoke<void>(m_tag,(int)(m_nWidth * m_nScaleX), (int)(m_nHeight * m_nScaleY));
return m_nHeight;
}
int JSOHOSEditBox::get_Height(){
return m_nHeight;
}
float JSOHOSEditBox::set_Opacity(float p_Opacity){
m_fOpacity = p_Opacity;
aki::JSBind::GetJSFunction("EditBox.setOpacity")->Invoke<void>(m_tag, m_fOpacity);
return m_fOpacity;
}
float JSOHOSEditBox::get_Opacity(){
return m_fOpacity;
}
const char* JSOHOSEditBox::set_Value(const char* p_sValue){
LOGI("JSOHOSEditBox::set_Value=%{public}s",p_sValue);
m_sValue = (p_sValue!=NULL)?p_sValue:"";
aki::JSBind::GetJSFunction("EditBox.setValue")->Invoke<void>(m_tag, m_sValue);
return m_sValue.c_str();
}
const char* JSOHOSEditBox::get_Value(){
m_sValue = aki::JSBind::GetJSFunction("EditBox.getValue")->Invoke<std::string>(m_tag);
return m_sValue.c_str();
}
void JSOHOSEditBox::set_Style(const char* p_sStyle){
if(p_sStyle==NULL)
m_sStyle = "";
else
m_sStyle = p_sStyle;
aki::JSBind::GetJSFunction("EditBox.setStyle")->Invoke<void>(m_tag, m_sStyle);
}
const char* JSOHOSEditBox::get_Style(){
return m_sStyle.c_str();
}
bool JSOHOSEditBox::set_Visible(bool p_bVisible){
m_bVisible = p_bVisible;
aki::JSBind::GetJSFunction("EditBox.setVisible")->Invoke<void>(m_tag, m_bVisible);
return m_bVisible;
}
bool JSOHOSEditBox::get_Visible(){
return m_bVisible;
}
void JSOHOSEditBox::setLeft(int p_nLeft){
set_Left(p_nLeft);
}
void JSOHOSEditBox::setTop(int p_nTop){
set_Top(p_nTop);
}
void JSOHOSEditBox::setWidth(int p_nWidth){
set_Width(p_nWidth);
}
void JSOHOSEditBox::setHeight(int p_nHeight){
set_Height(p_nHeight);
}
void JSOHOSEditBox::setOpacity(float p_Opacity){
set_Opacity(p_Opacity);
}
void JSOHOSEditBox::setValue(const char* p_sValue){
set_Value(p_sValue);
}
const char* JSOHOSEditBox::getValue(){
return get_Value();
}
void JSOHOSEditBox::setStyle(const char* p_sStyle){
set_Style(p_sStyle);
}
void JSOHOSEditBox::setVisible(bool p_bVisible){
set_Visible(p_bVisible);
}
void JSOHOSEditBox::focus(){
m_bVisible = true;
aki::JSBind::GetJSFunction("EditBox.focus")->Invoke<void>(m_tag);
}
void JSOHOSEditBox::blur(){
m_bVisible = false;
aki::JSBind::GetJSFunction("EditBox.setVisible")->Invoke<void>(m_tag,false);
}
void JSOHOSEditBox::setColor(const char* p_sColor){
aki::JSBind::GetJSFunction("EditBox.setColor")->Invoke<void>(m_tag,p_sColor);
}
void JSOHOSEditBox::setFontSize(int p_nFontSize){
m_nFontSize = p_nFontSize;
aki::JSBind::GetJSFunction("EditBox.setFontSize")->Invoke<void>(m_tag,(int)(m_nFontSize * m_nScaleY));
}
void JSOHOSEditBox::setPos(int x, int y){
m_nLeft = x;
m_nTop = y;
aki::JSBind::GetJSFunction("EditBox.setPos")->Invoke<void>(m_tag,m_nLeft,m_nTop);
}
void JSOHOSEditBox::setSize(int w, int h){
m_nWidth = w;
m_nHeight = h;
aki::JSBind::GetJSFunction("EditBox.setSize")->Invoke<void>(m_tag,(int)(m_nWidth * m_nScaleX),(int)(m_nHeight * m_nScaleY));
}
void JSOHOSEditBox::setCursorPosition(int pos){
aki::JSBind::GetJSFunction("EditBox.setCursorPosition")->Invoke<void>(m_tag, pos);
}
void JSOHOSEditBox::setScale(float p_nSx, float p_nSy){
m_nScaleX = p_nSx;
m_nScaleY = p_nSy;
setFontSize(m_nFontSize);
setSize(m_nWidth,m_nHeight);
}
void JSOHOSEditBox::setMaxLength(int p_nMaxLength){
m_nMaxLength = p_nMaxLength;
aki::JSBind::GetJSFunction("EditBox.setMaxLength")->Invoke<void>(m_tag, m_nMaxLength);
}
void JSOHOSEditBox::setType(const char* p_sType){
m_sType = p_sType;
int type = laya::EditBoxType::NORMAL;
if(m_sType == "password"){
type = laya::EditBoxType::PASSWORD;
}
aki::JSBind::GetJSFunction("EditBox.setType")->Invoke<void>(m_tag, type);
}
void JSOHOSEditBox::setRegular(const char* p_sRegular)
{
m_sRegular = p_sRegular;
aki::JSBind::GetJSFunction("EditBox.setRegular")->Invoke<void>(m_tag, m_sRegular);
}
void JSOHOSEditBox::setFont(const char* p_sFont){
}
void JSOHOSEditBox::setNumberOnly(bool p_bNumberOnly){
int type = laya::EditBoxType::NORMAL;
if(p_bNumberOnly){
if(m_sType == "password"){
type = laya::EditBoxType::NUMBER_PASSWORD;
}else{
type = laya::EditBoxType::NUMBER;
}
}else{
if(m_sType == "password"){
type = laya::EditBoxType::PASSWORD;
}
}
aki::JSBind::GetJSFunction("EditBox.setType")->Invoke<void>(m_tag,type);
}
void JSOHOSEditBox::onInputCallJSFunction(std::weak_ptr<int> callbackref){
if(!callbackref.lock())
return;
m_pJSFunctionOnInput.Call();
}
void JSOHOSEditBox::onInput(){
std::weak_ptr<int> cbref(m_CallbackRef);
std::function<void(void)> pFunction = std::bind(&JSOHOSEditBox::onInputCallJSFunction,this,cbref);
JCScriptRuntime::s_JSRT->m_pScriptThread->post(pFunction);
}
void JSOHOSEditBox::setMultiAble(bool p_bMultiAble){
aki::JSBind::GetJSFunction("EditBox.setMultiAble")->Invoke<void>(m_tag, p_bMultiAble);
}
void JSOHOSEditBox::setForbidEdit(bool bForbidEdit){
m_bForbidEdit = bForbidEdit;
aki::JSBind::GetJSFunction("EditBox.setForbidEdit")->Invoke<void>(m_tag, m_bForbidEdit);
}
bool JSOHOSEditBox::getForbidEdit(){
return m_bForbidEdit;
}
void JSOHOSEditBox::exportJS(){
JSP_CLASS("ConchInput",JSOHOSEditBox);
JSP_ADD_PROPERTY(left,JSOHOSEditBox,get_Left,set_Left);//2
JSP_ADD_PROPERTY(top,JSOHOSEditBox,get_Top,set_Top);//2
JSP_ADD_PROPERTY(width,JSOHOSEditBox,get_Width,set_Width);//2
JSP_ADD_PROPERTY(height,JSOHOSEditBox,get_Height,set_Height);//2
JSP_ADD_PROPERTY(opacity,JSOHOSEditBox,get_Opacity,set_Opacity);//2
JSP_ADD_PROPERTY(style,JSOHOSEditBox,get_Style,set_Style);//2
JSP_ADD_PROPERTY(value,JSOHOSEditBox,get_Value,set_Value);//2
JSP_ADD_PROPERTY(visible,JSOHOSEditBox,get_Visible,set_Visible);//2
JSP_ADD_METHOD("addEventListener",JSOHOSEditBox::addEventListener);
JSP_ADD_METHOD("setLeft",JSOHOSEditBox::setLeft);
JSP_ADD_METHOD("setTop",JSOHOSEditBox::setTop);
JSP_ADD_METHOD("setWidth",JSOHOSEditBox::setWidth);
JSP_ADD_METHOD("setHeight",JSOHOSEditBox::setHeight);
JSP_ADD_METHOD("setOpacity",JSOHOSEditBox::setOpacity);
JSP_ADD_METHOD("setValue",JSOHOSEditBox::setValue);
JSP_ADD_METHOD("getValue",JSOHOSEditBox::getValue);
JSP_ADD_METHOD("setStyle",JSOHOSEditBox::setStyle);
JSP_ADD_METHOD("setVisible",JSOHOSEditBox::setVisible);
JSP_ADD_METHOD("focus",JSOHOSEditBox::focus);
JSP_ADD_METHOD("blur",JSOHOSEditBox::blur);
JSP_ADD_METHOD("setColor",JSOHOSEditBox::setColor);
JSP_ADD_METHOD("setFontSize",JSOHOSEditBox::setFontSize);
JSP_ADD_METHOD("setPos",JSOHOSEditBox::setPos);
JSP_ADD_METHOD("setSize",JSOHOSEditBox::setSize);
JSP_ADD_METHOD("setCursorPosition",JSOHOSEditBox::setCursorPosition);
JSP_ADD_METHOD("setScale",JSOHOSEditBox::setScale);
JSP_ADD_METHOD("setMaxLength",JSOHOSEditBox::setMaxLength);
JSP_ADD_METHOD("setType",JSOHOSEditBox::setType);
JSP_ADD_METHOD("setNumberOnly",JSOHOSEditBox::setNumberOnly);
JSP_ADD_METHOD("setRegular",JSOHOSEditBox::setRegular);
JSP_ADD_METHOD("setFont",JSOHOSEditBox::setFont);
JSP_ADD_METHOD("setMultiAble",JSOHOSEditBox::setMultiAble);
JSP_ADD_METHOD("setForbidEdit",JSOHOSEditBox::setForbidEdit);
JSP_ADD_METHOD("getForbidEdit",JSOHOSEditBox::getForbidEdit);
JSP_INSTALL_CLASS("ConchInput",JSOHOSEditBox);
}
}
@@ -0,0 +1,94 @@
#ifndef __JSOHOSEditBox_H__
#define __JSOHOSEditBox_H__
#include <stdio.h>
#include <string>
#include "../JSInterface/JSInterface.h"
namespace laya{
//the same value with the openharmony TextInputType
enum EditBoxType{
NORMAL=0,
PASSWORD,
NUMBER,
NUMBER_PASSWORD,
};
class JSOHOSEditBox:public JsObjBase, public JSObjNode{
public:
static JsObjClassInfo JSCLSINFO;
void JSConstructor(JsFuncArgs& args){};
static void exportJS();
JSOHOSEditBox();
~JSOHOSEditBox();
public:
int set_Left(int p_nLeft);
int get_Left();
int set_Top(int p_nTop);
int get_Top();
int set_Width(int p_nWidth);
int get_Width();
int set_Height(int p_nHeight);
int get_Height();
float set_Opacity(float p_Opacity);
float get_Opacity();
const char* set_Value(const char* p_sValue);
const char* get_Value();
void set_Style(const char* p_sStyle);
const char* get_Style();
bool set_Visible(bool p_bVisible);
bool get_Visible();
public:
void setColor(const char* p_sColor);
void setFontSize(int p_nFontSize);
void setPos(int x,int y);
void setSize(int w,int h);
void setCursorPosition(int pos);
void setLeft(int p_nLeft);
void setTop(int p_nTop);
void setWidth(int p_nWidth);
void setHeight(int p_nHeight);
void setOpacity(float p_Opacity);
void setValue(const char* p_sValue);
const char* getValue();
void setStyle(const char* p_sStyle);
void setVisible(bool p_bVisible);
void setFont(const char* p_sFont);
void focus();
void blur();
void setForbidEdit(bool bForbidEdit);
bool getForbidEdit();
public:
void setScale(float p_nSx, float p_nSy);
void setMaxLength(int p_nMaxLength);
void setType(const char* p_sType);
void setRegular(const char* p_sRegular);
void setNumberOnly(bool p_bNumberOnly);
void addEventListener(const char* p_sName, JSValueAsParam p_pFunction);
void setMultiAble(bool p_bMultiAble);
void onInputCallJSFunction(std::weak_ptr<int> callbackref);
void onInput();
public:
int m_nLeft;
int m_nTop;
int m_nWidth;
int m_nHeight;
bool m_bVisible;
float m_fOpacity;
int m_nMaxLength;
int m_nFontSize;
float m_nScaleX;
float m_nScaleY;
std::string m_sType;
std::string m_sStyle;
std::string m_sValue;
std::string m_sRegular;
bool m_bForbidEdit;
private:
int m_tag;
std::shared_ptr<int> m_CallbackRef;
JsObjHandle m_pJSFunctionOnInput;//JS的回调
};
}
#endif //__JSOHOSEditBox_H__
@@ -19,6 +19,11 @@
#ifdef ANDROID
#include "../../CToJavaBridge.h"
#endif
#ifdef OHOS
#include "aki/jsbind.h"
#include "napi/NAPIFun.h"
#include "helper/NapiHelper.h"
#endif
#include "../../JCSystemConfig.h"
#include "JSInput.h"
#include "JSConchConfig.h"
@@ -160,6 +165,8 @@ namespace laya
CToJavaBridge::GetInstance()->callMethod(CToJavaBridge::JavaClass.c_str(), "captureScreen", kRet);
#elif __APPLE__
CToObjectCCaptureScreen();
#elif OHOS
NAPIFun::m_bTakeScreenshot = true;
#endif
}
const char* JSRuntime::getCachePath()
@@ -209,6 +216,8 @@ namespace laya
#elif ANDROID
CToJavaBridge::JavaRet kRet;
CToJavaBridge::GetInstance()->callMethod(CToJavaBridge::JavaClass.c_str(), "setScreenWakeLock", p_bWakeLock, kRet);
#elif OHOS
NapiHelper::GetInstance()->setKeepScreenOn(p_bWakeLock);
#elif WIN32
#endif
@@ -220,6 +229,14 @@ namespace laya
#elif ANDROID
CToJavaBridge::JavaRet kRet;
CToJavaBridge::GetInstance()->callMethod(CToJavaBridge::JavaClass.c_str(), "setSensorAble", p_bSensorAble, kRet);
#elif OHOS
if(p_bSensorAble) {
NapiHelper::GetInstance()->enableAccelerometer();
NapiHelper::GetInstance()->enableOrientation();
} else {
NapiHelper::GetInstance()->disableAccelerometer();
NapiHelper::GetInstance()->disableOrientation();
}
#elif WIN32
#endif
@@ -318,7 +335,10 @@ namespace laya
CToJavaBridge::JavaRet ret;
CToJavaBridge::GetInstance()->callMethod(CToJavaBridge::JavaClass.c_str(), "setExternalLink", sUrl,x,y,w,h, bCloseWebview?1:0,ret);
#elif __APPLE__
CToObjectCSetExternalLink( sUrl,x,y,w,h, bCloseWebview);
#elif OHOS
if(auto setExternalLink = aki::JSBind::GetJSFunction("WebUtils.createWebview")) {
setExternalLink->Invoke<void>(sUrl,x,y,w,h, bCloseWebview?1:0);
}
#elif WIN32
#endif
@@ -329,7 +349,11 @@ namespace laya
CToJavaBridge::JavaRet ret;
CToJavaBridge::GetInstance()->callMethod(CToJavaBridge::JavaClass.c_str(), "setExternalLink", sUrl, 0, 0, 0, 0,1,ret);
#elif __APPLE__
CToObjectCSetExternalLink(sUrl, 0, 0, 0, 0, true);
//CToObjectCSetExternalLink(sUrl, 0, 0, 0, 0, true);
#elif OHOS
if(auto setExternalLink = aki::JSBind::GetJSFunction("WebUtils.createWebview")) {
setExternalLink->Invoke<void>(sUrl,0, 0, 0, 0, 1);
}
#elif WIN32
#endif
@@ -340,7 +364,11 @@ namespace laya
CToJavaBridge::JavaRet ret;
CToJavaBridge::GetInstance()->callMethod(CToJavaBridge::JavaClass.c_str(), "closeExternalLink", ret);
#elif __APPLE__
CToObjectCCloseExternalLink();
//CToObjectCCloseExternalLink();
#elif OHOS
if(auto closeWebview = aki::JSBind::GetJSFunction("WebUtils.closeWebview")) {
closeWebview->Invoke<void>();
}
#elif WIN32
#endif
@@ -352,7 +380,10 @@ namespace laya
CToJavaBridge::JavaRet ret;
CToJavaBridge::GetInstance()->callMethod(CToJavaBridge::JavaClass.c_str(), "callWebViewJS", sFunctionName, sJsonParam, sCallbackFunction, ret);
#elif __APPLE__
CToObjectCCallWebviewJS(sFunctionName, sJsonParam, sCallbackFunction);
#elif OHOS
if(auto callWebViewJS = aki::JSBind::GetJSFunction("WebUtils.callWebViewJS")) {
callWebViewJS->Invoke<void>(sFunctionName, sJsonParam, sCallbackFunction);
}
#elif WIN32
#endif
@@ -363,7 +394,10 @@ namespace laya
CToJavaBridge::JavaRet ret;
CToJavaBridge::GetInstance()->callMethod(CToJavaBridge::JavaClass.c_str(), "hideExternalLink", ret);
#elif __APPLE__
CToObjectCHideWebView();
#elif OHOS
if(auto hideWebview = aki::JSBind::GetJSFunction("WebUtils.hideWebview")) {
hideWebview->Invoke<void>();
}
#elif WIN32
#endif
@@ -374,7 +408,10 @@ namespace laya
CToJavaBridge::JavaRet ret;
CToJavaBridge::GetInstance()->callMethod(CToJavaBridge::JavaClass.c_str(), "showExternalLink", ret);
#elif __APPLE__
CToObjectCShowWebView();
#elif OHOS
if(auto showWebView = aki::JSBind::GetJSFunction("WebUtils.showWebView")) {
showWebView->Invoke<void>();
}
#elif WIN32
#endif
@@ -384,6 +421,8 @@ namespace laya
#ifdef ANDROID
CToJavaBridge::JavaRet ret;
CToJavaBridge::GetInstance()->callMethod(CToJavaBridge::JavaClass.c_str(), "exit", ret);
#elif OHOS
NapiHelper::GetInstance()->exitGame();
#elif __APPLE__
#elif WIN32
#endif
@@ -401,6 +440,17 @@ namespace laya
{
return m_pScrpitRuntime->m_pJSOnUnhandledRejectionFunction.getJsObj();
}
#if OHOS
std::string JSRuntime::postMessage(const char* eventName, const char* data){
std::string result = NapiHelper::GetInstance()->postMessageToUIThread(eventName,data);
return result;
}
std::string JSRuntime::postSyncMessage(const char* eventName, const char* data){
std::string result = NapiHelper::GetInstance()->postSyncMessageToUIThread(eventName,data);
return result;
}
#endif
void JSRuntime::exportJS()
{
JSP_GLOBAL_CLASS("conch", JSRuntime, this);
@@ -441,6 +491,10 @@ namespace laya
JSP_GLOBAL_ADD_PROPERTY(onunhandledrejection, JSRuntime, getOnUnhandledRejection, setOnUnhandledRejection);
//JSP_GLOBAL_ADD_METHOD("updateArrayBufferRef", JSRuntime::updateArrayBufferRef);
JSP_GLOBAL_ADD_METHOD("exit", JSRuntime::exit);
#ifdef OHOS
JSP_GLOBAL_ADD_METHOD("postMessage", JSRuntime::postMessage);
JSP_GLOBAL_ADD_METHOD("postSyncMessage", JSRuntime::postSyncMessage);
#endif
JSP_INSTALL_GLOBAL_CLASS("conch", JSRuntime, this );
}
}
@@ -111,8 +111,9 @@ namespace laya
void exit();
//bool updateArrayBufferRef(int nID, bool bSyncToRender, JSValueAsParam pArrayBuffer);
std::string postMessage(const char* eventName, const char* data);
std::string postSyncMessage(const char* eventName, const char* data);
public:
JCScriptRuntime* m_pScrpitRuntime;
@@ -21,7 +21,10 @@
#ifdef ANDROID
#include "../../JCSystemConfig.h"
#include "../../CToJavaBridge.h"
#endif
#endif
#ifdef OHOS
#include "../../JCSystemConfig.h"
#endif
namespace laya
{
@@ -30,6 +30,10 @@ namespace laya
static JsObjClassInfo JSCLSINFO;
static void exportJS();
static void executeVideoCallback(int index, int event);
static void executeLoadedmetadata(int index, const char* evtName);
static void executeDurationBack(int index, int duration);
static void executeCurrentTimeBack(int index, int currentTime);
JSVideo();
~JSVideo();
@@ -93,6 +97,7 @@ namespace laya
void DispatchEvtToJS(const std::string path);
private:
int m_tag;
static int ms_handleIdx;
static std::set<std::string> ms_supportFormat;
@@ -0,0 +1,158 @@
#ifdef OHOS
#include "JSVideo.h"
#include "aki/jsbind.h"
#include "util/Log.h"
#include "helper/NapiHelper.h"
namespace laya
{
static int curIndex = 0;
static std::unordered_map<int, JSVideo *> s_allVideoPlayers;
static bool _isLooping = false;
static bool _isAutoplay = false;
static bool _isPause = false;
static double valX = 0;
static double valY = 0;
static double valW = 0;
static double valH = 0;
static int readyState= 0;
static int _duration= 0;
static int _currentTime= 0;
std::set<std::string> JSVideo::ms_supportFormat = {
"video/mp4",
"video/ogg",
};
JSVideo::JSVideo(){
Init();
//增加索引
m_tag = curIndex;
curIndex++;
s_allVideoPlayers[m_tag] = this;
AdjustAmountOfExternalAllocatedMemory(sizeof(JSVideo));
JCMemorySurvey::GetInstance()->newClass("JSVideo",sizeof(JSVideo),this);
NapiHelper::GetInstance()->createVideoPlayer(m_tag);
}
JSVideo::~JSVideo(){
Dispose();
JCMemorySurvey::GetInstance()->releaseClass("JSVideo",this);
NapiHelper::GetInstance()->removeVideoPlayer(m_tag);
auto iter = s_allVideoPlayers.find(m_tag);
if(iter != s_allVideoPlayers.end()){
s_allVideoPlayers.erase(iter);
}
}
void JSVideo::_releaseHandler(){
}
void JSVideo::LoadInternal(const std::string& path){
int isurl =1;
NapiHelper::GetInstance()->setURL(m_tag,path,isurl);
}
void JSVideo::Play(){
_isPause = false;
NapiHelper::GetInstance()->play(m_tag);
}
void JSVideo::Pause(){
_isPause = true;
m_isDownloadWaitPlay = false;
NapiHelper::GetInstance()->pause(m_tag);
}
void JSVideo::Stop(){
NapiHelper::GetInstance()->stop(m_tag);
}
bool JSVideo::GetPaused(){
return _isPause;
}
bool JSVideo::GetLoop(){
return _isLooping;
}
void JSVideo::SetLoop(bool value){
_isLooping = value;
NapiHelper::GetInstance()->setLooping(m_tag,value);
}
void JSVideo::SetAutoplay(bool value){
_isAutoplay = value;
NapiHelper::GetInstance()->setAutoplay(m_tag,value);
}
bool JSVideo::GetAutoplay(){
return _isAutoplay;
}
void JSVideo::SetX(double value){
valX = value;
NapiHelper::GetInstance()->setX(m_tag,value);
}
double JSVideo::GetX(){
return valX;
}
void JSVideo::SetY(double value){
valY = value;
NapiHelper::GetInstance()->setY(m_tag,value);
}
double JSVideo::GetY(){
return valY;
}
double JSVideo::GetVideoWidth(){
auto iter = s_allVideoPlayers.find(m_tag);
if(iter != s_allVideoPlayers.end()){
return s_allVideoPlayers[m_tag]->GetWidth();
}
return 0;
}
double JSVideo::GetVideoHeight(){
auto iter = s_allVideoPlayers.find(m_tag);
if(iter != s_allVideoPlayers.end()){
return s_allVideoPlayers[m_tag]->GetHeight();
}
return 0;
}
double JSVideo::GetWidth(){
return valW;
}
void JSVideo::SetWidth(double value){
valW = value;
NapiHelper::GetInstance()->setWidth(m_tag,value);
}
double JSVideo::GetHeight(){
return valH;
}
void JSVideo::SetHeight(double value){
valH = value;
NapiHelper::GetInstance()->setHeight(m_tag,value);
}
double JSVideo::GetCurrentTime(){
return (double)(_currentTime*0.001);
}
void JSVideo::SetCurrentTime(double value){
NapiHelper::GetInstance()->setVideoCurrentTime(m_tag,value);
}
double JSVideo::GetDuration(){
return (double)(_duration * 0.001);
}
double JSVideo::GetVolume(){
int ret = NapiHelper::GetInstance()->getVolume(m_tag);
return (double)ret;
}
void JSVideo::SetVolume(double value){
NapiHelper::GetInstance()->setVolume(m_tag,value);
}
int32_t JSVideo::GetReadyState(){
return readyState;
}
void JSVideo::executeVideoCallback(int index,int event){
readyState = event;
}
void JSVideo::executeLoadedmetadata(int index,const char* evtName){
auto iter = s_allVideoPlayers.find(index);
if(iter != s_allVideoPlayers.end()){
s_allVideoPlayers[index]->CallHandle(evtName);
}
}
void JSVideo::executeDurationBack(int index, int duration){
_duration = duration;
}
void JSVideo::executeCurrentTimeBack(int index, int currentTime){
_currentTime = currentTime;
}
}
#endif //OHOS
+16 -14
View File
@@ -23,6 +23,8 @@
#include <downloadCache/JCAndroidFileSource.h>
#elif __APPLE_
#include <downloadCache/JCIosFileSource.h>
#elif OHOS
#include <downloadCache/JCOHOSFileSource.h>
#endif
#include "util/Log.h"
#ifdef WIN32
@@ -98,7 +100,7 @@ public:
void *user, void *in, size_t len)
{
if (reason == LWS_CALLBACK_GET_THREAD_ID) {
//这个也不知道有什么用,就随便返回一个值吧
//Ҳ֪ʲôãһֵ
auto id = std::this_thread::get_id();
std::hash<std::thread::id> sh;
return sh(id);
@@ -152,8 +154,8 @@ void WsThreadHelper::quitSubThread()
void WsThreadHelper::wsThreadEntryFunc()
{
m_pWebSocket->onSubThreadStarted();
//先等个500毫秒再调用 libwebsocket_service
//否则再第二次调用connect的时候会出错(可能是win64ws2的异步连接的问题?)
//ȵȸ500ٵ libwebsocket_service
//ٵڶεconnectʱwin64ws2ӵ
#ifdef WIN32
std::this_thread::sleep_for(std::chrono::milliseconds(500));
#endif
@@ -280,8 +282,8 @@ bool WebSocket::init(const Delegate& delegate,
char* name = new char[20];
strcpy(name, "default-protocol");
m_wsProtocols[0].name = name;
m_wsProtocols[0].rx_buffer_size = RX_BUFFER_SIZE; //如果这里不设,则在android下当发送的数据很多的时候,会导致发送失败(返回0)
//猎刃有时候打不到怪就是因为这个(抓包看到的是发送的为原始内容,同普通socket不知道为什么,可能无关?)
m_wsProtocols[0].rx_buffer_size = RX_BUFFER_SIZE; //androidµ͵ݺܶʱ򣬻ᵼ·ʧܣ0
//ʱ򲻵־ΪץǷ͵Ϊԭʼݣͬͨsocket֪Ϊʲô޹أ
m_wsProtocols[0].callback = WebSocketCallbackWrapper::onSocketCallback;
}
@@ -334,8 +336,8 @@ void WebSocket::close()
}
LOGI("websocket connection closed by client");
//TODO 这里其实不应该设置. 原来是靠这个来关掉ws,但是实际上
//这个变量很容易被ws线程修改,导致下面join的时候卡死。
//TODO ʵӦ. ԭǿصwsʵ
//ױws߳޸ģjoinʱ
m_readyState = State::CLOSED;
m_bWantClose = true;
@@ -505,14 +507,14 @@ int WebSocket::onSocketCallback(
toWriteSize,
static_cast<lws_write_protocol>(writeProtocol));
/*if (bytesWrite == 0) {
//暂时无法发送,等会儿再试
//ʱ޷ͣȻ
break;
}
if (bytesWrite == 0) {
break;
}*/
if (bytesWrite < 0) {
//发生错误了。
//ˡ
LOGE("WebSocket::onSocketCallback libwebsocket_write error! ");
LAYA_SAFE_DELETE_ARRAY(data->bytes);
LAYA_SAFE_DELETE(data);
@@ -575,11 +577,11 @@ int WebSocket::onSocketCallback(
case LWS_CALLBACK_CLIENT_RECEIVE:
{
//bool finalfrg = lws_is_final_fragment(wsi)!=0; 这个永远都是1
//bool finalfrg = lws_is_final_fragment(wsi)!=0; Զ1
const size_t remaining = lws_remaining_packet_payload(wsi);
if (in && len > 0){
if (remaining>0) {
//帧不完整
//֡
char* pData = new char[m_nCurDataLen + len];
if(m_nCurDataLen)
memcpy(pData, m_pLastData, m_nCurDataLen);
@@ -588,7 +590,7 @@ int WebSocket::onSocketCallback(
if (m_pLastData) {
delete [] m_pLastData;
if (m_bLastIsBin != lws_frame_is_binary(wsi)) {
LOGE("warn:difference frame type");
LOGE("warn:difference frame type");
}
}
m_pLastData = pData;
@@ -664,7 +666,7 @@ void WebSocket::onJSThreadReceiveMessage(WsMessage* msg)
{
/*
Data* data = (Data*)msg->obj;
m_delegate->onMessage(this, *data); //TODO 这个指针直接传给js,js来删除,能避免一次newmemcpy
m_delegate->onMessage(this, *data); //TODO ֱָӴjsjsɾܱһnewmemcpy
LAYA_SAFE_DELETE_ARRAY(data->bytes);
LAYA_SAFE_DELETE(data);
*/
@@ -729,7 +731,7 @@ lws_vhost* WebSocket::createVhost(struct lws_protocols* protocols, int& sslConne
{
if (isCAFileExist)
{
#ifdef ANDROID
#ifdef ANDROID || OHOS
// if ca file is in the apk, try to extract it to writable path
std::string writablePath = gRedistPath;
static std::string newCaFilePath = writablePath + caFileName;
+2 -2
View File
@@ -249,11 +249,11 @@ var setTimeout:(handler: any, timeout?: any/*, ...args: any[]*/)=>number=window.
//onload
Object.defineProperty(window,'runtime',{get:function(){return true}});//给window.runtime赋值
window.postMessage=function(data,d) {
/*window.postMessage=function(data,d) {
if(typeof(data)=="object")
data=JSON.stringify(data);
conch.callWebviewJS( "window.__getMessemage",encodeURIComponent(data),"" );
}
}*/
window.postRuntimeMessage=function(d)
{
-18
View File
@@ -665,10 +665,7 @@ interface conch {
__onerror:Function;
onunhandledrejection:Function;
__onunhandledrejection:Function;
callWebviewJS(methodName:string,parms:string,callbackMethodName:string);
exp:any;
showWebView();
hideWebView();
captureScreen(cb:(ab:ArrayBuffer,w:number,h:number)=>void):void;
saveAsPng(ab:ArrayBuffer,w:number,h:number,file:string);
loadingAuto:boolean;
@@ -705,21 +702,6 @@ interface conch {
showLoadingView(b: boolean): void;
showWaiting(b: boolean): void;
showAssistantTouch(b: boolean): void;
/**
* webview
*/
setExternalLink(url: string): void;
/**
* webview
* @param url {string} url地址
* @param posx {number} weview的左上角位置
* @param posy {number} webivew的左上角位置
* @param width {number} webview的宽度
* @param height {number} webview的高度
* @param canclose {boolean} webview是否可以被关掉
*/
setExternalLinkEx(url:string,posx:number, posy:number,width:number,height:number,canclose:boolean):void;
closeExternalLink(): void;
setScreenWakeLock(b: boolean): void;
setUrlToLower(b: boolean): void;
setFontFace(family: string, src: string, type: string): void;
+3 -3
View File
@@ -1278,7 +1278,7 @@ class GLCommandEncoder
if (version.indexOf("OpenGL ES 3.") != -1)
{
//result.push("WEBGL_draw_buffers");
if (conchConfig.getOS() == "Conch-android")
if (conchConfig.getOS() == "Conch-android" || conchConfig.getOS() == "Conch-ohos")
{
result.push("WEBGL_compressed_texture_etc");
}
@@ -1437,7 +1437,7 @@ class GLCommandEncoder
return {UNSIGNED_INT_24_8_WEBGL:34042};
}
//>=3.1
else if (name.indexOf('WEBGL_compressed_texture_astc') != -1 && (extention.indexOf('GL_OES_texture_compression_astc') != -1 || extention.indexOf('GL_KHR_texture_compression_astc') != -1 || (conchConfig.getOS() == "Conch-android" && version.indexOf("OpenGL ES 3.") != -1 && version.indexOf("OpenGL ES 3.0") == -1)))
else if (name.indexOf('WEBGL_compressed_texture_astc') != -1 && (extention.indexOf('GL_OES_texture_compression_astc') != -1 || extention.indexOf('GL_KHR_texture_compression_astc') != -1 || ((conchConfig.getOS() == "Conch-android" || conchConfig.getOS() == "Conch-ohos") && version.indexOf("OpenGL ES 3.") != -1 && version.indexOf("OpenGL ES 3.0") == -1)))
{
return {
COMPRESSED_RGBA_ASTC_4x4_KHR : 0x93B0,
@@ -1470,7 +1470,7 @@ class GLCommandEncoder
COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : 0x93DD,
};
}
else if (name.indexOf('WEBGL_compressed_texture_etc') != -1 && conchConfig.getOS() == "Conch-android" && version.indexOf("OpenGL ES 3.") != -1 )
else if (name.indexOf('WEBGL_compressed_texture_etc') != -1 && (conchConfig.getOS() == "Conch-android" || conchConfig.getOS() == "Conch-ohos") && version.indexOf("OpenGL ES 3.") != -1 )
{
return {
COMPRESSED_R11_EAC : 0x9270,
+255
View File
@@ -0,0 +1,255 @@
#include "./NAPIFun.h"
using namespace laya;
NAPIFun NAPIFun::fun_;
bool NAPIFun::m_bTakeScreenshot = false;
void NAPIFun::postCmdToMainThread(int p_nCmd, int p_nParam1, int p_nParam2)
{
}
void NAPIFun::ConchNAPI_configSetParamExt(std::string p_strParamExt)
{
g_kSystemConfig.m_jsonparamExt = p_strParamExt;
}
void NAPIFun::ConchNAPI_configSetURL(std::string p_strUrl)
{
g_kSystemConfig.m_strStartURL = p_strUrl;
}
void NAPIFun::ConchNAPI_configSetIsPlug(bool p_bIsPlug)
{
JCSystemConfig::s_bIsPlug = p_bIsPlug;
}
void NAPIFun::ConchNAPI_InitDLib(napi_value assetManager, int nThreadNum, std::string p_strAssetRootPath, std::string p_strCachePath, int threadMode, int debugMode, int debugPort)
{
auto fun = NAPIFun::GetInstance();
LOGI("NAPI InitDLib");
if (fun->g_pConch)
{
LOGI("NAPI has an old conch object! delete it");
// 如果上次不正常退出,如果时间太短,可能有的线程还在创建过程中。所以等待一会儿。
// 例如g_pConch突然为null,可能有人还在用。
std::this_thread::sleep_for(std::chrono::milliseconds(500));
// 必须走完整流程,例如有的线程还在创建,完了后就正常跑,然后这里g_pConch又被删了
NAPIFun::ConchNAPI_ReleaseDLib();
LOGI("NAPI del old end");
}
// 这个不要放到开始,以影响面上面的异常处理
fun->g_nInitTime = tmGetCurms();
gRedistPath = p_strCachePath;
gRedistPath += "/";
gAssetRootPath = p_strAssetRootPath;
napi_env env = aki::JSBind::GetScopedEnv();
g_pAssetManager = OH_ResourceManager_InitNativeResourceManager(env, assetManager);
laya::JCOHOSFileSource *pAssets = new laya::JCOHOSFileSource();
pAssets->Init(g_pAssetManager, "");
JCConch::s_pAssetsFiles = pAssets;
THREAD_MODE nMode = (THREAD_MODE)(threadMode);
if (nMode == THREAD_MODE_SINGLE)
{
g_kSystemConfig.m_nThreadMODE = nMode;
LOGI(">>>>>>Thread Mode = single");
}
else if (nMode == THREAD_MODE_DOUBLE)
{
g_kSystemConfig.m_nThreadMODE = nMode;
LOGI(">>>>>>Thread Mode = double");
}
else
{
LOGI(">>>>>>Thread Mode = %d", g_kSystemConfig.m_nThreadMODE);
}
fun->g_pConch = new laya::JCConch(nThreadNum, (laya::JS_DEBUG_MODE)debugMode, debugPort);
fun->g_pConch->m_funcPostMsgToMainThread = std::bind(NAPIFun::postCmdToMainThread, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
}
void NAPIFun::ConchNAPI_SetLocalStoragePath(std::string p_strLocalStorage)
{
LOGI("NAPI localStoragePath=%{public}s", p_strLocalStorage.c_str());
}
void NAPIFun::ConchNAPI_ReleaseDLib()
{
LOGI("NAPI del engine");
JCAudioManager::GetInstance()->stopMp3();
auto fun = NAPIFun::GetInstance();
if (fun->g_pConch)
{
if (tmGetCurms() - fun->g_nInitTime < 2000)
{
LOGI("NAPI exit need a little wait");
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
if (fun->g_bInBKGround)
{
LOGI("NAPI App in background!");
JCConch::s_pConchRender->willExit();
}
fun->g_pConch->onAppDestory();
if (g_kSystemConfig.m_nThreadMODE == THREAD_MODE_SINGLE)
{
JCScriptRuntime::s_JSRT->stop();
}
delete fun->g_pConch;
fun->g_pConch = NULL;
}
fun->g_bEngineInited = false;
}
void NAPIFun::ConchNAPI_OnAppDestroy()
{
}
void NAPIFun::ConchNAPI_OnAppPause()
{
LOGI("NAPI OnAppPause");
auto fun = NAPIFun::GetInstance();
fun->g_bInBKGround = true;
if (laya::JCAudioManager::GetInstance()->getMp3Mute() == false && laya::JCAudioManager::GetInstance()->getMp3Stopped() == false)
{
JCAudioManager::GetInstance()->pauseMp3();
}
laya::JCAudioManager::GetInstance()->m_pWavPlayer->pause();
}
void NAPIFun::ConchNAPI_OnAppResume()
{
LOGI("NAPI OnAppResume");
auto fun = NAPIFun::GetInstance();
if (!fun->g_pConch)
return;
fun->g_bInBKGround = false;
// 继续声音
if (laya::JCAudioManager::GetInstance()->getMp3Mute() == false && laya::JCAudioManager::GetInstance()->getMp3Stopped() == false)
{
laya::JCAudioManager::GetInstance()->resumeMp3();
}
laya::JCAudioManager::GetInstance()->m_pWavPlayer->resume();
}
void NAPIFun::ConchNAPI_OnGLReady(int width, int height)
{
LOGI("NAPI onGLReady tid=%ld", gettidv1());
auto pRender = JCConch::s_pConchRender;
if (g_nInnerWidth != width || g_nInnerHeight != height)
{
LOGI("NAPI surface innersize changed : g_nInnerWidth=%d,g_nInnerHeight=%d", width, height);
g_nInnerWidth = width;
g_nInnerHeight = height;
g_bGLCanvasSizeChanged = true;
}
LOGI("NAPI init dev w=%d,h=%d", width, height);
pRender->onGLReady();
}
void NAPIFun::ConchNAPI_OnAppStart()
{
auto fun = NAPIFun::GetInstance();
if (fun->g_bEngineInited)
{
return;
}
fun->g_kReadyLock.lock();
// 启动js线程
fun->g_pConch->onAppStart();
fun->g_bEngineInited = true;
if (g_kSystemConfig.m_nThreadMODE == THREAD_MODE_SINGLE)
{
JCScriptRuntime::s_JSRT->start(JCConch::s_pConch->m_strStartJS.c_str());
}
fun->g_kReadyLock.unlock();
}
void NAPIFun::ConchNAPI_onDrawFrame()
{
auto pRender = JCConch::s_pConchRender;
if (pRender)
{
pRender->renderFrame(0, false);
}
}
void NAPIFun::ConchNAPI_onVSyncCallback(long VSynctm)
{
double vsynctm = VSynctm / 1e6;
if (JCScriptRuntime::s_JSRT)
{
JCScriptRuntime::s_JSRT->onVSyncEvent(vsynctm);
}
}
void NAPIFun::ConchNAPI_audioMusicPlayEnd()
{
laya::JCMp3Interface *pMp3Player = laya::JCAudioManager::GetInstance()->m_pMp3Player;
if (pMp3Player)
{
pMp3Player->onPlayEnd();
}
}
void NAPIFun::ConchNAPI_networkChanged(int nNetworkType)
{
JCScriptRuntime::s_JSRT->onNetworkChanged(nNetworkType);
}
void NAPIFun::ConchNAPI_inputChange(int keycode)
{
if (JCScriptRuntime::s_JSRT->m_pCurEditBox)
{
JCScriptRuntime::s_JSRT->m_pCurEditBox->onInput();
}
}
void NAPIFun::ConchNAPI_setLocalizable(bool p_bIsLocalPackage)
{
JCSystemConfig::s_bLocalizable = p_bIsLocalPackage;
LOGI("setLocalizable%d", p_bIsLocalPackage);
}
void NAPIFun::ConchNAPI_captureScreenCallBack(int w, int h, std::string byteArray)
{
}
void NAPIFun::ConchNAPI_handleDeviceMotionEvent(float ax, float ay, float az, float agx, float agy, float agz, float ra, float rb, float rg, float interval)
{
DeviceMotionEvent e;
e.nType = E_DEVICEMOTION;
e.ax = ax;
e.ay = ay;
e.az = az;
e.agx = agx;
e.agy = agy;
e.agz = agz;
e.ra = ra;
e.rb = rb;
e.rg = rg;
e.interval = interval;
strncpy(e.type, "devicemotion", 256);
JCScriptRuntime::s_JSRT->dispatchInputEvent(e);
}
void NAPIFun::ConchNAPI_handleDeviceOrientationEvent(float ra, float rb, float rg)
{
DeviceOrientationEvent e;
e.nType = E_DEVICEORIENTATION;
e.ra = ra;
e.rb = rb;
e.rg = rg;
strncpy(e.type, "deviceorientation", 256);
JCScriptRuntime::s_JSRT->dispatchInputEvent(e);
}
JSBIND_GLOBAL()
{
JSBIND_FUNCTION(NAPIFun::ConchNAPI_configSetParamExt, "ConchNAPI_configSetParamExt");
JSBIND_FUNCTION(NAPIFun::ConchNAPI_configSetURL, "ConchNAPI_configSetURL");
JSBIND_FUNCTION(NAPIFun::ConchNAPI_configSetIsPlug, "ConchNAPI_configSetIsPlug");
JSBIND_FUNCTION(NAPIFun::ConchNAPI_InitDLib, "ConchNAPI_InitDLib");
JSBIND_FUNCTION(NAPIFun::ConchNAPI_SetLocalStoragePath, "ConchNAPI_SetLocalStoragePath");
JSBIND_FUNCTION(NAPIFun::ConchNAPI_ReleaseDLib, "ConchNAPI_ReleaseDLib");
JSBIND_FUNCTION(NAPIFun::ConchNAPI_OnAppDestroy, "ConchNAPI_OnAppDestroy");
JSBIND_FUNCTION(NAPIFun::ConchNAPI_OnAppPause, "ConchNAPI_OnAppPause");
JSBIND_FUNCTION(NAPIFun::ConchNAPI_OnAppResume, "ConchNAPI_OnAppResume");
JSBIND_FUNCTION(NAPIFun::ConchNAPI_OnGLReady, "ConchNAPI_OnGLReady");
JSBIND_FUNCTION(NAPIFun::ConchNAPI_OnAppStart, "ConchNAPI_OnAppStart");
JSBIND_FUNCTION(NAPIFun::ConchNAPI_onDrawFrame, "ConchNAPI_onDrawFrame");
JSBIND_FUNCTION(NAPIFun::ConchNAPI_onVSyncCallback, "ConchNAPI_onVSyncCallback");
JSBIND_FUNCTION(NAPIFun::ConchNAPI_audioMusicPlayEnd, "ConchNAPI_audioMusicPlayEnd");
JSBIND_FUNCTION(NAPIFun::ConchNAPI_networkChanged, "ConchNAPI_networkChanged");
JSBIND_FUNCTION(NAPIFun::ConchNAPI_inputChange, "ConchNAPI_inputChange");
JSBIND_FUNCTION(NAPIFun::ConchNAPI_setLocalizable, "ConchNAPI_setLocalizable");
JSBIND_FUNCTION(NAPIFun::ConchNAPI_captureScreenCallBack, "ConchNAPI_captureScreenCallBack");
JSBIND_FUNCTION(NAPIFun::ConchNAPI_handleDeviceMotionEvent, "ConchNAPI_handleDeviceMotionEvent");
JSBIND_FUNCTION(NAPIFun::ConchNAPI_handleDeviceOrientationEvent, "ConchNAPI_handleDeviceOrientationEvent");
}
+72
View File
@@ -0,0 +1,72 @@
#ifndef _NAPIFUN_
#define _NAPIFUN_
#include "../conch/JCConch.h"
#include "../conch/Audio/JCAudioManager.h"
#include "util/Log.h"
#include "aki/jsbind.h"
#include "../conch/JCSystemConfig.h"
#include "../common/util/JCZipFile.h"
#include "../conch/JCScriptRuntime.h"
#include <rawfile/raw_file_manager.h>
#include "napi/plugin_manager.h"
#include "downloadCache/JCOHOSFileSource.h"
#include "../common/misc/JCLayaThreadPool.h"
using namespace laya;
extern int g_nInnerWidth;
extern int g_nInnerHeight;
extern bool g_bGLCanvasSizeChanged;
extern std::string gRedistPath;
extern NativeResourceManager *g_pAssetManager;
extern std::string gAssetRootPath;
class NAPIFun
{
public:
~NAPIFun() {}
static NAPIFun *GetInstance()
{
return &NAPIFun::fun_;
}
static void postCmdToMainThread(int p_nCmd, int p_nParam1,int p_nParam2);
static void ConchNAPI_configSetParamExt(std::string p_strParamExt);
static void ConchNAPI_configSetURL(std::string p_strUrl);
static void ConchNAPI_configSetIsPlug(bool p_bIsPlug);
static void ConchNAPI_InitDLib(napi_value assetManager,int nThreadNum,std::string p_strAssetRootPath,std::string p_strCachePath,int threadMode, int debugMode, int debugPort);
static void ConchNAPI_SetLocalStoragePath(std::string p_strLocalStorage);
static void ConchNAPI_ReleaseDLib();
static void ConchNAPI_OnAppDestroy();
static void ConchNAPI_OnAppPause();
static void ConchNAPI_OnAppResume();
static void ConchNAPI_OnGLReady(int width,int height);
static void ConchNAPI_OnAppStart();
static void ConchNAPI_onDrawFrame();
static void ConchNAPI_onVSyncCallback(long VSynctm);
static void ConchNAPI_audioMusicPlayEnd();
static void ConchNAPI_networkChanged(int nNetworkType);
static void ConchNAPI_inputChange(int keycode);
static void ConchNAPI_setLocalizable(bool p_bIsLocalPackage);
static void ConchNAPI_captureScreenCallBack(int w,int h,std::string byteArray);
static void ConchNAPI_handleDeviceMotionEvent(float ax,float ay,float az,float agx,float agy,
float agz,float ra,float rb,float rg,float interval);
static void ConchNAPI_handleDeviceOrientationEvent(float ra,float rb,float rg);
private:
bool g_bEngineInited =false;
std::mutex g_kReadyLock;
laya::JCConch *g_pConch= NULL;
bool g_bInBKGround = false;
int64_t g_nInitTime = 0;
private:
static NAPIFun fun_;
public:
static bool m_bTakeScreenshot;
};
#endif
+36
View File
@@ -0,0 +1,36 @@
#ifndef __PLATFORMDEFINE_H__
#define __PLATFORMDEFINE_H__
#include <assert.h>
#include "util/Log.h"
#define CC_DLL
#define CC_NO_MESSAGE_PSEUDOASSERT(cond) \
if (!(cond)) \
{ \
LOGI("[laya assert] %s function:%s line:%d", __FILE__, __FUNCTION__, __LINE__); \
}
#define CC_MESSAGE_PSEUDOASSERT(cond, msg) \
if (!(cond)) \
{ \
LOGI("[laya assert] file:%s function:%s line:%d, %s", __FILE__, __FUNCTION__, __LINE__, msg); \
}
#define CC_ASSERT(cond) CC_NO_MESSAGE_PSEUDOASSERT(cond)
#define CC_UNUSED_PARAM(unusedparam) (void)unusedparam
/* Define NULL pointer value */
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif
#endif
#endif
+20
View File
@@ -0,0 +1,20 @@
#include "WorkerMessageQueue.h"
void WorkerMessageQueue::enqueue(const WorkerMessageData& data) {
std::lock_guard<std::mutex> lck(_mutex);
_queue.push(data);
}
bool WorkerMessageQueue::dequeue(WorkerMessageData *data) {
std::lock_guard<std::mutex> lck(_mutex);
if (empty()) {
return false;
}
*data = _queue.front();
_queue.pop();
return true;
}
bool WorkerMessageQueue::empty() const {
return _queue.empty();
}
+38
View File
@@ -0,0 +1,38 @@
#pragma once
#include <queue>
#include <thread>
#include <mutex>
#include <ace/xcomponent/native_interface_xcomponent.h>
enum class MessageType {
WM_XCOMPONENT_SURFACE_CREATED = 0,
WM_XCOMPONENT_TOUCH_EVENT,
WM_XCOMPONENT_SURFACE_CHANGED,
WM_XCOMPONENT_SURFACE_DESTROY,
WM_APP_SHOW,
WM_APP_HIDE,
WM_APP_DESTROY,
WM_VSYNC,
};
struct WorkerMessageData {
MessageType type;
void* data;
void* window;
OH_NativeXComponent_TouchEvent* touchEvent;
};
class WorkerMessageQueue final {
public:
void enqueue(const WorkerMessageData& data);
bool dequeue(WorkerMessageData *data);
bool empty() const;
size_t size() const {
return _queue.size();
}
private:
std::mutex _mutex;
std::queue<WorkerMessageData> _queue;
};
+83
View File
@@ -0,0 +1,83 @@
#ifndef _NATIVE_COMMON_H_
#define _NATIVE_COMMON_H_
#define NAPI_RETVAL_NOTHING
#define GET_AND_THROW_LAST_ERROR(env) \
do { \
const napi_extended_error_info* errorInfo = nullptr; \
napi_get_last_error_info((env), &errorInfo); \
bool isPending = false; \
napi_is_exception_pending((env), &isPending); \
if (!isPending && errorInfo != nullptr) { \
const char* errorMessage = \
errorInfo->error_message != nullptr ? errorInfo->error_message : "empty error message"; \
napi_throw_error((env), nullptr, errorMessage); \
} \
} while (0)
#define NAPI_ASSERT_BASE(env, assertion, message, retVal) \
do { \
if (!(assertion)) { \
napi_throw_error((env), nullptr, "assertion (" #assertion ") failed: " message); \
return retVal; \
} \
} while (0)
#define NAPI_ASSERT(env, assertion, message) NAPI_ASSERT_BASE(env, assertion, message, nullptr)
#define NAPI_ASSERT_RETURN_VOID(env, assertion, message) NAPI_ASSERT_BASE(env, assertion, message, NAPI_RETVAL_NOTHING)
#define NAPI_CALL_BASE(env, theCall, retVal) \
do { \
if ((theCall) != napi_ok) { \
GET_AND_THROW_LAST_ERROR((env)); \
return retVal; \
} \
} while (0)
#define NAPI_CALL(env, theCall) NAPI_CALL_BASE(env, theCall, nullptr)
#define NAPI_CALL_RETURN_VOID(env, theCall) NAPI_CALL_BASE(env, theCall, NAPI_RETVAL_NOTHING)
#define DECLARE_NAPI_PROPERTY(name, val) \
{ \
(name), nullptr, nullptr, nullptr, nullptr, val, napi_default, nullptr \
}
#define DECLARE_NAPI_STATIC_PROPERTY(name, val) \
{ \
(name), nullptr, nullptr, nullptr, nullptr, val, napi_static, nullptr \
}
#define DECLARE_NAPI_FUNCTION(name, func) \
{ \
(name), nullptr, (func), nullptr, nullptr, nullptr, napi_default, nullptr \
}
#define DECLARE_NAPI_FUNCTION_WITH_DATA(name, func, data) \
{ \
(name), nullptr, (func), nullptr, nullptr, nullptr, napi_default, data \
}
#define DECLARE_NAPI_STATIC_FUNCTION(name, func) \
{ \
(name), nullptr, (func), nullptr, nullptr, nullptr, napi_static, nullptr \
}
#define DECLARE_NAPI_GETTER(name, getter) \
{ \
(name), nullptr, nullptr, (getter), nullptr, nullptr, napi_default, nullptr \
}
#define DECLARE_NAPI_SETTER(name, setter) \
{ \
(name), nullptr, nullptr, nullptr, (setter), nullptr, napi_default, nullptr \
}
#define DECLARE_NAPI_GETTER_SETTER(name, getter, setter) \
{ \
(name), nullptr, nullptr, (getter), (setter), nullptr, napi_default, nullptr \
}
#endif /* _NATIVE_COMMON_H_ */
+571
View File
@@ -0,0 +1,571 @@
#include "NapiHelper.h"
#include "aki/jsbind.h"
using namespace laya;
NapiHelper NapiHelper::help_;
std::string NapiHelper::getDeviceInfo()
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__getDeviceInfo, this));
return deviceInfo;
}
std::string NapiHelper::__getDeviceInfo()
{
if (auto getDeviceInfo = aki::JSBind::GetJSFunction("DeviceUtils.getDeviceInfo"))
{
deviceInfo = getDeviceInfo->Invoke<std::string>();
}
return deviceInfo;
}
int NapiHelper::getNetworkType()
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__getNetworkType, this));
return networkType;
}
int NapiHelper::__getNetworkType()
{
if (auto getNetworkType = aki::JSBind::GetJSFunction("NetworkUtils.getNetworkType"))
{
networkType = getNetworkType->Invoke<int>();
}
return networkType;
}
void NapiHelper::playBackgroundMusic(const char *p_sUrl, int p_nTimes, float nCurrentTime)
{
JCConch::s_pConchRender->setInterruptFunc(
std::bind(&NapiHelper::__playBackgroundMusic, this, p_sUrl, p_nTimes, nCurrentTime));
}
void NapiHelper::__playBackgroundMusic(const char *p_sUrl, int p_nTimes, float nCurrentTime)
{
if (auto playBackgroundMusic = aki::JSBind::GetJSFunction("SoundUtils.playBackgroundMusic"))
{
playBackgroundMusic->Invoke<void>(p_sUrl, p_nTimes, (int)(nCurrentTime * 1000));
}
}
void NapiHelper::pauseBackgroundMusic()
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__pauseBackgroundMusic, this));
}
void NapiHelper::__pauseBackgroundMusic()
{
if (auto pauseBackgroundMusic = aki::JSBind::GetJSFunction("SoundUtils.pauseBackgroundMusic"))
{
pauseBackgroundMusic->Invoke<void>();
}
}
void NapiHelper::stopBackgroundMusic()
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__stopBackgroundMusic, this));
}
void NapiHelper::__stopBackgroundMusic()
{
if (auto stopBackgroundMusic = aki::JSBind::GetJSFunction("SoundUtils.stopBackgroundMusic"))
{
stopBackgroundMusic->Invoke<void>();
}
}
void NapiHelper::resumeBackgroundMusic()
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__resumeBackgroundMusic, this));
}
void NapiHelper::__resumeBackgroundMusic()
{
if (auto resumeBackgroundMusic = aki::JSBind::GetJSFunction("SoundUtils.resumeBackgroundMusic"))
{
resumeBackgroundMusic->Invoke<void>();
}
}
void NapiHelper::setBackgroundMusicVolume(float p_nVolume)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__setBackgroundMusicVolume, this, p_nVolume));
}
void NapiHelper::__setBackgroundMusicVolume(float p_nVolume)
{
if (auto setBackgroundMusicVolume = aki::JSBind::GetJSFunction("SoundUtils.setBackgroundMusicVolume"))
{
setBackgroundMusicVolume->Invoke<void>(p_nVolume);
}
}
void NapiHelper::setCurrentTime(double nCurrentTime)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__setCurrentTime, this, nCurrentTime));
}
void NapiHelper::__setCurrentTime(double nCurrentTime)
{
if (auto setCurrentTime = aki::JSBind::GetJSFunction("SoundUtils.setCurrentTime"))
{
setCurrentTime->Invoke<void>(nCurrentTime);
}
}
double NapiHelper::getCurrentTime()
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__getCurrentTime, this));
return currentTime;
}
double NapiHelper::__getCurrentTime()
{
currentTime = 0.0f;
if (auto getCurrentTime = aki::JSBind::GetJSFunction("SoundUtils.getCurrentTime"))
{
currentTime = getCurrentTime->Invoke<double>();
}
return currentTime;
}
double NapiHelper::getDuration()
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__getDuration, this));
return duration;
}
double NapiHelper::__getDuration()
{
duration = 0.0f;
if (auto getMp3Duration = aki::JSBind::GetJSFunction("SoundUtils.getDuration"))
{
duration = getMp3Duration->Invoke<double>();
}
return duration;
}
void NapiHelper::startVibration(float duration)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__startVibration, this, duration));
}
void NapiHelper::__startVibration(float duration)
{
if (auto startVibration = aki::JSBind::GetJSFunction("DeviceUtils.startVibration"))
{
startVibration->Invoke<void>(duration);
}
}
std::string NapiHelper::getAppVersion()
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__getAppVersion, this));
return appVersion;
}
std::string NapiHelper::__getAppVersion()
{
if (auto getAppVersion = aki::JSBind::GetJSFunction("ApplicationManager.getAppVersion"))
{
appVersion = getAppVersion->Invoke<std::string>();
}
return appVersion;
}
std::string NapiHelper::getAppLocalVersion()
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__getAppLocalVersion, this));
return appLocalVersion;
}
std::string NapiHelper::__getAppLocalVersion()
{
if (auto getAppLocalVersion = aki::JSBind::GetJSFunction("ApplicationManager.getAppLocalVersion"))
{
appLocalVersion = getAppLocalVersion->Invoke<std::string>();
}
return appLocalVersion;
}
void NapiHelper::createVideoPlayer(int m_tag)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__createVideoPlayer, this, m_tag));
}
void NapiHelper::__createVideoPlayer(int m_tag)
{
if (auto createVideoPlayer = aki::JSBind::GetJSFunction("VideoPlayer.createVideoPlayer"))
{
createVideoPlayer->Invoke<void>(m_tag);
}
}
void NapiHelper::removeVideoPlayer(int m_tag)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__removeVideoPlayer, this, m_tag));
}
void NapiHelper::__removeVideoPlayer(int m_tag)
{
if (auto removeVideoPlayer = aki::JSBind::GetJSFunction("VideoPlayer.removeVideoPlayer"))
{
removeVideoPlayer->Invoke<void>(m_tag);
}
}
void NapiHelper::setURL(int m_tag, std::string path, int isurl)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__setURL, this, m_tag, path, isurl));
}
void NapiHelper::__setURL(int m_tag, std::string path, int isurl)
{
if (auto setURL = aki::JSBind::GetJSFunction("VideoPlayer.setURL"))
{
setURL->Invoke<void>(m_tag, path, isurl);
}
}
void NapiHelper::play(int m_tag)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__play, this, m_tag));
}
void NapiHelper::__play(int m_tag)
{
if (auto play = aki::JSBind::GetJSFunction("VideoPlayer.play"))
{
play->Invoke<void>(m_tag);
}
}
void NapiHelper::pause(int m_tag)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__pause, this, m_tag));
}
void NapiHelper::__pause(int m_tag)
{
if (auto pause = aki::JSBind::GetJSFunction("VideoPlayer.pause"))
{
pause->Invoke<void>(m_tag);
}
}
void NapiHelper::stop(int m_tag)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__stop, this, m_tag));
}
void NapiHelper::__stop(int m_tag)
{
if (auto stop = aki::JSBind::GetJSFunction("VideoPlayer.stop"))
{
stop->Invoke<void>(m_tag);
}
}
void NapiHelper::setLooping(int m_tag, bool value)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__setLooping, this, m_tag, value));
}
void NapiHelper::__setLooping(int m_tag, bool value)
{
if (auto setLooping = aki::JSBind::GetJSFunction("VideoPlayer.setLooping"))
{
setLooping->Invoke<void>(m_tag, value);
}
}
void NapiHelper::setAutoplay(int m_tag, bool value)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__setAutoplay, this, m_tag, value));
}
void NapiHelper::__setAutoplay(int m_tag, bool value)
{
if (auto setAutoplay = aki::JSBind::GetJSFunction("VideoPlayer.setAutoplay"))
{
setAutoplay->Invoke<void>(m_tag, value);
}
}
void NapiHelper::setX(int m_tag, double value)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__setX, this, m_tag, value));
}
void NapiHelper::__setX(int m_tag, double value)
{
if (auto setX = aki::JSBind::GetJSFunction("VideoPlayer.setX"))
{
setX->Invoke<void>(m_tag, value);
}
}
void NapiHelper::setY(int m_tag, double value)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__setY, this, m_tag, value));
}
void NapiHelper::__setY(int m_tag, double value)
{
if (auto setY = aki::JSBind::GetJSFunction("VideoPlayer.setY"))
{
setY->Invoke<void>(m_tag, value);
}
}
void NapiHelper::setWidth(int m_tag, double value)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__setWidth, this, m_tag, value));
}
void NapiHelper::__setWidth(int m_tag, double value)
{
if (auto setWidth = aki::JSBind::GetJSFunction("VideoPlayer.setWidth"))
{
setWidth->Invoke<void>(m_tag, value);
}
}
void NapiHelper::setHeight(int m_tag, double value)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__setHeight, this, m_tag, value));
}
void NapiHelper::__setHeight(int m_tag, double value)
{
if (auto setHeight = aki::JSBind::GetJSFunction("VideoPlayer.setHeight"))
{
setHeight->Invoke<void>(m_tag, value);
}
}
void NapiHelper::setVideoCurrentTime(int m_tag, double value)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__setVideoCurrentTime, this, m_tag, value));
}
void NapiHelper::__setVideoCurrentTime(int m_tag, double value)
{
if (auto setCurrentTime = aki::JSBind::GetJSFunction("VideoPlayer.setCurrentTime"))
{
setCurrentTime->Invoke<void>(m_tag, value);
}
}
void NapiHelper::setVolume(int m_tag, double value)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__setVolume, this, m_tag, value));
}
void NapiHelper::__setVolume(int m_tag, double value)
{
if (auto setVolume = aki::JSBind::GetJSFunction("VideoPlayer.setVolume"))
{
setVolume->Invoke<void>(m_tag, value);
}
}
int NapiHelper::getVolume(int m_tag)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__getVolume, this, m_tag));
return volume;
}
int NapiHelper::__getVolume(int m_tag)
{
if (auto getVolume = aki::JSBind::GetJSFunction("VideoPlayer.getVolume"))
{
volume = getVolume->Invoke<int>(m_tag);
}
return volume;
}
void NapiHelper::showDialog(const char *p_sBuffer)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__showDialog, this, p_sBuffer));
}
void NapiHelper::__showDialog(const char *p_sBuffer)
{
std::string strBuffer = p_sBuffer;
if (auto showDialog = aki::JSBind::GetJSFunction("Dialog.showDialog"))
{
showDialog->Invoke<void>(strBuffer.c_str());
}
}
void NapiHelper::setKeepScreenOn(bool value)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__setKeepScreenOn, this, value));
}
void NapiHelper::__setKeepScreenOn(bool value)
{
if (auto setKeepScreenOn = aki::JSBind::GetJSFunction("DeviceUtils.setKeepScreenOn"))
{
setKeepScreenOn->Invoke<void>(value);
}
}
void NapiHelper::setPreferredOrientation(int orientation)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__setPreferredOrientation, this, orientation));
}
void NapiHelper::__setPreferredOrientation(int orientation)
{
if (auto setPreferredOrientation = aki::JSBind::GetJSFunction("DeviceUtils.setPreferredOrientation"))
{
setPreferredOrientation->Invoke<void>(orientation);
}
}
float NapiHelper::getScreenInch()
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__getScreenInch, this));
return screenInch;
}
float NapiHelper::__getScreenInch()
{
std::promise<float> promise;
std::function<void(float)> cb = [&promise](float message)
{ promise.set_value(message); };
if (auto getScreenInch = aki::JSBind::GetJSFunction("DeviceUtils.getScreenInch"))
{
getScreenInch->Invoke<void>(cb);
}
screenInch = promise.get_future().get();
return screenInch;
}
int NapiHelper::getAvalidMem()
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__getAvalidMem, this));
return avalidMem;
}
int NapiHelper::__getAvalidMem()
{
if (auto getAvalidMem = aki::JSBind::GetJSFunction("DeviceUtils.getAvalidMem"))
{
avalidMem = getAvalidMem->Invoke<int>();
}
return avalidMem;
}
int NapiHelper::getUsedMem()
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__getUsedMem, this));
return usedMem;
}
int NapiHelper::__getUsedMem()
{
if (auto getUsedMem = aki::JSBind::GetJSFunction("DeviceUtils.getPrivateDirty"))
{
usedMem = getUsedMem->Invoke<int>();
}
return usedMem;
}
void NapiHelper::exitGame()
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__exitGame, this));
}
void NapiHelper::__exitGame()
{
if (auto exit = aki::JSBind::GetJSFunction("ApplicationManager.exit"))
{
exit->Invoke<void>();
}
}
std::string NapiHelper::postMessageToUIThread(std::string eventName, std::string data)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__postMessageToUIThread, this, eventName, data));
return eventResult;
}
std::string NapiHelper::__postMessageToUIThread(std::string eventName, std::string data)
{
if (auto post = aki::JSBind::GetJSFunction("HandleMessageUtils.handleMessage"))
{
eventResult = post->Invoke<std::string>(eventName, data);
}
return eventResult;
}
std::string NapiHelper::postSyncMessageToUIThread(std::string eventName, std::string data)
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__postSyncMessageToUIThread, this, eventName, data));
return syncEventResult;
}
std::string NapiHelper::__postSyncMessageToUIThread(std::string eventName, std::string data)
{
std::promise<std::string> promise;
std::function<void(std::string)> cb = [&promise](std::string message){
promise.set_value(message);
};
if (auto post = aki::JSBind::GetJSFunction("HandleMessageUtils.handleSyncMessage"))
{
post->Invoke<void>(eventName, data, cb);
}
syncEventResult = promise.get_future().get();
return syncEventResult;
}
void NapiHelper::enableAccelerometer()
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__enableAccelerometer, this));
}
void NapiHelper::__enableAccelerometer()
{
if (auto accelerometerEnable = aki::JSBind::GetJSFunction("Accelerometer.enable"))
{
accelerometerEnable->Invoke<void>();
}
}
void NapiHelper::disableAccelerometer()
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__disableAccelerometer, this));
}
void NapiHelper::__disableAccelerometer()
{
if (auto accelerometerDisable = aki::JSBind::GetJSFunction("Accelerometer.disable"))
{
accelerometerDisable->Invoke<void>();
}
}
void NapiHelper::enableOrientation()
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__enableOrientation, this));
}
void NapiHelper::__enableOrientation()
{
if (auto orientationEnable = aki::JSBind::GetJSFunction("Orientation.enable"))
{
orientationEnable->Invoke<void>();
}
}
void NapiHelper::disableOrientation()
{
JCConch::s_pConchRender->setInterruptFunc(std::bind(&NapiHelper::__disableOrientation, this));
}
void NapiHelper::__disableOrientation()
{
if (auto orientationDisable = aki::JSBind::GetJSFunction("Orientation.disable"))
{
orientationDisable->Invoke<void>();
}
}
+113
View File
@@ -0,0 +1,113 @@
#include "../conch/JCConch.h"
#include <hilog/log.h>
using namespace laya;
class NapiHelper{
public:
~NapiHelper(){}
static NapiHelper *GetInstance(){return &NapiHelper::help_;}
std::string getDeviceInfo();
int getNetworkType();
void startVibration(float duration);
void playBackgroundMusic(const char *p_sUrl,int p_nTimes,float nCurrentTime);
void pauseBackgroundMusic();
void stopBackgroundMusic();
void setBackgroundMusicVolume(float p_nVolume);
void resumeBackgroundMusic();
void setCurrentTime(double nCurrentTime);
double getCurrentTime();
double getDuration();
std::string getAppVersion();
std::string getAppLocalVersion();
void createVideoPlayer(int m_tag);
void removeVideoPlayer(int m_tag);
void setURL(int m_tag,std::string path,int isurl);
void play(int m_tag);
void pause(int m_tag);
void stop(int m_tag);
void setLooping(int m_tag,bool value);
void setAutoplay(int m_tag,bool value);
void setX(int m_tag,double value);
void setY(int m_tag,double value);
void setWidth(int m_tag,double value);
void setHeight(int m_tag,double value);
void setVideoCurrentTime(int m_tag,double value);
void setVolume(int m_tag,double value);
int getVolume(int m_tag);
void showDialog(const char *p_sBuffer);
void setKeepScreenOn(bool value);
void setPreferredOrientation(int orientation);
float getScreenInch();
int getAvalidMem();
int getUsedMem();
void exitGame();
void enableAccelerometer();
void disableAccelerometer();
void enableOrientation();
void disableOrientation();
std::string postMessageToUIThread(std::string eventName, std::string data);
std::string postSyncMessageToUIThread(std::string eventName, std::string data);
private:
std::string __getDeviceInfo();
int __getNetworkType();
void __startVibration(float duration);
void __playBackgroundMusic(const char *p_sUrl,int p_nTimes,float nCurrentTime);
void __pauseBackgroundMusic();
void __stopBackgroundMusic();
void __setBackgroundMusicVolume(float p_nVolume);
void __resumeBackgroundMusic();
void __setCurrentTime(double nCurrentTime);
double __getCurrentTime();
double __getDuration();
std::string __getAppVersion();
std::string __getAppLocalVersion();
void __createVideoPlayer(int m_tag);
void __removeVideoPlayer(int m_tag);
void __setURL(int m_tag,std::string path,int isurl);
void __play(int m_tag);
void __pause(int m_tag);
void __stop(int m_tag);
void __setLooping(int m_tag,bool value);
void __setAutoplay(int m_tag,bool value);
void __setX(int m_tag,double value);
void __setY(int m_tag,double value);
void __setWidth(int m_tag,double value);
void __setHeight(int m_tag,double value);
void __setVideoCurrentTime(int m_tag,double value);
void __setVolume(int m_tag,double value);
int __getVolume(int m_tag);
void __showDialog(const char *p_sBuffer);
void __setKeepScreenOn(bool value);
void __setPreferredOrientation(int orientation);
float __getScreenInch();
int __getAvalidMem();
int __getUsedMem();
void __exitGame();
void __enableAccelerometer();
void __disableAccelerometer();
void __enableOrientation();
void __disableOrientation();
std::string __postMessageToUIThread(std::string eventName, std::string data);
std::string __postSyncMessageToUIThread(std::string eventName, std::string data);
static NapiHelper help_;
private:
std::string deviceInfo;
std::string appVersion;
std::string appLocalVersion;
std::string eventResult;
std::string syncEventResult;
int networkType;
int volume;
double currentTime;
double duration;
float screenInch;
int avalidMem;
int usedMem;
};
+52
View File
@@ -0,0 +1,52 @@
#include "TouchesNapi.h"
using namespace laya;
extern "C"
{
void nativeHandleTouchDown(int id, int x, int y)
{
inputEvent e;
e.nType = E_ONTOUCHSTART;
e.nTouchType = 0;
e.posX = x;
e.posY = y;
e.id = id;
strncpy(e.type, "touchstart", 256);
JCScriptRuntime::s_JSRT->dispatchInputEvent(e);
}
void nativeHandleTouchUp(int id, int x, int y)
{
inputEvent e;
e.nType = E_ONTOUCHEND;
e.nTouchType = 6;
e.posX = x;
e.posY = y;
e.id = id;
strncpy(e.type, "touchend", 256);
JCScriptRuntime::s_JSRT->dispatchInputEvent(e);
}
void nativeHandleTouchMove(int id, int x, int y)
{
inputEvent e;
e.nType = E_ONTOUCHMOVE;
e.nTouchType = 2;
e.posX = x;
e.posY = y;
e.id = id;
strncpy(e.type, "touchmove", 256);
JCScriptRuntime::s_JSRT->dispatchInputEvent(e);
}
void nativeHandleTouchCancel(int id, int x, int y)
{
inputEvent e;
e.nType = E_ONTOUCHEND;
e.nTouchType = 3;
e.posX = x;
e.posY = y;
e.id = id;
strncpy(e.type, "touchCancel", 256);
JCScriptRuntime::s_JSRT->dispatchInputEvent(e);
}
}
+16
View File
@@ -0,0 +1,16 @@
#ifndef _TOUCHESNAPI_H_
#define _TOUCHESNAPI_H_
#include "conch/JCScriptRuntime.h"
using namespace laya;
extern "C"
{
void nativeHandleTouchDown(int id, int x, int y);
void nativeHandleTouchUp(int id, int x, int y);
void nativeHandleTouchMove(int id, int x, int y);
void nativeHandleTouchCancel(int id, int x, int y);
}
#endif
@@ -0,0 +1,172 @@
#include "VideoPlayerNapi.h"
#include "../plugin_manager.h"
#include "util/Log.h"
#include "conch/JSWrapper/LayaWrap/Video/JSVideo.h"
#include <js_native_api.h>
#include <js_native_api_types.h>
napi_value VideoPlayerNapi::onVideoCallBack(napi_env env, napi_callback_info info)
{
napi_status status;
size_t argc = 2;
napi_value args[2];
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr));
if (argc != 2)
{
napi_throw_type_error(env, NULL, "Wrong number of arguments");
return nullptr;
}
napi_valuetype valuetype;
status = napi_typeof(env, args[0], &valuetype);
if (status != napi_ok)
{
return nullptr;
}
if (valuetype != napi_number)
{
napi_throw_type_error(env, NULL, "Wrong arguments");
return nullptr;
}
status = napi_typeof(env, args[1], &valuetype);
if (status != napi_ok)
{
return nullptr;
}
if (valuetype != napi_number)
{
napi_throw_type_error(env, NULL, "Wrong arguments");
return nullptr;
}
int32_t viewTag;
NAPI_CALL(env, napi_get_value_int32(env, args[0], &viewTag));
int32_t event;
NAPI_CALL(env, napi_get_value_int32(env, args[1], &event));
laya::JSVideo::executeVideoCallback(viewTag, event);
return nullptr;
}
napi_value VideoPlayerNapi::loadedmetadata(napi_env env, napi_callback_info info)
{
napi_status status;
size_t argc = 1;
napi_value args[1];
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr));
if (argc != 1)
{
napi_throw_type_error(env, NULL, "Wrong number of arguments");
return nullptr;
}
napi_valuetype valuetype;
status = napi_typeof(env, args[0], &valuetype);
if (status != napi_ok)
{
return nullptr;
}
if (valuetype != napi_number)
{
napi_throw_type_error(env, NULL, "Wrong arguments");
return nullptr;
}
int32_t viewTag;
NAPI_CALL(env, napi_get_value_int32(env, args[0], &viewTag));
laya::JSVideo::executeLoadedmetadata(viewTag, "loadedmetadata");
return nullptr;
}
napi_value VideoPlayerNapi::onDurationBack(napi_env env, napi_callback_info info)
{
napi_status status;
size_t argc = 2;
napi_value args[2];
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr));
if (argc != 2)
{
napi_throw_type_error(env, NULL, "Wrong number of arguments");
return nullptr;
}
napi_valuetype valuetype;
status = napi_typeof(env, args[0], &valuetype);
if (status != napi_ok)
{
return nullptr;
}
if (valuetype != napi_number)
{
napi_throw_type_error(env, NULL, "Wrong arguments");
return nullptr;
}
status = napi_typeof(env, args[1], &valuetype);
if (status != napi_ok)
{
return nullptr;
}
if (valuetype != napi_number)
{
napi_throw_type_error(env, NULL, "Wrong arguments");
return nullptr;
}
int32_t viewTag;
NAPI_CALL(env, napi_get_value_int32(env, args[0], &viewTag));
int32_t duration;
NAPI_CALL(env, napi_get_value_int32(env, args[1], &duration));
laya::JSVideo::executeDurationBack(viewTag, duration);
return nullptr;
}
napi_value VideoPlayerNapi::onCurrentTimeBack(napi_env env, napi_callback_info info)
{
napi_status status;
size_t argc = 2;
napi_value args[2];
NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr));
if (argc != 2)
{
napi_throw_type_error(env, NULL, "Wrong number of arguments");
return nullptr;
}
napi_valuetype valuetype;
status = napi_typeof(env, args[0], &valuetype);
if (status != napi_ok)
{
return nullptr;
}
if (valuetype != napi_number)
{
napi_throw_type_error(env, NULL, "Wrong arguments");
return nullptr;
}
status = napi_typeof(env, args[1], &valuetype);
if (status != napi_ok)
{
return nullptr;
}
if (valuetype != napi_number)
{
napi_throw_type_error(env, NULL, "Wrong arguments");
return nullptr;
}
int32_t viewTag;
NAPI_CALL(env, napi_get_value_int32(env, args[0], &viewTag));
int32_t currentTime;
NAPI_CALL(env, napi_get_value_int32(env, args[1], &currentTime));
laya::JSVideo::executeCurrentTimeBack(viewTag, currentTime);
return nullptr;
}
@@ -0,0 +1,10 @@
#include <napi/native_api.h>
class VideoPlayerNapi
{
public:
static napi_value onVideoCallBack(napi_env env, napi_callback_info info);
static napi_value loadedmetadata(napi_env env, napi_callback_info info);
static napi_value onDurationBack(napi_env env, napi_callback_info info);
static napi_value onCurrentTimeBack(napi_env env, napi_callback_info info);
};
+234
View File
@@ -0,0 +1,234 @@
#include <stdint.h>
#include <string>
#include <stdio.h>
#include <ace/xcomponent/native_interface_xcomponent.h>
#include "modules/VideoPlayerNapi.h"
#include "plugin_manager.h"
#include <aki/jsbind.h>
#include "util/Log.h"
enum ContextType
{
APP_LIFECYCLE = 0,
JS_PAGE_LIFECYCLE,
WORKER_INIT,
NATIVE_API,
VIDEOPLAYER_NAPI,
};
JSBIND_ENUM(ContextType)
{
JSBIND_ENUM_VALUE(APP_LIFECYCLE);
JSBIND_ENUM_VALUE(JS_PAGE_LIFECYCLE);
JSBIND_ENUM_VALUE(WORKER_INIT);
JSBIND_ENUM_VALUE(NATIVE_API);
JSBIND_ENUM_VALUE(VIDEOPLAYER_NAPI);
}
NapiManager NapiManager::manager_;
napi_value NapiManager::GetContext(long contextEnum)
{
napi_env env = aki::JSBind::GetScopedEnv();
napi_value exports;
NAPI_CALL(env, napi_create_object(env, &exports));
switch (contextEnum)
{
case APP_LIFECYCLE:
{
/**** application life cycle: onCreate, onShow, onHide, onDestroy ******/
LOGI("GetContext APP_LIFECYCLE");
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("onCreate", NapiManager::NapiOnCreate),
DECLARE_NAPI_FUNCTION("onShow", NapiManager::NapiOnShow),
DECLARE_NAPI_FUNCTION("onHide", NapiManager::NapiOnHide),
DECLARE_NAPI_FUNCTION("onBackPress", NapiManager::NapiOnBackPress),
DECLARE_NAPI_FUNCTION("onDestroy", NapiManager::NapiOnDestroy),
};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc));
}
break;
case JS_PAGE_LIFECYCLE:
{
/**************** JS Page Lifecycle ****************************/
LOGI("GetContext JS_PAGE_LIFECYCLE");
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("onPageShow", NapiManager::NapiOnPageShow),
DECLARE_NAPI_FUNCTION("onPageHide", NapiManager::NapiOnPageHide),
};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc));
}
break;
case WORKER_INIT:
{
LOGI("NapiManager::GetContext WORKER_INIT");
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("workerInit", NapiManager::napiWorkerInit),
};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc));
}
break;
case NATIVE_API:
{
LOGI("NapiManager::GetContext NATIVE_RENDER_API");
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("nativeEngineStart", NapiManager::napiNativeEngineStart),
};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc));
}
break;
case VIDEOPLAYER_NAPI:
{
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("onVideoCallBack", VideoPlayerNapi::onVideoCallBack),
DECLARE_NAPI_FUNCTION("loadedmetadata", VideoPlayerNapi::loadedmetadata),
DECLARE_NAPI_FUNCTION("onDurationBack", VideoPlayerNapi::onDurationBack),
DECLARE_NAPI_FUNCTION("onCurrentTimeBack", VideoPlayerNapi::onCurrentTimeBack),
};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc));
}
break;
default:
LOGI("unknown type");
}
return exports;
}
bool NapiManager::Export(napi_env env, napi_value exports)
{
LOGI("NapiManager::Export");
napi_status status;
napi_value exportInstance = nullptr;
OH_NativeXComponent *nativeXComponent = nullptr;
int32_t ret;
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {};
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
status = napi_get_named_property(env, exports, OH_NATIVE_XCOMPONENT_OBJ, &exportInstance);
if (status != napi_ok)
{
return false;
}
status = napi_unwrap(env, exportInstance, reinterpret_cast<void **>(&nativeXComponent));
if (status != napi_ok)
{
return false;
}
auto context = NapiManager::GetInstance();
if (context)
{
context->SetNativeXComponent(nativeXComponent);
PluginRender::GetInstance()->SetNativeXComponent(nativeXComponent);
PluginRender::GetInstance()->Export(env, exports);
return true;
}
return false;
}
void NapiManager::SetNativeXComponent(OH_NativeXComponent *nativeXComponent)
{
nativeXComponent_ = nativeXComponent;
}
OH_NativeXComponent *NapiManager::GetNativeXComponent()
{
return nativeXComponent_;
}
void NapiManager::MainOnMessage(const uv_async_t *req)
{
LOGI("MainOnMessage Triggered");
}
napi_value NapiManager::NapiOnCreate(napi_env env, napi_callback_info info)
{
return nullptr;
}
napi_value NapiManager::NapiOnShow(napi_env env, napi_callback_info info)
{
LOGI("NapiManager::NapiOnShow");
WorkerMessageData data{MessageType::WM_APP_SHOW, nullptr, nullptr};
PluginRender::GetInstance()->enqueue(data);
return nullptr;
}
napi_value NapiManager::NapiOnHide(napi_env env, napi_callback_info info)
{
LOGI("NapiManager::NapiOnHide");
WorkerMessageData data{MessageType::WM_APP_HIDE, nullptr, nullptr};
PluginRender::GetInstance()->enqueue(data);
return nullptr;
}
napi_value NapiManager::NapiOnBackPress(napi_env env, napi_callback_info info)
{
LOGI("NapiManager::NapiOnBackPress");
return nullptr;
}
napi_value NapiManager::NapiOnDestroy(napi_env env, napi_callback_info info)
{
WorkerMessageData data{MessageType::WM_APP_DESTROY, nullptr, nullptr};
PluginRender::GetInstance()->enqueue(data);
return nullptr;
}
napi_value NapiManager::napiWorkerInit(napi_env env, napi_callback_info info)
{
LOGI("NapiManager::napiWorkerInit");
uv_loop_t *loop = nullptr;
NAPI_CALL(env, napi_get_uv_event_loop(env, &loop));
PluginRender::GetInstance()->workerInit(env, loop);
return nullptr;
}
napi_value NapiManager::napiNativeEngineStart(napi_env env, napi_callback_info info)
{
LOGI("NapiManager::napiNativeEngineStart");
PluginRender::GetInstance()->run();
return nullptr;
}
napi_value NapiManager::NapiOnPageShow(napi_env env, napi_callback_info info)
{
LOGI("NapiManager::NapiOnPageShow");
return nullptr;
}
napi_value NapiManager::NapiOnPageHide(napi_env env, napi_callback_info info)
{
LOGI("NapiManager::NapiOnPageHide");
return nullptr;
}
void NapiManager::OnPageShowNative()
{
LOGI("NapiManager::OnPageShowNative");
}
void NapiManager::OnPageHideNative()
{
LOGI("NapiManager::OnPageHideNative");
}
JSBIND_GLOBAL()
{
JSBIND_FUNCTION(NapiManager::GetContext, "getContext");
}
/*
* function for module exports
*/
napi_value InitLaya(napi_env env, napi_value exports) {
aki::JSBind::BindSymbols(env, exports);
bool ret = NapiManager::GetInstance()->Export(env, exports);
if (!ret) {
LOGE("napi init failed");
}
return exports;
}
+64
View File
@@ -0,0 +1,64 @@
#ifndef _PLUGIN_MANAGER_H_
#define _PLUGIN_MANAGER_H_
#include <string>
#include <unordered_map>
#include <ace/xcomponent/native_interface_xcomponent.h>
#include <napi/native_api.h>
#include <uv.h>
#include "common/native_common.h"
#include "WorkerMessageQueue.h"
#include "render/plugin_render.h"
napi_value InitLaya(napi_env env, napi_value exports);
class NapiManager {
public:
~NapiManager() {}
static NapiManager* GetInstance()
{
return &NapiManager::manager_;
}
static napi_value GetContext(long contextEnum);
/******************************APP Lifecycle******************************/
static napi_value NapiOnCreate(napi_env env, napi_callback_info info);
static napi_value NapiOnShow(napi_env env, napi_callback_info info);
static napi_value NapiOnHide(napi_env env, napi_callback_info info);
static napi_value NapiOnBackPress(napi_env env, napi_callback_info info);
static napi_value NapiOnDestroy(napi_env env, napi_callback_info info);
/*********************************************************************/
/******************************JS Page : Lifecycle*****************************/
static napi_value NapiOnPageShow(napi_env env, napi_callback_info info);
static napi_value NapiOnPageHide(napi_env env, napi_callback_info info);
void OnPageShowNative();
void OnPageHideNative();
/*************************************************************************/
// Worker Func
static napi_value napiWorkerInit(napi_env env, napi_callback_info info);
static napi_value napiNativeEngineStart(napi_env env, napi_callback_info info);
static napi_value napiWritablePathInit(napi_env env, napi_callback_info info);
OH_NativeXComponent* GetNativeXComponent();
void SetNativeXComponent(OH_NativeXComponent* nativeXComponent);
public:
// Napi export
bool Export(napi_env env, napi_value exports);
private:
static void MainOnMessage(const uv_async_t* req);
static NapiManager manager_;
OH_NativeXComponent* nativeXComponent_ = nullptr;
public:
napi_env mainEnv_ = nullptr;
uv_loop_t* mainLoop_ = nullptr;
uv_async_t mainOnMessageSignal_ {};
};
#endif // _PLUGIN_MANAGER_H_
+91
View File
@@ -0,0 +1,91 @@
#include "egl_core.h"
#include "plugin_render.h"
#include <EGL/egl.h>
#include <GLES3/gl3.h>
EGLConfig getConfig(int version, EGLDisplay eglDisplay) {
int attribList[] = {
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_STENCIL_SIZE, 8,
EGL_DEPTH_SIZE, 24,
EGL_NONE
};
EGLConfig configs = NULL;
int configsNum;
if (!eglChooseConfig(eglDisplay, attribList, &configs, 1, &configsNum)) {
// OHOS_LOGE("eglChooseConfig ERROR");
return NULL;
}
return configs;
}
void EGLCore::GLContextInit(void* window, int w, int h)
{
// OHOS_LOGD("EGLCore::GLContextInit window = %{public}p, w = %{public}d, h = %{public}d.", window, w, h);
width_ = w;
height_ = h;
mEglWindow = (EGLNativeWindowType)(window);
// 1. create sharedcontext
mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (mEGLDisplay == EGL_NO_DISPLAY) {
// OHOS_LOGE("EGLCore::unable to get EGL display.");
return;
}
EGLint eglMajVers, eglMinVers;
if (!eglInitialize(mEGLDisplay, &eglMajVers, &eglMinVers)) {
mEGLDisplay = EGL_NO_DISPLAY;
// OHOS_LOGE("EGLCore::unable to initialize display");
return;
}
mEGLConfig = getConfig(3, mEGLDisplay);
if (mEGLConfig == nullptr) {
// OHOS_LOGE("EGLCore::GLContextInit config ERROR");
return;
}
// 2. Create EGL Surface from Native Window
if (mEglWindow) {
mEGLSurface = eglCreateWindowSurface(mEGLDisplay, mEGLConfig, mEglWindow, nullptr);
if (mEGLSurface == nullptr) {
// OHOS_LOGE("EGLCore::eglCreateContext eglSurface is null");
return;
}
}
// 3. Create EGLContext from
int attrib3_list[] = {
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
mEGLContext = eglCreateContext(mEGLDisplay, mEGLConfig, mSharedEGLContext, attrib3_list);
if (!eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext)) {
// OHOS_LOGE("EGLCore::eglMakeCurrent error = %{public}d", eglGetError());
}
}
void EGLCore::Update()
{
eglSwapBuffers(mEGLDisplay, mEGLSurface);
}
bool EGLCore::checkGlError(const char* op)
{
// OHOS_LOGE("EGL ERROR CODE = %{public}x", eglGetError());
GLint error;
for (error = glGetError(); error; error = glGetError()) {
// OHOS_LOGE("ERROR: %{public}s, ERROR CODE = %{public}x", op, error);
return true;
}
return false;
}
+31
View File
@@ -0,0 +1,31 @@
#ifndef _GL_CORE_
#define _GL_CORE_
#include <GLES3/gl3.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <string>
class EGLCore {
public:
EGLCore() {};
void GLContextInit(void* window, int w, int h);
void Update();
public:
int width_;
int height_;
private:
bool checkGlError(const char* op);
EGLNativeWindowType mEglWindow;
EGLDisplay mEGLDisplay = EGL_NO_DISPLAY;
EGLConfig mEGLConfig = nullptr;
EGLContext mEGLContext = EGL_NO_CONTEXT;
EGLContext mSharedEGLContext = EGL_NO_CONTEXT;
EGLSurface mEGLSurface = nullptr;
};
#endif // _GL_CORE_
+338
View File
@@ -0,0 +1,338 @@
#include <stdint.h>
#include <unistd.h>
#include "plugin_render.h"
#include "../../napi/plugin_manager.h"
#include "../modules/TouchesNapi.h"
#include "../../napi/NAPIFun.cpp"
#include <assert.h>
#include "util/Log.h"
using namespace laya;
#ifdef __cplusplus
extern "C" {
#endif
PluginRender* PluginRender::instance_ = nullptr;
OH_NativeXComponent_Callback PluginRender::callback_;
uint64_t PluginRender::animationInterval_ = 16;
uint64_t PluginRender::lastTime = 0;
void OnSurfaceCreatedCB(OH_NativeXComponent* component, void* window)
{
LOGI("OnSurfaceCreatedCB");
PluginRender::GetInstance()->sendMsgToWorker(MessageType::WM_XCOMPONENT_SURFACE_CREATED, component, window);
}
void OnSurfaceChangedCB(OH_NativeXComponent* component, void* window)
{
LOGI("OnSurfaceChangedCB");
PluginRender::GetInstance()->sendMsgToWorker(MessageType::WM_XCOMPONENT_SURFACE_CHANGED, component, window);
}
void OnSurfaceDestroyedCB(OH_NativeXComponent* component, void* window)
{
LOGI("OnSurfaceDestroyedCB");
PluginRender::GetInstance()->sendMsgToWorker(MessageType::WM_XCOMPONENT_SURFACE_DESTROY, component, window);
}
void DispatchTouchEventCB(OH_NativeXComponent* component, void* window)
{
OH_NativeXComponent_TouchEvent* touchEvent = new(std::nothrow) OH_NativeXComponent_TouchEvent();
if (!touchEvent) {
LOGI("DispatchTouchEventCB::touchEvent alloc failed");
return;
}
int32_t ret = OH_NativeXComponent_GetTouchEvent(component, window, touchEvent);
if (ret == OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
PluginRender::GetInstance()->sendMsgToWorker(MessageType::WM_XCOMPONENT_TOUCH_EVENT, component, window, touchEvent);
} else {
delete touchEvent;
}
}
PluginRender::PluginRender() : component_(nullptr)
{
auto renderCallback = PluginRender::GetNXComponentCallback();
renderCallback->OnSurfaceCreated = OnSurfaceCreatedCB;
renderCallback->OnSurfaceChanged = OnSurfaceChangedCB;
renderCallback->OnSurfaceDestroyed = OnSurfaceDestroyedCB;
renderCallback->DispatchTouchEvent = DispatchTouchEventCB;
}
PluginRender* PluginRender::GetInstance()
{
if (instance_ == nullptr) {
instance_ = new PluginRender();
}
return instance_;
}
OH_NativeXComponent_Callback* PluginRender::GetNXComponentCallback()
{
return &PluginRender::callback_;
}
// static
void PluginRender::onMessageCallback(const uv_async_t* /* req */) {
void* window = nullptr;
WorkerMessageData msgData;
PluginRender* render = PluginRender::GetInstance();
while (true) {
//loop until all msg dispatch
if (!render->dequeue(reinterpret_cast<WorkerMessageData*>(&msgData))) {
// Queue has no data
break;
}
if ((msgData.type >= MessageType::WM_XCOMPONENT_SURFACE_CREATED) && (msgData.type <= MessageType::WM_XCOMPONENT_SURFACE_DESTROY)) {
OH_NativeXComponent* nativexcomponet = reinterpret_cast<OH_NativeXComponent*>(msgData.data);
// CC_ASSERT(nativexcomponet != nullptr);
if (msgData.type == MessageType::WM_XCOMPONENT_SURFACE_CREATED) {
render->OnSurfaceCreated(nativexcomponet, msgData.window);
} else if (msgData.type == MessageType::WM_XCOMPONENT_TOUCH_EVENT) {
render->DispatchTouchEvent(nativexcomponet, msgData.window, msgData.touchEvent);
} else if (msgData.type == MessageType::WM_XCOMPONENT_SURFACE_CHANGED) {
render->OnSurfaceChanged(nativexcomponet, msgData.window);
} else if (msgData.type == MessageType::WM_XCOMPONENT_SURFACE_DESTROY) {
render->OnSurfaceDestroyed(nativexcomponet, msgData.window);
} else {
// CC_ASSERT(false);
}
continue;
}
if (msgData.type == MessageType::WM_APP_SHOW) {
render->OnShowNative();
} else if (msgData.type == MessageType::WM_APP_HIDE) {
render->OnHideNative();
} else if (msgData.type == MessageType::WM_APP_DESTROY) {
render->OnDestroyNative();
}
if(msgData.type == MessageType::WM_VSYNC) {
// render->runTask();
}
}
}
static uint64_t getCurrentMillSecond() {
struct timeval stCurrentTime;
gettimeofday(&stCurrentTime,NULL);
return stCurrentTime.tv_sec * 1000 + stCurrentTime.tv_usec / 1000; //millseconds
}
// static
void PluginRender::timerCb(uv_timer_t* handle)
{
// LOGI("PluginRender::timerCb, animationInterval_ is %{public}lu", animationInterval_);
if (PluginRender::GetInstance()->eglCore_ != nullptr) {
PluginRender::GetInstance()->eglCore_->Update();
NAPIFun::ConchNAPI_onDrawFrame();
}
}
void PluginRender::SetNativeXComponent(OH_NativeXComponent* component)
{
component_ = component;
OH_NativeXComponent_RegisterCallback(component_, &PluginRender::callback_);
}
void PluginRender::workerInit(napi_env env, uv_loop_t* loop) {
LOGI("PluginRender::workerInit");
workerLoop_ = loop;
if (workerLoop_) {
uv_async_init(workerLoop_, &messageSignal_, reinterpret_cast<uv_async_cb>(PluginRender::onMessageCallback));
if (!messageQueue_.empty()) {
triggerMessageSignal(); // trigger the signal to handle the pending message
}
}
}
void PluginRender::sendMsgToWorker(const MessageType& type, OH_NativeXComponent* component, void* window) {
WorkerMessageData data{type, static_cast<void*>(component), window};
enqueue(data);
}
void PluginRender::sendMsgToWorker(const MessageType& type, OH_NativeXComponent* component, void* window, OH_NativeXComponent_TouchEvent* touchEvent) {
WorkerMessageData data{type, static_cast<void*>(component), window, touchEvent};
enqueue(data);
}
void PluginRender::enqueue(const WorkerMessageData& msg) {
messageQueue_.enqueue(msg);
triggerMessageSignal();
}
bool PluginRender::dequeue(WorkerMessageData* msg) {
return messageQueue_.dequeue(msg);
}
void PluginRender::triggerMessageSignal() {
if(workerLoop_ != nullptr) {
// It is possible that when the message is sent, the worker thread has not yet started.
uv_async_send(&messageSignal_);
}
}
void PluginRender::run() {
LOGI("PluginRender::run");
if (workerLoop_) {
uv_timer_init(workerLoop_, &timerHandle_);
timerInited_ = true;
}
}
void PluginRender::changeFPS(uint64_t animationInterval) {
LOGI("PluginRender::changeFPS, animationInterval from %{public}lu to %{public}lu", animationInterval_, animationInterval);
animationInterval_ = animationInterval;
}
void PluginRender::OnSurfaceCreated(OH_NativeXComponent* component, void* window)
{
LOGI("PluginRender::OnSurfaceCreated");
eglCore_ = new EGLCore();
int32_t ret = OH_NativeXComponent_GetXComponentSize(component, window, &width_, &height_);
if (ret == OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
eglCore_->GLContextInit(window, width_, height_);
NAPIFun::ConchNAPI_OnGLReady(width_,height_);
}
}
void PluginRender::OnSurfaceChanged(OH_NativeXComponent* component, void* window)
{
LOGI("PluginRender::OnSurfaceChanged");
int32_t ret = OH_NativeXComponent_GetXComponentSize(component, window, &width_, &height_);
if (ret == OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
NAPIFun::ConchNAPI_OnGLReady(width_,height_);
}
}
void PluginRender::OnSurfaceDestroyed(OH_NativeXComponent* component, void* window)
{
}
void PluginRender::DispatchTouchEvent(OH_NativeXComponent* component, void* window, OH_NativeXComponent_TouchEvent* touchEvent)
{
intptr_t ids[touchEvent->numPoints];
float xs[touchEvent->numPoints];
float ys[touchEvent->numPoints];
for (int i = 0; i < touchEvent->numPoints; i++) {
ids[i] = touchEvent->touchPoints[i].id;
xs[i] = touchEvent->touchPoints[i].x;
ys[i] = touchEvent->touchPoints[i].y;
LOGI("Touch Info : x = %{public}f, y = %{public}f", xs[i], ys[i]);
}
switch (touchEvent -> type) {
case OH_NATIVEXCOMPONENT_DOWN:
nativeHandleTouchDown(touchEvent->id, touchEvent->x,touchEvent->y);
LOGI("Touch Info : OH_NATIVEXCOMPONENT_DOWN");
break;
case OH_NATIVEXCOMPONENT_UP:
nativeHandleTouchUp(touchEvent->id, touchEvent->x,touchEvent->y);
LOGI("Touch Info : OH_NATIVEXCOMPONENT_UP");
break;
case OH_NATIVEXCOMPONENT_MOVE:
nativeHandleTouchMove(touchEvent->id, touchEvent->x,touchEvent->y);
LOGI("Touch Info : OH_NATIVEXCOMPONENT_MOVE");
break;
case OH_NATIVEXCOMPONENT_CANCEL:
nativeHandleTouchCancel(touchEvent->id, touchEvent->x,touchEvent->y);
LOGI("Touch Info : OH_NATIVEXCOMPONENT_CANCEL");
break;
case OH_NATIVEXCOMPONENT_UNKNOWN:
LOGI("Touch Info : OH_NATIVEXCOMPONENT_UNKNOWN");
break;
default:
LOGI("Touch Info : default");
break;
}
delete touchEvent;
}
void PluginRender::OnCreateNative(napi_env env, uv_loop_t* loop) {
LOGI("PluginRender::OnCreateNative");
}
void PluginRender::OnShowNative() {
LOGI("PluginRender::OnShowNative");
if (timerInited_) {
uv_timer_start(&timerHandle_, &PluginRender::timerCb, 0, 1);
}
JCAudioManager* am = JCAudioManager::GetInstance();
if(am->getMp3Mute() == false && am ->getMp3Stopped() == false)
{
auto pFunction = std::bind(&JCAudioManager::resumeMp3,am);
JCScriptRuntime::s_JSRT->m_pPoster->postToJS(pFunction);
}
laya::JCAudioManager::GetInstance()->m_pWavPlayer->resume();
}
void PluginRender::OnHideNative() {
LOGI("PluginRender::OnHideNative");
JCAudioManager* am =JCAudioManager::GetInstance();
if(am->getMp3Mute() == false && am->getMp3Stopped() == false)
{
auto pFunction = std::bind(&JCAudioManager::pauseMp3,am);
JCScriptRuntime::s_JSRT->m_pPoster->postToJS( pFunction );
}
laya::JCAudioManager::GetInstance()->m_pWavPlayer->pause();
if (timerInited_) {
uv_timer_stop(&timerHandle_);
}
}
void PluginRender::OnDestroyNative() {
LOGI("PluginRender::OnDestoryNative");
if (timerInited_) {
uv_timer_stop(&timerHandle_);
}
NAPIFun::ConchNAPI_ReleaseDLib();
}
napi_value PluginRender::Export(napi_env env, napi_value exports)
{
LOGI("PluginRender::Export");
// Register JS API
napi_property_descriptor desc[] = {
DECLARE_NAPI_FUNCTION("changeShape", PluginRender::NapiChangeShape),
DECLARE_NAPI_FUNCTION("drawTriangle", PluginRender::NapiDrawTriangle),
DECLARE_NAPI_FUNCTION("changeColor", PluginRender::NapiChangeColor),
};
NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc));
return exports;
}
napi_value PluginRender::NapiChangeShape(napi_env env, napi_callback_info info)
{
LOGI("PluginRender::NapiChangeShape");
PluginRender* instance = PluginRender::GetInstance();
if (instance) {
instance->eglCore_->Update();
}
return nullptr;
}
napi_value PluginRender::NapiDrawTriangle(napi_env env, napi_callback_info info)
{
LOGI("NapiDrawTriangle");
return nullptr;
}
napi_value PluginRender::NapiChangeColor(napi_env env, napi_callback_info info)
{
LOGI("NapiChangeColor");
return nullptr;
}
#ifdef __cplusplus
}
#endif
+81
View File
@@ -0,0 +1,81 @@
#ifndef _PLUGIN_RENDER_H_
#define _PLUGIN_RENDER_H_
#include <string>
#include <unordered_map>
#include <uv.h>
#include <ace/xcomponent/native_interface_xcomponent.h>
#include <napi/native_api.h>
#include "egl_core.h"
#include "../WorkerMessageQueue.h"
class PluginRender {
public:
PluginRender();
static PluginRender* GetInstance();
static OH_NativeXComponent_Callback* GetNXComponentCallback();
static void onMessageCallback(const uv_async_t* req);
static void timerCb(uv_timer_t* handle);
void SetNativeXComponent(OH_NativeXComponent* component);
void workerInit(napi_env env, uv_loop_t* loop);
void sendMsgToWorker(const MessageType& type, OH_NativeXComponent* component, void* window);
void sendMsgToWorker(const MessageType& type, OH_NativeXComponent* component, void* window, OH_NativeXComponent_TouchEvent* touchEvent);
void enqueue(const WorkerMessageData& data);
bool dequeue(WorkerMessageData* data);
void triggerMessageSignal();
void run();
void changeFPS(uint64_t animationInterval);
public:
// NAPI interface
napi_value Export(napi_env env, napi_value exports);
// Exposed to JS developers by NAPI
static napi_value NapiChangeShape(napi_env env, napi_callback_info info);
static napi_value NapiDrawTriangle(napi_env env, napi_callback_info info);
static napi_value NapiChangeColor(napi_env env, napi_callback_info info);
static napi_value NapiChangeColorWorker(napi_env env, napi_callback_info info);
// Callback, called by ACE XComponent
void OnSurfaceCreated(OH_NativeXComponent* component, void* window);
void OnSurfaceChanged(OH_NativeXComponent* component, void* window);
void OnSurfaceDestroyed(OH_NativeXComponent* component, void* window);
void DispatchTouchEvent(OH_NativeXComponent* component, void* window, OH_NativeXComponent_TouchEvent* touchEvent);
void OnCreateNative(napi_env env, uv_loop_t* loop);
void OnShowNative();
void OnHideNative();
void OnDestroyNative();
public:
static PluginRender* instance_;
static OH_NativeXComponent_Callback callback_;
OH_NativeXComponent* component_{nullptr};
uv_timer_t timerHandle_;
bool timerInited_{false};
uv_loop_t* workerLoop_{nullptr};
uv_async_t messageSignal_{};
WorkerMessageQueue messageQueue_;
EGLCore* eglCore_{nullptr};
uint64_t width_;
uint64_t height_;
double x_;
double y_;
static uint64_t animationInterval_;
static uint64_t lastTime;
};
#endif // _PLUGIN_RENDER_H_
+1 -1
View File
@@ -57,7 +57,7 @@ async function initFreeType() {
if (sOS == "Conch-window") {
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile("C:/Windows/Fonts/simhei.ttf");
}
else if (sOS == "Conch-android") {
else if (sOS == "Conch-android" || sOS == "Conch-ohos") {
var fSystemVersion = navigator.sv;
if (fSystemVersion >= 2.0 && fSystemVersion < 5.0) {
//这个步骤为因为HTC部分手机,作出了一个奇葩的决定:将DroidSansFallback架空,引入DFHEIA5A和DFHEIA7A两个字体文件。
-18
View File
@@ -659,10 +659,7 @@ interface _textBitmap
interface conch {
onerror:Function;
__onerror:Function;
callWebviewJS(methodName:string,parms:string,callbackMethodName:string);
exp:any;
showWebView();
hideWebView();
captureScreen(cb:(ab:ArrayBuffer,w:number,h:number)=>void):void;
saveAsPng(ab:ArrayBuffer,w:number,h:number,file:string);
loadingAuto:boolean;
@@ -699,21 +696,6 @@ interface conch {
showLoadingView(b: boolean): void;
showWaiting(b: boolean): void;
showAssistantTouch(b: boolean): void;
/**
* webview
*/
setExternalLink(url: string): void;
/**
* webview
* @param url {string} url地址
* @param posx {number} weview的左上角位置
* @param posy {number} webivew的左上角位置
* @param width {number} webview的宽度
* @param height {number} webview的高度
* @param canclose {boolean} webview是否可以被关掉
*/
setExternalLinkEx(url:string,posx:number, posy:number,width:number,height:number,canclose:boolean):void;
closeExternalLink(): void;
setScreenWakeLock(b: boolean): void;
setUrlToLower(b: boolean): void;
setFontFace(family: string, src: string, type: string): void;
+3 -3
View File
@@ -2821,7 +2821,7 @@ class GLCommandEncoder {
if (supports("GL_OES_depth_texture") || supports("GL_ARB_depth_texture") || supports("GL_ANGLE_depth_texture"))
result.push("WEBGL_depth_texture");
if (version.indexOf("OpenGL ES 3.") != -1) {
if (conchConfig.getOS() == "Conch-android") {
if (conchConfig.getOS() == "Conch-android" || conchConfig.getOS() == "Conch-ohos") {
result.push("WEBGL_compressed_texture_etc");
}
}
@@ -2949,7 +2949,7 @@ class GLCommandEncoder {
else if (name.indexOf('WEBGL_depth_texture') != -1 && ((supports("GL_OES_depth_texture") || supports("GL_ARB_depth_texture") || supports("GL_ANGLE_depth_texture")))) {
return { UNSIGNED_INT_24_8_WEBGL: 34042 };
}
else if (name.indexOf('WEBGL_compressed_texture_astc') != -1 && (extention.indexOf('GL_OES_texture_compression_astc') != -1 || extention.indexOf('GL_KHR_texture_compression_astc') != -1 || (conchConfig.getOS() == "Conch-android" && version.indexOf("OpenGL ES 3.") != -1 && version.indexOf("OpenGL ES 3.0") == -1))) {
else if (name.indexOf('WEBGL_compressed_texture_astc') != -1 && (extention.indexOf('GL_OES_texture_compression_astc') != -1 || extention.indexOf('GL_KHR_texture_compression_astc') != -1 || ((conchConfig.getOS() == "Conch-android" || conchConfig.getOS() == "Conch-ohos") && version.indexOf("OpenGL ES 3.") != -1 && version.indexOf("OpenGL ES 3.0") == -1))) {
return {
COMPRESSED_RGBA_ASTC_4x4_KHR: 0x93B0,
COMPRESSED_RGBA_ASTC_5x4_KHR: 0x93B1,
@@ -2981,7 +2981,7 @@ class GLCommandEncoder {
COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR: 0x93DD,
};
}
else if (name.indexOf('WEBGL_compressed_texture_etc') != -1 && conchConfig.getOS() == "Conch-android" && version.indexOf("OpenGL ES 3.") != -1) {
else if (name.indexOf('WEBGL_compressed_texture_etc') != -1 && (conchConfig.getOS() == "Conch-android" || conchConfig.getOS() == "Conch-ohos") && version.indexOf("OpenGL ES 3.") != -1) {
return {
COMPRESSED_R11_EAC: 0x9270,
COMPRESSED_SIGNED_R11_EAC: 0x9271,
+1 -1
View File
@@ -59,7 +59,7 @@ function initFreeType() {
if (sOS == "Conch-window") {
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile("C:/Windows/Fonts/simhei.ttf");
}
else if (sOS == "Conch-android") {
else if (sOS == "Conch-android" || sOS == "Conch-ohos") {
var fSystemVersion = navigator.sv;
if (fSystemVersion >= 2.0 && fSystemVersion < 5.0) {
bRet = _conchTextCanvas.initFreeTypeDefaultFontFromFile("/system/fonts/DFHEIA5A.ttf");
+60
View File
@@ -0,0 +1,60 @@
cmake_minimum_required(VERSION 3.6)
project(thirdParty)
add_library(${PROJECT_NAME} STATIC empty.cpp)
#
include_directories(${LAYA_ROOT_PATH}/ThirdParty/ohos-specific/aki/include)
# ArkTs FFI framework, refer to: https://gitee.com/openharmony-sig/aki/tree/master
add_subdirectory(ohos-specific/aki)
target_link_libraries(${PROJECT_NAME}
aki_jsbind
)
# ------------------------------ V8
add_library(v8_monolith STATIC IMPORTED GLOBAL)
set_target_properties(v8_monolith PROPERTIES
IMPORTED_LOCATION ${LAYA_ROOT_PATH}/ThirdParty/v8_9.1/lib/ohos/libv8_monolith.a
INTERFACE_INCLUDE_DIRECTORIES ${LAYA_ROOT_PATH}/ThirdParty/v8_9.1/include
)
target_link_libraries(${PROJECT_NAME}
${LAYA_ROOT_PATH}/ThirdParty/curl/lib/ohos/libcurl.a
${LAYA_ROOT_PATH}/ThirdParty/websockets/lib/ohos/libwebsockets.a
${LAYA_ROOT_PATH}/ThirdParty/jpeg-turbo/lib/ohos/libjpeg.a
${LAYA_ROOT_PATH}/ThirdParty/jpeg-turbo/lib/ohos/libturbojpeg.a
${LAYA_ROOT_PATH}/ThirdParty/png/lib/ohos/libpng.a
${LAYA_ROOT_PATH}/ThirdParty/freetype/lib/ohos/libfreetype.a
${LAYA_ROOT_PATH}/ThirdParty/zip/lib/ohos/libzip.a
${LAYA_ROOT_PATH}/ThirdParty/ogg/lib/ohos/libvorbisfile.a
${LAYA_ROOT_PATH}/ThirdParty/ogg/lib/ohos/libvorbis.a
${LAYA_ROOT_PATH}/ThirdParty/ogg/lib/ohos/libogg.a
${LAYA_ROOT_PATH}/ThirdParty/openssl/lib/ohos/libssl.a
${LAYA_ROOT_PATH}/ThirdParty/openssl/lib/ohos/libcrypto.a
${LAYA_ROOT_PATH}/ThirdParty/bullet/lib/ohos/libBulletDynamics.a
${LAYA_ROOT_PATH}/ThirdParty/bullet/lib/ohos/libBulletCollision.a
${LAYA_ROOT_PATH}/ThirdParty/bullet/lib/ohos/libLinearMath.a
${LAYA_ROOT_PATH}/ThirdParty/zlib/lib/ohos/libz.a
)
target_include_directories(${PROJECT_NAME} PUBLIC
${LAYA_ROOT_PATH}/ThirdParty/curl/include/ohos
${LAYA_ROOT_PATH}/ThirdParty/png/include/ohos
${LAYA_ROOT_PATH}/ThirdParty/jpeg-turbo/include/ohos
${LAYA_ROOT_PATH}/ThirdParty/freetype/include/ohos
${LAYA_ROOT_PATH}/ThirdParty/zip/include/ohos
${LAYA_ROOT_PATH}/ThirdParty/v8_9.1/include
${LAYA_ROOT_PATH}/ThirdParty/ogg/include/ohos
${LAYA_ROOT_PATH}/ThirdParty/websockets/include/ohos
${LAYA_ROOT_PATH}/ThirdParty/openssl/include/ohos
${LAYA_ROOT_PATH}/ThirdParty/openal/include/ohos
${LAYA_ROOT_PATH}/ThirdParty/bullet/include/ohos/bullet
)
# put "thirdParty" into External folder, too
set_target_properties(${PROJECT_NAME}
PROPERTIES
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
FOLDER "ThirdParty"
)
@@ -18,7 +18,7 @@ subject to the following restrictions:
#include "LinearMath/btVector3.h"
#include "BulletDynamics/Dynamics/btActionInterface.h"
#include <cstring>
class btCollisionShape;
class btRigidBody;
class btCollisionWorld;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,83 @@
/*
bParse
Copyright (c) 2006-2010 Charlie C & Erwin Coumans http://gamekit.googlecode.com
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B3_BULLET_FILE_H
#define B3_BULLET_FILE_H
#include "b3File.h"
#include "Bullet3Common/b3AlignedObjectArray.h"
#include "b3Defines.h"
#include "Bullet3Serialize/Bullet2FileLoader/b3Serializer.h"
namespace bParse {
// ----------------------------------------------------- //
class b3BulletFile : public bFile
{
protected:
char* m_DnaCopy;
public:
b3AlignedObjectArray<bStructHandle*> m_softBodies;
b3AlignedObjectArray<bStructHandle*> m_rigidBodies;
b3AlignedObjectArray<bStructHandle*> m_collisionObjects;
b3AlignedObjectArray<bStructHandle*> m_collisionShapes;
b3AlignedObjectArray<bStructHandle*> m_constraints;
b3AlignedObjectArray<bStructHandle*> m_bvhs;
b3AlignedObjectArray<bStructHandle*> m_triangleInfoMaps;
b3AlignedObjectArray<bStructHandle*> m_dynamicsWorldInfo;
b3AlignedObjectArray<char*> m_dataBlocks;
b3BulletFile();
b3BulletFile(const char* fileName);
b3BulletFile(char *memoryBuffer, int len);
virtual ~b3BulletFile();
virtual void addDataBlock(char* dataBlock);
// experimental
virtual int write(const char* fileName, bool fixupPointers=false);
virtual void parse(int verboseMode);
virtual void parseData();
virtual void writeDNA(FILE* fp);
void addStruct(const char* structType,void* data, int len, void* oldPtr, int code);
};
};
#endif //B3_BULLET_FILE_H
@@ -0,0 +1,92 @@
/*
bParse
Copyright (c) 2006-2009 Charlie C & Erwin Coumans http://gamekit.googlecode.com
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef __BCHUNK_H__
#define __BCHUNK_H__
#if defined (_WIN32) && ! defined (__MINGW32__)
#define b3Long64 __int64
#elif defined (__MINGW32__)
#include <stdint.h>
#define b3Long64 int64_t
#else
#define b3Long64 long long
#endif
namespace bParse {
// ----------------------------------------------------- //
class bChunkPtr4
{
public:
bChunkPtr4(){}
int code;
int len;
union
{
int m_uniqueInt;
};
int dna_nr;
int nr;
};
// ----------------------------------------------------- //
class bChunkPtr8
{
public:
bChunkPtr8(){}
int code, len;
union
{
b3Long64 oldPrev;
int m_uniqueInts[2];
};
int dna_nr, nr;
};
// ----------------------------------------------------- //
class bChunkInd
{
public:
bChunkInd(){}
int code, len;
void *oldPtr;
int dna_nr, nr;
};
// ----------------------------------------------------- //
class ChunkUtils
{
public:
// file chunk offset
static int getOffset(int flags);
// endian utils
static short swapShort(short sht);
static int swapInt(int inte);
static b3Long64 swapLong64(b3Long64 lng);
};
const int CHUNK_HEADER_LEN = ((sizeof(bChunkInd)));
const bool VOID_IS_8 = ((sizeof(void*)==8));
}
#endif//__BCHUNK_H__
@@ -0,0 +1,39 @@
/*
bParse
Copyright (c) 2006-2009 Charlie C & Erwin Coumans http://gamekit.googlecode.com
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef __BCOMMON_H__
#define __BCOMMON_H__
#include <assert.h>
//#include "bLog.h"
#include "Bullet3Common/b3AlignedObjectArray.h"
#include "Bullet3Common/b3HashMap.h"
namespace bParse {
class bMain;
class bFileData;
class bFile;
class bDNA;
// delete void* undefined
typedef struct bStructHandle {int unused;}bStructHandle;
typedef b3AlignedObjectArray<bStructHandle*> bListBasePtr;
typedef b3HashMap<b3HashPtr, bStructHandle*> bPtrMap;
}
#endif//__BCOMMON_H__
@@ -0,0 +1,110 @@
/*
bParse
Copyright (c) 2006-2009 Charlie C & Erwin Coumans http://gamekit.googlecode.com
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef __BDNA_H__
#define __BDNA_H__
#include "b3Common.h"
namespace bParse {
struct bNameInfo
{
char* m_name;
bool m_isPointer;
int m_dim0;
int m_dim1;
};
class bDNA
{
public:
bDNA();
~bDNA();
void init(char *data, int len, bool swap=false);
int getArraySize(char* str);
int getArraySizeNew(short name)
{
const bNameInfo& nameInfo = m_Names[name];
return nameInfo.m_dim0*nameInfo.m_dim1;
}
int getElementSize(short type, short name)
{
const bNameInfo& nameInfo = m_Names[name];
int size = nameInfo.m_isPointer ? mPtrLen*nameInfo.m_dim0*nameInfo.m_dim1 : mTlens[type]*nameInfo.m_dim0*nameInfo.m_dim1;
return size;
}
int getNumNames() const
{
return m_Names.size();
}
char *getName(int ind);
char *getType(int ind);
short *getStruct(int ind);
short getLength(int ind);
int getReverseType(short type);
int getReverseType(const char *type);
int getNumStructs();
//
bool lessThan(bDNA* other);
void initCmpFlags(bDNA *memDNA);
bool flagNotEqual(int dna_nr);
bool flagEqual(int dna_nr);
bool flagNone(int dna_nr);
int getPointerSize();
void dumpTypeDefinitions();
private:
enum FileDNAFlags
{
FDF_NONE=0,
FDF_STRUCT_NEQU,
FDF_STRUCT_EQU
};
void initRecurseCmpFlags(int i);
b3AlignedObjectArray<int> mCMPFlags;
b3AlignedObjectArray<bNameInfo> m_Names;
b3AlignedObjectArray<char*> mTypes;
b3AlignedObjectArray<short*> mStructs;
b3AlignedObjectArray<short> mTlens;
b3HashMap<b3HashInt, int> mStructReverse;
b3HashMap<b3HashString,int> mTypeLookup;
int mPtrLen;
};
}
#endif//__BDNA_H__
@@ -0,0 +1,136 @@
/* Copyright (C) 2006-2009 Charlie C & Erwin Coumans http://gamekit.googlecode.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef __B_DEFINES_H__
#define __B_DEFINES_H__
// MISC defines, see BKE_global.h, BKE_utildefines.h
#define B3_SIZEOFBLENDERHEADER 12
// ------------------------------------------------------------
#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
# define B3_MAKE_ID(a,b,c,d) ( (int)(a)<<24 | (int)(b)<<16 | (c)<<8 | (d) )
#else
# define B3_MAKE_ID(a,b,c,d) ( (int)(d)<<24 | (int)(c)<<16 | (b)<<8 | (a) )
#endif
// ------------------------------------------------------------
#if defined(__sgi) || defined(__sparc) || defined(__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
# define B3_MAKE_ID2(c, d) ( (c)<<8 | (d) )
#else
# define B3_MAKE_ID2(c, d) ( (d)<<8 | (c) )
#endif
// ------------------------------------------------------------
#define B3_ID_SCE B3_MAKE_ID2('S', 'C')
#define B3_ID_LI B3_MAKE_ID2('L', 'I')
#define B3_ID_OB B3_MAKE_ID2('O', 'B')
#define B3_ID_ME B3_MAKE_ID2('M', 'E')
#define B3_ID_CU B3_MAKE_ID2('C', 'U')
#define B3_ID_MB B3_MAKE_ID2('M', 'B')
#define B3_ID_MA B3_MAKE_ID2('M', 'A')
#define B3_ID_TE B3_MAKE_ID2('T', 'E')
#define B3_ID_IM B3_MAKE_ID2('I', 'M')
#define B3_ID_IK B3_MAKE_ID2('I', 'K')
#define B3_ID_WV B3_MAKE_ID2('W', 'V')
#define B3_ID_LT B3_MAKE_ID2('L', 'T')
#define B3_ID_SE B3_MAKE_ID2('S', 'E')
#define B3_ID_LF B3_MAKE_ID2('L', 'F')
#define B3_ID_LA B3_MAKE_ID2('L', 'A')
#define B3_ID_CA B3_MAKE_ID2('C', 'A')
#define B3_ID_IP B3_MAKE_ID2('I', 'P')
#define B3_ID_KE B3_MAKE_ID2('K', 'E')
#define B3_ID_WO B3_MAKE_ID2('W', 'O')
#define B3_ID_SCR B3_MAKE_ID2('S', 'R')
#define B3_ID_VF B3_MAKE_ID2('V', 'F')
#define B3_ID_TXT B3_MAKE_ID2('T', 'X')
#define B3_ID_SO B3_MAKE_ID2('S', 'O')
#define B3_ID_SAMPLE B3_MAKE_ID2('S', 'A')
#define B3_ID_GR B3_MAKE_ID2('G', 'R')
#define B3_ID_ID B3_MAKE_ID2('I', 'D')
#define B3_ID_AR B3_MAKE_ID2('A', 'R')
#define B3_ID_AC B3_MAKE_ID2('A', 'C')
#define B3_ID_SCRIPT B3_MAKE_ID2('P', 'Y')
#define B3_ID_FLUIDSIM B3_MAKE_ID2('F', 'S')
#define B3_ID_NT B3_MAKE_ID2('N', 'T')
#define B3_ID_BR B3_MAKE_ID2('B', 'R')
#define B3_ID_SEQ B3_MAKE_ID2('S', 'Q')
#define B3_ID_CO B3_MAKE_ID2('C', 'O')
#define B3_ID_PO B3_MAKE_ID2('A', 'C')
#define B3_ID_NLA B3_MAKE_ID2('N', 'L')
#define B3_ID_VS B3_MAKE_ID2('V', 'S')
#define B3_ID_VN B3_MAKE_ID2('V', 'N')
// ------------------------------------------------------------
#define B3_FORM B3_MAKE_ID('F','O','R','M')
#define B3_DDG1 B3_MAKE_ID('3','D','G','1')
#define B3_DDG2 B3_MAKE_ID('3','D','G','2')
#define B3_DDG3 B3_MAKE_ID('3','D','G','3')
#define B3_DDG4 B3_MAKE_ID('3','D','G','4')
#define B3_GOUR B3_MAKE_ID('G','O','U','R')
#define B3_BLEN B3_MAKE_ID('B','L','E','N')
#define B3_DER_ B3_MAKE_ID('D','E','R','_')
#define B3_V100 B3_MAKE_ID('V','1','0','0')
#define B3_DATA B3_MAKE_ID('D','A','T','A')
#define B3_GLOB B3_MAKE_ID('G','L','O','B')
#define B3_IMAG B3_MAKE_ID('I','M','A','G')
#define B3_TEST B3_MAKE_ID('T','E','S','T')
#define B3_USER B3_MAKE_ID('U','S','E','R')
// ------------------------------------------------------------
#define B3_DNA1 B3_MAKE_ID('D','N','A','1')
#define B3_REND B3_MAKE_ID('R','E','N','D')
#define B3_ENDB B3_MAKE_ID('E','N','D','B')
#define B3_NAME B3_MAKE_ID('N','A','M','E')
#define B3_SDNA B3_MAKE_ID('S','D','N','A')
#define B3_TYPE B3_MAKE_ID('T','Y','P','E')
#define B3_TLEN B3_MAKE_ID('T','L','E','N')
#define B3_STRC B3_MAKE_ID('S','T','R','C')
// ------------------------------------------------------------
#define B3_SWITCH_INT(a) { \
char s_i, *p_i; \
p_i= (char *)&(a); \
s_i=p_i[0]; p_i[0]=p_i[3]; p_i[3]=s_i; \
s_i=p_i[1]; p_i[1]=p_i[2]; p_i[2]=s_i; }
// ------------------------------------------------------------
#define B3_SWITCH_SHORT(a) { \
char s_i, *p_i; \
p_i= (char *)&(a); \
s_i=p_i[0]; p_i[0]=p_i[1]; p_i[1]=s_i; }
// ------------------------------------------------------------
#define B3_SWITCH_LONGINT(a) { \
char s_i, *p_i; \
p_i= (char *)&(a); \
s_i=p_i[0]; p_i[0]=p_i[7]; p_i[7]=s_i; \
s_i=p_i[1]; p_i[1]=p_i[6]; p_i[6]=s_i; \
s_i=p_i[2]; p_i[2]=p_i[5]; p_i[5]=s_i; \
s_i=p_i[3]; p_i[3]=p_i[4]; p_i[4]=s_i; }
#endif//__B_DEFINES_H__
@@ -0,0 +1,165 @@
/*
bParse
Copyright (c) 2006-2009 Charlie C & Erwin Coumans http://gamekit.googlecode.com
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef __BFILE_H__
#define __BFILE_H__
#include "b3Common.h"
#include "b3Chunk.h"
#include <stdio.h>
namespace bParse {
// ----------------------------------------------------- //
enum bFileFlags
{
FD_INVALID =0,
FD_OK =1,
FD_VOID_IS_8 =2,
FD_ENDIAN_SWAP =4,
FD_FILE_64 =8,
FD_BITS_VARIES =16,
FD_VERSION_VARIES = 32,
FD_DOUBLE_PRECISION =64,
FD_BROKEN_DNA = 128
};
enum bFileVerboseMode
{
FD_VERBOSE_EXPORT_XML = 1,
FD_VERBOSE_DUMP_DNA_TYPE_DEFINITIONS = 2,
FD_VERBOSE_DUMP_CHUNKS = 4,
FD_VERBOSE_DUMP_FILE_INFO=8,
};
// ----------------------------------------------------- //
class bFile
{
protected:
char m_headerString[7];
bool mOwnsBuffer;
char* mFileBuffer;
int mFileLen;
int mVersion;
bPtrMap mLibPointers;
int mDataStart;
bDNA* mFileDNA;
bDNA* mMemoryDNA;
b3AlignedObjectArray<char*> m_pointerFixupArray;
b3AlignedObjectArray<char*> m_pointerPtrFixupArray;
b3AlignedObjectArray<bChunkInd> m_chunks;
b3HashMap<b3HashPtr, bChunkInd> m_chunkPtrPtrMap;
//
bPtrMap mDataPointers;
int mFlags;
// ////////////////////////////////////////////////////////////////////////////
// buffer offset util
int getNextBlock(bChunkInd *dataChunk, const char *dataPtr, const int flags);
void safeSwapPtr(char *dst, const char *src);
virtual void parseHeader();
virtual void parseData() = 0;
void resolvePointersMismatch();
void resolvePointersChunk(const bChunkInd& dataChunk, int verboseMode);
int resolvePointersStructRecursive(char *strcPtr, int old_dna, int verboseMode, int recursion);
//void swapPtr(char *dst, char *src);
void parseStruct(char *strcPtr, char *dtPtr, int old_dna, int new_dna, bool fixupPointers);
void getMatchingFileDNA(short* old, const char* lookupName, const char* lookupType, char *strcData, char *data, bool fixupPointers);
char* getFileElement(short *firstStruct, char *lookupName, char *lookupType, char *data, short **foundPos);
void swap(char *head, class bChunkInd& ch, bool ignoreEndianFlag);
void swapData(char *data, short type, int arraySize, bool ignoreEndianFlag);
void swapStruct(int dna_nr, char *data, bool ignoreEndianFlag);
void swapLen(char *dataPtr);
void swapDNA(char* ptr);
char* readStruct(char *head, class bChunkInd& chunk);
char *getAsString(int code);
void parseInternal(int verboseMode, char* memDna,int memDnaLength);
public:
bFile(const char *filename, const char headerString[7]);
//todo: make memoryBuffer const char
//bFile( const char *memoryBuffer, int len);
bFile( char *memoryBuffer, int len, const char headerString[7]);
virtual ~bFile();
bDNA* getFileDNA()
{
return mFileDNA;
}
virtual void addDataBlock(char* dataBlock) = 0;
int getFlags() const
{
return mFlags;
}
bPtrMap& getLibPointers()
{
return mLibPointers;
}
void* findLibPointer(void *ptr);
bool ok();
virtual void parse(int verboseMode) = 0;
virtual int write(const char* fileName, bool fixupPointers=false) = 0;
virtual void writeChunks(FILE* fp, bool fixupPointers );
virtual void writeDNA(FILE* fp) = 0;
void updateOldPointers();
void resolvePointers(int verboseMode);
void dumpChunks(bDNA* dna);
int getVersion() const
{
return mVersion;
}
//pre-swap the endianness, so that data loaded on a target with different endianness doesn't need to be swapped
void preSwap();
void writeFile(const char* fileName);
};
}
#endif//__BFILE_H__
@@ -0,0 +1,639 @@
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B3_SERIALIZER_H
#define B3_SERIALIZER_H
#include "Bullet3Common/b3Scalar.h" // has definitions like B3_FORCE_INLINE
#include "Bullet3Common/b3StackAlloc.h"
#include "Bullet3Common/b3HashMap.h"
#if !defined( __CELLOS_LV2__) && !defined(__MWERKS__)
#include <memory.h>
#endif
#include <string.h>
extern char b3s_bulletDNAstr[];
extern int b3s_bulletDNAlen;
extern char b3s_bulletDNAstr64[];
extern int b3s_bulletDNAlen64;
B3_FORCE_INLINE int b3StrLen(const char* str)
{
if (!str)
return(0);
int len = 0;
while (*str != 0)
{
str++;
len++;
}
return len;
}
class b3Chunk
{
public:
int m_chunkCode;
int m_length;
void *m_oldPtr;
int m_dna_nr;
int m_number;
};
enum b3SerializationFlags
{
B3_SERIALIZE_NO_BVH = 1,
B3_SERIALIZE_NO_TRIANGLEINFOMAP = 2,
B3_SERIALIZE_NO_DUPLICATE_ASSERT = 4
};
class b3Serializer
{
public:
virtual ~b3Serializer() {}
virtual const unsigned char* getBufferPointer() const = 0;
virtual int getCurrentBufferSize() const = 0;
virtual b3Chunk* allocate(size_t size, int numElements) = 0;
virtual void finalizeChunk(b3Chunk* chunk, const char* structType, int chunkCode,void* oldPtr)= 0;
virtual void* findPointer(void* oldPtr) = 0;
virtual void* getUniquePointer(void*oldPtr) = 0;
virtual void startSerialization() = 0;
virtual void finishSerialization() = 0;
virtual const char* findNameForPointer(const void* ptr) const = 0;
virtual void registerNameForPointer(const void* ptr, const char* name) = 0;
virtual void serializeName(const char* ptr) = 0;
virtual int getSerializationFlags() const = 0;
virtual void setSerializationFlags(int flags) = 0;
};
#define B3_HEADER_LENGTH 12
#if defined(__sgi) || defined (__sparc) || defined (__sparc__) || defined (__PPC__) || defined (__ppc__) || defined (__BIG_ENDIAN__)
# define B3_MAKE_ID(a,b,c,d) ( (int)(a)<<24 | (int)(b)<<16 | (c)<<8 | (d) )
#else
# define B3_MAKE_ID(a,b,c,d) ( (int)(d)<<24 | (int)(c)<<16 | (b)<<8 | (a) )
#endif
#define B3_SOFTBODY_CODE B3_MAKE_ID('S','B','D','Y')
#define B3_COLLISIONOBJECT_CODE B3_MAKE_ID('C','O','B','J')
#define B3_RIGIDBODY_CODE B3_MAKE_ID('R','B','D','Y')
#define B3_CONSTRAINT_CODE B3_MAKE_ID('C','O','N','S')
#define B3_BOXSHAPE_CODE B3_MAKE_ID('B','O','X','S')
#define B3_QUANTIZED_BVH_CODE B3_MAKE_ID('Q','B','V','H')
#define B3_TRIANLGE_INFO_MAP B3_MAKE_ID('T','M','A','P')
#define B3_SHAPE_CODE B3_MAKE_ID('S','H','A','P')
#define B3_ARRAY_CODE B3_MAKE_ID('A','R','A','Y')
#define B3_SBMATERIAL_CODE B3_MAKE_ID('S','B','M','T')
#define B3_SBNODE_CODE B3_MAKE_ID('S','B','N','D')
#define B3_DYNAMICSWORLD_CODE B3_MAKE_ID('D','W','L','D')
#define B3_DNA_CODE B3_MAKE_ID('D','N','A','1')
struct b3PointerUid
{
union
{
void* m_ptr;
int m_uniqueIds[2];
};
};
///The b3DefaultSerializer is the main Bullet serialization class.
///The constructor takes an optional argument for backwards compatibility, it is recommended to leave this empty/zero.
class b3DefaultSerializer : public b3Serializer
{
b3AlignedObjectArray<char*> mTypes;
b3AlignedObjectArray<short*> mStructs;
b3AlignedObjectArray<short> mTlens;
b3HashMap<b3HashInt, int> mStructReverse;
b3HashMap<b3HashString,int> mTypeLookup;
b3HashMap<b3HashPtr,void*> m_chunkP;
b3HashMap<b3HashPtr,const char*> m_nameMap;
b3HashMap<b3HashPtr,b3PointerUid> m_uniquePointers;
int m_uniqueIdGenerator;
int m_totalSize;
unsigned char* m_buffer;
int m_currentSize;
void* m_dna;
int m_dnaLength;
int m_serializationFlags;
b3AlignedObjectArray<b3Chunk*> m_chunkPtrs;
protected:
virtual void* findPointer(void* oldPtr)
{
void** ptr = m_chunkP.find(oldPtr);
if (ptr && *ptr)
return *ptr;
return 0;
}
void writeDNA()
{
b3Chunk* dnaChunk = allocate(m_dnaLength,1);
memcpy(dnaChunk->m_oldPtr,m_dna,m_dnaLength);
finalizeChunk(dnaChunk,"DNA1",B3_DNA_CODE, m_dna);
}
int getReverseType(const char *type) const
{
b3HashString key(type);
const int* valuePtr = mTypeLookup.find(key);
if (valuePtr)
return *valuePtr;
return -1;
}
void initDNA(const char* bdnaOrg,int dnalen)
{
///was already initialized
if (m_dna)
return;
int littleEndian= 1;
littleEndian= ((char*)&littleEndian)[0];
m_dna = b3AlignedAlloc(dnalen,16);
memcpy(m_dna,bdnaOrg,dnalen);
m_dnaLength = dnalen;
int *intPtr=0;
short *shtPtr=0;
char *cp = 0;int dataLen =0;
intPtr = (int*)m_dna;
/*
SDNA (4 bytes) (magic number)
NAME (4 bytes)
<nr> (4 bytes) amount of names (int)
<string>
<string>
*/
if (strncmp((const char*)m_dna, "SDNA", 4)==0)
{
// skip ++ NAME
intPtr++; intPtr++;
}
// Parse names
if (!littleEndian)
*intPtr = b3SwapEndian(*intPtr);
dataLen = *intPtr;
intPtr++;
cp = (char*)intPtr;
int i;
for ( i=0; i<dataLen; i++)
{
while (*cp)cp++;
cp++;
}
cp = b3AlignPointer(cp,4);
/*
TYPE (4 bytes)
<nr> amount of types (int)
<string>
<string>
*/
intPtr = (int*)cp;
b3Assert(strncmp(cp, "TYPE", 4)==0); intPtr++;
if (!littleEndian)
*intPtr = b3SwapEndian(*intPtr);
dataLen = *intPtr;
intPtr++;
cp = (char*)intPtr;
for (i=0; i<dataLen; i++)
{
mTypes.push_back(cp);
while (*cp)cp++;
cp++;
}
cp = b3AlignPointer(cp,4);
/*
TLEN (4 bytes)
<len> (short) the lengths of types
<len>
*/
// Parse type lens
intPtr = (int*)cp;
b3Assert(strncmp(cp, "TLEN", 4)==0); intPtr++;
dataLen = (int)mTypes.size();
shtPtr = (short*)intPtr;
for (i=0; i<dataLen; i++, shtPtr++)
{
if (!littleEndian)
shtPtr[0] = b3SwapEndian(shtPtr[0]);
mTlens.push_back(shtPtr[0]);
}
if (dataLen & 1) shtPtr++;
/*
STRC (4 bytes)
<nr> amount of structs (int)
<typenr>
<nr_of_elems>
<typenr>
<namenr>
<typenr>
<namenr>
*/
intPtr = (int*)shtPtr;
cp = (char*)intPtr;
b3Assert(strncmp(cp, "STRC", 4)==0); intPtr++;
if (!littleEndian)
*intPtr = b3SwapEndian(*intPtr);
dataLen = *intPtr ;
intPtr++;
shtPtr = (short*)intPtr;
for (i=0; i<dataLen; i++)
{
mStructs.push_back (shtPtr);
if (!littleEndian)
{
shtPtr[0]= b3SwapEndian(shtPtr[0]);
shtPtr[1]= b3SwapEndian(shtPtr[1]);
int len = shtPtr[1];
shtPtr+= 2;
for (int a=0; a<len; a++, shtPtr+=2)
{
shtPtr[0]= b3SwapEndian(shtPtr[0]);
shtPtr[1]= b3SwapEndian(shtPtr[1]);
}
} else
{
shtPtr+= (2*shtPtr[1])+2;
}
}
// build reverse lookups
for (i=0; i<(int)mStructs.size(); i++)
{
short *strc = mStructs.at(i);
mStructReverse.insert(strc[0], i);
mTypeLookup.insert(b3HashString(mTypes[strc[0]]),i);
}
}
public:
b3DefaultSerializer(int totalSize=0)
:m_totalSize(totalSize),
m_currentSize(0),
m_dna(0),
m_dnaLength(0),
m_serializationFlags(0)
{
m_buffer = m_totalSize?(unsigned char*)b3AlignedAlloc(totalSize,16):0;
const bool VOID_IS_8 = ((sizeof(void*)==8));
#ifdef B3_INTERNAL_UPDATE_SERIALIZATION_STRUCTURES
if (VOID_IS_8)
{
#if _WIN64
initDNA((const char*)b3s_bulletDNAstr64,b3s_bulletDNAlen64);
#else
b3Assert(0);
#endif
} else
{
#ifndef _WIN64
initDNA((const char*)b3s_bulletDNAstr,b3s_bulletDNAlen);
#else
b3Assert(0);
#endif
}
#else //B3_INTERNAL_UPDATE_SERIALIZATION_STRUCTURES
if (VOID_IS_8)
{
initDNA((const char*)b3s_bulletDNAstr64,b3s_bulletDNAlen64);
} else
{
initDNA((const char*)b3s_bulletDNAstr,b3s_bulletDNAlen);
}
#endif //B3_INTERNAL_UPDATE_SERIALIZATION_STRUCTURES
}
virtual ~b3DefaultSerializer()
{
if (m_buffer)
b3AlignedFree(m_buffer);
if (m_dna)
b3AlignedFree(m_dna);
}
void writeHeader(unsigned char* buffer) const
{
#ifdef B3_USE_DOUBLE_PRECISION
memcpy(buffer, "BULLETd", 7);
#else
memcpy(buffer, "BULLETf", 7);
#endif //B3_USE_DOUBLE_PRECISION
int littleEndian= 1;
littleEndian= ((char*)&littleEndian)[0];
if (sizeof(void*)==8)
{
buffer[7] = '-';
} else
{
buffer[7] = '_';
}
if (littleEndian)
{
buffer[8]='v';
} else
{
buffer[8]='V';
}
buffer[9] = '2';
buffer[10] = '8';
buffer[11] = '1';
}
virtual void startSerialization()
{
m_uniqueIdGenerator= 1;
if (m_totalSize)
{
unsigned char* buffer = internalAlloc(B3_HEADER_LENGTH);
writeHeader(buffer);
}
}
virtual void finishSerialization()
{
writeDNA();
//if we didn't pre-allocate a buffer, we need to create a contiguous buffer now
int mysize = 0;
if (!m_totalSize)
{
if (m_buffer)
b3AlignedFree(m_buffer);
m_currentSize += B3_HEADER_LENGTH;
m_buffer = (unsigned char*)b3AlignedAlloc(m_currentSize,16);
unsigned char* currentPtr = m_buffer;
writeHeader(m_buffer);
currentPtr += B3_HEADER_LENGTH;
mysize+=B3_HEADER_LENGTH;
for (int i=0;i< m_chunkPtrs.size();i++)
{
int curLength = sizeof(b3Chunk)+m_chunkPtrs[i]->m_length;
memcpy(currentPtr,m_chunkPtrs[i], curLength);
b3AlignedFree(m_chunkPtrs[i]);
currentPtr+=curLength;
mysize+=curLength;
}
}
mTypes.clear();
mStructs.clear();
mTlens.clear();
mStructReverse.clear();
mTypeLookup.clear();
m_chunkP.clear();
m_nameMap.clear();
m_uniquePointers.clear();
m_chunkPtrs.clear();
}
virtual void* getUniquePointer(void*oldPtr)
{
if (!oldPtr)
return 0;
b3PointerUid* uptr = (b3PointerUid*)m_uniquePointers.find(oldPtr);
if (uptr)
{
return uptr->m_ptr;
}
m_uniqueIdGenerator++;
b3PointerUid uid;
uid.m_uniqueIds[0] = m_uniqueIdGenerator;
uid.m_uniqueIds[1] = m_uniqueIdGenerator;
m_uniquePointers.insert(oldPtr,uid);
return uid.m_ptr;
}
virtual const unsigned char* getBufferPointer() const
{
return m_buffer;
}
virtual int getCurrentBufferSize() const
{
return m_currentSize;
}
virtual void finalizeChunk(b3Chunk* chunk, const char* structType, int chunkCode,void* oldPtr)
{
if (!(m_serializationFlags&B3_SERIALIZE_NO_DUPLICATE_ASSERT))
{
b3Assert(!findPointer(oldPtr));
}
chunk->m_dna_nr = getReverseType(structType);
chunk->m_chunkCode = chunkCode;
void* uniquePtr = getUniquePointer(oldPtr);
m_chunkP.insert(oldPtr,uniquePtr);//chunk->m_oldPtr);
chunk->m_oldPtr = uniquePtr;//oldPtr;
}
virtual unsigned char* internalAlloc(size_t size)
{
unsigned char* ptr = 0;
if (m_totalSize)
{
ptr = m_buffer+m_currentSize;
m_currentSize += int(size);
b3Assert(m_currentSize<m_totalSize);
} else
{
ptr = (unsigned char*)b3AlignedAlloc(size,16);
m_currentSize += int(size);
}
return ptr;
}
virtual b3Chunk* allocate(size_t size, int numElements)
{
unsigned char* ptr = internalAlloc(int(size)*numElements+sizeof(b3Chunk));
unsigned char* data = ptr + sizeof(b3Chunk);
b3Chunk* chunk = (b3Chunk*)ptr;
chunk->m_chunkCode = 0;
chunk->m_oldPtr = data;
chunk->m_length = int(size)*numElements;
chunk->m_number = numElements;
m_chunkPtrs.push_back(chunk);
return chunk;
}
virtual const char* findNameForPointer(const void* ptr) const
{
const char*const * namePtr = m_nameMap.find(ptr);
if (namePtr && *namePtr)
return *namePtr;
return 0;
}
virtual void registerNameForPointer(const void* ptr, const char* name)
{
m_nameMap.insert(ptr,name);
}
virtual void serializeName(const char* name)
{
if (name)
{
//don't serialize name twice
if (findPointer((void*)name))
return;
int len = b3StrLen(name);
if (len)
{
int newLen = len+1;
int padding = ((newLen+3)&~3)-newLen;
newLen += padding;
//serialize name string now
b3Chunk* chunk = allocate(sizeof(char),newLen);
char* destinationName = (char*)chunk->m_oldPtr;
for (int i=0;i<len;i++)
{
destinationName[i] = name[i];
}
destinationName[len] = 0;
finalizeChunk(chunk,"char",B3_ARRAY_CODE,(void*)name);
}
}
}
virtual int getSerializationFlags() const
{
return m_serializationFlags;
}
virtual void setSerializationFlags(int flags)
{
m_serializationFlags = flags;
}
};
#endif //B3_SERIALIZER_H

Some files were not shown because too many files have changed in this diff Show More