diff --git a/native/cocos/math/CCGeometry.cpp b/native/cocos/math/CCGeometry.cpp index 8dc9c369ec..f37d1751ca 100644 --- a/native/cocos/math/CCGeometry.cpp +++ b/native/cocos/math/CCGeometry.cpp @@ -26,6 +26,7 @@ THE SOFTWARE. #include "math/CCGeometry.h" #include +#include #include "base/ccMacros.h" // implementation of Vec2 @@ -33,7 +34,7 @@ NS_CC_BEGIN // implementation of Size -Size::Size() : width(0), height(0) +Size::Size(void) : width(0), height(0) { } @@ -90,15 +91,15 @@ void Size::setSize(float w, float h) bool Size::equals(const Size& target) const { - return (fabs(this->width - target.width) < FLT_EPSILON) - && (fabs(this->height - target.height) < FLT_EPSILON); + return (std::abs(this->width - target.width) < FLT_EPSILON) + && (std::abs(this->height - target.height) < FLT_EPSILON); } const Size Size::ZERO = Size(0, 0); // implementation of Rect -Rect::Rect() +Rect::Rect(void) { setRect(0.0f, 0.0f, 0.0f, 0.0f); } @@ -200,16 +201,16 @@ bool Rect::intersectsCircle(const cocos2d::Vec2 ¢er, float radius) const float w = size.width / 2; float h = size.height / 2; - float dx = fabs(center.x - rectangleCenter.x); - float dy = fabs(center.y - rectangleCenter.y); + float dx = std::abs(center.x - rectangleCenter.x); + float dy = std::abs(center.y - rectangleCenter.y); if (dx > (radius + w) || dy > (radius + h)) { return false; } - Vec2 circleDistance(fabs(center.x - origin.x - w), - fabs(center.y - origin.y - h)); + Vec2 circleDistance(std::abs(center.x - origin.x - w), + std::abs(center.y - origin.y - h)); if (circleDistance.x <= (w)) { @@ -278,4 +279,3 @@ Rect Rect::unionWithRect(const Rect & rect) const const Rect Rect::ZERO = Rect(0, 0, 0, 0); NS_CC_END - diff --git a/native/cocos/math/CCGeometry.h b/native/cocos/math/CCGeometry.h index c0a3f05d3e..ca95bc1aec 100644 --- a/native/cocos/math/CCGeometry.h +++ b/native/cocos/math/CCGeometry.h @@ -26,8 +26,6 @@ THE SOFTWARE. #ifndef __MATH_CCGEOMETRY_H__ #define __MATH_CCGEOMETRY_H__ -#include - #include "platform/CCPlatformMacros.h" #include "base/ccMacros.h" #include "math/CCMath.h" @@ -223,4 +221,3 @@ NS_CC_END /// @} #endif // __MATH_CCGEOMETRY_H__ - diff --git a/native/cocos/math/CCMath.h b/native/cocos/math/CCMath.h index 106df7260e..bca9f41f9b 100644 --- a/native/cocos/math/CCMath.h +++ b/native/cocos/math/CCMath.h @@ -1,11 +1,10 @@ #ifndef __CC_MATH_H__ #define __CC_MATH_H__ -#include "Vec2.h" -#include "Vec3.h" -#include "Vec4.h" -#include "Mat4.h" -#include "Quaternion.h" +#include "math/Vec2.h" +#include "math/Vec3.h" +#include "math/Vec4.h" +#include "math/Mat4.h" +#include "math/Quaternion.h" #endif - diff --git a/native/cocos/math/Mat4.cpp b/native/cocos/math/Mat4.cpp index 93d2bf7ba0..ea5f509bd7 100644 --- a/native/cocos/math/Mat4.cpp +++ b/native/cocos/math/Mat4.cpp @@ -19,6 +19,8 @@ */ #include "math/Mat4.h" + +#include #include "math/Quaternion.h" #include "math/MathUtil.h" #include "base/ccMacros.h" @@ -108,12 +110,12 @@ void Mat4::createPerspective(float fieldOfView, float aspectRatio, float f_n = 1.0f / (zFarPlane - zNearPlane); float theta = MATH_DEG_TO_RAD(fieldOfView) * 0.5f; - if (fabs(fmod(theta, MATH_PIOVER2)) < MATH_EPSILON) + if (std::abs(std::fmod(theta, MATH_PIOVER2)) < MATH_EPSILON) { CCLOGERROR("Invalid field of view value (%f) causes attempted calculation tan(%f), which is undefined.", fieldOfView, theta); return; } - float divisor = tan(theta); + float divisor = std::tan(theta); GP_ASSERT(divisor); float factor = 1.0f / divisor; @@ -293,7 +295,7 @@ void Mat4::createRotation(const Vec3& axis, float angle, Mat4* dst) if (n != 1.0f) { // Not normalized. - n = sqrt(n); + n = std::sqrt(n); // Prevent divide too close to zero. if (n > 0.000001f) { @@ -304,8 +306,8 @@ void Mat4::createRotation(const Vec3& axis, float angle, Mat4* dst) } } - float c = cos(angle); - float s = sin(angle); + float c = std::cos(angle); + float s = std::sin(angle); float t = 1.0f - c; float tx = t * x; @@ -345,8 +347,8 @@ void Mat4::createRotationX(float angle, Mat4* dst) memcpy(dst, &IDENTITY, MATRIX_SIZE); - float c = cos(angle); - float s = sin(angle); + float c = std::cos(angle); + float s = std::sin(angle); dst->m[5] = c; dst->m[6] = s; @@ -360,8 +362,8 @@ void Mat4::createRotationY(float angle, Mat4* dst) memcpy(dst, &IDENTITY, MATRIX_SIZE); - float c = cos(angle); - float s = sin(angle); + float c = std::cos(angle); + float s = std::sin(angle); dst->m[0] = c; dst->m[2] = -s; @@ -375,8 +377,8 @@ void Mat4::createRotationZ(float angle, Mat4* dst) memcpy(dst, &IDENTITY, MATRIX_SIZE); - float c = cos(angle); - float s = sin(angle); + float c = std::cos(angle); + float s = std::sin(angle); dst->m[0] = c; dst->m[1] = s; @@ -479,7 +481,7 @@ bool Mat4::decompose(Vec3* scale, Quaternion* rotation, Vec3* translation) const return true; // Scale too close to zero, can't decompose rotation. - if (scaleX < MATH_TOLERANCE || scaleY < MATH_TOLERANCE || fabs(scaleZ) < MATH_TOLERANCE) + if (scaleX < MATH_TOLERANCE || scaleY < MATH_TOLERANCE || std::abs(scaleZ) < MATH_TOLERANCE) return false; float rn; @@ -505,7 +507,7 @@ bool Mat4::decompose(Vec3* scale, Quaternion* rotation, Vec3* translation) const if (trace > MATH_EPSILON) { - float s = 0.5f / sqrt(trace); + float s = 0.5f / std::sqrt(trace); rotation->w = 0.25f / s; rotation->x = (yaxis.z - zaxis.y) * s; rotation->y = (zaxis.x - xaxis.z) * s; @@ -517,7 +519,7 @@ bool Mat4::decompose(Vec3* scale, Quaternion* rotation, Vec3* translation) const // we will never divide by zero in the code below. if (xaxis.x > yaxis.y && xaxis.x > zaxis.z) { - float s = 0.5f / sqrt(1.0f + xaxis.x - yaxis.y - zaxis.z); + float s = 0.5f / std::sqrt(1.0f + xaxis.x - yaxis.y - zaxis.z); rotation->w = (yaxis.z - zaxis.y) * s; rotation->x = 0.25f / s; rotation->y = (yaxis.x + xaxis.y) * s; @@ -525,7 +527,7 @@ bool Mat4::decompose(Vec3* scale, Quaternion* rotation, Vec3* translation) const } else if (yaxis.y > zaxis.z) { - float s = 0.5f / sqrt(1.0f + yaxis.y - xaxis.x - zaxis.z); + float s = 0.5f / std::sqrt(1.0f + yaxis.y - xaxis.x - zaxis.z); rotation->w = (zaxis.x - xaxis.z) * s; rotation->x = (yaxis.x + xaxis.y) * s; rotation->y = 0.25f / s; @@ -533,7 +535,7 @@ bool Mat4::decompose(Vec3* scale, Quaternion* rotation, Vec3* translation) const } else { - float s = 0.5f / sqrt(1.0f + zaxis.z - xaxis.x - yaxis.y ); + float s = 0.5f / std::sqrt(1.0f + zaxis.z - xaxis.x - yaxis.y); rotation->w = (xaxis.y - yaxis.x ) * s; rotation->x = (zaxis.x + xaxis.z ) * s; rotation->y = (zaxis.y + yaxis.z ) * s; @@ -658,7 +660,7 @@ bool Mat4::inverse() float det = a0 * b5 - a1 * b4 + a2 * b3 + a3 * b2 - a4 * b1 + a5 * b0; // Close to zero, can't invert. - if (fabs(det) <= MATH_TOLERANCE) + if (std::abs(det) <= MATH_TOLERANCE) return false; // Support the case where m == dst. @@ -978,4 +980,3 @@ const Mat4 Mat4::ZERO = Mat4( 0, 0, 0, 0 ); NS_CC_MATH_END - diff --git a/native/cocos/math/MathUtil.cpp b/native/cocos/math/MathUtil.cpp index 1374057ab6..be87d026ca 100644 --- a/native/cocos/math/MathUtil.cpp +++ b/native/cocos/math/MathUtil.cpp @@ -18,7 +18,7 @@ Original file from GamePlay3D: http://gameplay3d.org This file was modified to fit the cocos2d-x project */ -#include "MathUtil.h" +#include "math/MathUtil.h" #include "base/ccMacros.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) @@ -59,18 +59,18 @@ This file was modified to fit the cocos2d-x project #endif #ifdef INCLUDE_NEON32 -#include "MathUtilNeon.inl" +#include "math/MathUtilNeon.inl" #endif #ifdef INCLUDE_NEON64 -#include "MathUtilNeon64.inl" +#include "math/MathUtilNeon64.inl" #endif #ifdef INCLUDE_SSE -#include "MathUtilSSE.inl" +#include "math/MathUtilSSE.inl" #endif -#include "MathUtil.inl" +#include "math/MathUtil.inl" NS_CC_MATH_BEGIN @@ -276,4 +276,3 @@ void MathUtil::crossVec3(const float* v1, const float* v2, float* dst) } NS_CC_MATH_END - diff --git a/native/cocos/math/MathUtil.h b/native/cocos/math/MathUtil.h index 06df94ea83..d5cdc8c685 100644 --- a/native/cocos/math/MathUtil.h +++ b/native/cocos/math/MathUtil.h @@ -26,7 +26,7 @@ #include #endif -#include "CCMathBase.h" +#include "math/CCMathBase.h" /** * @addtogroup base @@ -139,4 +139,3 @@ NS_CC_MATH_END #define MATRIX_SIZE ( sizeof(float) * 16) #endif - diff --git a/native/cocos/math/Quaternion.cpp b/native/cocos/math/Quaternion.cpp index d4172b93d3..c5b8212640 100644 --- a/native/cocos/math/Quaternion.cpp +++ b/native/cocos/math/Quaternion.cpp @@ -18,7 +18,9 @@ This file was modified to fit the cocos2d-x project */ -#include "Quaternion.h" +#include "math/Quaternion.h" + +#include #include "base/ccMacros.h" NS_CC_MATH_BEGIN @@ -177,7 +179,7 @@ void Quaternion::normalize() if (n == 1.0f) return; - n = sqrt(n); + n = std::sqrt(n); // Too close to zero. if (n < 0.000001f) return; @@ -251,7 +253,7 @@ float Quaternion::toAxisAngle(Vec3* axis) const axis->z = q.z; axis->normalize(); - return (2.0f * acos(q.w)); + return (2.0f * std::acos(q.w)); } void Quaternion::lerp(const Quaternion& q1, const Quaternion& q2, float t, Quaternion* dst) @@ -405,7 +407,7 @@ void Quaternion::slerpForSquad(const Quaternion& q1, const Quaternion& q2, float // This is a straight-forward implementation of the formula of slerp. It does not do any sign switching. float c = q1.x * q2.x + q1.y * q2.y + q1.z * q2.z + q1.w * q2.w; - if (fabs(c) >= 1.0f) + if (std::abs(c) >= 1.0f) { dst->x = q1.x; dst->y = q1.y; @@ -414,9 +416,9 @@ void Quaternion::slerpForSquad(const Quaternion& q1, const Quaternion& q2, float return; } - float omega = acos(c); - float s = sqrt(1.0f - c * c); - if (fabs(s) <= 0.00001f) + float omega = std::acos(c); + float s = std::sqrt(1.0f - c * c); + if (std::abs(s) <= 0.00001f) { dst->x = q1.x; dst->y = q1.y; @@ -425,8 +427,8 @@ void Quaternion::slerpForSquad(const Quaternion& q1, const Quaternion& q2, float return; } - float r1 = sin((1 - t) * omega) / s; - float r2 = sin(t * omega) / s; + float r1 = std::sin((1 - t) * omega) / s; + float r2 = std::sin(t * omega) / s; dst->x = (q1.x * r1 + q2.x * r2); dst->y = (q1.y * r1 + q2.y * r2); dst->z = (q1.z * r1 + q2.z * r2); @@ -434,4 +436,3 @@ void Quaternion::slerpForSquad(const Quaternion& q1, const Quaternion& q2, float } NS_CC_MATH_END - diff --git a/native/cocos/math/Quaternion.h b/native/cocos/math/Quaternion.h index f499c2d0e5..8d10cc6543 100644 --- a/native/cocos/math/Quaternion.h +++ b/native/cocos/math/Quaternion.h @@ -415,7 +415,6 @@ NS_CC_MATH_END end of base group @} */ -#include "Quaternion.inl" +#include "math/Quaternion.inl" #endif - diff --git a/native/cocos/math/Quaternion.inl b/native/cocos/math/Quaternion.inl index b848b7f6a7..f6ad8fec8f 100644 --- a/native/cocos/math/Quaternion.inl +++ b/native/cocos/math/Quaternion.inl @@ -18,7 +18,7 @@ This file was modified to fit the cocos2d-x project */ -#include "Quaternion.h" +#include "math/Quaternion.h" NS_CC_MATH_BEGIN diff --git a/native/cocos/math/Vec2.cpp b/native/cocos/math/Vec2.cpp index 1d6bdc6fa7..416bceab04 100644 --- a/native/cocos/math/Vec2.cpp +++ b/native/cocos/math/Vec2.cpp @@ -123,7 +123,7 @@ float Vec2::distance(const Vec2& v) const float dx = v.x - x; float dy = v.y - y; - return sqrt(dx * dx + dy * dy); + return std::sqrt(dx * dx + dy * dy); } float Vec2::dot(const Vec2& v1, const Vec2& v2) @@ -133,7 +133,7 @@ float Vec2::dot(const Vec2& v1, const Vec2& v2) float Vec2::length() const { - return sqrt(x * x + y * y); + return std::sqrt(x * x + y * y); } void Vec2::normalize() @@ -143,7 +143,7 @@ void Vec2::normalize() if (n == 1.0f) return; - n = sqrt(n); + n = std::sqrt(n); // Too close to zero. if (n < MATH_TOLERANCE) return; @@ -162,8 +162,8 @@ Vec2 Vec2::getNormalized() const void Vec2::rotate(const Vec2& point, float angle) { - double sinAngle = sin(angle); - double cosAngle = cos(angle); + float sinAngle = std::sin(angle); + float cosAngle = std::cos(angle); if (point.isZero()) { @@ -199,8 +199,8 @@ void Vec2::subtract(const Vec2& v1, const Vec2& v2, Vec2* dst) bool Vec2::equals(const Vec2& target) const { - return (fabs(this->x - target.x) < FLT_EPSILON) - && (fabs(this->y - target.y) < FLT_EPSILON); + return (std::abs(this->x - target.x) < FLT_EPSILON) + && (std::abs(this->y - target.y) < FLT_EPSILON); } bool Vec2::fuzzyEquals(const Vec2& b, float var) const @@ -216,7 +216,7 @@ float Vec2::getAngle(const Vec2& other) const Vec2 a2 = getNormalized(); Vec2 b2 = other.getNormalized(); float angle = atan2f(a2.cross(b2), a2.dot(b2)); - if( fabs(angle) < FLT_EPSILON ) return 0.f; + if (std::abs(angle) < FLT_EPSILON) return 0.f; return angle; } @@ -346,4 +346,3 @@ const Vec2 Vec2::ANCHOR_MIDDLE_TOP(0.5f, 1.0f); const Vec2 Vec2::ANCHOR_MIDDLE_BOTTOM(0.5f, 0.0f); NS_CC_MATH_END - diff --git a/native/cocos/math/Vec2.h b/native/cocos/math/Vec2.h index 5bc072a879..b2a9e7c831 100644 --- a/native/cocos/math/Vec2.h +++ b/native/cocos/math/Vec2.h @@ -24,7 +24,7 @@ #include #include -#include +#include #include "math/CCMathBase.h" /** @@ -766,7 +766,6 @@ NS_CC_MATH_END @} */ -#include "Vec2.inl" +#include "math/Vec2.inl" #endif // MATH_VEC2_H - diff --git a/native/cocos/math/Vec3.cpp b/native/cocos/math/Vec3.cpp index 23a27f3445..cf80403cb4 100644 --- a/native/cocos/math/Vec3.cpp +++ b/native/cocos/math/Vec3.cpp @@ -74,7 +74,7 @@ float Vec3::angle(const Vec3& v1, const Vec3& v2) float dy = v1.z * v2.x - v1.x * v2.z; float dz = v1.x * v2.y - v1.y * v2.x; - return atan2f(sqrt(dx * dx + dy * dy + dz * dz) + MATH_FLOAT_SMALL, dot(v1, v2)); + return std::atan2(std::sqrt(dx * dx + dy * dy + dz * dz) + MATH_FLOAT_SMALL, dot(v1, v2)); } void Vec3::add(const Vec3& v1, const Vec3& v2, Vec3* dst) @@ -157,7 +157,7 @@ float Vec3::distance(const Vec3& v) const float dy = v.y - y; float dz = v.z - z; - return sqrt(dx * dx + dy * dy + dz * dz); + return std::sqrt(dx * dx + dy * dy + dz * dz); } float Vec3::distanceSquared(const Vec3& v) const @@ -186,7 +186,7 @@ void Vec3::normalize() if (n == 1.0f) return; - n = sqrt(n); + n = std::sqrt(n); // Too close to zero. if (n < MATH_TOLERANCE) return; @@ -228,4 +228,3 @@ const Vec3 Vec3::UNIT_Y(0.0f, 1.0f, 0.0f); const Vec3 Vec3::UNIT_Z(0.0f, 0.0f, 1.0f); NS_CC_MATH_END - diff --git a/native/cocos/math/Vec3.h b/native/cocos/math/Vec3.h index a32e725332..a99d6daba1 100644 --- a/native/cocos/math/Vec3.h +++ b/native/cocos/math/Vec3.h @@ -22,6 +22,7 @@ #ifndef MATH_VEC3_H #define MATH_VEC3_H +#include #include "math/CCMathBase.h" /** @@ -506,7 +507,6 @@ NS_CC_MATH_END end of base group @} */ -#include "Vec3.inl" +#include "math/Vec3.inl" #endif // MATH_VEC3_H - diff --git a/native/cocos/math/Vec3.inl b/native/cocos/math/Vec3.inl index 0022ac29c9..4e8af7fa20 100644 --- a/native/cocos/math/Vec3.inl +++ b/native/cocos/math/Vec3.inl @@ -50,7 +50,7 @@ inline void Vec3::add(float xx, float yy, float zz) inline float Vec3::length() const { - return sqrt(x * x + y * y + z * z); + return std::sqrt(x * x + y * y + z * z); } inline float Vec3::lengthSquared() const diff --git a/native/cocos/math/Vec4.cpp b/native/cocos/math/Vec4.cpp index a6e74c9fb9..6bf1f0f431 100644 --- a/native/cocos/math/Vec4.cpp +++ b/native/cocos/math/Vec4.cpp @@ -19,6 +19,8 @@ */ #include "math/Vec4.h" + +#include #include "math/MathUtil.h" #include "base/ccMacros.h" @@ -84,7 +86,7 @@ float Vec4::angle(const Vec4& v1, const Vec4& v2) float dy = v1.w * v2.y - v1.y * v2.w - v1.z * v2.x + v1.x * v2.z; float dz = v1.w * v2.z - v1.z * v2.w - v1.x * v2.y + v1.y * v2.x; - return atan2f(sqrt(dx * dx + dy * dy + dz * dz) + MATH_FLOAT_SMALL, dot(v1, v2)); + return std::atan2(std::sqrt(dx * dx + dy * dy + dz * dz) + MATH_FLOAT_SMALL, dot(v1, v2)); } void Vec4::add(const Vec4& v) @@ -175,7 +177,7 @@ float Vec4::distance(const Vec4& v) const float dz = v.z - z; float dw = v.w - w; - return sqrt(dx * dx + dy * dy + dz * dz + dw * dw); + return std::sqrt(dx * dx + dy * dy + dz * dz + dw * dw); } float Vec4::distanceSquared(const Vec4& v) const @@ -200,7 +202,7 @@ float Vec4::dot(const Vec4& v1, const Vec4& v2) float Vec4::length() const { - return sqrt(x * x + y * y + z * z + w * w); + return std::sqrt(x * x + y * y + z * z + w * w); } @@ -224,7 +226,7 @@ void Vec4::normalize() if (n == 1.0f) return; - n = sqrt(n); + n = std::sqrt(n); // Too close to zero. if (n < MATH_TOLERANCE) return; @@ -311,4 +313,3 @@ const Vec4 Vec4::UNIT_Z = Vec4(0.0f, 0.0f, 1.0f, 0.0f); const Vec4 Vec4::UNIT_W = Vec4(0.0f, 0.0f, 0.0f, 1.0f); NS_CC_MATH_END - diff --git a/native/cocos/network/Android.mk b/native/cocos/network/Android.mk index 80e03db1e9..2ebcdbe5a8 100644 --- a/native/cocos/network/Android.mk +++ b/native/cocos/network/Android.mk @@ -5,13 +5,15 @@ LOCAL_MODULE := cocos_network_static LOCAL_MODULE_FILENAME := libnetwork +LOCAL_ARM_MODE := arm + LOCAL_SRC_FILES := HttpClient-android.cpp \ SocketIO.cpp \ WebSocket.cpp \ CCDownloader.cpp \ CCDownloader-android.cpp -LOCAL_EXPORT_C_INCLUDES := +LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../external/websockets/include/android diff --git a/native/cocos/network/CCDownloader-android.cpp b/native/cocos/network/CCDownloader-android.cpp index 2de26ba44b..08f61bf7b8 100644 --- a/native/cocos/network/CCDownloader-android.cpp +++ b/native/cocos/network/CCDownloader-android.cpp @@ -35,6 +35,8 @@ using namespace std; +static bool _registerNativeMethods(JNIEnv* env); + unordered_map sDownloaderMap; namespace cocos2d { namespace network { @@ -169,12 +171,19 @@ namespace cocos2d { namespace network { ); coTask->task.reset(); } + + + void _preloadJavaDownloaderClass() + { + if(!_registered) + { + _registered = _registerNativeMethods(JniHelper::getEnv()); + } + } } } // namespace cocos2d::network -extern "C" -{ -JNIEXPORT void Java_org_cocos2dx_lib_Cocos2dxDownloader_nativeOnProgress(JNIEnv *env, jclass clazz, jint id, jint taskId, jlong dl, jlong dlnow, jlong dltotal) +static void _nativeOnProgress(JNIEnv *env, jclass clazz, jint id, jint taskId, jlong dl, jlong dlnow, jlong dltotal) { DLLOG("_nativeOnProgress(id: %d, taskId: %d, dl: %lld, dlnow: %lld, dltotal: %lld)", id, taskId, dl, dlnow, dltotal); auto iter = sDownloaderMap.find(id); @@ -187,7 +196,7 @@ JNIEXPORT void Java_org_cocos2dx_lib_Cocos2dxDownloader_nativeOnProgress(JNIEnv downloader->_onProcess((int)taskId, (int64_t)dl, (int64_t)dlnow, (int64_t)dltotal); } -JNIEXPORT void Java_org_cocos2dx_lib_Cocos2dxDownloader_nativeOnFinish(JNIEnv *env, jclass clazz, jint id, jint taskId, jint errCode, jstring errStr, jbyteArray data) +static void _nativeOnFinish(JNIEnv *env, jclass clazz, jint id, jint taskId, jint errCode, jstring errStr, jbyteArray data) { DLLOG("_nativeOnFinish(id: %d, taskId: %d)", id, taskId); auto iter = sDownloaderMap.find(id); @@ -220,4 +229,28 @@ JNIEXPORT void Java_org_cocos2dx_lib_Cocos2dxDownloader_nativeOnFinish(JNIEnv *e } downloader->_onFinish((int)taskId, (int)errCode, nullptr, buf); } + +static JNINativeMethod sMethodTable[] = { + { "nativeOnProgress", "(IIJJJ)V", (void*)_nativeOnProgress }, + { "nativeOnFinish", "(III" JARG_STR "[B)V", (void*)_nativeOnFinish }, +}; + +static bool _registerNativeMethods(JNIEnv* env) +{ + jclass clazz = env->FindClass(JCLS_DOWNLOADER); + if (clazz == NULL) + { + DLLOG("_registerNativeMethods: can't find java class:%s", JARG_DOWNLOADER); + return false; + } + if (JNI_OK != env->RegisterNatives(clazz, sMethodTable, sizeof(sMethodTable) / sizeof(sMethodTable[0]))) + { + DLLOG("_registerNativeMethods: failed"); + if (env->ExceptionCheck()) + { + env->ExceptionClear(); + } + return false; + } + return true; } diff --git a/native/cocos/network/CCDownloader-android.h b/native/cocos/network/CCDownloader-android.h index 75f5a3a74e..868f602736 100644 --- a/native/cocos/network/CCDownloader-android.h +++ b/native/cocos/network/CCDownloader-android.h @@ -50,5 +50,8 @@ namespace cocos2d { namespace network std::unordered_map _taskMap; }; + // Load java downloader class from main thread, to void addImageAsync function + // perform in sub-thread cause java downloader unusable + void _preloadJavaDownloaderClass(); }} // namespace cocos2d::network diff --git a/native/cocos/network/CCDownloader-apple.mm b/native/cocos/network/CCDownloader-apple.mm index 0abd3ef6ba..0613d7df30 100644 --- a/native/cocos/network/CCDownloader-apple.mm +++ b/native/cocos/network/CCDownloader-apple.mm @@ -25,8 +25,8 @@ #include "network/CCDownloader-apple.h" #include "network/CCDownloader.h" +#include "base/ccUTF8.h" #include -#include "base/CCString.h" //////////////////////////////////////////////////////////////////////////////// // OC Classes Declaration @@ -553,9 +553,7 @@ namespace cocos2d { namespace network { if ('/' == [destPath characterAtIndex:0]) { - // absolute path, need add prefix - NSString *prefix = @"file://"; - destURL = [NSURL URLWithString:[prefix stringByAppendingString: destPath]]; + destURL = [NSURL fileURLWithPath:destPath]; break; } diff --git a/native/cocos/network/CCDownloader-curl.cpp b/native/cocos/network/CCDownloader-curl.cpp index 61218485dc..5567296a26 100644 --- a/native/cocos/network/CCDownloader-curl.cpp +++ b/native/cocos/network/CCDownloader-curl.cpp @@ -108,7 +108,7 @@ namespace cocos2d { namespace network { do { string dir; - unsigned long found = _tempFileName.find_last_of("/\\"); + size_t found = _tempFileName.find_last_of("/\\"); if (found == string::npos) { _errCode = DownloadTask::ERROR_INVALID_PARAMS; @@ -409,7 +409,7 @@ namespace cocos2d { namespace network { { char buf[256] = {0}; sprintf(buf - , "When crequest url(%s) header info, return unexcept http response code(%ld)" + , "When request url(%s) header info, return unexcept http response code(%ld)" , wrapper.first->requestURL.c_str() , httpResponseCode); coTask.setErrorProc(DownloadTask::ERROR_IMPL_INTERNAL, CURLE_OK, buf); diff --git a/native/cocos/network/HttpAsynConnection-apple.m b/native/cocos/network/HttpAsynConnection-apple.m index 6bb10002a7..51c83b41ab 100755 --- a/native/cocos/network/HttpAsynConnection-apple.m +++ b/native/cocos/network/HttpAsynConnection-apple.m @@ -25,7 +25,7 @@ #include "platform/CCPlatformConfig.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) -#import "HttpAsynConnection-apple.h" +#import "network/HttpAsynConnection-apple.h" @interface HttpAsynConnection () @@ -35,18 +35,18 @@ @implementation HttpAsynConnection -@synthesize srcURL; -@synthesize sslFile; -@synthesize responseHeader; -@synthesize responseData; -@synthesize getDataTime; -@synthesize responseCode; -@synthesize statusString; -@synthesize responseError; -@synthesize connError; -@synthesize conn; -@synthesize finish; -@synthesize runLoop; +@synthesize srcURL = srcURL; +@synthesize sslFile = sslFile; +@synthesize responseHeader = responseHeader; +@synthesize responseData = responseData; +@synthesize getDataTime = getDataTime; +@synthesize responseCode = responseCode; +@synthesize statusString = statusString; +@synthesize responseError = responseError; +@synthesize connError = connError; +@synthesize conn = conn; +@synthesize finish = finish; +@synthesize runLoop = runLoop; - (void)dealloc { @@ -191,12 +191,15 @@ } [certData release]; if (cert) + { CFRelease(cert); - if (certArrayRef) + } + if (certArrayRef) + { CFRelease(certArrayRef); - + } //Did our custom trust chain evaluate successfully? - return trustResult = kSecTrustResultUnspecified || trustResult == kSecTrustResultProceed; + return trustResult == kSecTrustResultUnspecified || trustResult == kSecTrustResultProceed; } - (void) connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge @@ -225,4 +228,3 @@ @end #endif // #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) - diff --git a/native/cocos/network/HttpClient-android.cpp b/native/cocos/network/HttpClient-android.cpp index 2e3efa5250..79c2d27da4 100644 --- a/native/cocos/network/HttpClient-android.cpp +++ b/native/cocos/network/HttpClient-android.cpp @@ -27,7 +27,7 @@ #include "platform/CCPlatformConfig.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) -#include "HttpClient.h" +#include "network/HttpClient.h" #include #include @@ -383,7 +383,7 @@ public: return header; } - const std::string getCookieFileName() + const std::string& getCookieFileName() const { return _cookieFileName; } @@ -585,7 +585,7 @@ private: return nullptr; } char *ret = nullptr; - std::string strValue = JniHelper::getStringUTFCharsJNI(env, jstr); + std::string strValue = cocos2d::StringUtils::getStringUTFCharsJNI(env, jstr); ret = strdup(strValue.c_str()); return ret; } @@ -608,7 +608,7 @@ private: return len; } - const std::string getCookieString() + const std::string& getCookieString() const { return _responseCookies; } @@ -1054,4 +1054,3 @@ const std::string& HttpClient::getSSLVerification() NS_CC_END #endif // #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) - diff --git a/native/cocos/network/HttpClient-apple.mm b/native/cocos/network/HttpClient-apple.mm index 397d159761..c057509cd3 100644 --- a/native/cocos/network/HttpClient-apple.mm +++ b/native/cocos/network/HttpClient-apple.mm @@ -27,7 +27,7 @@ #include "platform/CCPlatformConfig.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) -#include "HttpClient.h" +#include "network/HttpClient.h" #include #include @@ -50,7 +50,7 @@ void HttpClient::networkThread() { increaseThreadCount(); - while (true) { + while (true) @autoreleasepool { HttpRequest *request; // step 1: send http request if the requestQueue isn't empty @@ -66,21 +66,23 @@ void HttpClient::networkThread() if (request == _requestSentinel) { break; } - - if (Director::DirectorInstance && !Director::isPurgeDirectorInNextLoop()) + + // Create a HttpResponse object, the default setting is http access failed + HttpResponse *response = new (std::nothrow) HttpResponse(request); + + processResponse(response, _responseMessage); + + // add response packet into queue + _responseQueueMutex.lock(); + _responseQueue.pushBack(response); + _responseQueueMutex.unlock(); + + _schedulerMutex.lock(); + if (nullptr != _scheduler) { - // Create a HttpResponse object, the default setting is http access failed - HttpResponse *response = new (std::nothrow) HttpResponse(request); - - processResponse(response, _responseMessage); - - // add response packet into queue - _responseQueueMutex.lock(); - _responseQueue.pushBack(response); - _responseQueueMutex.unlock(); - - Director::DirectorInstance->getScheduler()->performFunctionInCocosThread(CC_CALLBACK_0(HttpClient::dispatchResponseCallbacks, this)); + _scheduler->performFunctionInCocosThread(CC_CALLBACK_0(HttpClient::dispatchResponseCallbacks, this)); } + _schedulerMutex.unlock(); } // cleanup: if worker thread received quit signal, clean up un-completed request queue @@ -102,10 +104,11 @@ void HttpClient::networkThreadAlone(HttpRequest* request, HttpResponse* response char responseMessage[RESPONSE_BUFFER_SIZE] = { 0 }; processResponse(response, responseMessage); - - if (Director::DirectorInstance && !Director::isPurgeDirectorInNextLoop()) + + _schedulerMutex.lock(); + if (nullptr != _scheduler) { - Director::DirectorInstance->getScheduler()->performFunctionInCocosThread([this, response, request]{ + _scheduler->performFunctionInCocosThread([this, response, request]{ const ccHttpRequestCallback& callback = request->getCallback(); Ref* pTarget = request->getTarget(); SEL_HttpResponse pSelector = request->getSelector(); @@ -123,6 +126,7 @@ void HttpClient::networkThreadAlone(HttpRequest* request, HttpResponse* response request->release(); }); } + _schedulerMutex.unlock(); decreaseThreadCountAndMayDeleteThis(); } @@ -151,7 +155,7 @@ static int processTask(HttpClient* client, HttpRequest* request, NSString* reque if(!headers.empty()) { /* append custom headers one by one */ - for (auto it = headers.begin(); it != headers.end(); ++it) + for (std::vector::iterator it = headers.begin(); it != headers.end(); ++it) { unsigned long i = it->find(':', 0); unsigned long length = it->size(); @@ -174,7 +178,7 @@ static int processTask(HttpClient* client, HttpRequest* request, NSString* reque } } - //read cookie propertities from file and set cookie + //read cookie properties from file and set cookie std::string cookieFilename = client->getCookieFilename(); if(!cookieFilename.empty() && nullptr != client->getCookie()) { @@ -277,13 +281,13 @@ static int processTask(HttpClient* client, HttpRequest* request, NSString* reque [header deleteCharactersInRange:range]; } NSData *headerData = [header dataUsingEncoding:NSUTF8StringEncoding]; - auto headerBuffer = (std::vector*)headerStream; + std::vector *headerBuffer = (std::vector*)headerStream; const void* headerptr = [headerData bytes]; long headerlen = [headerData length]; headerBuffer->insert(headerBuffer->end(), (char*)headerptr, (char*)headerptr+headerlen); //handle response data - auto recvBuffer = (std::vector*)stream; + std::vector *recvBuffer = (std::vector*)stream; const void* ptr = [httpAsynConn.responseData bytes]; long len = [httpAsynConn.responseData length]; recvBuffer->insert(recvBuffer->end(), (char*)ptr, (char*)ptr+len); @@ -314,9 +318,12 @@ void HttpClient::destroyInstance() auto thiz = _httpClient; _httpClient = nullptr; - - Director::DirectorInstance->getScheduler()->unscheduleAllForTarget(thiz); - + + thiz->_scheduler->unscheduleAllForTarget(thiz); + thiz->_schedulerMutex.lock(); + thiz->_scheduler = nullptr; + thiz->_schedulerMutex.unlock(); + thiz->_requestQueueMutex.lock(); thiz->_requestQueue.pushBack(thiz->_requestSentinel); thiz->_requestQueueMutex.unlock(); @@ -365,6 +372,7 @@ HttpClient::HttpClient() { CCLOG("In the constructor of HttpClient!"); memset(_responseMessage, 0, sizeof(char) * RESPONSE_BUFFER_SIZE); + _scheduler = Director::getInstance()->getScheduler(); increaseThreadCount(); } diff --git a/native/cocos/network/HttpClient.cpp b/native/cocos/network/HttpClient.cpp index 956628ab91..94921ee21c 100644 --- a/native/cocos/network/HttpClient.cpp +++ b/native/cocos/network/HttpClient.cpp @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "HttpClient.h" +#include "network/HttpClient.h" #include #include #include @@ -46,7 +46,7 @@ typedef size_t (*write_callback)(void *ptr, size_t size, size_t nmemb, void *str // Callback function used by libcurl for collect response data static size_t writeData(void *ptr, size_t size, size_t nmemb, void *stream) { - auto recvBuffer = (std::vector*)stream; + std::vector *recvBuffer = (std::vector*)stream; size_t sizes = size * nmemb; // add data to the end of recvBuffer @@ -59,7 +59,7 @@ static size_t writeData(void *ptr, size_t size, size_t nmemb, void *stream) // Callback function used by libcurl for collect header data static size_t writeHeaderData(void *ptr, size_t size, size_t nmemb, void *stream) { - auto recvBuffer = (std::vector*)stream; + std::vector *recvBuffer = (std::vector*)stream; size_t sizes = size * nmemb; // add data to the end of recvBuffer @@ -253,7 +253,7 @@ public: if(!headers.empty()) { /* append custom headers one by one */ - for (auto it = headers.begin(); it != headers.end(); ++it) + for (std::vector::iterator it = headers.begin(); it != headers.end(); ++it) _headers = curl_slist_append(_headers,it->c_str()); /* set custom headers for curl */ if (!setOption(CURLOPT_HTTPHEADER, _headers)) diff --git a/native/cocos/network/HttpCookie.cpp b/native/cocos/network/HttpCookie.cpp index e41ee5c71c..3c8b60704c 100644 --- a/native/cocos/network/HttpCookie.cpp +++ b/native/cocos/network/HttpCookie.cpp @@ -22,8 +22,8 @@ THE SOFTWARE. ****************************************************************************/ -#include "HttpCookie.h" -#include "CCFileUtils.h" +#include "network/HttpCookie.h" +#include "platform/CCFileUtils.h" #include #include diff --git a/native/cocos/network/HttpCookie.h b/native/cocos/network/HttpCookie.h index 87cc9820cc..86450d79cb 100644 --- a/native/cocos/network/HttpCookie.h +++ b/native/cocos/network/HttpCookie.h @@ -26,6 +26,9 @@ #define HTTP_COOKIE_H /// @cond DO_NOT_SHOW +#include +#include + struct CookiesInfo { std::string domain; diff --git a/native/cocos/network/HttpRequest.h b/native/cocos/network/HttpRequest.h index 4687fa1028..e018548077 100644 --- a/native/cocos/network/HttpRequest.h +++ b/native/cocos/network/HttpRequest.h @@ -236,6 +236,29 @@ public: return _pUserData; } + /** + * Set the target and related callback selector. + * When response come back, it would call (pTarget->*pSelector) to process something. + * + * @param pTarget the target object pointer. + * @param pSelector the callback function. + */ + CC_DEPRECATED_ATTRIBUTE inline void setResponseCallback(Ref* pTarget, SEL_CallFuncND pSelector) + { + doSetResponseCallback(pTarget, (SEL_HttpResponse)pSelector); + } + + /** + * Set the target and related callback selector of HttpRequest object. + * When response come back, we would call (pTarget->*pSelector) to process response data. + * + * @param pTarget the target object pointer. + * @param pSelector the SEL_HttpResponse function. + */ + inline void setResponseCallback(Ref* pTarget, SEL_HttpResponse pSelector) + { + doSetResponseCallback(pTarget, pSelector); + } /** * Set response callback function of HttpRequest object. * When response come back, we would call _pCallback to process response data. @@ -247,23 +270,6 @@ public: _pCallback = callback; } - CC_DEPRECATED_ATTRIBUTE inline void setResponseCallback(Ref* target ,const ccHttpRequestCallback& callback) - { - if(_pTarget != target) - { - if (_pTarget) { - _pTarget->release(); - } - - _pTarget = target; - if (_pTarget) { - _pTarget->retain(); - } - } - - _pCallback = callback; - } - /** * Get the target of callback selector funtion, mainly used by HttpClient. * @@ -333,6 +339,22 @@ public: return _headers; } +private: + inline void doSetResponseCallback(Ref* pTarget, SEL_HttpResponse pSelector) + { + if (_pTarget) + { + _pTarget->release(); + } + + _pTarget = pTarget; + _pSelector = pSelector; + if (_pTarget) + { + _pTarget->retain(); + } + } + protected: // properties Type _requestType; /// kHttpRequestGet, kHttpRequestPost or other enums diff --git a/native/cocos/network/HttpResponse.h b/native/cocos/network/HttpResponse.h index a7bac9e4af..efbae4bfe4 100644 --- a/native/cocos/network/HttpResponse.h +++ b/native/cocos/network/HttpResponse.h @@ -106,7 +106,7 @@ public: inline bool isSucceed() const { return _succeed; - }; + } /** * Get the http response data. diff --git a/native/cocos/network/SocketIO.cpp b/native/cocos/network/SocketIO.cpp index d696ba2a55..e49fdc07f4 100644 --- a/native/cocos/network/SocketIO.cpp +++ b/native/cocos/network/SocketIO.cpp @@ -27,14 +27,14 @@ ****************************************************************************/ -#include "SocketIO.h" +#include "network/SocketIO.h" #include #include #include #include "base/CCDirector.h" #include "base/CCScheduler.h" -#include "WebSocket.h" -#include "HttpClient.h" +#include "network/WebSocket.h" +#include "network/HttpClient.h" #include "json/rapidjson.h" #include "json/document.h" @@ -877,9 +877,8 @@ void SIOClientImpl::onMessage(WebSocket* ws, const WebSocket::Data& data) break; case 4: { - const char second = payload.at(0); - int control2 = atoi(&second); - CCLOGINFO("Message code: [%i]", control); + int control2 = payload.at(0) - '0'; + CCLOGINFO("Message code: [%i]", control2); SocketIOPacket *packetOut = SocketIOPacket::createPacketWithType("event", _version); std::string endpoint = ""; @@ -988,8 +987,8 @@ void SIOClientImpl::onClose(WebSocket* ws) } // discard this client _connected = false; - if (Director::DirectorInstance) - Director::DirectorInstance->getScheduler()->unscheduleAllForTarget(this); + if (Director::getInstance()) + Director::getInstance()->getScheduler()->unscheduleAllForTarget(this); SocketIO::getInstance()->removeSocket(_uri); } @@ -1000,7 +999,7 @@ void SIOClientImpl::onClose(WebSocket* ws) void SIOClientImpl::onError(WebSocket* ws, const WebSocket::ErrorCode& error) { CC_UNUSED_PARAM(ws); - CCLOGERROR("Websocket error received: %d", error); + CCLOGERROR("Websocket error received: %d", static_cast(error)); } //begin SIOClient methods diff --git a/native/cocos/network/WebSocket.cpp b/native/cocos/network/WebSocket.cpp index b204cd2306..7ecf19f172 100644 --- a/native/cocos/network/WebSocket.cpp +++ b/native/cocos/network/WebSocket.cpp @@ -27,21 +27,20 @@ ****************************************************************************/ -#include "WebSocket.h" +#include "network/WebSocket.h" +#include "base/CCDirector.h" +#include "base/CCScheduler.h" +#include "base/CCEventDispatcher.h" +#include "base/CCEventListenerCustom.h" -#include -#include #include #include #include #include -#include +#include +#include -#include "base/CCDirector.h" -#include "base/CCScheduler.h" -#include "websockets/libwebsockets.h" -#include "base/CCEventDispatcher.h" -#include "base/CCEventListenerCustom.h" +#include "libwebsockets.h" #define WS_RX_BUFFER_SIZE (65536) #define WS_RESERVE_RECEIVE_BUFFER_SIZE (4096) @@ -123,6 +122,8 @@ public: // Creates a new thread bool createWebSocketThread(const WebSocket& ws); + // Quits websocket thread. + void quitWebSocketThread(); // Sends message to Cocos thread. It's needed to be invoked in Websocket thread. void sendMessageToCocosThread(const std::function& cb); @@ -136,11 +137,11 @@ public: protected: void wsThreadEntryFunc(); private: - std::list _subThreadWsMessageQueue; + std::list* _subThreadWsMessageQueue; std::mutex _subThreadWsMessageQueueMutex; - std::thread _subThreadInstance; + std::thread* _subThreadInstance; WebSocket* _ws; - + bool _needQuit; friend class WebSocket; }; @@ -165,43 +166,71 @@ public: } }; +// Implementation of WsThreadHelper WsThreadHelper::WsThreadHelper() -: _ws(nullptr) +: _subThreadInstance(nullptr) +, _ws(nullptr) +, _needQuit(false) { + _subThreadWsMessageQueue = new (std::nothrow) std::list(); } WsThreadHelper::~WsThreadHelper() { + joinWebSocketThread(); + CC_SAFE_DELETE(_subThreadInstance); + delete _subThreadWsMessageQueue; } bool WsThreadHelper::createWebSocketThread(const WebSocket& ws) { _ws = const_cast(&ws); - _subThreadInstance = std::thread(&WebSocket::onSubThreadLoop, _ws); + // Creates websocket thread + _subThreadInstance = new (std::nothrow) std::thread(&WsThreadHelper::wsThreadEntryFunc, this); return true; } +void WsThreadHelper::quitWebSocketThread() +{ + _needQuit = true; +} + +void WsThreadHelper::wsThreadEntryFunc() +{ + LOGD("WebSocket thread start, helper instance: %p\n", this); + _ws->onSubThreadStarted(); + + while (!_needQuit) + { + _ws->onSubThreadLoop(); + } + + _ws->onSubThreadEnded(); + + LOGD("WebSocket thread exit, helper instance: %p\n", this); +} + void WsThreadHelper::sendMessageToCocosThread(const std::function& cb) { - if (Director::DirectorInstance) - Director::DirectorInstance->getScheduler()->performFunctionInCocosThread(cb); + Director::getInstance()->getScheduler()->performFunctionInCocosThread(cb); } void WsThreadHelper::sendMessageToWebSocketThread(WsMessage *msg) { std::lock_guard lk(_subThreadWsMessageQueueMutex); - _subThreadWsMessageQueue.push_back(msg); + _subThreadWsMessageQueue->push_back(msg); } void WsThreadHelper::joinWebSocketThread() { - if (_subThreadInstance.joinable()) + if (_subThreadInstance->joinable()) { - _subThreadInstance.join(); + _subThreadInstance->join(); } } +// Define a WebSocket frame class WebSocketFrame { public: @@ -253,24 +282,26 @@ private: std::vector _data; }; + enum WS_MSG { WS_MSG_TO_SUBTRHEAD_SENDING_STRING = 0, WS_MSG_TO_SUBTRHEAD_SENDING_BINARY, }; -static std::unordered_set* __websocketInstances = nullptr; +static std::vector* __websocketInstances = nullptr; void WebSocket::closeAllConnections() { if (__websocketInstances != nullptr) { - auto copyInstances = *__websocketInstances; - for (auto&& instance : copyInstances) + ssize_t count = __websocketInstances->size(); + for (ssize_t i = count-1; i >=0 ; i--) { + WebSocket* instance = __websocketInstances->at(i); instance->close(); } - delete __websocketInstances; + __websocketInstances->clear(); __websocketInstances = nullptr; } } @@ -281,6 +312,7 @@ WebSocket::WebSocket() , _wsHelper(nullptr) , _wsInstance(nullptr) , _wsContext(nullptr) +, _isDestroyed(std::make_shared>(false)) , _delegate(nullptr) , _SSLConnection(0) , _wsProtocols(nullptr) @@ -289,41 +321,21 @@ WebSocket::WebSocket() _receivedData.reserve(WS_RESERVE_RECEIVE_BUFFER_SIZE); if (__websocketInstances == nullptr) { - __websocketInstances = new (std::nothrow) std::unordered_set(); + __websocketInstances = new (std::nothrow) std::vector(); } - __websocketInstances->insert(this); - auto eventDispatcher = Director::getInstance()->getEventDispatcher(); - auto instance = this; - _resetDirectorListener = eventDispatcher->addCustomEventListener(Director::EVENT_RESET, - [instance](EventCustom*) - { - if (__websocketInstances && __websocketInstances->find(instance) != __websocketInstances->end()) - { - instance->close(); - } + __websocketInstances->push_back(this); + + std::shared_ptr> isDestroyed = _isDestroyed; + _resetDirectorListener = Director::getInstance()->getEventDispatcher()->addCustomEventListener(Director::EVENT_RESET, [this, isDestroyed](EventCustom*){ + if (*isDestroyed) + return; + close(); }); } WebSocket::~WebSocket() { - if (__websocketInstances != nullptr) - { - auto iter = __websocketInstances->find(this); - if (iter != __websocketInstances->end()) - { - __websocketInstances->erase(iter); - } - else - { - LOGD("ERROR: WebSocket instance (%p) wasn't added to the container which saves websocket instances!\n", this); - } - } - - if (Director::DirectorInstance) { - Director::DirectorInstance->getEventDispatcher()->removeEventListener(_resetDirectorListener); - } - LOGD("In the destructor of WebSocket (%p)\n", this); CC_SAFE_DELETE(_wsHelper); @@ -335,6 +347,23 @@ WebSocket::~WebSocket() } } CC_SAFE_DELETE_ARRAY(_wsProtocols); + + if (__websocketInstances != nullptr) + { + auto iter = std::find(__websocketInstances->begin(), __websocketInstances->end(), this); + if (iter != __websocketInstances->end()) + { + __websocketInstances->erase(iter); + } + else + { + LOGD("ERROR: WebSocket instance (%p) wasn't added to the container which saves websocket instances!\n", this); + } + } + + Director::getInstance()->getEventDispatcher()->removeEventListener(_resetDirectorListener); + + *_isDestroyed = true; } bool WebSocket::init(const Delegate& delegate, @@ -397,7 +426,7 @@ bool WebSocket::init(const Delegate& delegate, if (protocols && !protocols->empty()) { int i = 0; - for (auto iter = protocols->begin(); iter != protocols->end(); ++iter, ++i) + for (std::vector::const_iterator iter = protocols->begin(); iter != protocols->end(); ++iter, ++i) { char* name = new (std::nothrow) char[(*iter).length()+1]; strcpy(name, (*iter).c_str()); @@ -491,10 +520,10 @@ void WebSocket::close() // 'closed' state has to be set before quit websocket thread. _readyState = State::CLOSED; _readStateMutex.unlock(); - + + _wsHelper->quitWebSocketThread(); LOGD("Waiting WebSocket (%p) to exit!\n", this); _wsHelper->joinWebSocketThread(); - // Since 'onConnectionClosed' didn't post message to Cocos Thread for invoking 'onClose' callback, do it here. // onClose must be invoked at the end of this method. _delegate->onClose(this); @@ -502,10 +531,7 @@ void WebSocket::close() void WebSocket::closeAsync() { - _readStateMutex.lock(); - if (_readyState != State::CLOSING && _readyState != State::CLOSED) - _readyState = State::CLOSING; - _readStateMutex.unlock(); + _wsHelper->quitWebSocketThread(); } WebSocket::State WebSocket::getReadyState() @@ -516,42 +542,37 @@ WebSocket::State WebSocket::getReadyState() void WebSocket::onSubThreadLoop() { - onSubThreadStarted(); - - while (true) { - _readStateMutex.lock(); - if (_wsContext && (_readyState == State::CONNECTING || _readyState == State::OPEN)) + _readStateMutex.lock(); + if (_wsContext && _readyState != State::CLOSED && _readyState != State::CLOSING) + { + _readStateMutex.unlock(); + _wsHelper->_subThreadWsMessageQueueMutex.lock(); + bool isEmpty = _wsHelper->_subThreadWsMessageQueue->empty(); + _wsHelper->_subThreadWsMessageQueueMutex.unlock(); + if (!isEmpty) { - _readStateMutex.unlock(); - _wsHelper->_subThreadWsMessageQueueMutex.lock(); - bool isEmpty = _wsHelper->_subThreadWsMessageQueue.empty(); - _wsHelper->_subThreadWsMessageQueueMutex.unlock(); - if (!isEmpty) - { - lws_callback_on_writable(_wsInstance); - } + lws_callback_on_writable(_wsInstance); + } - lws_service(_wsContext, 50); - } - else - { - LOGD("Ready state is closing or was closed, code=%d, quit websocket thread!\n", _readyState); - _readStateMutex.unlock(); - break; - } + lws_service(_wsContext, 50); + } + else + { + LOGD("Ready state is closing or was closed, code=%d, quit websocket thread!\n", static_cast(_readyState)); + _readStateMutex.unlock(); + _wsHelper->quitWebSocketThread(); } - - onSubThreadEnded(); } void WebSocket::onSubThreadStarted() { - LOGD("WebSocket::onSubThreadStarted, instance: %p\n", this); - static const struct lws_extension exts[] = { { "permessage-deflate", lws_extension_callback_pm_deflate, + // client_no_context_takeover extension is not supported in the current version, it will cause connection fail + // It may be a bug of lib websocket build +// "permessage-deflate; client_no_context_takeover; client_max_window_bits" "permessage-deflate; client_max_window_bits" }, { @@ -581,7 +602,7 @@ void WebSocket::onSubThreadStarted() info.options = 0; info.user = this; - int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE | LLL_HEADER | LLL_EXT | LLL_CLIENT | LLL_LATENCY; + int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE/* | LLL_INFO | LLL_DEBUG | LLL_PARSER*/ | LLL_HEADER | LLL_EXT | LLL_CLIENT | LLL_LATENCY; lws_set_log_level(log_level, printWebSocketLog); _wsContext = lws_create_context(&info); @@ -604,10 +625,9 @@ void WebSocket::onSubThreadStarted() sprintf(portStr, "%d", _port); std::string ads_port = _host + ":" + portStr; - lws_client_connect_info cInfo = {_wsContext, _host.c_str(), (int)_port, _SSLConnection, - _path.c_str(), ads_port.c_str(), ads_port.c_str(), - name.c_str(), -1,nullptr,nullptr}; - _wsInstance = lws_client_connect_via_info(&cInfo); + _wsInstance = lws_client_connect(_wsContext, _host.c_str(), _port, _SSLConnection, + _path.c_str(), ads_port.c_str(), ads_port.c_str(), + name.c_str(), -1); if (nullptr == _wsInstance) { @@ -625,33 +645,30 @@ void WebSocket::onSubThreadEnded() if (_wsContext != nullptr) { lws_context_destroy(_wsContext); - _wsContext = nullptr; } - - LOGD("WebSocket::onSubThreadEnded, instance: %p\n", this); } void WebSocket::onClientWritable() { std::lock_guard lk(_wsHelper->_subThreadWsMessageQueueMutex); - if (_wsHelper->_subThreadWsMessageQueue.empty()) + if (_wsHelper->_subThreadWsMessageQueue->empty()) { return; } - std::list::iterator iter = _wsHelper->_subThreadWsMessageQueue.begin(); + std::list::iterator iter = _wsHelper->_subThreadWsMessageQueue->begin(); ssize_t bytesWrite = 0; - if (iter != _wsHelper->_subThreadWsMessageQueue.end()) + if (iter != _wsHelper->_subThreadWsMessageQueue->end()) { WsMessage* subThreadMsg = *iter; Data* data = (Data*)subThreadMsg->obj; - const size_t c_bufferSize = WS_RX_BUFFER_SIZE; + const ssize_t c_bufferSize = WS_RX_BUFFER_SIZE; - const size_t remaining = data->len - data->issued; - const size_t n = std::min(remaining, c_bufferSize ); + const ssize_t remaining = data->len - data->issued; + const ssize_t n = std::min(remaining, c_bufferSize); WebSocketFrame* frame = nullptr; @@ -674,7 +691,7 @@ void WebSocket::onClientWritable() delete frame; CC_SAFE_FREE(data->bytes); CC_SAFE_DELETE(data); - _wsHelper->_subThreadWsMessageQueue.erase(iter); + _wsHelper->_subThreadWsMessageQueue->erase(iter); CC_SAFE_DELETE(subThreadMsg); return; } @@ -716,7 +733,7 @@ void WebSocket::onClientWritable() delete ((WebSocketFrame*)data->ext); data->ext = nullptr; CC_SAFE_DELETE(data); - _wsHelper->_subThreadWsMessageQueue.erase(iter); + _wsHelper->_subThreadWsMessageQueue->erase(iter); CC_SAFE_DELETE(subThreadMsg); closeAsync(); @@ -755,7 +772,7 @@ void WebSocket::onClientWritable() delete ((WebSocketFrame*)data->ext); data->ext = nullptr; CC_SAFE_DELETE(data); - _wsHelper->_subThreadWsMessageQueue.erase(iter); + _wsHelper->_subThreadWsMessageQueue->erase(iter); CC_SAFE_DELETE(subThreadMsg); LOGD("-----------------------------------------------------------\n"); @@ -777,12 +794,13 @@ void WebSocket::onClientReceivedData(void* in, ssize_t len) } else { - LOGD("Emtpy message received, index=%d!\n", packageIndex); + LOGD("Empty message received, index=%d!\n", packageIndex); } // If no more data pending, send it to the client thread size_t remainingSize = lws_remaining_packet_payload(_wsInstance); int isFinalFragment = lws_is_final_fragment(_wsInstance); +// LOGD("remainingSize: %d, isFinalFragment: %d\n", (int)remainingSize, isFinalFragment); if (remainingSize == 0 && isFinalFragment) { @@ -793,15 +811,15 @@ void WebSocket::onClientReceivedData(void* in, ssize_t len) ssize_t frameSize = frameData->size(); - bool isBinary = lws_frame_is_binary(_wsInstance); + bool isBinary = (lws_frame_is_binary(_wsInstance) != 0); if (!isBinary) { frameData->push_back('\0'); } - auto instance = this; - _wsHelper->sendMessageToCocosThread([instance, frameData, frameSize, isBinary](){ + std::shared_ptr> isDestroyed = _isDestroyed; + _wsHelper->sendMessageToCocosThread([this, frameData, frameSize, isBinary, isDestroyed](){ // In UI thread LOGD("Notify data len %d to Cocos thread.\n", (int)frameSize); @@ -810,9 +828,13 @@ void WebSocket::onClientReceivedData(void* in, ssize_t len) data.bytes = (char*)frameData->data(); data.len = frameSize; - if (__websocketInstances && __websocketInstances->find(instance) != __websocketInstances->end()) + if (*isDestroyed) { - instance->_delegate->onMessage(instance, data); + LOGD("WebSocket instance was destroyed!\n"); + } + else + { + _delegate->onMessage(this, data); } delete frameData; @@ -832,11 +854,15 @@ void WebSocket::onConnectionOpened() _readyState = State::OPEN; _readStateMutex.unlock(); - auto instance = this; - _wsHelper->sendMessageToCocosThread([instance](){ - if (__websocketInstances && __websocketInstances->find(instance) != __websocketInstances->end()) + std::shared_ptr> isDestroyed = _isDestroyed; + _wsHelper->sendMessageToCocosThread([this, isDestroyed](){ + if (*isDestroyed) { - instance->_delegate->onOpen(instance); + LOGD("WebSocket instance was destroyed!\n"); + } + else + { + _delegate->onOpen(this); } }); } @@ -849,11 +875,15 @@ void WebSocket::onConnectionError() _readyState = State::CLOSING; _readStateMutex.unlock(); - auto instance = this; - _wsHelper->sendMessageToCocosThread([instance](){ - if (__websocketInstances && __websocketInstances->find(instance) != __websocketInstances->end()) + std::shared_ptr> isDestroyed = _isDestroyed; + _wsHelper->sendMessageToCocosThread([this, isDestroyed](){ + if (*isDestroyed) { - instance->_delegate->onError(instance, ErrorCode::CONNECTION_FAILURE); + LOGD("WebSocket instance was destroyed!\n"); + } + else + { + _delegate->onError(this, ErrorCode::CONNECTION_FAILURE); } }); } @@ -872,13 +902,18 @@ void WebSocket::onConnectionClosed() _readyState = State::CLOSED; _readStateMutex.unlock(); - auto instance = this; - _wsHelper->sendMessageToCocosThread([instance](){ - if (__websocketInstances && __websocketInstances->find(instance) != __websocketInstances->end()) + _wsHelper->quitWebSocketThread(); + std::shared_ptr> isDestroyed = _isDestroyed; + _wsHelper->sendMessageToCocosThread([this, isDestroyed](){ + if (*isDestroyed) { - //Waiting for the subThread safety exit - instance->_wsHelper->joinWebSocketThread(); - instance->_delegate->onClose(instance); + LOGD("WebSocket instance was destroyed!\n"); + } + else + { + // Waiting for the subThread safety exit + _wsHelper->joinWebSocketThread(); + _delegate->onClose(this); } }); } @@ -887,6 +922,8 @@ int WebSocket::onSocketCallback(struct lws *wsi, int reason, void *user, void *in, ssize_t len) { + //LOGD("socket callback for %d reason\n", reason); + switch (reason) { case LWS_CALLBACK_CLIENT_ESTABLISHED: @@ -910,10 +947,8 @@ int WebSocket::onSocketCallback(struct lws *wsi, onClientWritable(); break; - case LWS_CALLBACK_GET_THREAD_ID: - break; default: - //LOGD("Unhandled websocket event: %d\n", reason); +// LOGD("Unhandled websocket event: %d\n", reason); break; } @@ -923,4 +958,3 @@ int WebSocket::onSocketCallback(struct lws *wsi, } NS_CC_END - diff --git a/native/cocos/network/WebSocket.h b/native/cocos/network/WebSocket.h index 9755e2aa5f..b639a260f9 100644 --- a/native/cocos/network/WebSocket.h +++ b/native/cocos/network/WebSocket.h @@ -33,7 +33,8 @@ #include #include #include -#include +#include // for std::shared_ptr +#include #include "platform/CCPlatformMacros.h" #include "platform/CCStdC.h" @@ -226,7 +227,7 @@ private: std::mutex _readStateMutex; State _readyState; std::string _host; - int _port; + unsigned int _port; std::string _path; std::vector _receivedData; @@ -237,7 +238,7 @@ private: struct lws* _wsInstance; struct lws_context* _wsContext; - + std::shared_ptr> _isDestroyed; Delegate* _delegate; int _SSLConnection; struct lws_protocols* _wsProtocols; @@ -252,4 +253,3 @@ NS_CC_END /// @} #endif /* defined(__CC_JSB_WEBSOCKET_H__) */ -