Improve code style

This commit is contained in:
halx99 2021-12-06 13:00:44 +08:00
parent 0f4b92c1e4
commit a95a00e96b
2 changed files with 517 additions and 475 deletions

View File

@ -3,8 +3,9 @@ Copyright (c) 2010 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
Copyright (c) 2020 c4games.com Copyright (c) 2020 c4games.com
Copyright (c) 2021 Bytedance Inc.
http://www.cocos2d-x.org https://adxe.org
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
@ -33,7 +34,7 @@ THE SOFTWARE.
#include <signal.h> #include <signal.h>
#if !defined(_WIN32) #if !defined(_WIN32)
// for unix/linux kill // for unix/linux kill
#include <unistd.h> # include <unistd.h>
#endif #endif
#include "openssl/md5.h" #include "openssl/md5.h"
@ -65,7 +66,7 @@ int ccNextPOT(int x)
x = x | (x >> 2); x = x | (x >> 2);
x = x | (x >> 4); x = x | (x >> 4);
x = x | (x >> 8); x = x | (x >> 8);
x = x | (x >>16); x = x | (x >> 16);
return x + 1; return x + 1;
} }
@ -89,19 +90,24 @@ void captureScreen(std::function<void(RefPtr<Image>)> imageCallback)
// !!!Metal: needs setFrameBufferOnly before draw // !!!Metal: needs setFrameBufferOnly before draw
#if defined(CC_USE_METAL) #if defined(CC_USE_METAL)
s_captureScreenListener = eventDispatcher->addCustomEventListener(Director::EVENT_BEFORE_DRAW, [=](EventCustom* /*event*/) { s_captureScreenListener =
eventDispatcher->addCustomEventListener(Director::EVENT_BEFORE_DRAW, [=](EventCustom* /*event*/) {
#else #else
s_captureScreenListener = eventDispatcher->addCustomEventListener(Director::EVENT_AFTER_DRAW, [=](EventCustom* /*event*/) { s_captureScreenListener =
eventDispatcher->addCustomEventListener(Director::EVENT_AFTER_DRAW, [=](EventCustom* /*event*/) {
#endif #endif
eventDispatcher->removeEventListener(s_captureScreenListener); eventDispatcher->removeEventListener(s_captureScreenListener);
s_captureScreenListener = nullptr; s_captureScreenListener = nullptr;
// !!!GL: AFTER_DRAW and BEFORE_END_FRAME // !!!GL: AFTER_DRAW and BEFORE_END_FRAME
renderer->readPixels(renderer->getDefaultRenderTarget(), [=](const backend::PixelBufferDescriptor& pbd) { renderer->readPixels(renderer->getDefaultRenderTarget(), [=](const backend::PixelBufferDescriptor& pbd) {
if (pbd) { if (pbd)
auto image = utils::makeInstance<Image>(&Image::initWithRawData, pbd._data.getBytes(), pbd._data.getSize(), pbd._width, pbd._height, 8, false); {
auto image = utils::makeInstance<Image>(&Image::initWithRawData, pbd._data.getBytes(),
pbd._data.getSize(), pbd._width, pbd._height, 8, false);
imageCallback(image); imageCallback(image);
} }
else imageCallback(nullptr); else
imageCallback(nullptr);
}); });
}); });
} }
@ -130,7 +136,8 @@ void captureNode(Node* startNode, std::function<void(RefPtr<Image>)> imageCallba
// rtx->setKeepMatrix(true); // rtx->setKeepMatrix(true);
Point savedPos = startNode->getPosition(); Point savedPos = startNode->getPosition();
Point anchor; Point anchor;
if (!startNode->isIgnoreAnchorPointForPosition()) { if (!startNode->isIgnoreAnchorPointForPosition())
{
anchor = startNode->getAnchorPoint(); anchor = startNode->getAnchorPoint();
} }
startNode->setPosition(Point(size.width * anchor.x, size.height * anchor.y)); startNode->setPosition(Point(size.width * anchor.x, size.height * anchor.y));
@ -139,15 +146,17 @@ void captureNode(Node* startNode, std::function<void(RefPtr<Image>)> imageCallba
rtx->end(); rtx->end();
startNode->setPosition(savedPos); startNode->setPosition(savedPos);
if (std::abs(scale - 1.0f) < 1e-6f/* no scale */) if (std::abs(scale - 1.0f) < 1e-6f /* no scale */)
finalRtx = rtx; finalRtx = rtx;
else { else
{
/* scale */ /* scale */
auto finalRect = Rect(0, 0, size.width, size.height); auto finalRect = Rect(0, 0, size.width, size.height);
Sprite *sprite = Sprite::createWithTexture(rtx->getSprite()->getTexture(), finalRect); Sprite* sprite = Sprite::createWithTexture(rtx->getSprite()->getTexture(), finalRect);
sprite->setAnchorPoint(Point(0, 0)); sprite->setAnchorPoint(Point(0, 0));
sprite->setFlippedY(true); sprite->setFlippedY(true);
finalRtx = RenderTexture::create(size.width * scale, size.height * scale, backend::PixelFormat::RGBA8, PixelFormat::D24S8); finalRtx = RenderTexture::create(size.width * scale, size.height * scale, backend::PixelFormat::RGBA8,
PixelFormat::D24S8);
sprite->setScale(scale); // or use finalRtx->setKeepMatrix(true); sprite->setScale(scale); // or use finalRtx->setKeepMatrix(true);
finalRtx->begin(); finalRtx->begin();
@ -160,7 +169,8 @@ void captureNode(Node* startNode, std::function<void(RefPtr<Image>)> imageCallba
finalRtx->newImage(imageCallback); finalRtx->newImage(imageCallback);
}; };
auto listener = Director::getInstance()->getEventDispatcher()->addCustomEventListener(Director::EVENT_BEFORE_DRAW, callback); auto listener =
Director::getInstance()->getEventDispatcher()->addCustomEventListener(Director::EVENT_BEFORE_DRAW, callback);
s_captureNodeListener[startNode] = listener; s_captureNodeListener[startNode] = listener;
} }
@ -175,17 +185,19 @@ void captureScreen(std::function<void(bool, const std::string&)> afterCap, const
outfile = FileUtils::getInstance()->getWritablePath() + filename; outfile = FileUtils::getInstance()->getWritablePath() + filename;
captureScreen([_afterCap = std::move(afterCap), _outfile = std::move(outfile)](RefPtr<Image> image) mutable { captureScreen([_afterCap = std::move(afterCap), _outfile = std::move(outfile)](RefPtr<Image> image) mutable {
AsyncTaskPool::getInstance()->enqueue(AsyncTaskPool::TaskType::TASK_IO, [_afterCap = std::move(_afterCap), image = std::move(image), _outfile = std::move(_outfile)]() mutable AsyncTaskPool::getInstance()->enqueue(
{ AsyncTaskPool::TaskType::TASK_IO,
[_afterCap = std::move(_afterCap), image = std::move(image), _outfile = std::move(_outfile)]() mutable {
bool ok = image->saveToFile(_outfile); bool ok = image->saveToFile(_outfile);
Director::getInstance()->getScheduler()->performFunctionInCocosThread([ok, _afterCap = std::move(_afterCap), _outfile = std::move(_outfile)]{ Director::getInstance()->getScheduler()->performFunctionInCocosThread(
[ok, _afterCap = std::move(_afterCap), _outfile = std::move(_outfile)] {
_afterCap(ok, _outfile); _afterCap(ok, _outfile);
}); });
}); });
}); });
} }
std::vector<Node*> findChildren(const Node &node, const std::string &name) std::vector<Node*> findChildren(const Node& node, const std::string& name)
{ {
std::vector<Node*> vec; std::vector<Node*> vec;
@ -223,17 +235,17 @@ double gettime()
struct timeval tv; struct timeval tv;
gettimeofday(&tv, nullptr); gettimeofday(&tv, nullptr);
return (double)tv.tv_sec + (double)tv.tv_usec/1000000; return (double)tv.tv_sec + (double)tv.tv_usec / 1000000;
} }
long long getTimeInMilliseconds() long long getTimeInMilliseconds()
{ {
struct timeval tv; struct timeval tv;
gettimeofday (&tv, nullptr); gettimeofday(&tv, nullptr);
return (long long)tv.tv_sec * 1000 + tv.tv_usec / 1000; return (long long)tv.tv_sec * 1000 + tv.tv_usec / 1000;
} }
Rect getCascadeBoundingBox(Node *node) Rect getCascadeBoundingBox(Node* node)
{ {
Rect cbb; Rect cbb;
Vec2 contentSize = node->getContentSize(); Vec2 contentSize = node->getContentSize();
@ -241,13 +253,15 @@ Rect getCascadeBoundingBox(Node *node)
// check all children bounding box, get maximize box // check all children bounding box, get maximize box
Node* child = nullptr; Node* child = nullptr;
bool merge = false; bool merge = false;
for(auto object : node->getChildren()) for (auto object : node->getChildren())
{ {
child = dynamic_cast<Node*>(object); child = dynamic_cast<Node*>(object);
if (!child->isVisible()) continue; if (!child->isVisible())
continue;
const Rect box = getCascadeBoundingBox(child); const Rect box = getCascadeBoundingBox(child);
if (box.size.width <= 0 || box.size.height <= 0) continue; if (box.size.width <= 0 || box.size.height <= 0)
continue;
if (!merge) if (!merge)
{ {
@ -263,7 +277,8 @@ Rect getCascadeBoundingBox(Node *node)
// merge content size // merge content size
if (contentSize.width > 0 && contentSize.height > 0) if (contentSize.width > 0 && contentSize.height > 0)
{ {
const Rect box = RectApplyAffineTransform(Rect(0, 0, contentSize.width, contentSize.height), node->getNodeToWorldAffineTransform()); const Rect box = RectApplyAffineTransform(Rect(0, 0, contentSize.width, contentSize.height),
node->getNodeToWorldAffineTransform());
if (!merge) if (!merge)
{ {
cbb = box; cbb = box;
@ -286,11 +301,12 @@ Sprite* createSpriteFromBase64Cached(const char* base64String, const char* key)
unsigned char* decoded; unsigned char* decoded;
int length = base64Decode((const unsigned char*)base64String, (unsigned int)strlen(base64String), &decoded); int length = base64Decode((const unsigned char*)base64String, (unsigned int)strlen(base64String), &decoded);
Image *image = new (std::nothrow) Image(); Image* image = new (std::nothrow) Image();
bool imageResult = image->initWithImageData(decoded, length, true); bool imageResult = image->initWithImageData(decoded, length, true);
CCASSERT(imageResult, "Failed to create image from base64!"); CCASSERT(imageResult, "Failed to create image from base64!");
if (!imageResult) { if (!imageResult)
{
CC_SAFE_RELEASE_NULL(image); CC_SAFE_RELEASE_NULL(image);
return nullptr; return nullptr;
} }
@ -309,16 +325,17 @@ Sprite* createSpriteFromBase64(const char* base64String)
unsigned char* decoded; unsigned char* decoded;
int length = base64Decode((const unsigned char*)base64String, (unsigned int)strlen(base64String), &decoded); int length = base64Decode((const unsigned char*)base64String, (unsigned int)strlen(base64String), &decoded);
Image *image = new (std::nothrow) Image(); Image* image = new (std::nothrow) Image();
bool imageResult = image->initWithImageData(decoded, length, decoded); bool imageResult = image->initWithImageData(decoded, length, decoded);
CCASSERT(imageResult, "Failed to create image from base64!"); CCASSERT(imageResult, "Failed to create image from base64!");
if (!imageResult) { if (!imageResult)
{
CC_SAFE_RELEASE_NULL(image); CC_SAFE_RELEASE_NULL(image);
return nullptr; return nullptr;
} }
Texture2D *texture = new (std::nothrow) Texture2D(); Texture2D* texture = new (std::nothrow) Texture2D();
texture->initWithImage(image); texture->initWithImage(image);
texture->setAliasTexParameters(); texture->setAliasTexParameters();
image->release(); image->release();
@ -370,7 +387,7 @@ Node* findChild(Node* levelRoot, int tag)
return nullptr; return nullptr;
} }
std::string getFileMD5Hash(const std::string &filename) std::string getFileMD5Hash(const std::string& filename)
{ {
Data data; Data data;
FileUtils::getInstance()->getContents(filename, &data); FileUtils::getInstance()->getContents(filename, &data);
@ -378,7 +395,8 @@ std::string getFileMD5Hash(const std::string &filename)
return getDataMD5Hash(data); return getDataMD5Hash(data);
} }
std::string getDataMD5Hash(const Data& data) { std::string getDataMD5Hash(const Data& data)
{
// static const unsigned int MD5_DIGEST_LENGTH = 16; // static const unsigned int MD5_DIGEST_LENGTH = 16;
if (data.isNull()) if (data.isNull())
@ -388,10 +406,10 @@ std::string getDataMD5Hash(const Data& data) {
MD5state_st state; MD5state_st state;
uint8_t digest[MD5_DIGEST_LENGTH]; uint8_t digest[MD5_DIGEST_LENGTH];
char hexOutput[(MD5_DIGEST_LENGTH << 1) + 1] = { 0 }; char hexOutput[(MD5_DIGEST_LENGTH << 1) + 1] = {0};
MD5_Init(&state); MD5_Init(&state);
MD5_Update(&state, data.getBytes(), (int) data.getSize()); MD5_Update(&state, data.getBytes(), (int)data.getSize());
MD5_Final(digest, &state); MD5_Final(digest, &state);
for (int di = 0; di < 16; ++di) for (int di = 0; di < 16; ++di)
@ -487,7 +505,8 @@ LanguageType getLanguageTypeByISO2(const char* code)
backend::BlendFactor toBackendBlendFactor(int factor) backend::BlendFactor toBackendBlendFactor(int factor)
{ {
switch (factor) { switch (factor)
{
case GLBlendConst::ONE: case GLBlendConst::ONE:
return backend::BlendFactor::ONE; return backend::BlendFactor::ONE;
case GLBlendConst::ZERO: case GLBlendConst::ZERO:
@ -607,48 +626,55 @@ backend::SamplerAddressMode toBackendAddressMode(int mode)
const Mat4& getAdjustMatrix() const Mat4& getAdjustMatrix()
{ {
static cocos2d::Mat4 adjustMatrix = { static cocos2d::Mat4 adjustMatrix = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0.5, 0.5, 0, 0, 0, 1};
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 0.5, 0.5,
0, 0, 0, 1
};
return adjustMatrix; return adjustMatrix;
} }
std::vector<float> getNormalMat3OfMat4(const Mat4 &mat) std::vector<float> getNormalMat3OfMat4(const Mat4& mat)
{ {
std::vector<float> normalMat(9); std::vector<float> normalMat(9);
Mat4 mvInverse = mat; Mat4 mvInverse = mat;
mvInverse.m[12] = mvInverse.m[13] = mvInverse.m[14] = 0.0f; mvInverse.m[12] = mvInverse.m[13] = mvInverse.m[14] = 0.0f;
mvInverse.inverse(); mvInverse.inverse();
mvInverse.transpose(); mvInverse.transpose();
normalMat[0] = mvInverse.m[0]; normalMat[1] = mvInverse.m[1]; normalMat[2] = mvInverse.m[2]; normalMat[0] = mvInverse.m[0];
normalMat[3] = mvInverse.m[4]; normalMat[4] = mvInverse.m[5]; normalMat[5] = mvInverse.m[6]; normalMat[1] = mvInverse.m[1];
normalMat[6] = mvInverse.m[8]; normalMat[7] = mvInverse.m[9]; normalMat[8] = mvInverse.m[10]; normalMat[2] = mvInverse.m[2];
normalMat[3] = mvInverse.m[4];
normalMat[4] = mvInverse.m[5];
normalMat[5] = mvInverse.m[6];
normalMat[6] = mvInverse.m[8];
normalMat[7] = mvInverse.m[9];
normalMat[8] = mvInverse.m[10];
return normalMat; return normalMat;
} }
std::vector<int> parseIntegerList(const std::string &intsString) { std::vector<int> parseIntegerList(std::string_view intsString)
{
std::vector<int> result; std::vector<int> result;
const char *cStr = intsString.c_str(); if (!intsString.empty())
char *endptr; {
const char* cStr = intsString.data();
char* endptr;
for (int32_t i = strtol(cStr, &endptr, 10); endptr != cStr; i = strtol(cStr, &endptr, 10)) { for (int32_t i = strtol(cStr, &endptr, 10); endptr != cStr; i = strtol(cStr, &endptr, 10))
if (errno == ERANGE) { {
if (errno == ERANGE)
{
errno = 0; errno = 0;
CCLOGWARN("%s contains out of range integers", intsString.c_str()); CCLOGWARN("%s contains out of range integers", intsString.data());
} }
result.push_back(static_cast<int>(i)); result.push_back(static_cast<int>(i));
cStr= endptr; cStr = endptr;
}
} }
return result; return result;
} }
std::string bin2hex(const std::string& binary /*charstring also regard as binary in C/C++*/, int delim, bool prefix) std::string bin2hex(std::string_view binary /*charstring also regard as binary in C/C++*/, int delim, bool prefix)
{ {
char low; char low;
char high; char high;
@ -659,19 +685,19 @@ std::string bin2hex(const std::string& binary /*charstring also regard as binary
std::string result; std::string result;
result.reserve((len << 1) + (delim_needed ? len : 0) + (prefix ? (len << 1) : 0)); result.reserve((len << 1) + (delim_needed ? len : 0) + (prefix ? (len << 1) : 0));
for (size_t i = 0; i < len; ++i) for (size_t i = 0; i < len; ++i)
{ {
auto ch = binary[i]; auto ch = binary[i];
high = (ch >> 4) & 0x0f; high = (ch >> 4) & 0x0f;
low = ch & 0x0f; low = ch & 0x0f;
if (prefix) { if (prefix)
{
result.push_back('0'); result.push_back('0');
result.push_back('x'); result.push_back('x');
} }
auto hic = CC_HEX2CHAR(high); auto hic = nibble2hex(high);
auto lic = CC_HEX2CHAR(low); auto lic = nibble2hex(low);
result.push_back(hic); result.push_back(hic);
result.push_back(lic); result.push_back(lic);
if (delim_needed) if (delim_needed)
@ -692,6 +718,74 @@ void killCurrentProcess()
#endif #endif
} }
unsigned char nibble2hex(unsigned char c)
{
return ((c) < 0xa ? ((c) + '0') : ((c) + 'a' - 10));
} }
unsigned char hex2nibble(unsigned char c)
{
if (c >= '0' && c <= '9')
{
return c - '0';
}
else if (c >= 'a' && c <= 'f')
{
return 10 + (c - 'a');
}
else if (c >= 'A' && c <= 'F')
{
return 10 + (c - 'A');
}
return 0;
}
std::string urlEncode(std::string_view s)
{
std::string encoded;
for (const char c : s)
{
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~')
{
encoded = encoded + c;
}
else
{
char hex[4];
snprintf(hex, sizeof(hex), "%%%02x", c);
encoded = encoded + hex;
}
}
return encoded;
}
std::string urlDecode(std::string_view st)
{
std::string decoded;
const char* s = st.data();
const size_t length = st.length();
for (unsigned int i = 0; i < length; ++i)
{
if (!s[i])
break;
if (s[i] == '%')
{
decoded.push_back(hex2char(s + i + 1));
i = i + 2;
}
else if (s[i] == '+')
{
decoded.push_back(' ');
}
else
{
decoded.push_back(s[i]);
}
}
return decoded;
}
} // namespace utils
NS_CC_END NS_CC_END

View File

@ -3,8 +3,9 @@ Copyright (c) 2010 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
Copyright (c) 2020 c4games.com Copyright (c) 2020 c4games.com
Copyright (c) 2021 Bytedance Inc.
http://www.cocos2d-x.org https://adxe.org
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
@ -36,8 +37,6 @@ THE SOFTWARE.
#include "renderer/backend/Types.h" #include "renderer/backend/Types.h"
#include "math/Mat4.h" #include "math/Mat4.h"
#define CC_HEX2CHAR(hex) ((hex) < 0xa ? ((hex) + '0') : ((hex) + 'a' - 10))
/** @file ccUtils.h /** @file ccUtils.h
Misc free functions Misc free functions
*/ */
@ -65,35 +64,37 @@ class Image;
namespace utils namespace utils
{ {
/** Capture the entire screen. /** Capture the entire screen.
* To ensure the snapshot is applied after everything is updated and rendered in the current frame, * To ensure the snapshot is applied after everything is updated and rendered in the current frame,
* we need to wrap the operation with a custom command which is then inserted into the tail of the render queue. * we need to wrap the operation with a custom command which is then inserted into the tail of the render queue.
* @param afterCaptured specify the callback function which will be invoked after the snapshot is done. * @param afterCaptured specify the callback function which will be invoked after the snapshot is done.
* @param filename specify a filename where the snapshot is stored. This parameter can be either an absolute path or a simple * @param filename specify a filename where the snapshot is stored. This parameter can be either an absolute path or a
* base filename ("hello.png" etc.), don't use a relative path containing directory names.("mydir/hello.png" etc.). * simple base filename ("hello.png" etc.), don't use a relative path containing directory names.("mydir/hello.png"
* etc.).
* @since v4.0 with adxe * @since v4.0 with adxe
*/ */
CC_DLL void captureScreen(std::function<void(RefPtr<Image>)> imageCallback); CC_DLL void captureScreen(std::function<void(RefPtr<Image>)> imageCallback);
/** Capture a specific Node. /** Capture a specific Node.
* @param startNode specify the snapshot Node. It should be cocos2d::Scene * @param startNode specify the snapshot Node. It should be cocos2d::Scene
* @param scale * @param scale
* @returns: return a Image, then can call saveToFile to save the image as "xxx.png or xxx.jpg". * @returns: return a Image, then can call saveToFile to save the image as "xxx.png or xxx.jpg".
* @since v4.0 with adxe * @since v4.0 with adxe
*/ */
CC_DLL void captureNode(Node* startNode, std::function<void(RefPtr<Image>)> imageCallback, float scale = 1.0f); CC_DLL void captureNode(Node* startNode, std::function<void(RefPtr<Image>)> imageCallback, float scale = 1.0f);
/** Capture the entire screen. V4-copmatiable only, [DEPRECATED] /** Capture the entire screen. V4-copmatiable only, [DEPRECATED]
* To ensure the snapshot is applied after everything is updated and rendered in the current frame, * To ensure the snapshot is applied after everything is updated and rendered in the current frame,
* we need to wrap the operation with a custom command which is then inserted into the tail of the render queue. * we need to wrap the operation with a custom command which is then inserted into the tail of the render queue.
* @param afterCaptured specify the callback function which will be invoked after the snapshot is done. * @param afterCaptured specify the callback function which will be invoked after the snapshot is done.
* @param filename specify a filename where the snapshot is stored. This parameter can be either an absolute path or a simple * @param filename specify a filename where the snapshot is stored. This parameter can be either an absolute path or a
* base filename ("hello.png" etc.), don't use a relative path containing directory names.("mydir/hello.png" etc.). * simple base filename ("hello.png" etc.), don't use a relative path containing directory names.("mydir/hello.png"
* etc.).
* @since v4.0 * @since v4.0
*/ */
CC_DLL void captureScreen(std::function<void(bool, const std::string&)> afterCap, const std::string& filename); CC_DLL void captureScreen(std::function<void(bool, const std::string&)> afterCap, const std::string& filename);
/** Find children by name, it will return all child that has the same name. /** Find children by name, it will return all child that has the same name.
* It supports c++ 11 regular expression. It is a helper function of `Node::enumerateChildren()`. * It supports c++ 11 regular expression. It is a helper function of `Node::enumerateChildren()`.
* You can refer to `Node::enumerateChildren()` for detail information. * You can refer to `Node::enumerateChildren()` for detail information.
* *
@ -102,191 +103,193 @@ namespace utils
* @return Array of Nodes that matches the name * @return Array of Nodes that matches the name
* @since v3.2 * @since v3.2
*/ */
CC_DLL std::vector<Node*> findChildren(const Node &node, const std::string &name); CC_DLL std::vector<Node*> findChildren(const Node& node, const std::string& name);
/** Same to ::atof, but strip the string, remain 7 numbers after '.' before call atof. /** Same to ::atof, but strip the string, remain 7 numbers after '.' before call atof.
* Why we need this? Because in android c++_static, atof ( and std::atof ) is unsupported for numbers have long decimal part and contain * Why we need this? Because in android c++_static, atof ( and std::atof ) is unsupported for numbers have long decimal
* several numbers can approximate to 1 ( like 90.099998474121094 ), it will return inf. This function is used to fix this bug. * part and contain several numbers can approximate to 1 ( like 90.099998474121094 ), it will return inf. This function
* is used to fix this bug.
* @param str The string be to converted to double. * @param str The string be to converted to double.
* @return Returns converted value of a string. * @return Returns converted value of a string.
*/ */
CC_DLL double atof(const char* str); CC_DLL double atof(const char* str);
/** Get current exact time, accurate to nanoseconds. /** Get current exact time, accurate to nanoseconds.
* @return Returns the time in seconds since the Epoch. * @return Returns the time in seconds since the Epoch.
*/ */
CC_DLL double gettime(); CC_DLL double gettime();
/** /**
* Get current time in milliseconds, accurate to nanoseconds * Get current time in milliseconds, accurate to nanoseconds
* *
* @return Returns the time in milliseconds since the Epoch. * @return Returns the time in milliseconds since the Epoch.
*/ */
CC_DLL long long getTimeInMilliseconds(); CC_DLL long long getTimeInMilliseconds();
/** /**
* Calculate unionof bounding box of a node and its children. * Calculate unionof bounding box of a node and its children.
* @return Returns unionof bounding box of a node and its children. * @return Returns unionof bounding box of a node and its children.
*/ */
CC_DLL Rect getCascadeBoundingBox(Node *node); CC_DLL Rect getCascadeBoundingBox(Node* node);
/** /**
* Create a sprite instance from base64 encoded image and adds the texture to the Texture Cache. * Create a sprite instance from base64 encoded image and adds the texture to the Texture Cache.
* @return Returns an instance of sprite * @return Returns an instance of sprite
*/ */
CC_DLL Sprite* createSpriteFromBase64Cached(const char* base64String, const char* key); CC_DLL Sprite* createSpriteFromBase64Cached(const char* base64String, const char* key);
/** /**
* Create a sprite instance from base64 encoded image. * Create a sprite instance from base64 encoded image.
* @return Returns an instance of sprite * @return Returns an instance of sprite
*/ */
CC_DLL Sprite* createSpriteFromBase64(const char* base64String); CC_DLL Sprite* createSpriteFromBase64(const char* base64String);
/**
/**
* Find a child by name recursively * Find a child by name recursively
* @return Returns found node or nullptr * @return Returns found node or nullptr
*/ */
CC_DLL Node* findChild(Node* levelRoot, const std::string& name); CC_DLL Node* findChild(Node* levelRoot, const std::string& name);
/** /**
* Find a child by tag recursively * Find a child by tag recursively
* @return Returns found node or nullptr * @return Returns found node or nullptr
*/ */
CC_DLL Node* findChild(Node* levelRoot, int tag); CC_DLL Node* findChild(Node* levelRoot, int tag);
/** /**
* Find a child by name recursively * Find a child by name recursively
* @return Returns found node or nullptr with specified type 'T' * @return Returns found node or nullptr with specified type 'T'
*/ */
template<typename T> template <typename T>
inline T findChild(Node* levelRoot, const std::string& name) inline T findChild(Node* levelRoot, const std::string& name)
{ {
return dynamic_cast<T>(findChild(levelRoot, name)); return dynamic_cast<T>(findChild(levelRoot, name));
} }
/** /**
* Find a child by tag recursively * Find a child by tag recursively
* @return Returns found node or nullptr with specified type 'T' * @return Returns found node or nullptr with specified type 'T'
*/ */
template<typename T> template <typename T>
inline T findChild(Node* levelRoot, int tag) inline T findChild(Node* levelRoot, int tag)
{ {
return dynamic_cast<T>(findChild(levelRoot, tag)); return dynamic_cast<T>(findChild(levelRoot, tag));
} }
/** /**
* Gets the md5 hash for the given file. * Gets the md5 hash for the given file.
* @param filename The file to calculate md5 hash. * @param filename The file to calculate md5 hash.
* @return The md5 hash for the file * @return The md5 hash for the file
*/ */
CC_DLL std::string getFileMD5Hash(const std::string &filename); CC_DLL std::string getFileMD5Hash(const std::string& filename);
/**
/**
* Gets the md5 hash for the given buffer. * Gets the md5 hash for the given buffer.
* @param data The buffer to calculate md5 hash. * @param data The buffer to calculate md5 hash.
* @return The md5 hash for the data * @return The md5 hash for the data
*/ */
CC_DLL std::string getDataMD5Hash(const Data &data); CC_DLL std::string getDataMD5Hash(const Data& data);
/** /**
@brief Converts language iso 639-1 code to LanguageType enum. @brief Converts language iso 639-1 code to LanguageType enum.
@return LanguageType enum. @return LanguageType enum.
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
CC_DLL LanguageType getLanguageTypeByISO2(const char* code); CC_DLL LanguageType getLanguageTypeByISO2(const char* code);
CC_DLL backend::BlendFactor toBackendBlendFactor(int factor); CC_DLL backend::BlendFactor toBackendBlendFactor(int factor);
CC_DLL int toGLBlendFactor(backend::BlendFactor blendFactor); CC_DLL int toGLBlendFactor(backend::BlendFactor blendFactor);
CC_DLL backend::SamplerFilter toBackendSamplerFilter(int mode); CC_DLL backend::SamplerFilter toBackendSamplerFilter(int mode);
CC_DLL backend::SamplerAddressMode toBackendAddressMode(int mode); CC_DLL backend::SamplerAddressMode toBackendAddressMode(int mode);
// Adjust matrix for metal. // Adjust matrix for metal.
CC_DLL const Mat4& getAdjustMatrix(); CC_DLL const Mat4& getAdjustMatrix();
/** /**
Get the Normal Matrix of matrixMV Get the Normal Matrix of matrixMV
*/ */
CC_DLL std::vector<float> getNormalMat3OfMat4(const Mat4 &mat); CC_DLL std::vector<float> getNormalMat3OfMat4(const Mat4& mat);
/** /**
@brief Parses a list of space-separated integers. @brief Parses a list of space-separated integers.
@return Vector of ints. @return Vector of ints.
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
CC_DLL std::vector<int> parseIntegerList(const std::string &intsString); CC_DLL std::vector<int> parseIntegerList(std::string_view intsString);
/** /**
@brief translate charstring/binarystream to hexstring. @brief translate charstring/binarystream to hexstring.
@return hexstring. @return hexstring.
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
CC_DLL std::string bin2hex(const std::string& binary /*charstring also regard as binary in C/C++*/, int delim = -1, bool prefix = false); CC_DLL std::string bin2hex(std::string_view binary /*charstring also regard as binary in C/C++*/,
int delim = -1,
bool prefix = false);
/** /**
@brief killCurrentProcess immidiately, any object's destructor never call @brief killCurrentProcess immidiately, any object's destructor never call
@return NA. @return NA.
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
CC_DLL void killCurrentProcess(); CC_DLL void killCurrentProcess();
/** /**
* Create a Game Object, like CREATE_FUNC, but more powerful * Create a Game Object, like CREATE_FUNC, but more powerful
* @return Returns a RefPtr<T> game object * @return Returns a RefPtr<T> game object
* @remark Auto manage cocos2d::Ref reference count, use std::unique_ptr * @remark Auto manage cocos2d::Ref reference count, use std::unique_ptr
* @limition The init function finit must be public * @limition The init function finit must be public
*/ */
template <typename T, typename F, typename... Ts> template <typename T, typename F, typename... Ts>
static RefPtr<T> makeInstance(F&& memf, Ts&&... args) static RefPtr<T> makeInstance(F&& memf, Ts&&... args)
{ {
RefPtr<T> pRet(ReferencedObject<T>{new(std::nothrow) T()}); RefPtr<T> pRet(ReferencedObject<T>{new (std::nothrow) T()});
if (pRet && std::mem_fn(memf)(pRet.get(), std::forward<Ts>(args)...)) if (pRet && std::mem_fn(memf)(pRet.get(), std::forward<Ts>(args)...))
return pRet; return pRet;
pRet.reset(); pRet.reset();
return pRet; return pRet;
} }
/** /**
* Create a Game Object with 'bool T::init()', like CREATE_FUNC, but more powerful * Create a Game Object with 'bool T::init()', like CREATE_FUNC, but more powerful
* @return Returns a autorelease game object * @return Returns a autorelease game object
* @remark Auto manage cocos2d::Ref reference count, use std::unique_ptr * @remark Auto manage cocos2d::Ref reference count, use std::unique_ptr
* @limition The init function finit must be public * @limition The init function finit must be public
*/ */
template<typename T> inline template <typename T>
static RefPtr<T> makeInstance() inline static RefPtr<T> makeInstance()
{ {
return makeInstance<T>(&T::init); return makeInstance<T>(&T::init);
} }
/** /**
* Create a Game Object, like CREATE_FUNC, but more powerful * Create a Game Object, like CREATE_FUNC, but more powerful
* @return Returns a autorelease game object * @return Returns a autorelease game object
* @remark Auto manage cocos2d::Ref reference count, use AutoReleasePool * @remark Auto manage cocos2d::Ref reference count, use AutoReleasePool
* @limition The init function finit must be public * @limition The init function finit must be public
*/ */
template<typename T, typename F, typename...Ts> template <typename T, typename F, typename... Ts>
inline T* createInstance(F&& finit, Ts&&... args) inline T* createInstance(F&& finit, Ts&&... args)
{
T* pRet = new (std::nothrow) T();
if (pRet && std::mem_fn(finit)(pRet, std::forward<Ts>(args)...))
{ {
T* pRet = new(std::nothrow) T();
if (pRet && std::mem_fn(finit)(pRet, std::forward<Ts>(args)...)) {
pRet->autorelease(); pRet->autorelease();
return pRet; return pRet;
} }
@ -296,32 +299,32 @@ namespace utils
pRet = nullptr; pRet = nullptr;
return nullptr; return nullptr;
} }
} }
/** /**
* Create a Game Object with 'bool T::init()', like CREATE_FUNC, but more powerful * Create a Game Object with 'bool T::init()', like CREATE_FUNC, but more powerful
* @return Returns a autorelease game object * @return Returns a autorelease game object
* @remark Auto manage cocos2d::Ref reference count, use AutoReleasePool * @remark Auto manage cocos2d::Ref reference count, use AutoReleasePool
* @limition The init function finit must be public * @limition The init function finit must be public
*/ */
template<typename T> template <typename T>
inline T* createInstance() inline T* createInstance()
{ {
return ::cocos2d::utils::createInstance<T>(&T::init); return ::cocos2d::utils::createInstance<T>(&T::init);
} }
/** /**
* Create a Game Object with 'bool T::init()', like CREATE_FUNC, but more powerful * Create a Game Object with 'bool T::init()', like CREATE_FUNC, but more powerful
* @return Returns a game object * @return Returns a game object
* @remark You need call release after you don't want use it manually * @remark You need call release after you don't want use it manually
* @limition The init function finit must be public * @limition The init function finit must be public
*/ */
template <typename T, typename F, typename... Ts> template <typename T, typename F, typename... Ts>
static T* newInstance(F&& memf, Ts&&... args) static T* newInstance(F&& memf, Ts&&... args)
{ {
T* pRet = new(std::nothrow) T(); T* pRet = new (std::nothrow) T();
if (pRet && std::mem_fn(memf)(pRet, std::forward<Ts>(args)...)) if (pRet && std::mem_fn(memf)(pRet, std::forward<Ts>(args)...))
{ {
return pRet; return pRet;
@ -332,103 +335,48 @@ namespace utils
pRet = nullptr; pRet = nullptr;
return nullptr; return nullptr;
} }
}
/**
* Create a Game Object with 'bool T::init()', like CREATE_FUNC, but more powerful
* @return Returns a game object
* @remark You need call release after you don't want use it manually
* @limition The init function finit must be public
*/
template<typename T> inline
static T* newInstance()
{
return newInstance<T>(&T::init);
}
// check a number is power of two.
static bool isPOT(int number)
{
return ((number > 0) && (number & (number - 1)) == 0);
}
// Convert ASCII hex digit to a nibble (four bits, 0 - 15).
//
// Use unsigned to avoid signed overflow UB.
inline unsigned char hex2nibble(unsigned char c)
{
if (c >= '0' && c <= '9')
{
return c - '0';
}
else if (c >= 'a' && c <= 'f')
{
return 10 + (c - 'a');
}
else if (c >= 'A' && c <= 'F')
{
return 10 + (c - 'A');
}
return 0;
}
// Convert ASCII hex string (two characters) to byte.
//
// E.g., "0B" => 0x0B, "af" => 0xAF.
inline char hex2char(const char* p)
{
return hex2nibble(p[0]) * 16 + hex2nibble(p[1]);
}
inline std::string urlEncode(const std::string& s)
{
std::string encoded;
for (const char c : s)
{
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~')
{
encoded = encoded + c;
}
else
{
char hex[4];
snprintf(hex, sizeof(hex), "%%%02x", c);
encoded = encoded + hex;
}
}
return encoded;
}
inline std::string urlDecode(const std::string& st)
{
std::string decoded;
const char* s = st.c_str();
const size_t length = st.length();
for (unsigned int i = 0; i < length; ++i)
{
if (!s[i])
break;
if (s[i] == '%')
{
decoded.push_back(hex2char(s + i + 1));
i = i + 2;
}
else if (s[i] == '+')
{
decoded.push_back(' ');
}
else
{
decoded.push_back(s[i]);
}
}
return decoded;
}
} }
/**
* Create a Game Object with 'bool T::init()', like CREATE_FUNC, but more powerful
* @return Returns a game object
* @remark You need call release after you don't want use it manually
* @limition The init function finit must be public
*/
template <typename T>
inline static T* newInstance()
{
return newInstance<T>(&T::init);
}
// check a number is power of two.
inline bool isPOT(int number)
{
return ((number > 0) && (number & (number - 1)) == 0);
}
// Convert a nibble ASCII hex digit
CC_DLL unsigned char nibble2hex(unsigned char c);
// Convert ASCII hex digit to a nibble (four bits, 0 - 15).
//
// Use unsigned to avoid signed overflow UB.
CC_DLL unsigned char hex2nibble(unsigned char c);
// Convert ASCII hex string (two characters) to byte.
//
// E.g., "0B" => 0x0B, "af" => 0xAF.
inline char hex2char(const char* p)
{
return hex2nibble(p[0]) * 16 + hex2nibble(p[1]);
}
CC_DLL std::string urlEncode(std::string_view s);
CC_DLL std::string urlDecode(std::string_view st);
} // namespace utils
NS_CC_END NS_CC_END
#endif // __SUPPORT_CC_UTILS_H__ #endif // __SUPPORT_CC_UTILS_H__