diff --git a/native/cocos/2d/renderer/Batcher2d.cpp b/native/cocos/2d/renderer/Batcher2d.cpp index c4f8965a66..17a41d4d75 100644 --- a/native/cocos/2d/renderer/Batcher2d.cpp +++ b/native/cocos/2d/renderer/Batcher2d.cpp @@ -40,16 +40,16 @@ int32_t sorting2DCount{0}; CC_FORCE_INLINE void fillIndexBuffers(RenderDrawInfo* drawInfo) { // NOLINT(readability-convert-member-functions-to-static) uint16_t* ib = drawInfo->getIDataBuffer(); - + UIMeshBuffer* buffer = drawInfo->getMeshBuffer(); uint32_t indexOffset = buffer->getIndexOffset(); - + uint16_t* indexb = drawInfo->getIbBuffer(); uint32_t indexCount = drawInfo->getIbCount(); - + memcpy(&ib[indexOffset], indexb, indexCount * sizeof(uint16_t)); indexOffset += indexCount; - + buffer->setIndexOffset(indexOffset); } @@ -83,7 +83,7 @@ CC_FORCE_INLINE void fillColor(RenderEntity* entity, RenderDrawInfo* drawInfo) { uint32_t size = drawInfo->getVbCount() * stride; float* vbBuffer = drawInfo->getVbBuffer(); Color temp = entity->getColor(); - + uint32_t offset = 0; for (int i = 0; i < size; i += stride) { offset = i + 5; @@ -91,9 +91,9 @@ CC_FORCE_INLINE void fillColor(RenderEntity* entity, RenderDrawInfo* drawInfo) { // Spine set 'UIRenderer._useVertexOpacity = true', it uses RGBA32 (4 bytes) color and fills color in Skeleton._updateColor and spine/simple.ts assembler. // So for Spine rendering, it will never go here to fill color. vbBuffer[offset] = static_cast(temp.r) / 255.0F; - vbBuffer[offset+1] = static_cast(temp.g) / 255.0F; - vbBuffer[offset+2] = static_cast(temp.b) / 255.0F; - vbBuffer[offset+3] = entity->getOpacity(); + vbBuffer[offset + 1] = static_cast(temp.g) / 255.0F; + vbBuffer[offset + 2] = static_cast(temp.b) / 255.0F; + vbBuffer[offset + 3] = entity->getOpacity(); } } @@ -110,7 +110,7 @@ Batcher2d::Batcher2d(Root* root) _root = root; _device = _root->getDevice(); _stencilManager = StencilManager::getInstance(); - + _recordedRendererInfoQueue.reserve(100); } @@ -138,7 +138,7 @@ Batcher2d::~Batcher2d() { // NOLINT _maskAttributes.clear(); } -ccstd::vector &Batcher2d::getRecordedRendererInfoQueue() { +ccstd::vector& Batcher2d::getRecordedRendererInfoQueue() { return _recordedRendererInfoQueue; } @@ -170,11 +170,11 @@ void Batcher2d::fillBuffersAndMergeBatches() { for (auto* rootNode : _rootNodeArr) { // _batches will add by generateBatch walk(rootNode, 1, false); - + if (ENABLE_SORTING_2D && sorting2DCount > 0) { flushRecordedUIRenderers(); } - + generateBatch(_currEntity, _currDrawInfo); auto* scene = rootNode->getScene()->getRenderScene(); @@ -186,7 +186,7 @@ void Batcher2d::fillBuffersAndMergeBatches() { } } -void Batcher2d::handleUIRenderer(RenderEntity *entity) { // NOLINT(misc-no-recursion) +void Batcher2d::handleUIRenderer(RenderEntity* entity) { // NOLINT(misc-no-recursion) uint32_t size = entity->getRenderDrawInfosSize(); for (uint32_t i = 0; i < size; i++) { auto* drawInfo = entity->getRenderDrawInfoAt(i); @@ -195,25 +195,25 @@ void Batcher2d::handleUIRenderer(RenderEntity *entity) { // NOLINT(misc-no-recur entity->setVBColorDirty(false); } -int32_t Batcher2d::recordUIRenderer(RenderEntity *entity) { +int32_t Batcher2d::recordUIRenderer(RenderEntity* entity) { if (!ENABLE_SORTING_2D) return -1; - auto &queue = getRecordedRendererInfoQueue(); - auto &info = queue.emplace_back(); + auto& queue = getRecordedRendererInfoQueue(); + auto& info = queue.emplace_back(); info.renderEntity = entity; return static_cast(queue.size() - 1); } void Batcher2d::flushRecordedUIRenderers() { // NOLINT(misc-no-recursion) if (!ENABLE_SORTING_2D) return; - auto &queue = getRecordedRendererInfoQueue(); + auto& queue = getRecordedRendererInfoQueue(); if (queue.empty()) return; - std::stable_sort(queue.begin(), queue.end(), [](const auto &a, const auto &b){ + std::stable_sort(queue.begin(), queue.end(), [](const auto& a, const auto& b) { return a.renderEntity->getPriority() < b.renderEntity->getPriority(); }); - for (const auto &info : queue) { - auto *entity = info.renderEntity; + for (const auto& info : queue) { + auto* entity = info.renderEntity; if (entity) { handleUIRenderer(entity); } @@ -227,13 +227,13 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { / } bool breakWalk = false; auto* entity = static_cast(node->getUserData()); - + const bool isCurrentColorDirty = node->_isColorDirty() || parentColorDirty; const float localOpacity = node->_getLocalOpacity(); // Keep the same logic as which in batcher-2d.ts const float finalOpacity = parentOpacity * localOpacity * (entity ? entity->getColorAlpha() : 1.F); node->_setFinalOpacity(finalOpacity); - + const bool visible = math::isNotEqualF(finalOpacity, 0); if (entity) { @@ -244,7 +244,7 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { / entity->setOpacity(finalOpacity); entity->setVBColorDirty(true); } - + if (ENABLE_SORTING_2D && sorting2DCount > 0) { if (entity->getIsMask()) { flushRecordedUIRenderers(); @@ -257,7 +257,7 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { / handleUIRenderer(entity); } } - + if (entity->getRenderEntityType() == RenderEntityType::CROSSED) { breakWalk = true; } @@ -271,7 +271,7 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { / walk(child, thisOpacity, isCurrentColorDirty); } } - + if (isCurrentColorDirty) { node->_setColorDirty(false); } @@ -283,7 +283,7 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { / flushRecordedUIRenderers(); } } - + if (visible && _stencilManager->getMaskStackSize() > 0) { handlePostRender(entity); } @@ -521,7 +521,7 @@ void Batcher2d::generateBatch(RenderEntity* entity, RenderDrawInfo* drawInfo) { curdrawBatch->setFirstIndex(indexOffset); curdrawBatch->setIndexCount(indexCount); curdrawBatch->fillPass(_currMaterial, depthStencil, dssHash); - const auto &passes = curdrawBatch->getPasses(); + const auto& passes = curdrawBatch->getPasses(); if (!passes.empty()) { const auto& pass = passes.at(0); if (entity->getUseLocal()) { diff --git a/native/cocos/2d/renderer/Batcher2d.h b/native/cocos/2d/renderer/Batcher2d.h index fcd649968d..14fe4a18f0 100644 --- a/native/cocos/2d/renderer/Batcher2d.h +++ b/native/cocos/2d/renderer/Batcher2d.h @@ -41,13 +41,13 @@ using UIMeshBufferArray = ccstd::vector; using UIMeshBufferMap = ccstd::unordered_map; struct RecordedRendererInfo { - RenderEntity *renderEntity{nullptr}; + RenderEntity* renderEntity{nullptr}; }; class Batcher2d final { public: static void setSorting2DCount(int32_t v); - + Batcher2d(); explicit Batcher2d(Root* root); ~Batcher2d(); @@ -87,10 +87,10 @@ private: void createClearModel(); gfx::DescriptorSet* getDescriptorSet(gfx::Texture* texture, gfx::Sampler* sampler, const gfx::DescriptorSetLayout* dsLayout); - - ccstd::vector &getRecordedRendererInfoQueue(); - void handleUIRenderer(RenderEntity *entity); - int32_t recordUIRenderer(RenderEntity *entity); + + ccstd::vector& getRecordedRendererInfoQueue(); + void handleUIRenderer(RenderEntity* entity); + int32_t recordUIRenderer(RenderEntity* entity); void flushRecordedUIRenderers(); StencilManager* _stencilManager{nullptr}; @@ -103,7 +103,7 @@ private: // manage memory manually ccstd::vector _batches; memop::Pool _drawBatchPool; - + ccstd::vector _recordedRendererInfoQueue; // weak reference diff --git a/native/cocos/2d/renderer/RenderDrawInfo.h b/native/cocos/2d/renderer/RenderDrawInfo.h index a0ba0e70f5..452b694911 100644 --- a/native/cocos/2d/renderer/RenderDrawInfo.h +++ b/native/cocos/2d/renderer/RenderDrawInfo.h @@ -24,8 +24,8 @@ #pragma once #include "2d/renderer/UIMeshBuffer.h" -#include "base/Ptr.h" #include "base/Macros.h" +#include "base/Ptr.h" #include "base/TypeDef.h" #include "bindings/utils/BindingUtils.h" #include "core/ArrayBuffer.h" @@ -115,7 +115,7 @@ public: inline void setIsMeshBuffer(bool isMeshBuffer) { _drawInfoAttrs._isMeshBuffer = isMeshBuffer ? 1 : 0; } - + inline bool isVertexPositionInWorld() const { return _drawInfoAttrs._isVertexPositionInWorld != 0; } @@ -262,9 +262,9 @@ private: struct DrawInfoAttrs { RenderDrawInfoType _drawInfoType{RenderDrawInfoType::COMP}; bool _vertDirty{false}; - uint8_t _isMeshBuffer: 1; - uint8_t _isVertexPositionInWorld: 1; - uint8_t _padding: 6; + uint8_t _isMeshBuffer : 1; + uint8_t _isVertexPositionInWorld : 1; + uint8_t _padding : 6; uint8_t _stride{0}; uint16_t _bufferId{0}; uint16_t _accId{0}; diff --git a/native/cocos/2d/renderer/RenderEntity.cpp b/native/cocos/2d/renderer/RenderEntity.cpp index 1b61930703..10bbb90443 100644 --- a/native/cocos/2d/renderer/RenderEntity.cpp +++ b/native/cocos/2d/renderer/RenderEntity.cpp @@ -33,11 +33,11 @@ RenderEntity::RenderEntity(RenderEntityType type) : _renderEntityType(type) { } else { ccnew_placement(&_dynamicDrawInfos) ccstd::vector(); } - + _entityAttrLayout.enabledIndex = 0; _entityAttrLayout.useLocal = 0; _entityAttrLayout.paddings = 0; - + _entitySharedBufferActor.initialize(&_entityAttrLayout, sizeof(EntityAttrLayout)); } diff --git a/native/cocos/2d/renderer/RenderEntity.h b/native/cocos/2d/renderer/RenderEntity.h index f1677eded5..63740525d0 100644 --- a/native/cocos/2d/renderer/RenderEntity.h +++ b/native/cocos/2d/renderer/RenderEntity.h @@ -49,7 +49,7 @@ enum class MaskMode : uint8_t { MASK_NODE_INVERTED }; -enum class FillColorType: uint8_t { +enum class FillColorType : uint8_t { COLOR = 0, VERTEX, }; @@ -62,9 +62,9 @@ struct EntityAttrLayout { uint8_t colorA{255}; uint8_t maskMode{0}; FillColorType fillColorType{FillColorType::COLOR}; - uint8_t enabledIndex: 1; - uint8_t useLocal: 1; - uint8_t paddings: 6; + uint8_t enabledIndex : 1; + uint8_t useLocal : 1; + uint8_t paddings : 6; uint8_t paddings2{0}; }; @@ -99,7 +99,7 @@ public: inline void setUseLocal(bool useLocal) { _entityAttrLayout.useLocal = useLocal; } - + inline FillColorType getFillColorType() const { return _entityAttrLayout.fillColorType; } inline Node* getNode() const { return _node; } @@ -142,7 +142,7 @@ public: inline RenderDrawInfo* getRenderDrawInfoAt(uint32_t index) { return _renderEntityType == RenderEntityType::STATIC ? &(_staticDrawInfos[index]) : _dynamicDrawInfos[index]; } - + inline uint32_t getPriority() const { return _entityAttrLayout.priority; } private: @@ -152,7 +152,7 @@ private: // weak reference Node* _renderTransform{nullptr}; - + bindings::NativeMemorySharedToScriptActor _entitySharedBufferActor; union { @@ -160,13 +160,13 @@ private: ccstd::vector _dynamicDrawInfos; }; EntityAttrLayout _entityAttrLayout; - + StencilStage _stencilStage{StencilStage::DISABLED}; RenderEntityType _renderEntityType{RenderEntityType::STATIC}; uint8_t _staticDrawInfoSize{0}; bool _vbColorDirty{true}; uint8_t _paddings[1]; - + float _opacity{1.0F}; }; diff --git a/native/cocos/2d/renderer/UIMeshBuffer.h b/native/cocos/2d/renderer/UIMeshBuffer.h index 8e2bbef8e5..8bd17ffd20 100644 --- a/native/cocos/2d/renderer/UIMeshBuffer.h +++ b/native/cocos/2d/renderer/UIMeshBuffer.h @@ -23,12 +23,12 @@ ****************************************************************************/ #pragma once -#include "base/Ptr.h" #include "base/Macros.h" +#include "base/Ptr.h" #include "base/TypeDef.h" -#include "renderer/gfx-base/GFXInputAssembler.h" -#include "renderer/gfx-base/GFXDef-common.h" #include "renderer/gfx-base/GFXBuffer.h" +#include "renderer/gfx-base/GFXDef-common.h" +#include "renderer/gfx-base/GFXInputAssembler.h" namespace cc { diff --git a/native/cocos/2d/renderer/UIModelProxy.cpp b/native/cocos/2d/renderer/UIModelProxy.cpp index 6a6ebb7e28..e7c57f8d0c 100644 --- a/native/cocos/2d/renderer/UIModelProxy.cpp +++ b/native/cocos/2d/renderer/UIModelProxy.cpp @@ -58,13 +58,13 @@ void UIModelProxy::activeSubModels() { auto* vertexBuffer = _device->createBuffer({ gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST, gfx::MemoryUsageBit::DEVICE, - 65536 * _stride, // Uint16 can address 65536 vertices (indices 0–65535) + 65536 * _stride, // Uint16 can address 65536 vertices (indices 0–65535) _stride, }); auto* indexBuffer = _device->createBuffer({ gfx::BufferUsageBit::INDEX | gfx::BufferUsageBit::TRANSFER_DST, gfx::MemoryUsageBit::DEVICE, - 65536 * sizeof(uint16_t) * 2, // Uint16 can address 65536 vertices (indices 0–65535) + 65536 * sizeof(uint16_t) * 2, // Uint16 can address 65536 vertices (indices 0–65535) sizeof(uint16_t), }); gfx::BufferList vbReference; @@ -133,8 +133,8 @@ void UIModelProxy::clear() { return; } const auto& subModels = _model->getSubModels(); - for (const auto &subModel : subModels) { - auto *ia = subModel->getInputAssembler(); + for (const auto& subModel : subModels) { + auto* ia = subModel->getInputAssembler(); ia->setVertexCount(0); ia->setIndexCount(0); } diff --git a/native/cocos/3d/assets/Mesh.cpp b/native/cocos/3d/assets/Mesh.cpp index 1eb4e1acfc..f3448109f4 100644 --- a/native/cocos/3d/assets/Mesh.cpp +++ b/native/cocos/3d/assets/Mesh.cpp @@ -531,14 +531,14 @@ void Mesh::initialize() { uint32_t vertexCount = _struct.vertexBundles[prim.vertexBundelIndices[0]].view.count; #if CC_OPTIMIZE_MESH_DATA if (vertexCount <= 65536) { // Uint16 can address 65536 vertices (indices 0–65535) - dstStride >>= 1; // Reduce to short. + dstStride >>= 1; // Reduce to short. dstSize >>= 1; } else if (!gfxDevice->hasFeature(gfx::Feature::ELEMENT_INDEX_UINT)) { continue; // Ignore this primitive } #else if (!gfxDevice->hasFeature(gfx::Feature::ELEMENT_INDEX_UINT)) { - if (vertexCount > 65536) { // Uint16 can address 65536 vertices (indices 0–65535) + if (vertexCount > 65536) { // Uint16 can address 65536 vertices (indices 0–65535) CC_LOG_WARNING("Device does not support UINT element index type and vertexCount (%u) is larger than ushort", vertexCount); continue; } diff --git a/native/cocos/3d/misc/CreateMesh.cpp b/native/cocos/3d/misc/CreateMesh.cpp index 0db64ef7dc..21626ba833 100644 --- a/native/cocos/3d/misc/CreateMesh.cpp +++ b/native/cocos/3d/misc/CreateMesh.cpp @@ -310,7 +310,7 @@ Mesh::ICreateInfo MeshUtils::createDynamicMeshInfo(const IDynamicGeometry &geome if (aOptions.has_value()) { options = aOptions.value(); } - + gfx::AttributeList attributes; uint32_t stream = 0U; diff --git a/native/cocos/audio/android/AudioDecoderSLES.cpp b/native/cocos/audio/android/AudioDecoderSLES.cpp index 43b7a147cd..f78dd169bb 100644 --- a/native/cocos/audio/android/AudioDecoderSLES.cpp +++ b/native/cocos/audio/android/AudioDecoderSLES.cpp @@ -25,8 +25,8 @@ #define LOG_TAG "AudioDecoderSLES" -#include "base/Macros.h" #include "audio/android/AudioDecoderSLES.h" +#include "base/Macros.h" #include "platform/FileUtils.h" #include diff --git a/native/cocos/audio/android/AudioEngine-inl.cpp b/native/cocos/audio/android/AudioEngine-inl.cpp index 561d6ae5e3..fa15c124a4 100644 --- a/native/cocos/audio/android/AudioEngine-inl.cpp +++ b/native/cocos/audio/android/AudioEngine-inl.cpp @@ -29,9 +29,9 @@ #include // for native asset manager #if CC_PLATFORM == CC_PLATFORM_ANDROID -#include -#include -#include + #include + #include + #include #endif #include @@ -45,11 +45,11 @@ #include "base/UTF8.h" #include "base/memory/Memory.h" #if CC_PLATFORM == CC_PLATFORM_ANDROID -#include "platform/android/FileUtils-android.h" -#include "platform/java/jni/JniHelper.h" -#include "platform/java/jni/JniImp.h" + #include "platform/android/FileUtils-android.h" + #include "platform/java/jni/JniHelper.h" + #include "platform/java/jni/JniImp.h" #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY -#include "cocos/platform/openharmony/FileUtils-OpenHarmony.h" + #include "cocos/platform/openharmony/FileUtils-OpenHarmony.h" #endif #include "audio/android/AudioDecoder.h" @@ -68,20 +68,20 @@ namespace { AudioEngineImpl *gAudioImpl = nullptr; int outputSampleRate = 44100; #if CC_PLATFORM == CC_PLATFORM_ANDROID -int bufferSizeInFrames = 192; +int bufferSizeInFrames = 192; #endif void getAudioInfo() { #if CC_PLATFORM == CC_PLATFORM_ANDROID - JNIEnv * env = JniHelper::getEnv(); - jclass audioSystem = env->FindClass("android/media/AudioSystem"); - jmethodID method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputSamplingRate", "()I"); - outputSampleRate = env->CallStaticIntMethod(audioSystem, method); - method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputFrameCount", "()I"); - bufferSizeInFrames = env->CallStaticIntMethod(audioSystem, method); + JNIEnv *env = JniHelper::getEnv(); + jclass audioSystem = env->FindClass("android/media/AudioSystem"); + jmethodID method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputSamplingRate", "()I"); + outputSampleRate = env->CallStaticIntMethod(audioSystem, method); + method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputFrameCount", "()I"); + bufferSizeInFrames = env->CallStaticIntMethod(audioSystem, method); #else // In openharmony, setting to 48K does not cause audio delays - outputSampleRate = 48000; + outputSampleRate = 48000; #endif } } // namespace @@ -123,8 +123,8 @@ static int fdGetter(const ccstd::string &url, off_t *start, off_t *length) { AAsset_close(asset); } #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY - FileUtilsOpenHarmony* fileUtils = dynamic_cast(FileUtils::getInstance()); - if(fileUtils) { + FileUtilsOpenHarmony *fileUtils = dynamic_cast(FileUtils::getInstance()); + if (fileUtils) { RawFileDescriptor64 descriptor; fileUtils->getRawFileDescriptor(url, descriptor); fd = descriptor.fd; @@ -189,27 +189,27 @@ bool AudioEngineImpl::init() { CC_LOG_ERROR("get the engine interface fail"); break; } - #if CC_PLATFORM == CC_PLATFORM_ANDROID - // create output mix - const SLInterfaceID outputMixIIDs[] = {}; - const SLboolean outputMixReqs[] = {}; - result = (*_engineEngine)->CreateOutputMix(_engineEngine, &_outputMixObject, 0, outputMixIIDs, outputMixReqs); - if (SL_RESULT_SUCCESS != result) { - CC_LOG_ERROR("create output mix fail"); - break; - } +#if CC_PLATFORM == CC_PLATFORM_ANDROID + // create output mix + const SLInterfaceID outputMixIIDs[] = {}; + const SLboolean outputMixReqs[] = {}; + result = (*_engineEngine)->CreateOutputMix(_engineEngine, &_outputMixObject, 0, outputMixIIDs, outputMixReqs); + if (SL_RESULT_SUCCESS != result) { + CC_LOG_ERROR("create output mix fail"); + break; + } - // realize the output mix - result = (*_outputMixObject)->Realize(_outputMixObject, SL_BOOLEAN_FALSE); - if (SL_RESULT_SUCCESS != result) { - CC_LOG_ERROR("realize the output mix fail"); - break; - } + // realize the output mix + result = (*_outputMixObject)->Realize(_outputMixObject, SL_BOOLEAN_FALSE); + if (SL_RESULT_SUCCESS != result) { + CC_LOG_ERROR("realize the output mix fail"); + break; + } - _audioPlayerProvider = ccnew AudioPlayerProvider(_engineEngine, _outputMixObject, outputSampleRate, bufferSizeInFrames, fdGetter, &gCallerThreadUtils); - #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY - _audioPlayerProvider = ccnew AudioPlayerProvider(_engineEngine, outputSampleRate, fdGetter, &gCallerThreadUtils); - #endif + _audioPlayerProvider = ccnew AudioPlayerProvider(_engineEngine, _outputMixObject, outputSampleRate, bufferSizeInFrames, fdGetter, &gCallerThreadUtils); +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY + _audioPlayerProvider = ccnew AudioPlayerProvider(_engineEngine, outputSampleRate, fdGetter, &gCallerThreadUtils); +#endif ret = true; } while (false); @@ -227,14 +227,14 @@ int AudioEngineImpl::play2d(const ccstd::string &filePath, bool loop, float volu auto audioId = AudioEngine::INVALID_AUDIO_ID; do { - #if CC_PLATFORM == CC_PLATFORM_ANDROID - if (_engineEngine == nullptr || _audioPlayerProvider == nullptr) { - break; - } - #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY - if (_audioPlayerProvider == nullptr) - break; - #endif +#if CC_PLATFORM == CC_PLATFORM_ANDROID + if (_engineEngine == nullptr || _audioPlayerProvider == nullptr) { + break; + } +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY + if (_audioPlayerProvider == nullptr) + break; +#endif auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); @@ -443,12 +443,12 @@ PCMHeader AudioEngineImpl::getPCMHeader(const char *url) { CC_LOG_DEBUG("file %s pcm data already cached", url); return header; } - #if CC_PLATFORM == CC_PLATFORM_ANDROID +#if CC_PLATFORM == CC_PLATFORM_ANDROID AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(_engineEngine, fileFullPath, bufferSizeInFrames, outputSampleRate, fdGetter); - #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY +#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder( _engineEngine, fileFullPath, _audioPlayerProvider->getBufferSizeInFrames(), outputSampleRate, fdGetter); - #endif +#endif if (decoder == nullptr) { CC_LOG_DEBUG("decode %s failed, the file formate might not support", url); return header; @@ -482,12 +482,12 @@ ccstd::vector AudioEngineImpl::getOriginalPCMBuffer(const char *url, ui if (_audioPlayerProvider->getPcmData(url, data)) { CC_LOG_DEBUG("file %s pcm data already cached", url); } else { - #if CC_PLATFORM == CC_PLATFORM_ANDROID +#if CC_PLATFORM == CC_PLATFORM_ANDROID AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(_engineEngine, fileFullPath, bufferSizeInFrames, outputSampleRate, fdGetter); - #else +#else AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder( _engineEngine, fileFullPath, _audioPlayerProvider->getBufferSizeInFrames(), outputSampleRate, fdGetter); - #endif +#endif if (decoder == nullptr) { CC_LOG_DEBUG("decode %s failed, the file formate might not support", url); return pcmData; diff --git a/native/cocos/audio/android/AudioEngine-inl.h b/native/cocos/audio/android/AudioEngine-inl.h index 8ef0771931..4df1bfa146 100644 --- a/native/cocos/audio/android/AudioEngine-inl.h +++ b/native/cocos/audio/android/AudioEngine-inl.h @@ -26,9 +26,9 @@ #include #if CC_PLATFORM == CC_PLATFORM_ANDROID -#include + #include #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY -#include + #include #endif #include #include "audio/include/AudioDef.h" diff --git a/native/cocos/audio/android/AudioMixer.h b/native/cocos/audio/android/AudioMixer.h index bb56df3c0f..7e82c31a74 100644 --- a/native/cocos/audio/android/AudioMixer.h +++ b/native/cocos/audio/android/AudioMixer.h @@ -17,9 +17,9 @@ #pragma once -#include -#include #include +#include +#include #include "audio/android/AudioBufferProvider.h" #include "audio/android/AudioResamplerPublic.h" @@ -160,7 +160,7 @@ private: struct track_t; typedef void (*hook_t)(track_t *t, int32_t *output, size_t numOutFrames, int32_t *temp, int32_t *aux); //NOLINT(modernize-use-using) - static const int BLOCKSIZE = 16; // 4 cache lines + static const int BLOCKSIZE = 16; // 4 cache lines struct track_t { uint32_t needs; @@ -288,19 +288,19 @@ private: }; // bitmask of allocated track names, where bit 0 corresponds to TRACK0 etc. - uint32_t mTrackNames;// NOLINT(readability-identifier-naming) + uint32_t mTrackNames; // NOLINT(readability-identifier-naming) // bitmask of configured track names; ~0 if maxNumTracks == MAX_NUM_TRACKS, // but will have fewer bits set if maxNumTracks < MAX_NUM_TRACKS - const uint32_t mConfiguredNames;// NOLINT(readability-identifier-naming) + const uint32_t mConfiguredNames; // NOLINT(readability-identifier-naming) - const uint32_t mSampleRate;// NOLINT(readability-identifier-naming) + const uint32_t mSampleRate; // NOLINT(readability-identifier-naming) //cjh NBLog::Writer mDummyLog; public: //cjh void setLog(NBLog::Writer* log); private: - state_t mState __attribute__((aligned(32)));// NOLINT(readability-identifier-naming) + state_t mState __attribute__((aligned(32))); // NOLINT(readability-identifier-naming) // Call after changing either the enabled status of a track, or parameters of an enabled track. // OK to call more often than that, but unnecessary. @@ -309,19 +309,19 @@ private: bool setChannelMasks(int name, audio_channel_mask_t trackChannelMask, audio_channel_mask_t mixerChannelMask); - static void track__genericResample(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming) - static void track__nop(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming) - static void track__16BitsStereo(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming) - static void track__16BitsMono(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming) + static void track__genericResample(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming) + static void track__nop(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming) + static void track__16BitsStereo(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming) + static void track__16BitsMono(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming) static void volumeRampStereo(track_t *t, int32_t *out, size_t frameCount, int32_t *temp, int32_t *aux); static void volumeStereo(track_t *t, int32_t *out, size_t frameCount, int32_t *temp, int32_t *aux); - static void process__validate(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming) - static void process__nop(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming) - static void process__genericNoResampling(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming) - static void process__genericResampling(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming) - static void process__OneTrack16BitsStereoNoResampling(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming) + static void process__validate(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming) + static void process__nop(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming) + static void process__genericNoResampling(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming) + static void process__genericResampling(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming) + static void process__OneTrack16BitsStereoNoResampling(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming) static int64_t calculateOutputPTS(const track_t &t, int64_t basePTS, int outputFrameIndex); @@ -347,11 +347,11 @@ private: // multi-format process hooks template - static void process_NoResampleOneTrack(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming) + static void process_NoResampleOneTrack(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming) // multi-format track hooks template - static void track__Resample(track_t *t, TO *out, size_t frameCount, TO *temp __unused, TA *aux);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming) + static void track__Resample(track_t *t, TO *out, size_t frameCount, TO *temp __unused, TA *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming) template static void track__NoResample(track_t *t, TO *out, size_t frameCount, TO *temp __unused, TA *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming) diff --git a/native/cocos/audio/android/AudioMixerController.h b/native/cocos/audio/android/AudioMixerController.h index b9690a92ba..f1a6835192 100644 --- a/native/cocos/audio/android/AudioMixerController.h +++ b/native/cocos/audio/android/AudioMixerController.h @@ -33,8 +33,8 @@ #include "base/std/container/vector.h" #if CC_PLATFORM == CC_PLATFORM_OPENHARMONY -// for openharmony platform, buffer size is 4458 in normal latency mode, 240 in fast latency mode -#define MAX_AUDIO_BUFFER_SIZE 4458 + // for openharmony platform, buffer size is 4458 in normal latency mode, 240 in fast latency mode + #define MAX_AUDIO_BUFFER_SIZE 4458 #endif namespace cc { diff --git a/native/cocos/audio/android/AudioPlayerProvider.cpp b/native/cocos/audio/android/AudioPlayerProvider.cpp index 49610052c7..cafe0c1b55 100644 --- a/native/cocos/audio/android/AudioPlayerProvider.cpp +++ b/native/cocos/audio/android/AudioPlayerProvider.cpp @@ -42,14 +42,14 @@ #include "base/ThreadPool.h" #include "base/memory/Memory.h" #if CC_PLATFORM == CC_PLATFORM_ANDROID -#include -#include "audio/android/UrlAudioPlayer.h" -#include "audio/android/PcmAudioService.h" + #include + #include "audio/android/PcmAudioService.h" + #include "audio/android/UrlAudioPlayer.h" #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY -#include "cocos/platform/FileUtils.h" -#include "cocos/platform/openharmony/FileUtils-OpenHarmony.h" -#include "audio/openharmony/UrlAudioPlayer.h" -#include "audio/openharmony/PcmAudioService.h" + #include "audio/openharmony/PcmAudioService.h" + #include "audio/openharmony/UrlAudioPlayer.h" + #include "cocos/platform/FileUtils.h" + #include "cocos/platform/openharmony/FileUtils-OpenHarmony.h" #endif #include // for std::find_if #include @@ -107,12 +107,9 @@ AudioPlayerProvider::AudioPlayerProvider(SLEngineItf engineItf, SLObjectItf outp } #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY AudioPlayerProvider::AudioPlayerProvider(SLEngineItf engineItf, int deviceSampleRate, - const FdGetterCallback &fdGetterCallback, + const FdGetterCallback &fdGetterCallback, ICallerThreadUtils *callerThreadUtils) - : _engineItf(engineItf), _deviceSampleRate(deviceSampleRate), _fdGetterCallback(fdGetterCallback), - _callerThreadUtils(callerThreadUtils), _pcmAudioService(nullptr), - _mixController(nullptr), _threadPool(LegacyThreadPool::newCachedThreadPool(1, 8, 5, 2, 2)) -{ +: _engineItf(engineItf), _deviceSampleRate(deviceSampleRate), _fdGetterCallback(fdGetterCallback), _callerThreadUtils(callerThreadUtils), _pcmAudioService(nullptr), _mixController(nullptr), _threadPool(LegacyThreadPool::newCachedThreadPool(1, 8, 5, 2, 2)) { _mixController = ccnew AudioMixerController(_deviceSampleRate, 2); _pcmAudioService = ccnew PcmAudioService(); _pcmAudioService->init(_mixController, 2, deviceSampleRate, &_bufferSizeInFrames); @@ -364,13 +361,13 @@ AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo( fileSize = length; #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY RawFileDescriptor64 descriptor; - FileUtilsOpenHarmony* fileUtils = static_cast(FileUtils::getInstance()); - if(!fileUtils) { + FileUtilsOpenHarmony *fileUtils = static_cast(FileUtils::getInstance()); + if (!fileUtils) { return info; } FileUtils::Status status = fileUtils->getRawFileDescriptor(audioFilePath, descriptor); - if(status != FileUtils::Status::OK || descriptor.fd<= 0) { + if (status != FileUtils::Status::OK || descriptor.fd <= 0) { ALOGE("Failed to open file descriptor for %s", audioFilePath.c_str()); return info; } @@ -412,9 +409,9 @@ bool AudioPlayerProvider::isSmallFile(const AudioFileInfo &info) { //NOLINT(read extension = audioFileInfo.url.substr(pos); } auto *iter = std::find_if(std::begin(gAudioFileIndicator), std::end(gAudioFileIndicator), - [&extension](const AudioFileIndicator &judge) -> bool { - return judge.extension == extension; - }); + [&extension](const AudioFileIndicator &judge) -> bool { + return judge.extension == extension; + }); if (iter != std::end(gAudioFileIndicator)) { // ALOGV("isSmallFile: found: %s: ", iter->extension.c_str()); @@ -472,19 +469,18 @@ UrlAudioPlayer *AudioPlayerProvider::createUrlAudioPlayer( } #if CC_PLATFORM == CC_PLATFORM_ANDROID SLuint32 locatorType = info.assetFd->getFd() > 0 ? SL_DATALOCATOR_ANDROIDFD : SL_DATALOCATOR_URI; - auto *urlPlayer = new (std::nothrow) UrlAudioPlayer(_engineItf, _outputMixObject, _callerThreadUtils); - bool ret = urlPlayer->prepare(info.url, locatorType, info.assetFd, info.start, info.length); + auto *urlPlayer = new (std::nothrow) UrlAudioPlayer(_engineItf, _outputMixObject, _callerThreadUtils); + bool ret = urlPlayer->prepare(info.url, locatorType, info.assetFd, info.start, info.length); if (!ret) { SL_SAFE_DELETE(urlPlayer); } #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY auto urlPlayer = new (std::nothrow) UrlAudioPlayer(_callerThreadUtils); bool ret = urlPlayer->prepare(info.url, info.assetFd, info.start, info.length); - if (!ret) - { - if (urlPlayer != nullptr) { + if (!ret) { + if (urlPlayer != nullptr) { delete urlPlayer; - urlPlayer = nullptr; + urlPlayer = nullptr; } } #endif diff --git a/native/cocos/audio/android/AudioResampler.h b/native/cocos/audio/android/AudioResampler.h index 9fdf9c2334..5b33d60557 100644 --- a/native/cocos/audio/android/AudioResampler.h +++ b/native/cocos/audio/android/AudioResampler.h @@ -18,9 +18,9 @@ #include #if CC_PLATFORM == CC_PLATFORM_ANDROID -#include -#include -#include + #include + #include + #include #endif #include "audio/android/AudioBufferProvider.h" @@ -108,21 +108,20 @@ protected: int64_t calculateOutputPTS(int outputFrameIndex); - - const int32_t mChannelCount;// NOLINT(readability-identifier-naming) - const int32_t mSampleRate;// NOLINT(readability-identifier-naming) - int32_t mInSampleRate;// NOLINT(readability-identifier-naming) - AudioBufferProvider::Buffer mBuffer;// NOLINT(readability-identifier-naming) + const int32_t mChannelCount; // NOLINT(readability-identifier-naming) + const int32_t mSampleRate; // NOLINT(readability-identifier-naming) + int32_t mInSampleRate; // NOLINT(readability-identifier-naming) + AudioBufferProvider::Buffer mBuffer; // NOLINT(readability-identifier-naming) union { - int16_t mVolume[2];// NOLINT(readability-identifier-naming) - uint32_t mVolumeRL;// NOLINT(readability-identifier-naming) + int16_t mVolume[2]; // NOLINT(readability-identifier-naming) + uint32_t mVolumeRL; // NOLINT(readability-identifier-naming) }; - int16_t mTargetVolume[2];// NOLINT(readability-identifier-naming) - size_t mInputIndex;// NOLINT(readability-identifier-naming) - int32_t mPhaseIncrement;// NOLINT(readability-identifier-naming) - uint32_t mPhaseFraction;// NOLINT(readability-identifier-naming) - uint64_t mLocalTimeFreq;// NOLINT(readability-identifier-naming) - int64_t mPTS;// NOLINT(readability-identifier-naming) + int16_t mTargetVolume[2]; // NOLINT(readability-identifier-naming) + size_t mInputIndex; // NOLINT(readability-identifier-naming) + int32_t mPhaseIncrement; // NOLINT(readability-identifier-naming) + uint32_t mPhaseFraction; // NOLINT(readability-identifier-naming) + uint64_t mLocalTimeFreq; // NOLINT(readability-identifier-naming) + int64_t mPTS; // NOLINT(readability-identifier-naming) // returns the inFrameCount required to generate outFrameCount frames. // @@ -155,7 +154,7 @@ protected: return (static_cast(outFrameCount) * mInSampleRate + (mSampleRate - 1)) / mSampleRate; } - inline float clampFloatVol(float volume) {//NOLINT(readability-identifier-naming, readability-convert-member-functions-to-static) + inline float clampFloatVol(float volume) { //NOLINT(readability-identifier-naming, readability-convert-member-functions-to-static) float ret = 0.0F; if (volume > UNITY_GAIN_FLOAT) { ret = UNITY_GAIN_FLOAT; @@ -166,7 +165,7 @@ protected: } private: - const src_quality mQuality;// NOLINT(readability-identifier-naming) + const src_quality mQuality; // NOLINT(readability-identifier-naming) // Return 'true' if the quality level is supported without explicit request static bool qualityIsSupported(src_quality quality); diff --git a/native/cocos/audio/android/AudioResamplerCubic.h b/native/cocos/audio/android/AudioResamplerCubic.h index b625064d95..3940d0b689 100644 --- a/native/cocos/audio/android/AudioResamplerCubic.h +++ b/native/cocos/audio/android/AudioResamplerCubic.h @@ -19,8 +19,8 @@ #include #include -#include "audio/android/AudioResampler.h" #include "audio/android/AudioBufferProvider.h" +#include "audio/android/AudioResampler.h" namespace cc { // ---------------------------------------------------------------------------- diff --git a/native/cocos/audio/android/OpenSLHelper.h b/native/cocos/audio/android/OpenSLHelper.h index d1621d5f3a..56d2aa026e 100644 --- a/native/cocos/audio/android/OpenSLHelper.h +++ b/native/cocos/audio/android/OpenSLHelper.h @@ -29,9 +29,9 @@ #include #if CC_PLATFORM == CC_PLATFORM_ANDROID -#include + #include #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY -#include + #include #endif #include diff --git a/native/cocos/audio/android/PcmAudioService.cpp b/native/cocos/audio/android/PcmAudioService.cpp index 4989d0a92e..eed52e1de4 100644 --- a/native/cocos/audio/android/PcmAudioService.cpp +++ b/native/cocos/audio/android/PcmAudioService.cpp @@ -25,28 +25,28 @@ #define LOG_TAG "PcmAudioService" -#include "base/Macros.h" #include "audio/android/PcmAudioService.h" #include "audio/android/AudioMixerController.h" #include "audio/android/utils/Compat.h" +#include "base/Macros.h" namespace cc { -static ccstd::vector __silenceData;//NOLINT(bugprone-reserved-identifier, readability-identifier-naming) +static ccstd::vector __silenceData; //NOLINT(bugprone-reserved-identifier, readability-identifier-naming) #define AUDIO_PLAYER_BUFFER_COUNT (2) class SLPcmAudioPlayerCallbackProxy { public: #if CC_PLATFORM == CC_PLATFORM_ANDROID - static void samplePlayerCallback(CCSLBufferQueueItf bq, void *context) { + static void samplePlayerCallback(CCSLBufferQueueItf bq, void *context){ #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY static void samplePlayerCallback(CCSLBufferQueueItf bq, void *context, SLuint32 size) { #endif auto *thiz = reinterpret_cast(context); - thiz->bqFetchBufferCallback(bq); - } -}; + thiz->bqFetchBufferCallback(bq); +} +}; // namespace cc PcmAudioService::PcmAudioService(SLEngineItf engineItf, SLObjectItf outputMixObject) : _engineItf(engineItf), _outputMixObj(outputMixObject), _playObj(nullptr), _playItf(nullptr), _volumeItf(nullptr), _bufferQueueItf(nullptr), _numChannels(-1), _sampleRate(-1), _bufferSizeInBytes(0), _controller(nullptr) { @@ -59,12 +59,12 @@ PcmAudioService::~PcmAudioService() { } bool PcmAudioService::enqueue() { - #if CC_PLATFORM == CC_PLATFORM_OPENHARMONY - // We need to call this interface in openharmony, otherwise there will be noise - SLuint8 *buffer = nullptr; - SLuint32 size = 0; - (*_bufferQueueItf)->GetBuffer(_bufferQueueItf, &buffer, &size); - #endif +#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY + // We need to call this interface in openharmony, otherwise there will be noise + SLuint8 *buffer = nullptr; + SLuint32 size = 0; + (*_bufferQueueItf)->GetBuffer(_bufferQueueItf, &buffer, &size); +#endif if (_controller->hasPlayingTacks()) { if (_controller->isPaused()) { SLresult r = (*_bufferQueueItf)->Enqueue(_bufferQueueItf, __silenceData.data(), __silenceData.size()); @@ -141,7 +141,7 @@ bool PcmAudioService::init(AudioMixerController *controller, int numChannels, in SLresult r; - r = (*_engineItf)->CreateAudioPlayer(_engineItf, &_playObj, &source, &sink, sizeof(ids) / sizeof(ids[0]), ids, req);//NOLINT(bugprone-sizeof-expression) + r = (*_engineItf)->CreateAudioPlayer(_engineItf, &_playObj, &source, &sink, sizeof(ids) / sizeof(ids[0]), ids, req); //NOLINT(bugprone-sizeof-expression) SL_RETURN_VAL_IF_FAILED(r, false, "CreateAudioPlayer failed"); r = (*_playObj)->Realize(_playObj, SL_BOOLEAN_FALSE); @@ -162,12 +162,12 @@ bool PcmAudioService::init(AudioMixerController *controller, int numChannels, in if (__silenceData.empty()) { __silenceData.resize(_numChannels * _bufferSizeInBytes, 0x00); } - #if CC_PLATFORM == CC_PLATFORM_OPENHARMONY - // We need to call this interface in openharmony, otherwise there will be noise - SLuint8 *buffer = nullptr; - SLuint32 size = 0; - (*_bufferQueueItf)->GetBuffer(_bufferQueueItf, &buffer, &size); - #endif +#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY + // We need to call this interface in openharmony, otherwise there will be noise + SLuint8 *buffer = nullptr; + SLuint32 size = 0; + (*_bufferQueueItf)->GetBuffer(_bufferQueueItf, &buffer, &size); +#endif r = (*_bufferQueueItf)->Enqueue(_bufferQueueItf, __silenceData.data(), __silenceData.size()); SL_RETURN_VAL_IF_FAILED(r, false, "_bufferQueueItf Enqueue failed"); diff --git a/native/cocos/audio/android/UrlAudioPlayer.cpp b/native/cocos/audio/android/UrlAudioPlayer.cpp index 881f49bd53..cecb372a95 100644 --- a/native/cocos/audio/android/UrlAudioPlayer.cpp +++ b/native/cocos/audio/android/UrlAudioPlayer.cpp @@ -26,17 +26,17 @@ #define LOG_TAG "UrlAudioPlayer" #include "audio/android/UrlAudioPlayer.h" -#include "audio/android/ICallerThreadUtils.h" -#include "base/std/container/vector.h" -#include "base/Macros.h" -#include #include // for std::find +#include +#include "audio/android/ICallerThreadUtils.h" +#include "base/Macros.h" +#include "base/std/container/vector.h" namespace { -std::mutex __playerContainerMutex;//NOLINT(bugprone-reserved-identifier,readability-identifier-naming) -ccstd::vector __playerContainer;//NOLINT(bugprone-reserved-identifier,readability-identifier-naming) -std::once_flag __onceFlag;//NOLINT(bugprone-reserved-identifier,readability-identifier-naming) +std::mutex __playerContainerMutex; //NOLINT(bugprone-reserved-identifier,readability-identifier-naming) +ccstd::vector __playerContainer; //NOLINT(bugprone-reserved-identifier,readability-identifier-naming) +std::once_flag __onceFlag; //NOLINT(bugprone-reserved-identifier,readability-identifier-naming) } // namespace @@ -216,7 +216,7 @@ float UrlAudioPlayer::getDuration() const { if (duration == SL_TIME_UNKNOWN) { return -1.0F; - } else {// NOLINT(readability-else-after-return) + } else { // NOLINT(readability-else-after-return) const_cast(this)->_duration = duration / 1000.0F; if (_duration <= 0) { diff --git a/native/cocos/audio/android/cutils/bitops.h b/native/cocos/audio/android/cutils/bitops.h index 215872f6ea..c11f6bdf73 100644 --- a/native/cocos/audio/android/cutils/bitops.h +++ b/native/cocos/audio/android/cutils/bitops.h @@ -22,10 +22,10 @@ #include #if CC_PLATFORM == CC_PLATFORM_ANDROID -#include + #include #endif -#ifdef __cplusplus +#ifdef __cplusplus extern "C" { #endif @@ -41,7 +41,7 @@ static inline int popcountll(unsigned long long x) { return __builtin_popcountll(x); } -#ifdef __cplusplus +#ifdef __cplusplus } #endif diff --git a/native/cocos/audio/android/cutils/log.h b/native/cocos/audio/android/cutils/log.h index fa32d12feb..e1dec8d5dd 100644 --- a/native/cocos/audio/android/cutils/log.h +++ b/native/cocos/audio/android/cutils/log.h @@ -34,10 +34,10 @@ #include #include #if CC_PLATFORM == CC_PLATFORM_ANDROID -#include + #include #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY -#include -#define LOG_VERBOSE LOG_INFO + #include + #define LOG_VERBOSE LOG_INFO #endif #ifdef __cplusplus @@ -90,11 +90,11 @@ extern "C" { * Simplified macro to send a verbose log message using the current LOG_TAG. */ #ifndef ALOGV -#if CC_PLATFORM == CC_PLATFORM_ANDROID - #define __ALOGV(...) ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) -#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY - #define __ALOGV(...) ((void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__)) -#endif + #if CC_PLATFORM == CC_PLATFORM_ANDROID + #define __ALOGV(...) ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__)) + #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY + #define __ALOGV(...) ((void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__)) + #endif #if LOG_NDEBUG #define ALOGV(...) \ do { \ @@ -413,23 +413,23 @@ extern "C" { * is -inverted- from the normal assert() semantics. */ #ifndef LOG_ALWAYS_FATAL_IF -#if CC_PLATFORM == CC_PLATFORM_ANDROID - #define LOG_ALWAYS_FATAL_IF(cond, ...) \ - ((__predict_false(cond)) \ - ? ((void)android_printAssert(#cond, LOG_TAG, ##__VA_ARGS__)) \ - : (void)0) -#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY - #define LOG_ALWAYS_FATAL_IF(cond, ...) ((void)0 ) -#endif + #if CC_PLATFORM == CC_PLATFORM_ANDROID + #define LOG_ALWAYS_FATAL_IF(cond, ...) \ + ((__predict_false(cond)) \ + ? ((void)android_printAssert(#cond, LOG_TAG, ##__VA_ARGS__)) \ + : (void)0) + #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY + #define LOG_ALWAYS_FATAL_IF(cond, ...) ((void)0) + #endif #endif #ifndef LOG_ALWAYS_FATAL -#if CC_PLATFORM == CC_PLATFORM_ANDROID - #define LOG_ALWAYS_FATAL(...) \ - (((void)android_printAssert(NULL, LOG_TAG, ##__VA_ARGS__))) -#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY - #define LOG_ALWAYS_FATAL(...) ((void) OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) -#endif + #if CC_PLATFORM == CC_PLATFORM_ANDROID + #define LOG_ALWAYS_FATAL(...) \ + (((void)android_printAssert(NULL, LOG_TAG, ##__VA_ARGS__))) + #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY + #define LOG_ALWAYS_FATAL(...) ((void)OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) + #endif #endif /* @@ -476,26 +476,25 @@ extern "C" { * The second argument may be NULL or "" to indicate the "global" tag. */ #ifndef ALOG -#if CC_PLATFORM == CC_PLATFORM_ANDROID -#define ALOG(priority, tag, ...) \ - LOG_PRI(ANDROID_##priority, tag, __VA_ARGS__) -#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY -#define ALOG(priority, tag, ...) \ - LOG_PRI(priority, tag, __VA_ARGS__) + #if CC_PLATFORM == CC_PLATFORM_ANDROID + #define ALOG(priority, tag, ...) \ + LOG_PRI(ANDROID_##priority, tag, __VA_ARGS__) + #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY + #define ALOG(priority, tag, ...) \ + LOG_PRI(priority, tag, __VA_ARGS__) + #endif #endif -#endif - /* * Log macro that allows you to specify a number for the priority. */ #ifndef LOG_PRI -#if CC_PLATFORM == CC_PLATFORM_ANDROID - #define LOG_PRI(priority, tag, ...) \ - android_printLog(priority, tag, __VA_ARGS__) -#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY - #define LOG_PRI(priority, tag, ...) ((void) OH_LOG_Print(LOG_APP, priority, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) -#endif + #if CC_PLATFORM == CC_PLATFORM_ANDROID + #define LOG_PRI(priority, tag, ...) \ + android_printLog(priority, tag, __VA_ARGS__) + #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY + #define LOG_PRI(priority, tag, ...) ((void)OH_LOG_Print(LOG_APP, priority, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) + #endif #endif /* diff --git a/native/cocos/audio/android/utils/Compat.h b/native/cocos/audio/android/utils/Compat.h index 6ccae6a834..2179a1f42f 100644 --- a/native/cocos/audio/android/utils/Compat.h +++ b/native/cocos/audio/android/utils/Compat.h @@ -17,16 +17,15 @@ #ifndef COCOS_LIB_UTILS_COMPAT_H #define COCOS_LIB_UTILS_COMPAT_H - #if CC_PLATFORM == CC_PLATFORM_ANDROID -#include -#include -#include + #include + #include + #include #elif CC_PLATFORM == CC_PLATFORM_WINDOWS #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY -#include -#include + #include + #include #endif #if defined(__APPLE__) @@ -97,11 +96,11 @@ static inline ssize_t pwrite64(int fd, const void *buf, size_t nbytes, off64_t o #if CC_PLATFORM == CC_PLATFORM_ANDROID typedef SLAndroidSimpleBufferQueueItf CCSLBufferQueueItf; -#define CC_SL_IDD_BUFFER_QUEUE SL_IID_ANDROIDSIMPLEBUFFERQUEUE + #define CC_SL_IDD_BUFFER_QUEUE SL_IID_ANDROIDSIMPLEBUFFERQUEUE #elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY typedef SLOHBufferQueueItf CCSLBufferQueueItf; -#define CC_SL_IDD_BUFFER_QUEUE SL_IID_OH_BUFFERQUEUE -#define __unused + #define CC_SL_IDD_BUFFER_QUEUE SL_IID_OH_BUFFERQUEUE + #define __unused #endif #endif /* COCOS_LIB_UTILS_COMPAT_H */ diff --git a/native/cocos/audio/android/utils/Errors.h b/native/cocos/audio/android/utils/Errors.h index 5b61b62478..ce4fa0c675 100644 --- a/native/cocos/audio/android/utils/Errors.h +++ b/native/cocos/audio/android/utils/Errors.h @@ -17,8 +17,8 @@ #ifndef COCOS_ERRORS_H #define COCOS_ERRORS_H -#include #include +#include namespace cc { diff --git a/native/cocos/audio/apple/AudioCache.h b/native/cocos/audio/apple/AudioCache.h index 16c746484d..a2d3fd9aeb 100644 --- a/native/cocos/audio/apple/AudioCache.h +++ b/native/cocos/audio/apple/AudioCache.h @@ -27,8 +27,8 @@ #import -#include #include +#include #include "base/std/container/string.h" #include "audio/apple/AudioMacros.h" diff --git a/native/cocos/audio/common/utils/include/format.h b/native/cocos/audio/common/utils/include/format.h index 854c16033e..8fad90ebe8 100644 --- a/native/cocos/audio/common/utils/include/format.h +++ b/native/cocos/audio/common/utils/include/format.h @@ -19,7 +19,7 @@ #include #if CC_PLATFORM == CC_PLATFORM_ANDROID -#include + #include #endif #include "audio/android/audio.h" diff --git a/native/cocos/audio/common/utils/include/primitives.h b/native/cocos/audio/common/utils/include/primitives.h index 0901e2043d..cc6a551435 100644 --- a/native/cocos/audio/common/utils/include/primitives.h +++ b/native/cocos/audio/common/utils/include/primitives.h @@ -25,7 +25,7 @@ #include #include #if CC_PLATFORM == CC_PLATFORM_ANDROID -#include + #include #endif /* The memcpy_* conversion routines are designed to work in-place on same dst as src diff --git a/native/cocos/audio/oalsoft/AudioEngine-soft.cpp b/native/cocos/audio/oalsoft/AudioEngine-soft.cpp index 208cc4d1fb..d1d1b9868d 100644 --- a/native/cocos/audio/oalsoft/AudioEngine-soft.cpp +++ b/native/cocos/audio/oalsoft/AudioEngine-soft.cpp @@ -178,7 +178,7 @@ bool AudioEngineImpl::init() { alcMakeContextCurrent(sALContext); - std::fill(std::begin(_alSources), std::end(_alSources), 0); + std::fill(std::begin(_alSources), std::end(_alSources), 0); alGenSources(MAX_AUDIOINSTANCES, _alSources); auto alError = alGetError(); diff --git a/native/cocos/audio/openharmony/PcmAudioService.cpp b/native/cocos/audio/openharmony/PcmAudioService.cpp index 54224c8367..92e982cef2 100644 --- a/native/cocos/audio/openharmony/PcmAudioService.cpp +++ b/native/cocos/audio/openharmony/PcmAudioService.cpp @@ -26,9 +26,9 @@ THE SOFTWARE. #define LOG_TAG "PcmAudioService" #include "audio/openharmony/PcmAudioService.h" +#include #include "audio/android/AudioMixerController.h" #include "audio/android/cutils/log.h" -#include namespace cc { @@ -106,10 +106,10 @@ bool PcmAudioService::init(AudioMixerController *controller, int numChannels, in OH_AudioRenderer_Callbacks callbacks; static int sdkApi = OH_GetSdkApiVersion(); - if(sdkApi >= 21) { + if (sdkApi >= 21) { callbacks.OH_AudioRenderer_OnWriteData = nullptr; } else { - callbacks.OH_AudioRenderer_OnWriteData = reinterpret_cast(AudioRendererOnWriteData); + callbacks.OH_AudioRenderer_OnWriteData = reinterpret_cast(AudioRendererOnWriteData); } callbacks.OH_AudioRenderer_OnInterruptEvent = AudioRendererOnInterrupt; callbacks.OH_AudioRenderer_OnError = nullptr; @@ -118,9 +118,9 @@ bool PcmAudioService::init(AudioMixerController *controller, int numChannels, in if (ret != AUDIOSTREAM_SUCCESS) { return false; } - - if(sdkApi >= 21) { - ret = OH_AudioStreamBuilder_SetRendererWriteDataCallback(_builder, AudioRendererOnWriteData, this); + + if (sdkApi >= 21) { + ret = OH_AudioStreamBuilder_SetRendererWriteDataCallback(_builder, AudioRendererOnWriteData, this); if (ret != AUDIOSTREAM_SUCCESS) { return false; } diff --git a/native/cocos/audio/openharmony/UrlAudioPlayer.cpp b/native/cocos/audio/openharmony/UrlAudioPlayer.cpp index 916b7b808d..d33d08909b 100644 --- a/native/cocos/audio/openharmony/UrlAudioPlayer.cpp +++ b/native/cocos/audio/openharmony/UrlAudioPlayer.cpp @@ -26,8 +26,8 @@ THE SOFTWARE. #define LOG_TAG "UrlAudioPlayer" #include "audio/openharmony/UrlAudioPlayer.h" -#include #include // for std::find +#include #include "audio/android/ICallerThreadUtils.h" #include "audio/android/cutils/log.h" #include "cocos/application/ApplicationManager.h" diff --git a/native/cocos/base/Log.cpp b/native/cocos/base/Log.cpp index 034b0b82fe..7b2f7d190f 100644 --- a/native/cocos/base/Log.cpp +++ b/native/cocos/base/Log.cpp @@ -209,23 +209,23 @@ void Log::logMessage(LogType type, LogLevel level, const char *formats, ...) { ::LogLevel ohosLoglevel = ::LogLevel::LOG_DEBUG; switch (level) { case LogLevel::LEVEL_DEBUG: - ohosLoglevel = ::LogLevel::LOG_DEBUG; - break; + ohosLoglevel = ::LogLevel::LOG_DEBUG; + break; case LogLevel::INFO: - ohosLoglevel = ::LogLevel::LOG_INFO; - break; + ohosLoglevel = ::LogLevel::LOG_INFO; + break; case LogLevel::WARN: - ohosLoglevel = ::LogLevel::LOG_WARN; - break; + ohosLoglevel = ::LogLevel::LOG_WARN; + break; case LogLevel::ERR: - ohosLoglevel = ::LogLevel::LOG_ERROR; - break; + ohosLoglevel = ::LogLevel::LOG_ERROR; + break; case LogLevel::FATAL: - ohosLoglevel = ::LogLevel::LOG_FATAL; - break; + ohosLoglevel = ::LogLevel::LOG_FATAL; + break; default: - ohosLoglevel = ::LogLevel::LOG_INFO; - break; + ohosLoglevel = ::LogLevel::LOG_INFO; + break; } OH_LOG_Print(LOG_APP, ohosLoglevel, LOG_DOMAIN, "HMG_LOG", "%{public}s", buff); #else diff --git a/native/cocos/base/Scheduler.cpp b/native/cocos/base/Scheduler.cpp index 3bf0370d24..71c3df3a07 100644 --- a/native/cocos/base/Scheduler.cpp +++ b/native/cocos/base/Scheduler.cpp @@ -346,7 +346,7 @@ void Scheduler::runFunctionsToBePerformedInCocosThread() { // fixed #4123: Save the callback functions, they must be invoked after '_performMutex.unlock()', otherwise if new functions are added in callback, it will cause thread deadlock. auto temp = std::move(_functionsToPerform); _performMutex.unlock(); - + auto iter = temp.begin(); for (; iter != temp.end(); ++iter) { nowTime = std::chrono::steady_clock::now(); @@ -355,10 +355,10 @@ void Scheduler::runFunctionsToBePerformedInCocosThread() { if (passedMS > 16) { break; } - + (*iter)(); } - + std::lock_guard lk(_performMutex); _functionsToPerform.insert(_functionsToPerform.begin(), std::make_move_iterator(iter), std::make_move_iterator(temp.end())); } diff --git a/native/cocos/base/Scheduler.h b/native/cocos/base/Scheduler.h index 35421ce96a..f62afd1a60 100644 --- a/native/cocos/base/Scheduler.h +++ b/native/cocos/base/Scheduler.h @@ -268,7 +268,7 @@ public: * @js NA */ void removeAllFunctionsToBePerformedInCocosThread(); - + void runFunctionsToBePerformedInCocosThread(); bool isCurrentTargetSalvaged() const { return _currentTargetSalvaged; }; diff --git a/native/cocos/base/TypeDef.h b/native/cocos/base/TypeDef.h index 7f5997649c..894456abe8 100644 --- a/native/cocos/base/TypeDef.h +++ b/native/cocos/base/TypeDef.h @@ -42,38 +42,38 @@ using index_t = int32_t; #define CC_ENUM_CONVERSION_OPERATOR(T) \ inline std::underlying_type_t toNumber(const T v) { return static_cast>(v); } -#define CC_ENUM_BITWISE_OPERATORS(T) \ - constexpr bool operator!(const T v) { return !static_cast>(v); } \ - constexpr T operator~(const T v) { return static_cast(~static_cast>(v)); } \ +#define CC_ENUM_BITWISE_OPERATORS(T) \ + constexpr bool operator!(const T v) { return !static_cast>(v); } \ + constexpr T operator~(const T v) { return static_cast(~static_cast>(v)); } \ constexpr bool operator||(const T lhs, const T rhs) { return (static_cast>(lhs) || static_cast>(rhs)); } \ constexpr bool operator&&(const T lhs, const T rhs) { return (static_cast>(lhs) && static_cast>(rhs)); } \ constexpr T operator|(const T lhs, const T rhs) { return static_cast(static_cast>(lhs) | static_cast>(rhs)); } \ constexpr T operator&(const T lhs, const T rhs) { return static_cast(static_cast>(lhs) & static_cast>(rhs)); } \ constexpr T operator^(const T lhs, const T rhs) { return static_cast(static_cast>(lhs) ^ static_cast>(rhs)); } \ constexpr T operator+(const T lhs, const T rhs) { return static_cast(static_cast>(lhs) + static_cast>(rhs)); } \ - constexpr T operator+(const T lhs, bool rhs) { return static_cast(static_cast>(lhs) + rhs); } \ + constexpr T operator+(const T lhs, bool rhs) { return static_cast(static_cast>(lhs) + rhs); } \ constexpr void operator|=(T &lhs, const T rhs) { lhs = static_cast(static_cast>(lhs) | static_cast>(rhs)); } \ constexpr void operator&=(T &lhs, const T rhs) { lhs = static_cast(static_cast>(lhs) & static_cast>(rhs)); } \ constexpr void operator^=(T &lhs, const T rhs) { lhs = static_cast(static_cast>(lhs) ^ static_cast>(rhs)); } \ - constexpr bool hasFlag(const T flags, const T flagToTest) { \ - using ValueType = std::underlying_type_t; \ - CC_ASSERT((static_cast(flagToTest) & (static_cast(flagToTest) - 1)) == 0); \ - return (static_cast(flags) & static_cast(flagToTest)) != 0; \ - } \ - constexpr bool hasAnyFlags(const T flags, const T flagsToTest) { \ - using ValueType = std::underlying_type_t; \ - return (static_cast(flags) & static_cast(flagsToTest)) != 0; \ - } \ - constexpr bool hasAllFlags(const T flags, const T flagsToTest) { \ - using ValueType = std::underlying_type_t; \ - return (static_cast(flags) & static_cast(flagsToTest)) == static_cast(flagsToTest); \ - } \ - constexpr T addFlags(T &flags, const T flagsToAdd) { \ - flags |= flagsToAdd; \ - return flags; \ - } \ - constexpr T removeFlags(T &flags, const T flagsToRemove) { \ - flags &= ~flagsToRemove; \ - return flags; \ - } \ + constexpr bool hasFlag(const T flags, const T flagToTest) { \ + using ValueType = std::underlying_type_t; \ + CC_ASSERT((static_cast(flagToTest) & (static_cast(flagToTest) - 1)) == 0); \ + return (static_cast(flags) & static_cast(flagToTest)) != 0; \ + } \ + constexpr bool hasAnyFlags(const T flags, const T flagsToTest) { \ + using ValueType = std::underlying_type_t; \ + return (static_cast(flags) & static_cast(flagsToTest)) != 0; \ + } \ + constexpr bool hasAllFlags(const T flags, const T flagsToTest) { \ + using ValueType = std::underlying_type_t; \ + return (static_cast(flags) & static_cast(flagsToTest)) == static_cast(flagsToTest); \ + } \ + constexpr T addFlags(T &flags, const T flagsToAdd) { \ + flags |= flagsToAdd; \ + return flags; \ + } \ + constexpr T removeFlags(T &flags, const T flagsToRemove) { \ + flags &= ~flagsToRemove; \ + return flags; \ + } \ CC_ENUM_CONVERSION_OPERATOR(T) diff --git a/native/cocos/base/UTF8.cpp b/native/cocos/base/UTF8.cpp index 3e1e8dde75..00cc10abc5 100644 --- a/native/cocos/base/UTF8.cpp +++ b/native/cocos/base/UTF8.cpp @@ -34,8 +34,8 @@ #include "ConvertUTF/ConvertUTF.h" #if CC_USE_SIMD_UTF -#include "simdutf/simdutf.cpp" //NOLINT -#include "simdutf/simdutf.h" + #include "simdutf/simdutf.cpp" //NOLINT + #include "simdutf/simdutf.h" #endif #include "base/Log.h" diff --git a/native/cocos/base/threading/MessageQueue.cpp b/native/cocos/base/threading/MessageQueue.cpp index 854f0ede4a..043b720e04 100644 --- a/native/cocos/base/threading/MessageQueue.cpp +++ b/native/cocos/base/threading/MessageQueue.cpp @@ -24,8 +24,8 @@ #include "MessageQueue.h" #include "AutoReleasePool.h" -#include "base/Utils.h" #include "base/Log.h" +#include "base/Utils.h" #if CC_PLATFORM == CC_PLATFORM_ANDROID #include diff --git a/native/cocos/bindings/jswrapper/HandleObject.cpp b/native/cocos/bindings/jswrapper/HandleObject.cpp index f040f99c41..1aef20644a 100644 --- a/native/cocos/bindings/jswrapper/HandleObject.cpp +++ b/native/cocos/bindings/jswrapper/HandleObject.cpp @@ -37,7 +37,7 @@ HandleObject::HandleObject(Object *obj) } } -HandleObject::HandleObject(HandleObject &&o) noexcept{ +HandleObject::HandleObject(HandleObject &&o) noexcept { _obj = o._obj; o._obj = nullptr; } @@ -49,7 +49,7 @@ HandleObject::~HandleObject() { } } -HandleObject& HandleObject::operator=(HandleObject &&o) noexcept { +HandleObject &HandleObject::operator=(HandleObject &&o) noexcept { _obj = o._obj; o._obj = nullptr; return *this; diff --git a/native/cocos/bindings/jswrapper/HandleObject.h b/native/cocos/bindings/jswrapper/HandleObject.h index c8647b3eae..9e9f134375 100644 --- a/native/cocos/bindings/jswrapper/HandleObject.h +++ b/native/cocos/bindings/jswrapper/HandleObject.h @@ -98,10 +98,10 @@ public: return (_obj == nullptr); } HandleObject(HandleObject &&) noexcept; - HandleObject& operator=(HandleObject &&) noexcept; + HandleObject &operator=(HandleObject &&) noexcept; HandleObject(const HandleObject &) = delete; - HandleObject& operator=(const HandleObject &) = delete; + HandleObject &operator=(const HandleObject &) = delete; void *operator new(size_t size) = delete; void operator delete(void *, size_t) = delete; diff --git a/native/cocos/bindings/jswrapper/MappingUtils.h b/native/cocos/bindings/jswrapper/MappingUtils.h index 7ec4085d9c..fe1ac6639b 100644 --- a/native/cocos/bindings/jswrapper/MappingUtils.h +++ b/native/cocos/bindings/jswrapper/MappingUtils.h @@ -169,12 +169,12 @@ private: if (kls != nullptr && kls != itr->second->_getClass()) { continue; } - // JS object may be null when it is obtained on zhe JSVM brach of the 5.1 ROMS - #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSVM - if(itr->second->_getJSObject() == nullptr) { - continue; - } - #endif +// JS object may be null when it is obtained on zhe JSVM brach of the 5.1 ROMS +#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSVM + if (itr->second->_getJSObject() == nullptr) { + continue; + } +#endif eleCount++; CC_ASSERT_LT(eleCount, 2); eachCallback(itr->second); diff --git a/native/cocos/bindings/jswrapper/Object.h b/native/cocos/bindings/jswrapper/Object.h index bed507f583..952a29f9ae 100644 --- a/native/cocos/bindings/jswrapper/Object.h +++ b/native/cocos/bindings/jswrapper/Object.h @@ -43,12 +43,10 @@ #include "chakracore/Object.h" #endif - #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_NAPI #include "napi/Object.h" #endif - #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSVM #include "jsvm/Object.h" #endif \ No newline at end of file diff --git a/native/cocos/bindings/jswrapper/PrivateObject.h b/native/cocos/bindings/jswrapper/PrivateObject.h index b2fc7274d4..bc2b26a245 100644 --- a/native/cocos/bindings/jswrapper/PrivateObject.h +++ b/native/cocos/bindings/jswrapper/PrivateObject.h @@ -27,10 +27,10 @@ #include #include #include +#include "base/HasMemberFunction.h" #include "base/Ptr.h" #include "base/RefCounted.h" #include "base/memory/Memory.h" -#include "base/HasMemberFunction.h" namespace se { @@ -116,7 +116,7 @@ public: explicit CCIntrusivePtrPrivateObject(const cc::IntrusivePtr &p) : _ptr(p) {} explicit CCIntrusivePtrPrivateObject(cc::IntrusivePtr &&p) : _ptr(std::move(p)) {} ~CCIntrusivePtrPrivateObject() override { - if constexpr (cc::has_setScriptObject::value) { + if constexpr (cc::has_setScriptObject::value) { _ptr->setScriptObject(nullptr); } } diff --git a/native/cocos/bindings/jswrapper/Value.cpp b/native/cocos/bindings/jswrapper/Value.cpp index 246224532e..447cb6540d 100644 --- a/native/cocos/bindings/jswrapper/Value.cpp +++ b/native/cocos/bindings/jswrapper/Value.cpp @@ -24,13 +24,13 @@ ****************************************************************************/ #include "Value.h" +#include #include #include #include #include #include #include "Object.h" -#include namespace se { diff --git a/native/cocos/bindings/jswrapper/config.h b/native/cocos/bindings/jswrapper/config.h index fb0defaf45..12c415ebdd 100644 --- a/native/cocos/bindings/jswrapper/config.h +++ b/native/cocos/bindings/jswrapper/config.h @@ -36,11 +36,11 @@ #define SCRIPT_ENGINE_JSVM 6 #ifndef SCRIPT_ENGINE_TYPE -#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY - #define SCRIPT_ENGINE_TYPE SCRIPT_ENGINE_NAPI -#else - #define SCRIPT_ENGINE_TYPE SCRIPT_ENGINE_V8 -#endif + #if CC_PLATFORM == CC_PLATFORM_OPENHARMONY + #define SCRIPT_ENGINE_TYPE SCRIPT_ENGINE_NAPI + #else + #define SCRIPT_ENGINE_TYPE SCRIPT_ENGINE_V8 + #endif #endif #define SE_LOG_TO_JS_ENV 0 // print log to JavaScript environment, for example DevTools @@ -65,9 +65,9 @@ CC_FORMAT_HINT(3, 4) void selogMessage(cc::LogLevel level, const char *tag, const char *format, ...); #if CC_DEBUG -#define SE_LOGD(...) selogMessage(cc::LogLevel::LEVEL_DEBUG, "D/", ##__VA_ARGS__) + #define SE_LOGD(...) selogMessage(cc::LogLevel::LEVEL_DEBUG, "D/", ##__VA_ARGS__) #else -#define SE_LOGD(...) + #define SE_LOGD(...) #endif #define SE_LOGE(...) selogMessage(cc::LogLevel::ERR, "E/", ##__VA_ARGS__) diff --git a/native/cocos/bindings/jswrapper/jsvm-v8-backend/callback_queue-inl.h b/native/cocos/bindings/jswrapper/jsvm-v8-backend/callback_queue-inl.h index 9e46ae4869..a2ef069079 100644 --- a/native/cocos/bindings/jswrapper/jsvm-v8-backend/callback_queue-inl.h +++ b/native/cocos/bindings/jswrapper/jsvm-v8-backend/callback_queue-inl.h @@ -3,7 +3,7 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "callback_queue.h" + #include "callback_queue.h" namespace node { @@ -11,87 +11,87 @@ template template std::unique_ptr::Callback> CallbackQueue::CreateCallback(Fn&& fn, CallbackFlags::Flags flags) { - return std::make_unique>(std::move(fn), flags); + return std::make_unique>(std::move(fn), flags); } template std::unique_ptr::Callback> CallbackQueue::Shift() { - std::unique_ptr ret = std::move(head_); - if (ret) { - head_ = ret->get_next(); - if (!head_) - tail_ = nullptr; // The queue is now empty. - size_--; - } - return ret; + std::unique_ptr ret = std::move(head_); + if (ret) { + head_ = ret->get_next(); + if (!head_) + tail_ = nullptr; // The queue is now empty. + size_--; + } + return ret; } template void CallbackQueue::Push(std::unique_ptr cb) { - Callback* prev_tail = tail_; + Callback* prev_tail = tail_; - size_++; - tail_ = cb.get(); - if (prev_tail != nullptr) - prev_tail->set_next(std::move(cb)); - else - head_ = std::move(cb); + size_++; + tail_ = cb.get(); + if (prev_tail != nullptr) + prev_tail->set_next(std::move(cb)); + else + head_ = std::move(cb); } template void CallbackQueue::ConcatMove(CallbackQueue&& other) { - size_ += other.size_; - if (tail_ != nullptr) - tail_->set_next(std::move(other.head_)); - else - head_ = std::move(other.head_); - tail_ = other.tail_; - other.tail_ = nullptr; - other.size_ = 0; + size_ += other.size_; + if (tail_ != nullptr) + tail_->set_next(std::move(other.head_)); + else + head_ = std::move(other.head_); + tail_ = other.tail_; + other.tail_ = nullptr; + other.size_ = 0; } template size_t CallbackQueue::size() const { - return size_.load(); + return size_.load(); } template CallbackQueue::Callback::Callback(CallbackFlags::Flags flags) - : flags_(flags) {} +: flags_(flags) {} template CallbackFlags::Flags CallbackQueue::Callback::flags() const { - return flags_; + return flags_; } template std::unique_ptr::Callback> CallbackQueue::Callback::get_next() { - return std::move(next_); + return std::move(next_); } template void CallbackQueue::Callback::set_next( std::unique_ptr next) { - next_ = std::move(next); + next_ = std::move(next); } template template CallbackQueue::CallbackImpl::CallbackImpl( Fn&& callback, CallbackFlags::Flags flags) - : Callback(flags), - callback_(std::move(callback)) {} +: Callback(flags), + callback_(std::move(callback)) {} template template R CallbackQueue::CallbackImpl::Call(Args... args) { - return callback_(std::forward(args)...); + return callback_(std::forward(args)...); } -} // namespace node +} // namespace node -#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS +#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#endif // SRC_CALLBACK_QUEUE_INL_H_ +#endif // SRC_CALLBACK_QUEUE_INL_H_ diff --git a/native/cocos/bindings/jswrapper/jsvm-v8-backend/callback_queue.h b/native/cocos/bindings/jswrapper/jsvm-v8-backend/callback_queue.h index e5694d5e1f..91c47846a6 100644 --- a/native/cocos/bindings/jswrapper/jsvm-v8-backend/callback_queue.h +++ b/native/cocos/bindings/jswrapper/jsvm-v8-backend/callback_queue.h @@ -3,14 +3,14 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include + #include namespace node { namespace CallbackFlags { enum Flags { - kUnrefed = 0, - kRefed = 1, + kUnrefed = 0, + kRefed = 1, }; } @@ -22,57 +22,57 @@ enum Flags { // should be run even if nothing else is keeping the event loop alive. template class CallbackQueue { - public: - class Callback { - public: - explicit inline Callback(CallbackFlags::Flags flags); +public: + class Callback { + public: + explicit inline Callback(CallbackFlags::Flags flags); - virtual ~Callback() = default; - virtual R Call(Args... args) = 0; + virtual ~Callback() = default; + virtual R Call(Args... args) = 0; - inline CallbackFlags::Flags flags() const; + inline CallbackFlags::Flags flags() const; - private: - inline std::unique_ptr get_next(); - inline void set_next(std::unique_ptr next); + private: + inline std::unique_ptr get_next(); + inline void set_next(std::unique_ptr next); - CallbackFlags::Flags flags_; - std::unique_ptr next_; + CallbackFlags::Flags flags_; + std::unique_ptr next_; - friend class CallbackQueue; - }; + friend class CallbackQueue; + }; - template - inline std::unique_ptr CreateCallback( - Fn&& fn, CallbackFlags::Flags); + template + inline std::unique_ptr CreateCallback( + Fn&& fn, CallbackFlags::Flags); - inline std::unique_ptr Shift(); - inline void Push(std::unique_ptr cb); - // ConcatMove adds elements from 'other' to the end of this list, and clears - // 'other' afterwards. - inline void ConcatMove(CallbackQueue&& other); + inline std::unique_ptr Shift(); + inline void Push(std::unique_ptr cb); + // ConcatMove adds elements from 'other' to the end of this list, and clears + // 'other' afterwards. + inline void ConcatMove(CallbackQueue&& other); - // size() is atomic and may be called from any thread. - inline size_t size() const; + // size() is atomic and may be called from any thread. + inline size_t size() const; - private: - template - class CallbackImpl final : public Callback { - public: - CallbackImpl(Fn&& callback, CallbackFlags::Flags flags); - R Call(Args... args) override; +private: + template + class CallbackImpl final : public Callback { + public: + CallbackImpl(Fn&& callback, CallbackFlags::Flags flags); + R Call(Args... args) override; - private: - Fn callback_; - }; + private: + Fn callback_; + }; - std::atomic size_ {0}; - std::unique_ptr head_; - Callback* tail_ = nullptr; + std::atomic size_{0}; + std::unique_ptr head_; + Callback* tail_ = nullptr; }; -} // namespace node +} // namespace node -#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS +#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#endif // SRC_CALLBACK_QUEUE_H_ +#endif // SRC_CALLBACK_QUEUE_H_ diff --git a/native/cocos/bindings/jswrapper/jsvm-v8-backend/js_native_api_v8.h b/native/cocos/bindings/jswrapper/jsvm-v8-backend/js_native_api_v8.h index 72911b9faf..4dd36fe797 100644 --- a/native/cocos/bindings/jswrapper/jsvm-v8-backend/js_native_api_v8.h +++ b/native/cocos/bindings/jswrapper/jsvm-v8-backend/js_native_api_v8.h @@ -1,18 +1,18 @@ #ifndef SRC_JS_NATIVE_API_V8_H_ #define SRC_JS_NATIVE_API_V8_H_ -#include -#include -#include #include -#include "jsvm_types.h" -#include "js_native_api_v8_internals.h" +#include +#include +#include #include "callback_queue.h" +#include "js_native_api_v8_internals.h" +#include "jsvm_types.h" #ifdef TARGET_OHOS -#include + #include extern "C" void ReportData(uint32_t resType, int64_t value, - const std::unordered_map& mapPayLoad); + const std::unordered_map& mapPayLoad); #endif inline JSVM_Status jsvm_clear_last_error(JSVM_Env env); @@ -20,372 +20,372 @@ inline JSVM_Status jsvm_clear_last_error(JSVM_Env env); namespace v8impl { class RefTracker { - public: - RefTracker() {} - virtual ~RefTracker() {} - virtual void Finalize() {} +public: + RefTracker() {} + virtual ~RefTracker() {} + virtual void Finalize() {} - typedef RefTracker RefList; + typedef RefTracker RefList; - inline void Link(RefList* list) { - prev_ = list; - next_ = list->next_; - if (next_ != nullptr) { - next_->prev_ = this; + inline void Link(RefList* list) { + prev_ = list; + next_ = list->next_; + if (next_ != nullptr) { + next_->prev_ = this; + } + list->next_ = this; } - list->next_ = this; - } - inline void Unlink() { - if (prev_ != nullptr) { - prev_->next_ = next_; + inline void Unlink() { + if (prev_ != nullptr) { + prev_->next_ = next_; + } + if (next_ != nullptr) { + next_->prev_ = prev_; + } + prev_ = nullptr; + next_ = nullptr; } - if (next_ != nullptr) { - next_->prev_ = prev_; - } - prev_ = nullptr; - next_ = nullptr; - } - static void FinalizeAll(RefList* list) { - while (list->next_ != nullptr) { - list->next_->Finalize(); + static void FinalizeAll(RefList* list) { + while (list->next_ != nullptr) { + list->next_->Finalize(); + } } - } - private: - RefList* next_ = nullptr; - RefList* prev_ = nullptr; +private: + RefList* next_ = nullptr; + RefList* prev_ = nullptr; }; class Finalizer; class Agent; -} // end of namespace v8impl +} // end of namespace v8impl struct JSVM_Data__ { - public: - using SourcePtr = std::variant, v8::Global>; - using DataType = enum { kJsvmScript }; +public: + using SourcePtr = std::variant, v8::Global>; + using DataType = enum { kJsvmScript }; - template - JSVM_Data__(T ptr, bool retained, DataType type = kJsvmScript) + template + JSVM_Data__(T ptr, bool retained, DataType type = kJsvmScript) : taggedPointer(ptr), isGlobal(retained), type(type) {} - template - v8::Local ToV8Local(v8::Isolate *isolate) { - if (isGlobal) { - return v8::Local::New(isolate, std::get>(taggedPointer)); - } else { - return std::get>(taggedPointer); + template + v8::Local ToV8Local(v8::Isolate* isolate) { + if (isGlobal) { + return v8::Local::New(isolate, std::get>(taggedPointer)); + } else { + return std::get>(taggedPointer); + } } - } - SourcePtr taggedPointer; - bool isGlobal = false; - DataType type; + SourcePtr taggedPointer; + bool isGlobal = false; + DataType type; }; struct JSVM_Env__ { - explicit JSVM_Env__(v8::Local context, - int32_t module_api_version) - : isolate(context->GetIsolate()), - context_persistent(isolate, context), - module_api_version(module_api_version) { - jsvm_clear_last_error(this); - } - - // Constructor for creating partial env. - explicit JSVM_Env__(v8::Isolate* isolate, int32_t module_api_version); - -//cjh template -// inline void RequestInterrupt(Fn&& cb) { -// auto callback = native_immediates_interrupts_.CreateCallback( -// std::move(cb), node::CallbackFlags::kRefed); -// { -// node::Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_); -// native_immediates_interrupts_.Push(std::move(callback)); -// } -// isolate->RequestInterrupt([](v8::Isolate* isolate, void* data) { -// static_cast(data)->RunAndClearInterrupts(); -// }, this); -// } -// -// void RunAndClearInterrupts(); -// -// v8impl::Agent* inspector_agent() { return inspector_agent_; } - - v8::Platform* platform(); - - inline v8::Local context() const { - return v8impl::PersistentToLocal::Strong(context_persistent); - } - - inline void Ref() { refs++; } - inline void Unref() { - if (--refs == 0) DeleteMe(); - } - - virtual bool can_call_into_js() const { return true; } - - static inline void HandleThrow(JSVM_Env env, v8::Local value) { - if (env->terminatedOrTerminating()) { - return; + explicit JSVM_Env__(v8::Local context, + int32_t module_api_version) + : isolate(context->GetIsolate()), + context_persistent(isolate, context), + module_api_version(module_api_version) { + jsvm_clear_last_error(this); } - env->isolate->ThrowException(value); - } - // i.e. whether v8 exited or is about to exit - inline bool terminatedOrTerminating() { - return this->isolate->IsExecutionTerminating() || !can_call_into_js(); - } + // Constructor for creating partial env. + explicit JSVM_Env__(v8::Isolate* isolate, int32_t module_api_version); - // v8 uses a special exception to indicate termination, the - // `handle_exception` callback should identify such case using - // terminatedOrTerminating() before actually handle the exception - template - inline void CallIntoModule(T&& call, U&& handle_exception = HandleThrow) { - int open_handle_scopes_before = open_handle_scopes; - int open_callback_scopes_before = open_callback_scopes; - jsvm_clear_last_error(this); - call(this); - CHECK_EQ(open_handle_scopes, open_handle_scopes_before); - CHECK_EQ(open_callback_scopes, open_callback_scopes_before); - if (!last_exception.IsEmpty()) { - handle_exception(this, last_exception.Get(this->isolate)); - last_exception.Reset(); + //cjh template + // inline void RequestInterrupt(Fn&& cb) { + // auto callback = native_immediates_interrupts_.CreateCallback( + // std::move(cb), node::CallbackFlags::kRefed); + // { + // node::Mutex::ScopedLock lock(native_immediates_threadsafe_mutex_); + // native_immediates_interrupts_.Push(std::move(callback)); + // } + // isolate->RequestInterrupt([](v8::Isolate* isolate, void* data) { + // static_cast(data)->RunAndClearInterrupts(); + // }, this); + // } + // + // void RunAndClearInterrupts(); + // + // v8impl::Agent* inspector_agent() { return inspector_agent_; } + + v8::Platform* platform(); + + inline v8::Local context() const { + return v8impl::PersistentToLocal::Strong(context_persistent); } - } - // Call finalizer immediately. - virtual void CallFinalizer(JSVM_Finalize cb, void* data, void* hint) { - v8::HandleScope handle_scope(isolate); - CallIntoModule([&](JSVM_Env env) { cb(env, data, hint); }); - } - - // Invoke finalizer from V8 garbage collector. - void InvokeFinalizerFromGC(v8impl::RefTracker* finalizer); - - // Enqueue the finalizer to the JSVM_Env's own queue of the second pass - // weak callback. - // Implementation should drain the queue at the time it is safe to call - // into JavaScript. - virtual void EnqueueFinalizer(v8impl::RefTracker* finalizer) { - pending_finalizers.emplace(finalizer); - } - - // Remove the finalizer from the scheduled second pass weak callback queue. - // The finalizer can be deleted after this call. - virtual void DequeueFinalizer(v8impl::RefTracker* finalizer) { - pending_finalizers.erase(finalizer); - } - - virtual void DeleteMe(); - - void CheckGCAccess() { - if (in_gc_finalizer) { - v8impl::OnFatalError( - nullptr, - "Finalizer is calling a function that may affect GC state.\n" - "The finalizers are run directly from GC and must not affect GC " - "state.\n" - "Use `node_api_post_finalizer` from inside of the finalizer to work " - "around this issue.\n" - "It schedules the call as a new task in the event loop."); + inline void Ref() { refs++; } + inline void Unref() { + if (--refs == 0) DeleteMe(); } - } - template - JSVM_Data__ *NewJsvmData(T srcPtr, JSVM_Data__::DataType type = JSVM_Data__::kJsvmScript) { - if (dataStack.empty() || open_handle_scopes != dataStack.top().first) { - dataStack.emplace(open_handle_scopes, std::vector()); + virtual bool can_call_into_js() const { return true; } + + static inline void HandleThrow(JSVM_Env env, v8::Local value) { + if (env->terminatedOrTerminating()) { + return; + } + env->isolate->ThrowException(value); } - auto newData = new JSVM_Data__(srcPtr, false, type); - dataStack.top().second.push_back(newData); - return newData; - } - void ReleaseJsvmData() { - if (dataStack.empty() || open_handle_scopes != dataStack.top().first) { - return; + // i.e. whether v8 exited or is about to exit + inline bool terminatedOrTerminating() { + return this->isolate->IsExecutionTerminating() || !can_call_into_js(); } - for (auto data : dataStack.top().second) { - if (!data->isGlobal) { - delete data; - } + + // v8 uses a special exception to indicate termination, the + // `handle_exception` callback should identify such case using + // terminatedOrTerminating() before actually handle the exception + template + inline void CallIntoModule(T&& call, U&& handle_exception = HandleThrow) { + int open_handle_scopes_before = open_handle_scopes; + int open_callback_scopes_before = open_callback_scopes; + jsvm_clear_last_error(this); + call(this); + CHECK_EQ(open_handle_scopes, open_handle_scopes_before); + CHECK_EQ(open_callback_scopes, open_callback_scopes_before); + if (!last_exception.IsEmpty()) { + handle_exception(this, last_exception.Get(this->isolate)); + last_exception.Reset(); + } } - dataStack.pop(); - } - v8::Isolate* const isolate; // Shortcut for context()->GetIsolate() - v8impl::Persistent context_persistent; + // Call finalizer immediately. + virtual void CallFinalizer(JSVM_Finalize cb, void* data, void* hint) { + v8::HandleScope handle_scope(isolate); + CallIntoModule([&](JSVM_Env env) { cb(env, data, hint); }); + } - v8impl::Persistent last_exception; + // Invoke finalizer from V8 garbage collector. + void InvokeFinalizerFromGC(v8impl::RefTracker* finalizer); - // We store references in two different lists, depending on whether they have - // `JSVM_Finalizer` callbacks, because we must first finalize the ones that - // have such a callback. See `~JSVM_Env__()` above for details. - v8impl::RefTracker::RefList reflist; - v8impl::RefTracker::RefList finalizing_reflist; - // The invocation order of the finalizers is not determined. - std::unordered_set pending_finalizers; - JSVM_ExtendedErrorInfo last_error; - int open_handle_scopes = 0; - int open_callback_scopes = 0; - int refs = 1; - void* instance_data = nullptr; - int32_t module_api_version = NODE_API_DEFAULT_MODULE_API_VERSION; - bool in_gc_finalizer = false; - v8::Locker* locker = nullptr; - std::stack>> dataStack; + // Enqueue the finalizer to the JSVM_Env's own queue of the second pass + // weak callback. + // Implementation should drain the queue at the time it is safe to call + // into JavaScript. + virtual void EnqueueFinalizer(v8impl::RefTracker* finalizer) { + pending_finalizers.emplace(finalizer); + } - private: - v8impl::Agent* inspector_agent_; - typedef node::CallbackQueue NativeImmediateQueue; -//cjh node::Mutex native_immediates_threadsafe_mutex_; + // Remove the finalizer from the scheduled second pass weak callback queue. + // The finalizer can be deleted after this call. + virtual void DequeueFinalizer(v8impl::RefTracker* finalizer) { + pending_finalizers.erase(finalizer); + } + + virtual void DeleteMe(); + + void CheckGCAccess() { + if (in_gc_finalizer) { + v8impl::OnFatalError( + nullptr, + "Finalizer is calling a function that may affect GC state.\n" + "The finalizers are run directly from GC and must not affect GC " + "state.\n" + "Use `node_api_post_finalizer` from inside of the finalizer to work " + "around this issue.\n" + "It schedules the call as a new task in the event loop."); + } + } + + template + JSVM_Data__* NewJsvmData(T srcPtr, JSVM_Data__::DataType type = JSVM_Data__::kJsvmScript) { + if (dataStack.empty() || open_handle_scopes != dataStack.top().first) { + dataStack.emplace(open_handle_scopes, std::vector()); + } + auto newData = new JSVM_Data__(srcPtr, false, type); + dataStack.top().second.push_back(newData); + return newData; + } + + void ReleaseJsvmData() { + if (dataStack.empty() || open_handle_scopes != dataStack.top().first) { + return; + } + for (auto data : dataStack.top().second) { + if (!data->isGlobal) { + delete data; + } + } + dataStack.pop(); + } + + v8::Isolate* const isolate; // Shortcut for context()->GetIsolate() + v8impl::Persistent context_persistent; + + v8impl::Persistent last_exception; + + // We store references in two different lists, depending on whether they have + // `JSVM_Finalizer` callbacks, because we must first finalize the ones that + // have such a callback. See `~JSVM_Env__()` above for details. + v8impl::RefTracker::RefList reflist; + v8impl::RefTracker::RefList finalizing_reflist; + // The invocation order of the finalizers is not determined. + std::unordered_set pending_finalizers; + JSVM_ExtendedErrorInfo last_error; + int open_handle_scopes = 0; + int open_callback_scopes = 0; + int refs = 1; + void* instance_data = nullptr; + int32_t module_api_version = NODE_API_DEFAULT_MODULE_API_VERSION; + bool in_gc_finalizer = false; + v8::Locker* locker = nullptr; + std::stack>> dataStack; + +private: + v8impl::Agent* inspector_agent_; + typedef node::CallbackQueue NativeImmediateQueue; + //cjh node::Mutex native_immediates_threadsafe_mutex_; std::mutex native_immediates_threadsafe_mutex_; - NativeImmediateQueue native_immediates_interrupts_; + NativeImmediateQueue native_immediates_interrupts_; - protected: - // Should not be deleted directly. Delete with `JSVM_Env__::DeleteMe()` - // instead. - virtual ~JSVM_Env__() = default; +protected: + // Should not be deleted directly. Delete with `JSVM_Env__::DeleteMe()` + // instead. + virtual ~JSVM_Env__() = default; }; inline JSVM_Status jsvm_clear_last_error(JSVM_Env env) { - env->last_error.errorCode = JSVM_OK; - env->last_error.engineErrorCode = 0; - env->last_error.engineReserved = nullptr; - env->last_error.errorMessage = nullptr; - return JSVM_OK; + env->last_error.errorCode = JSVM_OK; + env->last_error.engineErrorCode = 0; + env->last_error.engineReserved = nullptr; + env->last_error.errorMessage = nullptr; + return JSVM_OK; } inline JSVM_Status jsvm_set_last_error(JSVM_Env env, JSVM_Status errorCode, uint32_t engineErrorCode = 0, void* engineReserved = nullptr) { - env->last_error.errorCode = errorCode; - env->last_error.engineErrorCode = engineErrorCode; - env->last_error.engineReserved = engineReserved; - return errorCode; + env->last_error.errorCode = errorCode; + env->last_error.engineErrorCode = engineErrorCode; + env->last_error.engineReserved = engineReserved; + return errorCode; } -#define RETURN_STATUS_IF_FALSE(env, condition, status) \ - do { \ - if (!(condition)) { \ - return jsvm_set_last_error((env), (status)); \ - } \ - } while (0) +#define RETURN_STATUS_IF_FALSE(env, condition, status) \ + do { \ + if (!(condition)) { \ + return jsvm_set_last_error((env), (status)); \ + } \ + } while (0) -#define RETURN_STATUS_IF_FALSE_WITH_PREAMBLE(env, condition, status) \ - do { \ - if (!(condition)) { \ - return jsvm_set_last_error( \ - (env), try_catch.HasCaught() ? JSVM_PENDING_EXCEPTION : (status)); \ - } \ - } while (0) +#define RETURN_STATUS_IF_FALSE_WITH_PREAMBLE(env, condition, status) \ + do { \ + if (!(condition)) { \ + return jsvm_set_last_error( \ + (env), try_catch.HasCaught() ? JSVM_PENDING_EXCEPTION : (status)); \ + } \ + } while (0) -#define CHECK_ENV(env) \ - do { \ - if ((env) == nullptr) { \ - return JSVM_INVALID_ARG; \ - } \ - } while (0) +#define CHECK_ENV(env) \ + do { \ + if ((env) == nullptr) { \ + return JSVM_INVALID_ARG; \ + } \ + } while (0) -#define CHECK_ENV_NOT_IN_GC(env) \ - do { \ - CHECK_ENV((env)); \ - (env)->CheckGCAccess(); \ - } while (0) +#define CHECK_ENV_NOT_IN_GC(env) \ + do { \ + CHECK_ENV((env)); \ + (env)->CheckGCAccess(); \ + } while (0) -#define CHECK_ARG(env, arg) \ - RETURN_STATUS_IF_FALSE((env), ((arg) != nullptr), JSVM_INVALID_ARG) +#define CHECK_ARG(env, arg) \ + RETURN_STATUS_IF_FALSE((env), ((arg) != nullptr), JSVM_INVALID_ARG) -#define CHECK_ARG_NOT_ZERO(env, arg) \ - RETURN_STATUS_IF_FALSE((env), ((arg) != 0), JSVM_INVALID_ARG) +#define CHECK_ARG_NOT_ZERO(env, arg) \ + RETURN_STATUS_IF_FALSE((env), ((arg) != 0), JSVM_INVALID_ARG) -#define CHECK_ARG_WITH_PREAMBLE(env, arg) \ - RETURN_STATUS_IF_FALSE_WITH_PREAMBLE( \ - (env), ((arg) != nullptr), JSVM_INVALID_ARG) +#define CHECK_ARG_WITH_PREAMBLE(env, arg) \ + RETURN_STATUS_IF_FALSE_WITH_PREAMBLE( \ + (env), ((arg) != nullptr), JSVM_INVALID_ARG) -#define CHECK_MAYBE_EMPTY(env, maybe, status) \ - RETURN_STATUS_IF_FALSE((env), !((maybe).IsEmpty()), (status)) +#define CHECK_MAYBE_EMPTY(env, maybe, status) \ + RETURN_STATUS_IF_FALSE((env), !((maybe).IsEmpty()), (status)) -#define CHECK_MAYBE_EMPTY_WITH_PREAMBLE(env, maybe, status) \ - RETURN_STATUS_IF_FALSE_WITH_PREAMBLE((env), !((maybe).IsEmpty()), (status)) +#define CHECK_MAYBE_EMPTY_WITH_PREAMBLE(env, maybe, status) \ + RETURN_STATUS_IF_FALSE_WITH_PREAMBLE((env), !((maybe).IsEmpty()), (status)) // JSVM_PREAMBLE is not wrapped in do..while: try_catch must have function scope -#define JSVM_PREAMBLE(env) \ - CHECK_ENV((env)); \ - RETURN_STATUS_IF_FALSE( \ - (env), (env)->last_exception.IsEmpty(), JSVM_PENDING_EXCEPTION); \ - RETURN_STATUS_IF_FALSE((env), \ - (env)->can_call_into_js(), \ - (env->module_api_version == JSVM_VERSION_EXPERIMENTAL \ - ? JSVM_CANNOT_RUN_JS \ - : JSVM_PENDING_EXCEPTION)); \ - jsvm_clear_last_error((env)); \ - v8impl::TryCatch try_catch((env)) +#define JSVM_PREAMBLE(env) \ + CHECK_ENV((env)); \ + RETURN_STATUS_IF_FALSE( \ + (env), (env)->last_exception.IsEmpty(), JSVM_PENDING_EXCEPTION); \ + RETURN_STATUS_IF_FALSE((env), \ + (env)->can_call_into_js(), \ + (env->module_api_version == JSVM_VERSION_EXPERIMENTAL \ + ? JSVM_CANNOT_RUN_JS \ + : JSVM_PENDING_EXCEPTION)); \ + jsvm_clear_last_error((env)); \ + v8impl::TryCatch try_catch((env)) -#define CHECK_TO_TYPE(env, type, context, result, src, status) \ - do { \ - CHECK_ARG((env), (src)); \ - auto maybe = v8impl::V8LocalValueFromJsValue((src))->To##type((context)); \ - CHECK_MAYBE_EMPTY((env), maybe, (status)); \ - (result) = maybe.ToLocalChecked(); \ - } while (0) +#define CHECK_TO_TYPE(env, type, context, result, src, status) \ + do { \ + CHECK_ARG((env), (src)); \ + auto maybe = v8impl::V8LocalValueFromJsValue((src))->To##type((context)); \ + CHECK_MAYBE_EMPTY((env), maybe, (status)); \ + (result) = maybe.ToLocalChecked(); \ + } while (0) -#define CHECK_TO_TYPE_WITH_PREAMBLE(env, type, context, result, src, status) \ - do { \ - CHECK_ARG_WITH_PREAMBLE((env), (src)); \ - auto maybe = v8impl::V8LocalValueFromJsValue((src))->To##type((context)); \ - CHECK_MAYBE_EMPTY_WITH_PREAMBLE((env), maybe, (status)); \ - (result) = maybe.ToLocalChecked(); \ - } while (0) +#define CHECK_TO_TYPE_WITH_PREAMBLE(env, type, context, result, src, status) \ + do { \ + CHECK_ARG_WITH_PREAMBLE((env), (src)); \ + auto maybe = v8impl::V8LocalValueFromJsValue((src))->To##type((context)); \ + CHECK_MAYBE_EMPTY_WITH_PREAMBLE((env), maybe, (status)); \ + (result) = maybe.ToLocalChecked(); \ + } while (0) -#define CHECK_TO_FUNCTION(env, result, src) \ - do { \ - CHECK_ARG((env), (src)); \ - v8::Local v8value = v8impl::V8LocalValueFromJsValue((src)); \ - RETURN_STATUS_IF_FALSE((env), v8value->IsFunction(), JSVM_INVALID_ARG); \ - (result) = v8value.As(); \ - } while (0) +#define CHECK_TO_FUNCTION(env, result, src) \ + do { \ + CHECK_ARG((env), (src)); \ + v8::Local v8value = v8impl::V8LocalValueFromJsValue((src)); \ + RETURN_STATUS_IF_FALSE((env), v8value->IsFunction(), JSVM_INVALID_ARG); \ + (result) = v8value.As(); \ + } while (0) -#define CHECK_TO_OBJECT(env, context, result, src) \ - CHECK_TO_TYPE((env), Object, (context), (result), (src), JSVM_OBJECT_EXPECTED) +#define CHECK_TO_OBJECT(env, context, result, src) \ + CHECK_TO_TYPE((env), Object, (context), (result), (src), JSVM_OBJECT_EXPECTED) -#define CHECK_TO_BIGINT(env, context, result, src) \ - CHECK_TO_TYPE((env), BigInt, (context), (result), (src), JSVM_BIGINT_EXPECTED) +#define CHECK_TO_BIGINT(env, context, result, src) \ + CHECK_TO_TYPE((env), BigInt, (context), (result), (src), JSVM_BIGINT_EXPECTED) -#define CHECK_TO_OBJECT_WITH_PREAMBLE(env, context, result, src) \ - CHECK_TO_TYPE_WITH_PREAMBLE( \ - (env), Object, (context), (result), (src), JSVM_OBJECT_EXPECTED) +#define CHECK_TO_OBJECT_WITH_PREAMBLE(env, context, result, src) \ + CHECK_TO_TYPE_WITH_PREAMBLE( \ + (env), Object, (context), (result), (src), JSVM_OBJECT_EXPECTED) -#define CHECK_TO_STRING(env, context, result, src) \ - CHECK_TO_TYPE((env), String, (context), (result), (src), JSVM_STRING_EXPECTED) +#define CHECK_TO_STRING(env, context, result, src) \ + CHECK_TO_TYPE((env), String, (context), (result), (src), JSVM_STRING_EXPECTED) -#define GET_RETURN_STATUS(env) \ - (!try_catch.HasCaught() \ - ? JSVM_OK \ - : jsvm_set_last_error((env), JSVM_PENDING_EXCEPTION)) +#define GET_RETURN_STATUS(env) \ + (!try_catch.HasCaught() \ + ? JSVM_OK \ + : jsvm_set_last_error((env), JSVM_PENDING_EXCEPTION)) -#define THROW_RANGE_ERROR_IF_FALSE(env, condition, error, message) \ - do { \ - if (!(condition)) { \ - OH_JSVM_ThrowRangeError((env), (error), (message)); \ - return jsvm_set_last_error((env), JSVM_GENERIC_FAILURE); \ - } \ - } while (0) +#define THROW_RANGE_ERROR_IF_FALSE(env, condition, error, message) \ + do { \ + if (!(condition)) { \ + OH_JSVM_ThrowRangeError((env), (error), (message)); \ + return jsvm_set_last_error((env), JSVM_GENERIC_FAILURE); \ + } \ + } while (0) -#define CHECK_MAYBE_EMPTY_WITH_PREAMBLE(env, maybe, status) \ - RETURN_STATUS_IF_FALSE_WITH_PREAMBLE((env), !((maybe).IsEmpty()), (status)) +#define CHECK_MAYBE_EMPTY_WITH_PREAMBLE(env, maybe, status) \ + RETURN_STATUS_IF_FALSE_WITH_PREAMBLE((env), !((maybe).IsEmpty()), (status)) -#define STATUS_CALL(call) \ - do { \ - JSVM_Status status = (call); \ - if (status != JSVM_OK) return status; \ - } while (0) +#define STATUS_CALL(call) \ + do { \ + JSVM_Status status = (call); \ + if (status != JSVM_OK) return status; \ + } while (0) namespace v8impl { @@ -397,259 +397,256 @@ static_assert(sizeof(v8::Local) == sizeof(JSVM_Value), "Cannot convert between v8::Local and JSVM_Value"); inline JSVM_Value JsValueFromV8LocalValue(v8::Local local) { - return reinterpret_cast(*local); + return reinterpret_cast(*local); } inline v8::Local V8LocalValueFromJsValue(JSVM_Value v) { - v8::Local local; - memcpy(static_cast(&local), &v, sizeof(v)); - return local; + v8::Local local; + memcpy(static_cast(&local), &v, sizeof(v)); + return local; } // Adapter for JSVM_Finalize callbacks. class Finalizer { - protected: - Finalizer(JSVM_Env env, - JSVM_Finalize finalize_callback, - void* finalize_data, - void* finalize_hint) - : env_(env), - finalize_callback_(finalize_callback), - finalize_data_(finalize_data), - finalize_hint_(finalize_hint) {} +protected: + Finalizer(JSVM_Env env, + JSVM_Finalize finalize_callback, + void* finalize_data, + void* finalize_hint) + : env_(env), + finalize_callback_(finalize_callback), + finalize_data_(finalize_data), + finalize_hint_(finalize_hint) {} - virtual ~Finalizer() = default; + virtual ~Finalizer() = default; - public: - static Finalizer* New(JSVM_Env env, - JSVM_Finalize finalize_callback = nullptr, - void* finalize_data = nullptr, - void* finalize_hint = nullptr) { - return new Finalizer(env, finalize_callback, finalize_data, finalize_hint); - } +public: + static Finalizer* New(JSVM_Env env, + JSVM_Finalize finalize_callback = nullptr, + void* finalize_data = nullptr, + void* finalize_hint = nullptr) { + return new Finalizer(env, finalize_callback, finalize_data, finalize_hint); + } - JSVM_Finalize callback() { return finalize_callback_; } - void* data() { return finalize_data_; } - void* hint() { return finalize_hint_; } + JSVM_Finalize callback() { return finalize_callback_; } + void* data() { return finalize_data_; } + void* hint() { return finalize_hint_; } - void ResetFinalizer(); + void ResetFinalizer(); - protected: - JSVM_Env env_; - JSVM_Finalize finalize_callback_; - void* finalize_data_; - void* finalize_hint_; +protected: + JSVM_Env env_; + JSVM_Finalize finalize_callback_; + void* finalize_data_; + void* finalize_hint_; }; class TryCatch : public v8::TryCatch { - public: - explicit TryCatch(JSVM_Env env) : v8::TryCatch(env->isolate), _env(env) {} +public: + explicit TryCatch(JSVM_Env env) : v8::TryCatch(env->isolate), _env(env) {} - ~TryCatch() { - if (HasCaught()) { - _env->last_exception.Reset(_env->isolate, Exception()); + ~TryCatch() { + if (HasCaught()) { + _env->last_exception.Reset(_env->isolate, Exception()); + } } - } - private: - JSVM_Env _env; +private: + JSVM_Env _env; }; // Ownership of a reference. enum class Ownership { - // The reference is owned by the runtime. No userland call is needed to - // destruct the reference. - kRuntime, - // The reference is owned by the userland. User code is responsible to delete - // the reference with appropriate node-api calls. - kUserland, + // The reference is owned by the runtime. No userland call is needed to + // destruct the reference. + kRuntime, + // The reference is owned by the userland. User code is responsible to delete + // the reference with appropriate node-api calls. + kUserland, }; // Wrapper around Finalizer that can be tracked. class TrackedFinalizer : public Finalizer, public RefTracker { - protected: - TrackedFinalizer(JSVM_Env env, - JSVM_Finalize finalizeCallback, - void* finalizeData, - void* finalizeHint); +protected: + TrackedFinalizer(JSVM_Env env, + JSVM_Finalize finalizeCallback, + void* finalizeData, + void* finalizeHint); - public: - static TrackedFinalizer* New(JSVM_Env env, - JSVM_Finalize finalizeCallback, - void* finalizeData, - void* finalizeHint); - ~TrackedFinalizer() override; +public: + static TrackedFinalizer* New(JSVM_Env env, + JSVM_Finalize finalizeCallback, + void* finalizeData, + void* finalizeHint); + ~TrackedFinalizer() override; - protected: - void Finalize() override; - void FinalizeCore(bool deleteMe); +protected: + void Finalize() override; + void FinalizeCore(bool deleteMe); }; // Wrapper around Finalizer that implements reference counting. class RefBase : public TrackedFinalizer { - protected: - RefBase(JSVM_Env env, - uint32_t initialRefcount, - Ownership ownership, - JSVM_Finalize finalizeCallback, - void* finalizeData, - void* finalizeHint); +protected: + RefBase(JSVM_Env env, + uint32_t initialRefcount, + Ownership ownership, + JSVM_Finalize finalizeCallback, + void* finalizeData, + void* finalizeHint); - public: - static RefBase* New(JSVM_Env env, - uint32_t initialRefcount, - Ownership ownership, - JSVM_Finalize finalizeCallback, - void* finalizeData, - void* finalizeHint); +public: + static RefBase* New(JSVM_Env env, + uint32_t initialRefcount, + Ownership ownership, + JSVM_Finalize finalizeCallback, + void* finalizeData, + void* finalizeHint); - void* Data(); - uint32_t Ref(); - uint32_t Unref(); - uint32_t RefCount(); + void* Data(); + uint32_t Ref(); + uint32_t Unref(); + uint32_t RefCount(); - Ownership ownership() { return ownership_; } + Ownership ownership() { return ownership_; } - protected: - void Finalize() override; +protected: + void Finalize() override; - private: - uint32_t refcount_; - Ownership ownership_; +private: + uint32_t refcount_; + Ownership ownership_; }; // Wrapper around v8impl::Persistent. class Reference : public RefBase { - protected: - template - Reference(JSVM_Env env, v8::Local value, Args&&... args); +protected: + template + Reference(JSVM_Env env, v8::Local value, Args&&... args); - public: - static Reference* New(JSVM_Env env, - v8::Local value, - uint32_t initialRefcount, - Ownership ownership, - JSVM_Finalize finalizeCallback = nullptr, - void* finalizeData = nullptr, - void* finalizeHint = nullptr); +public: + static Reference* New(JSVM_Env env, + v8::Local value, + uint32_t initialRefcount, + Ownership ownership, + JSVM_Finalize finalizeCallback = nullptr, + void* finalizeData = nullptr, + void* finalizeHint = nullptr); - virtual ~Reference(); - bool HasDeletedByUser() { - return deleted_by_user; - } - uint32_t Ref(); - uint32_t Unref(); - v8::Local Get(); - void Delete(); - - protected: - void Finalize() override; + virtual ~Reference(); + bool HasDeletedByUser() { + return deleted_by_user; + } + uint32_t Ref(); + uint32_t Unref(); + v8::Local Get(); + void Delete(); - private: - static void WeakCallback(const v8::WeakCallbackInfo& data); +protected: + void Finalize() override; - void SetWeak(); +private: + static void WeakCallback(const v8::WeakCallbackInfo& data); - v8impl::Persistent persistent_; - bool can_be_weak_; - bool deleted_by_user; - bool wait_callback; + void SetWeak(); + + v8impl::Persistent persistent_; + bool can_be_weak_; + bool deleted_by_user; + bool wait_callback; }; -typedef JSVM_Value (* GetterCallback)(JSVM_Env, JSVM_Value, JSVM_Value, JSVM_Value); -typedef JSVM_Value (* SetterCallback)(JSVM_Env, JSVM_Value, JSVM_Value, JSVM_Value, JSVM_Value); -typedef JSVM_Value (* DeleterCallback)(JSVM_Env, JSVM_Value, JSVM_Value, JSVM_Value); -typedef JSVM_Value (* EnumeratorCallback)(JSVM_Env, JSVM_Value, JSVM_Value); +typedef JSVM_Value (*GetterCallback)(JSVM_Env, JSVM_Value, JSVM_Value, JSVM_Value); +typedef JSVM_Value (*SetterCallback)(JSVM_Env, JSVM_Value, JSVM_Value, JSVM_Value, JSVM_Value); +typedef JSVM_Value (*DeleterCallback)(JSVM_Env, JSVM_Value, JSVM_Value, JSVM_Value); +typedef JSVM_Value (*EnumeratorCallback)(JSVM_Env, JSVM_Value, JSVM_Value); struct JSVM_PropertyHandlerCfgStruct { - GetterCallback namedGetterCallback_; - SetterCallback namedSetterCallback_; - DeleterCallback nameDeleterCallback_; - EnumeratorCallback namedEnumeratorCallback_; - GetterCallback indexedGetterCallback_; - SetterCallback indexedSetterCallback_; - DeleterCallback indexedDeleterCallback_; - EnumeratorCallback indexedEnumeratorCallback_; - JSVM_Ref namedPropertyData_; - JSVM_Ref indexedPropertyData_; + GetterCallback namedGetterCallback_; + SetterCallback namedSetterCallback_; + DeleterCallback nameDeleterCallback_; + EnumeratorCallback namedEnumeratorCallback_; + GetterCallback indexedGetterCallback_; + SetterCallback indexedSetterCallback_; + DeleterCallback indexedDeleterCallback_; + EnumeratorCallback indexedEnumeratorCallback_; + JSVM_Ref namedPropertyData_; + JSVM_Ref indexedPropertyData_; }; -inline JSVM_PropertyHandlerCfgStruct* CreatePropertyCfg(JSVM_Env env, JSVM_PropertyHandlerCfg propertyCfg) -{ - JSVM_PropertyHandlerCfgStruct* newPropertyCfg = new JSVM_PropertyHandlerCfgStruct; - if (newPropertyCfg != nullptr && propertyCfg != nullptr) { - newPropertyCfg->namedGetterCallback_ = propertyCfg->genericNamedPropertyGetterCallback; - newPropertyCfg->namedSetterCallback_ = propertyCfg->genericNamedPropertySetterCallback; - newPropertyCfg->nameDeleterCallback_ = propertyCfg->genericNamedPropertyDeleterCallback; - newPropertyCfg->namedEnumeratorCallback_ = propertyCfg->genericNamedPropertyEnumeratorCallback; - newPropertyCfg->indexedGetterCallback_ = propertyCfg->genericIndexedPropertyGetterCallback; - newPropertyCfg->indexedSetterCallback_ = propertyCfg->genericIndexedPropertySetterCallback; - newPropertyCfg->indexedDeleterCallback_ = propertyCfg->genericIndexedPropertyDeleterCallback; - newPropertyCfg->indexedEnumeratorCallback_ = propertyCfg->genericIndexedPropertyEnumeratorCallback; - newPropertyCfg->namedPropertyData_ = nullptr; - newPropertyCfg->indexedPropertyData_ = nullptr; - if (propertyCfg->namedPropertyData != nullptr) { - v8::Local v8_value = v8impl::V8LocalValueFromJsValue(propertyCfg->namedPropertyData); - v8impl::Reference* reference = v8impl::Reference::New(env, v8_value, 1, v8impl::Ownership::kUserland); - newPropertyCfg->namedPropertyData_ = reinterpret_cast(reference); +inline JSVM_PropertyHandlerCfgStruct* CreatePropertyCfg(JSVM_Env env, JSVM_PropertyHandlerCfg propertyCfg) { + JSVM_PropertyHandlerCfgStruct* newPropertyCfg = new JSVM_PropertyHandlerCfgStruct; + if (newPropertyCfg != nullptr && propertyCfg != nullptr) { + newPropertyCfg->namedGetterCallback_ = propertyCfg->genericNamedPropertyGetterCallback; + newPropertyCfg->namedSetterCallback_ = propertyCfg->genericNamedPropertySetterCallback; + newPropertyCfg->nameDeleterCallback_ = propertyCfg->genericNamedPropertyDeleterCallback; + newPropertyCfg->namedEnumeratorCallback_ = propertyCfg->genericNamedPropertyEnumeratorCallback; + newPropertyCfg->indexedGetterCallback_ = propertyCfg->genericIndexedPropertyGetterCallback; + newPropertyCfg->indexedSetterCallback_ = propertyCfg->genericIndexedPropertySetterCallback; + newPropertyCfg->indexedDeleterCallback_ = propertyCfg->genericIndexedPropertyDeleterCallback; + newPropertyCfg->indexedEnumeratorCallback_ = propertyCfg->genericIndexedPropertyEnumeratorCallback; + newPropertyCfg->namedPropertyData_ = nullptr; + newPropertyCfg->indexedPropertyData_ = nullptr; + if (propertyCfg->namedPropertyData != nullptr) { + v8::Local v8_value = v8impl::V8LocalValueFromJsValue(propertyCfg->namedPropertyData); + v8impl::Reference* reference = v8impl::Reference::New(env, v8_value, 1, v8impl::Ownership::kUserland); + newPropertyCfg->namedPropertyData_ = reinterpret_cast(reference); + } + + if (propertyCfg->indexedPropertyData != nullptr) { + v8::Local v8_value = v8impl::V8LocalValueFromJsValue(propertyCfg->indexedPropertyData); + v8impl::Reference* reference = v8impl::Reference::New(env, v8_value, 1, v8impl::Ownership::kUserland); + newPropertyCfg->indexedPropertyData_ = reinterpret_cast(reference); + } } - if (propertyCfg->indexedPropertyData != nullptr) { - v8::Local v8_value = v8impl::V8LocalValueFromJsValue(propertyCfg->indexedPropertyData); - v8impl::Reference* reference = v8impl::Reference::New(env, v8_value, 1, v8impl::Ownership::kUserland); - newPropertyCfg->indexedPropertyData_ = reinterpret_cast(reference); - } - } - - return newPropertyCfg; + return newPropertyCfg; } -inline void CfgFinalizedCallback(JSVM_Env env, void* finalizeData, void* finalizeHint) -{ - auto cfg = reinterpret_cast(finalizeData); - if (cfg->namedPropertyData_ != nullptr) { - delete reinterpret_cast(cfg->namedPropertyData_); - } - if (cfg->indexedPropertyData_ != nullptr) { - delete reinterpret_cast(cfg->indexedPropertyData_); - } - delete cfg; +inline void CfgFinalizedCallback(JSVM_Env env, void* finalizeData, void* finalizeHint) { + auto cfg = reinterpret_cast(finalizeData); + if (cfg->namedPropertyData_ != nullptr) { + delete reinterpret_cast(cfg->namedPropertyData_); + } + if (cfg->indexedPropertyData_ != nullptr) { + delete reinterpret_cast(cfg->indexedPropertyData_); + } + delete cfg; } #ifdef TARGET_OHOS namespace ResourceSchedule { namespace ResType { enum : uint32_t { - RES_TYPE_REPORT_KEY_THREAD = 39 + RES_TYPE_REPORT_KEY_THREAD = 39 }; enum ReportChangeStatus : int64_t { - CREATE = 0, - REMOVE = 1 + CREATE = 0, + REMOVE = 1 }; enum ThreadRole : int64_t { - USER_INTERACT = 0, - NORMAL_DISPLAY = 1, - IMPORTANT_DISPLAY = 2, - NORMAL_AUDIO = 3, - IMPORTANT_AUDIO = 4, - IMAGE_DECODE = 5 + USER_INTERACT = 0, + NORMAL_DISPLAY = 1, + IMPORTANT_DISPLAY = 2, + NORMAL_AUDIO = 3, + IMPORTANT_AUDIO = 4, + IMAGE_DECODE = 5 }; -} +} // namespace ResType -static inline void ReportKeyThread(uid_t uid, pid_t pid, pid_t tid, ResType::ThreadRole role) -{ - std::unordered_map payLoad = { - {"uid", std::to_string(uid)}, - {"pid", std::to_string(pid)}, - {"tid", std::to_string(tid)}, - {"role", std::to_string(role)}}; - ReportData(v8impl::ResourceSchedule::ResType::RES_TYPE_REPORT_KEY_THREAD, - v8impl::ResourceSchedule::ResType::ReportChangeStatus::CREATE, payLoad); -} +static inline void ReportKeyThread(uid_t uid, pid_t pid, pid_t tid, ResType::ThreadRole role) { + std::unordered_map payLoad = { + {"uid", std::to_string(uid)}, + {"pid", std::to_string(pid)}, + {"tid", std::to_string(tid)}, + {"role", std::to_string(role)}}; + ReportData(v8impl::ResourceSchedule::ResType::RES_TYPE_REPORT_KEY_THREAD, + v8impl::ResourceSchedule::ResType::ReportChangeStatus::CREATE, payLoad); } +} // namespace ResourceSchedule #endif -} // end of namespace v8impl +} // end of namespace v8impl -#endif // SRC_JS_NATIVE_API_V8_H_ +#endif // SRC_JS_NATIVE_API_V8_H_ diff --git a/native/cocos/bindings/jswrapper/jsvm-v8-backend/js_native_api_v8_internals.h b/native/cocos/bindings/jswrapper/jsvm-v8-backend/js_native_api_v8_internals.h index 9347b4bc37..87cfdbfbba 100644 --- a/native/cocos/bindings/jswrapper/jsvm-v8-backend/js_native_api_v8_internals.h +++ b/native/cocos/bindings/jswrapper/jsvm-v8-backend/js_native_api_v8_internals.h @@ -24,10 +24,10 @@ #define JSVM_ARRAYSIZE(array) node::arraysize((array)) -#define JSVM_FIXED_ONE_BYTE_STRING(isolate, string) \ - node::FIXED_ONE_BYTE_STRING((isolate), (string)) +#define JSVM_FIXED_ONE_BYTE_STRING(isolate, string) \ + node::FIXED_ONE_BYTE_STRING((isolate), (string)) -#define JSVM_PRIVATE_KEY(isolate, suffix) \ +#define JSVM_PRIVATE_KEY(isolate, suffix) \ (v8impl::GetIsolateData(isolate)->jsvm_##suffix##_key.Get(isolate)) namespace v8impl { @@ -38,10 +38,10 @@ using Persistent = v8::Global; using PersistentToLocal = node::PersistentToLocal; inline void OnFatalError(const char* location, - const char* message) { -//cjh node::OnFatalError(location, message); + const char* message) { + //cjh node::OnFatalError(location, message); } -} // end of namespace v8impl +} // end of namespace v8impl -#endif // SRC_JS_NATIVE_API_V8_INTERNALS_H_ +#endif // SRC_JS_NATIVE_API_V8_INTERNALS_H_ diff --git a/native/cocos/bindings/jswrapper/jsvm-v8-backend/jsvm.h b/native/cocos/bindings/jswrapper/jsvm-v8-backend/jsvm.h index 7c8728af60..f866a7067c 100644 --- a/native/cocos/bindings/jswrapper/jsvm-v8-backend/jsvm.h +++ b/native/cocos/bindings/jswrapper/jsvm-v8-backend/jsvm.h @@ -43,42 +43,42 @@ */ // This file needs to be compatible with C compilers. -#include // NOLINT(modernize-deprecated-headers) -#include // NOLINT(modernize-deprecated-headers) +#include // NOLINT(modernize-deprecated-headers) +#include // NOLINT(modernize-deprecated-headers) // Use INT_MAX, this should only be consumed by the pre-processor anyway. #define JSVM_VERSION_EXPERIMENTAL 2147483647 #ifndef JSVM_VERSION -#ifdef JSVM_EXPERIMENTAL -#define JSVM_VERSION JSVM_VERSION_EXPERIMENTAL -#else -// The baseline version for JSVM-API. -// The JSVM_VERSION controls which version will be used by default when -// compilling a native addon. If the addon developer specifically wants to use -// functions available in a new version of JSVM-API that is not yet ported in all -// LTS versions, they can set JSVM_VERSION knowing that they have specifically -// depended on that version. -#define JSVM_VERSION 8 -#endif + #ifdef JSVM_EXPERIMENTAL + #define JSVM_VERSION JSVM_VERSION_EXPERIMENTAL + #else + // The baseline version for JSVM-API. + // The JSVM_VERSION controls which version will be used by default when + // compilling a native addon. If the addon developer specifically wants to use + // functions available in a new version of JSVM-API that is not yet ported in all + // LTS versions, they can set JSVM_VERSION knowing that they have specifically + // depended on that version. + #define JSVM_VERSION 8 + #endif #endif #include "jsvm_types.h" #ifndef JSVM_EXTERN -#ifdef _WIN32 -/** + #ifdef _WIN32 + /** * @brief externally visible. * * @since 11 */ -#define JSVM_EXTERN __declspec(dllexport) -#elif defined(__wasm__) -#define JSVM_EXTERN \ - __attribute__((visibility("default"))) \ - __attribute__((__import_module__("jsvm"))) -#else -#define JSVM_EXTERN __attribute__((visibility("default"))) -#endif + #define JSVM_EXTERN __declspec(dllexport) + #elif defined(__wasm__) + #define JSVM_EXTERN \ + __attribute__((visibility("default"))) \ + __attribute__((__import_module__("jsvm"))) + #else + #define JSVM_EXTERN __attribute__((visibility("default"))) + #endif #endif /** @@ -89,11 +89,11 @@ #define JSVM_AUTO_LENGTH SIZE_MAX #ifdef __cplusplus -#define EXTERN_C_START extern "C" { -#define EXTERN_C_END } + #define EXTERN_C_START extern "C" { + #define EXTERN_C_END } #else -#define EXTERN_C_START -#define EXTERN_C_END + #define EXTERN_C_START + #define EXTERN_C_END #endif EXTERN_C_START @@ -657,7 +657,6 @@ JSVM_EXTERN JSVM_Status OH_JSVM_GetReferenceValue(JSVM_Env env, JSVM_EXTERN JSVM_Status OH_JSVM_CreateArray(JSVM_Env env, JSVM_Value* result); - /** * @brief This API returns a JSVM-API value corresponding to a JavaScript Array type. The Array's length property * is set to the passed-in length parameter. However, the underlying buffer is not guaranteed to be pre-allocated @@ -707,7 +706,7 @@ JSVM_EXTERN JSVM_Status OH_JSVM_CreateArraybuffer(JSVM_Env env, */ JSVM_Status JSVM_CDECL OH_JSVM_AllocateArrayBufferBackingStoreData(size_t byteLength, JSVM_InitializedFlag initialized, - void **data); + void** data); /** * @brief This API release the memory of an array buffer backing store. @@ -718,7 +717,7 @@ JSVM_Status JSVM_CDECL OH_JSVM_AllocateArrayBufferBackingStoreData(size_t byteLe * Returns {@link JSVM_INVALID_ARG } if data is null pointer.\n * @since 12 */ -JSVM_Status JSVM_CDECL OH_JSVM_FreeArrayBufferBackingStoreData(void *data); +JSVM_Status JSVM_CDECL OH_JSVM_FreeArrayBufferBackingStoreData(void* data); /** * @brief This API create an array buffer using the backing store data. @@ -738,11 +737,11 @@ JSVM_Status JSVM_CDECL OH_JSVM_FreeArrayBufferBackingStoreData(void *data); * @since 12 */ JSVM_Status JSVM_CDECL OH_JSVM_CreateArrayBufferFromBackingStoreData(JSVM_Env env, - void *data, + void* data, size_t backingStoreSize, size_t offset, size_t arrayBufferSize, - JSVM_Value *result); + JSVM_Value* result); /** * @brief This API does not observe leap seconds; they are ignored, as ECMAScript aligns with POSIX time specification. @@ -1850,7 +1849,7 @@ JSVM_EXTERN JSVM_Status OH_JSVM_CallFunction(JSVM_Env env, const JSVM_Value* argv, JSVM_Value* result); - /** +/** * @brief This API allows an add-on author to create a function object in native * code. This is the primary mechanism to allow calling into the add-on's native * code from JavaScript.The newly created function is not automatically visible @@ -1876,7 +1875,7 @@ JSVM_EXTERN JSVM_Status OH_JSVM_CreateFunction(JSVM_Env env, JSVM_Callback cb, JSVM_Value* result); - /** +/** * @brief This method is used within a callback function to retrieve details about * the call like the arguments and the this pointer from a given callback info. * @@ -2770,12 +2769,12 @@ JSVM_EXTERN JSVM_Status OH_JSVM_OpenInspectorWithName(JSVM_Env env, * @since 12 */ JSVM_EXTERN JSVM_Status OH_JSVM_CompileWasmModule(JSVM_Env env, - const uint8_t *wasmBytecode, + const uint8_t* wasmBytecode, size_t wasmBytecodeLength, - const uint8_t *cacheData, + const uint8_t* cacheData, size_t cacheDataLength, - bool *cacheRejected, - JSVM_Value *wasmModule); + bool* cacheRejected, + JSVM_Value* wasmModule); /** * @brief Compile the function with the specified index in the WebAssembly module @@ -2853,4 +2852,3 @@ EXTERN_C_END /** @} */ #endif /* ARK_RUNTIME_JSVM_JSVM_H */ - diff --git a/native/cocos/bindings/jswrapper/jsvm-v8-backend/jsvm_types.h b/native/cocos/bindings/jswrapper/jsvm-v8-backend/jsvm_types.h index 7abb16a3f1..ea6eae5e2f 100644 --- a/native/cocos/bindings/jswrapper/jsvm-v8-backend/jsvm_types.h +++ b/native/cocos/bindings/jswrapper/jsvm-v8-backend/jsvm_types.h @@ -42,20 +42,20 @@ * @since 11 */ +#include // NOLINT(modernize-deprecated-headers) #include // NOLINT(modernize-deprecated-headers) #include // NOLINT(modernize-deprecated-headers) -#include // NOLINT(modernize-deprecated-headers) #if !defined __cplusplus || (defined(_MSC_VER) && _MSC_VER < 1900) typedef uint16_t char16_t; #endif #ifndef JSVM_CDECL -#ifdef _WIN32 -#define JSVM_CDECL __cdecl -#else -#define JSVM_CDECL -#endif + #ifdef _WIN32 + #define JSVM_CDECL __cdecl + #else + #define JSVM_CDECL + #endif #endif /** @@ -142,7 +142,6 @@ typedef struct JSVM_CallbackInfo__* JSVM_CallbackInfo; */ typedef struct JSVM_Deferred__* JSVM_Deferred; - /** * @brief Callback function pointer and data for user-provided native function which are to exposed to js via JSVM-API. * @@ -150,7 +149,7 @@ typedef struct JSVM_Deferred__* JSVM_Deferred; */ typedef struct { JSVM_Value(JSVM_CDECL* callback)(JSVM_Env env, - JSVM_CallbackInfo info); + JSVM_CallbackInfo info); void* data; } JSVM_CallbackStruct; @@ -699,12 +698,12 @@ typedef struct { JSVM_CompileOptionId id; /** option content. */ union { - /** ptr type. */ - void *ptr; - /** int type. */ - int num; - /** bool type. */ - bool boolean; + /** ptr type. */ + void* ptr; + /** int type. */ + int num; + /** bool type. */ + bool boolean; } content; } JSVM_CompileOptions; @@ -715,7 +714,7 @@ typedef struct { */ typedef struct { /** cache pointer. */ - uint8_t *cache; + uint8_t* cache; /** length. */ size_t length; } JSVM_CodeCache; @@ -751,7 +750,7 @@ typedef enum { */ typedef const struct { /** profile pointer. */ - int *profile; + int* profile; /** length. */ size_t length; } JSVM_CompileProfile; diff --git a/native/cocos/bindings/jswrapper/jsvm-v8-backend/node_version.h b/native/cocos/bindings/jswrapper/jsvm-v8-backend/node_version.h index 6973a3d0fd..1ba1a608da 100644 --- a/native/cocos/bindings/jswrapper/jsvm-v8-backend/node_version.h +++ b/native/cocos/bindings/jswrapper/jsvm-v8-backend/node_version.h @@ -26,50 +26,44 @@ #define NODE_MINOR_VERSION 20 #define NODE_PATCH_VERSION 1 -#define NODE_VERSION_IS_LTS 1 +#define NODE_VERSION_IS_LTS 1 #define NODE_VERSION_LTS_CODENAME "Hydrogen" #define NODE_VERSION_IS_RELEASE 1 #ifndef NODE_STRINGIFY -#define NODE_STRINGIFY(n) NODE_STRINGIFY_HELPER(n) -#define NODE_STRINGIFY_HELPER(n) #n + #define NODE_STRINGIFY(n) NODE_STRINGIFY_HELPER(n) + #define NODE_STRINGIFY_HELPER(n) #n #endif #ifndef NODE_RELEASE -#define NODE_RELEASE "node" + #define NODE_RELEASE "node" #endif #ifndef NODE_TAG -# if NODE_VERSION_IS_RELEASE -# define NODE_TAG "" -# else -# define NODE_TAG "-pre" -# endif + #if NODE_VERSION_IS_RELEASE + #define NODE_TAG "" + #else + #define NODE_TAG "-pre" + #endif #else -// NODE_TAG is passed without quotes when rc.exe is run from msbuild -# define NODE_EXE_VERSION NODE_STRINGIFY(NODE_MAJOR_VERSION) "." \ - NODE_STRINGIFY(NODE_MINOR_VERSION) "." \ - NODE_STRINGIFY(NODE_PATCH_VERSION) \ - NODE_STRINGIFY(NODE_TAG) + // NODE_TAG is passed without quotes when rc.exe is run from msbuild + #define NODE_EXE_VERSION NODE_STRINGIFY(NODE_MAJOR_VERSION) \ + "." NODE_STRINGIFY(NODE_MINOR_VERSION) "." NODE_STRINGIFY(NODE_PATCH_VERSION) \ + NODE_STRINGIFY(NODE_TAG) #endif -# define NODE_VERSION_STRING NODE_STRINGIFY(NODE_MAJOR_VERSION) "." \ - NODE_STRINGIFY(NODE_MINOR_VERSION) "." \ - NODE_STRINGIFY(NODE_PATCH_VERSION) \ - NODE_TAG +#define NODE_VERSION_STRING NODE_STRINGIFY(NODE_MAJOR_VERSION) \ +"." NODE_STRINGIFY(NODE_MINOR_VERSION) "." NODE_STRINGIFY(NODE_PATCH_VERSION) \ + NODE_TAG #ifndef NODE_EXE_VERSION -# define NODE_EXE_VERSION NODE_VERSION_STRING + #define NODE_EXE_VERSION NODE_VERSION_STRING #endif #define NODE_VERSION "v" NODE_VERSION_STRING - #define NODE_VERSION_AT_LEAST(major, minor, patch) \ - (( (major) < NODE_MAJOR_VERSION) \ - || ((major) == NODE_MAJOR_VERSION && (minor) < NODE_MINOR_VERSION) \ - || ((major) == NODE_MAJOR_VERSION && \ - (minor) == NODE_MINOR_VERSION && (patch) <= NODE_PATCH_VERSION)) + (((major) < NODE_MAJOR_VERSION) || ((major) == NODE_MAJOR_VERSION && (minor) < NODE_MINOR_VERSION) || ((major) == NODE_MAJOR_VERSION && (minor) == NODE_MINOR_VERSION && (patch) <= NODE_PATCH_VERSION)) /** * Node.js will refuse to load modules that weren't compiled against its own @@ -99,4 +93,4 @@ // specified. It must be always 8. #define NODE_API_DEFAULT_MODULE_API_VERSION 8 -#endif // SRC_NODE_VERSION_H_ +#endif // SRC_NODE_VERSION_H_ diff --git a/native/cocos/bindings/jswrapper/jsvm-v8-backend/util.h b/native/cocos/bindings/jswrapper/jsvm-v8-backend/util.h index edf2c7b36d..6d45a53036 100644 --- a/native/cocos/bindings/jswrapper/jsvm-v8-backend/util.h +++ b/native/cocos/bindings/jswrapper/jsvm-v8-backend/util.h @@ -23,55 +23,55 @@ #define SRC_UTIL_H_ #ifndef NODE_WANT_INTERNALS -#define NODE_WANT_INTERNALS 1 + #define NODE_WANT_INTERNALS 1 #endif #ifndef NODE_EXTERN_PRIVATE -#define NODE_EXTERN_PRIVATE + #define NODE_EXTERN_PRIVATE #endif #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "v8.h" + #include "v8.h" -//#include "node.h" + //#include "node.h" -#include -#include -#include -#include -#include + #include + #include + #include + #include + #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include -#ifdef __GNUC__ -#define MUST_USE_RESULT __attribute__((warn_unused_result)) -#else -#define MUST_USE_RESULT -#endif + #ifdef __GNUC__ + #define MUST_USE_RESULT __attribute__((warn_unused_result)) + #else + #define MUST_USE_RESULT + #endif namespace node { bool ReadSystemXpmState(); -// Maybe remove kPathSeparator when cpp17 is ready -#ifdef _WIN32 - constexpr char kPathSeparator = '\\'; -/* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */ -#define PATH_MAX_BYTES (MAX_PATH * 4) -#else - constexpr char kPathSeparator = '/'; -#define PATH_MAX_BYTES (PATH_MAX) -#endif + // Maybe remove kPathSeparator when cpp17 is ready + #ifdef _WIN32 +constexpr char kPathSeparator = '\\'; + /* MAX_PATH is in characters, not bytes. Make sure we have enough headroom. */ + #define PATH_MAX_BYTES (MAX_PATH * 4) + #else +constexpr char kPathSeparator = '/'; + #define PATH_MAX_BYTES (PATH_MAX) + #endif // These should be used in our code as opposed to the native // versions as they abstract out some platform and or @@ -108,7 +108,7 @@ namespace per_process { // Tells whether the per-process V8::Initialize() is called and // if it is safe to call v8::Isolate::TryGetCurrent(). extern bool v8_initialized; -} // namespace per_process +} // namespace per_process // Used by the allocation functions when allocation fails. // Thin wrapper around v8::Isolate::LowMemoryNotification() that checks @@ -118,93 +118,91 @@ void LowMemoryNotification(); // The reason that Assert() takes a struct argument instead of individual // const char*s is to ease instruction cache pressure in calls from CHECK. struct AssertionInfo { - const char* file_line; // filename:line - const char* message; - const char* function; + const char* file_line; // filename:line + const char* message; + const char* function; }; void NODE_EXTERN_PRIVATE Assert(const AssertionInfo& info); void NODE_EXTERN_PRIVATE Abort(); void DumpBacktrace(FILE* fp); -// Windows 8+ does not like abort() in Release mode -#ifdef _WIN32 -#define ABORT_NO_BACKTRACE() _exit(134) -#else -#define ABORT_NO_BACKTRACE() abort() -#endif + // Windows 8+ does not like abort() in Release mode + #ifdef _WIN32 + #define ABORT_NO_BACKTRACE() _exit(134) + #else + #define ABORT_NO_BACKTRACE() abort() + #endif -#define ABORT() node::Abort() + #define ABORT() node::Abort() -#define ERROR_AND_ABORT(expr) \ - do { \ - /* Make sure that this struct does not end up in inline code, but */ \ - /* rather in a read-only data section when modifying this code. */ \ - static const node::AssertionInfo args = { \ - __FILE__ ":" STRINGIFY(__LINE__), #expr, PRETTY_FUNCTION_NAME \ - }; \ - printf("[FATAL] file_line:%s, message:%s, function:%s\n", args.file_line, args.message, args.function); \ - assert(false); \ - } while (0) + #define ERROR_AND_ABORT(expr) \ + do { \ + /* Make sure that this struct does not end up in inline code, but */ \ + /* rather in a read-only data section when modifying this code. */ \ + static const node::AssertionInfo args = { \ + __FILE__ ":" STRINGIFY(__LINE__), #expr, PRETTY_FUNCTION_NAME}; \ + printf("[FATAL] file_line:%s, message:%s, function:%s\n", args.file_line, args.message, args.function); \ + assert(false); \ + } while (0) -// node::Assert(args); \ + // node::Assert(args); \ -#ifdef __GNUC__ -#define LIKELY(expr) __builtin_expect(!!(expr), 1) -#define UNLIKELY(expr) __builtin_expect(!!(expr), 0) -#define PRETTY_FUNCTION_NAME __PRETTY_FUNCTION__ -#else -#define LIKELY(expr) expr -#define UNLIKELY(expr) expr -#define PRETTY_FUNCTION_NAME "" -#endif + #ifdef __GNUC__ + #define LIKELY(expr) __builtin_expect(!!(expr), 1) + #define UNLIKELY(expr) __builtin_expect(!!(expr), 0) + #define PRETTY_FUNCTION_NAME __PRETTY_FUNCTION__ + #else + #define LIKELY(expr) expr + #define UNLIKELY(expr) expr + #define PRETTY_FUNCTION_NAME "" + #endif -#define STRINGIFY_(x) #x -#define STRINGIFY(x) STRINGIFY_(x) + #define STRINGIFY_(x) #x + #define STRINGIFY(x) STRINGIFY_(x) -#define CHECK(expr) \ - do { \ - if (UNLIKELY(!(expr))) { \ - ERROR_AND_ABORT(expr); \ - } \ - } while (0) + #define CHECK(expr) \ + do { \ + if (UNLIKELY(!(expr))) { \ + ERROR_AND_ABORT(expr); \ + } \ + } while (0) -#define CHECK_EQ(a, b) CHECK((a) == (b)) -#define CHECK_GE(a, b) CHECK((a) >= (b)) -#define CHECK_GT(a, b) CHECK((a) > (b)) -#define CHECK_LE(a, b) CHECK((a) <= (b)) -#define CHECK_LT(a, b) CHECK((a) < (b)) -#define CHECK_NE(a, b) CHECK((a) != (b)) -#define CHECK_NULL(val) CHECK((val) == nullptr) -#define CHECK_NOT_NULL(val) CHECK((val) != nullptr) -#define CHECK_IMPLIES(a, b) CHECK(!(a) || (b)) + #define CHECK_EQ(a, b) CHECK((a) == (b)) + #define CHECK_GE(a, b) CHECK((a) >= (b)) + #define CHECK_GT(a, b) CHECK((a) > (b)) + #define CHECK_LE(a, b) CHECK((a) <= (b)) + #define CHECK_LT(a, b) CHECK((a) < (b)) + #define CHECK_NE(a, b) CHECK((a) != (b)) + #define CHECK_NULL(val) CHECK((val) == nullptr) + #define CHECK_NOT_NULL(val) CHECK((val) != nullptr) + #define CHECK_IMPLIES(a, b) CHECK(!(a) || (b)) -#ifdef DEBUG - #define DCHECK(expr) CHECK(expr) - #define DCHECK_EQ(a, b) CHECK((a) == (b)) - #define DCHECK_GE(a, b) CHECK((a) >= (b)) - #define DCHECK_GT(a, b) CHECK((a) > (b)) - #define DCHECK_LE(a, b) CHECK((a) <= (b)) - #define DCHECK_LT(a, b) CHECK((a) < (b)) - #define DCHECK_NE(a, b) CHECK((a) != (b)) - #define DCHECK_NULL(val) CHECK((val) == nullptr) - #define DCHECK_NOT_NULL(val) CHECK((val) != nullptr) - #define DCHECK_IMPLIES(a, b) CHECK(!(a) || (b)) -#else - #define DCHECK(expr) - #define DCHECK_EQ(a, b) - #define DCHECK_GE(a, b) - #define DCHECK_GT(a, b) - #define DCHECK_LE(a, b) - #define DCHECK_LT(a, b) - #define DCHECK_NE(a, b) - #define DCHECK_NULL(val) - #define DCHECK_NOT_NULL(val) - #define DCHECK_IMPLIES(a, b) -#endif + #ifdef DEBUG + #define DCHECK(expr) CHECK(expr) + #define DCHECK_EQ(a, b) CHECK((a) == (b)) + #define DCHECK_GE(a, b) CHECK((a) >= (b)) + #define DCHECK_GT(a, b) CHECK((a) > (b)) + #define DCHECK_LE(a, b) CHECK((a) <= (b)) + #define DCHECK_LT(a, b) CHECK((a) < (b)) + #define DCHECK_NE(a, b) CHECK((a) != (b)) + #define DCHECK_NULL(val) CHECK((val) == nullptr) + #define DCHECK_NOT_NULL(val) CHECK((val) != nullptr) + #define DCHECK_IMPLIES(a, b) CHECK(!(a) || (b)) + #else + #define DCHECK(expr) + #define DCHECK_EQ(a, b) + #define DCHECK_GE(a, b) + #define DCHECK_GT(a, b) + #define DCHECK_LE(a, b) + #define DCHECK_LT(a, b) + #define DCHECK_NE(a, b) + #define DCHECK_NULL(val) + #define DCHECK_NOT_NULL(val) + #define DCHECK_IMPLIES(a, b) + #endif - -#define UNREACHABLE(...) \ - ERROR_AND_ABORT("Unreachable code reached" __VA_OPT__(": ") __VA_ARGS__) + #define UNREACHABLE(...) \ + ERROR_AND_ABORT("Unreachable code reached" __VA_OPT__(": ") __VA_ARGS__) // ECMA262 20.1.2.6 Number.MAX_SAFE_INTEGER (2^53-1) constexpr int64_t kMaxSafeJsInteger = 9007199254740991; @@ -216,68 +214,70 @@ template class ListNode; // TAILQ-style intrusive list head. -template (T::*M)> +template (T::*M)> class ListHead; template class ListNode { - public: - inline ListNode(); - inline ~ListNode(); - inline void Remove(); - inline bool IsEmpty() const; +public: + inline ListNode(); + inline ~ListNode(); + inline void Remove(); + inline bool IsEmpty() const; - ListNode(const ListNode&) = delete; - ListNode& operator=(const ListNode&) = delete; + ListNode(const ListNode&) = delete; + ListNode& operator=(const ListNode&) = delete; - private: - template (U::*M)> friend class ListHead; - friend int GenDebugSymbols(); - ListNode* prev_; - ListNode* next_; +private: + template (U::*M)> + friend class ListHead; + friend int GenDebugSymbols(); + ListNode* prev_; + ListNode* next_; }; -template (T::*M)> +template (T::*M)> class ListHead { - public: - class Iterator { - public: - inline T* operator*() const; - inline const Iterator& operator++(); - inline bool operator!=(const Iterator& that) const; +public: + class Iterator { + public: + inline T* operator*() const; + inline const Iterator& operator++(); + inline bool operator!=(const Iterator& that) const; - private: - friend class ListHead; - inline explicit Iterator(ListNode* node); - ListNode* node_; - }; + private: + friend class ListHead; + inline explicit Iterator(ListNode* node); + ListNode* node_; + }; - inline ListHead() = default; - inline ~ListHead(); - inline void PushBack(T* element); - inline void PushFront(T* element); - inline bool IsEmpty() const; - inline T* PopFront(); - inline Iterator begin() const; - inline Iterator end() const; + inline ListHead() = default; + inline ~ListHead(); + inline void PushBack(T* element); + inline void PushFront(T* element); + inline bool IsEmpty() const; + inline T* PopFront(); + inline Iterator begin() const; + inline Iterator end() const; - ListHead(const ListHead&) = delete; - ListHead& operator=(const ListHead&) = delete; + ListHead(const ListHead&) = delete; + ListHead& operator=(const ListHead&) = delete; - private: - friend int GenDebugSymbols(); - ListNode head_; +private: + friend int GenDebugSymbols(); + ListNode head_; }; // The helper is for doing safe downcasts from base types to derived types. template class ContainerOfHelper { - public: - inline ContainerOfHelper(Inner Outer::*field, Inner* pointer); - template - inline operator TypeName*() const; - private: - Outer* const pointer_; +public: + inline ContainerOfHelper(Inner Outer::*field, Inner* pointer); + template + inline operator TypeName*() const; + +private: + Outer* const pointer_; }; // Calculate the address of the outer (i.e. embedding) struct from @@ -287,34 +287,34 @@ constexpr ContainerOfHelper ContainerOf(Inner Outer::*field, Inner* pointer); class KVStore { - public: - KVStore() = default; - virtual ~KVStore() = default; - KVStore(const KVStore&) = delete; - KVStore& operator=(const KVStore&) = delete; - KVStore(KVStore&&) = delete; - KVStore& operator=(KVStore&&) = delete; +public: + KVStore() = default; + virtual ~KVStore() = default; + KVStore(const KVStore&) = delete; + KVStore& operator=(const KVStore&) = delete; + KVStore(KVStore&&) = delete; + KVStore& operator=(KVStore&&) = delete; - virtual v8::MaybeLocal Get(v8::Isolate* isolate, - v8::Local key) const = 0; - virtual v8::Maybe Get(const char* key) const = 0; - virtual void Set(v8::Isolate* isolate, - v8::Local key, - v8::Local value) = 0; - virtual int32_t Query(v8::Isolate* isolate, - v8::Local key) const = 0; - virtual int32_t Query(const char* key) const = 0; - virtual void Delete(v8::Isolate* isolate, v8::Local key) = 0; - virtual v8::Local Enumerate(v8::Isolate* isolate) const = 0; + virtual v8::MaybeLocal Get(v8::Isolate* isolate, + v8::Local key) const = 0; + virtual v8::Maybe Get(const char* key) const = 0; + virtual void Set(v8::Isolate* isolate, + v8::Local key, + v8::Local value) = 0; + virtual int32_t Query(v8::Isolate* isolate, + v8::Local key) const = 0; + virtual int32_t Query(const char* key) const = 0; + virtual void Delete(v8::Isolate* isolate, v8::Local key) = 0; + virtual v8::Local Enumerate(v8::Isolate* isolate) const = 0; - virtual std::shared_ptr Clone(v8::Isolate* isolate) const; - virtual v8::Maybe AssignFromObject(v8::Local context, - v8::Local entries); - v8::Maybe AssignToObject(v8::Isolate* isolate, - v8::Local context, - v8::Local object); + virtual std::shared_ptr Clone(v8::Isolate* isolate) const; + virtual v8::Maybe AssignFromObject(v8::Local context, + v8::Local entries); + v8::Maybe AssignToObject(v8::Isolate* isolate, + v8::Local context, + v8::Local object); - static std::shared_ptr CreateMapKVStore(); + static std::shared_ptr CreateMapKVStore(); }; // Convenience wrapper around v8::String::NewFromOneByte(). @@ -335,19 +335,17 @@ inline v8::Local OneByteString(v8::Isolate* isolate, template inline v8::Local FIXED_ONE_BYTE_STRING( v8::Isolate* isolate, - const char(&data)[N]) { - return OneByteString(isolate, data, N - 1); + const char (&data)[N]) { + return OneByteString(isolate, data, N - 1); } template inline v8::Local FIXED_ONE_BYTE_STRING( v8::Isolate* isolate, const std::array& arr) { - return OneByteString(isolate, arr.data(), N - 1); + return OneByteString(isolate, arr.data(), N - 1); } - - // Swaps bytes in place. nbytes is the number of bytes to swap and must be a // multiple of the word size (checked by function). inline void SwapBytes16(char* data, size_t nbytes); @@ -370,133 +368,133 @@ inline bool StringEqualNoCaseN(const char* a, const char* b, size_t length); template constexpr size_t arraysize(const T (&)[N]) { - return N; + return N; } template constexpr size_t strsize(const T (&)[N]) { - return N - 1; + return N - 1; } // Allocates an array of member type T. For up to kStackStorageSize items, // the stack is used, otherwise malloc(). template class MaybeStackBuffer { - public: - const T* out() const { - return buf_; - } +public: + const T* out() const { + return buf_; + } - T* out() { - return buf_; - } + T* out() { + return buf_; + } - // operator* for compatibility with `v8::String::(Utf8)Value` - T* operator*() { - return buf_; - } + // operator* for compatibility with `v8::String::(Utf8)Value` + T* operator*() { + return buf_; + } - const T* operator*() const { - return buf_; - } + const T* operator*() const { + return buf_; + } - T& operator[](size_t index) { - CHECK_LT(index, length()); - return buf_[index]; - } + T& operator[](size_t index) { + CHECK_LT(index, length()); + return buf_[index]; + } - const T& operator[](size_t index) const { - CHECK_LT(index, length()); - return buf_[index]; - } + const T& operator[](size_t index) const { + CHECK_LT(index, length()); + return buf_[index]; + } - size_t length() const { - return length_; - } + size_t length() const { + return length_; + } - // Current maximum capacity of the buffer with which SetLength() can be used - // without first calling AllocateSufficientStorage(). - size_t capacity() const { - return capacity_; - } + // Current maximum capacity of the buffer with which SetLength() can be used + // without first calling AllocateSufficientStorage(). + size_t capacity() const { + return capacity_; + } - // Make sure enough space for `storage` entries is available. - // This method can be called multiple times throughout the lifetime of the - // buffer, but once this has been called Invalidate() cannot be used. - // Content of the buffer in the range [0, length()) is preserved. - void AllocateSufficientStorage(size_t storage); + // Make sure enough space for `storage` entries is available. + // This method can be called multiple times throughout the lifetime of the + // buffer, but once this has been called Invalidate() cannot be used. + // Content of the buffer in the range [0, length()) is preserved. + void AllocateSufficientStorage(size_t storage); - void SetLength(size_t length) { - // capacity() returns how much memory is actually available. - CHECK_LE(length, capacity()); - length_ = length; - } + void SetLength(size_t length) { + // capacity() returns how much memory is actually available. + CHECK_LE(length, capacity()); + length_ = length; + } - void SetLengthAndZeroTerminate(size_t length) { - // capacity() returns how much memory is actually available. - CHECK_LE(length + 1, capacity()); - SetLength(length); + void SetLengthAndZeroTerminate(size_t length) { + // capacity() returns how much memory is actually available. + CHECK_LE(length + 1, capacity()); + SetLength(length); - // T() is 0 for integer types, nullptr for pointers, etc. - buf_[length] = T(); - } + // T() is 0 for integer types, nullptr for pointers, etc. + buf_[length] = T(); + } - // Make dereferencing this object return nullptr. - // This method can be called multiple times throughout the lifetime of the - // buffer, but once this has been called AllocateSufficientStorage() cannot - // be used. - void Invalidate() { - CHECK(!IsAllocated()); - capacity_ = 0; - length_ = 0; - buf_ = nullptr; - } + // Make dereferencing this object return nullptr. + // This method can be called multiple times throughout the lifetime of the + // buffer, but once this has been called AllocateSufficientStorage() cannot + // be used. + void Invalidate() { + CHECK(!IsAllocated()); + capacity_ = 0; + length_ = 0; + buf_ = nullptr; + } - // If the buffer is stored in the heap rather than on the stack. - bool IsAllocated() const { - return !IsInvalidated() && buf_ != buf_st_; - } + // If the buffer is stored in the heap rather than on the stack. + bool IsAllocated() const { + return !IsInvalidated() && buf_ != buf_st_; + } - // If Invalidate() has been called. - bool IsInvalidated() const { - return buf_ == nullptr; - } + // If Invalidate() has been called. + bool IsInvalidated() const { + return buf_ == nullptr; + } - // Release ownership of the malloc'd buffer. - // Note: This does not free the buffer. - void Release() { - CHECK(IsAllocated()); - buf_ = buf_st_; - length_ = 0; - capacity_ = arraysize(buf_st_); - } + // Release ownership of the malloc'd buffer. + // Note: This does not free the buffer. + void Release() { + CHECK(IsAllocated()); + buf_ = buf_st_; + length_ = 0; + capacity_ = arraysize(buf_st_); + } - MaybeStackBuffer() - : length_(0), capacity_(arraysize(buf_st_)), buf_(buf_st_) { - // Default to a zero-length, null-terminated buffer. - buf_[0] = T(); - } + MaybeStackBuffer() + : length_(0), capacity_(arraysize(buf_st_)), buf_(buf_st_) { + // Default to a zero-length, null-terminated buffer. + buf_[0] = T(); + } - explicit MaybeStackBuffer(size_t storage) : MaybeStackBuffer() { - AllocateSufficientStorage(storage); - } + explicit MaybeStackBuffer(size_t storage) : MaybeStackBuffer() { + AllocateSufficientStorage(storage); + } - ~MaybeStackBuffer() { - if (IsAllocated()) - free(buf_); - } + ~MaybeStackBuffer() { + if (IsAllocated()) + free(buf_); + } - inline std::basic_string ToString() const { return {out(), length()}; } - inline std::basic_string_view ToStringView() const { - return {out(), length()}; - } + inline std::basic_string ToString() const { return {out(), length()}; } + inline std::basic_string_view ToStringView() const { + return {out(), length()}; + } - private: - size_t length_; - // capacity of the malloc'ed buf_ - size_t capacity_; - T* buf_; - T buf_st_[kStackStorageSize]; +private: + size_t length_; + // capacity of the malloc'ed buf_ + size_t capacity_; + T* buf_; + T buf_st_[kStackStorageSize]; }; // Provides access to an ArrayBufferView's storage, either the original, @@ -504,83 +502,86 @@ class MaybeStackBuffer { // original ArrayBufferView's lifetime. template class ArrayBufferViewContents { - public: - ArrayBufferViewContents() = default; +public: + ArrayBufferViewContents() = default; - ArrayBufferViewContents(const ArrayBufferViewContents&) = delete; - void operator=(const ArrayBufferViewContents&) = delete; + ArrayBufferViewContents(const ArrayBufferViewContents&) = delete; + void operator=(const ArrayBufferViewContents&) = delete; - explicit inline ArrayBufferViewContents(v8::Local value); - explicit inline ArrayBufferViewContents(v8::Local value); - explicit inline ArrayBufferViewContents(v8::Local abv); - inline void Read(v8::Local abv); - inline void ReadValue(v8::Local buf); + explicit inline ArrayBufferViewContents(v8::Local value); + explicit inline ArrayBufferViewContents(v8::Local value); + explicit inline ArrayBufferViewContents(v8::Local abv); + inline void Read(v8::Local abv); + inline void ReadValue(v8::Local buf); - inline bool WasDetached() const { return was_detached_; } - inline const T* data() const { return data_; } - inline size_t length() const { return length_; } + inline bool WasDetached() const { return was_detached_; } + inline const T* data() const { return data_; } + inline size_t length() const { return length_; } - private: - // Declaring operator new and delete as deleted is not spec compliant. - // Therefore, declare them private instead to disable dynamic alloc. - void* operator new(size_t size); - void* operator new[](size_t size); - void operator delete(void*, size_t); - void operator delete[](void*, size_t); +private: + // Declaring operator new and delete as deleted is not spec compliant. + // Therefore, declare them private instead to disable dynamic alloc. + void* operator new(size_t size); + void* operator new[](size_t size); + void operator delete(void*, size_t); + void operator delete[](void*, size_t); - T stack_storage_[kStackStorageSize]; - T* data_ = nullptr; - size_t length_ = 0; - bool was_detached_ = false; + T stack_storage_[kStackStorageSize]; + T* data_ = nullptr; + size_t length_ = 0; + bool was_detached_ = false; }; class Utf8Value : public MaybeStackBuffer { - public: - explicit Utf8Value(v8::Isolate* isolate, v8::Local value); +public: + explicit Utf8Value(v8::Isolate* isolate, v8::Local value); - inline bool operator==(const char* a) const { return strcmp(out(), a) == 0; } - inline bool operator!=(const char* a) const { return !(*this == a); } + inline bool operator==(const char* a) const { return strcmp(out(), a) == 0; } + inline bool operator!=(const char* a) const { return !(*this == a); } }; class TwoByteValue : public MaybeStackBuffer { - public: - explicit TwoByteValue(v8::Isolate* isolate, v8::Local value); +public: + explicit TwoByteValue(v8::Isolate* isolate, v8::Local value); }; class BufferValue : public MaybeStackBuffer { - public: - explicit BufferValue(v8::Isolate* isolate, v8::Local value); +public: + explicit BufferValue(v8::Isolate* isolate, v8::Local value); - inline std::string ToString() const { return std::string(out(), length()); } + inline std::string ToString() const { return std::string(out(), length()); } }; -#define SPREAD_BUFFER_ARG(val, name) \ - CHECK((val)->IsArrayBufferView()); \ - v8::Local name = (val).As(); \ - const size_t name##_offset = name->ByteOffset(); \ - const size_t name##_length = name->ByteLength(); \ - char* const name##_data = \ - static_cast(name->Buffer()->Data()) + name##_offset; \ - if (name##_length > 0) CHECK_NE(name##_data, nullptr); + #define SPREAD_BUFFER_ARG(val, name) \ + CHECK((val)->IsArrayBufferView()); \ + v8::Local name = (val).As(); \ + const size_t name##_offset = name->ByteOffset(); \ + const size_t name##_length = name->ByteLength(); \ + char* const name##_data = \ + static_cast(name->Buffer()->Data()) + name##_offset; \ + if (name##_length > 0) CHECK_NE(name##_data, nullptr); // Use this when a variable or parameter is unused in order to explicitly // silence a compiler warning about that. -template inline void USE(T&&) {} +template +inline void USE(T&&) {} template struct OnScopeLeaveImpl { - Fn fn_; - bool active_; + Fn fn_; + bool active_; - explicit OnScopeLeaveImpl(Fn&& fn) : fn_(std::move(fn)), active_(true) {} - ~OnScopeLeaveImpl() { if (active_) fn_(); } + explicit OnScopeLeaveImpl(Fn&& fn) : fn_(std::move(fn)), active_(true) {} + ~OnScopeLeaveImpl() { + if (active_) fn_(); + } - OnScopeLeaveImpl(const OnScopeLeaveImpl& other) = delete; - OnScopeLeaveImpl& operator=(const OnScopeLeaveImpl& other) = delete; - OnScopeLeaveImpl(OnScopeLeaveImpl&& other) + OnScopeLeaveImpl(const OnScopeLeaveImpl& other) = delete; + OnScopeLeaveImpl& operator=(const OnScopeLeaveImpl& other) = delete; + OnScopeLeaveImpl(OnScopeLeaveImpl&& other) : fn_(std::move(other.fn_)), active_(other.active_) { - other.active_ = false; - } + other.active_ = false; + } }; // Run a function when exiting the current scope. Used like this: @@ -589,95 +590,94 @@ struct OnScopeLeaveImpl { // }); template inline MUST_USE_RESULT OnScopeLeaveImpl OnScopeLeave(Fn&& fn) { - return OnScopeLeaveImpl{std::move(fn)}; + return OnScopeLeaveImpl{std::move(fn)}; } // Simple RAII wrapper for contiguous data that uses malloc()/free(). template struct MallocedBuffer { - T* data; - size_t size; + T* data; + size_t size; - T* release() { - T* ret = data; - data = nullptr; - return ret; - } + T* release() { + T* ret = data; + data = nullptr; + return ret; + } - void Truncate(size_t new_size) { - CHECK_LE(new_size, size); - size = new_size; - } + void Truncate(size_t new_size) { + CHECK_LE(new_size, size); + size = new_size; + } - void Realloc(size_t new_size) { - Truncate(new_size); - data = UncheckedRealloc(data, new_size); - } + void Realloc(size_t new_size) { + Truncate(new_size); + data = UncheckedRealloc(data, new_size); + } - bool is_empty() const { return data == nullptr; } + bool is_empty() const { return data == nullptr; } - MallocedBuffer() : data(nullptr), size(0) {} - explicit MallocedBuffer(size_t size) : data(Malloc(size)), size(size) {} - MallocedBuffer(T* data, size_t size) : data(data), size(size) {} - MallocedBuffer(MallocedBuffer&& other) : data(other.data), size(other.size) { - other.data = nullptr; - } - MallocedBuffer& operator=(MallocedBuffer&& other) { - this->~MallocedBuffer(); - return *new(this) MallocedBuffer(std::move(other)); - } - ~MallocedBuffer() { - free(data); - } - MallocedBuffer(const MallocedBuffer&) = delete; - MallocedBuffer& operator=(const MallocedBuffer&) = delete; + MallocedBuffer() : data(nullptr), size(0) {} + explicit MallocedBuffer(size_t size) : data(Malloc(size)), size(size) {} + MallocedBuffer(T* data, size_t size) : data(data), size(size) {} + MallocedBuffer(MallocedBuffer&& other) : data(other.data), size(other.size) { + other.data = nullptr; + } + MallocedBuffer& operator=(MallocedBuffer&& other) { + this->~MallocedBuffer(); + return *new (this) MallocedBuffer(std::move(other)); + } + ~MallocedBuffer() { + free(data); + } + MallocedBuffer(const MallocedBuffer&) = delete; + MallocedBuffer& operator=(const MallocedBuffer&) = delete; }; template class NonCopyableMaybe { - public: - NonCopyableMaybe() : empty_(true) {} - explicit NonCopyableMaybe(T&& value) - : empty_(false), - value_(std::move(value)) {} +public: + NonCopyableMaybe() : empty_(true) {} + explicit NonCopyableMaybe(T&& value) + : empty_(false), + value_(std::move(value)) {} - bool IsEmpty() const { - return empty_; - } + bool IsEmpty() const { + return empty_; + } - const T* get() const { - return empty_ ? nullptr : &value_; - } + const T* get() const { + return empty_ ? nullptr : &value_; + } - const T* operator->() const { - CHECK(!empty_); - return &value_; - } + const T* operator->() const { + CHECK(!empty_); + return &value_; + } - T&& Release() { - CHECK_EQ(empty_, false); - empty_ = true; - return std::move(value_); - } + T&& Release() { + CHECK_EQ(empty_, false); + empty_ = true; + return std::move(value_); + } - private: - bool empty_; - T value_; +private: + bool empty_; + T value_; }; // Test whether some value can be called with (). template -struct is_callable : std::is_function { }; +struct is_callable : std::is_function {}; template struct is_callable::value - >::type> : std::true_type { }; + std::is_same::value>::type> : std::true_type {}; template struct FunctionDeleter { - void operator()(T* pointer) const { function(pointer); } - typedef std::unique_ptr Pointer; + void operator()(T* pointer) const { function(pointer); } + typedef std::unique_ptr Pointer; }; template @@ -690,7 +690,7 @@ inline v8::MaybeLocal ToV8Value(v8::Local context, std::string_view str, v8::Isolate* isolate = nullptr); template ::is_specialized, bool>::type> + typename std::enable_if::is_specialized, bool>::type> inline v8::MaybeLocal ToV8Value(v8::Local context, const T& number, v8::Isolate* isolate = nullptr); @@ -707,157 +707,158 @@ inline v8::MaybeLocal ToV8Value(v8::Local context, const std::unordered_map& map, v8::Isolate* isolate = nullptr); -// These macros expects a `Isolate* isolate` and a `Local context` -// to be in the scope. -#define READONLY_PROPERTY(obj, name, value) \ - do { \ - obj->DefineOwnProperty( \ - context, FIXED_ONE_BYTE_STRING(isolate, name), value, v8::ReadOnly) \ - .Check(); \ - } while (0) + // These macros expects a `Isolate* isolate` and a `Local context` + // to be in the scope. + #define READONLY_PROPERTY(obj, name, value) \ + do { \ + obj->DefineOwnProperty( \ + context, FIXED_ONE_BYTE_STRING(isolate, name), value, v8::ReadOnly) \ + .Check(); \ + } while (0) -#define READONLY_DONT_ENUM_PROPERTY(obj, name, var) \ - do { \ - obj->DefineOwnProperty( \ - context, \ - OneByteString(isolate, name), \ - var, \ - static_cast(v8::ReadOnly | v8::DontEnum)) \ - .Check(); \ - } while (0) + #define READONLY_DONT_ENUM_PROPERTY(obj, name, var) \ + do { \ + obj->DefineOwnProperty( \ + context, \ + OneByteString(isolate, name), \ + var, \ + static_cast(v8::ReadOnly | v8::DontEnum)) \ + .Check(); \ + } while (0) -#define READONLY_FALSE_PROPERTY(obj, name) \ - READONLY_PROPERTY(obj, name, v8::False(isolate)) + #define READONLY_FALSE_PROPERTY(obj, name) \ + READONLY_PROPERTY(obj, name, v8::False(isolate)) -#define READONLY_TRUE_PROPERTY(obj, name) \ - READONLY_PROPERTY(obj, name, v8::True(isolate)) + #define READONLY_TRUE_PROPERTY(obj, name) \ + READONLY_PROPERTY(obj, name, v8::True(isolate)) -#define READONLY_STRING_PROPERTY(obj, name, str) \ - READONLY_PROPERTY(obj, name, ToV8Value(context, str).ToLocalChecked()) + #define READONLY_STRING_PROPERTY(obj, name, str) \ + READONLY_PROPERTY(obj, name, ToV8Value(context, str).ToLocalChecked()) -// Variation on NODE_DEFINE_CONSTANT that sets a String value. -#define NODE_DEFINE_STRING_CONSTANT(target, name, constant) \ - do { \ - v8::Isolate* isolate = target->GetIsolate(); \ - v8::Local constant_name = \ - v8::String::NewFromUtf8(isolate, name).ToLocalChecked(); \ - v8::Local constant_value = \ - v8::String::NewFromUtf8(isolate, constant).ToLocalChecked(); \ - v8::PropertyAttribute constant_attributes = \ - static_cast(v8::ReadOnly | v8::DontDelete); \ - target \ - ->DefineOwnProperty(isolate->GetCurrentContext(), \ - constant_name, \ - constant_value, \ - constant_attributes) \ - .Check(); \ - } while (0) + // Variation on NODE_DEFINE_CONSTANT that sets a String value. + #define NODE_DEFINE_STRING_CONSTANT(target, name, constant) \ + do { \ + v8::Isolate* isolate = target->GetIsolate(); \ + v8::Local constant_name = \ + v8::String::NewFromUtf8(isolate, name).ToLocalChecked(); \ + v8::Local constant_value = \ + v8::String::NewFromUtf8(isolate, constant).ToLocalChecked(); \ + v8::PropertyAttribute constant_attributes = \ + static_cast(v8::ReadOnly | v8::DontDelete); \ + target \ + ->DefineOwnProperty(isolate->GetCurrentContext(), \ + constant_name, \ + constant_value, \ + constant_attributes) \ + .Check(); \ + } while (0) -enum class Endianness { LITTLE, BIG }; +enum class Endianness { LITTLE, + BIG }; inline Endianness GetEndianness() { - // Constant-folded by the compiler. - const union { - uint8_t u8[2]; - uint16_t u16; - } u = {{1, 0}}; - return u.u16 == 1 ? Endianness::LITTLE : Endianness::BIG; + // Constant-folded by the compiler. + const union { + uint8_t u8[2]; + uint16_t u16; + } u = {{1, 0}}; + return u.u16 == 1 ? Endianness::LITTLE : Endianness::BIG; } inline bool IsLittleEndian() { - return GetEndianness() == Endianness::LITTLE; + return GetEndianness() == Endianness::LITTLE; } inline bool IsBigEndian() { - return GetEndianness() == Endianness::BIG; + return GetEndianness() == Endianness::BIG; } // Round up a to the next highest multiple of b. template constexpr T RoundUp(T a, T b) { - return a % b != 0 ? a + b - (a % b) : a; + return a % b != 0 ? a + b - (a % b) : a; } // Align ptr to an `alignment`-bytes boundary. template constexpr T* AlignUp(T* ptr, U alignment) { - return reinterpret_cast( - RoundUp(reinterpret_cast(ptr), alignment)); + return reinterpret_cast( + RoundUp(reinterpret_cast(ptr), alignment)); } class SlicedArguments : public MaybeStackBuffer> { - public: - inline explicit SlicedArguments( - const v8::FunctionCallbackInfo& args, size_t start = 0); +public: + inline explicit SlicedArguments( + const v8::FunctionCallbackInfo& args, size_t start = 0); }; // Convert a v8::PersistentBase, e.g. v8::Global, to a Local, with an extra // optimization for strong persistent handles. class PersistentToLocal { - public: - // If persistent.IsWeak() == false, then do not call persistent.Reset() - // while the returned Local is still in scope, it will destroy the - // reference to the object. - template - static inline v8::Local Default( - v8::Isolate* isolate, - const v8::PersistentBase& persistent) { - if (persistent.IsWeak()) { - return PersistentToLocal::Weak(isolate, persistent); - } else { - return PersistentToLocal::Strong(persistent); +public: + // If persistent.IsWeak() == false, then do not call persistent.Reset() + // while the returned Local is still in scope, it will destroy the + // reference to the object. + template + static inline v8::Local Default( + v8::Isolate* isolate, + const v8::PersistentBase& persistent) { + if (persistent.IsWeak()) { + return PersistentToLocal::Weak(isolate, persistent); + } else { + return PersistentToLocal::Strong(persistent); + } } - } - // Unchecked conversion from a non-weak Persistent to Local, - // use with care! - // - // Do not call persistent.Reset() while the returned Local is still in - // scope, it will destroy the reference to the object. - template - static inline v8::Local Strong( - const v8::PersistentBase& persistent) { - DCHECK(!persistent.IsWeak()); - return *reinterpret_cast*>( - const_cast*>(&persistent)); - } + // Unchecked conversion from a non-weak Persistent to Local, + // use with care! + // + // Do not call persistent.Reset() while the returned Local is still in + // scope, it will destroy the reference to the object. + template + static inline v8::Local Strong( + const v8::PersistentBase& persistent) { + DCHECK(!persistent.IsWeak()); + return *reinterpret_cast*>( + const_cast*>(&persistent)); + } - template - static inline v8::Local Weak( - v8::Isolate* isolate, - const v8::PersistentBase& persistent) { - return v8::Local::New(isolate, persistent); - } + template + static inline v8::Local Weak( + v8::Isolate* isolate, + const v8::PersistentBase& persistent) { + return v8::Local::New(isolate, persistent); + } }; // Can be used as a key for std::unordered_map when lookup performance is more // important than size and the keys are statically used to avoid redundant hash // computations. class FastStringKey { - public: - constexpr explicit FastStringKey(std::string_view name); +public: + constexpr explicit FastStringKey(std::string_view name); - struct Hash { - constexpr size_t operator()(const FastStringKey& key) const; - }; - constexpr bool operator==(const FastStringKey& other) const; + struct Hash { + constexpr size_t operator()(const FastStringKey& key) const; + }; + constexpr bool operator==(const FastStringKey& other) const; - constexpr std::string_view as_string_view() const; + constexpr std::string_view as_string_view() const; - private: - static constexpr size_t HashImpl(std::string_view str); +private: + static constexpr size_t HashImpl(std::string_view str); - const std::string_view name_; - const size_t cached_hash_; + const std::string_view name_; + const size_t cached_hash_; }; // Like std::static_pointer_cast but for unique_ptr with the default deleter. template std::unique_ptr static_unique_pointer_cast(std::unique_ptr&& ptr) { - return std::unique_ptr(static_cast(ptr.release())); + return std::unique_ptr(static_cast(ptr.release())); } -#define MAYBE_FIELD_PTR(ptr, field) ptr == nullptr ? nullptr : &(ptr->field) + #define MAYBE_FIELD_PTR(ptr, field) ptr == nullptr ? nullptr : &(ptr->field) // Returns a non-zero code if it fails to open or read the file, // aborts if it fails to close the file. @@ -914,8 +915,8 @@ void SetProtoMethodNoSideEffect(v8::Isolate* isolate, v8::FunctionCallback callback); enum class SetConstructorFunctionFlag { - NONE, - SET_CLASS_NAME, + NONE, + SET_CLASS_NAME, }; void SetConstructorFunction(v8::Local context, @@ -932,8 +933,8 @@ void SetConstructorFunction(v8::Local context, SetConstructorFunctionFlag flag = SetConstructorFunctionFlag::SET_CLASS_NAME); -} // namespace node +} // namespace node -#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS +#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#endif // SRC_UTIL_H_ +#endif // SRC_UTIL_H_ diff --git a/native/cocos/bindings/jswrapper/jsvm/Class.cpp b/native/cocos/bindings/jswrapper/jsvm/Class.cpp index 337d0a31d6..8b65cbc221 100644 --- a/native/cocos/bindings/jswrapper/jsvm/Class.cpp +++ b/native/cocos/bindings/jswrapper/jsvm/Class.cpp @@ -51,7 +51,7 @@ Class *Class::create(const std::string &clsName, se::Object *parent, Object *par return cls; } -Class* Class::create(const std::initializer_list &classPath, se::Object *parent, Object *parentProto, JSVM_Callback ctor) { +Class *Class::create(const std::initializer_list &classPath, se::Object *parent, Object *parentProto, JSVM_Callback ctor) { se::AutoHandleScope scope; se::Object *currentParent = parent; se::Value tmp; @@ -64,7 +64,7 @@ Class* Class::create(const std::initializer_list &classPath, se::O } bool Class::init(const std::string &clsName, Object *parent, Object *parentProto, JSVM_Callback ctor) { - _name = clsName; + _name = clsName; _parent = parent; if (_parent != nullptr) _parent->incRef(); @@ -86,7 +86,7 @@ JSVM_Value Class::_defaultCtor(JSVM_Env env, JSVM_CallbackInfo info) { return thisArg; } -void Class::defineProperty(const char* name, JSVM_Callback g, JSVM_Callback s) { +void Class::defineProperty(const char *name, JSVM_Callback g, JSVM_Callback s) { _properties.push_back({name, nullptr, nullptr, g, s, 0, JSVM_DEFAULT_JSPROPERTY}); } @@ -96,18 +96,18 @@ void Class::defineProperty(const std::initializer_list &names, JSV } } -void Class::defineStaticProperty(const char* name, JSVM_Callback g, JSVM_Callback s) { - if(g != nullptr && s != nullptr) +void Class::defineStaticProperty(const char *name, JSVM_Callback g, JSVM_Callback s) { + if (g != nullptr && s != nullptr) _properties.push_back({name, nullptr, nullptr, g, s, 0, JSVM_STATIC}); } -void Class::defineFunction(const char* name, JSVM_Callback func) { - // When JSVM defines a function, it needs to add the enum attribute, otherwise JS cannot traverse the function +void Class::defineFunction(const char *name, JSVM_Callback func) { + // When JSVM defines a function, it needs to add the enum attribute, otherwise JS cannot traverse the function _properties.push_back({name, nullptr, func, nullptr, nullptr, nullptr, JSVM_JSPROPERTY_NO_RECEIVER_CHECK}); } -void Class::defineStaticFunction(const char* name, JSVM_Callback func) { - _properties.push_back({name, nullptr, func, nullptr, nullptr, 0, JSVM_PropertyAttributes((int)JSVM_STATIC|(int)JSVM_WRITABLE)}); +void Class::defineStaticFunction(const char *name, JSVM_Callback func) { + _properties.push_back({name, nullptr, func, nullptr, nullptr, 0, JSVM_PropertyAttributes((int)JSVM_STATIC | (int)JSVM_WRITABLE)}); } bool Class::defineStaticProperty(const char *name, const Value &v, PropertyAttribute attribute /* = PropertyAttribute::NONE */) { @@ -129,7 +129,7 @@ JSVM_Finalize Class::_getFinalizeFunction() const { bool Class::install() { auto env = ScriptEngine::getEnv(); - JSVM_Value cons; + JSVM_Value cons; JSVM_Status status; NODE_API_CALL(status, env, OH_JSVM_DefineClass(env, _name.c_str(), -1, _ctorFunc, _properties.size(), _properties.data(), &cons)); if (_parentProto) { @@ -147,7 +147,7 @@ bool Class::install() { _proto->root(); } - return true; + return true; } JSVM_Status Class::inherit(JSVM_Env env, JSVM_Value subclass, JSVM_Value superProto) { @@ -205,7 +205,7 @@ JSVM_Ref Class::_getCtorRef() const { JSVM_Value Class::_getCtorFunc() const { assert(_constructor); - JSVM_Value result = nullptr; + JSVM_Value result = nullptr; JSVM_Status status; NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_GetReferenceValue(ScriptEngine::getEnv(), _constructor, &result)); return result; @@ -231,7 +231,7 @@ void Class::destroy() { } _ctor.reset(); } - + OH_JSVM_DeleteReference(ScriptEngine::getEnv(), _constructor); } diff --git a/native/cocos/bindings/jswrapper/jsvm/Class.h b/native/cocos/bindings/jswrapper/jsvm/Class.h index 175682e6b8..5f7eedcf39 100644 --- a/native/cocos/bindings/jswrapper/jsvm/Class.h +++ b/native/cocos/bindings/jswrapper/jsvm/Class.h @@ -24,11 +24,11 @@ ****************************************************************************/ #pragma once -#include #include +#include +#include "../Define.h" #include "CommonHeader.h" #include "Object.h" -#include "../Define.h" namespace se { class Class { @@ -36,49 +36,48 @@ public: static Class *create(const std::string &clsName, se::Object *parent, Object *parentProto, JSVM_Callback ctor = nullptr); static Class *create(const std::initializer_list &classPath, se::Object *parent, Object *parentProto, JSVM_Callback ctor = nullptr); - void defineFunction(const char* name, JSVM_Callback func); - void defineProperty(const char* name, JSVM_Callback g, JSVM_Callback s); - void defineProperty(const std::initializer_list &names, JSVM_Callback g, JSVM_Callback s); + void defineFunction(const char *name, JSVM_Callback func); + void defineProperty(const char *name, JSVM_Callback g, JSVM_Callback s); + void defineProperty(const std::initializer_list &names, JSVM_Callback g, JSVM_Callback s); - void defineStaticFunction(const char* name, JSVM_Callback func); - void defineStaticProperty(const char* name, JSVM_Callback g, JSVM_Callback s); - bool defineStaticProperty(const char *name, const Value &value, PropertyAttribute attribute = PropertyAttribute::NONE); + void defineStaticFunction(const char *name, JSVM_Callback func); + void defineStaticProperty(const char *name, JSVM_Callback g, JSVM_Callback s); + bool defineStaticProperty(const char *name, const Value &value, PropertyAttribute attribute = PropertyAttribute::NONE); - static JSVM_Value _createJSObjectWithClass(Class *cls); - - void defineFinalizeFunction(JSVM_Finalize func); + static JSVM_Value _createJSObjectWithClass(Class *cls); + + void defineFinalizeFunction(JSVM_Finalize func); JSVM_Finalize _getFinalizeFunction() const; - - - Object * getProto() const; - bool install(); - JSVM_Status inherit(JSVM_Env env, JSVM_Value subclass, JSVM_Value superclass); - JSVM_Ref _getCtorRef() const; - JSVM_Value _getCtorFunc() const; - const char * getName() const { return _name.c_str(); } - static void setExports(JSVM_Value *expPtr) { _exports = expPtr; } + + Object *getProto() const; + bool install(); + JSVM_Status inherit(JSVM_Env env, JSVM_Value subclass, JSVM_Value superclass); + JSVM_Ref _getCtorRef() const; + JSVM_Value _getCtorFunc() const; + const char *getName() const { return _name.c_str(); } + static void setExports(JSVM_Value *expPtr) { _exports = expPtr; } static void cleanup(); // Private API used in wrapper - void _setCtor(Object *obj); // NOLINT(readability-identifier-naming) + void _setCtor(Object *obj); // NOLINT(readability-identifier-naming) inline const std::optional &_getCtor() const { return _ctor; } // NOLINT(readability-identifier-naming) private: Class(); ~Class(); - bool init(const std::string &clsName, Object *parent, Object *parentProto, JSVM_Callback ctor = nullptr); - void destroy(); + bool init(const std::string &clsName, Object *parent, Object *parentProto, JSVM_Callback ctor = nullptr); + void destroy(); static JSVM_Value _defaultCtor(JSVM_Env env, JSVM_CallbackInfo info); private: - std::optional _ctor; - static JSVM_Value * _exports; - std::string _name; - Object * _parent = nullptr; - Object * _proto = nullptr; - Object * _parentProto = nullptr; - JSVM_CallbackStruct _ctorStruct = {Class::_defaultCtor,nullptr}; - JSVM_Callback _ctorFunc = &_ctorStruct; - JSVM_Ref _constructor = nullptr; - std::vector _properties; - JSVM_Finalize _finalizeFunc = nullptr; + std::optional _ctor; + static JSVM_Value *_exports; + std::string _name; + Object *_parent = nullptr; + Object *_proto = nullptr; + Object *_parentProto = nullptr; + JSVM_CallbackStruct _ctorStruct = {Class::_defaultCtor, nullptr}; + JSVM_Callback _ctorFunc = &_ctorStruct; + JSVM_Ref _constructor = nullptr; + std::vector _properties; + JSVM_Finalize _finalizeFunc = nullptr; }; }; // namespace se \ No newline at end of file diff --git a/native/cocos/bindings/jswrapper/jsvm/CommonHeader.h b/native/cocos/bindings/jswrapper/jsvm/CommonHeader.h index bc8fc6dee1..363f3414f3 100644 --- a/native/cocos/bindings/jswrapper/jsvm/CommonHeader.h +++ b/native/cocos/bindings/jswrapper/jsvm/CommonHeader.h @@ -26,9 +26,9 @@ #pragma once #if CC_PLATFORM == CC_PLATFORM_OPENHARMONY -#include "ark_runtime/jsvm.h" + #include "ark_runtime/jsvm.h" #else -#include "jsvm.h" + #include "jsvm.h" #endif #include "platform/openharmony/napi/native_common.h" @@ -52,22 +52,22 @@ } \ } while (0) -#define NODE_API_CALL_RESULT(status, env, the_call, ret_val) \ - do { \ - status = the_call; \ - if (status != JSVM_OK) { \ - se::internal::logJsException((env), __FILE_NAME__, __LINE__); \ - return ret_val; \ - } \ +#define NODE_API_CALL_RESULT(status, env, the_call, ret_val) \ + do { \ + status = the_call; \ + if (status != JSVM_OK) { \ + se::internal::logJsException((env), __FILE_NAME__, __LINE__); \ + return ret_val; \ + } \ } while (0) // Returns nullptr if the_call doesn't return JSVM_OK. -#define NODE_API_CALL(status, env, the_call) \ - do { \ - status = the_call; \ - if (status != JSVM_OK) { \ - se::internal::logJsException((env), __FILE_NAME__, __LINE__); \ - } \ +#define NODE_API_CALL(status, env, the_call) \ + do { \ + status = the_call; \ + if (status != JSVM_OK) { \ + se::internal::logJsException((env), __FILE_NAME__, __LINE__); \ + } \ } while (0) // Returns empty if the_call doesn't return JSVM_OK. @@ -82,7 +82,7 @@ #define JSVM_CALL_BASE(theCall, retVal) \ do { \ - if((theCall) != JSVM_OK){ \ + if ((theCall) != JSVM_OK) { \ return retVal; \ } \ } while (0) diff --git a/native/cocos/bindings/jswrapper/jsvm/HelperMacros.cpp b/native/cocos/bindings/jswrapper/jsvm/HelperMacros.cpp index 23e917f996..604792b0ae 100644 --- a/native/cocos/bindings/jswrapper/jsvm/HelperMacros.cpp +++ b/native/cocos/bindings/jswrapper/jsvm/HelperMacros.cpp @@ -39,10 +39,10 @@ SE_HOT JSVM_Value jsbFunctionWrapper(JSVM_Env env, JSVM_CallbackInfo info, se_fu JSVM_Value args[15]; NODE_API_CALL(status, env, OH_JSVM_GetCbInfo(env, info, &argc, args, &_this, NULL)); - void* nativeThisObject = nullptr; + void *nativeThisObject = nullptr; status = OH_JSVM_Unwrap(env, _this, &nativeThisObject); se::internal::jsToSeArgs(argc, args, &seArgs); - se::State state(reinterpret_cast(nativeThisObject), seArgs); + se::State state(reinterpret_cast(nativeThisObject), seArgs); ret = func(state); if (!ret) { SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", funcName, __FILE__, __LINE__); @@ -110,9 +110,9 @@ SE_HOT JSVM_Value jsbGetterWrapper(JSVM_Env env, JSVM_CallbackInfo info, se_func JSVM_Status status; NODE_API_CALL(status, env, OH_JSVM_GetCbInfo(env, info, nullptr, nullptr, &_this, nullptr)); - void* obj = nullptr; + void *obj = nullptr; status = OH_JSVM_Unwrap(env, _this, &obj); - se::State state(reinterpret_cast(obj)); + se::State state(reinterpret_cast(obj)); bool ret = func(state); if (!ret) { SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", funcName, __FILE__, __LINE__); @@ -134,9 +134,9 @@ SE_HOT JSVM_Value jsbSetterWrapper(JSVM_Env env, JSVM_CallbackInfo info, se_func se::ValueArray args2; args2.reserve(10); args2.push_back(std::move(data)); - void* nativeThisObject = nullptr; + void *nativeThisObject = nullptr; status = OH_JSVM_Unwrap(env, _this, &nativeThisObject); - se::State state(reinterpret_cast(nativeThisObject), args2); + se::State state(reinterpret_cast(nativeThisObject), args2); bool ret = func(state); if (!ret) { SE_LOGE("[ERROR] Failed to invoke %s, location: %s:%d\n", funcName, __FILE__, __LINE__); diff --git a/native/cocos/bindings/jswrapper/jsvm/HelperMacros.h b/native/cocos/bindings/jswrapper/jsvm/HelperMacros.h index 027ef87ab8..0a6eb23785 100644 --- a/native/cocos/bindings/jswrapper/jsvm/HelperMacros.h +++ b/native/cocos/bindings/jswrapper/jsvm/HelperMacros.h @@ -30,10 +30,10 @@ #include #ifndef LOGI - #define LOGI(...) ((void) OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) - #define LOGW(...) ((void) OH_LOG_Print(LOG_APP, LOG_WARN, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) - #define LOGE(...) ((void) OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) - #define LOGD(...) ((void) OH_LOG_Print(LOG_APP, LOG_DEBUG, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) + #define LOGI(...) ((void)OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) + #define LOGW(...) ((void)OH_LOG_Print(LOG_APP, LOG_WARN, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) + #define LOGE(...) ((void)OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) + #define LOGD(...) ((void)OH_LOG_Print(LOG_APP, LOG_DEBUG, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) #endif #else #define LOGI CC_LOG_INFO @@ -80,67 +80,66 @@ constexpr inline T *SE_THIS_OBJECT(STATE &s) { // NOLINT(readability-identifier- #define SE_QUOTEME(x) SE_QUOTEME_(x) #define SE_REPORT_ERROR(fmt, ...) SE_LOGE("[ERROR] (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__) -#define SE_BIND_PROP_GET_IMPL(funcName, postFix) \ - JSVM_Value funcName##postFix##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \ - return jsbGetterWrapper(env, info, funcName, #funcName); \ - } \ - JSVM_CallbackStruct funcName##postFix##RegistryStruct = {(funcName##postFix##Registry),nullptr}; +#define SE_BIND_PROP_GET_IMPL(funcName, postFix) \ + JSVM_Value funcName##postFix##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \ + return jsbGetterWrapper(env, info, funcName, #funcName); \ + } \ + JSVM_CallbackStruct funcName##postFix##RegistryStruct = {(funcName##postFix##Registry), nullptr}; #define SE_BIND_PROP_GET(funcName) SE_BIND_PROP_GET_IMPL(funcName, ) #define SE_BIND_FUNC_AS_PROP_GET(funcName) SE_BIND_PROP_GET_IMPL(funcName, _asGetter) -#define SE_BIND_PROP_SET_IMPL(funcName, postFix) \ - JSVM_Value funcName##postFix##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \ - return jsbSetterWrapper(env, info, funcName, #funcName); \ - } \ - JSVM_CallbackStruct funcName##postFix##RegistryStruct = {(funcName##postFix##Registry),nullptr}; +#define SE_BIND_PROP_SET_IMPL(funcName, postFix) \ + JSVM_Value funcName##postFix##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \ + return jsbSetterWrapper(env, info, funcName, #funcName); \ + } \ + JSVM_CallbackStruct funcName##postFix##RegistryStruct = {(funcName##postFix##Registry), nullptr}; #define SE_BIND_PROP_SET(funcName) SE_BIND_PROP_SET_IMPL(funcName, ) #define SE_BIND_FUNC_AS_PROP_SET(funcName) SE_BIND_PROP_SET_IMPL(funcName, _asSetter) -#define SE_DECLARE_FUNC(funcName) \ - JSVM_Value funcName##Registry(JSVM_Env env, JSVM_CallbackInfo info); \ - extern JSVM_CallbackStruct funcName##RegistryStruct; +#define SE_DECLARE_FUNC(funcName) \ + JSVM_Value funcName##Registry(JSVM_Env env, JSVM_CallbackInfo info); \ + extern JSVM_CallbackStruct funcName##RegistryStruct; -#define SE_BIND_FUNC(funcName) \ - JSVM_Value funcName##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \ - return jsbFunctionWrapper(env, info, funcName, #funcName); \ - } \ - JSVM_CallbackStruct funcName##RegistryStruct = {(funcName##Registry),nullptr}; +#define SE_BIND_FUNC(funcName) \ + JSVM_Value funcName##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \ + return jsbFunctionWrapper(env, info, funcName, #funcName); \ + } \ + JSVM_CallbackStruct funcName##RegistryStruct = {(funcName##Registry), nullptr}; -#define SE_BIND_FUNC_FAST(funcName) \ - JSVM_Value funcName##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \ - JSVM_Status status; \ - JSVM_Value _this; \ - size_t argc = 15; \ - JSVM_Value args[15]; \ - void *nativeThisObject = nullptr; \ - NODE_API_CALL(status, env, OH_JSVM_GetCbInfo(env, info, &argc, args, &_this, NULL)); \ - status = OH_JSVM_Unwrap(env, _this, &nativeThisObject); \ - auto *nativeObject = nativeThisObject != nullptr ? ((se::Object*)nativeThisObject)->getPrivateData() : nullptr; \ - funcName(nativeObject); \ - return nullptr; \ - } \ - JSVM_CallbackStruct funcName##RegistryStruct = {(funcName##Registry),nullptr}; - -#define SE_BIND_CTOR(funcName, cls, finalizeCb) \ - JSVM_Value funcName##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \ - return jsbConstructorWrapper(env, info, funcName, _SE(finalizeCb), cls, #funcName); \ - } \ - JSVM_CallbackStruct funcName##RegistryStruct = {(funcName##Registry),nullptr}; +#define SE_BIND_FUNC_FAST(funcName) \ + JSVM_Value funcName##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \ + JSVM_Status status; \ + JSVM_Value _this; \ + size_t argc = 15; \ + JSVM_Value args[15]; \ + void *nativeThisObject = nullptr; \ + NODE_API_CALL(status, env, OH_JSVM_GetCbInfo(env, info, &argc, args, &_this, NULL)); \ + status = OH_JSVM_Unwrap(env, _this, &nativeThisObject); \ + auto *nativeObject = nativeThisObject != nullptr ? ((se::Object *)nativeThisObject)->getPrivateData() : nullptr; \ + funcName(nativeObject); \ + return nullptr; \ + } \ + JSVM_CallbackStruct funcName##RegistryStruct = {(funcName##Registry), nullptr}; +#define SE_BIND_CTOR(funcName, cls, finalizeCb) \ + JSVM_Value funcName##Registry(JSVM_Env env, JSVM_CallbackInfo info) { \ + return jsbConstructorWrapper(env, info, funcName, _SE(finalizeCb), cls, #funcName); \ + } \ + JSVM_CallbackStruct funcName##RegistryStruct = {(funcName##Registry), nullptr}; #define SE_BIND_SUB_CLS_CTOR SE_BIND_CTOR -#define SE_DECLARE_FINALIZE_FUNC(funcName) \ - void funcName##RegistryStruct(JSVM_Env env, void *nativeObject, void * /*finalize_hint*/); \ +#define SE_DECLARE_FINALIZE_FUNC(funcName) \ + void funcName##RegistryStruct(JSVM_Env env, void *nativeObject, void * /*finalize_hint*/); -#define SE_BIND_FINALIZE_FUNC(funcName) \ - void funcName##RegistryStruct(JSVM_Env env, void *nativeObject, void *hint /*finalize_hint*/) { \ - if (nativeObject == nullptr) { \ - return; \ - } \ - jsbFinalizeWrapper(nativeObject, funcName, #funcName); \ +#define SE_BIND_FINALIZE_FUNC(funcName) \ + void funcName##RegistryStruct(JSVM_Env env, void *nativeObject, void *hint /*finalize_hint*/) { \ + if (nativeObject == nullptr) { \ + return; \ + } \ + jsbFinalizeWrapper(nativeObject, funcName, #funcName); \ } -#define _SE(name) &(name##RegistryStruct) +#define _SE(name) &(name##RegistryStruct) diff --git a/native/cocos/bindings/jswrapper/jsvm/Object.cpp b/native/cocos/bindings/jswrapper/jsvm/Object.cpp index 32f205bcb1..65b8d37152 100644 --- a/native/cocos/bindings/jswrapper/jsvm/Object.cpp +++ b/native/cocos/bindings/jswrapper/jsvm/Object.cpp @@ -38,7 +38,7 @@ namespace se { std::unique_ptr> __objectSet; std::unordered_set __objectSetToBeReleasedInCleanup; -Object::Object(): _objRef(this) {} +Object::Object() : _objRef(this) {} Object::~Object() { if (!_destructInFinalizer && _cls != nullptr) { // Remove wrap will ensure that we release the underlying `v8impl::Reference` that the private wrap associates with. @@ -46,7 +46,7 @@ Object::~Object() { // We just do this if `_cls` is not null since only JSB objects get wrapped, OH_JSVM_RemoveWrap(_env, _objRef.getValue(_env), nullptr); } - + if (__objectSet) { __objectSet->erase(this); } @@ -65,7 +65,7 @@ bool Object::setProperty(const char* name, const Value& data) { JSVM_Status status; JSVM_Value jsVal; bool ret = internal::seToJsValue(data, &jsVal); - if(!ret) { + if (!ret) { return false; } NODE_API_CALL(status, _env, OH_JSVM_SetNamedProperty(_env, _objRef.getValue(_env), name, jsVal)); @@ -119,7 +119,7 @@ void Object::setPrivateObject(PrivateObjectBase* data) { // Passing nullptr to the `result` parameter to make JSVM mangle the lifecycle of `v8impl::Reference` NODE_API_CALL(status, _env, OH_JSVM_Wrap(_env, tmpThis, this, weakCallback, this /* finalize_hint */, nullptr)); - + // WORKAROUND: See the explain in `ObjectRef::deleteRef` about why we need to `decRef` here. _objRef.decRef(_env); // @@ -163,7 +163,7 @@ bool Object::setArrayElement(uint32_t index, const Value& data) { JSVM_Status status; JSVM_Value val; bool ret = internal::seToJsValue(data, &val); - if(!ret) { + if (!ret) { return false; } NODE_API_CALL_RESULT(status, _env, OH_JSVM_SetElement(_env, _objRef.getValue(_env), index, val), false); @@ -521,7 +521,7 @@ bool Object::getAllKeys(std::vector* allKeys) const { if (status == JSVM_OK) { size_t result = 0; NODE_API_CALL(status, _env, OH_JSVM_GetValueStringUtf8(_env, val, nullptr, 0, &result)); - if(status == JSVM_OK){ + if (status == JSVM_OK) { result += 1; char buffer[result]; NODE_API_CALL(status, _env, OH_JSVM_GetValueStringUtf8(_env, val, buffer, sizeof(buffer), &result)); @@ -558,14 +558,14 @@ bool Object::call(const ValueArray& args, Object* thisObject, Value* rval) { argv.reserve(10); argc = args.size(); bool valid = internal::seToJsArgs(_env, args, &argv); - if(!valid) { + if (!valid) { SE_LOGE("Failed to convert arguments from se::Value to JSVM_Value"); return false; } JSVM_Value return_val; JSVM_Status status; assert(isFunction()); - if(thisObject != nullptr && !thisObject->_getJSObject()) { + if (thisObject != nullptr && !thisObject->_getJSObject()) { SE_LOGE("Invalid 'this' object passed to function call (JS object is invalid or released)"); return false; } @@ -575,7 +575,7 @@ bool Object::call(const ValueArray& args, Object* thisObject, Value* rval) { undefinedValue; }); NODE_API_CALL_RESULT(status, _env, - OH_JSVM_CallFunction(_env, thisObj, _getJSObject(), argc, argv.data(), &return_val), false); + OH_JSVM_CallFunction(_env, thisObj, _getJSObject(), argc, argv.data(), &return_val), false); if (rval) { internal::jsToSeValue(return_val, rval); } @@ -703,7 +703,7 @@ void Object::sendWeakCallback(JSVM_Env env, void* nativeObject, void* finalizeHi void Object::setClearMappingInFinalizer(bool v) { _clearMappingInFinalizer = v; - + // The lifecycle of Spine and Dragonbones c++ objects are controlled by their runtime. // See the `cc::setSpineObjectDisposeCallback` invocation in jsb_spine_manuall.cpp. // It listens on spine C++ objects's destruction and when the callback comes, @@ -727,7 +727,7 @@ void Object::weakCallback(JSVM_Env env, void* nativeObject, void* finalizeHint / if (seObj->_onCleaingPrivateData) { //called by cleanPrivateData, not release seObj; return; } - if(!NativePtrToObjectMap::isValid()) { + if (!NativePtrToObjectMap::isValid()) { return; } if (seObj->_clearMappingInFinalizer && rawPtr != nullptr) { @@ -747,9 +747,9 @@ void Object::weakCallback(JSVM_Env env, void* nativeObject, void* finalizeHint / seObj->_getClass()->_getFinalizeFunction()(env, finalizeHint, finalizeHint); } } - + __objectSetToBeReleasedInCleanup.erase(seObj); - + seObj->_destructInFinalizer = true; seObj->decRef(); } @@ -780,14 +780,14 @@ void Object::cleanup() { } obj->decRef(); } - - for (auto *obj : __objectSetToBeReleasedInCleanup) { + + for (auto* obj : __objectSetToBeReleasedInCleanup) { obj->decRef(); } __objectSetToBeReleasedInCleanup.clear(); NativePtrToObjectMap::clear(); - + if (__objectSet) { for (const auto& obj : *__objectSet) { cls = obj->_getClass(); @@ -890,20 +890,19 @@ Object* Object::createPromise() { return object; } -ObjectRef::ObjectRef(Object *parent) +ObjectRef::ObjectRef(Object* parent) : _parent(parent) { - } ObjectRef::~ObjectRef() { deleteRef(); } - + void ObjectRef::init(JSVM_Env env, JSVM_Value obj) { assert(_ref == nullptr); _obj = obj; _env = env; - + // There is a bug in JSVM implementation: // If we initialize the reference to 0 which means weak reference in JSVM, // then we call the JSVM API in the following order: @@ -915,7 +914,7 @@ void ObjectRef::init(JSVM_Env env, JSVM_Value obj) { // OH_JSVM_CreateReference(_env, _obj, 1, &_ref); } - + JSVM_Value ObjectRef::getValue(JSVM_Env env) const { JSVM_Value r = nullptr; JSVM_Status status; @@ -1010,7 +1009,7 @@ void ObjectRef::deleteRef() { In `se::Object::setPrivateObject`, after invoking `OH_JSVM_Wrap`, we need to call `ObjectRef::decRef` to reset the object state to weak, which makes sure that weak callback get called. */ - + // If we have already been in the weak callback ( finalizer ), no need to apply this workaround fix. if (!_parent->_destructInFinalizer) { // WORKAROUND HERE @@ -1023,4 +1022,3 @@ void ObjectRef::deleteRef() { } } // namespace se - diff --git a/native/cocos/bindings/jswrapper/jsvm/Object.h b/native/cocos/bindings/jswrapper/jsvm/Object.h index a94f20ddf1..1b6c228e0c 100644 --- a/native/cocos/bindings/jswrapper/jsvm/Object.h +++ b/native/cocos/bindings/jswrapper/jsvm/Object.h @@ -24,8 +24,9 @@ ****************************************************************************/ #pragma once -#include #include +#include +#include #include "../PrivateObject.h" #include "../RefCounter.h" #include "../Value.h" @@ -33,7 +34,6 @@ #include "CommonHeader.h" #include "HelperMacros.h" #include "Utils.h" -#include namespace se { class Class; @@ -47,12 +47,12 @@ private: JSVM_Ref _ref{nullptr}; JSVM_Env _env{nullptr}; JSVM_Value _obj{nullptr}; - Object* _parent{nullptr}; + Object *_parent{nullptr}; public: ObjectRef(Object *parent); ~ObjectRef(); - + JSVM_Value getValue(JSVM_Env env) const; void init(JSVM_Env env, JSVM_Value obj); void incRef(JSVM_Env env); @@ -76,7 +76,7 @@ public: BIGINT64, BIGUINT64 }; - + using BufferContentsFreeFunc = void (*)(void *contents, size_t byteLength, void *userData); struct ExternalArrayBufferCallbackParams { @@ -458,9 +458,9 @@ private: uint32_t _rootCount = 0; bool _onCleaingPrivateData = false; internal::PrivateData *_internalData; - - static std::unordered_map resolverMap; - + + static std::unordered_map resolverMap; + friend class ObjectRef; friend class ScriptEngine; }; diff --git a/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.cpp b/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.cpp index 8bcd1869db..cf3ead335f 100644 --- a/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.cpp +++ b/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.cpp @@ -27,14 +27,14 @@ #include #include "../MappingUtils.h" #include "Class.h" +#include "CommonHeader.h" #include "State.h" #include "Utils.h" -#include "CommonHeader.h" #if CC_PLATFORM == CC_PLATFORM_OPENHARMONY -#include "ark_runtime/jsvm.h" + #include "ark_runtime/jsvm.h" #else -#include "jsvm.h" + #include "jsvm.h" #endif #define _EXPOSE_GC "__jsb_gc__" @@ -61,11 +61,11 @@ se::Value __oldConsoleWarn; se::Value __oldConsoleError; se::Value __oldConsoleAssert; -bool JSB_console_format_log(State& s, cc::LogLevel level, int msgIndex = 0) { +bool JSB_console_format_log(State &s, cc::LogLevel level, int msgIndex = 0) { if (msgIndex < 0) return false; - const auto& args = s.args(); + const auto &args = s.args(); int argc = (int)args.size(); if ((argc - msgIndex) == 1) { std::string msg = args[msgIndex].toStringForce(); @@ -73,37 +73,37 @@ bool JSB_console_format_log(State& s, cc::LogLevel level, int msgIndex = 0) { } else if (argc > 1) { std::string msg = args[msgIndex].toStringForce(); size_t pos; - for (int i = (msgIndex+1); i < argc; ++i) { + for (int i = (msgIndex + 1); i < argc; ++i) { pos = msg.find("%"); - if (pos != std::string::npos && pos != (msg.length()-1) && - (msg[pos+1] == 'd' || msg[pos+1] == 's' || msg[pos+1] == 'f')) { - msg.replace(pos, 2, args[i].toStringForce()); - } else { - msg += " " + args[i].toStringForce(); - } + if (pos != std::string::npos && pos != (msg.length() - 1) && + (msg[pos + 1] == 'd' || msg[pos + 1] == 's' || msg[pos + 1] == 'f')) { + msg.replace(pos, 2, args[i].toStringForce()); + } else { + msg += " " + args[i].toStringForce(); + } } cc::Log::logMessage(cc::LogType::KERNEL, level, "JS: %s", msg.c_str()); } return true; } -bool JSB_console_log(State& s) { +bool JSB_console_log(State &s) { JSB_console_format_log(s, cc::LogLevel::LEVEL_DEBUG); __oldConsoleLog.toObject()->call(s.args(), s.thisObject()); return true; } - + SE_BIND_FUNC(JSB_console_log) -bool JSB_console_debug(State& s) { +bool JSB_console_debug(State &s) { JSB_console_format_log(s, cc::LogLevel::LEVEL_DEBUG); __oldConsoleDebug.toObject()->call(s.args(), s.thisObject()); return true; } - + SE_BIND_FUNC(JSB_console_debug) -bool JSB_console_info(State& s) { +bool JSB_console_info(State &s) { JSB_console_format_log(s, cc::LogLevel::INFO); __oldConsoleInfo.toObject()->call(s.args(), s.thisObject()); return true; @@ -111,15 +111,15 @@ bool JSB_console_info(State& s) { SE_BIND_FUNC(JSB_console_info) -bool JSB_console_warn(State& s) { +bool JSB_console_warn(State &s) { JSB_console_format_log(s, cc::LogLevel::WARN); __oldConsoleWarn.toObject()->call(s.args(), s.thisObject()); return true; } - + SE_BIND_FUNC(JSB_console_warn) -bool JSB_console_error(State& s) { +bool JSB_console_error(State &s) { JSB_console_format_log(s, cc::LogLevel::ERR); __oldConsoleError.toObject()->call(s.args(), s.thisObject()); return true; @@ -127,8 +127,8 @@ bool JSB_console_error(State& s) { SE_BIND_FUNC(JSB_console_error) -bool JSB_console_assert(State& s) { - const auto& args = s.args(); +bool JSB_console_assert(State &s) { + const auto &args = s.args(); if (!args.empty()) { if (args[0].isBoolean() && !args[0].toBoolean()) { JSB_console_format_log(s, cc::LogLevel::WARN, 1); @@ -184,11 +184,11 @@ bool ScriptEngine::runScript(const std::string &path, Value *ret /* = nullptr */ } bool ScriptEngine::evalString(const char *scriptStr, ssize_t length, Value *ret, const char *fileName) { - length = length < 0 ? strlen(scriptStr) :length; + length = length < 0 ? strlen(scriptStr) : length; JSVM_Status status; - JSVM_Value jsvmStr; + JSVM_Value jsvmStr; NODE_API_CALL(status, _env, OH_JSVM_CreateStringUtf8(_env, scriptStr, length, &jsvmStr)); - if(status != JSVM_OK) { + if (status != JSVM_OK) { CC_LOG_ERROR("ScriptEngine::evalString, create string failed, fileName = %s", fileName); return false; } @@ -202,32 +202,31 @@ bool ScriptEngine::evalString(const char *scriptStr, ssize_t length, Value *ret, .sourceMapUrl = nullptr, .resourceName = fileName ? fileName : "", .resourceLineOffset = 0, - .resourceColumnOffset = 0 - }; + .resourceColumnOffset = 0}; - NODE_API_CALL(status, _env, - OH_JSVM_CompileScriptWithOrigin(_env, jsvmStr, cachedData, cacheLength, false, &cacheRejected,&scriptOrigin, &compiledScript)); - - if(status != JSVM_OK) { - CC_LOG_ERROR("ScriptEngine::evalSting, compile failed, fileName = %s", fileName); - return false; + NODE_API_CALL(status, _env, + OH_JSVM_CompileScriptWithOrigin(_env, jsvmStr, cachedData, cacheLength, false, &cacheRejected, &scriptOrigin, &compiledScript)); + + if (status != JSVM_OK) { + CC_LOG_ERROR("ScriptEngine::evalSting, compile failed, fileName = %s", fileName); + return false; } JSVM_Value result; NODE_API_CALL(status, _env, OH_JSVM_RunScript(_env, compiledScript, &result)); - if(status != JSVM_OK) { - CC_LOG_ERROR("ScriptEngine::evelSting, run failed, fileName = %s", fileName); - return false; + if (status != JSVM_OK) { + CC_LOG_ERROR("ScriptEngine::evelSting, run failed, fileName = %s", fileName); + return false; } // NOTE: Currently, we don't support JSVM code cache saving/loading. // So creating code cache here is useless and wastes memory. -// if(!cachedData || cacheRejected) { -// NODE_API_CALL(status, _env, -// OH_JSVM_CreateCodeCache(_env, compiledScript, (const uint8_t **)&cachedData, &cacheLength)); -// } - - if(ret) { + // if(!cachedData || cacheRejected) { + // NODE_API_CALL(status, _env, + // OH_JSVM_CreateCodeCache(_env, compiledScript, (const uint8_t **)&cachedData, &cacheLength)); + // } + + if (ret) { internal::jsToSeValue(result, ret); } @@ -236,7 +235,7 @@ bool ScriptEngine::evalString(const char *scriptStr, ssize_t length, Value *ret, bool ScriptEngine::init() { JSVM_Status status; - JSVM_Value result; + JSVM_Value result; for (const auto &hook : _beforeInitHookArray) { hook(); @@ -248,7 +247,7 @@ bool ScriptEngine::init() { NODE_API_CALL(status, _env, OH_JSVM_OpenEnvScope(_env, &_envScope)); se::AutoHandleScope hs; - + uint32_t jsvmVersion = 0; NODE_API_CALL(status, _env, OH_JSVM_GetVersion(_env, &jsvmVersion)); SE_LOGD("Initializing JSVM, version: %u\n", jsvmVersion); @@ -284,9 +283,9 @@ bool ScriptEngine::init() { _globalObj->defineFunction("log", _SE(JSB_console_log)); _globalObj->defineFunction("forceGC", _SE(__forceGC)); - + _globalObj->getProperty(_EXPOSE_GC, &_gcFuncValue); - if(_gcFuncValue.isObject() && _gcFuncValue.toObject()->isFunction()) { + if (_gcFuncValue.isObject() && _gcFuncValue.toObject()->isFunction()) { _gcFunc = _gcFuncValue.toObject(); } else { _gcFunc = nullptr; @@ -303,7 +302,7 @@ bool ScriptEngine::init() { } Object *ScriptEngine::getGlobalObject() const { return _globalObj; } - + void ScriptEngine::closeEngine() { JSVM_Env env = _env; _env = nullptr; @@ -327,16 +326,16 @@ bool ScriptEngine::start() { if (!init()) { return false; } - // debugger + // debugger if (isDebuggerEnabled()) { - if(_debuggerServerAddr == "0.0.0.0") { - OH_JSVM_OpenInspector(_env, "localhost", _debuggerServerPort); + if (_debuggerServerAddr == "0.0.0.0") { + OH_JSVM_OpenInspector(_env, "localhost", _debuggerServerPort); } else { OH_JSVM_OpenInspector(_env, _debuggerServerAddr.c_str(), _debuggerServerPort); } SE_LOGD("Debugger listening..., visit [ http://localhost:%d/json ] to configuration debugging information and copy the devtoolsFrontendUrl value to the browser!", _debuggerServerPort); - - if(_isWaitForConnect) { + + if (_isWaitForConnect) { OH_JSVM_WaitForDebugger(_env, true); } } @@ -373,11 +372,11 @@ void ScriptEngine::cleanup() { SE_LOGD("ScriptEngine::cleanup begin ...\n"); _isInCleanup = true; se::AutoHandleScope hs; - do{ + do { for (const auto &hook : _beforeCleanupHookArray) { hook(); } - }while (0); + } while (0); _beforeCleanupHookArray.clear(); SAFE_DEC_REF(_globalObj); @@ -393,7 +392,7 @@ void ScriptEngine::cleanup() { __oldConsoleAssert.setUndefined(); _globalObj = nullptr; - _isValid = false; + _isValid = false; _gcFunc = nullptr; _registerCallbackArray.clear(); @@ -409,7 +408,7 @@ void ScriptEngine::cleanup() { _isInCleanup = false; NativePtrToObjectMap::destroy(); _gcFuncValue.setUndefined(); - + SE_LOGD("ScriptEngine::cleanup end ...\n"); } @@ -477,16 +476,16 @@ void ScriptEngine::clearException() { } void ScriptEngine::garbageCollect() { - CC_LOG_DEBUG("GC begin ..., (js->native map) size: %d",(int)NativePtrToObjectMap::size()); + CC_LOG_DEBUG("GC begin ..., (js->native map) size: %d", (int)NativePtrToObjectMap::size()); - if(_gcFunc == nullptr) { + if (_gcFunc == nullptr) { JSVM_Status status; NODE_API_CALL(status, _env, OH_JSVM_MemoryPressureNotification(_env, JSVM_MEMORY_PRESSURE_LEVEL_CRITICAL)); } else { _gcFunc->call({}, nullptr); } - - CC_LOG_DEBUG("GC end ..., (js->native map) size: %d",(int)NativePtrToObjectMap::size()); + + CC_LOG_DEBUG("GC end ..., (js->native map) size: %d", (int)NativePtrToObjectMap::size()); } bool ScriptEngine::isGarbageCollecting() const { diff --git a/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.h b/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.h index 0946949abc..e221fe39bd 100644 --- a/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.h +++ b/native/cocos/bindings/jswrapper/jsvm/ScriptEngine.h @@ -35,7 +35,7 @@ using HandleScope = JSVM_HandleScope; namespace se { class AutoHandleScope { public: - // This interface needs to be implemented in JSVM, similar to V8. + // This interface needs to be implemented in JSVM, similar to V8. // Ref:https://nodejs.org/docs/latest-v17.x/api/n-api.html#object-lifetime-management AutoHandleScope(); ~AutoHandleScope(); @@ -43,7 +43,7 @@ public: private: HandleScope _handleScope; }; -using RegisterCallback = bool (*)(Object *); +using RegisterCallback = bool (*)(Object *); using ExceptionCallback = std::function; // location, message, stack class ScriptEngine { @@ -80,8 +80,8 @@ public: /** * @brief Shut down the JSVM engine, because cleanup doesn't destroy all objects immediately. */ - void closeEngine(); - + void closeEngine(); + /** * @brief Sets the delegate for file operation. * @param delegate[in] The delegate instance for file operation. @@ -126,9 +126,9 @@ public: */ void setExceptionCallback(const ExceptionCallback &cb); - ExceptionCallback& getExceptionCallback() { - return _exceptionCallback; - } + ExceptionCallback &getExceptionCallback() { + return _exceptionCallback; + } /** * @brief Grab a snapshot of the current JavaScript execution stack. @@ -150,7 +150,7 @@ public: * @param[in] cb A callback for registering a native binding module. * @note This method just add a callback to a vector, callbacks is invoked in `start` method. */ - void addPermanentRegisterCallback(RegisterCallback cb); + void addPermanentRegisterCallback(RegisterCallback cb); /** * @brief Starts the script engine. @@ -206,7 +206,7 @@ public: Object *getGlobalObject() const; static JSVM_Env getEnv(); - static void setEnv(JSVM_Env env); + static void setEnv(JSVM_Env env); /** * @brief Adds a callback for registering a native binding module. @@ -272,12 +272,12 @@ public: */ void throwException(const std::string &errorMessage); - /** + /** * @brief for jsvm_new_instance, skip constructor. */ void _setNeedCallConstructor(bool need); - /** + /** * @brief for jsvm_new_instance, skip constructor. */ bool _needCallConstructor(); @@ -292,7 +292,7 @@ public: void handlePromiseExceptions(); private: - FileOperationDelegate _fileOperationDelegate; + FileOperationDelegate _fileOperationDelegate; std::vector _registerCallbackArray; std::vector _permRegisterCallbackArray; @@ -301,12 +301,12 @@ private: std::vector> _beforeCleanupHookArray; std::vector> _afterCleanupHookArray; - Object * _globalObj = nullptr; + Object *_globalObj = nullptr; Value _gcFuncValue; Object *_gcFunc{nullptr}; - JSVM_Env _env = nullptr; - JSVM_VM _vm = nullptr; + JSVM_Env _env = nullptr; + JSVM_VM _vm = nullptr; JSVM_VMScope _vmScope = nullptr; JSVM_EnvScope _envScope = nullptr; ExceptionCallback _exceptionCallback; @@ -316,7 +316,7 @@ private: bool _isInCleanup{false}; bool _isErrorHandleWorking{false}; bool _isneedCallConstructor{true}; - + bool _isWaitForConnect{false}; uint32_t _debuggerServerPort{0}; ccstd::string _debuggerServerAddr; diff --git a/native/cocos/bindings/jswrapper/jsvm/Utils.cpp b/native/cocos/bindings/jswrapper/jsvm/Utils.cpp index 0efb51b586..b19edea446 100644 --- a/native/cocos/bindings/jswrapper/jsvm/Utils.cpp +++ b/native/cocos/bindings/jswrapper/jsvm/Utils.cpp @@ -24,9 +24,9 @@ ****************************************************************************/ #include "Utils.h" +#include "Class.h" #include "CommonHeader.h" #include "ScriptEngine.h" -#include "Class.h" #define MAX_STRING_LENS 1024 @@ -35,20 +35,20 @@ namespace internal { void jsToSeValue(const target_value& value, Value* v) { assert(v != nullptr); auto env = ScriptEngine::getEnv(); - JSVM_Status status; + JSVM_Status status; JSVM_ValueType valType; - int64_t iRet = 0; - double dRet = 0.0; - bool bRet = false; - bool lossless = false; - size_t len = 0; - void* privateObjPtr = nullptr; - void* nativePtr = nullptr; - Object* obj = nullptr; + int64_t iRet = 0; + double dRet = 0.0; + bool bRet = false; + bool lossless = false; + size_t len = 0; + void* privateObjPtr = nullptr; + void* nativePtr = nullptr; + Object* obj = nullptr; if (!value) { valType = JSVM_ValueType::JSVM_UNDEFINED; - }else { + } else { NODE_API_CALL(status, env, OH_JSVM_Typeof(env, value, &valType)); } @@ -106,7 +106,7 @@ void jsToSeValue(const target_value& value, Value* v) { obj = reinterpret_cast(privateObjPtr); obj->incRef(); } - + if (obj == nullptr) { obj = Object::_createJSObject(env, value, nullptr); } @@ -141,7 +141,7 @@ bool seToJsValue(const Value& v, target_value* outJsVal) { NODE_API_CALL(status, env, OH_JSVM_CreateDouble(env, v.toDouble(), outJsVal)); ret = (status == JSVM_OK); break; - case Value::Type::String: + case Value::Type::String: NODE_API_CALL(status, env, OH_JSVM_CreateStringUtf8(env, v.toString().c_str(), v.toString().length(), outJsVal)); ret = (status == JSVM_OK); break; @@ -151,7 +151,7 @@ bool seToJsValue(const Value& v, target_value* outJsVal) { break; case Value::Type::Object: *outJsVal = v.toObject()->_getJSObject(); - ret = (outJsVal != nullptr); + ret = (outJsVal != nullptr); break; case Value::Type::Null: NODE_API_CALL(status, env, OH_JSVM_GetNull(env, outJsVal)); @@ -199,7 +199,7 @@ bool setReturnValue(const Value& data, target_value& argv) { return seToJsValue(data, &argv); } -std::string jsToString(const target_value &value) { +std::string jsToString(const target_value& value) { se::Value seValue; internal::jsToSeValue(value, &seValue); if (seValue.isString()) { @@ -209,7 +209,7 @@ std::string jsToString(const target_value &value) { } } -void logJsException(JSVM_Env env, const char *file, int line) { +void logJsException(JSVM_Env env, const char* file, int line) { bool isPending = false; JSVM_CALL_RETURN_VOID(OH_JSVM_IsExceptionPending(env, &isPending)); if (!isPending) { @@ -232,11 +232,12 @@ void logJsException(JSVM_Env env, const char *file, int line) { std::string stackStr = jsToString(stack); std::string messageStr = jsToString(message); - CC_LOG_ERROR("JS exception occurred at %s:%d\n\ + CC_LOG_ERROR( + "JS exception occurred at %s:%d\n\ [name]: %s\n\ [message]: %s\n\ [stack]: %s", - file, line, nameStr.c_str(), messageStr.c_str(), stackStr.c_str()); + file, line, nameStr.c_str(), messageStr.c_str(), stackStr.c_str()); auto exceptionCallback = ScriptEngine::getInstance()->getExceptionCallback(); exceptionCallback("", messageStr.c_str(), stackStr.c_str()); } diff --git a/native/cocos/bindings/jswrapper/jsvm/Utils.h b/native/cocos/bindings/jswrapper/jsvm/Utils.h index 73ddb4b104..84f753b5ed 100644 --- a/native/cocos/bindings/jswrapper/jsvm/Utils.h +++ b/native/cocos/bindings/jswrapper/jsvm/Utils.h @@ -33,7 +33,7 @@ namespace internal { using target_value = JSVM_Value; struct PrivateData { - void * data; + void *data; Object *seObj; }; diff --git a/native/cocos/bindings/jswrapper/napi/Class.cpp b/native/cocos/bindings/jswrapper/napi/Class.cpp index fe9ad54698..786f835872 100644 --- a/native/cocos/bindings/jswrapper/napi/Class.cpp +++ b/native/cocos/bindings/jswrapper/napi/Class.cpp @@ -51,7 +51,7 @@ Class *Class::create(const std::string &clsName, se::Object *parent, Object *par return cls; } -Class* Class::create(const std::initializer_list &classPath, se::Object *parent, Object *parentProto, napi_callback ctor) { +Class *Class::create(const std::initializer_list &classPath, se::Object *parent, Object *parentProto, napi_callback ctor) { se::AutoHandleScope scope; se::Object *currentParent = parent; se::Value tmp; @@ -64,7 +64,7 @@ Class* Class::create(const std::initializer_list &classPath, se::O } bool Class::init(const std::string &clsName, Object *parent, Object *parentProto, napi_callback ctor) { - _name = clsName; + _name = clsName; _parent = parent; if (_parent != nullptr) _parent->incRef(); @@ -86,7 +86,7 @@ napi_value Class::_defaultCtor(napi_env env, napi_callback_info info) { return _this; } -void Class::defineProperty(const char* name, napi_callback g, napi_callback s) { +void Class::defineProperty(const char *name, napi_callback g, napi_callback s) { _properties.push_back({name, nullptr, nullptr, g, s, 0, napi_default_jsproperty, 0}); } @@ -96,8 +96,8 @@ void Class::defineProperty(const std::initializer_list &names, nap } } -void Class::defineStaticProperty(const char* name, napi_callback g, napi_callback s) { - if(g != nullptr && s != nullptr) +void Class::defineStaticProperty(const char *name, napi_callback g, napi_callback s) { + if (g != nullptr && s != nullptr) _properties.push_back({name, nullptr, nullptr, g, s, 0, napi_static, 0}); } @@ -109,12 +109,12 @@ bool Class::defineStaticProperty(const char *name, const Value &v, PropertyAttri return true; } -void Class::defineFunction(const char* name, napi_callback func) { - // When Napi defines a function, it needs to add the enum attribute, otherwise JS cannot traverse the function +void Class::defineFunction(const char *name, napi_callback func) { + // When Napi defines a function, it needs to add the enum attribute, otherwise JS cannot traverse the function _properties.push_back({name, nullptr, func, nullptr, nullptr, nullptr, napi_default_jsproperty, nullptr}); } -void Class::defineStaticFunction(const char* name, napi_callback func) { +void Class::defineStaticFunction(const char *name, napi_callback func) { _properties.push_back({name, nullptr, func, nullptr, nullptr, 0, napi_static, 0}); } @@ -128,7 +128,7 @@ napi_finalize Class::_getFinalizeFunction() const { } void Class::install() { - napi_value cons; + napi_value cons; napi_status status; NODE_API_CALL(status, ScriptEngine::getEnv(), napi_define_class(ScriptEngine::getEnv(), _name.c_str(), -1, _ctorFunc, nullptr, _properties.size(), _properties.data(), &cons)); if (_parentProto) { @@ -172,7 +172,7 @@ napi_status Class::inherit(napi_env env, napi_value subclass, napi_value superPr return napi_ok; } argv[1] = superProto; - status = napi_call_function(env, objectClass, setProto, 2, argv, &callbackResult); + status = napi_call_function(env, objectClass, setProto, 2, argv, &callbackResult); if (status != napi_ok) { LOGE("ace zbclog napi_call_function setProto 1 %{public}d", status); return napi_ok; @@ -191,7 +191,7 @@ napi_value Class::_createJSObjectWithClass(Class *cls) { return nullptr; } se::ScriptEngine::getInstance()->_setNeedCallConstructor(false); - NODE_API_CALL(status, ScriptEngine::getEnv(), napi_new_instance( ScriptEngine::getEnv(), clsCtor, 0, nullptr, &obj)); + NODE_API_CALL(status, ScriptEngine::getEnv(), napi_new_instance(ScriptEngine::getEnv(), clsCtor, 0, nullptr, &obj)); se::ScriptEngine::getInstance()->_setNeedCallConstructor(true); return obj; } @@ -207,7 +207,7 @@ napi_ref Class::_getCtorRef() const { napi_value Class::_getCtorFunc() const { assert(_constructor); - napi_value result = nullptr; + napi_value result = nullptr; napi_status status; NODE_API_CALL(status, ScriptEngine::getEnv(), napi_get_reference_value(ScriptEngine::getEnv(), _constructor, &result)); return result; diff --git a/native/cocos/bindings/jswrapper/napi/Class.h b/native/cocos/bindings/jswrapper/napi/Class.h index d038e02d7e..66868bef28 100644 --- a/native/cocos/bindings/jswrapper/napi/Class.h +++ b/native/cocos/bindings/jswrapper/napi/Class.h @@ -25,9 +25,9 @@ #pragma once #include +#include "../Define.h" #include "CommonHeader.h" #include "Object.h" -#include "../Define.h" #include "base/std/optional.h" namespace se { @@ -36,27 +36,26 @@ public: static Class *create(const std::string &clsName, se::Object *parent, Object *parentProto, napi_callback ctor = nullptr); static Class *create(const std::initializer_list &classPath, se::Object *parent, Object *parentProto, napi_callback ctor = nullptr); - void defineFunction(const char* name, napi_callback func); - void defineProperty(const char* name, napi_callback g, napi_callback s); - void defineProperty(const std::initializer_list &names, napi_callback g, napi_callback s); + void defineFunction(const char *name, napi_callback func); + void defineProperty(const char *name, napi_callback g, napi_callback s); + void defineProperty(const std::initializer_list &names, napi_callback g, napi_callback s); - void defineStaticFunction(const char* name, napi_callback func); - void defineStaticProperty(const char* name, napi_callback g, napi_callback s); - bool defineStaticProperty(const char *name, const Value &value, PropertyAttribute attribute = PropertyAttribute::NONE); + void defineStaticFunction(const char *name, napi_callback func); + void defineStaticProperty(const char *name, napi_callback g, napi_callback s); + bool defineStaticProperty(const char *name, const Value &value, PropertyAttribute attribute = PropertyAttribute::NONE); - static napi_value _createJSObjectWithClass(Class *cls); - - void defineFinalizeFunction(napi_finalize func); + static napi_value _createJSObjectWithClass(Class *cls); + + void defineFinalizeFunction(napi_finalize func); napi_finalize _getFinalizeFunction() const; - - - Object * getProto() const; - void install(); - napi_status inherit(napi_env env, napi_value subclass, napi_value superclass); - napi_ref _getCtorRef() const; - napi_value _getCtorFunc() const; - const char * getName() const { return _name.c_str(); } - static void setExports(napi_value *expPtr) { _exports = expPtr; } + + Object *getProto() const; + void install(); + napi_status inherit(napi_env env, napi_value subclass, napi_value superclass); + napi_ref _getCtorRef() const; + napi_value _getCtorFunc() const; + const char *getName() const { return _name.c_str(); } + static void setExports(napi_value *expPtr) { _exports = expPtr; } static void cleanup(); // Private API used in wrapper void _setCtor(Object *obj); // NOLINT(readability-identifier-naming) @@ -64,20 +63,20 @@ public: private: Class(); ~Class(); - bool init(const std::string &clsName, Object *parent, Object *parentProto, napi_callback ctor = nullptr); - void destroy(); + bool init(const std::string &clsName, Object *parent, Object *parentProto, napi_callback ctor = nullptr); + void destroy(); static napi_value _defaultCtor(napi_env env, napi_callback_info info); private: - ccstd::optional _ctor; - static napi_value * _exports; - std::string _name; - Object * _parent = nullptr; - Object * _proto = nullptr; - Object * _parentProto = nullptr; - napi_callback _ctorFunc = Class::_defaultCtor; - napi_ref _constructor = nullptr; + ccstd::optional _ctor; + static napi_value *_exports; + std::string _name; + Object *_parent = nullptr; + Object *_proto = nullptr; + Object *_parentProto = nullptr; + napi_callback _ctorFunc = Class::_defaultCtor; + napi_ref _constructor = nullptr; std::vector _properties; - napi_finalize _finalizeFunc = nullptr; + napi_finalize _finalizeFunc = nullptr; }; }; // namespace se \ No newline at end of file diff --git a/native/cocos/bindings/jswrapper/napi/CommonHeader.h b/native/cocos/bindings/jswrapper/napi/CommonHeader.h index 60fb084ed5..e7cdb83689 100644 --- a/native/cocos/bindings/jswrapper/napi/CommonHeader.h +++ b/native/cocos/bindings/jswrapper/napi/CommonHeader.h @@ -64,10 +64,10 @@ #define DECLARE_NODE_API_GETTER(name, func) \ { (name), nullptr, nullptr, (func), nullptr, nullptr, napi_default, nullptr } -void add_returned_status(napi_env env, +void add_returned_status(napi_env env, const char* key, - napi_value object, - char* expected_message, + napi_value object, + char* expected_message, napi_status expected_status, napi_status actual_status); diff --git a/native/cocos/bindings/jswrapper/napi/HelperMacros.h b/native/cocos/bindings/jswrapper/napi/HelperMacros.h index 87a2eebc35..b441fbcfc2 100644 --- a/native/cocos/bindings/jswrapper/napi/HelperMacros.h +++ b/native/cocos/bindings/jswrapper/napi/HelperMacros.h @@ -30,10 +30,10 @@ #include #ifndef LOGI - #define LOGI(...) ((void) OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) - #define LOGW(...) ((void) OH_LOG_Print(LOG_APP, LOG_WARN, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) - #define LOGE(...) ((void) OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) - #define LOGD(...) ((void) OH_LOG_Print(LOG_APP, LOG_DEBUG, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) + #define LOGI(...) ((void)OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) + #define LOGW(...) ((void)OH_LOG_Print(LOG_APP, LOG_WARN, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) + #define LOGE(...) ((void)OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) + #define LOGD(...) ((void)OH_LOG_Print(LOG_APP, LOG_DEBUG, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__)) #endif #else #define LOGI @@ -91,17 +91,17 @@ constexpr inline T *SE_THIS_OBJECT(STATE &s) { // NOLINT(readability-identifier- #define SE_QUOTEME(x) SE_QUOTEME_(x) #define SE_REPORT_ERROR(fmt, ...) SE_LOGE("[ERROR] (" __FILE__ ", " SE_QUOTEME(__LINE__) "): " fmt "\n", ##__VA_ARGS__) -#define SE_BIND_PROP_GET_IMPL(funcName, postFix) \ - napi_value funcName##postFix##Registry(napi_env env, napi_callback_info info) { \ - return jsbGetterWrapper(env, info, funcName, #funcName); \ +#define SE_BIND_PROP_GET_IMPL(funcName, postFix) \ + napi_value funcName##postFix##Registry(napi_env env, napi_callback_info info) { \ + return jsbGetterWrapper(env, info, funcName, #funcName); \ } #define SE_BIND_PROP_GET(funcName) SE_BIND_PROP_GET_IMPL(funcName, ) #define SE_BIND_FUNC_AS_PROP_GET(funcName) SE_BIND_PROP_GET_IMPL(funcName, _asGetter) -#define SE_BIND_PROP_SET_IMPL(funcName, postFix) \ - napi_value funcName##postFix##Registry(napi_env env, napi_callback_info info) { \ - return jsbSetterWrapper(env, info, funcName, #funcName); \ +#define SE_BIND_PROP_SET_IMPL(funcName, postFix) \ + napi_value funcName##postFix##Registry(napi_env env, napi_callback_info info) { \ + return jsbSetterWrapper(env, info, funcName, #funcName); \ } #define SE_BIND_PROP_SET(funcName) SE_BIND_PROP_SET_IMPL(funcName, ) @@ -110,10 +110,10 @@ constexpr inline T *SE_THIS_OBJECT(STATE &s) { // NOLINT(readability-identifier- #define SE_DECLARE_FUNC(funcName) \ napi_value funcName##Registry(napi_env env, napi_callback_info info) -#define SE_BIND_FUNC(funcName) \ - napi_value funcName##Registry( \ - napi_env env, napi_callback_info info) { \ - return jsbFunctionWrapper(env, info, funcName, #funcName); \ +#define SE_BIND_FUNC(funcName) \ + napi_value funcName##Registry( \ + napi_env env, napi_callback_info info) { \ + return jsbFunctionWrapper(env, info, funcName, #funcName); \ } #define SE_BIND_FUNC_FAST(funcName) \ @@ -130,10 +130,10 @@ constexpr inline T *SE_THIS_OBJECT(STATE &s) { // NOLINT(readability-identifier- return nullptr; \ } -#define SE_BIND_CTOR(funcName, cls, finalizeCb) \ - napi_value funcName##Registry( \ - napi_env env, napi_callback_info info) { \ - return jsbConstructorWrapper(env, info, funcName, _SE(finalizeCb), cls, #funcName); \ +#define SE_BIND_CTOR(funcName, cls, finalizeCb) \ + napi_value funcName##Registry( \ + napi_env env, napi_callback_info info) { \ + return jsbConstructorWrapper(env, info, funcName, _SE(finalizeCb), cls, #funcName); \ } #define SE_BIND_SUB_CLS_CTOR SE_BIND_CTOR @@ -142,12 +142,11 @@ constexpr inline T *SE_THIS_OBJECT(STATE &s) { // NOLINT(readability-identifier- void funcName##Registry( \ napi_env env, void *nativeObject, void * /*finalize_hint*/); -#define SE_BIND_FINALIZE_FUNC(funcName) \ - void funcName##Registry( \ - napi_env env, void *nativeObject, void *hint /*finalize_hint*/) { \ - if (nativeObject == nullptr) { \ - return; \ - } \ - jsbFinalizeWrapper(nativeObject, funcName, #funcName); \ +#define SE_BIND_FINALIZE_FUNC(funcName) \ + void funcName##Registry( \ + napi_env env, void *nativeObject, void *hint /*finalize_hint*/) { \ + if (nativeObject == nullptr) { \ + return; \ + } \ + jsbFinalizeWrapper(nativeObject, funcName, #funcName); \ } - diff --git a/native/cocos/bindings/jswrapper/napi/Object.cpp b/native/cocos/bindings/jswrapper/napi/Object.cpp index 4071dac814..4310857c0a 100644 --- a/native/cocos/bindings/jswrapper/napi/Object.cpp +++ b/native/cocos/bindings/jswrapper/napi/Object.cpp @@ -35,7 +35,7 @@ namespace se { std::unique_ptr> __objectMap; // Currently, the value `void*` is always nullptr -Object::Object(): _objRef(this) {} +Object::Object() : _objRef(this) {} Object::~Object() { if (!_destructInFinalizer && _cls != nullptr) { napi_remove_wrap(_env, _objRef.getValue(_env), nullptr); @@ -738,18 +738,16 @@ void Object::clearPrivateData(bool clearMapping) { } } -ObjectRef::ObjectRef(Object *parent) +ObjectRef::ObjectRef(Object* parent) : _parent(parent) { - } ObjectRef::~ObjectRef() { deleteRef(); } - napi_value ObjectRef::getValue(napi_env env) const { - napi_value result; + napi_value result; napi_status status; NODE_API_CALL(status, env, napi_get_reference_value(env, _ref, &result)); assert(status == napi_ok); @@ -776,7 +774,7 @@ void ObjectRef::deleteRef() { if (!_ref) { return; } - if(!_parent->_destructInFinalizer) { + if (!_parent->_destructInFinalizer) { // Similar to jsvm, please read the comments inside jsvm. napi_reference_ref(_env, _ref, nullptr); } diff --git a/native/cocos/bindings/jswrapper/napi/Object.h b/native/cocos/bindings/jswrapper/napi/Object.h index cb7cba712a..44842623bd 100644 --- a/native/cocos/bindings/jswrapper/napi/Object.h +++ b/native/cocos/bindings/jswrapper/napi/Object.h @@ -25,22 +25,22 @@ #pragma once #include +#include "../PrivateObject.h" #include "../RefCounter.h" #include "../Value.h" #include "../config.h" #include "CommonHeader.h" #include "HelperMacros.h" -#include "../PrivateObject.h" #include "base/std/container/unordered_map.h" namespace se { class Class; class ObjectRef { private: - napi_ref _ref{nullptr}; - napi_env _env{nullptr}; + napi_ref _ref{nullptr}; + napi_env _env{nullptr}; napi_value _obj{nullptr}; - Object* _parent{nullptr}; + Object *_parent{nullptr}; public: ObjectRef(Object *parent); @@ -77,7 +77,7 @@ public: void *contents{nullptr}; size_t byteLength{0}; void *userData{0}; - }; + }; Object(); ~Object(); @@ -192,7 +192,6 @@ public: return static_cast *>(_privateObject)->getData(); } - template inline T *getTypedPrivateData() const { return reinterpret_cast(getPrivateData()); @@ -204,7 +203,6 @@ public: */ void clearPrivateData(bool clearMapping = true); - /** * @brief Sets whether to clear the mapping of native object & se::Object in finalizer */ @@ -415,9 +413,9 @@ public: */ static Object *getObjectWithPtr(void *ptr); - Class * _getClass() const; // NOLINT(readability-identifier-naming) + Class *_getClass() const; // NOLINT(readability-identifier-naming) napi_value _getJSObject() const; - void _setFinalizeCallback(napi_finalize finalizeCb); // NOLINT(readability-identifier-naming) + void _setFinalizeCallback(napi_finalize finalizeCb); // NOLINT(readability-identifier-naming) /** * @brief Returns the string for describing current object. * @return The string for describing current object. @@ -432,16 +430,16 @@ private: static void cleanup(); private: - ObjectRef _objRef; - napi_finalize _finalizeCb = nullptr; + ObjectRef _objRef; + napi_finalize _finalizeCb = nullptr; bool _clearMappingInFinalizer = true; bool _destructInFinalizer = false; void *_privateData = nullptr; PrivateObjectBase *_privateObject = nullptr; - napi_env _env = nullptr; - Class * _cls = nullptr; - uint32_t _rootCount = 0; - bool _onCleaingPrivateData = false; + napi_env _env = nullptr; + Class *_cls = nullptr; + uint32_t _rootCount = 0; + bool _onCleaingPrivateData = false; friend class ObjectRef; friend class ScriptEngine; diff --git a/native/cocos/bindings/jswrapper/napi/ScriptEngine.cpp b/native/cocos/bindings/jswrapper/napi/ScriptEngine.cpp index faecdf7e1c..fd4b36b0ed 100644 --- a/native/cocos/bindings/jswrapper/napi/ScriptEngine.cpp +++ b/native/cocos/bindings/jswrapper/napi/ScriptEngine.cpp @@ -24,12 +24,12 @@ ****************************************************************************/ #include "ScriptEngine.h" +#include #include #include "../MappingUtils.h" #include "Class.h" -#include "Utils.h" #include "CommonHeader.h" -#include +#include "Utils.h" #include "base/std/container/array.h" namespace se { @@ -43,7 +43,7 @@ AutoHandleScope::~AutoHandleScope() { ScriptEngine *gSriptEngineInstance = nullptr; -ScriptEngine::ScriptEngine() {}; +ScriptEngine::ScriptEngine(){}; ScriptEngine::~ScriptEngine() = default; @@ -85,8 +85,8 @@ bool ScriptEngine::runScript(const std::string &path, Value *ret /* = nullptr */ bool ScriptEngine::evalString(const char *scriptStr, ssize_t length, Value *ret, const char *fileName) { napi_status status; - napi_value script; - napi_value result; + napi_value script; + napi_value result; length = length < 0 ? NAPI_AUTO_LENGTH : length; status = napi_create_string_utf8(ScriptEngine::getEnv(), scriptStr, length, &script); LOGI("eval :%{public}s", scriptStr); @@ -96,7 +96,7 @@ bool ScriptEngine::evalString(const char *scriptStr, ssize_t length, Value *ret, bool ScriptEngine::init() { napi_status status; - napi_value result; + napi_value result; for (const auto &hook : _beforeInitHookArray) { hook(); @@ -171,7 +171,7 @@ void ScriptEngine::cleanup() { garbageCollect(); _globalObj = nullptr; - _isValid = false; + _isValid = false; _registerCallbackArray.clear(); diff --git a/native/cocos/bindings/jswrapper/napi/ScriptEngine.h b/native/cocos/bindings/jswrapper/napi/ScriptEngine.h index 35835ffb43..145ebea75d 100644 --- a/native/cocos/bindings/jswrapper/napi/ScriptEngine.h +++ b/native/cocos/bindings/jswrapper/napi/ScriptEngine.h @@ -35,7 +35,7 @@ using HandleScope = napi_handle_scope; namespace se { class AutoHandleScope { public: - // This interface needs to be implemented in NAPI, similar to V8. + // This interface needs to be implemented in NAPI, similar to V8. // Ref:https://nodejs.org/docs/latest-v17.x/api/n-api.html#object-lifetime-management AutoHandleScope(); ~AutoHandleScope(); @@ -43,7 +43,7 @@ public: private: HandleScope _handleScope; }; -using RegisterCallback = bool (*)(Object *); +using RegisterCallback = bool (*)(Object *); using ExceptionCallback = std::function; // location, message, stack class ScriptEngine { @@ -197,7 +197,7 @@ public: Object *getGlobalObject() const; static napi_env getEnv(); - static void setEnv(napi_env env); + static void setEnv(napi_env env); /** * @brief Adds a callback for registering a native binding module. @@ -263,12 +263,12 @@ public: */ void throwException(const std::string &errorMessage); - /** + /** * @brief for napi_new_instance, skip constructor. */ void _setNeedCallConstructor(bool need); - /** + /** * @brief for napi_new_instance, skip constructor. */ bool _needCallConstructor(); @@ -283,7 +283,7 @@ public: void handlePromiseExceptions(); private: - FileOperationDelegate _fileOperationDelegate; + FileOperationDelegate _fileOperationDelegate; std::vector _registerCallbackArray; std::vector _permRegisterCallbackArray; @@ -292,8 +292,8 @@ private: std::vector> _beforeCleanupHookArray; std::vector> _afterCleanupHookArray; - Object * _globalObj = nullptr; - napi_env _env = nullptr; + Object *_globalObj = nullptr; + napi_env _env = nullptr; bool _isValid{false}; bool _isGarbageCollecting{false}; diff --git a/native/cocos/bindings/jswrapper/napi/Utils.cpp b/native/cocos/bindings/jswrapper/napi/Utils.cpp index 31b9d469d9..a0ea09eb1d 100644 --- a/native/cocos/bindings/jswrapper/napi/Utils.cpp +++ b/native/cocos/bindings/jswrapper/napi/Utils.cpp @@ -24,9 +24,9 @@ ****************************************************************************/ #include "Utils.h" +#include "Class.h" #include "CommonHeader.h" #include "ScriptEngine.h" -#include "Class.h" #define MAX_STRING_LENS 1024 @@ -34,20 +34,20 @@ namespace se { namespace internal { void jsToSeValue(const target_value& value, Value* v) { assert(v != nullptr); - napi_status status; + napi_status status; napi_valuetype valType; - int64_t iRet = 0; - double dRet = 0.0; - bool bRet = false; - bool lossless = false; - size_t len = 0; - void* privateObjPtr = nullptr; - void* nativePtr = nullptr; - Object* obj = nullptr; + int64_t iRet = 0; + double dRet = 0.0; + bool bRet = false; + bool lossless = false; + size_t len = 0; + void* privateObjPtr = nullptr; + void* nativePtr = nullptr; + Object* obj = nullptr; if (!value) { valType = napi_valuetype::napi_undefined; - }else { + } else { NODE_API_CALL(status, ScriptEngine::getEnv(), napi_typeof(ScriptEngine::getEnv(), value, &valType)); } @@ -132,7 +132,7 @@ void jsToSeArgs(size_t argc, target_value* argv, ValueArray* outArr) { bool seToJsValue(const Value& v, target_value* outJsVal) { assert(outJsVal != nullptr); - bool ret = false; + bool ret = false; napi_status status = napi_ok; switch (v.getType()) { case Value::Type::Number: @@ -149,7 +149,7 @@ bool seToJsValue(const Value& v, target_value* outJsVal) { break; case Value::Type::Object: *outJsVal = v.toObject()->_getJSObject(); - ret = (outJsVal != nullptr); + ret = (outJsVal != nullptr); break; case Value::Type::Null: NODE_API_CALL(status, ScriptEngine::getEnv(), napi_get_null(ScriptEngine::getEnv(), outJsVal)); diff --git a/native/cocos/bindings/jswrapper/napi/Utils.h b/native/cocos/bindings/jswrapper/napi/Utils.h index 45e7bb616e..24e49194dd 100644 --- a/native/cocos/bindings/jswrapper/napi/Utils.h +++ b/native/cocos/bindings/jswrapper/napi/Utils.h @@ -33,7 +33,7 @@ namespace internal { using target_value = napi_value; struct PrivateData { - void * data; + void *data; Object *seObj; }; diff --git a/native/cocos/bindings/jswrapper/napi/native_common.h b/native/cocos/bindings/jswrapper/napi/native_common.h index c1633d2f23..c774a3a093 100644 --- a/native/cocos/bindings/jswrapper/napi/native_common.h +++ b/native/cocos/bindings/jswrapper/napi/native_common.h @@ -25,91 +25,91 @@ #pragma once #ifndef FOUNDATION_ACE_NAPI_INTERFACES_KITS_NAPI_NATIVE_COMMON_H -#define FOUNDATION_ACE_NAPI_INTERFACES_KITS_NAPI_NATIVE_COMMON_H + #define FOUNDATION_ACE_NAPI_INTERFACES_KITS_NAPI_NATIVE_COMMON_H -#define DEPRECATED __attribute__((__deprecated__)) + #define DEPRECATED __attribute__((__deprecated__)) -#ifndef NAPI_VERSION -#define NAPI_VERSION 8 -#endif + #ifndef NAPI_VERSION + #define NAPI_VERSION 8 + #endif -#define NAPI_RETVAL_NOTHING + #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 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_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(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_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_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(env, theCall) NAPI_CALL_BASE(env, theCall, nullptr) -#define NAPI_CALL_RETURN_VOID(env, theCall) NAPI_CALL_BASE(env, theCall, NAPI_RETVAL_NOTHING) + #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_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_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(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_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_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_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_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 \ - } + #define DECLARE_NAPI_GETTER_SETTER(name, getter, setter) \ + { \ + (name), nullptr, nullptr, (getter), (setter), nullptr, napi_default, nullptr \ + } #endif /* FOUNDATION_ACE_NAPI_INTERFACES_KITS_NAPI_NATIVE_COMMON_H */ diff --git a/native/cocos/bindings/jswrapper/v8/HelperMacros.h b/native/cocos/bindings/jswrapper/v8/HelperMacros.h index 4a625133ff..70b0027546 100644 --- a/native/cocos/bindings/jswrapper/v8/HelperMacros.h +++ b/native/cocos/bindings/jswrapper/v8/HelperMacros.h @@ -25,7 +25,6 @@ #pragma once -#include "v8.h" #include #include #include @@ -36,6 +35,7 @@ #include "base/Log.h" #include "base/Macros.h" #include "base/std/container/string.h" +#include "v8.h" // #define RECORD_JSB_INVOKING diff --git a/native/cocos/bindings/jswrapper/v8/Object.cpp b/native/cocos/bindings/jswrapper/v8/Object.cpp index 3364e9fc87..28a8357e3c 100644 --- a/native/cocos/bindings/jswrapper/v8/Object.cpp +++ b/native/cocos/bindings/jswrapper/v8/Object.cpp @@ -24,8 +24,8 @@ ****************************************************************************/ #include "Object.h" -#include "v8/HelperMacros.h" #include "application/ApplicationManager.h" +#include "v8/HelperMacros.h" // Use node::Buffer to replace v8 api,to avoid link err in editor platform. #if CC_EDITOR && CC_PLATFORM == CC_PLATFORM_WINDOWS @@ -164,7 +164,7 @@ Object *Object::createPlainObject() { return obj; } -std::unordered_map*> Object::resolverMap; +std::unordered_map *> Object::resolverMap; void Object::resolverPromise(Object *object, const Value &value) { auto it = resolverMap.find(object); @@ -172,7 +172,7 @@ void Object::resolverPromise(Object *object, const Value &value) { v8::Isolate *isolate = __isolate; v8::HandleScope scope(isolate); v8::Local context = isolate->GetCurrentContext(); - auto* resolver = it->second; + auto *resolver = it->second; v8::Local v8Val; se::internal::seToJsValue(__isolate, value, &v8Val); resolver->Get(isolate)->Resolve(context, v8Val).ToChecked(); @@ -188,7 +188,7 @@ void Object::rejectPromise(Object *object, const Value &value) { v8::Isolate *isolate = __isolate; v8::HandleScope scope(isolate); v8::Local context = isolate->GetCurrentContext(); - auto* resolver = it->second; + auto *resolver = it->second; v8::Local v8Val; se::internal::seToJsValue(isolate, value, &v8Val); resolver->Get(isolate)->Reject(context, v8Val).ToChecked(); diff --git a/native/cocos/bindings/jswrapper/v8/Object.h b/native/cocos/bindings/jswrapper/v8/Object.h index 56934fa514..9ed8583147 100644 --- a/native/cocos/bindings/jswrapper/v8/Object.h +++ b/native/cocos/bindings/jswrapper/v8/Object.h @@ -708,7 +708,7 @@ private: ccstd::string _objectCreationStackFrame; #endif - static std::unordered_map*> resolverMap; + static std::unordered_map *> resolverMap; friend class ScriptEngine; friend class JSBPersistentHandleVisitor; diff --git a/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp b/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp index 4016a17231..dc5e76595e 100644 --- a/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp +++ b/native/cocos/bindings/jswrapper/v8/ScriptEngine.cpp @@ -480,7 +480,7 @@ void ScriptEngine::cleanup() { hook(); } _beforeCleanupHookArray.clear(); - + // Clear unhandled promises _unhandledPromises.clear(); _ignoreUnhandledPromises = false; diff --git a/native/cocos/bindings/jswrapper/v8/Utils.cpp b/native/cocos/bindings/jswrapper/v8/Utils.cpp index a2f7cd4f82..b6f7058818 100644 --- a/native/cocos/bindings/jswrapper/v8/Utils.cpp +++ b/native/cocos/bindings/jswrapper/v8/Utils.cpp @@ -248,8 +248,8 @@ ExternalStringResource::ExternalStringResource(std::u16string &&s) : _s(std::move(s)) { } -const uint16_t* ExternalStringResource::data() const { - return reinterpret_cast(_s.data()); +const uint16_t *ExternalStringResource::data() const { + return reinterpret_cast(_s.data()); } size_t ExternalStringResource::length() const { diff --git a/native/cocos/bindings/jswrapper/v8/Utils.h b/native/cocos/bindings/jswrapper/v8/Utils.h index 3528057be4..a5c9a95318 100644 --- a/native/cocos/bindings/jswrapper/v8/Utils.h +++ b/native/cocos/bindings/jswrapper/v8/Utils.h @@ -54,8 +54,8 @@ class ExternalStringResource : public v8::String::ExternalStringResource { public: explicit ExternalStringResource(std::u16string &&s); ~ExternalStringResource() override = default; - - const uint16_t* data() const override; + + const uint16_t *data() const override; size_t length() const override; void Dispose() override; diff --git a/native/cocos/bindings/jswrapper/v8/debugger/SHA1.cpp b/native/cocos/bindings/jswrapper/v8/debugger/SHA1.cpp index 29186312bd..1e97003a4c 100644 --- a/native/cocos/bindings/jswrapper/v8/debugger/SHA1.cpp +++ b/native/cocos/bindings/jswrapper/v8/debugger/SHA1.cpp @@ -10,8 +10,8 @@ #if (SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8) && SE_ENABLE_INSPECTOR - #include #include + #include #if defined(_MSC_VER) #include diff --git a/native/cocos/bindings/jswrapper/v8/debugger/inspector_agent.cpp b/native/cocos/bindings/jswrapper/v8/debugger/inspector_agent.cpp index 6f06a12853..f284e97d1c 100644 --- a/native/cocos/bindings/jswrapper/v8/debugger/inspector_agent.cpp +++ b/native/cocos/bindings/jswrapper/v8/debugger/inspector_agent.cpp @@ -391,11 +391,11 @@ public: explicit ChannelImpl(V8Inspector *inspector, InspectorSessionDelegate *delegate) : delegate_(delegate) { -#if V8_MAJOR_VERSION > 10 || (V8_MAJOR_VERSION == 10 && V8_MINOR_VERSION > 3) + #if V8_MAJOR_VERSION > 10 || (V8_MAJOR_VERSION == 10 && V8_MINOR_VERSION > 3) session_ = inspector->connect(1, this, StringView(), v8_inspector::V8Inspector::ClientTrustLevel::kFullyTrusted); -#else + #else session_ = inspector->connect(1, this, StringView()); -#endif + #endif } virtual ~ChannelImpl() {} diff --git a/native/cocos/bindings/jswrapper/v8/debugger/inspector_io.cpp b/native/cocos/bindings/jswrapper/v8/debugger/inspector_io.cpp index bb60666492..490f70b7af 100644 --- a/native/cocos/bindings/jswrapper/v8/debugger/inspector_io.cpp +++ b/native/cocos/bindings/jswrapper/v8/debugger/inspector_io.cpp @@ -1,13 +1,13 @@ #include "inspector_io.h" #if (SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8) && SE_ENABLE_INSPECTOR - #include "inspector_socket_server.h" #include "env.h" + #include "inspector_socket_server.h" #include "node.h" //cjh #include "node_crypto.h" #include "node_mutex.h" - #include "v8-inspector.h" #include "util.h" + #include "v8-inspector.h" #include "zlib.h" #include "libplatform/libplatform.h" diff --git a/native/cocos/bindings/jswrapper/v8/debugger/inspector_io.h b/native/cocos/bindings/jswrapper/v8/debugger/inspector_io.h index 62ac03169e..5d492f77d1 100644 --- a/native/cocos/bindings/jswrapper/v8/debugger/inspector_io.h +++ b/native/cocos/bindings/jswrapper/v8/debugger/inspector_io.h @@ -9,9 +9,9 @@ #include "node_mutex.h" #include "uv.h" + #include #include #include - #include #if !HAVE_INSPECTOR #error("This header can only be used when inspector is enabled") diff --git a/native/cocos/bindings/jswrapper/v8/debugger/util-inl.h b/native/cocos/bindings/jswrapper/v8/debugger/util-inl.h index c52c738d65..5302fa595b 100644 --- a/native/cocos/bindings/jswrapper/v8/debugger/util-inl.h +++ b/native/cocos/bindings/jswrapper/v8/debugger/util-inl.h @@ -28,8 +28,8 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS - #include "util.h" #include + #include "util.h" #if defined(_MSC_VER) #include diff --git a/native/cocos/bindings/jswrapper/v8/debugger/util.h b/native/cocos/bindings/jswrapper/v8/debugger/util.h index 89870336d3..d001f88d9b 100644 --- a/native/cocos/bindings/jswrapper/v8/debugger/util.h +++ b/native/cocos/bindings/jswrapper/v8/debugger/util.h @@ -316,7 +316,8 @@ public: // Current maximum capacity of the buffer with which SetLength() can be used // without first calling AllocateSufficientStorage(). size_t capacity() const { - return IsAllocated() ? capacity_ : IsInvalidated() ? 0 : kStackStorageSize; + return IsAllocated() ? capacity_ : IsInvalidated() ? 0 + : kStackStorageSize; } // Make sure enough space for `storage` entries is available. diff --git a/native/cocos/bindings/manual/Box2dCallbacks.cpp b/native/cocos/bindings/manual/Box2dCallbacks.cpp index 4b8b01d3c3..8d8df8874d 100644 --- a/native/cocos/bindings/manual/Box2dCallbacks.cpp +++ b/native/cocos/bindings/manual/Box2dCallbacks.cpp @@ -2,44 +2,44 @@ #include "bindings/auto/jsb_box2d_auto.h" #include "bindings/manual/jsb_global.h" -#define GET_THIS() \ -do {\ - if (_thisObject != nullptr) { \ - _thisObject->decRef(); \ - } \ - _thisObject = thisObject; \ - _thisObject->incRef(); \ -} while(0) +#define GET_THIS() \ + do { \ + if (_thisObject != nullptr) { \ + _thisObject->decRef(); \ + } \ + _thisObject = thisObject; \ + _thisObject->incRef(); \ + } while (0) -#define GET_JS_PROPERTY(name) \ -do {\ - if (_cb##name != nullptr) { \ - _cb##name->decRef(); \ - _cb##name = nullptr; \ - } \ - se::Value callbackVal; \ - bool ok = thisObject->getProperty(#name, &callbackVal); \ - CC_ASSERT(ok && callbackVal.isObject() && callbackVal.toObject()->isFunction()); \ - se::Object* callbackObj = callbackVal.toObject(); \ - callbackObj->incRef(); \ - _cb##name = callbackObj; \ -} while(0) +#define GET_JS_PROPERTY(name) \ + do { \ + if (_cb##name != nullptr) { \ + _cb##name->decRef(); \ + _cb##name = nullptr; \ + } \ + se::Value callbackVal; \ + bool ok = thisObject->getProperty(#name, &callbackVal); \ + CC_ASSERT(ok&& callbackVal.isObject() && callbackVal.toObject()->isFunction()); \ + se::Object* callbackObj = callbackVal.toObject(); \ + callbackObj->incRef(); \ + _cb##name = callbackObj; \ + } while (0) #define SAFE_RELEASE_CALLBACK(name) \ -do {\ - if (_cb##name != nullptr) { \ - _cb##name->decRef(); \ - _cb##name = nullptr; \ - } \ -} while(0) + do { \ + if (_cb##name != nullptr) { \ + _cb##name->decRef(); \ + _cb##name = nullptr; \ + } \ + } while (0) -#define SAFE_RELEASE_THIS() \ -do { \ - if (_thisObject != nullptr) { \ - _thisObject->decRef(); \ - _thisObject = nullptr; \ - } \ -} while(0) +#define SAFE_RELEASE_THIS() \ + do { \ + if (_thisObject != nullptr) { \ + _thisObject->decRef(); \ + _thisObject = nullptr; \ + } \ + } while (0) JSBQueryCallback::JSBQueryCallback() { _args.resize(1); @@ -50,11 +50,11 @@ JSBQueryCallback::~JSBQueryCallback() { SAFE_RELEASE_CALLBACK(ReportFixture); } -void JSBQueryCallback::initWithThis(se::Object *thisObject) { +void JSBQueryCallback::initWithThis(se::Object* thisObject) { GET_THIS(); GET_JS_PROPERTY(ReportFixture); } - + bool JSBQueryCallback::ReportFixture(b2Fixture* fixture) { se::AutoHandleScope hs; if (_cbReportFixture == nullptr) { @@ -69,17 +69,15 @@ bool JSBQueryCallback::ReportFixture(b2Fixture* fixture) { if (rval.isBoolean()) { return rval.toBoolean(); } - + return false; } - - JSBRayCastCallback::JSBRayCastCallback() { _args.resize(4); } -void JSBRayCastCallback::initWithThis(se::Object *thisObject) { +void JSBRayCastCallback::initWithThis(se::Object* thisObject) { GET_THIS(); GET_JS_PROPERTY(ReportFixture); } @@ -88,14 +86,14 @@ JSBRayCastCallback::~JSBRayCastCallback() { SAFE_RELEASE_THIS(); SAFE_RELEASE_CALLBACK(ReportFixture); } - + float JSBRayCastCallback::ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float fraction) { se::AutoHandleScope hs; - + if (_cbReportFixture == nullptr) { return 0.F; } - + bool ok = nativevalue_to_se(fixture, _args[0]); SE_PRECONDITION2(ok, 0.F, "Error processing arguments"); ok = nativevalue_to_se(point, _args[1]); @@ -110,7 +108,7 @@ float JSBRayCastCallback::ReportFixture(b2Fixture* fixture, const b2Vec2& point, if (rval.isNumber()) { return rval.toFloat(); } - + return 0.F; } @@ -131,7 +129,7 @@ JSBB2Draw::~JSBB2Draw() { SAFE_RELEASE_CALLBACK(DrawPoint); } -void JSBB2Draw::initWithThis(se::Object *thisObject) { +void JSBB2Draw::initWithThis(se::Object* thisObject) { GET_THIS(); GET_JS_PROPERTY(DrawPolygon); GET_JS_PROPERTY(DrawSolidPolygon); @@ -142,7 +140,7 @@ void JSBB2Draw::initWithThis(se::Object *thisObject) { GET_JS_PROPERTY(DrawPoint); } -void JSBB2Draw::DrawPolygonWithCallback(se::Object *cbObj, const b2Vec2* vertices, int32 vertexCount, const b2Color& color) { +void JSBB2Draw::DrawPolygonWithCallback(se::Object* cbObj, const b2Vec2* vertices, int32 vertexCount, const b2Color& color) { if (cbObj == nullptr || vertexCount <= 0 || vertices == nullptr) { return; } @@ -151,7 +149,7 @@ void JSBB2Draw::DrawPolygonWithCallback(se::Object *cbObj, const b2Vec2* vertice ccstd::vector verticeArray; verticeArray.resize(vertexCount); memcpy(verticeArray.data(), vertices, sizeof(b2Vec2) * vertexCount); - + bool ok = nativevalue_to_se(verticeArray, _args3[0]); SE_PRECONDITION2_VOID(ok, "Error processing arguments"); ok = nativevalue_to_se(vertexCount, _args3[1]); @@ -172,7 +170,6 @@ void JSBB2Draw::DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, cons DrawPolygonWithCallback(_cbDrawSolidPolygon, vertices, vertexCount, color); } - /// Draw a circle. void JSBB2Draw::DrawCircle(const b2Vec2& center, float radius, const b2Color& color) { if (_cbDrawCircle == nullptr) { @@ -180,7 +177,7 @@ void JSBB2Draw::DrawCircle(const b2Vec2& center, float radius, const b2Color& co } se::AutoHandleScope hs; - + bool ok = nativevalue_to_se(center, _args3[0]); SE_PRECONDITION2_VOID(ok, "Error processing arguments"); ok = nativevalue_to_se(radius, _args3[1]); @@ -232,7 +229,7 @@ void JSBB2Draw::DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& c /// Draw a transform. Choose your own length scale. /// @param xf a transform. void JSBB2Draw::DrawTransform(const b2Transform& xf) { - if (_cbDrawTransform== nullptr) { + if (_cbDrawTransform == nullptr) { return; } @@ -251,7 +248,7 @@ void JSBB2Draw::DrawPoint(const b2Vec2& p, float size, const b2Color& color) { } se::AutoHandleScope hs; - + bool ok = nativevalue_to_se(p, _args3[0]); SE_PRECONDITION2_VOID(ok, "Error processing arguments"); ok = nativevalue_to_se(size, _args3[1]); @@ -261,8 +258,6 @@ void JSBB2Draw::DrawPoint(const b2Vec2& p, float size, const b2Color& color) { _cbDrawPoint->call(_args3, _thisObject); } - - // b2ContactListener @@ -278,7 +273,7 @@ JSB_b2ContactListener::~JSB_b2ContactListener() { SAFE_RELEASE_CALLBACK(PostSolve); } -void JSB_b2ContactListener::initWithThis(se::Object *thisObject) { +void JSB_b2ContactListener::initWithThis(se::Object* thisObject) { GET_THIS(); GET_JS_PROPERTY(BeginContact); GET_JS_PROPERTY(EndContact); @@ -316,12 +311,12 @@ void JSB_b2ContactListener::PreSolve(b2Contact* contact, const b2Manifold* oldMa bool ok = nativevalue_to_se(contact, _args2[0]); SE_PRECONDITION2_VOID(ok, "Error processing arguments"); - + static b2Manifold gManifold; gManifold = *oldManifold; ok = nativevalue_to_se(gManifold, _args2[1]); SE_PRECONDITION2_VOID(ok, "Error processing arguments"); - + ok = _cbPreSolve->call(_args2, _thisObject); } @@ -333,11 +328,11 @@ void JSB_b2ContactListener::PostSolve(b2Contact* contact, const b2ContactImpulse bool ok = nativevalue_to_se(contact, _args2[0]); SE_PRECONDITION2_VOID(ok, "Error processing arguments"); - + static b2ContactImpulse gImpulse; gImpulse = *impulse; ok = nativevalue_to_se(gImpulse, _args2[1]); SE_PRECONDITION2_VOID(ok, "Error processing arguments"); - + ok = _cbPostSolve->call(_args2, _thisObject); } diff --git a/native/cocos/bindings/manual/Box2dCallbacks.h b/native/cocos/bindings/manual/Box2dCallbacks.h index d4b3a8e4e5..99ba744f84 100644 --- a/native/cocos/bindings/manual/Box2dCallbacks.h +++ b/native/cocos/bindings/manual/Box2dCallbacks.h @@ -1,35 +1,35 @@ #pragma once -#include "box2d/box2d.h" #include "bindings/jswrapper/SeApi.h" +#include "box2d/box2d.h" class JSBQueryCallback : public b2QueryCallback { public: JSBQueryCallback(); ~JSBQueryCallback(); - - void initWithThis(se::Object *thisObject); - + + void initWithThis(se::Object* thisObject); + bool ReportFixture(b2Fixture* fixture) override; - + private: - se::Object *_cbReportFixture{}; - se::Object *_thisObject{}; + se::Object* _cbReportFixture{}; + se::Object* _thisObject{}; se::ValueArray _args; }; -class JSBRayCastCallback : public b2RayCastCallback { +class JSBRayCastCallback : public b2RayCastCallback { public: JSBRayCastCallback(); ~JSBRayCastCallback(); - - void initWithThis(se::Object *thisObject); - + + void initWithThis(se::Object* thisObject); + float ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float fraction) override; - + private: - se::Object *_cbReportFixture{}; - se::Object *_thisObject{}; + se::Object* _cbReportFixture{}; + se::Object* _thisObject{}; se::ValueArray _args; }; @@ -37,11 +37,12 @@ class JSBB2Draw : public b2Draw { public: JSBB2Draw(); ~JSBB2Draw(); - - void initWithThis(se::Object *thisObject); - + + void initWithThis(se::Object* thisObject); + private: - void DrawPolygonWithCallback(se::Object *cbObj, const b2Vec2* vertices, int32 vertexCount, const b2Color& color); + void DrawPolygonWithCallback(se::Object* cbObj, const b2Vec2* vertices, int32 vertexCount, const b2Color& color); + public: /// Draw a closed polygon provided in CCW order. void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) override; @@ -49,13 +50,12 @@ public: /// Draw a solid closed polygon provided in CCW order. void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) override; - /// Draw a circle. void DrawCircle(const b2Vec2& center, float radius, const b2Color& color) override; - + /// Draw a solid circle. void DrawSolidCircle(const b2Vec2& center, float radius, const b2Vec2& axis, const b2Color& color) override; - + /// Draw a line segment. void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) override; @@ -65,30 +65,29 @@ public: /// Draw a point. void DrawPoint(const b2Vec2& p, float size, const b2Color& color) override; - - + /// Set the drawing flags. inline void SetFlags(uint32 flags) { b2Draw::SetFlags(flags); } /// Get the drawing flags. - inline uint32 GetFlags() const { return b2Draw::GetFlags(); }; - + inline uint32 GetFlags() const { return b2Draw::GetFlags(); }; + /// Append flags to the current flags. inline void AppendFlags(uint32 flags) { b2Draw::AppendFlags(flags); } /// Clear flags from the current flags. inline void ClearFlags(uint32 flags) { b2Draw::ClearFlags(flags); } - + private: - se::Object *_cbDrawPolygon{}; - se::Object *_cbDrawSolidPolygon{}; - se::Object *_cbDrawCircle{}; - se::Object *_cbDrawSolidCircle{}; - se::Object *_cbDrawSegment{}; - se::Object *_cbDrawTransform{}; - se::Object *_cbDrawPoint{}; - - se::Object *_thisObject{}; + se::Object* _cbDrawPolygon{}; + se::Object* _cbDrawSolidPolygon{}; + se::Object* _cbDrawCircle{}; + se::Object* _cbDrawSolidCircle{}; + se::Object* _cbDrawSegment{}; + se::Object* _cbDrawTransform{}; + se::Object* _cbDrawPoint{}; + + se::Object* _thisObject{}; se::ValueArray _args1; se::ValueArray _args3; se::ValueArray _args4; @@ -99,19 +98,19 @@ class JSB_b2ContactListener : public b2ContactListener { public: JSB_b2ContactListener(); ~JSB_b2ContactListener(); - - void initWithThis(se::Object *thisObject); + + void initWithThis(se::Object* thisObject); void BeginContact(b2Contact* contact) override; void EndContact(b2Contact* contact) override; void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) override; void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) override; private: - se::Object *_thisObject{}; - se::Object *_cbBeginContact{}; - se::Object *_cbEndContact{}; - se::Object *_cbPreSolve{}; - se::Object *_cbPostSolve{}; + se::Object* _thisObject{}; + se::Object* _cbBeginContact{}; + se::Object* _cbEndContact{}; + se::Object* _cbPreSolve{}; + se::Object* _cbPostSolve{}; se::ValueArray _args1; se::ValueArray _args2; }; diff --git a/native/cocos/bindings/manual/JavaScriptArkTsBridge.cpp b/native/cocos/bindings/manual/JavaScriptArkTsBridge.cpp index 087a68e028..2dba97da8d 100644 --- a/native/cocos/bindings/manual/JavaScriptArkTsBridge.cpp +++ b/native/cocos/bindings/manual/JavaScriptArkTsBridge.cpp @@ -107,13 +107,12 @@ bool JavaScriptArkTsBridge::CallInfo::execute(se::Value& rval) { module_name = pos != std::string::npos ? pathStr.substr(0, pos).c_str() : "entry"; } - char* module_info = __getModuleInfo(module_name); std::promise promise; std::function cb = [&promise](cc::CallbackParamType message) { promise.set_value(message); }; - cc::CallParam *callParam = new cc::CallParam{_isSyn, cb, _paramStr, module_info, _clsPath, method}; + cc::CallParam* callParam = new cc::CallParam{_isSyn, cb, _paramStr, module_info, _clsPath, method}; if (_isSyn) { cc::JSFunction::getFunction("executeMethodSync").invoke(callParam); } else { @@ -154,8 +153,8 @@ static bool JavaScriptArkTsBridge_callStaticMethod(se::State& s) { methodName = seval_to_type(args[1], ok); SE_PRECONDITION2(ok, false, "Converting methodName failed!"); - - if(argc > 2) { + + if (argc > 2) { paramStr = seval_to_type(args[2], ok); SE_PRECONDITION2(ok, false, "Converting paramStr failed!"); } diff --git a/native/cocos/bindings/manual/JavaScriptArkTsBridge.h b/native/cocos/bindings/manual/JavaScriptArkTsBridge.h index 5d80d08ca9..25a3a47ef3 100644 --- a/native/cocos/bindings/manual/JavaScriptArkTsBridge.h +++ b/native/cocos/bindings/manual/JavaScriptArkTsBridge.h @@ -24,7 +24,7 @@ #pragma once namespace se { - class Object; +class Object; } bool register_javascript_arkTs_bridge(se::Object* obj); \ No newline at end of file diff --git a/native/cocos/bindings/manual/jsb_box2d_manual.cpp b/native/cocos/bindings/manual/jsb_box2d_manual.cpp index bd8267264f..009c4519fc 100644 --- a/native/cocos/bindings/manual/jsb_box2d_manual.cpp +++ b/native/cocos/bindings/manual/jsb_box2d_manual.cpp @@ -22,15 +22,14 @@ private: TempFloatArray tempFloatArray; -bool js_b2World_SetContactListener(se::State& s) -{ +bool js_b2World_SetContactListener(se::State &s) { CC_UNUSED bool ok = true; - const auto& args = s.args(); + const auto &args = s.args(); size_t argc = args.size(); - b2World *arg1 = (b2World *) NULL ; - JSB_b2ContactListener *arg2 = (JSB_b2ContactListener *) NULL ; + b2World *arg1 = (b2World *)NULL; + JSB_b2ContactListener *arg2 = (JSB_b2ContactListener *)NULL; - if(argc != 1) { + if (argc != 1) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); return false; } @@ -41,20 +40,18 @@ bool js_b2World_SetContactListener(se::State& s) SE_PRECONDITION2(ok, false, "Error processing arguments"); (arg1)->SetContactListener(arg2); - return true; } SE_BIND_FUNC(js_b2World_SetContactListener) -bool js_b2World_SetDebugDraw(se::State& s) -{ +bool js_b2World_SetDebugDraw(se::State &s) { CC_UNUSED bool ok = true; - const auto& args = s.args(); + const auto &args = s.args(); size_t argc = args.size(); - b2World *arg1 = (b2World *) NULL ; - JSBB2Draw *arg2 = (JSBB2Draw *) NULL ; + b2World *arg1 = (b2World *)NULL; + JSBB2Draw *arg2 = (JSBB2Draw *)NULL; - if(argc != 1) { + if (argc != 1) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); return false; } @@ -65,22 +62,20 @@ bool js_b2World_SetDebugDraw(se::State& s) SE_PRECONDITION2(ok, false, "Error processing arguments"); (arg1)->SetDebugDraw(arg2); - return true; } SE_BIND_FUNC(js_b2World_SetDebugDraw) -bool js_b2World_QueryAABB(se::State& s) -{ +bool js_b2World_QueryAABB(se::State &s) { CC_UNUSED bool ok = true; - const auto& args = s.args(); + const auto &args = s.args(); size_t argc = args.size(); - b2World *arg1 = (b2World *) NULL ; - JSBQueryCallback *arg2 = (JSBQueryCallback *) NULL ; - b2AABB *arg3 = 0 ; - b2AABB temp3 ; + b2World *arg1 = (b2World *)NULL; + JSBQueryCallback *arg2 = (JSBQueryCallback *)NULL; + b2AABB *arg3 = 0; + b2AABB temp3; - if(argc != 2) { + if (argc != 2) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); return false; } @@ -94,26 +89,24 @@ bool js_b2World_QueryAABB(se::State& s) SE_PRECONDITION2(ok, false, "Error processing arguments"); arg3 = &temp3; - ((b2World const *)arg1)->QueryAABB(arg2,(b2AABB const &)*arg3); - + ((b2World const *)arg1)->QueryAABB(arg2, (b2AABB const &)*arg3); return true; } SE_BIND_FUNC(js_b2World_QueryAABB) -bool js_b2World_RayCast(se::State& s) -{ +bool js_b2World_RayCast(se::State &s) { CC_UNUSED bool ok = true; - const auto& args = s.args(); + const auto &args = s.args(); size_t argc = args.size(); - b2World *arg1 = (b2World *) NULL ; - JSBRayCastCallback *arg2 = (JSBRayCastCallback *) NULL ; - b2Vec2 *arg3 = 0 ; - b2Vec2 *arg4 = 0 ; - b2Vec2 temp3 ; - b2Vec2 temp4 ; + b2World *arg1 = (b2World *)NULL; + JSBRayCastCallback *arg2 = (JSBRayCastCallback *)NULL; + b2Vec2 *arg3 = 0; + b2Vec2 *arg4 = 0; + b2Vec2 temp3; + b2Vec2 temp4; - if(argc != 3) { + if (argc != 3) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 3); return false; } @@ -127,26 +120,23 @@ bool js_b2World_RayCast(se::State& s) SE_PRECONDITION2(ok, false, "Error processing arguments"); arg3 = &temp3; - ok &= sevalue_to_native(args[2], &temp4, s.thisObject()); SE_PRECONDITION2(ok, false, "Error processing arguments"); arg4 = &temp4; - ((b2World const *)arg1)->RayCast(arg2,(b2Vec2 const &)*arg3,(b2Vec2 const &)*arg4); - + ((b2World const *)arg1)->RayCast(arg2, (b2Vec2 const &)*arg3, (b2Vec2 const &)*arg4); return true; } SE_BIND_FUNC(js_b2World_RayCast) -bool js_Contact_GetWorldManifold(se::State& s) -{ +bool js_Contact_GetWorldManifold(se::State &s) { CC_UNUSED bool ok = true; - const auto& args = s.args(); + const auto &args = s.args(); size_t argc = args.size(); - b2Contact *arg1 = (b2Contact *) NULL ; + b2Contact *arg1 = (b2Contact *)NULL; - if(argc != 1) { + if (argc != 1) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); return false; } @@ -172,7 +162,7 @@ bool js_Contact_GetWorldManifold(se::State& s) se::Value points; worldManifoldObj->getProperty("points", &points); if (points.isObject() && points.toObject()->isArray()) { - auto* pointsObj = points.toObject(); + auto *pointsObj = points.toObject(); for (uint32_t i = 0; i < b2_maxManifoldPoints; ++i) { se::Value e; if (pointsObj->getArrayElement(i, &e) && e.isObject()) { @@ -187,7 +177,7 @@ bool js_Contact_GetWorldManifold(se::State& s) se::Value separations; worldManifoldObj->getProperty("separations", &separations); if (separations.isObject() && separations.toObject()->isArray()) { - auto* separationsObj = separations.toObject(); + auto *separationsObj = separations.toObject(); for (uint32_t i = 0; i < b2_maxManifoldPoints; ++i) { separationsObj->setArrayElement(i, se::Value(worldManifold.separations[i])); } @@ -198,9 +188,9 @@ bool js_Contact_GetWorldManifold(se::State& s) } SE_BIND_FUNC(js_Contact_GetWorldManifold) -bool js_b2PolygonShape_Set(se::State& s) { +bool js_b2PolygonShape_Set(se::State &s) { CC_UNUSED bool ok = true; - const auto& args = s.args(); + const auto &args = s.args(); size_t argc = args.size(); if (argc != 2) { return false; @@ -359,7 +349,7 @@ bool js_ChainShape_m_vertices_get(se::State &s) { } SE_BIND_PROP_GET(js_ChainShape_m_vertices_get) -} // namespace { +} // namespace bool register_all_box2d_manual(se::Object *obj) { // NOLINT // Get the ns @@ -390,12 +380,12 @@ bool register_all_box2d_manual(se::Object *obj) { // NOLINT __jsb_b2ContactImpulse_proto->defineProperty("normalImpulses", _SE(js_ContactImpulse_normalImpulses_get), nullptr); __jsb_b2ContactImpulse_proto->defineProperty("tangentImpulses", _SE(js_ContactImpulse_tangentImpulses_get), nullptr); - + __jsb_b2PolygonShape_proto->defineProperty("m_vertices", _SE(js_PolygonShape_m_vertices_get), nullptr); __jsb_b2PolygonShape_proto->defineProperty("m_normals", _SE(js_PolygonShape_m_normals_get), nullptr); - + __jsb_b2ChainShape_proto->defineProperty("m_vertices", _SE(js_ChainShape_m_vertices_get), nullptr); - + nsObj->setProperty("maxFloat", se::Value(b2_maxFloat)); nsObj->setProperty("epsilon", se::Value(b2_epsilon)); nsObj->setProperty("pi", se::Value(b2_pi)); diff --git a/native/cocos/bindings/manual/jsb_cocos_manual.cpp b/native/cocos/bindings/manual/jsb_cocos_manual.cpp index f71fabf9c5..1ebb8d36bc 100644 --- a/native/cocos/bindings/manual/jsb_cocos_manual.cpp +++ b/native/cocos/bindings/manual/jsb_cocos_manual.cpp @@ -738,7 +738,6 @@ static bool js_readFile_doJob(const ccstd::string &fullPath, typename ReadFileDo return false; } - if constexpr (std::is_same_v && isJson) { // TODO(cjh): OpenHarmony NAPI support #if SCRIPT_ENGINE_TYPE != SCRIPT_ENGINE_NAPI diff --git a/native/cocos/bindings/manual/jsb_conversions.h b/native/cocos/bindings/manual/jsb_conversions.h index 4855aecad6..1d05d37397 100644 --- a/native/cocos/bindings/manual/jsb_conversions.h +++ b/native/cocos/bindings/manual/jsb_conversions.h @@ -40,8 +40,8 @@ #include "bindings/jswrapper/HandleObject.h" #include "bindings/jswrapper/SeApi.h" #include "bindings/manual/jsb_classtype.h" -#include "jsb_conversions_spec.h" #include "core/data/JSBNativeDataHolder.h" +#include "jsb_conversions_spec.h" #if CC_USE_SPINE #include "cocos/editor-support/spine-creator-support/spine-cocos2dx.h" @@ -725,7 +725,7 @@ sevalue_to_native(const se::Value &from, T **to, se::Object * /*ctx*/) { // NOLI } // duplicate extern to resolve the circular reference jsb_cocos_auto.h -// see jsb_cocos_auto.h +// see jsb_cocos_auto.h extern se::Class *__jsb_cc_JSBNativeDataHolder_class; // NOLINT template diff --git a/native/cocos/bindings/manual/jsb_conversions_spec.cpp b/native/cocos/bindings/manual/jsb_conversions_spec.cpp index 00af76c128..434a3f2764 100644 --- a/native/cocos/bindings/manual/jsb_conversions_spec.cpp +++ b/native/cocos/bindings/manual/jsb_conversions_spec.cpp @@ -43,7 +43,7 @@ #include "bindings/auto/jsb_assets_auto.h" #include "bindings/auto/jsb_cocos_auto.h" #if CC_USE_PHYSICS_PHYSX -#include "bindings/auto/jsb_physics_auto.h" + #include "bindings/auto/jsb_physics_auto.h" #endif #include "cocos/core/geometry/Geometry.h" #include "scene/Fog.h" @@ -51,11 +51,11 @@ #include "scene/Skybox.h" #if CC_USE_SPINE -#include "cocos/editor-support/spine-creator-support/Vector2.h" + #include "cocos/editor-support/spine-creator-support/Vector2.h" #endif #if CC_USE_BOX2D_JSB -#include "bindings/auto/jsb_box2d_auto.h" + #include "bindings/auto/jsb_box2d_auto.h" #endif ///////////////////////// utils ///////////////////////// diff --git a/native/cocos/bindings/manual/jsb_conversions_spec.h b/native/cocos/bindings/manual/jsb_conversions_spec.h index a154fa60e1..4dfefcde8d 100644 --- a/native/cocos/bindings/manual/jsb_conversions_spec.h +++ b/native/cocos/bindings/manual/jsb_conversions_spec.h @@ -39,7 +39,7 @@ #endif #if CC_USE_BOX2D_JSB -#include "box2d/box2d.h" + #include "box2d/box2d.h" #endif namespace cc { @@ -377,11 +377,11 @@ inline bool sevalue_to_native(const se::Value &from, ccstd::string **to, se::Obj bool sevalue_to_native(const se::Value &from, cc::ValueMap *to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming) -bool sevalue_to_native(const se::Value &from, ccstd::vector *to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming) +bool sevalue_to_native(const se::Value &from, ccstd::vector *to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming) bool sevalue_to_native(const se::Value &from, ccstd::variant *to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming) -bool sevalue_to_native(const se::Value &from, ccstd::vector *to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming) -bool sevalue_to_native(const se::Value &from, cc::IPropertyValue *to, se::Object *ctx); // NOLINT(readability-identifier-naming) -inline bool sevalue_to_native(const se::Value & /*from*/, ccstd::monostate * /*to*/, se::Object * /*ctx*/) { // NOLINT(readability-identifier-naming) +bool sevalue_to_native(const se::Value &from, ccstd::vector *to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming) +bool sevalue_to_native(const se::Value &from, cc::IPropertyValue *to, se::Object *ctx); // NOLINT(readability-identifier-naming) +inline bool sevalue_to_native(const se::Value & /*from*/, ccstd::monostate * /*to*/, se::Object * /*ctx*/) { // NOLINT(readability-identifier-naming) // nothing todo return false; } @@ -646,8 +646,8 @@ bool sevalue_to_native(const se::Value &from, b2Vec2 *to, se::Object * /*unused* bool sevalue_to_native(const se::Value &from, b2Vec3 *to, se::Object * /*unused*/); bool sevalue_to_native(const se::Value &from, b2Color *to, se::Object * /*unused*/); -bool nativevalue_to_se(const b2Vec2 &from, se::Value &to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming) -bool nativevalue_to_se(const b2Vec3 &from, se::Value &to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming) +bool nativevalue_to_se(const b2Vec2 &from, se::Value &to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming) +bool nativevalue_to_se(const b2Vec3 &from, se::Value &to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming) bool nativevalue_to_se(const b2Color &from, se::Value &to, se::Object * /*ctx*/); // NOLINT(readability-identifier-naming) #endif //CC_USE_BOX2D_JSB diff --git a/native/cocos/bindings/manual/jsb_global.h b/native/cocos/bindings/manual/jsb_global.h index 23bbb0846d..8f90e59c88 100644 --- a/native/cocos/bindings/manual/jsb_global.h +++ b/native/cocos/bindings/manual/jsb_global.h @@ -28,7 +28,7 @@ #include "jsb_global_init.h" namespace cc { - class LegacyThreadPool; +class LegacyThreadPool; } extern cc::LegacyThreadPool *gIOThreadPool; diff --git a/native/cocos/bindings/manual/jsb_module_register.cpp b/native/cocos/bindings/manual/jsb_module_register.cpp index 84637fcb5c..2db91b91f7 100644 --- a/native/cocos/bindings/manual/jsb_module_register.cpp +++ b/native/cocos/bindings/manual/jsb_module_register.cpp @@ -49,8 +49,8 @@ #include "cocos/bindings/manual/jsb_scene_manual.h" #include "cocos/bindings/manual/jsb_xmlhttprequest.h" #if CC_USE_BOX2D_JSB -#include "cocos/bindings/manual/jsb_box2d_manual.h" -#include "cocos/bindings/auto/jsb_box2d_auto.h" + #include "cocos/bindings/auto/jsb_box2d_auto.h" + #include "cocos/bindings/manual/jsb_box2d_manual.h" #endif #if USE_GFX_RENDERER diff --git a/native/cocos/bindings/manual/jsb_network_manual.cpp b/native/cocos/bindings/manual/jsb_network_manual.cpp index 6989e6d5a5..ecc6514359 100644 --- a/native/cocos/bindings/manual/jsb_network_manual.cpp +++ b/native/cocos/bindings/manual/jsb_network_manual.cpp @@ -58,9 +58,9 @@ static bool js_network_Downloader_createDownloadTask(se::State &s) { // NOLINT(r ccstd::string arg1; ccstd::string identifier; ccstd::unordered_map header; - + std::shared_ptr result; - + ok &= sevalue_to_native(args[0], &arg0); ok &= sevalue_to_native(args[1], &arg1); if (args[2].isString()) { @@ -84,13 +84,13 @@ static bool js_network_Downloader_createDownloadTask(se::State &s) { // NOLINT(r "js_network_Downloader_createDownloadTask : Error processing arguments"); return true; } - + if (argc == 4) { ccstd::string arg0; ccstd::string arg1; ccstd::unordered_map arg2; ccstd::string arg3; - + ok &= sevalue_to_native(args[0], &arg0); ok &= sevalue_to_native(args[1], &arg1); ok &= sevalue_to_native(args[2], &arg2); @@ -310,7 +310,7 @@ bool register_all_network_manual(se::Object * /*obj*/) { // NOLINT(readability-i __jsb_cc_network_Downloader_proto->defineProperty("onError", nullptr, _SE(js_network_Downloader_setOnError_asSetter)); __jsb_cc_network_Downloader_proto->defineFunction("createDownloadTask", _SE(js_network_Downloader_createDownloadTask)); - __jsb_cc_network_Downloader_proto->defineFunction("createDownloadFileTask", // deprecated since v3.6, use createDownloadTask instead. + __jsb_cc_network_Downloader_proto->defineFunction("createDownloadFileTask", // deprecated since v3.6, use createDownloadTask instead. _SE(js_network_Downloader_createDownloadTask)); __jsb_cc_network_Downloader_proto->defineFunction("setOnTaskError", _SE(js_network_Downloader_setOnTaskError)); // deprecated since v3.6 diff --git a/native/cocos/bindings/manual/jsb_platform.h b/native/cocos/bindings/manual/jsb_platform.h index 4df49e8cab..67489eb5ba 100644 --- a/native/cocos/bindings/manual/jsb_platform.h +++ b/native/cocos/bindings/manual/jsb_platform.h @@ -27,8 +27,8 @@ #include "base/std/container/unordered_map.h" #if CC_PLATFORM == CC_PLATFORM_OPENHARMONY -#include -#include + #include + #include #endif namespace se { class Object; @@ -38,5 +38,5 @@ bool register_platform_bindings(se::Object *obj); // NOLINT[readability-identifi const ccstd::unordered_map &getFontFamilyNameMap(); #if CC_PLATFORM == CC_PLATFORM_OPENHARMONY const std::string defaultFontKey = "openharmony_system_font"; -const std::unordered_map& getFontFamilyCollectionMap(); +const std::unordered_map &getFontFamilyCollectionMap(); #endif diff --git a/native/cocos/bindings/manual/jsb_platform_openharmony.cpp b/native/cocos/bindings/manual/jsb_platform_openharmony.cpp index fcf2032e94..222cf6776b 100644 --- a/native/cocos/bindings/manual/jsb_platform_openharmony.cpp +++ b/native/cocos/bindings/manual/jsb_platform_openharmony.cpp @@ -25,20 +25,19 @@ #include "jsb_platform.h" +#include +#include +#include #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_conversions.h" #include "cocos/bindings/manual/jsb_global_init.h" #include "cocos/platform/FileUtils.h" -#include -#include -#include using namespace cc; -static std::unordered_map _fontCollectionMap = { - { defaultFontKey, OH_Drawing_CreateSharedFontCollection() } -}; +static std::unordered_map _fontCollectionMap = { + {defaultFontKey, OH_Drawing_CreateSharedFontCollection()}}; -const std::unordered_map& getFontFamilyCollectionMap() { +const std::unordered_map &getFontFamilyCollectionMap() { return _fontCollectionMap; } @@ -49,31 +48,29 @@ const std::unordered_map &getFontFamilyNameMap() { } static bool JSB_loadFont(se::State &s) { - const auto& args = s.args(); + const auto &args = s.args(); size_t argc = args.size(); CC_UNUSED bool ok = true; if (argc >= 1) { s.rval().setNull(); - + std::string fontFamily; ok &= seval_to_std_string(args[0], &fontFamily); SE_PRECONDITION2(ok, false, "JSB_loadFont : Error processing argument: fontFamily"); - + std::string source; ok &= seval_to_std_string(args[1], &source); SE_PRECONDITION2(ok, false, "JSB_loadFont : Error processing argument: source"); - + std::string fontFilePath; std::regex re("url\\(\\s*'\\s*(.*?)\\s*'\\s*\\)"); std::match_results results; - if (std::regex_search(source.cbegin(), source.cend(), results, re)) - { + if (std::regex_search(source.cbegin(), source.cend(), results, re)) { fontFilePath = results[1].str(); } - + fontFilePath = FileUtils::getInstance()->fullPathForFilename(fontFilePath); - if (fontFilePath.empty()) - { + if (fontFilePath.empty()) { SE_LOGE("Font (%s) doesn't exist!", fontFilePath.c_str()); return true; } @@ -87,10 +84,10 @@ static bool JSB_loadFont(se::State &s) { OH_Drawing_RegisterFontBuffer(_fontCollection, fontFamily.c_str(), bufferData.getBytes(), bufferData.getSize()); _fontCollectionMap.emplace(fontFamily, _fontCollection); s.rval().setString(fontFamily); - + return true; } - + SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); return false; } diff --git a/native/cocos/bindings/manual/jsb_scene_manual.cpp b/native/cocos/bindings/manual/jsb_scene_manual.cpp index 7ad3745b4c..568fc01665 100644 --- a/native/cocos/bindings/manual/jsb_scene_manual.cpp +++ b/native/cocos/bindings/manual/jsb_scene_manual.cpp @@ -23,12 +23,12 @@ ****************************************************************************/ #include "jsb_scene_manual.h" +#include "application/ApplicationManager.h" #include "bindings/auto/jsb_gfx_auto.h" #include "bindings/auto/jsb_scene_auto.h" #include "core/Root.h" #include "core/scene-graph/Node.h" #include "scene/Model.h" -#include "application/ApplicationManager.h" #ifndef JSB_ALLOC #define JSB_ALLOC(kls, ...) ccnew kls(__VA_ARGS__) @@ -689,7 +689,7 @@ static bool js_Model_setInstancedAttribute(se::State &s) // NOLINT(readability-i if (val.toObject()->isArray()) { uint32_t len = 0; val.toObject()->getArrayLength(&len); - + cc::Float32Array value(len); se::Value dataVal; diff --git a/native/cocos/bindings/manual/jsb_socketio.cpp b/native/cocos/bindings/manual/jsb_socketio.cpp index b885bfa0ec..cd7c66b075 100644 --- a/native/cocos/bindings/manual/jsb_socketio.cpp +++ b/native/cocos/bindings/manual/jsb_socketio.cpp @@ -134,7 +134,7 @@ static bool SocketIO_finalize(se::State &s) { // NOLINT(readability-identifier-n auto *cobj = static_cast(s.nativeThisObject()); CC_LOG_INFO("jsbindings: finalizing JS object %p (SocketIO)", cobj); cobj->disconnect(); - if(se::ScriptEngine::getInstance()->isInCleanup()) { + if (se::ScriptEngine::getInstance()->isInCleanup()) { return true; } auto *delegate = static_cast(cobj->getDelegate()); diff --git a/native/cocos/bindings/manual/jsb_spine_manual.cpp b/native/cocos/bindings/manual/jsb_spine_manual.cpp index 0c379985de..24b6df6254 100644 --- a/native/cocos/bindings/manual/jsb_spine_manual.cpp +++ b/native/cocos/bindings/manual/jsb_spine_manual.cpp @@ -42,8 +42,8 @@ #include "platform/FileUtils.h" #include "spine-creator-support/SkeletonDataMgr.h" #include "spine-creator-support/SkeletonRenderer.h" -#include "spine-creator-support/spine-cocos2dx.h" #include "spine-creator-support/Vector2.h" +#include "spine-creator-support/spine-cocos2dx.h" using namespace cc; @@ -239,7 +239,7 @@ static bool js_VertexAttachment_computeWorldVertices(se::State &s) { ok = sevalue_to_native(args[1], &start, s.thisObject()); SE_PRECONDITION2(ok, false, "Error processing start"); - + ok = sevalue_to_native(args[2], &worldVerticesVal, s.thisObject()); SE_PRECONDITION2(ok, false, "Error processing vertices"); @@ -248,22 +248,22 @@ static bool js_VertexAttachment_computeWorldVertices(se::State &s) { ok = sevalue_to_native(args[4], &offset, s.thisObject()); SE_PRECONDITION2(ok, false, "Error processing offset"); - + ok = sevalue_to_native(args[5], &stride, s.thisObject()); SE_PRECONDITION2(ok, false, "Error processing stride"); if (worldVerticesVal.toObject()->isTypedArray()) { - uint8_t* ptr = nullptr; + uint8_t *ptr = nullptr; size_t len = 0; worldVerticesVal.toObject()->getTypedArrayData(&ptr, &len); - vertexAttachment->computeWorldVertices(*slot, start, count, reinterpret_cast(ptr), offset, stride); + vertexAttachment->computeWorldVertices(*slot, start, count, reinterpret_cast(ptr), offset, stride); } else if (worldVerticesVal.toObject()->isArray()) { spine::Vector worldVertices; worldVertices.ensureCapacity(count); vertexAttachment->computeWorldVertices(*slot, start, count, worldVertices, 0); int tCount = offset + (count >> 1) * stride; - + for (size_t i = offset, t = 0; i < tCount; i += stride, t += 2) { worldVerticesVal.toObject()->setArrayElement(i, se::Value(worldVertices[t])); worldVerticesVal.toObject()->setArrayElement(i + 1, se::Value(worldVertices[t + 1])); @@ -305,7 +305,7 @@ static bool js_RegionAttachment_computeWorldVertices(se::State &s) { SE_PRECONDITION2(ok, false, "Error processing arguments"); if (worldVerticesVal.toObject()->isTypedArray()) { - uint8_t* ptr = nullptr; + uint8_t *ptr = nullptr; size_t len = 0; worldVerticesVal.toObject()->getTypedArrayData(&ptr, &len); #if CC_USE_SPINE_3_8 @@ -345,7 +345,7 @@ SE_BIND_FUNC(js_RegionAttachment_computeWorldVertices) static bool js_Skeleton_getBounds(se::State &s) { const auto &args = s.args(); - spine::Skeleton* skeleton = SE_THIS_OBJECT(s); + spine::Skeleton *skeleton = SE_THIS_OBJECT(s); if (nullptr == skeleton) return true; se::Value temp; @@ -374,7 +374,7 @@ SE_BIND_FUNC(js_Skeleton_getBounds) static bool js_Bone_worldToLocal(se::State &s) { const auto &args = s.args(); - spine::Bone* bone = SE_THIS_OBJECT(s); + spine::Bone *bone = SE_THIS_OBJECT(s); if (nullptr == bone) return true; spine::Vector2 world(0, 0); @@ -396,7 +396,7 @@ SE_BIND_FUNC(js_Bone_worldToLocal) static bool js_Bone_localToWorld(se::State &s) { const auto &args = s.args(); - spine::Bone* bone = SE_THIS_OBJECT(s); + spine::Bone *bone = SE_THIS_OBJECT(s); if (nullptr == bone) return true; spine::Vector2 local(0, 0); @@ -418,10 +418,10 @@ SE_BIND_FUNC(js_Bone_localToWorld) static bool js_PointAttachment_computeWorldPosition(se::State &s) { const auto &args = s.args(); - spine::PointAttachment* pointAttachment = SE_THIS_OBJECT(s); + spine::PointAttachment *pointAttachment = SE_THIS_OBJECT(s); if (nullptr == pointAttachment) return true; - spine::Bone* bone = nullptr; + spine::Bone *bone = nullptr; bool ok = false; ok = sevalue_to_native(args[0], &bone, s.thisObject()); @@ -440,7 +440,7 @@ SE_BIND_FUNC(js_PointAttachment_computeWorldPosition) static bool js_Skin_findAttachmentsForSlot(se::State &s) { const auto &args = s.args(); - spine::Skin* skin = SE_THIS_OBJECT(s); + spine::Skin *skin = SE_THIS_OBJECT(s); if (nullptr == skin) return true; size_t slotIndex = 0; @@ -472,7 +472,7 @@ SE_BIND_FUNC(js_Skin_findAttachmentsForSlot) #if CC_USE_SPINE_3_8 static bool js_VertexEffect_transform(se::State &s) { const auto &args = s.args(); - spine::VertexEffect* effect = SE_THIS_OBJECT(s); + spine::VertexEffect *effect = SE_THIS_OBJECT(s); if (nullptr == effect) return true; float outX = 0.F, outY = 0.F; @@ -486,7 +486,7 @@ SE_BIND_FUNC(js_VertexEffect_transform) static bool js_SwirlVertexEffect_transform(se::State &s) { const auto &args = s.args(); - spine::SwirlVertexEffect* effect = SE_THIS_OBJECT(s); + spine::SwirlVertexEffect *effect = SE_THIS_OBJECT(s); if (nullptr == effect) return true; float outX = 0.F, outY = 0.F; @@ -500,7 +500,7 @@ SE_BIND_FUNC(js_SwirlVertexEffect_transform) static bool js_JitterVertexEffect_transform(se::State &s) { const auto &args = s.args(); - spine::JitterVertexEffect* effect = SE_THIS_OBJECT(s); + spine::JitterVertexEffect *effect = SE_THIS_OBJECT(s); if (nullptr == effect) return true; float outX = 0.F, outY = 0.F; @@ -513,13 +513,13 @@ static bool js_JitterVertexEffect_transform(se::State &s) { SE_BIND_FUNC(js_JitterVertexEffect_transform) #endif -static bool js_spine_Skin_getAttachments(se::State& s) { +static bool js_spine_Skin_getAttachments(se::State &s) { CC_UNUSED bool ok = true; - const auto& args = s.args(); + const auto &args = s.args(); size_t argc = args.size(); - spine::Skin *skin = (spine::Skin *) NULL ; - - if(argc != 0) { + spine::Skin *skin = (spine::Skin *)NULL; + + if (argc != 0) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); return false; } @@ -535,26 +535,26 @@ static bool js_spine_Skin_getAttachments(se::State& s) { SE_PRECONDITION2(ok, false, "Error processing arguments"); entries.push_back(entryVal); } - + se::HandleObject array(se::Object::createArrayObject(entries.size())); for (int i = 0; i < entries.size(); ++i) { array->setArrayElement(i, entries[i]); } s.rval().setObject(array); - + return true; } SE_BIND_FUNC(js_spine_Skin_getAttachments) -static bool js_spine_Slot_setAttachment(se::State& s) { +static bool js_spine_Slot_setAttachment(se::State &s) { CC_UNUSED bool ok = true; - const auto& args = s.args(); - spine::Slot *slot = (spine::Slot *) NULL ; + const auto &args = s.args(); + spine::Slot *slot = (spine::Slot *)NULL; slot = SE_THIS_OBJECT(s); if (nullptr == slot) return true; - spine::Attachment* attachment = nullptr; + spine::Attachment *attachment = nullptr; ok = sevalue_to_native(args[0], &attachment, s.thisObject()); SE_PRECONDITION2(ok, false, "Error processing arguments"); @@ -565,10 +565,10 @@ static bool js_spine_Slot_setAttachment(se::State& s) { } SE_BIND_FUNC(js_spine_Slot_setAttachment) -static bool js_spine_Slot_getAttachment(se::State& s) { +static bool js_spine_Slot_getAttachment(se::State &s) { CC_UNUSED bool ok = true; - const auto& args = s.args(); - spine::Slot *slot = (spine::Slot *) NULL ; + const auto &args = s.args(); + spine::Slot *slot = (spine::Slot *)NULL; slot = SE_THIS_OBJECT(s); if (nullptr == slot) return true; @@ -582,29 +582,27 @@ static bool js_spine_Slot_getAttachment(se::State& s) { } SE_BIND_FUNC(js_spine_Slot_getAttachment) -static bool js_spine_Skeleton_setSkin(se::State& s) -{ +static bool js_spine_Skeleton_setSkin(se::State &s) { CC_UNUSED bool ok = true; - const auto& args = s.args(); + const auto &args = s.args(); size_t argc = args.size(); - spine::Skeleton *arg1 = (spine::Skeleton *) NULL ; - spine::Skin *arg2 = (spine::Skin *) NULL ; - - if(argc != 1) { + spine::Skeleton *arg1 = (spine::Skeleton *)NULL; + spine::Skin *arg2 = (spine::Skin *)NULL; + + if (argc != 1) { SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); return false; } arg1 = SE_THIS_OBJECT(s); if (nullptr == arg1) return true; - + ok &= sevalue_to_native(args[0], &arg2, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); + SE_PRECONDITION2(ok, false, "Error processing arguments"); (arg1)->setSkin(arg2); - - + return true; } -SE_BIND_FUNC(js_spine_Skeleton_setSkin) +SE_BIND_FUNC(js_spine_Skeleton_setSkin) bool register_all_spine_manual(se::Object *obj) { // Get the ns @@ -624,7 +622,7 @@ bool register_all_spine_manual(se::Object *obj) { __jsb_spine_VertexAttachment_proto->defineFunction("computeWorldVertices", _SE(js_VertexAttachment_computeWorldVertices)); __jsb_spine_RegionAttachment_proto->defineFunction("computeWorldVertices", _SE(js_RegionAttachment_computeWorldVertices)); __jsb_spine_Skeleton_proto->defineFunction("getBounds", _SE(js_Skeleton_getBounds)); - __jsb_spine_Skeleton_proto->defineFunction("setSkin", _SE(js_spine_Skeleton_setSkin)); + __jsb_spine_Skeleton_proto->defineFunction("setSkin", _SE(js_spine_Skeleton_setSkin)); __jsb_spine_Skin_proto->defineFunction("getAttachmentsForSlot", _SE(js_Skin_findAttachmentsForSlot)); __jsb_spine_Bone_proto->defineFunction("worldToLocal", _SE(js_Bone_worldToLocal)); __jsb_spine_Bone_proto->defineFunction("localToWorld", _SE(js_Bone_localToWorld)); diff --git a/native/cocos/bindings/manual/jsb_websocket.cpp b/native/cocos/bindings/manual/jsb_websocket.cpp index 718ddd54c4..c43e3673b0 100644 --- a/native/cocos/bindings/manual/jsb_websocket.cpp +++ b/native/cocos/bindings/manual/jsb_websocket.cpp @@ -24,9 +24,9 @@ #include "jsb_websocket.h" #include "MappingUtils.h" -#include "base/std/container/unordered_set.h" #include "base/DeferredReleasePool.h" #include "base/UTF8.h" +#include "base/std/container/unordered_set.h" #include "bindings/jswrapper/SeApi.h" #include "bindings/manual/jsb_conversions.h" #include "bindings/manual/jsb_global.h" @@ -34,7 +34,6 @@ #include "application/ApplicationManager.h" - /* [Constructor(in DOMString url, in optional DOMString protocols)] [Constructor(in DOMString url, in optional DOMString[] protocols)] @@ -250,7 +249,7 @@ static bool webSocketFinalize(se::State &s) { CC_LOG_INFO("WebSocket (%p) isn't closed, try to close it!", cobj); cobj->closeAsync(); } - if(se::ScriptEngine::getInstance()->isInCleanup()) { + if (se::ScriptEngine::getInstance()->isInCleanup()) { return true; } static_cast(cobj->getDelegate())->release(); diff --git a/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp b/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp index 6249e9e004..5df364953a 100644 --- a/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp +++ b/native/cocos/bindings/manual/jsb_xmlhttprequest.cpp @@ -263,7 +263,6 @@ bool XMLHttpRequest::open(const ccstd::string &method, const ccstd::string &url) requestType = HttpRequest::Type::DELETE; } else if (_method == "patch" || _method == "PATCH") { requestType = HttpRequest::Type::PATCH; - } CC_ASSERT(requestType != HttpRequest::Type::UNKNOWN); @@ -578,7 +577,7 @@ se::Class *__jsb_XMLHttpRequest_class = nullptr; //NOLINT(readability-identifier static bool XMLHttpRequest_finalize(se::State &s) { //NOLINT(readability-identifier-naming, google-runtime-references) auto *request = static_cast(s.nativeThisObject()); - if(se::ScriptEngine::getInstance()->isInCleanup()) { + if (se::ScriptEngine::getInstance()->isInCleanup()) { request->onloadstart = nullptr; request->onload = nullptr; request->onloadend = nullptr; diff --git a/native/cocos/cocos-version.h b/native/cocos/cocos-version.h index 46a935974e..5cd554a428 100644 --- a/native/cocos/cocos-version.h +++ b/native/cocos/cocos-version.h @@ -23,11 +23,11 @@ THE SOFTWARE. ****************************************************************************/ #pragma once -#define COCOS_MAJOR_VERSION 4 -#define COCOS_MINJOR_VERSION 0 -#define COCOS_PATCH_VERSION 0 -#define COCOS_VERSION_STRING "4.0.0" -#define COCOS_VERSION_DEFINED 1 -#define COCOS_VERSION 40000 +#define COCOS_MAJOR_VERSION 4 +#define COCOS_MINJOR_VERSION 0 +#define COCOS_PATCH_VERSION 0 +#define COCOS_VERSION_STRING "4.0.0" +#define COCOS_VERSION_DEFINED 1 +#define COCOS_VERSION 40000 // #define COCOS_PRE_RELEASE "alpha" diff --git a/native/cocos/core/ArrayBuffer.cpp b/native/cocos/core/ArrayBuffer.cpp index 76f6df254d..5a87aabca1 100644 --- a/native/cocos/core/ArrayBuffer.cpp +++ b/native/cocos/core/ArrayBuffer.cpp @@ -51,7 +51,7 @@ void ArrayBuffer::setJSArrayBuffer(se::Object *arrayBuffer) { _jsArrayBuffer->unroot(); _jsArrayBuffer->decRef(); } - + _jsArrayBuffer = arrayBuffer; _jsArrayBuffer->incRef(); _jsArrayBuffer->root(); diff --git a/native/cocos/core/DataView.h b/native/cocos/core/DataView.h index 8ddad6686a..aabc22c76f 100644 --- a/native/cocos/core/DataView.h +++ b/native/cocos/core/DataView.h @@ -25,9 +25,9 @@ #pragma once #include "base/Macros.h" +#include "base/std/container/unordered_map.h" #include "base/std/variant.h" #include "core/ArrayBuffer.h" -#include "base/std/container/unordered_map.h" namespace cc { diff --git a/native/cocos/core/Root.cpp b/native/cocos/core/Root.cpp index 61608ed426..9c239feb0c 100644 --- a/native/cocos/core/Root.cpp +++ b/native/cocos/core/Root.cpp @@ -47,8 +47,8 @@ #include "renderer/pipeline/forward/ForwardPipeline.h" #include "scene/Camera.h" #include "scene/DirectionalLight.h" -#include "scene/SpotLight.h" #include "scene/Skybox.h" +#include "scene/SpotLight.h" namespace cc { @@ -359,8 +359,7 @@ void Root::onGlobalPipelineStateChanged() { scene->onGlobalPipelineStateChanged(); } - if (_pipelineRuntime->getPipelineSceneData()->getSkybox()->isEnabled()) - { + if (_pipelineRuntime->getPipelineSceneData()->getSkybox()->isEnabled()) { _pipelineRuntime->getPipelineSceneData()->getSkybox()->getModel()->onGlobalPipelineStateChanged(); } @@ -569,7 +568,7 @@ void Root::doXRFrameMove(int32_t totalFrames) { bool isSceneUpdated = false; int viewCount = _xr->getXRConfig(xr::XRConfigKey::VIEW_COUNT).getInt(); // compatible native pipeline - static bool isNativePipeline = dynamic_cast(_pipelineRuntime.get()) != nullptr; + static bool isNativePipeline = dynamic_cast(_pipelineRuntime.get()) != nullptr; bool forceUpdateSceneTwice = isNativePipeline ? true : _xr->getXRConfig(xr::XRConfigKey::EYE_RENDER_JS_CALLBACK).getBool(); for (int xrEye = 0; xrEye < viewCount; xrEye++) { _xr->beginRenderEyeFrame(xrEye); diff --git a/native/cocos/core/Root.h b/native/cocos/core/Root.h index 3834fc75ec..0296caecb2 100644 --- a/native/cocos/core/Root.h +++ b/native/cocos/core/Root.h @@ -28,16 +28,16 @@ #include "bindings/event/EventDispatcher.h" #include "core/event/Event.h" #include "core/memop/Pool.h" -#include "renderer/pipeline/RenderPipeline.h" #include "renderer/pipeline/DebugView.h" +#include "renderer/pipeline/RenderPipeline.h" #include "scene/DrawBatch2D.h" #include "scene/Light.h" #include "scene/Model.h" +#include "scene/PointLight.h" +#include "scene/RangedDirectionalLight.h" #include "scene/RenderScene.h" #include "scene/RenderWindow.h" #include "scene/SphereLight.h" -#include "scene/PointLight.h" -#include "scene/RangedDirectionalLight.h" namespace cc { class IXRInterface; diff --git a/native/cocos/core/TypedArray.cpp b/native/cocos/core/TypedArray.cpp index c9a8f1cd51..e1ad10b641 100644 --- a/native/cocos/core/TypedArray.cpp +++ b/native/cocos/core/TypedArray.cpp @@ -131,15 +131,15 @@ void copyTypedArray(TypedArray &dst, uint32_t dstOffset, const TypedArray &src) CC_ASSERT(dstOffset + srcLength <= dstLength); // Optimization: If src and dst are of the same type, use memcpy for efficiency -#define COPY_TYPED_ARRAY_MEMCPY(type) \ - do { \ - auto *srcArray = ccstd::get_if(&src); \ - auto *dstArray = ccstd::get_if(&dst); \ - if (srcArray != nullptr && dstArray != nullptr) { \ - memcpy(&(*dstArray)[dstOffset], &(*srcArray)[0], \ - srcLength * srcBytesPerElement); \ - return; \ - } \ +#define COPY_TYPED_ARRAY_MEMCPY(type) \ + do { \ + auto *srcArray = ccstd::get_if(&src); \ + auto *dstArray = ccstd::get_if(&dst); \ + if (srcArray != nullptr && dstArray != nullptr) { \ + memcpy(&(*dstArray)[dstOffset], &(*srcArray)[0], \ + srcLength *srcBytesPerElement); \ + return; \ + } \ } while (false) COPY_TYPED_ARRAY_MEMCPY(Float32Array); @@ -154,15 +154,15 @@ void copyTypedArray(TypedArray &dst, uint32_t dstOffset, const TypedArray &src) #undef COPY_TYPED_ARRAY_MEMCPY // Cross-type copy: Use a loop for element-wise copying with type conversion -#define COPY_TYPED_ARRAY_TO_DEST(type) \ - do { \ - auto *dstArray = ccstd::get_if(&dst); \ - if (dstArray != nullptr) { \ - for (uint32_t i = 0; i < srcLength; ++i) { \ +#define COPY_TYPED_ARRAY_TO_DEST(type) \ + do { \ + auto *dstArray = ccstd::get_if(&dst); \ + if (dstArray != nullptr) { \ + for (uint32_t i = 0; i < srcLength; ++i) { \ (*dstArray)[dstOffset + i] = getTypedArrayValue(src, i); \ - } \ - return; \ - } \ + } \ + return; \ + } \ } while (false) COPY_TYPED_ARRAY_TO_DEST(Float32Array); diff --git a/native/cocos/core/assets/EffectAsset.cpp b/native/cocos/core/assets/EffectAsset.cpp index 3de9bb7c77..d9391041f3 100644 --- a/native/cocos/core/assets/EffectAsset.cpp +++ b/native/cocos/core/assets/EffectAsset.cpp @@ -232,7 +232,7 @@ void EffectAsset::precompile() { if (programLib == nullptr) { ccstd::vector defines = EffectAsset::doCombine( ccstd::vector(), combination, combination.begin()); - for (auto &define: defines) { + for (auto &define : defines) { ProgramLib::getInstance()->getGFXShader(root->getDevice(), shader.name, define, root->getPipeline()); } diff --git a/native/cocos/core/assets/ImageAsset.h b/native/cocos/core/assets/ImageAsset.h index fc2ed07188..85500e0984 100644 --- a/native/cocos/core/assets/ImageAsset.h +++ b/native/cocos/core/assets/ImageAsset.h @@ -116,8 +116,8 @@ public: setFormat(format); _isFormatFixed = true; } - inline bool isFormatFixed() const { return _isFormatFixed; } - + inline bool isFormatFixed() const { return _isFormatFixed; } + // Functions for Utils. IntrusivePtr extractMipmap0(); std::vector> extractMipmaps(); diff --git a/native/cocos/core/assets/SimpleTexture.cpp b/native/cocos/core/assets/SimpleTexture.cpp index e0a0120276..e18039c199 100644 --- a/native/cocos/core/assets/SimpleTexture.cpp +++ b/native/cocos/core/assets/SimpleTexture.cpp @@ -80,7 +80,7 @@ void SimpleTexture::uploadData(const uint8_t *source, uint32_t level /* = 0 */, gfx::BufferTextureCopy region; region.texExtent.width = _textureWidth >> level; region.texExtent.height = _textureHeight >> level; - if(region.texExtent.width < 1 ||region.texExtent.height < 1) { + if (region.texExtent.width < 1 || region.texExtent.height < 1) { return; } region.texSubres.mipLevel = level; diff --git a/native/cocos/core/assets/TextureBase.h b/native/cocos/core/assets/TextureBase.h index 4486b34d02..853523f08a 100644 --- a/native/cocos/core/assets/TextureBase.h +++ b/native/cocos/core/assets/TextureBase.h @@ -26,10 +26,10 @@ #include #include "base/Ptr.h" +#include "base/std/container/unordered_map.h" #include "core/assets/Asset.h" #include "core/assets/AssetEnum.h" #include "renderer/gfx-base/GFXDef.h" -#include "base/std/container/unordered_map.h" #include "base/std/any.h" diff --git a/native/cocos/core/data/Object.h b/native/cocos/core/data/Object.h index 981ddbd753..6147fc07e2 100644 --- a/native/cocos/core/data/Object.h +++ b/native/cocos/core/data/Object.h @@ -121,7 +121,7 @@ public: }; static void deferredDestroy(); - + explicit CCObject(ccstd::string name = ""); ~CCObject() override; @@ -232,6 +232,7 @@ protected: public: Flags _objFlags{Flags::ZERO}; ccstd::string _name; + protected: se::Object* _scriptObject{nullptr}; // weak reference }; diff --git a/native/cocos/core/scene-graph/Node.cpp b/native/cocos/core/scene-graph/Node.cpp index 83702eb0a4..f69fc2cd58 100644 --- a/native/cocos/core/scene-graph/Node.cpp +++ b/native/cocos/core/scene-graph/Node.cpp @@ -55,15 +55,15 @@ Node::Node(const ccstd::string &name) { _active = 1; _isStatic = 0; _colorDirty = 1; - + #define NODE_SHARED_MEMORY_BYTE_LENGTH (36) #ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Winvalid-offsetof" + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Winvalid-offsetof" #endif static_assert(offsetof(Node, _finalOpacity) + sizeof(_finalOpacity) - offsetof(Node, _eventMask) == NODE_SHARED_MEMORY_BYTE_LENGTH, "Wrong shared memory size"); #ifdef __clang__ -#pragma clang diagnostic pop + #pragma clang diagnostic pop #endif _sharedMemoryActor.initialize(&_eventMask, NODE_SHARED_MEMORY_BYTE_LENGTH); #undef NODE_SHARED_MEMORY_BYTE_LENGTH @@ -480,9 +480,9 @@ void Node::updateLocalMatrixBySkew(Mat4 *outLocalMatrix) const { if (_skewX == 0 && _skewY == 0) { return; } - + float *m = outLocalMatrix->m; - + if (_skewType == static_cast(SkewType::ROTATIONAL)) { const float radiansX = -mathutils::toRadian(_skewX); const float radiansY = mathutils::toRadian(_skewY); @@ -546,7 +546,7 @@ void Node::updateWorldTransformRecursive(uint32_t &dirtyBits) { // NOLINT(misc-n // Save the original world matrix without skew side effect. Mat4::multiply(tempMat4, localMatrix, &tempMat4); originalWorldMatrix = &tempMat4; - + if (_skewType != static_cast(SkewType::NONE)) { updateLocalMatrixBySkew(&localMatrix); } @@ -582,7 +582,7 @@ void Node::updateWorldTransformRecursive(uint32_t &dirtyBits) { // NOLINT(misc-n } } } - + _transformFlags = (static_cast(TransformBit::NONE)); } @@ -691,43 +691,43 @@ void Node::setWorldScale(float x, float y, float z) { TransformBit rotationFlag = TransformBit::NONE; if (_parent != nullptr) { updateWorldTransform(); // ensure reentryability - + if (_skewType != static_cast(SkewType::NONE)) { Mat4::fromRTS(_localRotation, _localPosition, _localScale, &_worldMatrix); Mat4::multiply(_parent->_worldMatrix, _worldMatrix, &_worldMatrix); } - + float *m = _worldMatrix.m; Vec3 oldWorldScale(Vec3(m[0], m[1], m[2]).length(), Vec3(m[4], m[5], m[6]).length(), Vec3(m[8], m[9], m[10]).length()); - + _worldScale.set(x, y, z); Mat3 localRS; Mat3 localRotInv; Mat4 worldMatrixTmp = _worldMatrix; Vec3 rescaleFactor; - + if (oldWorldScale.x == 0) { oldWorldScale.x = 1; worldMatrixTmp.m[0] = 1.F; rotationFlag = TransformBit::ROTATION; } - + if (oldWorldScale.y == 0) { oldWorldScale.y = 1; worldMatrixTmp.m[5] = 1.F; rotationFlag = TransformBit::ROTATION; } - + if (oldWorldScale.z == 0) { oldWorldScale.z = 1; worldMatrixTmp.m[10] = 1.F; rotationFlag = TransformBit::ROTATION; } - + rescaleFactor = _worldScale / oldWorldScale; - + // apply new world scale to temp world matrix worldMatrixTmp.scale(rescaleFactor); // need opt // get temp local matrix @@ -742,7 +742,7 @@ void Node::setWorldScale(float x, float y, float z) { _localScale.x = Vec3{localRS.m[0], localRS.m[1], localRS.m[2]}.length(); _localScale.y = Vec3{localRS.m[3], localRS.m[4], localRS.m[5]}.length(); _localScale.z = Vec3{localRS.m[6], localRS.m[7], localRS.m[8]}.length(); - + if (_localScale.x == 0 || _localScale.y == 0 || _localScale.z == 0) { rotationFlag = TransformBit::ROTATION; } @@ -793,7 +793,7 @@ bool Node::findSkewAndGetOriginalWorldMatrix(Node *node, Mat4 *out) { if (!node) { return false; } - static ccstd::vector tempNodes; + static ccstd::vector tempNodes; tempNodes.resize(0); auto &ancestors = tempNodes; Node *startNode = nullptr; @@ -853,14 +853,14 @@ void Node::onSetParent(Node *oldParent, bool keepWorldTransform) { // Calculate current node's world matrix without skew side effect. Mat4::multiply(oldParentMatrix, localMatrix, &_worldMatrix); } - + // Calculate new parent's world matrix without skew side effect. const bool foundSkewInNewParent = Node::findSkewAndGetOriginalWorldMatrix(_parent, &tempMatrix); if (foundSkewInNewParent) { newParentMatrix = &tempMatrix; } } - + // Calculate current node's new local transform localMatrix = newParentMatrix->getInversed() * _worldMatrix; Mat4::toRTS(localMatrix, &_localRotation, &_localPosition, &_localScale); diff --git a/native/cocos/core/scene-graph/Node.h b/native/cocos/core/scene-graph/Node.h index 60a16cb56c..e49e1351d4 100644 --- a/native/cocos/core/scene-graph/Node.h +++ b/native/cocos/core/scene-graph/Node.h @@ -135,7 +135,7 @@ public: static void resetChangedFlags(); static void clearNodeArray(); - + static void _incSkewCompCount(); // NOLINT static void _decSkewCompCount(); // NOLINT @@ -601,14 +601,14 @@ public: void _setChildren(ccstd::vector> &&children); // NOLINT inline se::Object *_getSharedArrayBufferObject() const { return _sharedMemoryActor.getSharedArrayBufferObject(); } // NOLINT - + inline float _getLocalOpacity() const { return _localOpacity; } // NOLINT - + inline float _getFinalOpacity() const { return _finalOpacity; } // NOLINT - inline void _setFinalOpacity(float v) { _finalOpacity = v; } // NOLINT - + inline void _setFinalOpacity(float v) { _finalOpacity = v; } // NOLINT + inline bool _isColorDirty() const { return _colorDirty == 0 ? false : true; } // NOLINT - inline void _setColorDirty(bool v) { _colorDirty = v ? 1 : 0; } // NOLINT + inline void _setColorDirty(bool v) { _colorDirty = v ? 1 : 0; } // NOLINT bool onPreDestroy() override; bool onPreDestroyBase(); @@ -680,7 +680,7 @@ public: // For deserialization ccstd::string _id; Node *_parent{nullptr}; - + private: Scene *_scene{nullptr}; IntrusivePtr _userData; @@ -701,28 +701,28 @@ private: // Shared memory with JS // NOTE: TypeArray created in node.jsb.ts _ctor should have the same memory layout - uint32_t _eventMask{0}; // Uint32: 0 - uint32_t _layer{static_cast(Layers::LayerList::DEFAULT)}; // Uint32: 1 + uint32_t _eventMask{0}; // Uint32: 0 + uint32_t _layer{static_cast(Layers::LayerList::DEFAULT)}; // Uint32: 1 uint32_t _transformFlags{static_cast(TransformBit::TRS | TransformBit::SKEW)}; // Uint32: 2 - index_t _siblingIndex{0}; // Int32: 0 - uint8_t _activeInHierarchy: 1; // Uint8: 0:0 - uint8_t _active: 1; // Uint8: 0:1 - uint8_t _isStatic: 1; // Uint8: 0:2 - uint8_t _colorDirty: 1; // Uint8: 0:3 - uint8_t _boolBitPaddings: 4; // Uint8: 0:4~7 - uint8_t _skewType{static_cast(SkewType::NONE)}; // Uint8: 1 - uint8_t _u8Paddings[2]; // Uint8: 2, 3 - float _skewX{.0F}; // Float32: 0 - float _skewY{.0F}; // Float32: 1 - float _localOpacity{1.F}; // Float32: 2 - float _finalOpacity{1.F}; // Float32: 3 + index_t _siblingIndex{0}; // Int32: 0 + uint8_t _activeInHierarchy : 1; // Uint8: 0:0 + uint8_t _active : 1; // Uint8: 0:1 + uint8_t _isStatic : 1; // Uint8: 0:2 + uint8_t _colorDirty : 1; // Uint8: 0:3 + uint8_t _boolBitPaddings : 4; // Uint8: 0:4~7 + uint8_t _skewType{static_cast(SkewType::NONE)}; // Uint8: 1 + uint8_t _u8Paddings[2]; // Uint8: 2, 3 + float _skewX{.0F}; // Float32: 0 + float _skewY{.0F}; // Float32: 1 + float _localOpacity{1.F}; // Float32: 2 + float _finalOpacity{1.F}; // Float32: 3 /* set _hasChangedFlagsVersion to globalFlagChangeVersion when `_hasChangedFlags` updated. * `globalFlagChangeVersion == _hasChangedFlagsVersion` means that "_hasChangedFlags is dirty in current frametime". */ uint32_t _hasChangedFlagsVersion{0}; uint32_t _hasChangedFlags{0}; - + public: MobilityMode _mobility = MobilityMode::Static; diff --git a/native/cocos/core/scene-graph/SceneGlobals.cpp b/native/cocos/core/scene-graph/SceneGlobals.cpp index 6947fcbb5b..78ffaea792 100644 --- a/native/cocos/core/scene-graph/SceneGlobals.cpp +++ b/native/cocos/core/scene-graph/SceneGlobals.cpp @@ -30,10 +30,10 @@ #include "scene/Ambient.h" #include "scene/Fog.h" #include "scene/Octree.h" +#include "scene/PostSettings.h" #include "scene/Shadow.h" #include "scene/Skin.h" #include "scene/Skybox.h" -#include "scene/PostSettings.h" namespace cc { diff --git a/native/cocos/editor-support/MiddlewareManager.cpp b/native/cocos/editor-support/MiddlewareManager.cpp index 6325028685..933d53f94b 100644 --- a/native/cocos/editor-support/MiddlewareManager.cpp +++ b/native/cocos/editor-support/MiddlewareManager.cpp @@ -57,8 +57,8 @@ MeshBuffer *MiddlewareManager::getMeshBuffer(int format) { void MiddlewareManager::updateOperateCache() { if (_operateCacheQueue.empty()) return; - ccstd::vector seen; - ccstd::vector> finalOperations; + ccstd::vector seen; + ccstd::vector> finalOperations; for (auto it = _operateCacheQueue.rbegin(); it != _operateCacheQueue.rend(); ++it) { if (std::find(seen.begin(), seen.end(), it->first) == seen.end()) { seen.push_back(it->first); @@ -99,10 +99,10 @@ void MiddlewareManager::update(float dt) { } void MiddlewareManager::render(float dt) { - ccstd::vector skipRenderList; + ccstd::vector skipRenderList; if (!_operateCacheQueue.empty()) { - ccstd::vector seen; - // Object._deferredDestroy is called after component update in Director.tick and before emitting BEFORE_DRAW event in which MiddlewareManager::render is invoked, + ccstd::vector seen; + // Object._deferredDestroy is called after component update in Director.tick and before emitting BEFORE_DRAW event in which MiddlewareManager::render is invoked, // so the native object may be released here. // We shouldn't execute editor->render(dt) if it's already removed in _operateCacheQueue. for (auto it = _operateCacheQueue.rbegin(); it != _operateCacheQueue.rend(); ++it) { diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonAnimation.cpp b/native/cocos/editor-support/spine-creator-support/SkeletonAnimation.cpp index f7da60aef7..e7fe42d6e5 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonAnimation.cpp +++ b/native/cocos/editor-support/spine-creator-support/SkeletonAnimation.cpp @@ -49,7 +49,7 @@ void animationCallback(AnimationState *state, EventType type, TrackEntry *entry, auto *skeletonAnimation = static_cast(state->getRendererObject()); skeletonAnimation->cacheAnimationEvent(entry, type, event); if (type == EventType::EventType_Dispose) { - /** + /** * In the official implementation of Spine's AnimationState class, the animationCallback is invoked after the trackEntryCallback. * After the AnimationState completes the EventType_Dispose callback, the TrackEntry will be reclaimed, so this event must be dispatched immediately. */ diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonAnimation.h b/native/cocos/editor-support/spine-creator-support/SkeletonAnimation.h index b06969da8d..f25f34f361 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonAnimation.h +++ b/native/cocos/editor-support/spine-creator-support/SkeletonAnimation.h @@ -28,16 +28,16 @@ *****************************************************************************/ #pragma once +#include #include "spine-creator-support/SkeletonRenderer.h" #include "spine/spine.h" -#include namespace cc { struct CacheEventInfo { - spine::EventType type{spine::EventType::EventType_Start}; - spine::TrackEntry *entry{nullptr}; - spine::Event *event{nullptr}; + spine::EventType type{spine::EventType::EventType_Start}; + spine::TrackEntry *entry{nullptr}; + spine::Event *event{nullptr}; }; typedef std::function StartListener; typedef std::function InterruptListener; diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonCache.cpp b/native/cocos/editor-support/spine-creator-support/SkeletonCache.cpp index e348fc2b03..09307c3096 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonCache.cpp +++ b/native/cocos/editor-support/spine-creator-support/SkeletonCache.cpp @@ -28,9 +28,9 @@ *****************************************************************************/ #include "SkeletonCache.h" +#include "SkeletonDataMgr.h" #include "base/memory/Memory.h" #include "spine-creator-support/AttachmentVertices.h" -#include "SkeletonDataMgr.h" USING_NS_MW; // NOLINT(google-build-using-namespace) using namespace cc; // NOLINT(google-build-using-namespace) @@ -316,7 +316,6 @@ void SkeletonCache::renderAnimationFrame(AnimationData *animationData) { matm[13] = bone->getWorldY(); } - auto *skeletonDataInfo = SkeletonDataMgr::getInstance()->getSkeletonDataInfo(_uuid); if (!skeletonDataInfo) return; auto &attachmentVerticesMap = skeletonDataInfo->attachmentVerticesMap; diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonCacheAnimation.h b/native/cocos/editor-support/spine-creator-support/SkeletonCacheAnimation.h index 884691a3b9..884f136079 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonCacheAnimation.h +++ b/native/cocos/editor-support/spine-creator-support/SkeletonCacheAnimation.h @@ -39,7 +39,7 @@ namespace cc { class RenderEntity; class RenderDrawInfo; class Material; -}; +}; // namespace cc namespace cc { @@ -104,7 +104,8 @@ public: cc::RenderDrawInfo *requestDrawInfo(int idx); cc::Material *requestMaterial(uint16_t blendSrc, uint16_t blendDst); void setMaterial(cc::Material *material); - void setRenderEntity(cc::RenderEntity* entity); + void setRenderEntity(cc::RenderEntity *entity); + private: float _timeScale = 1; bool _paused = false; @@ -140,7 +141,7 @@ private: cc::RenderEntity *_entity = nullptr; cc::Material *_material = nullptr; ccstd::vector _drawInfoArray; - ccstd::unordered_map _materialCaches; + ccstd::unordered_map _materialCaches; bool _needClearMaterialCaches = false; }; } // namespace cc diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonDataMgr.cpp b/native/cocos/editor-support/spine-creator-support/SkeletonDataMgr.cpp index eb840f66d3..ff6168c921 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonDataMgr.cpp +++ b/native/cocos/editor-support/spine-creator-support/SkeletonDataMgr.cpp @@ -33,8 +33,7 @@ #include "AttachmentVertices.h" using namespace spine; //NOLINT -using namespace cc; //NOLINT - +using namespace cc; //NOLINT static uint16_t quadTriangles[6] = {0, 1, 2, 2, 3, 0}; diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonDataMgr.h b/native/cocos/editor-support/spine-creator-support/SkeletonDataMgr.h index bf687c2638..0e97fd74ca 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonDataMgr.h +++ b/native/cocos/editor-support/spine-creator-support/SkeletonDataMgr.h @@ -32,8 +32,8 @@ #include #include #include -#include #include +#include #include "AttachmentVertices.h" #include "base/RefCounted.h" #include "spine/SkeletonData.h" @@ -44,7 +44,6 @@ namespace cc { class AttachmentVertices; - class SkeletonDataInfo { public: SkeletonDataInfo() = default; @@ -94,7 +93,7 @@ public: _destroyCallback = std::move(callback); } - std::vector getSkeletonDataInfos() const; + std::vector getSkeletonDataInfos() const; private: static SkeletonDataMgr *instance; diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.cpp b/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.cpp index f3109253f1..0cadab4ab1 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.cpp +++ b/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.cpp @@ -44,7 +44,6 @@ #include "spine-creator-support/AttachmentVertices.h" #include "spine-creator-support/spine-cocos2dx.h" - USING_NS_MW; // NOLINT(google-build-using-namespace) using namespace spine; // NOLINT(google-build-using-namespace) using namespace cc; // NOLINT(google-build-using-namespace) @@ -190,7 +189,7 @@ SkeletonRenderer::~SkeletonRenderer() { CC_SAFE_DELETE(item.second); } - for (auto iter: _slotTextureSet) { + for (auto iter : _slotTextureSet) { auto &info = iter.second; releaseSlotCacheInfo(info); } @@ -424,7 +423,7 @@ void SkeletonRenderer::render(float /*deltaTime*/) { effect->begin(*_skeleton); } #else - void *effect = nullptr; + void *effect = nullptr; #endif auto *skeletonDataInfo = SkeletonDataMgr::getInstance()->getSkeletonDataInfo(_uuid); @@ -821,7 +820,7 @@ void SkeletonRenderer::render(float /*deltaTime*/) { } else { curTexture = nullptr; } - + // If texture or blendMode change,will change material. if (preTexture != curTexture || preBlendMode != slot->getData().getBlendMode() || isFull) { flush(); diff --git a/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.h b/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.h index 96c3129787..e2eb5bee67 100644 --- a/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.h +++ b/native/cocos/editor-support/spine-creator-support/SkeletonRenderer.h @@ -39,7 +39,7 @@ #include "core/assets/Texture2D.h" #include "middleware-adapter.h" #if CC_USE_SPINE_3_8 -#include "spine-creator-support/VertexEffectDelegate.h" + #include "spine-creator-support/VertexEffectDelegate.h" #endif #include "spine/spine.h" @@ -50,7 +50,6 @@ class Material; class AttachmentVertices; - template void loopUVCoords(VertexType *tmp, const UVArrayType &uvs, int count) { for (int i = 0, ii = 0; i < count; ++i, ii += 2) { diff --git a/native/cocos/editor-support/spine-creator-support/Vector2.cpp b/native/cocos/editor-support/spine-creator-support/Vector2.cpp index bac1dfcaea..b58fa884e2 100644 --- a/native/cocos/editor-support/spine-creator-support/Vector2.cpp +++ b/native/cocos/editor-support/spine-creator-support/Vector2.cpp @@ -2,8 +2,7 @@ #include namespace spine { -Vector2::Vector2(): x(0), y(0) { - +Vector2::Vector2() : x(0), y(0) { } Vector2::Vector2(float x, float y) { @@ -16,7 +15,7 @@ Vector2::~Vector2() {} void Vector2::setX(float x) { this->x = x; } - + float Vector2::getX() const { return x; } @@ -45,4 +44,4 @@ Vector2& Vector2::normalize() { this->setY(y * invLen); return *this; } -} \ No newline at end of file +} // namespace spine \ No newline at end of file diff --git a/native/cocos/editor-support/spine-creator-support/Vector2.h b/native/cocos/editor-support/spine-creator-support/Vector2.h index 24842bad4f..edd0989227 100644 --- a/native/cocos/editor-support/spine-creator-support/Vector2.h +++ b/native/cocos/editor-support/spine-creator-support/Vector2.h @@ -32,23 +32,23 @@ #include "spine/spine.h" namespace spine { - class Vector2 - { - public: - float x, y; - public: - Vector2(); - Vector2(float x, float y); - ~Vector2(); +class Vector2 { +public: + float x, y; - void setX(float x); - float getX() const; +public: + Vector2(); + Vector2(float x, float y); + ~Vector2(); - void setY(float y); - float getY() const; + void setX(float x); + float getX() const; - Vector2 &set(float x, float y); - float length() const; - Vector2 &normalize(); - }; -} \ No newline at end of file + void setY(float y); + float getY() const; + + Vector2 &set(float x, float y); + float length() const; + Vector2 &normalize(); +}; +} // namespace spine \ No newline at end of file diff --git a/native/cocos/editor-support/spine-creator-support/VertexEffectDelegate.cpp b/native/cocos/editor-support/spine-creator-support/VertexEffectDelegate.cpp index 688261fc13..94b5d7cd7c 100644 --- a/native/cocos/editor-support/spine-creator-support/VertexEffectDelegate.cpp +++ b/native/cocos/editor-support/spine-creator-support/VertexEffectDelegate.cpp @@ -27,8 +27,8 @@ * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ -#include "VertexEffectDelegate.h" - +#include "VertexEffectDelegate.h" + namespace cc { VertexEffectDelegate::VertexEffectDelegate() { diff --git a/native/cocos/engine/Engine.cpp b/native/cocos/engine/Engine.cpp index 07890fea49..cdb4749693 100644 --- a/native/cocos/engine/Engine.cpp +++ b/native/cocos/engine/Engine.cpp @@ -116,10 +116,7 @@ namespace cc { /** static */ bool Engine::isValid() { - return CC_CURRENT_APPLICATION() - && CC_CURRENT_ENGINE() - && se::ScriptEngine::getInstance() - && se::ScriptEngine::getInstance()->isValid(); + return CC_CURRENT_APPLICATION() && CC_CURRENT_ENGINE() && se::ScriptEngine::getInstance() && se::ScriptEngine::getInstance()->isValid(); } Engine::Engine() { @@ -215,10 +212,10 @@ void Engine::destroy() { if (cc::render::getRenderingModule()) { cc::render::Factory::destroy(cc::render::getRenderingModule()); } - #if (SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSVM) - // When using JSVM, not all objects are destroyed during cleanup, so we need to close JSVM at the end. - _scriptEngine->closeEngine(); - #endif +#if (SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSVM) + // When using JSVM, not all objects are destroyed during cleanup, so we need to close JSVM at the end. + _scriptEngine->closeEngine(); +#endif CC_SAFE_DESTROY_AND_DELETE(_gfxDevice); delete _fs; @@ -319,10 +316,10 @@ void Engine::tick() { cc::DeferredReleasePool::clear(); if (_xr) _xr->endRenderFrame(); - + // Executing async tasks at the end of the current frame to make the callback invoked as soon as possible. _scheduler->runFunctionsToBePerformedInCocosThread(); - + now = std::chrono::steady_clock::now(); dtNS = dtNS * 0.1 + 0.9 * static_cast(std::chrono::duration_cast(now - prevTime).count()); dt = static_cast(dtNS) / NANOSECONDS_PER_SECOND; diff --git a/native/cocos/gi/light-probe/LightProbe.cpp b/native/cocos/gi/light-probe/LightProbe.cpp index 3593410486..c35d276972 100644 --- a/native/cocos/gi/light-probe/LightProbe.cpp +++ b/native/cocos/gi/light-probe/LightProbe.cpp @@ -312,7 +312,7 @@ void LightProbeInfo::onProbeBakingChanged(Node *node) { // NOLINT(misc-no-recurs node->emit(); const auto &children = node->getChildren(); - for (const auto &child: children) { + for (const auto &child : children) { onProbeBakingChanged(child); } } diff --git a/native/cocos/network/HttpClient.cpp b/native/cocos/network/HttpClient.cpp index b7a0ae9dea..bb41265040 100644 --- a/native/cocos/network/HttpClient.cpp +++ b/native/cocos/network/HttpClient.cpp @@ -134,7 +134,6 @@ void HttpClient::networkThread() { // Worker thread void HttpClient::networkThreadAlone(HttpRequest *request, HttpResponse *response) { - char responseMessage[RESPONSE_BUFFER_SIZE] = {0}; processResponse(response, responseMessage); @@ -521,12 +520,12 @@ void HttpClient::processResponse(HttpResponse *response, char *responseMessage) case HttpRequest::Type::PATCH: retValue = processPatchTask(this, request, - writeData, - response->getResponseData(), - &responseCode, - writeHeaderData, - response->getResponseHeader(), - responseMessage); + writeData, + response->getResponseData(), + &responseCode, + writeHeaderData, + response->getResponseHeader(), + responseMessage); break; default: diff --git a/native/cocos/network/WebSocket-libwebsockets.cpp b/native/cocos/network/WebSocket-libwebsockets.cpp index 9b73394d44..cbc7c9c234 100644 --- a/native/cocos/network/WebSocket-libwebsockets.cpp +++ b/native/cocos/network/WebSocket-libwebsockets.cpp @@ -463,9 +463,9 @@ void WsThreadHelper::onSubThreadLoop() { // Android: Let libuv lws to decide when to stop wsPolling = true; lws_service(wsContext, WS_ENABLE_LIBUV ? 40 : 4); - #if CC_PLATFORM == CC_PLATFORM_OPENHARMONY - std::this_thread::sleep_for(std::chrono::milliseconds(3)); - #endif +#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY + std::this_thread::sleep_for(std::chrono::milliseconds(3)); +#endif wsPolling = false; } } diff --git a/native/cocos/network/WebSocket-okhttp.cpp b/native/cocos/network/WebSocket-okhttp.cpp index a4f165e199..97da74f22e 100644 --- a/native/cocos/network/WebSocket-okhttp.cpp +++ b/native/cocos/network/WebSocket-okhttp.cpp @@ -28,9 +28,9 @@ #include "base/Scheduler.h" #include "base/UTF8.h" #include "base/memory/Memory.h" +#include "engine/Engine.h" #include "platform/FileUtils.h" #include "platform/java/jni/JniHelper.h" -#include "engine/Engine.h" #ifdef JAVA_CLASS_WEBSOCKET #error "JAVA_CLASS_WEBSOCKET is already defined" diff --git a/native/cocos/physics/PhysicsSDK.h b/native/cocos/physics/PhysicsSDK.h index c225526cba..7c5caf01fd 100644 --- a/native/cocos/physics/PhysicsSDK.h +++ b/native/cocos/physics/PhysicsSDK.h @@ -24,8 +24,8 @@ #pragma once +#include "physics/sdk/CharacterController.h" #include "physics/sdk/Joint.h" #include "physics/sdk/RigidBody.h" #include "physics/sdk/Shape.h" #include "physics/sdk/World.h" -#include "physics/sdk/CharacterController.h" diff --git a/native/cocos/physics/physx/PhysXEventManager.cpp b/native/cocos/physics/physx/PhysXEventManager.cpp index 9733819747..a0f1e82e85 100644 --- a/native/cocos/physics/physx/PhysXEventManager.cpp +++ b/native/cocos/physics/physx/PhysXEventManager.cpp @@ -173,15 +173,13 @@ void PhysXEventManager::refreshPairs() { continue; } - const auto& cctIter = getPxCCTMap().find(reinterpret_cast(&(reinterpret_cast(wrapperPtrCCT)->getCCT()))); - const auto& shapeIter = getPxShapeMap().find(reinterpret_cast(&(reinterpret_cast(wrapperPtrShape)->getShape()))); + const auto &cctIter = getPxCCTMap().find(reinterpret_cast(&(reinterpret_cast(wrapperPtrCCT)->getCCT()))); + const auto &shapeIter = getPxShapeMap().find(reinterpret_cast(&(reinterpret_cast(wrapperPtrShape)->getShape()))); if (cctIter == getPxCCTMap().end() || shapeIter == getPxShapeMap().end()) { iter = getCCTTriggerPairs().erase(iter); - } - else if (iter->get()->state == ETouchState::EXIT) { + } else if (iter->get()->state == ETouchState::EXIT) { iter = getCCTTriggerPairs().erase(iter); - } - else { + } else { iter->get()->state = ETouchState::STAY; iter++; } diff --git a/native/cocos/physics/physx/PhysXEventManager.h b/native/cocos/physics/physx/PhysXEventManager.h index 6cc2f0d000..f071f1b835 100644 --- a/native/cocos/physics/physx/PhysXEventManager.h +++ b/native/cocos/physics/physx/PhysXEventManager.h @@ -59,8 +59,8 @@ public: inline SimulationEventCallback &getEventCallback() { return *_mCallback; } inline ccstd::vector> &getTriggerPairs() { return _mTriggerPairs; } - inline ccstd::vector>& getConatctPairs() { return _mConatctPairs; } - inline ccstd::vector>& getCCTShapePairs() { return _mCCTShapePairs; } + inline ccstd::vector> &getConatctPairs() { return _mConatctPairs; } + inline ccstd::vector> &getCCTShapePairs() { return _mCCTShapePairs; } inline ccstd::vector> &getCCTTriggerPairs() { return _mCCTTriggerPairs; } void refreshPairs(); diff --git a/native/cocos/physics/physx/PhysXUtils.h b/native/cocos/physics/physx/PhysXUtils.h index 59a79a771c..76bcebb673 100644 --- a/native/cocos/physics/physx/PhysXUtils.h +++ b/native/cocos/physics/physx/PhysXUtils.h @@ -27,11 +27,11 @@ #include "base/Macros.h" #include "base/std/container/unordered_map.h" #include "base/std/container/vector.h" -#include "renderer/pipeline/Define.h" #include "math/Vec3.h" #include "math/Vec4.h" #include "physics/physx/PhysXFilterShader.h" #include "physics/physx/PhysXInc.h" +#include "renderer/pipeline/Define.h" #define PX_RELEASE(x) \ if (x) { \ @@ -117,10 +117,10 @@ inline void pxSetQuatExt(T1 &p, const T2 &cp) { p = T1(cp.x, cp.y, cp.z, cp.w); } -inline void pxSetColor(gfx::Color& color, physx::PxU32 rgba) { +inline void pxSetColor(gfx::Color &color, physx::PxU32 rgba) { color.z = ((rgba >> 16) & 0xff); color.y = ((rgba >> 8) & 0xff); - color.x = ((rgba) & 0xff); + color.x = ((rgba)&0xff); color.w = 255; } @@ -137,7 +137,7 @@ inline ccstd::unordered_map &getPxShapeMap() { } //physx::PxCharacterController ptr <--> PhysxCharacterController ObjectID -inline ccstd::unordered_map& getPxCCTMap() { +inline ccstd::unordered_map &getPxCCTMap() { static ccstd::unordered_map m; return m; } diff --git a/native/cocos/physics/physx/PhysXWorld.cpp b/native/cocos/physics/physx/PhysXWorld.cpp index 261ce66453..1d6cee3992 100644 --- a/native/cocos/physics/physx/PhysXWorld.cpp +++ b/native/cocos/physics/physx/PhysXWorld.cpp @@ -24,16 +24,16 @@ #include "physics/physx/PhysXWorld.h" #include "base/memory/Memory.h" +#include "core/Root.h" #include "physics/physx/PhysXFilterShader.h" #include "physics/physx/PhysXInc.h" #include "physics/physx/PhysXUtils.h" #include "physics/physx/joints/PhysXJoint.h" #include "physics/spec/IWorld.h" -#include "core/Root.h" -#include "scene/Camera.h" -#include "scene/RenderWindow.h" #include "renderer/pipeline/Define.h" #include "renderer/pipeline/RenderPipeline.h" +#include "scene/Camera.h" +#include "scene/RenderWindow.h" namespace cc { namespace physics { @@ -133,9 +133,9 @@ void PhysXWorld::step(float fixedTimeStep) { } #if CC_USE_GEOMETRY_RENDERER -pipeline::GeometryRenderer* PhysXWorld::getDebugRenderer () { +pipeline::GeometryRenderer *PhysXWorld::getDebugRenderer() { auto cameras = Root::getInstance()->getMainWindow()->getCameras(); - scene::Camera* camera = nullptr; + scene::Camera *camera = nullptr; for (int c = 0; c < cameras.size(); c++) { if (!cameras[c]) continue; @@ -154,29 +154,29 @@ pipeline::GeometryRenderer* PhysXWorld::getDebugRenderer () { return nullptr; } -void PhysXWorld::debugDraw () { - pipeline::GeometryRenderer* debugRenderer = getDebugRenderer(); +void PhysXWorld::debugDraw() { + pipeline::GeometryRenderer *debugRenderer = getDebugRenderer(); if (!debugRenderer) return; _debugLineCount = 0; static Vec3 v0, v1; static gfx::Color c; - auto& rb = _mScene->getRenderBuffer(); + auto &rb = _mScene->getRenderBuffer(); // lines for (int i = 0; i < rb.getNbLines(); i++) { - if (_debugLineCount < _MAX_DEBUG_LINE_COUNT){ + if (_debugLineCount < _MAX_DEBUG_LINE_COUNT) { _debugLineCount++; - const physx::PxDebugLine& line = rb.getLines()[i]; + const physx::PxDebugLine &line = rb.getLines()[i]; pxSetColor(c, line.color0); pxSetVec3Ext(v0, line.pos0); pxSetVec3Ext(v1, line.pos1); debugRenderer->addLine(v0, v1, c); - } + } } // triangles for (int i = 0; i < rb.getNbTriangles(); i++) { if (_debugLineCount < _MAX_DEBUG_LINE_COUNT - 3) { _debugLineCount = _debugLineCount + 3; - const physx::PxDebugTriangle& triangle = rb.getTriangles()[i]; + const physx::PxDebugTriangle &triangle = rb.getTriangles()[i]; pxSetColor(c, triangle.color0); pxSetVec3Ext(v0, triangle.pos0); pxSetVec3Ext(v1, triangle.pos1); @@ -379,7 +379,7 @@ void PhysXWorld::removeActor(const PhysXSharedBody &sb) { } } -void PhysXWorld::addCCT (const PhysXCharacterController &cct) { +void PhysXWorld::addCCT(const PhysXCharacterController &cct) { auto beg = _mCCTs.begin(); auto end = _mCCTs.end(); auto iter = find(beg, end, &cct); @@ -388,7 +388,7 @@ void PhysXWorld::addCCT (const PhysXCharacterController &cct) { } } -void PhysXWorld::removeCCT(const PhysXCharacterController&cct) { +void PhysXWorld::removeCCT(const PhysXCharacterController &cct) { auto beg = _mCCTs.begin(); auto end = _mCCTs.end(); auto iter = find(beg, end, &cct); @@ -467,39 +467,39 @@ RaycastResult &PhysXWorld::raycastClosestResult() { } bool PhysXWorld::sweepBox(RaycastOptions &opt, float halfExtentX, float halfExtentY, float halfExtentZ, - float orientationW, float orientationX, float orientationY, float orientationZ) { - return sweep(opt, physx::PxBoxGeometry{ halfExtentX, halfExtentY, halfExtentZ}, - physx::PxQuat(orientationX, orientationY, orientationZ, orientationW)); + float orientationW, float orientationX, float orientationY, float orientationZ) { + return sweep(opt, physx::PxBoxGeometry{halfExtentX, halfExtentY, halfExtentZ}, + physx::PxQuat(orientationX, orientationY, orientationZ, orientationW)); } bool PhysXWorld::sweepBoxClosest(RaycastOptions &opt, float halfExtentX, float halfExtentY, float halfExtentZ, - float orientationW, float orientationX, float orientationY, float orientationZ) { - return sweepClosest(opt, physx::PxBoxGeometry{ halfExtentX, halfExtentY, halfExtentZ}, - physx::PxQuat(orientationX, orientationY, orientationZ, orientationW)); + float orientationW, float orientationX, float orientationY, float orientationZ) { + return sweepClosest(opt, physx::PxBoxGeometry{halfExtentX, halfExtentY, halfExtentZ}, + physx::PxQuat(orientationX, orientationY, orientationZ, orientationW)); } bool PhysXWorld::sweepSphere(RaycastOptions &opt, float radius) { - return sweep(opt, physx::PxSphereGeometry{ radius }, physx::PxQuat(0, 0, 0, 1)); + return sweep(opt, physx::PxSphereGeometry{radius}, physx::PxQuat(0, 0, 0, 1)); } bool PhysXWorld::sweepSphereClosest(RaycastOptions &opt, float radius) { - return sweepClosest(opt, physx::PxSphereGeometry{ radius }, physx::PxQuat(0, 0, 0, 1)); + return sweepClosest(opt, physx::PxSphereGeometry{radius}, physx::PxQuat(0, 0, 0, 1)); } bool PhysXWorld::sweepCapsule(RaycastOptions &opt, float radius, float height, - float orientationW, float orientationX, float orientationY, float orientationZ) { + float orientationW, float orientationX, float orientationY, float orientationZ) { //add an extra 90 degree rotation to PxCapsuleGeometry whose axis is originally along the X axis physx::PxQuat finalOrientation = physx::PxQuat(physx::PxPiDivTwo, physx::PxVec3{0.F, 0.F, 1.F}); finalOrientation = physx::PxQuat(orientationX, orientationY, orientationZ, orientationW) * finalOrientation; - return sweep(opt, physx::PxCapsuleGeometry{ radius, height/2.f }, finalOrientation); + return sweep(opt, physx::PxCapsuleGeometry{radius, height / 2.f}, finalOrientation); } bool PhysXWorld::sweepCapsuleClosest(RaycastOptions &opt, float radius, float height, - float orientationW, float orientationX, float orientationY, float orientationZ) { + float orientationW, float orientationX, float orientationY, float orientationZ) { //add an extra 90 degree rotation to PxCapsuleGeometry whose axis is originally along the X axis physx::PxQuat finalOrientation = physx::PxQuat(physx::PxPiDivTwo, physx::PxVec3{0.F, 0.F, 1.F}); finalOrientation = physx::PxQuat(orientationX, orientationY, orientationZ, orientationW) * finalOrientation; - return sweepClosest(opt, physx::PxCapsuleGeometry{ radius, height/2.f }, finalOrientation); + return sweepClosest(opt, physx::PxCapsuleGeometry{radius, height / 2.f}, finalOrientation); } bool PhysXWorld::sweep(RaycastOptions &opt, const physx::PxGeometry &geometry, const physx::PxQuat &orientation) { diff --git a/native/cocos/physics/physx/character-controllers/PhysXBoxCharacterController.cpp b/native/cocos/physics/physx/character-controllers/PhysXBoxCharacterController.cpp index 83a13f93ac..c40eabc6ab 100644 --- a/native/cocos/physics/physx/character-controllers/PhysXBoxCharacterController.cpp +++ b/native/cocos/physics/physx/character-controllers/PhysXBoxCharacterController.cpp @@ -23,14 +23,13 @@ ****************************************************************************/ #include "physics/physx/character-controllers/PhysXBoxCharacterController.h" +#include "math/Utils.h" #include "physics/physx/PhysXUtils.h" #include "physics/physx/PhysXWorld.h" -#include "math/Utils.h" namespace cc { namespace physics { -PhysXBoxCharacterController::PhysXBoxCharacterController() : -_mHalfHeight(0.5F), _mHalfSideExtent(0.5F), _mHalfForwardExtent(0.5F) { +PhysXBoxCharacterController::PhysXBoxCharacterController() : _mHalfHeight(0.5F), _mHalfSideExtent(0.5F), _mHalfForwardExtent(0.5F) { } void PhysXBoxCharacterController::setHalfHeight(float v) { @@ -55,7 +54,7 @@ void PhysXBoxCharacterController::onComponentSet() { void PhysXBoxCharacterController::create() { release(); - physx::PxControllerManager& controllerManager = PhysXWorld::getInstance().getControllerManager(); + physx::PxControllerManager &controllerManager = PhysXWorld::getInstance().getControllerManager(); auto pxMtl = reinterpret_cast(PhysXWorld::getInstance().getPXMaterialPtrWithMaterialID(0)); physx::PxBoxControllerDesc boxDesc; @@ -76,28 +75,28 @@ void PhysXBoxCharacterController::create() { boxDesc.material = pxMtl; boxDesc.userData = this; boxDesc.reportCallback = &report; - _impl = static_cast(controllerManager.createController(boxDesc)); + _impl = static_cast(controllerManager.createController(boxDesc)); updateScale(); insertToCCTMap(); updateFilterData(); } -void PhysXBoxCharacterController::updateScale(){ +void PhysXBoxCharacterController::updateScale() { updateGeometry(); } -void PhysXBoxCharacterController::updateGeometry(){ - if(!_impl) return; +void PhysXBoxCharacterController::updateGeometry() { + if (!_impl) return; auto *node = _mNode; node->updateWorldTransform(); float s = _mHalfSideExtent * physx::PxAbs(node->getWorldScale().x); float h = _mHalfHeight * physx::PxAbs(node->getWorldScale().y); float f = _mHalfForwardExtent * physx::PxAbs(node->getWorldScale().z); - static_cast(_impl)->setHalfSideExtent(physx::PxMax(s, PX_NORMALIZATION_EPSILON)); - static_cast(_impl)->setHalfHeight(physx::PxMax(h, PX_NORMALIZATION_EPSILON)); - static_cast(_impl)->setHalfForwardExtent(physx::PxMax(f, PX_NORMALIZATION_EPSILON)); + static_cast(_impl)->setHalfSideExtent(physx::PxMax(s, PX_NORMALIZATION_EPSILON)); + static_cast(_impl)->setHalfHeight(physx::PxMax(h, PX_NORMALIZATION_EPSILON)); + static_cast(_impl)->setHalfForwardExtent(physx::PxMax(f, PX_NORMALIZATION_EPSILON)); } } // namespace physics diff --git a/native/cocos/physics/physx/character-controllers/PhysXBoxCharacterController.h b/native/cocos/physics/physx/character-controllers/PhysXBoxCharacterController.h index 8e0833f095..51121909a1 100644 --- a/native/cocos/physics/physx/character-controllers/PhysXBoxCharacterController.h +++ b/native/cocos/physics/physx/character-controllers/PhysXBoxCharacterController.h @@ -33,7 +33,7 @@ class PhysXBoxCharacterController final : public PhysXCharacterController, publi public: PhysXBoxCharacterController(); ~PhysXBoxCharacterController() override = default; - + // IBoxCharacterController void setHalfHeight(float v) override; void setHalfSideExtent(float v) override; diff --git a/native/cocos/physics/physx/character-controllers/PhysXCapsuleCharacterController.cpp b/native/cocos/physics/physx/character-controllers/PhysXCapsuleCharacterController.cpp index f4801f6831..1ee3df34e5 100644 --- a/native/cocos/physics/physx/character-controllers/PhysXCapsuleCharacterController.cpp +++ b/native/cocos/physics/physx/character-controllers/PhysXCapsuleCharacterController.cpp @@ -23,14 +23,13 @@ ****************************************************************************/ #include "physics/physx/character-controllers/PhysXCapsuleCharacterController.h" +#include "math/Utils.h" #include "physics/physx/PhysXUtils.h" #include "physics/physx/PhysXWorld.h" -#include "math/Utils.h" namespace cc { namespace physics { -PhysXCapsuleCharacterController::PhysXCapsuleCharacterController() : -_mRadius(0.5F), _mHeight(1.0F) { +PhysXCapsuleCharacterController::PhysXCapsuleCharacterController() : _mRadius(0.5F), _mHeight(1.0F) { } void PhysXCapsuleCharacterController::setRadius(float v) { @@ -50,7 +49,7 @@ void PhysXCapsuleCharacterController::onComponentSet() { void PhysXCapsuleCharacterController::create() { release(); - physx::PxControllerManager& controllerManager = PhysXWorld::getInstance().getControllerManager(); + physx::PxControllerManager &controllerManager = PhysXWorld::getInstance().getControllerManager(); auto pxMtl = reinterpret_cast(PhysXWorld::getInstance().getPXMaterialPtrWithMaterialID(0)); physx::PxCapsuleControllerDesc capsuleDesc; @@ -71,26 +70,26 @@ void PhysXCapsuleCharacterController::create() { capsuleDesc.material = pxMtl; capsuleDesc.userData = this; capsuleDesc.reportCallback = &report; - _impl = static_cast(controllerManager.createController(capsuleDesc)); + _impl = static_cast(controllerManager.createController(capsuleDesc)); updateScale(); insertToCCTMap(); updateFilterData(); } -void PhysXCapsuleCharacterController::updateScale(){ +void PhysXCapsuleCharacterController::updateScale() { updateGeometry(); } void PhysXCapsuleCharacterController::updateGeometry() { - if(!_impl) return; + if (!_impl) return; auto *node = _mNode; node->updateWorldTransform(); float r = _mRadius * pxAbsMax(node->getWorldScale().x, node->getWorldScale().z); float h = _mHeight * physx::PxAbs(node->getWorldScale().y); - static_cast(_impl)->setRadius(physx::PxMax(r, PX_NORMALIZATION_EPSILON)); - static_cast(_impl)->setHeight(physx::PxMax(h, PX_NORMALIZATION_EPSILON)); + static_cast(_impl)->setRadius(physx::PxMax(r, PX_NORMALIZATION_EPSILON)); + static_cast(_impl)->setHeight(physx::PxMax(h, PX_NORMALIZATION_EPSILON)); } } // namespace physics diff --git a/native/cocos/physics/physx/character-controllers/PhysXCapsuleCharacterController.h b/native/cocos/physics/physx/character-controllers/PhysXCapsuleCharacterController.h index d8622e6790..ae4d984101 100644 --- a/native/cocos/physics/physx/character-controllers/PhysXCapsuleCharacterController.h +++ b/native/cocos/physics/physx/character-controllers/PhysXCapsuleCharacterController.h @@ -33,7 +33,7 @@ class PhysXCapsuleCharacterController final : public PhysXCharacterController, p public: PhysXCapsuleCharacterController(); ~PhysXCapsuleCharacterController() override = default; - + // ICapsuleCharacterController void setRadius(float v) override; void setHeight(float v) override; diff --git a/native/cocos/physics/physx/character-controllers/PhysXCharacterController.cpp b/native/cocos/physics/physx/character-controllers/PhysXCharacterController.cpp index 66635d2344..327a70664c 100644 --- a/native/cocos/physics/physx/character-controllers/PhysXCharacterController.cpp +++ b/native/cocos/physics/physx/character-controllers/PhysXCharacterController.cpp @@ -24,9 +24,9 @@ #include "physics/physx/character-controllers/PhysXCharacterController.h" #include "base/std/container/unordered_map.h" -#include "physics/physx/shapes/PhysXShape.h" #include "physics/physx/PhysXUtils.h" #include "physics/physx/PhysXWorld.h" +#include "physics/physx/shapes/PhysXShape.h" namespace cc { namespace physics { @@ -48,7 +48,7 @@ static PhysXShape* convertPxShape2PhysXShape(physx::PxShape* shape) { void ControllerHitReport::onShapeHit(const physx::PxControllerShapeHit& hit) { const auto& hitShape = getPxShapeMap().find(reinterpret_cast(hit.shape)); - assert(hitShape!= getPxShapeMap().end()); + assert(hitShape != getPxShapeMap().end()); uint32_t shapeObjectID = hitShape->second; const auto& cct = getPxCCTMap().find(reinterpret_cast(hit.controller)); @@ -75,15 +75,15 @@ void ControllerHitReport::onObstacleHit(const physx::PxControllerObstacleHit& hi } physx::PxQueryHitType::Enum QueryFilterCallback::preFilter(const physx::PxFilterData& filterData, -const physx::PxShape* shape, const physx::PxRigidActor* actor, physx::PxHitFlags& queryFlags) { + const physx::PxShape* shape, const physx::PxRigidActor* actor, physx::PxHitFlags& queryFlags) { //PxShape --> PhysXShape ID - const auto &hitShape = getPxShapeMap().find(reinterpret_cast(shape)); + const auto& hitShape = getPxShapeMap().find(reinterpret_cast(shape)); if (hitShape == getPxShapeMap().end()) { return physx::PxQueryHitType::eNONE; } //PhysXShape ID --> PhysXShape pointer uintptr_t wrapperPtrShape = PhysXWorld::getInstance().getWrapperPtrWithObjectID(hitShape->second); - if(wrapperPtrShape == 0){ + if (wrapperPtrShape == 0) { return physx::PxQueryHitType::eNONE; } PhysXShape* wrapperShape = reinterpret_cast(wrapperPtrShape); @@ -92,8 +92,8 @@ const physx::PxShape* shape, const physx::PxRigidActor* actor, physx::PxHitFlags } return physx::PxQueryHitType::eBLOCK; } - -physx::PxQueryHitType::Enum QueryFilterCallback::postFilter(const physx::PxFilterData& filterData, const physx::PxQueryHit& hit){ + +physx::PxQueryHitType::Enum QueryFilterCallback::postFilter(const physx::PxFilterData& filterData, const physx::PxQueryHit& hit) { PX_UNUSED(filterData); PX_UNUSED(hit); return physx::PxQueryHitType::eNONE; @@ -101,18 +101,18 @@ physx::PxQueryHitType::Enum QueryFilterCallback::postFilter(const physx::PxFilte PhysXCharacterController::PhysXCharacterController() { _mObjectID = PhysXWorld::getInstance().addWrapperObject(reinterpret_cast(this)); - _mFilterData = physx::PxFilterData(1, 1, 1, 0 ); + _mFilterData = physx::PxFilterData(1, 1, 1, 0); }; void PhysXCharacterController::release() { eraseFromCCTMap(); - if(_impl){ + if (_impl) { _impl->release(); _impl = nullptr; } } -bool PhysXCharacterController::initialize(Node *node) { +bool PhysXCharacterController::initialize(Node* node) { _mNode = node; onComponentSet(); @@ -121,7 +121,7 @@ bool PhysXCharacterController::initialize(Node *node) { } else { PhysXWorld::getInstance().addCCT(*this); return true; - } + } } void PhysXCharacterController::onEnable() { @@ -157,13 +157,12 @@ void PhysXCharacterController::syncSceneToPhysics() { if (getChangedFlags & static_cast(TransformBit::SCALE)) syncScale(); //teleport if (getChangedFlags & static_cast(TransformBit::POSITION)) { - const auto & cctPos = _mNode->getWorldPosition() + scaledCenter(); + const auto& cctPos = _mNode->getWorldPosition() + scaledCenter(); setPosition(cctPos.x, cctPos.y, cctPos.z); } - } -void PhysXCharacterController::syncScale () { +void PhysXCharacterController::syncScale() { updateScale(); } @@ -214,7 +213,7 @@ void PhysXCharacterController::setOverlapRecovery(bool v) { _mOverlapRecovery = v; } -void PhysXCharacterController::setCenter(float x, float y, float z){ +void PhysXCharacterController::setCenter(float x, float y, float z) { _mCenter = Vec3(x, y, z); } @@ -242,7 +241,7 @@ void PhysXCharacterController::updateEventListener(EShapeFilterFlag flag) { } void PhysXCharacterController::updateFilterData() { - setSimulationFilterData(_mFilterData); + setSimulationFilterData(_mFilterData); } void PhysXCharacterController::setSimulationFilterData(physx::PxFilterData filterData) { diff --git a/native/cocos/physics/physx/character-controllers/PhysXCharacterController.h b/native/cocos/physics/physx/character-controllers/PhysXCharacterController.h index da11603ea1..9f7b1944ba 100644 --- a/native/cocos/physics/physx/character-controllers/PhysXCharacterController.h +++ b/native/cocos/physics/physx/character-controllers/PhysXCharacterController.h @@ -42,14 +42,14 @@ public: class QueryFilterCallback : public physx::PxQueryFilterCallback { public: virtual physx::PxQueryHitType::Enum preFilter(const physx::PxFilterData& filterData, const physx::PxShape* shape, - const physx::PxRigidActor* actor, physx::PxHitFlags& queryFlags) override; - + const physx::PxRigidActor* actor, physx::PxHitFlags& queryFlags) override; + virtual physx::PxQueryHitType::Enum postFilter(const physx::PxFilterData& filterData, const physx::PxQueryHit& hit) override; }; class PhysXCharacterController : virtual public IBaseCharacterController { PX_NOCOPY(PhysXCharacterController) - PhysXCharacterController(); + PhysXCharacterController(); public: ~PhysXCharacterController() override = default; @@ -79,7 +79,7 @@ public: virtual void setDetectCollisions(bool v) override; virtual void setOverlapRecovery(bool v) override; virtual void setCenter(float x, float y, float z) override; - + uint32_t getGroup() override; void setGroup(uint32_t g) override; uint32_t getMask() override; @@ -91,21 +91,21 @@ public: inline physx::PxController& getCCT() { return *_impl; }; protected: - physx::PxController* _impl{ nullptr }; - uint8_t _mFlag{ 0 }; - bool _mEnabled{ false }; - uint32_t _mObjectID{ 0 }; - Node* _mNode{ nullptr }; + physx::PxController* _impl{nullptr}; + uint8_t _mFlag{0}; + bool _mEnabled{false}; + uint32_t _mObjectID{0}; + Node* _mNode{nullptr}; physx::PxFilterData _mFilterData; ControllerHitReport report; QueryFilterCallback _mFilterCallback; physx::PxControllerFilters controllerFilter; physx::PxControllerCollisionFlags _pxCollisionFlags; - bool _mOverlapRecovery{ true }; - float _mContactOffset{ 0.01f }; - float _mStepOffset{ 1.f }; - float _mSlopeLimit{ 45.f }; - cc::Vec3 _mCenter{ 0.f, 0.f, 0.f }; + bool _mOverlapRecovery{true}; + float _mContactOffset{0.01f}; + float _mStepOffset{1.f}; + float _mSlopeLimit{45.f}; + cc::Vec3 _mCenter{0.f, 0.f, 0.f}; void release(); void updateFilterData(); diff --git a/native/cocos/physics/physx/joints/PhysXGenericJoint.cpp b/native/cocos/physics/physx/joints/PhysXGenericJoint.cpp index cace104cb2..b224795f67 100644 --- a/native/cocos/physics/physx/joints/PhysXGenericJoint.cpp +++ b/native/cocos/physics/physx/joints/PhysXGenericJoint.cpp @@ -111,7 +111,7 @@ void PhysXGenericJoint::setAngularExtent(float twist, float swing1, float swing2 _angularLimit.twistExtent = mathutils::toRadian(std::fmax(twist, 1e-9)); _angularLimit.swing1Extent = mathutils::toRadian(std::fmax(swing1, 1e-9)); _angularLimit.swing2Extent = mathutils::toRadian(std::fmax(swing2, 1e-9)); - + updateTwistLimit(); updateSwingLimit(); } diff --git a/native/cocos/physics/physx/joints/PhysXJoint.cpp b/native/cocos/physics/physx/joints/PhysXJoint.cpp index 1b1fa4a4c9..78c4894092 100644 --- a/native/cocos/physics/physx/joints/PhysXJoint.cpp +++ b/native/cocos/physics/physx/joints/PhysXJoint.cpp @@ -69,7 +69,6 @@ void PhysXJoint::setConnectedBody(uint32_t rigidBodyID) { if (pxRigidBody == nullptr) return; - auto *oldConnectedBody = _mConnectedBody; if (oldConnectedBody) { oldConnectedBody->removeJoint(*this, physx::PxJointActorIndex::eACTOR1); diff --git a/native/cocos/physics/physx/joints/PhysXJoint.h b/native/cocos/physics/physx/joints/PhysXJoint.h index d17f48c365..e1531fcd1e 100644 --- a/native/cocos/physics/physx/joints/PhysXJoint.h +++ b/native/cocos/physics/physx/joints/PhysXJoint.h @@ -57,7 +57,7 @@ protected: PhysXSharedBody *_mSharedBody{nullptr}; PhysXSharedBody *_mConnectedBody{nullptr}; bool _mEnableCollision{false}; - bool _mEnableDebugVisualization{ false }; + bool _mEnableDebugVisualization{false}; virtual void onComponentSet() = 0; uint32_t _mObjectID{0}; diff --git a/native/cocos/physics/sdk/CharacterController.cpp b/native/cocos/physics/sdk/CharacterController.cpp index fc53ac4a0f..1473a77c54 100644 --- a/native/cocos/physics/sdk/CharacterController.cpp +++ b/native/cocos/physics/sdk/CharacterController.cpp @@ -26,107 +26,106 @@ #include #include "physics/PhysicsSelector.h" -#define CC_PHYSICS_CCT_DEFINITION(CLASS, WRAPPED) \ - \ -CLASS::CLASS() { \ - _impl.reset(ccnew WRAPPED()); \ -} \ - \ -CLASS::~CLASS() { \ - _impl.reset(nullptr); \ -} \ - \ -bool CLASS::initialize(Node *node) { \ - return _impl->initialize(node); \ -} \ - \ -void CLASS::onEnable() { \ - _impl->onEnable(); \ -} \ - \ -void CLASS::onDisable() { \ - _impl->onDisable(); \ -} \ - \ -void CLASS::onDestroy() { \ - _impl->onDestroy(); \ -} \ - \ -cc::Vec3 CLASS::getPosition() { \ - return _impl->getPosition(); \ -} \ - \ -void CLASS::setPosition(float x, float y, float z) { \ - _impl->setPosition(x, y, z); \ -} \ - \ -bool CLASS::onGround() { \ - return _impl->onGround(); \ -} \ - \ -void CLASS::move(float x, float y, float z, float minDist, float elapsedTime) { \ - _impl->move(x, y, z, minDist, elapsedTime); \ -} \ - \ -void CLASS::syncPhysicsToScene() { \ - _impl->syncPhysicsToScene(); \ -} \ - \ -void CLASS::setStepOffset(float v) { \ - _impl->setStepOffset(v); \ -} \ - \ -float CLASS::getStepOffset() { \ - return _impl->getStepOffset(); \ -} \ - \ -void CLASS::setSlopeLimit(float v) { \ - _impl->setSlopeLimit(v); \ -} \ - \ -float CLASS::getSlopeLimit() { \ - return _impl->getSlopeLimit(); \ -} \ - \ -void CLASS::setContactOffset(float v) { \ - _impl->setContactOffset(v); \ -} \ - \ -float CLASS::getContactOffset() { \ - return _impl->getContactOffset(); \ -} \ - \ -void CLASS::setDetectCollisions(bool v) { \ - _impl->setDetectCollisions(v); \ -} \ -void CLASS::setOverlapRecovery(bool v) { \ - _impl->setOverlapRecovery(v); \ -} \ -void CLASS::setCenter(float x, float y, float z) { \ - _impl->setCenter(x, y, z); \ -} \ -uint32_t CLASS::getGroup() { \ - return _impl->getGroup(); \ -} \ - \ -void CLASS::setGroup(uint32_t g) { \ - _impl->setGroup(g); \ -} \ - \ -uint32_t CLASS::getMask() { \ - return _impl->getMask(); \ -} \ - \ -void CLASS::setMask(uint32_t m) { \ - _impl->setMask(m); \ -} \ -void CLASS::updateEventListener(EShapeFilterFlag flag) { \ - _impl->updateEventListener(flag); \ -} \ -uint32_t CLASS::getObjectID()const { \ - return _impl->getObjectID(); \ -} \ - \ +#define CC_PHYSICS_CCT_DEFINITION(CLASS, WRAPPED) \ + \ + CLASS::CLASS() { \ + _impl.reset(ccnew WRAPPED()); \ + } \ + \ + CLASS::~CLASS() { \ + _impl.reset(nullptr); \ + } \ + \ + bool CLASS::initialize(Node *node) { \ + return _impl->initialize(node); \ + } \ + \ + void CLASS::onEnable() { \ + _impl->onEnable(); \ + } \ + \ + void CLASS::onDisable() { \ + _impl->onDisable(); \ + } \ + \ + void CLASS::onDestroy() { \ + _impl->onDestroy(); \ + } \ + \ + cc::Vec3 CLASS::getPosition() { \ + return _impl->getPosition(); \ + } \ + \ + void CLASS::setPosition(float x, float y, float z) { \ + _impl->setPosition(x, y, z); \ + } \ + \ + bool CLASS::onGround() { \ + return _impl->onGround(); \ + } \ + \ + void CLASS::move(float x, float y, float z, float minDist, float elapsedTime) { \ + _impl->move(x, y, z, minDist, elapsedTime); \ + } \ + \ + void CLASS::syncPhysicsToScene() { \ + _impl->syncPhysicsToScene(); \ + } \ + \ + void CLASS::setStepOffset(float v) { \ + _impl->setStepOffset(v); \ + } \ + \ + float CLASS::getStepOffset() { \ + return _impl->getStepOffset(); \ + } \ + \ + void CLASS::setSlopeLimit(float v) { \ + _impl->setSlopeLimit(v); \ + } \ + \ + float CLASS::getSlopeLimit() { \ + return _impl->getSlopeLimit(); \ + } \ + \ + void CLASS::setContactOffset(float v) { \ + _impl->setContactOffset(v); \ + } \ + \ + float CLASS::getContactOffset() { \ + return _impl->getContactOffset(); \ + } \ + \ + void CLASS::setDetectCollisions(bool v) { \ + _impl->setDetectCollisions(v); \ + } \ + void CLASS::setOverlapRecovery(bool v) { \ + _impl->setOverlapRecovery(v); \ + } \ + void CLASS::setCenter(float x, float y, float z) { \ + _impl->setCenter(x, y, z); \ + } \ + uint32_t CLASS::getGroup() { \ + return _impl->getGroup(); \ + } \ + \ + void CLASS::setGroup(uint32_t g) { \ + _impl->setGroup(g); \ + } \ + \ + uint32_t CLASS::getMask() { \ + return _impl->getMask(); \ + } \ + \ + void CLASS::setMask(uint32_t m) { \ + _impl->setMask(m); \ + } \ + void CLASS::updateEventListener(EShapeFilterFlag flag) { \ + _impl->updateEventListener(flag); \ + } \ + uint32_t CLASS::getObjectID() const { \ + return _impl->getObjectID(); \ + } namespace cc { namespace physics { diff --git a/native/cocos/physics/sdk/CharacterController.h b/native/cocos/physics/sdk/CharacterController.h index e87e34dc66..a4fa53e61e 100644 --- a/native/cocos/physics/sdk/CharacterController.h +++ b/native/cocos/physics/sdk/CharacterController.h @@ -27,54 +27,55 @@ #include #include "base/Macros.h" #include "core/scene-graph/Node.h" -#include "physics/spec/IShape.h" #include "physics/spec/ICharacterController.h" +#include "physics/spec/IShape.h" -#define CC_PHYSICS_CCT_CLASS(CLASS) \ - class CC_DLL CLASS final : public I##CLASS { \ - protected: \ - std::unique_ptr _impl; \ - \ - public: \ - CLASS(); \ - ~CLASS() override; \ - bool initialize(Node *node) override; \ - void onEnable() override; \ - void onDisable() override; \ - void onDestroy() override; \ - virtual cc::Vec3 getPosition() override; \ - virtual void setPosition(float x, float y, float z) override; \ - virtual bool onGround() override; \ - virtual void move(float x, float y, float z, float minDist, \ - float elapsedTime) override; \ - void syncPhysicsToScene() override; \ - virtual void setStepOffset(float v) override; \ - virtual float getStepOffset() override; \ - virtual void setSlopeLimit(float v) override; \ - virtual float getSlopeLimit() override; \ - virtual void setContactOffset(float v) override; \ - virtual float getContactOffset() override; \ - virtual void setDetectCollisions(bool v) override; \ - virtual void setOverlapRecovery(bool v) override; \ - virtual void setCenter(float x, float y, float z) override; \ - uint32_t getGroup() override; \ - void setGroup(uint32_t g) override; \ - uint32_t getMask() override; \ - void setMask(uint32_t m) override; \ - void updateEventListener(EShapeFilterFlag flag) override; \ +#define CC_PHYSICS_CCT_CLASS(CLASS) \ + class CC_DLL CLASS final : public I##CLASS { \ + protected: \ + std::unique_ptr _impl; \ + \ + public: \ + CLASS(); \ + ~CLASS() override; \ + bool initialize(Node *node) override; \ + void onEnable() override; \ + void onDisable() override; \ + void onDestroy() override; \ + virtual cc::Vec3 getPosition() override; \ + virtual void setPosition(float x, float y, float z) override; \ + virtual bool onGround() override; \ + virtual void move(float x, float y, float z, float minDist, \ + float elapsedTime) override; \ + void syncPhysicsToScene() override; \ + virtual void setStepOffset(float v) override; \ + virtual float getStepOffset() override; \ + virtual void setSlopeLimit(float v) override; \ + virtual float getSlopeLimit() override; \ + virtual void setContactOffset(float v) override; \ + virtual float getContactOffset() override; \ + virtual void setDetectCollisions(bool v) override; \ + virtual void setOverlapRecovery(bool v) override; \ + virtual void setCenter(float x, float y, float z) override; \ + uint32_t getGroup() override; \ + void setGroup(uint32_t g) override; \ + uint32_t getMask() override; \ + void setMask(uint32_t m) override; \ + void updateEventListener(EShapeFilterFlag flag) override; \ uint32_t getObjectID() const override; namespace cc { namespace physics { - CC_PHYSICS_CCT_CLASS(CapsuleCharacterController) - void setRadius(float v) override; - void setHeight(float v) override; - }; - - CC_PHYSICS_CCT_CLASS(BoxCharacterController) - void setHalfHeight(float v) override; - void setHalfSideExtent(float v) override; - void setHalfForwardExtent(float v) override; +CC_PHYSICS_CCT_CLASS(CapsuleCharacterController) +void setRadius(float v) override; +void setHeight(float v) override; }; -}; // namespace physics + +CC_PHYSICS_CCT_CLASS(BoxCharacterController) +void setHalfHeight(float v) override; +void setHalfSideExtent(float v) override; +void setHalfForwardExtent(float v) override; +}; +} +; // namespace physics } // namespace cc diff --git a/native/cocos/physics/sdk/World.cpp b/native/cocos/physics/sdk/World.cpp index 5bdbeeb965..8c185d9d07 100644 --- a/native/cocos/physics/sdk/World.cpp +++ b/native/cocos/physics/sdk/World.cpp @@ -78,7 +78,7 @@ ccstd::vector> &World::getContactEventPairs() return _impl->getContactEventPairs(); } -ccstd::vector>& World::getCCTShapeEventPairs() { +ccstd::vector> &World::getCCTShapeEventPairs() { return _impl->getCCTShapeEventPairs(); } @@ -143,12 +143,12 @@ void World::setFixedTimeStep(float fixedTimeStep) { } bool World::sweepBox(RaycastOptions &opt, float halfExtentX, float halfExtentY, float halfExtentZ, - float orientationW, float orientationX, float orientationY, float orientationZ){ + float orientationW, float orientationX, float orientationY, float orientationZ) { return _impl->sweepBox(opt, halfExtentX, halfExtentY, halfExtentZ, orientationW, orientationX, orientationY, orientationZ); } bool World::sweepBoxClosest(RaycastOptions &opt, float halfExtentX, float halfExtentY, float halfExtentZ, - float orientationW, float orientationX, float orientationY, float orientationZ){ + float orientationW, float orientationX, float orientationY, float orientationZ) { return _impl->sweepBoxClosest(opt, halfExtentX, halfExtentY, halfExtentZ, orientationW, orientationX, orientationY, orientationZ); } @@ -160,13 +160,13 @@ bool World::sweepSphereClosest(RaycastOptions &opt, float radius) { return _impl->sweepSphereClosest(opt, radius); } -bool World::sweepCapsule(RaycastOptions &opt, float radius, float height, - float orientationW, float orientationX, float orientationY, float orientationZ) { +bool World::sweepCapsule(RaycastOptions &opt, float radius, float height, + float orientationW, float orientationX, float orientationY, float orientationZ) { return _impl->sweepCapsule(opt, radius, height, orientationW, orientationX, orientationY, orientationZ); } bool World::sweepCapsuleClosest(RaycastOptions &opt, float radius, float height, - float orientationW, float orientationX, float orientationY, float orientationZ) { + float orientationW, float orientationX, float orientationY, float orientationZ) { return _impl->sweepCapsuleClosest(opt, radius, height, orientationW, orientationX, orientationY, orientationZ); } diff --git a/native/cocos/physics/sdk/World.h b/native/cocos/physics/sdk/World.h index dec44009df..80bf57249a 100644 --- a/native/cocos/physics/sdk/World.h +++ b/native/cocos/physics/sdk/World.h @@ -46,23 +46,23 @@ public: float getDebugDrawConstraintSize() override; void setCollisionMatrix(uint32_t i, uint32_t m) override; ccstd::vector> &getTriggerEventPairs() override; - ccstd::vector>& getContactEventPairs() override; - ccstd::vector>& getCCTShapeEventPairs() override; - ccstd::vector>& getCCTTriggerEventPairs() override; + ccstd::vector> &getContactEventPairs() override; + ccstd::vector> &getCCTShapeEventPairs() override; + ccstd::vector> &getCCTTriggerEventPairs() override; bool raycast(RaycastOptions &opt) override; bool raycastClosest(RaycastOptions &opt) override; ccstd::vector &raycastResult() override; RaycastResult &raycastClosestResult() override; bool sweepBox(RaycastOptions &opt, float halfExtentX, float halfExtentY, float halfExtentZ, - float orientationW, float orientationX, float orientationY, float orientationZ) override; + float orientationW, float orientationX, float orientationY, float orientationZ) override; bool sweepBoxClosest(RaycastOptions &opt, float halfExtentX, float halfExtentY, float halfExtentZ, - float orientationW, float orientationX, float orientationY, float orientationZ) override; + float orientationW, float orientationX, float orientationY, float orientationZ) override; bool sweepSphere(RaycastOptions &opt, float radius) override; bool sweepSphereClosest(RaycastOptions &opt, float radius) override; bool sweepCapsule(RaycastOptions &opt, float radius, float height, - float orientationW, float orientationX, float orientationY, float orientationZ) override; + float orientationW, float orientationX, float orientationY, float orientationZ) override; bool sweepCapsuleClosest(RaycastOptions &opt, float radius, float height, - float orientationW, float orientationX, float orientationY, float orientationZ) override; + float orientationW, float orientationX, float orientationY, float orientationZ) override; RaycastResult &sweepClosestResult() override; ccstd::vector &sweepResult() override; diff --git a/native/cocos/physics/spec/IWorld.h b/native/cocos/physics/spec/IWorld.h index e0c9d8c09f..88fdbc4066 100644 --- a/native/cocos/physics/spec/IWorld.h +++ b/native/cocos/physics/spec/IWorld.h @@ -87,18 +87,18 @@ struct CharacterControllerContact { static constexpr uint8_t COUNT = 10; }; struct CCTShapeEventPair { - uint32_t cct; //wrapper object ID + uint32_t cct; //wrapper object ID uint32_t shape; //wrapper object ID //ETouchState state; ccstd::vector contacts; static constexpr uint8_t COUNT = 3; CCTShapeEventPair(const uint32_t cct, const uint32_t shape) - : cct(cct), shape(shape) { + : cct(cct), shape(shape) { } }; struct CCTTriggerEventPair { - uint32_t cct; //wrapper object ID + uint32_t cct; //wrapper object ID uint32_t shape; //wrapper object ID ETouchState state; static constexpr uint8_t COUNT = 3; @@ -158,23 +158,23 @@ public: virtual float getDebugDrawConstraintSize() = 0; virtual void setCollisionMatrix(uint32_t i, uint32_t m) = 0; virtual ccstd::vector> &getTriggerEventPairs() = 0; - virtual ccstd::vector>& getContactEventPairs() = 0; - virtual ccstd::vector>& getCCTShapeEventPairs() = 0; + virtual ccstd::vector> &getContactEventPairs() = 0; + virtual ccstd::vector> &getCCTShapeEventPairs() = 0; virtual ccstd::vector> &getCCTTriggerEventPairs() = 0; virtual bool raycast(RaycastOptions &opt) = 0; virtual bool raycastClosest(RaycastOptions &opt) = 0; virtual ccstd::vector &raycastResult() = 0; virtual RaycastResult &raycastClosestResult() = 0; virtual bool sweepBox(RaycastOptions &opt, float halfExtentX, float halfExtentY, float halfExtentZ, - float orientationW, float orientationX, float orientationY, float orientationZ) = 0; + float orientationW, float orientationX, float orientationY, float orientationZ) = 0; virtual bool sweepBoxClosest(RaycastOptions &opt, float halfExtentX, float halfExtentY, float halfExtentZ, - float orientationW, float orientationX, float orientationY, float orientationZ) = 0; + float orientationW, float orientationX, float orientationY, float orientationZ) = 0; virtual bool sweepSphere(RaycastOptions &opt, float radius) = 0; virtual bool sweepSphereClosest(RaycastOptions &opt, float radius) = 0; virtual bool sweepCapsule(RaycastOptions &opt, float radius, float height, - float orientationW, float orientationX, float orientationY, float orientationZ) = 0; + float orientationW, float orientationX, float orientationY, float orientationZ) = 0; virtual bool sweepCapsuleClosest(RaycastOptions &opt, float radius, float height, - float orientationW, float orientationX, float orientationY, float orientationZ) = 0; + float orientationW, float orientationX, float orientationY, float orientationZ) = 0; virtual RaycastResult &sweepClosestResult() = 0; virtual ccstd::vector &sweepResult() = 0; virtual uint32_t createConvex(ConvexDesc &desc) = 0; diff --git a/native/cocos/platform/FileUtils.cpp b/native/cocos/platform/FileUtils.cpp index 0dcce374c5..f1d04e6b08 100644 --- a/native/cocos/platform/FileUtils.cpp +++ b/native/cocos/platform/FileUtils.cpp @@ -1068,10 +1068,10 @@ bool FileUtils::removeDirectory(const ccstd::string &path) { // NOLINT(misc-no-r #if (CC_PLATFORM != CC_PLATFORM_ANDROID) return nftw(path.c_str(), unlinkCb, 64, FTW_DEPTH | FTW_PHYS) != -1; #else - DIR* dir = opendir(path.c_str()); + DIR *dir = opendir(path.c_str()); if (!dir) return false; - struct dirent* entry; + struct dirent *entry; while ((entry = readdir(dir)) != nullptr) { // 跳过 . 和 .. if (strcmp(entry->d_name, ".") == 0 || diff --git a/native/cocos/platform/UniversalPlatform.cpp b/native/cocos/platform/UniversalPlatform.cpp index 89128edb64..c0058cd387 100644 --- a/native/cocos/platform/UniversalPlatform.cpp +++ b/native/cocos/platform/UniversalPlatform.cpp @@ -80,7 +80,6 @@ void UniversalPlatform::onDestroy() { } void UniversalPlatform::exit() { - } } // namespace cc diff --git a/native/cocos/platform/android/AndroidPlatform.cpp b/native/cocos/platform/android/AndroidPlatform.cpp index 4d28969dd8..c4f5c50e25 100644 --- a/native/cocos/platform/android/AndroidPlatform.cpp +++ b/native/cocos/platform/android/AndroidPlatform.cpp @@ -45,14 +45,14 @@ #include "platform/interfaces/modules/IXRInterface.h" #if CC_USE_XR -#include "platform/java/modules/XRInterface.h" + #include "platform/java/modules/XRInterface.h" #endif #include "base/StringUtil.h" #include "engine/EngineEvents.h" #include "paddleboat.h" -#include "platform/java/jni/JniImp.h" #include "platform/interfaces/modules/Device.h" +#include "platform/java/jni/JniImp.h" #define ABORT_GAME \ { \ @@ -428,8 +428,7 @@ public: if (actionMasked == AMOTION_EVENT_ACTION_DOWN || actionMasked == AMOTION_EVENT_ACTION_POINTER_DOWN) { if (actionMasked == AMOTION_EVENT_ACTION_POINTER_DOWN) { - eventChangedIndex = ((action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) - >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT); + eventChangedIndex = ((action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT); } else { eventChangedIndex = 0; } @@ -438,8 +437,7 @@ public: actionMasked == AMOTION_EVENT_ACTION_POINTER_UP) { touchEvent.type = cc::TouchEvent::Type::ENDED; if (actionMasked == AMOTION_EVENT_ACTION_POINTER_UP) { - eventChangedIndex = ((action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) - >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT); + eventChangedIndex = ((action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT); } else { eventChangedIndex = 0; } diff --git a/native/cocos/platform/android/AndroidPlatform.h b/native/cocos/platform/android/AndroidPlatform.h index 55d0a853da..937f51572b 100644 --- a/native/cocos/platform/android/AndroidPlatform.h +++ b/native/cocos/platform/android/AndroidPlatform.h @@ -48,7 +48,7 @@ public: int32_t loop() override; void exit() override; - + void *getActivity(); static void *getEnv(); diff --git a/native/cocos/platform/interfaces/modules/Device.cpp b/native/cocos/platform/interfaces/modules/Device.cpp index d8bb672b4b..172448a253 100644 --- a/native/cocos/platform/interfaces/modules/Device.cpp +++ b/native/cocos/platform/interfaces/modules/Device.cpp @@ -29,9 +29,9 @@ #include "platform/interfaces/modules/IBattery.h" #include "platform/interfaces/modules/INetwork.h" #include "platform/interfaces/modules/IScreen.h" -#include "platform/interfaces/modules/IVibrator.h" #include "platform/interfaces/modules/ISystemWindow.h" #include "platform/interfaces/modules/ISystemWindowManager.h" +#include "platform/interfaces/modules/IVibrator.h" namespace cc { diff --git a/native/cocos/platform/interfaces/modules/XRCommon.h b/native/cocos/platform/interfaces/modules/XRCommon.h index d33f211508..a93a99b1be 100644 --- a/native/cocos/platform/interfaces/modules/XRCommon.h +++ b/native/cocos/platform/interfaces/modules/XRCommon.h @@ -119,7 +119,7 @@ enum class XRConfigKey { ASYNC_LOAD_ASSETS_IMAGE = 55, ASYNC_LOAD_ASSETS_IMAGE_RESULTS = 56, LEFT_CONTROLLER_ACTIVE = 57, - RIGHT_CONTROLLER_ACTIVE= 58, + RIGHT_CONTROLLER_ACTIVE = 58, TS_EVENT_CALLBACK = 59, MAX_COUNT }; @@ -330,13 +330,13 @@ struct XRTouch : public XRControllerInfo { Type type = Type::UNKNOWN; XRTouch(Type type, bool isActive) - : type(type), - isActive(isActive) {} + : type(type), + isActive(isActive) {} XRTouch(Type type, float value) - : type(type), - isActive(true), - value(value) {} + : type(type), + isActive(true), + value(value) {} XREventType getXREventType() const override { return XREventType::TOUCH; diff --git a/native/cocos/platform/ios/IOSPlatform.h b/native/cocos/platform/ios/IOSPlatform.h index dd6ce26d64..32fdb3bd83 100644 --- a/native/cocos/platform/ios/IOSPlatform.h +++ b/native/cocos/platform/ios/IOSPlatform.h @@ -44,9 +44,9 @@ public: * @brief Start base platform initialization. */ int32_t run(int argc, const char **argv) override; - + void requestExit(); - + void exit() override; /** * @brief Implement the main logic of the base platform. diff --git a/native/cocos/platform/java/jni/JniGooglePlayHandler.cpp b/native/cocos/platform/java/jni/JniGooglePlayHandler.cpp index a959b2a850..ce769c4903 100644 --- a/native/cocos/platform/java/jni/JniGooglePlayHandler.cpp +++ b/native/cocos/platform/java/jni/JniGooglePlayHandler.cpp @@ -37,11 +37,11 @@ JNIEXPORT void JNICALL Java_google_play_TaskManager_onTaskCompleteNative(JNIEnv } JNIEXPORT void JNICALL Java_google_play_TaskManager_onTaskFailureNative(JNIEnv *env, jclass clazz, jint taskId, jint listenerId, jobject obj, jint exceptionId) { - cc::PlayTaskManager::getInstance()->onTaskFailure(taskId, listenerId, reinterpret_cast(obj), exceptionId); + cc::PlayTaskManager::getInstance()->onTaskFailure(taskId, listenerId, reinterpret_cast(obj), exceptionId); } JNIEXPORT void JNICALL Java_google_play_TaskManager_onTaskSuccessNative(JNIEnv *env, jclass clazz, jint taskId, jint listenerId, jobject obj) { - cc::PlayTaskManager::getInstance()->onTaskSucess(taskId, listenerId, reinterpret_cast(obj)); + cc::PlayTaskManager::getInstance()->onTaskSucess(taskId, listenerId, reinterpret_cast(obj)); } JNIEXPORT jobject JNICALL Java_google_play_TaskManager_onContinueWithNative(JNIEnv *env, jclass clazz, jint taskId, jint listenerId, jint nextTaskId) { diff --git a/native/cocos/platform/java/jni/JniImp.cpp b/native/cocos/platform/java/jni/JniImp.cpp index cc37a74ee9..f309ac593c 100644 --- a/native/cocos/platform/java/jni/JniImp.cpp +++ b/native/cocos/platform/java/jni/JniImp.cpp @@ -47,7 +47,6 @@ #endif #define JNI_AUDIO(FUNC) JNI_METHOD1(COM_AUDIOFOCUS_CLASS_NAME, FUNC) - /*********************************************************** * Functions invoke from cpp to Java. ***********************************************************/ @@ -138,12 +137,12 @@ float getBatteryLevelJNI() { void flushTasksOnGameThreadJNI() { JniHelper::callStaticVoidMethod(JCLS_HELPER, - "flushTasksOnGameThread"); + "flushTasksOnGameThread"); } void flushTasksOnGameThreadAtForegroundJNI() { JniHelper::callStaticVoidMethod(JCLS_HELPER, - "flushTasksOnGameThreadAtForeground"); + "flushTasksOnGameThreadAtForeground"); } void setAccelerometerEnabledJNI(bool isEnabled) { diff --git a/native/cocos/platform/java/modules/XRInterface.cpp b/native/cocos/platform/java/modules/XRInterface.cpp index b59f0447cf..5f496ad0ed 100644 --- a/native/cocos/platform/java/modules/XRInterface.cpp +++ b/native/cocos/platform/java/modules/XRInterface.cpp @@ -113,7 +113,7 @@ void XRInterface::dispatchGamepadEventInternal(const xr::XRControllerEvent &xrCo switch (xrControllerEvent.xrControllerInfos.at(i)->getXREventType()) { case xr::XREventType::CLICK: { auto *xrClick = static_cast(xrControllerEvent.xrControllerInfos.at(i).get()); - if(CLICK_TYPE_TO_KEY_CODE.count(xrClick->type) > 0) { + if (CLICK_TYPE_TO_KEY_CODE.count(xrClick->type) > 0) { StickKeyCode stickKeyCode = CLICK_TYPE_TO_KEY_CODE.at(xrClick->type); switch (xrClick->type) { @@ -176,7 +176,7 @@ void XRInterface::dispatchGamepadEventInternal(const xr::XRControllerEvent &xrCo } break; case xr::XREventType::GRAB: { auto *xrGrab = static_cast(xrControllerEvent.xrControllerInfos.at(i).get()); - if(GRAB_TYPE_TO_AXIS_CODE.count(xrGrab->type) > 0) { + if (GRAB_TYPE_TO_AXIS_CODE.count(xrGrab->type) > 0) { StickAxisCode stickAxisCode = GRAB_TYPE_TO_AXIS_CODE.at(xrGrab->type); switch (xrGrab->type) { case xr::XRGrab::Type::TRIGGER_LEFT: @@ -234,7 +234,7 @@ void XRInterface::dispatchHandleEventInternal(const xr::XRControllerEvent &xrCon switch (xrControllerEvent.xrControllerInfos.at(i)->getXREventType()) { case xr::XREventType::CLICK: { auto *xrClick = static_cast(xrControllerEvent.xrControllerInfos.at(i).get()); - if(CLICK_TYPE_TO_KEY_CODE.count(xrClick->type) > 0) { + if (CLICK_TYPE_TO_KEY_CODE.count(xrClick->type) > 0) { StickKeyCode stickKeyCode = CLICK_TYPE_TO_KEY_CODE.at(xrClick->type); switch (xrClick->type) { case xr::XRClick::Type::MENU: { @@ -242,7 +242,7 @@ void XRInterface::dispatchHandleEventInternal(const xr::XRControllerEvent &xrCon controllerInfo->buttonInfos.emplace_back(ControllerInfo::ButtonInfo(StickKeyCode::MENU, xrClick->isPress)); #else CC_LOG_INFO("[XRInterface] exit when menu click in seed."); - CC_CURRENT_APPLICATION_SAFE()->close(); + CC_CURRENT_APPLICATION_SAFE()->close(); #endif break; } @@ -290,14 +290,14 @@ void XRInterface::dispatchHandleEventInternal(const xr::XRControllerEvent &xrCon } break; case xr::XREventType::GRAB: { auto *xrGrab = static_cast(xrControllerEvent.xrControllerInfos.at(i).get()); - if(GRAB_TYPE_TO_AXIS_CODE.count(xrGrab->type) > 0) { + if (GRAB_TYPE_TO_AXIS_CODE.count(xrGrab->type) > 0) { StickAxisCode stickAxisCode = GRAB_TYPE_TO_AXIS_CODE.at(xrGrab->type); controllerInfo->axisInfos.emplace_back(ControllerInfo::AxisInfo(stickAxisCode, xrGrab->value)); } } break; case xr::XREventType::TOUCH: { auto *xrTouch = static_cast(xrControllerEvent.xrControllerInfos.at(i).get()); - if(TOUCH_TYPE_TO_AXIS_CODE.count(xrTouch->type) > 0) { + if (TOUCH_TYPE_TO_AXIS_CODE.count(xrTouch->type) > 0) { StickTouchCode stickTouchCode = TOUCH_TYPE_TO_AXIS_CODE.at(xrTouch->type); controllerInfo->touchInfos.emplace_back(ControllerInfo::TouchInfo(stickTouchCode, xrTouch->value)); } diff --git a/native/cocos/platform/mac/MacPlatform.h b/native/cocos/platform/mac/MacPlatform.h index 3b7da485c0..c9fda38df2 100644 --- a/native/cocos/platform/mac/MacPlatform.h +++ b/native/cocos/platform/mac/MacPlatform.h @@ -59,6 +59,7 @@ public: void onResume() override; void onClose() override; void pollEvent() override; + private: bool _readyToExit{false}; std::shared_ptr _windowManager{nullptr}; diff --git a/native/cocos/platform/mac/modules/SystemWindow.h b/native/cocos/platform/mac/modules/SystemWindow.h index 8678c3e09e..aac361860e 100644 --- a/native/cocos/platform/mac/modules/SystemWindow.h +++ b/native/cocos/platform/mac/modules/SystemWindow.h @@ -24,8 +24,8 @@ #pragma once -#include #include +#include #include "platform/interfaces/modules/ISystemWindow.h" struct SDL_Window; @@ -58,9 +58,10 @@ public: */ void setCursorEnabled(bool value) override; NSWindow* getNSWindow() const; + private: SDL_Window* getSDLWindow() const { return _window; } - void initWindowProperty(SDL_Window* window, const char *title, int x, int y, int w, int h); + void initWindowProperty(SDL_Window* window, const char* title, int x, int y, int w, int h); uint32_t _width{0}; uint32_t _height{0}; diff --git a/native/cocos/platform/mac/modules/SystemWindowManager.h b/native/cocos/platform/mac/modules/SystemWindowManager.h index 699832e0c9..37f5c790a0 100644 --- a/native/cocos/platform/mac/modules/SystemWindowManager.h +++ b/native/cocos/platform/mac/modules/SystemWindowManager.h @@ -46,6 +46,7 @@ public: ISystemWindow *getWindowFromSDLWindow(SDL_Window *window) const; ISystemWindow *getWindowFromNSWindow(NSWindow *window) const; + private: uint32_t _nextWindowId{1}; // start from 1, 0 means an invalid ID SystemWindowMap _windows; diff --git a/native/cocos/platform/ohos/OhosPlatform.cpp b/native/cocos/platform/ohos/OhosPlatform.cpp index 574134629c..54116ddc66 100644 --- a/native/cocos/platform/ohos/OhosPlatform.cpp +++ b/native/cocos/platform/ohos/OhosPlatform.cpp @@ -79,7 +79,6 @@ void OhosPlatform::waitWindowInitialized() { } void OhosPlatform::exit() { - } int32_t OhosPlatform::loop() { diff --git a/native/cocos/platform/openharmony/FileUtils-OpenHarmony.cpp b/native/cocos/platform/openharmony/FileUtils-OpenHarmony.cpp index c0e538bb6f..94486d4541 100644 --- a/native/cocos/platform/openharmony/FileUtils-OpenHarmony.cpp +++ b/native/cocos/platform/openharmony/FileUtils-OpenHarmony.cpp @@ -179,7 +179,7 @@ long FileUtilsOpenHarmony::getFileSize(const std::string &filepath) { return 0; } - if(fullPath[0] == '/') { + if (fullPath[0] == '/') { return FileUtils::getFileSize(fullPath); } diff --git a/native/cocos/platform/openharmony/OpenHarmonyGamepad.cpp b/native/cocos/platform/openharmony/OpenHarmonyGamepad.cpp index f56907640b..64a2b40937 100644 --- a/native/cocos/platform/openharmony/OpenHarmonyGamepad.cpp +++ b/native/cocos/platform/openharmony/OpenHarmonyGamepad.cpp @@ -79,7 +79,7 @@ StickKeyCode ohButtonCode2StickKeyCode(int32_t code) { case OH_ButtonHome: return StickKeyCode::MINUS; case OH_ButtonMenu: return StickKeyCode::PLUS; - // case OH_ButtonC: return StickAxisCode::HOME; + // case OH_ButtonC: return StickAxisCode::HOME; } return StickKeyCode::UNDEFINE; } @@ -188,19 +188,19 @@ void OnDeviceChanged(const struct GameDevice_DeviceEvent* deviceEvent) { GameDevice_DeviceType type; CALL_OH_GAMEPAD(OH_GameDevice_DeviceInfo_GetDeviceType(deviceInfo, &type)); - // TODO: This is a hack because some system components in HarmonyOS also receive this message, making it impossible - // to distinguish between a game controller and system components. This could cause the game to misinterpret + // TODO: This is a hack because some system components in HarmonyOS also receive this message, making it impossible + // to distinguish between a game controller and system components. This could cause the game to misinterpret // the presence of multiple controllers, leading to anomalies. Therefore, a filter condition has been added here. // Theoretically, the distinction should be made using the "type" field, but in the system, game controllers are also identified as "unknown". // product == 480 && version == 256 : hid-over-i2c 27C6:01E0 Touchpad // product == 5120 && version == 256 : uart_hid 14F3:1400 System Control - if((product == 480 && version == 256) || (product == 5120 && version == 256)) { + if ((product == 480 && version == 256) || (product == 5120 && version == 256)) { return; } -// if(type != GameDevice_DeviceType::GAME_PAD) { -// return; -// } - + // if(type != GameDevice_DeviceType::GAME_PAD) { + // return; + // } + do { if (status == GameDevice_StatusChangedType::ONLINE) { int id = 0; diff --git a/native/cocos/platform/openharmony/OpenHarmonyGamepad.h b/native/cocos/platform/openharmony/OpenHarmonyGamepad.h index b1d6ea8e5d..f394057d5d 100644 --- a/native/cocos/platform/openharmony/OpenHarmonyGamepad.h +++ b/native/cocos/platform/openharmony/OpenHarmonyGamepad.h @@ -32,7 +32,6 @@ class CC_DLL OpenHarmonyGamePad { public: OpenHarmonyGamePad(); virtual ~OpenHarmonyGamePad(); - }; } // namespace cc diff --git a/native/cocos/platform/openharmony/OpenHarmonyPlatform.cpp b/native/cocos/platform/openharmony/OpenHarmonyPlatform.cpp index 914eb7a412..ea089a8d74 100644 --- a/native/cocos/platform/openharmony/OpenHarmonyPlatform.cpp +++ b/native/cocos/platform/openharmony/OpenHarmonyPlatform.cpp @@ -186,13 +186,13 @@ int ohKeyCodeToCocosKeyCode(OH_NativeXComponent_KeyCode ohKeyCode) { {KEY_SPACE, cc::KeyCode::SPACE}, {KEY_ALT_RIGHT, cc::KeyCode::ALT_RIGHT}, {KEY_CTRL_RIGHT, cc::KeyCode::CONTROL_RIGHT}, - + {KEY_DPAD_LEFT, cc::KeyCode::ARROW_LEFT}, {KEY_DPAD_RIGHT, cc::KeyCode::ARROW_RIGHT}, {KEY_DPAD_DOWN, cc::KeyCode::ARROW_DOWN}, {KEY_DPAD_UP, cc::KeyCode::ARROW_UP}, {KEY_DPAD_CENTER, cc::KeyCode::DPAD_CENTER}, - + {KEY_MOVE_HOME, cc::KeyCode::HOME}, {KEY_MOVE_END, cc::KeyCode::END}, {KEY_FORWARD_DEL, cc::KeyCode::DELETE_KEY}, @@ -211,7 +211,7 @@ int ohKeyCodeToCocosKeyCode(OH_NativeXComponent_KeyCode ohKeyCode) { {KEY_NUMPAD_DOT, cc::KeyCode::NUMPAD_DECIMAL}, {KEY_NUMPAD_COMMA, cc::KeyCode::COMMA}, {KEY_NUMPAD_EQUALS, cc::KeyCode::EQUAL}, - + {KEY_NUMPAD_0, cc::KeyCode::NUMPAD_0}, {KEY_NUMPAD_1, cc::KeyCode::NUMPAD_1}, {KEY_NUMPAD_2, cc::KeyCode::NUMPAD_2}, @@ -397,13 +397,12 @@ OpenHarmonyPlatform::OpenHarmonyPlatform() { _callback.OnSurfaceChanged = onSurfaceChangedCB; _callback.OnSurfaceDestroyed = onSurfaceDestroyedCB; _callback.DispatchTouchEvent = dispatchTouchEventCB; - #if CC_USE_GAMEPAD - _gamePad = std::make_unique(); - #endif +#if CC_USE_GAMEPAD + _gamePad = std::make_unique(); +#endif } OpenHarmonyPlatform::~OpenHarmonyPlatform() { - } int32_t OpenHarmonyPlatform::init() { diff --git a/native/cocos/platform/openharmony/OpenHarmonyPlatform.h b/native/cocos/platform/openharmony/OpenHarmonyPlatform.h index f6557bb21e..f90d9601f5 100644 --- a/native/cocos/platform/openharmony/OpenHarmonyPlatform.h +++ b/native/cocos/platform/openharmony/OpenHarmonyPlatform.h @@ -94,9 +94,9 @@ public: uv_async_t _messageSignal{}; bool _timerInited{false}; WorkerMessageQueue _messageQueue; - #if CC_USE_GAMEPAD +#if CC_USE_GAMEPAD std::unique_ptr _gamePad; - #endif +#endif // game started bool g_started{false}; bool isMouseLeftActive{false}; diff --git a/native/cocos/platform/openharmony/WorkerMessageQueue.cpp b/native/cocos/platform/openharmony/WorkerMessageQueue.cpp index 7dfc9aa31a..68665c9af9 100644 --- a/native/cocos/platform/openharmony/WorkerMessageQueue.cpp +++ b/native/cocos/platform/openharmony/WorkerMessageQueue.cpp @@ -26,13 +26,13 @@ #include "platform/openharmony/WorkerMessageQueue.h" namespace cc { - + void WorkerMessageQueue::enqueue(const WorkerMessageData& data) { std::lock_guard lck(_mutex); _queue.push(data); } -bool WorkerMessageQueue::dequeue(WorkerMessageData *data) { +bool WorkerMessageQueue::dequeue(WorkerMessageData* data) { std::lock_guard lck(_mutex); if (empty()) { return false; diff --git a/native/cocos/platform/openharmony/WorkerMessageQueue.h b/native/cocos/platform/openharmony/WorkerMessageQueue.h index 13ee7ac661..e5b3170606 100644 --- a/native/cocos/platform/openharmony/WorkerMessageQueue.h +++ b/native/cocos/platform/openharmony/WorkerMessageQueue.h @@ -27,9 +27,8 @@ #include -#include #include - +#include namespace cc { @@ -60,15 +59,15 @@ struct WorkerMessageData { class WorkerMessageQueue final { public: - void enqueue(const WorkerMessageData& data); - bool dequeue(WorkerMessageData *data); - bool empty() const; + void enqueue(const WorkerMessageData& data); + bool dequeue(WorkerMessageData* data); + bool empty() const; size_t size() const { return _queue.size(); } private: - std::mutex _mutex; + std::mutex _mutex; std::queue _queue; }; diff --git a/native/cocos/platform/openharmony/modules/Accelerometer.cpp b/native/cocos/platform/openharmony/modules/Accelerometer.cpp index 628eedf7ff..7e13d96482 100644 --- a/native/cocos/platform/openharmony/modules/Accelerometer.cpp +++ b/native/cocos/platform/openharmony/modules/Accelerometer.cpp @@ -69,21 +69,21 @@ void SensorDataCallbackImpl(Sensor_Event *event) { return; } switch (sensorType) { - case SENSOR_TYPE_ACCELEROMETER: - motionValue.accelerationIncludingGravityX = data[0]; - motionValue.accelerationIncludingGravityY = data[1]; - motionValue.accelerationIncludingGravityZ = -data[2]; - break; - case SENSOR_TYPE_LINEAR_ACCELERATION: - motionValue.accelerationX = data[0]; - motionValue.accelerationY = data[1]; - motionValue.accelerationZ = data[2]; - break; - case SENSOR_TYPE_GYROSCOPE: - motionValue.rotationRateAlpha = radiansToDegrees(data[0]); - motionValue.rotationRateBeta = radiansToDegrees(data[1]); - motionValue.rotationRateGamma = radiansToDegrees(data[2]); - break; + case SENSOR_TYPE_ACCELEROMETER: + motionValue.accelerationIncludingGravityX = data[0]; + motionValue.accelerationIncludingGravityY = data[1]; + motionValue.accelerationIncludingGravityZ = -data[2]; + break; + case SENSOR_TYPE_LINEAR_ACCELERATION: + motionValue.accelerationX = data[0]; + motionValue.accelerationY = data[1]; + motionValue.accelerationZ = data[2]; + break; + case SENSOR_TYPE_GYROSCOPE: + motionValue.rotationRateAlpha = radiansToDegrees(data[0]); + motionValue.rotationRateBeta = radiansToDegrees(data[1]); + motionValue.rotationRateGamma = radiansToDegrees(data[2]); + break; } } @@ -123,7 +123,7 @@ static void disableSensor(int index) { Sensor_SubscriptionAttribute *at = g_attr[index]; Sensor_Subscriber *gUser = g_user[index]; - if(it == nullptr || at == nullptr || gUser == nullptr) { + if (it == nullptr || at == nullptr || gUser == nullptr) { return; } ret = OH_Sensor_Unsubscribe(it, gUser); diff --git a/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.cpp b/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.cpp index 2bd0e69de1..79b25d591d 100644 --- a/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.cpp +++ b/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.cpp @@ -24,12 +24,12 @@ ****************************************************************************/ #include "platform/openharmony/modules/CanvasRenderingContext2DDelegate.h" -#include +#include #include #include -#include #include -#include +#include +#include namespace cc { namespace { @@ -46,24 +46,30 @@ void unMultiplyAlpha(unsigned char *ptr, ssize_t size) { } } } -} -enum class TextAlign { LEFT, CENTER, RIGHT }; +} // namespace +enum class TextAlign { LEFT, + CENTER, + RIGHT }; -enum class TextBaseline { TOP, MIDDLE, BOTTOM, ALPHABETIC }; +enum class TextBaseline { TOP, + MIDDLE, + BOTTOM, + ALPHABETIC }; class CanvasRenderingContext2DDelegate::ScopedTypography { public: - ScopedTypography(OH_Drawing_Typography* typography) :_typegraphy(typography) {} + ScopedTypography(OH_Drawing_Typography *typography) : _typegraphy(typography) {} ~ScopedTypography() { - if(_typegraphy) { + if (_typegraphy) { OH_Drawing_DestroyTypography(_typegraphy); } } - OH_Drawing_Typography* get() { + OH_Drawing_Typography *get() { return _typegraphy; } + private: - OH_Drawing_Typography* _typegraphy{nullptr}; + OH_Drawing_Typography *_typegraphy{nullptr}; }; CanvasRenderingContext2DDelegate::CanvasRenderingContext2DDelegate() { @@ -77,17 +83,17 @@ CanvasRenderingContext2DDelegate::CanvasRenderingContext2DDelegate() { } CanvasRenderingContext2DDelegate::~CanvasRenderingContext2DDelegate() { - if(_typographyStyle) { + if (_typographyStyle) { OH_Drawing_DestroyTypographyStyle(_typographyStyle); _typographyStyle = nullptr; } - if(_typographyCreate) { + if (_typographyCreate) { OH_Drawing_DestroyTypographyHandler(_typographyCreate); _typographyCreate = nullptr; } - if(_textStyle) { + if (_textStyle) { OH_Drawing_DestroyTextStyle(_textStyle); _textStyle = nullptr; } @@ -97,12 +103,12 @@ CanvasRenderingContext2DDelegate::~CanvasRenderingContext2DDelegate() { _strokeTextStyle = nullptr; } - if(_canvas) { + if (_canvas) { OH_Drawing_CanvasDestroy(_canvas); _canvas = nullptr; } - if(_bitmap) { + if (_bitmap) { OH_Drawing_BitmapDestroy(_bitmap); _bitmap = nullptr; } @@ -114,23 +120,23 @@ CanvasRenderingContext2DDelegate::~CanvasRenderingContext2DDelegate() { } void CanvasRenderingContext2DDelegate::recreateBuffer(float w, float h) { - _bufferWidth = w; + _bufferWidth = w; _bufferHeight = h; if (_bufferWidth < 1.0F || _bufferHeight < 1.0F) { return; } - if(_canvas) { + if (_canvas) { OH_Drawing_CanvasDestroy(_canvas); _canvas = nullptr; } - if(_bitmap) { + if (_bitmap) { OH_Drawing_BitmapDestroy(_bitmap); _bitmap = nullptr; } _bufferSize = static_cast(_bufferWidth * _bufferHeight * 4); - auto *data = static_cast(malloc(sizeof(uint8_t) * _bufferSize)); + auto *data = static_cast(malloc(sizeof(uint8_t) * _bufferSize)); memset(data, 0x00, _bufferSize); _imageData.fastSet(data, _bufferSize); @@ -185,14 +191,14 @@ void CanvasRenderingContext2DDelegate::fillRect(float x, float y, float w, float uint8_t b = static_cast(_fillStyle[2]); uint8_t a = static_cast(_fillStyle[3]); - OH_Drawing_Path* path = OH_Drawing_PathCreate(); + OH_Drawing_Path *path = OH_Drawing_PathCreate(); OH_Drawing_PathMoveTo(path, x, y); OH_Drawing_PathLineTo(path, x + w, y); OH_Drawing_PathLineTo(path, x + w, y + h); OH_Drawing_PathLineTo(path, x, y + h); OH_Drawing_PathLineTo(path, x, y); OH_Drawing_PathClose(path); - OH_Drawing_Brush* brush = OH_Drawing_BrushCreate(); + OH_Drawing_Brush *brush = OH_Drawing_BrushCreate(); OH_Drawing_BrushSetColor(brush, OH_Drawing_ColorSetArgb(a, r, g, b)); OH_Drawing_CanvasAttachBrush(_canvas, brush); OH_Drawing_CanvasDrawPath(_canvas, path); @@ -200,12 +206,11 @@ void CanvasRenderingContext2DDelegate::fillRect(float x, float y, float w, float void CanvasRenderingContext2DDelegate::setPremultiply(bool multiply) { _premultiply = multiply; } - void CanvasRenderingContext2DDelegate::fillText(const ccstd::string &text, float x, float y, float /*maxWidth*/) { if (text.empty() || _bufferWidth < 1.0F || _bufferHeight < 1.0F) { return; } - Size textSize = {0, 0}; + Size textSize = {0, 0}; uint8_t r = static_cast(_fillStyle[0]); uint8_t g = static_cast(_fillStyle[1]); uint8_t b = static_cast(_fillStyle[2]); @@ -223,7 +228,7 @@ void CanvasRenderingContext2DDelegate::strokeText(const ccstd::string &text, flo OH_Drawing_PenDestroy(_pen); _pen = nullptr; } - + if (_strokeTextStyle) { OH_Drawing_DestroyTextStyle(_strokeTextStyle); _strokeTextStyle = nullptr; @@ -249,14 +254,14 @@ void CanvasRenderingContext2DDelegate::strokeText(const ccstd::string &text, flo CanvasRenderingContext2DDelegate::Size CanvasRenderingContext2DDelegate::measureText(const ccstd::string &text) { auto typography = createTypography(text, _textStyle); return ccstd::array{static_cast(OH_Drawing_TypographyGetMaxIntrinsicWidth(typography->get())), - static_cast(OH_Drawing_TypographyGetHeight(typography->get()))}; + static_cast(OH_Drawing_TypographyGetHeight(typography->get()))}; } void CanvasRenderingContext2DDelegate::updateFont(const ccstd::string &fontName, - float fontSize, - bool bold, - bool italic, - bool oblique, + float fontSize, + bool bold, + bool italic, + bool oblique, bool /* smallCaps */) { _fontName = fontName; _fontSize = static_cast(fontSize); @@ -324,7 +329,7 @@ void CanvasRenderingContext2DDelegate::setLineWidth(float lineWidth) { } const cc::Data &CanvasRenderingContext2DDelegate::getDataRef() const { - void* bitmapAddr = OH_Drawing_BitmapGetPixels(_bitmap); + void *bitmapAddr = OH_Drawing_BitmapGetPixels(_bitmap); memcpy(_imageData.getBytes(), bitmapAddr, _bufferSize); return _imageData; } @@ -354,9 +359,9 @@ void CanvasRenderingContext2DDelegate::fillTextureData() { ccstd::array CanvasRenderingContext2DDelegate::convertDrawPoint(Point point, const ccstd::string &text, OH_Drawing_TextStyle *textStyle) { auto typography = createTypography(text, textStyle); - Size textSize {static_cast(OH_Drawing_TypographyGetMaxIntrinsicWidth(typography->get())), - static_cast(OH_Drawing_TypographyGetHeight(typography->get()))}; - + Size textSize{static_cast(OH_Drawing_TypographyGetMaxIntrinsicWidth(typography->get())), + static_cast(OH_Drawing_TypographyGetHeight(typography->get()))}; + if (_textAlign == TextAlign::CENTER) { point[0] -= textSize[0] / 2.0f; } else if (_textAlign == TextAlign::RIGHT) { @@ -381,12 +386,11 @@ std::unique_ptr CanvasRender OH_Drawing_TypographyHandlerPushTextStyle(_typographyCreate, textStyle); OH_Drawing_TypographyHandlerAddText(_typographyCreate, text.c_str()); OH_Drawing_TypographyHandlerPopTextStyle(_typographyCreate); - OH_Drawing_Typography* typography = OH_Drawing_CreateTypography(_typographyCreate); + OH_Drawing_Typography *typography = OH_Drawing_CreateTypography(_typographyCreate); OH_Drawing_TypographyLayout(typography, _bufferWidth); return std::make_unique(typography); } - void CanvasRenderingContext2DDelegate::fill() { } @@ -410,7 +414,6 @@ void CanvasRenderingContext2DDelegate::rect(float /* x */, } void CanvasRenderingContext2DDelegate::updateData() { - } } // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.h b/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.h index b5d8bfafd7..b3577a1f6d 100644 --- a/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.h +++ b/native/cocos/platform/openharmony/modules/CanvasRenderingContext2DDelegate.h @@ -29,12 +29,12 @@ #include #include -#include #include +#include -#include #include #include +#include #include "base/csscolorparser.h" #include "cocos/bindings/manual/jsb_platform.h" @@ -45,100 +45,100 @@ namespace cc { class CanvasRenderingContext2DDelegate : public ICanvasRenderingContext2D::Delegate { public: - using Point = ccstd::array; - using Vec2 = ccstd::array; - using Size = ccstd::array; + using Point = ccstd::array; + using Vec2 = ccstd::array; + using Size = ccstd::array; using Color4F = ccstd::array; using TextAlign = ICanvasRenderingContext2D::TextAlign; using TextBaseline = ICanvasRenderingContext2D::TextBaseline; - + CanvasRenderingContext2DDelegate(); ~CanvasRenderingContext2DDelegate() override; - void recreateBuffer(float w, float h) override; - void beginPath() override; - void closePath() override; - void moveTo(float x, float y) override; - void lineTo(float x, float y) override; - void stroke() override; - void saveContext() override; - void restoreContext() override; - void clearRect(float /*x*/, float /*y*/, float w, float h) override; - void fillRect(float x, float y, float w, float h) override; - void fillText(const ccstd::string &text, float x, float y, float /*maxWidth*/) override; - void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override; - Size measureText(const ccstd::string &text) override; - void updateFont(const ccstd::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) override; - void setTextAlign(TextAlign align) override; - void setTextBaseline(TextBaseline baseline) override; - void setFillStyle(uint8_t r, uint8_t g, uint8_t b, uint8_t a) override; - void setStrokeStyle(uint8_t r, uint8_t g, uint8_t b, uint8_t a) override; - void setLineWidth(float lineWidth) override; + void recreateBuffer(float w, float h) override; + void beginPath() override; + void closePath() override; + void moveTo(float x, float y) override; + void lineTo(float x, float y) override; + void stroke() override; + void saveContext() override; + void restoreContext() override; + void clearRect(float /*x*/, float /*y*/, float w, float h) override; + void fillRect(float x, float y, float w, float h) override; + void fillText(const ccstd::string &text, float x, float y, float /*maxWidth*/) override; + void strokeText(const ccstd::string &text, float /*x*/, float /*y*/, float /*maxWidth*/) override; + Size measureText(const ccstd::string &text) override; + void updateFont(const ccstd::string &fontName, float fontSize, bool bold, bool italic, bool oblique, bool smallCaps) override; + void setTextAlign(TextAlign align) override; + void setTextBaseline(TextBaseline baseline) override; + void setFillStyle(uint8_t r, uint8_t g, uint8_t b, uint8_t a) override; + void setStrokeStyle(uint8_t r, uint8_t g, uint8_t b, uint8_t a) override; + void setLineWidth(float lineWidth) override; const cc::Data &getDataRef() const override; - void fill() override; - void setLineCap(const ccstd::string &lineCap) override; - void setLineJoin(const ccstd::string &lineCap) override; - void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override; - void rect(float x, float y, float w, float h) override; - void setShadowBlur(float blur)override{} - void setShadowColor(uint8_t r, uint8_t g, uint8_t b, uint8_t a) override{} - void setShadowOffsetX(float offsetX) override{} - void setShadowOffsetY(float offsetY) override{} - void updateData() override; - void setTextStyle(OH_Drawing_TextStyle *textStyle); + void fill() override; + void setLineCap(const ccstd::string &lineCap) override; + void setLineJoin(const ccstd::string &lineCap) override; + void fillImageData(const Data &imageData, float imageWidth, float imageHeight, float offsetX, float offsetY) override; + void rect(float x, float y, float w, float h) override; + void setShadowBlur(float blur) override {} + void setShadowColor(uint8_t r, uint8_t g, uint8_t b, uint8_t a) override {} + void setShadowOffsetX(float offsetX) override {} + void setShadowOffsetY(float offsetY) override {} + void updateData() override; + void setTextStyle(OH_Drawing_TextStyle *textStyle); + private: - static wchar_t * utf8ToUtf16(const ccstd::string &str, int *pRetLen = nullptr); - void removeCustomFont(); - int drawText(const ccstd::string &text, int x, int y); - Size sizeWithText(const wchar_t *pszText, int nLen); - void prepareBitmap(int nWidth, int nHeight); - void deleteBitmap(); - void fillTextureData(); + static wchar_t *utf8ToUtf16(const ccstd::string &str, int *pRetLen = nullptr); + void removeCustomFont(); + int drawText(const ccstd::string &text, int x, int y); + Size sizeWithText(const wchar_t *pszText, int nLen); + void prepareBitmap(int nWidth, int nHeight); + void deleteBitmap(); + void fillTextureData(); ccstd::array convertDrawPoint(Point point, const ccstd::string &text, OH_Drawing_TextStyle *textStyle); class ScopedTypography; std::unique_ptr createTypography(const ccstd::string &text, OH_Drawing_TextStyle *textStyle); void setPremultiply(bool multiply); + public: - int _screen{0}; + int _screen{0}; private: - int32_t _x{0}; int32_t _y{0}; int32_t _lineCap{0}; int32_t _lineJoin{0}; private: - OH_Drawing_Bitmap* _bitmap{nullptr}; - OH_Drawing_BitmapFormat _format {COLOR_FORMAT_RGBA_8888, ALPHA_FORMAT_OPAQUE}; - OH_Drawing_Canvas* _canvas{nullptr}; - OH_Drawing_TypographyStyle* _typographyStyle{nullptr}; - OH_Drawing_TypographyCreate* _typographyCreate{nullptr}; - OH_Drawing_FontCollection* _fontCollection{nullptr}; - OH_Drawing_TextStyle* _textStyle{nullptr}; + OH_Drawing_Bitmap *_bitmap{nullptr}; + OH_Drawing_BitmapFormat _format{COLOR_FORMAT_RGBA_8888, ALPHA_FORMAT_OPAQUE}; + OH_Drawing_Canvas *_canvas{nullptr}; + OH_Drawing_TypographyStyle *_typographyStyle{nullptr}; + OH_Drawing_TypographyCreate *_typographyCreate{nullptr}; + OH_Drawing_FontCollection *_fontCollection{nullptr}; + OH_Drawing_TextStyle *_textStyle{nullptr}; OH_Drawing_TextStyle *_strokeTextStyle{nullptr}; OH_Drawing_Pen *_pen{nullptr}; - cc::Data _imageData; + cc::Data _imageData; ccstd::string _curFontPath; - int _savedDC{0}; - float _lineWidth{0.0F}; - float _bufferWidth{0.0F}; - float _bufferHeight{0.0F}; - int32_t _bufferSize{0}; + int _savedDC{0}; + float _lineWidth{0.0F}; + float _bufferWidth{0.0F}; + float _bufferHeight{0.0F}; + int32_t _bufferSize{0}; - ccstd::string _fontName; - int _fontSize{0}; - Size _textSize; - TextAlign _textAlign{TextAlign::CENTER}; - TextBaseline _textBaseLine{TextBaseline::TOP}; - Color4F _fillStyle{0}; - Color4F _strokeStyle{0}; - bool _bold{false}; - bool _italic{false}; - bool _premultiply{true}; - + ccstd::string _fontName; + int _fontSize{0}; + Size _textSize; + TextAlign _textAlign{TextAlign::CENTER}; + TextBaseline _textBaseLine{TextBaseline::TOP}; + Color4F _fillStyle{0}; + Color4F _strokeStyle{0}; + bool _bold{false}; + bool _italic{false}; + bool _premultiply{true}; }; } // namespace cc diff --git a/native/cocos/platform/openharmony/modules/Screen.cpp b/native/cocos/platform/openharmony/modules/Screen.cpp index e159957361..5b6d284a9e 100644 --- a/native/cocos/platform/openharmony/modules/Screen.cpp +++ b/native/cocos/platform/openharmony/modules/Screen.cpp @@ -83,28 +83,28 @@ Vec4 Screen::getSafeAreaEdge() const { float safearea_bottom = 0.0f; float safearea_right = 0.0f; - if(0 == avoidSide) { + if (0 == avoidSide) { auto top = NapiHelper::napiCallFunction("getCutoutToTop"); int32_t cutout_top = 0; if (top.IsNumber()) { cutout_top = top.As().Int32Value(); } safearea_top += cutout_top; - } else if(1 == avoidSide) { + } else if (1 == avoidSide) { auto right = NapiHelper::napiCallFunction("getCutoutToRight"); int32_t cutout_right = 0; if (right.IsNumber()) { cutout_right = right.As().Int32Value(); } safearea_right += cutout_right; - } else if(2 == avoidSide) { + } else if (2 == avoidSide) { auto bottom = NapiHelper::napiCallFunction("getCutoutToBottom"); int32_t cutout_bottom = 0; if (bottom.IsNumber()) { cutout_bottom = bottom.As().Int32Value(); } safearea_bottom += cutout_bottom; - } else if(3 == avoidSide) { + } else if (3 == avoidSide) { auto left = NapiHelper::napiCallFunction("getCutoutToLeft"); int32_t cutout_left = 0; if (left.IsNumber()) { @@ -112,7 +112,7 @@ Vec4 Screen::getSafeAreaEdge() const { } safearea_left += cutout_left; } - + return Vec4(safearea_top, safearea_left, safearea_bottom, safearea_right); } diff --git a/native/cocos/platform/openharmony/modules/System.cpp b/native/cocos/platform/openharmony/modules/System.cpp index 4e4c64d320..84952fdfc7 100644 --- a/native/cocos/platform/openharmony/modules/System.cpp +++ b/native/cocos/platform/openharmony/modules/System.cpp @@ -90,7 +90,7 @@ std::string System::getCurrentLanguageCode() const { } auto str = ret.As().Utf8Value(); std::string::size_type pos = str.find('-'); - if(pos != std::string::npos) { + if (pos != std::string::npos) { str = str.substr(0, pos); } return str; diff --git a/native/cocos/platform/openharmony/modules/SystemWindow.cpp b/native/cocos/platform/openharmony/modules/SystemWindow.cpp index 32e8c01b27..974c703505 100644 --- a/native/cocos/platform/openharmony/modules/SystemWindow.cpp +++ b/native/cocos/platform/openharmony/modules/SystemWindow.cpp @@ -31,7 +31,7 @@ namespace cc { -SystemWindow::SystemWindow(uint32_t windowId, void *externalHandle) +SystemWindow::SystemWindow(uint32_t windowId, void* externalHandle) : _windowId(windowId) { if (externalHandle) { _windowHandle = reinterpret_cast(externalHandle); @@ -56,7 +56,6 @@ bool SystemWindow::createWindow(const char* title, return true; } - void SystemWindow::setCursorEnabled(bool value) { } @@ -86,5 +85,4 @@ SystemWindow::Size SystemWindow::getViewSize() const { static_cast(_height)}; } - } // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/openharmony/modules/SystemWindow.h b/native/cocos/platform/openharmony/modules/SystemWindow.h index b13a2762a9..3f50ac124f 100644 --- a/native/cocos/platform/openharmony/modules/SystemWindow.h +++ b/native/cocos/platform/openharmony/modules/SystemWindow.h @@ -27,8 +27,8 @@ #include -#include "platform/interfaces/modules/ISystemWindow.h" #include +#include "platform/interfaces/modules/ISystemWindow.h" namespace cc { @@ -36,7 +36,7 @@ class SystemWindow : public ISystemWindow { public: explicit SystemWindow(uint32_t windowId, void* externalHandle); ~SystemWindow() override; - + bool createWindow(const char* title, int x, int y, int w, int h, int flags) override; @@ -50,7 +50,7 @@ public: /** @brief enable/disable(lock) the cursor, default is enabled */ - void setCursorEnabled(bool value) override; + void setCursorEnabled(bool value) override; private: void* _windowHandle{nullptr}; diff --git a/native/cocos/platform/openharmony/modules/SystemWindowManager.cpp b/native/cocos/platform/openharmony/modules/SystemWindowManager.cpp index caf1d9ebfb..ce702cddf6 100644 --- a/native/cocos/platform/openharmony/modules/SystemWindowManager.cpp +++ b/native/cocos/platform/openharmony/modules/SystemWindowManager.cpp @@ -60,7 +60,6 @@ ISystemWindow *SystemWindowManager::getWindow(uint32_t windowId) const { return nullptr; } - ISystemWindow *SystemWindowManager::getWindowFromHandle(void *window) const { if (!window) { return nullptr; @@ -75,7 +74,7 @@ ISystemWindow *SystemWindowManager::getWindowFromHandle(void *window) const { return nullptr; } -void SystemWindowManager::removeWindow(void* window) { +void SystemWindowManager::removeWindow(void *window) { if (!window) { return; } diff --git a/native/cocos/platform/openharmony/modules/SystemWindowManager.h b/native/cocos/platform/openharmony/modules/SystemWindowManager.h index 46395d5006..375ac71fcc 100644 --- a/native/cocos/platform/openharmony/modules/SystemWindowManager.h +++ b/native/cocos/platform/openharmony/modules/SystemWindowManager.h @@ -41,8 +41,9 @@ public: ISystemWindow *createWindow(const ISystemWindowInfo &info) override; ISystemWindow *getWindow(uint32_t windowId) const override; const SystemWindowMap &getWindows() const override { return _windows; } - ISystemWindow *getWindowFromHandle(void* handle) const; - void removeWindow(void* window); + ISystemWindow *getWindowFromHandle(void *handle) const; + void removeWindow(void *window); + private: uint32_t _nextWindowId{1}; // start from 1, 0 means an invalid ID diff --git a/native/cocos/renderer/GFXDeviceManager.h b/native/cocos/renderer/GFXDeviceManager.h index 0804ceb9ff..6d1a00ce26 100644 --- a/native/cocos/renderer/GFXDeviceManager.h +++ b/native/cocos/renderer/GFXDeviceManager.h @@ -83,10 +83,10 @@ public: #ifdef CC_USE_VULKAN bool skipVulkan = false; -#if CC_PLATFORM == CC_PLATFORM_ANDROID + #if CC_PLATFORM == CC_PLATFORM_ANDROID auto sdkVersion = BasePlatform::getPlatform()->getSdkVersion(); skipVulkan = sdkVersion <= 27; // Android 8 -#endif + #endif if (!skipVulkan && tryCreate(info, &device)) return device; #endif diff --git a/native/cocos/renderer/core/PassUtils.cpp b/native/cocos/renderer/core/PassUtils.cpp index d973a282f1..a4e8e5c0f8 100644 --- a/native/cocos/renderer/core/PassUtils.cpp +++ b/native/cocos/renderer/core/PassUtils.cpp @@ -35,38 +35,38 @@ const ccstd::unordered_map type2reader = { CC_LOG_ERROR("type2reader unknown type"); }}, {gfx::Type::INT, [](const float *a, MaterialProperty &v, index_t idx) { - v = static_cast(a[idx]); + v = static_cast(a[idx]); }}, {gfx::Type::INT2, [](const float *a, MaterialProperty &v, index_t idx) { - v = Vec2(a[idx], a[idx + 1]); + v = Vec2(a[idx], a[idx + 1]); }}, {gfx::Type::INT3, [](const float *a, MaterialProperty &v, index_t idx) { - v = Vec3(a[idx], a[idx + 1], a[idx + 2]); + v = Vec3(a[idx], a[idx + 1], a[idx + 2]); }}, {gfx::Type::INT4, [](const float *a, MaterialProperty &v, index_t idx) { - v = Vec4(a[idx], a[idx + 1], a[idx + 2], a[idx + 3]); + v = Vec4(a[idx], a[idx + 1], a[idx + 2], a[idx + 3]); }}, {gfx::Type::FLOAT, [](const float *a, MaterialProperty &v, index_t idx) { - v = a[idx]; + v = a[idx]; }}, {gfx::Type::FLOAT2, [](const float *a, MaterialProperty &v, index_t idx) { - v = Vec2(a[idx], a[idx + 1]); + v = Vec2(a[idx], a[idx + 1]); }}, {gfx::Type::FLOAT3, [](const float *a, MaterialProperty &v, index_t idx) { - v = Vec3(a[idx], a[idx + 1], a[idx + 2]); + v = Vec3(a[idx], a[idx + 1], a[idx + 2]); }}, {gfx::Type::FLOAT4, [](const float *a, MaterialProperty &v, index_t idx) { - v = Vec4(a[idx], a[idx + 1], a[idx + 2], a[idx + 3]); + v = Vec4(a[idx], a[idx + 1], a[idx + 2], a[idx + 3]); }}, {gfx::Type::MAT3, [](const float *a, MaterialProperty &v, index_t idx) { - Mat3 mat3; - memcpy(&mat3.m[0], &a[idx], sizeof(Mat3)); - v = mat3; + Mat3 mat3; + memcpy(&mat3.m[0], &a[idx], sizeof(Mat3)); + v = mat3; }}, {gfx::Type::MAT4, [](const float *a, MaterialProperty &v, index_t idx) { - Mat4 mat4; - memcpy(&mat4.m[0], &a[idx], sizeof(Mat4)); - v = mat4; + Mat4 mat4; + memcpy(&mat4.m[0], &a[idx], sizeof(Mat4)); + v = mat4; }}, }; diff --git a/native/cocos/renderer/frame-graph/DevicePass.cpp b/native/cocos/renderer/frame-graph/DevicePass.cpp index 874ea5119f..f783c36973 100644 --- a/native/cocos/renderer/frame-graph/DevicePass.cpp +++ b/native/cocos/renderer/frame-graph/DevicePass.cpp @@ -158,7 +158,7 @@ void DevicePass::passDependency(gfx::RenderPassInfo &rpInfo) { nullptr, {}, {}, - }); + }); for (const auto &rearBarrier : _barriers[barrierID].get().rearBarriers) { const auto &res = getBarrier(rearBarrier, &_resourceTable); diff --git a/native/cocos/renderer/gfx-agent/DeviceAgent.h b/native/cocos/renderer/gfx-agent/DeviceAgent.h index ce11e0feb5..1e1466a407 100644 --- a/native/cocos/renderer/gfx-agent/DeviceAgent.h +++ b/native/cocos/renderer/gfx-agent/DeviceAgent.h @@ -107,6 +107,7 @@ public: void enableAutoBarrier(bool en) override; SampleCount getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const override; + protected: static DeviceAgent *instance; diff --git a/native/cocos/renderer/gfx-base/GFXDef-common.h b/native/cocos/renderer/gfx-base/GFXDef-common.h index 4d4310f7f3..6dac936b87 100644 --- a/native/cocos/renderer/gfx-base/GFXDef-common.h +++ b/native/cocos/renderer/gfx-base/GFXDef-common.h @@ -179,7 +179,7 @@ enum class Feature : uint32_t { SUBPASS_DEPTH_STENCIL_INPUT, RASTERIZATION_ORDER_NOCOHERENT, - MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL, // resolve depth stencil + MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL, // resolve depth stencil COUNT, }; CC_ENUM_CONVERSION_OPERATOR(Feature); @@ -350,7 +350,7 @@ enum class FormatType : uint32_t { }; CC_ENUM_CONVERSION_OPERATOR(FormatType); -enum class SampleType: uint32_t { +enum class SampleType : uint32_t { FLOAT, UNFILTERABLE_FLOAT, SINT, @@ -465,7 +465,7 @@ enum class TextureType : uint32_t { }; CC_ENUM_CONVERSION_OPERATOR(TextureType); -enum class ViewDimension: uint32_t { +enum class ViewDimension : uint32_t { UNKNOWN, BUFFER, TEX1D, @@ -521,10 +521,10 @@ using FormatFeature = FormatFeatureBit; CC_ENUM_BITWISE_OPERATORS(FormatFeatureBit); enum class SampleCount : uint32_t { - X1 = 0x01, - X2 = 0x02, - X4 = 0x04, - X8 = 0x08, + X1 = 0x01, + X2 = 0x02, + X4 = 0x04, + X8 = 0x08, X16 = 0x10, X32 = 0x20, X64 = 0x40 @@ -1441,7 +1441,7 @@ using BufferBarrierInfoList = ccstd::vector; struct FramebufferInfo { RenderPass *renderPass{nullptr}; TextureList colorTextures; - Texture *depthStencilTexture{nullptr}; // @ts-nullable + Texture *depthStencilTexture{nullptr}; // @ts-nullable Texture *depthStencilResolveTexture{nullptr}; // @ts-nullable EXPOSE_COPY_FN(FramebufferInfo) diff --git a/native/cocos/renderer/gfx-base/GFXTexture.cpp b/native/cocos/renderer/gfx-base/GFXTexture.cpp index 59432996a0..07f25fa579 100644 --- a/native/cocos/renderer/gfx-base/GFXTexture.cpp +++ b/native/cocos/renderer/gfx-base/GFXTexture.cpp @@ -131,8 +131,8 @@ void Texture::updateTextureInfo(const SwapchainTextureInfo &info, Texture *out) out->_info.samples = SampleCount::X1; out->_info.flags = TextureFlagBit::NONE; out->_info.usage = TextureUsageBit::SAMPLED | (GFX_FORMAT_INFOS[toNumber(info.format)].hasDepth - ? TextureUsageBit::DEPTH_STENCIL_ATTACHMENT - : TextureUsageBit::COLOR_ATTACHMENT); + ? TextureUsageBit::DEPTH_STENCIL_ATTACHMENT + : TextureUsageBit::COLOR_ATTACHMENT); out->_swapchain = info.swapchain; out->_size = formatSize(info.format, info.width, info.height, 1); out->_hash = computeHash(out); diff --git a/native/cocos/renderer/gfx-base/SPIRVUtils.cpp b/native/cocos/renderer/gfx-base/SPIRVUtils.cpp index cd2a54e3bd..11a7b33106 100644 --- a/native/cocos/renderer/gfx-base/SPIRVUtils.cpp +++ b/native/cocos/renderer/gfx-base/SPIRVUtils.cpp @@ -31,10 +31,10 @@ #include "glslang/StandAlone/ResourceLimits.h" #include "spirv/spirv.h" -#define CC_GLSLANG_VERSION_GREATOR_OR_EQUAL_TO(major, minor, patch) \ - (((major) < GLSLANG_VERSION_MAJOR) || ((major) == GLSLANG_VERSION_MAJOR && \ - (((minor) < GLSLANG_VERSION_MINOR) || ((minor) == GLSLANG_VERSION_MINOR && \ - ((patch) <= GLSLANG_VERSION_PATCH))))) +#define CC_GLSLANG_VERSION_GREATOR_OR_EQUAL_TO(major, minor, patch) \ + (((major) < GLSLANG_VERSION_MAJOR) || ((major) == GLSLANG_VERSION_MAJOR && \ + (((minor) < GLSLANG_VERSION_MINOR) || ((minor) == GLSLANG_VERSION_MINOR && \ + ((patch) <= GLSLANG_VERSION_PATCH))))) namespace cc { namespace gfx { diff --git a/native/cocos/renderer/gfx-empty/EmptyDevice.h b/native/cocos/renderer/gfx-empty/EmptyDevice.h index 8cc420a54b..2c43f7b248 100644 --- a/native/cocos/renderer/gfx-empty/EmptyDevice.h +++ b/native/cocos/renderer/gfx-empty/EmptyDevice.h @@ -54,7 +54,7 @@ public: using Device::createTexture; using Device::createTextureBarrier; - void frameSync() override {}; + void frameSync() override{}; void acquire(Swapchain *const *swapchains, uint32_t count) override; void present() override; diff --git a/native/cocos/renderer/gfx-gles2/GLES2Device.h b/native/cocos/renderer/gfx-gles2/GLES2Device.h index 0b7269005f..253848b3e8 100644 --- a/native/cocos/renderer/gfx-gles2/GLES2Device.h +++ b/native/cocos/renderer/gfx-gles2/GLES2Device.h @@ -96,6 +96,7 @@ public: // check the specified format is texture-exclusive (no renderbuffers allowed) inline bool isTextureExclusive(const Format &format) { return _textureExclusive[static_cast(format)]; }; SampleCount getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const override; + protected: static GLES2Device *instance; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp index e853f1ddd3..9bfcb33920 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Commands.cpp @@ -872,7 +872,7 @@ static void textureStorage(GLES3Device *device, GLES3GPUTexture *gpuTexture) { static bool useRenderBuffer(const GLES3Device *device, Format format, TextureUsage usage) { return !device->isTextureExclusive(format) && - hasAllFlags(TextureUsage::COLOR_ATTACHMENT | TextureUsage::DEPTH_STENCIL_ATTACHMENT, usage); + hasAllFlags(TextureUsage::COLOR_ATTACHMENT | TextureUsage::DEPTH_STENCIL_ATTACHMENT, usage); } void cmdFuncGLES3CreateTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) { @@ -882,7 +882,7 @@ void cmdFuncGLES3CreateTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) bool supportRenderBufferMS = device->constantRegistry()->mMSRT > MSRTSupportLevel::NONE; gpuTexture->useRenderBuffer = useRenderBuffer(device, gpuTexture->format, gpuTexture->usage) && - (gpuTexture->glSamples <= 1 || supportRenderBufferMS); + (gpuTexture->glSamples <= 1 || supportRenderBufferMS); if (gpuTexture->glSamples > 1) { // Allocate render buffer when binding a framebuffer if the MSRT extension is not present. @@ -941,12 +941,12 @@ void cmdFuncGLES3ResizeTexture(GLES3Device *device, GLES3GPUTexture *gpuTexture) // immutable by default cmdFuncGLES3DestroyTexture(device, gpuTexture); cmdFuncGLES3CreateTexture(device, gpuTexture); - } else if (gpuTexture->size > 0){ + } else if (gpuTexture->size > 0) { renderBufferStorage(device, gpuTexture); } } -void cmdFuncGLES3CreateTextureView(GLES3Device */*device*/, GLES3GPUTextureView *gpuTextureView) { +void cmdFuncGLES3CreateTextureView(GLES3Device * /*device*/, GLES3GPUTextureView *gpuTextureView) { gpuTextureView->glTarget = getTextureViewTarget(gpuTextureView); } @@ -1396,7 +1396,7 @@ void cmdFuncGLES3CreateRenderPass(GLES3Device * /*device*/, GLES3GPURenderPass * std::vector visited(gpuRenderPass->colorAttachments.size() + hasDS); for (auto &input : sub.inputs) { visited[input] = true; - if(input == gpuRenderPass->colorAttachments.size()) { + if (input == gpuRenderPass->colorAttachments.size()) { // ds input continue; } @@ -1426,7 +1426,6 @@ void cmdFuncGLES3CreateRenderPass(GLES3Device * /*device*/, GLES3GPURenderPass * } } - if (sub.depthStencil != gfx::INVALID_BINDING) { gpuRenderPass->depthStencil = sub.depthStencil; gpuRenderPass->indices.back() = gpuRenderPass->depthStencil; @@ -3107,8 +3106,8 @@ void GLES3GPUFramebufferObject::bindDepthStencilMultiSample(const GLES3GPUTextur bool hasDepth = info.hasDepth; bool hasStencil = info.hasStencil; - dsAttachment = hasDepth && hasStencil ? GL_DEPTH_STENCIL_ATTACHMENT : - hasDepth ? GL_DEPTH_ATTACHMENT : GL_STENCIL_ATTACHMENT; + dsAttachment = hasDepth && hasStencil ? GL_DEPTH_STENCIL_ATTACHMENT : hasDepth ? GL_DEPTH_ATTACHMENT + : GL_STENCIL_ATTACHMENT; if (hasDepth) { auto att = isDefaultFb ? GL_DEPTH : GL_DEPTH_ATTACHMENT; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp index e081883bec..f20da464e3 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.cpp @@ -132,17 +132,17 @@ bool GLES3Device::doInit(const DeviceInfo & /*info*/) { if (*it == CC_TOSTR(GL_EXT_shader_framebuffer_fetch_non_coherent)) { _gpuConstantRegistry->mFBF = FBFSupportLevel::NON_COHERENT_EXT; _features[toNumber(Feature::RASTERIZATION_ORDER_NOCOHERENT)] = true; - fbfLevelStr = "NON_COHERENT_EXT"; + fbfLevelStr = "NON_COHERENT_EXT"; } else if (*it == CC_TOSTR(GL_QCOM_shader_framebuffer_fetch_noncoherent)) { _gpuConstantRegistry->mFBF = FBFSupportLevel::NON_COHERENT_QCOM; - fbfLevelStr = "NON_COHERENT_QCOM"; + fbfLevelStr = "NON_COHERENT_QCOM"; _features[toNumber(Feature::RASTERIZATION_ORDER_NOCOHERENT)] = true; GL_CHECK(glEnable(GL_FRAMEBUFFER_FETCH_NONCOHERENT_QCOM)); } } else if (checkExtension(CC_TOSTR(GL_EXT_shader_framebuffer_fetch))) { // we only care about EXT_shader_framebuffer_fetch, the ARM version does not support MRT _gpuConstantRegistry->mFBF = FBFSupportLevel::COHERENT; - fbfLevelStr = "COHERENT"; + fbfLevelStr = "COHERENT"; } _features[toNumber(Feature::INPUT_ATTACHMENT_BENEFIT)] = _gpuConstantRegistry->mFBF != FBFSupportLevel::NONE; _features[toNumber(Feature::SUBPASS_COLOR_INPUT)] = true; @@ -154,7 +154,7 @@ bool GLES3Device::doInit(const DeviceInfo & /*info*/) { if (checkExtension(CC_TOSTR(ARM_shader_framebuffer_fetch_depth_stencil))) { _features[toNumber(Feature::SUBPASS_DEPTH_STENCIL_INPUT)] = true; - fbfLevelStr += "_DEPTH_STENCIL"; + fbfLevelStr += "_DEPTH_STENCIL"; } ccstd::string msaaLevelStr = "NONE"; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Device.h b/native/cocos/renderer/gfx-gles3/GLES3Device.h index cba5ba99a0..30e62a2da6 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Device.h +++ b/native/cocos/renderer/gfx-gles3/GLES3Device.h @@ -97,6 +97,7 @@ public: inline bool isTextureExclusive(const Format &format) const { return _textureExclusive[static_cast(format)]; }; SampleCount getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const override; + protected: static GLES3Device *instance; diff --git a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h index 4dabb15f05..a8cfddfe73 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h +++ b/native/cocos/renderer/gfx-gles3/GLES3GPUObjects.h @@ -359,7 +359,7 @@ struct GLES3GPUFramebufferObject { void destroy(GLES3GPUStateCache *cache, GLES3GPUFramebufferCacheMap *framebufferCacheMap); GLuint getHandle() const { return swapchain != nullptr ? swapchain->glFramebuffer : handle; } - using Reference = std::pair; + using Reference = std::pair; GLES3GPUSwapchain *swapchain{nullptr}; @@ -369,6 +369,7 @@ struct GLES3GPUFramebufferObject { ccstd::vector loadInvalidates; ccstd::vector storeInvalidates; + private: GLuint handle{0}; }; diff --git a/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp b/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp index 2bab251e70..2626b7e6a5 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Texture.cpp @@ -100,7 +100,6 @@ void GLES3Texture::createTextureView() { _gpuTextureView->basePlane = _viewInfo.basePlane; _gpuTextureView->planeCount = _viewInfo.planeCount; cmdFuncGLES3CreateTextureView(GLES3Device::getInstance(), _gpuTextureView); - } void GLES3Texture::doDestroy() { diff --git a/native/cocos/renderer/gfx-gles3/GLES3Wrangler.cpp b/native/cocos/renderer/gfx-gles3/GLES3Wrangler.cpp index 379a6bc3ee..1fdd44235f 100644 --- a/native/cocos/renderer/gfx-gles3/GLES3Wrangler.cpp +++ b/native/cocos/renderer/gfx-gles3/GLES3Wrangler.cpp @@ -26,10 +26,10 @@ #if defined(_WIN32) && !defined(ANDROID) #define WIN32_LEAN_AND_MEAN 1 + #include #include #include "base/Log.h" #include "base/memory/Memory.h" - #include static HMODULE libegl = NULL; static HMODULE libgles = NULL; @@ -100,17 +100,16 @@ void *gles3wLoad(const char *proc) { } #else #include - #include "BasePlatform.h" #include "../gfx-gles-common/eglw.h" #include "../gfx-gles-common/gles2w.h" #include "../gfx-gles-common/gles3w.h" - + #include "BasePlatform.h" namespace { - void *libegl = nullptr; - void *libgles = nullptr; - PFNGLES3WLOADPROC pfnGles3wLoad = nullptr; -} +void *libegl = nullptr; +void *libgles = nullptr; +PFNGLES3WLOADPROC pfnGles3wLoad = nullptr; +} // namespace bool gles3wOpen() { libegl = dlopen("libEGL.so", RTLD_LAZY | RTLD_GLOBAL); @@ -136,17 +135,17 @@ bool gles3wClose() { void *gles3wLoad(const char *proc) { void *res = nullptr; if (eglGetProcAddress) res = reinterpret_cast(eglGetProcAddress(proc)); - -#if CC_PLATFORM != CC_PLATFORM_OPENHARMONY + + #if CC_PLATFORM != CC_PLATFORM_OPENHARMONY auto sdkVersion = cc::BasePlatform::getPlatform()->getSdkVersion(); if (sdkVersion <= 23) { if (!res) res = dlsym(libgles, proc); } else { if (!res) res = dlsym(libegl, proc); } -#else + #else if (!res) res = dlsym(libegl, proc); -#endif + #endif return res; } #endif diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.h b/native/cocos/renderer/gfx-metal/MTLDevice.h index 14064a3f30..f304b973ac 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.h +++ b/native/cocos/renderer/gfx-metal/MTLDevice.h @@ -88,8 +88,8 @@ public: _swapchains.erase(iter); } } - - inline CCMTLGPUDeviceObject* gpuObject() const { return _gpuDeviceObj; } + + inline CCMTLGPUDeviceObject *gpuObject() const { return _gpuDeviceObj; } protected: static CCMTLDevice *_instance; diff --git a/native/cocos/renderer/gfx-metal/MTLShader.h b/native/cocos/renderer/gfx-metal/MTLShader.h index 42c86271b3..efabf368b0 100644 --- a/native/cocos/renderer/gfx-metal/MTLShader.h +++ b/native/cocos/renderer/gfx-metal/MTLShader.h @@ -65,7 +65,7 @@ protected: void doInit(const ShaderInfo &info) override; void doDestroy() override; - bool checkInputAttachment(const ShaderInfo& info) const; + bool checkInputAttachment(const ShaderInfo &info) const; bool createMTLFunction(const ShaderStage &, CCMTLRenderPass *renderPass, uint32_t subPass); void setAvailableBufferBindingIndex(); diff --git a/native/cocos/renderer/gfx-metal/MTLUtils.h b/native/cocos/renderer/gfx-metal/MTLUtils.h index 18f597b3f3..e27e11dabd 100644 --- a/native/cocos/renderer/gfx-metal/MTLUtils.h +++ b/native/cocos/renderer/gfx-metal/MTLUtils.h @@ -71,7 +71,7 @@ MTLSamplerAddressMode toMTLSamplerAddressMode(Address); int toMTLSamplerBorderColor(const Color &); MTLSamplerMinMagFilter toMTLSamplerMinMagFilter(Filter); MTLSamplerMipFilter toMTLSamplerMipFilter(Filter); -ccstd::string spirv2MSL(const uint32_t *ir, size_t word_count, ShaderStageFlagBit shaderType, CCMTLGPUShader *gpuShader, RenderPass* renderpass, uint32_t subpassIndex); +ccstd::string spirv2MSL(const uint32_t *ir, size_t word_count, ShaderStageFlagBit shaderType, CCMTLGPUShader *gpuShader, RenderPass *renderpass, uint32_t subpassIndex); const uint8_t *convertRGB8ToRGBA8(const uint8_t *source, uint32_t length); const uint8_t *convertRGB32FToRGBA32F(const uint8_t *source, uint32_t length); NSUInteger highestSupportedFeatureSet(id device); diff --git a/native/cocos/renderer/gfx-validator/DeviceValidator.h b/native/cocos/renderer/gfx-validator/DeviceValidator.h index 4122d715e7..6070fd584a 100644 --- a/native/cocos/renderer/gfx-validator/DeviceValidator.h +++ b/native/cocos/renderer/gfx-validator/DeviceValidator.h @@ -96,6 +96,7 @@ public: void enableAutoBarrier(bool enable) override; SampleCount getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const override; + protected: static DeviceValidator *instance; diff --git a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp index 7eb7898a97..f30520f85c 100644 --- a/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-vulkan/VKCommandBuffer.cpp @@ -507,7 +507,7 @@ void CCVKCommandBuffer::draw(const DrawInfo &info) { if (hasIndexBuffer) { if (info.indexCount > 0) { vkCmdDrawIndexed(_gpuCommandBuffer->vkCommandBuffer, info.indexCount, instanceCount, - info.firstIndex, info.vertexOffset, info.firstInstance); + info.firstIndex, info.vertexOffset, info.firstInstance); } } else { vkCmdDraw(_gpuCommandBuffer->vkCommandBuffer, info.vertexCount, instanceCount, diff --git a/native/cocos/renderer/gfx-vulkan/VKDevice.h b/native/cocos/renderer/gfx-vulkan/VKDevice.h index 4d7d9c938a..7709ecc664 100644 --- a/native/cocos/renderer/gfx-vulkan/VKDevice.h +++ b/native/cocos/renderer/gfx-vulkan/VKDevice.h @@ -106,6 +106,7 @@ public: void updateBackBufferCount(uint32_t backBufferCount); SampleCount getMaxSampleCount(Format format, TextureUsage usage, TextureFlags flags) const override; + protected: static CCVKDevice *instance; diff --git a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h index 8c8f3c278b..a2fa53cb78 100644 --- a/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h +++ b/native/cocos/renderer/gfx-vulkan/VKGPUObjects.h @@ -103,7 +103,7 @@ public: CCVKGPUDeviceObject() = default; ~CCVKGPUDeviceObject() = default; - virtual void shutdown() {}; + virtual void shutdown(){}; }; template diff --git a/native/cocos/renderer/gfx-wgpu/WGPUBuffer.cpp b/native/cocos/renderer/gfx-wgpu/WGPUBuffer.cpp index 03cd9d69bd..f8f6978080 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUBuffer.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUBuffer.cpp @@ -24,10 +24,10 @@ #include "WGPUBuffer.h" #include +#include #include "WGPUDevice.h" #include "WGPUObject.h" #include "WGPUUtils.h" -#include namespace cc { namespace gfx { diff --git a/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.cpp b/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.cpp index 2100682ad8..1c94638d24 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUCommandBuffer.cpp @@ -157,9 +157,9 @@ void CCWGPUCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *f } ccstd::vector depthStencils; - if(renderPass->getDepthStencilAttachment().format == Format::UNKNOWN) { + if (renderPass->getDepthStencilAttachment().format == Format::UNKNOWN) { renderPassDesc.depthStencilAttachment = nullptr; - } else if(dsTexture) { + } else if (dsTexture) { WGPURenderPassDepthStencilAttachment depthStencil = { .view = static_cast(dsTexture)->gpuTextureObject()->selfView, .depthLoadOp = toWGPULoadOp(depthStencilConfig.depthLoadOp), @@ -174,17 +174,17 @@ void CCWGPUCommandBuffer::beginRenderPass(RenderPass *renderPass, Framebuffer *f depthStencils.emplace_back(depthStencil); } else { WGPURenderPassDepthStencilAttachment depthStencil = { - .view = swapchain->gpuSwapchainObject()->swapchainDepthStencil->gpuTextureObject()->selfView, - .depthLoadOp = toWGPULoadOp(depthStencilConfig.depthLoadOp), - .depthStoreOp = toWGPUStoreOp(depthStencilConfig.depthStoreOp), - .depthClearValue = depth, - .depthReadOnly = false, - .stencilLoadOp = toWGPULoadOp(depthStencilConfig.stencilLoadOp), - .stencilStoreOp = toWGPUStoreOp(depthStencilConfig.stencilStoreOp), - .stencilClearValue = stencil, - .stencilReadOnly = false, - }; - depthStencils.emplace_back(depthStencil); + .view = swapchain->gpuSwapchainObject()->swapchainDepthStencil->gpuTextureObject()->selfView, + .depthLoadOp = toWGPULoadOp(depthStencilConfig.depthLoadOp), + .depthStoreOp = toWGPUStoreOp(depthStencilConfig.depthStoreOp), + .depthClearValue = depth, + .depthReadOnly = false, + .stencilLoadOp = toWGPULoadOp(depthStencilConfig.stencilLoadOp), + .stencilStoreOp = toWGPUStoreOp(depthStencilConfig.stencilStoreOp), + .stencilClearValue = stencil, + .stencilReadOnly = false, + }; + depthStencils.emplace_back(depthStencil); } setViewport({renderArea.x, renderArea.y, renderArea.width, renderArea.height, 0.0F, 1.0F}); diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp index 0213a2e66e..508a6a6136 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUDescriptorSetLayout.cpp @@ -138,15 +138,15 @@ void CCWGPUDescriptorSetLayout::updateSampledTextureLayout(uint8_t index, const CC_ASSERT(texture); - WGPUTextureBindingLayout textureLayout{}; - textureLayout.sampleType = sampletypeTraits(texture, plane); // textureSampleTypeTrait(texture->getFormat()); - const CCWGPUTexture *ccTex = static_cast(texture->isTextureView() ? texture->getViewInfo().texture : texture); - TextureType type = ccTex->getViewInfo().type; - textureLayout.viewDimension = toWGPUTextureViewDimension(type); - textureLayout.multisampled = ccTex->getInfo().samples != SampleCount::X1; - textureEntry.texture = textureLayout; + WGPUTextureBindingLayout textureLayout{}; + textureLayout.sampleType = sampletypeTraits(texture, plane); // textureSampleTypeTrait(texture->getFormat()); + const CCWGPUTexture *ccTex = static_cast(texture->isTextureView() ? texture->getViewInfo().texture : texture); + TextureType type = ccTex->getViewInfo().type; + textureLayout.viewDimension = toWGPUTextureViewDimension(type); + textureLayout.multisampled = ccTex->getInfo().samples != SampleCount::X1; + textureEntry.texture = textureLayout; _gpuLayoutEntryObj->bindGroupLayoutEntries[textureEntry.binding] = textureEntry; - } +} void CCWGPUDescriptorSetLayout::updateStorageTextureLayout(uint8_t index, const CCWGPUTexture *texture, uint32_t plane) { WGPUBindGroupLayoutEntry textureEntry{}; textureEntry.binding = _bindings[index].binding; @@ -214,7 +214,7 @@ void CCWGPUDescriptorSetLayout::prepare(ccstd::set &bindingInUse, bool ccstd::vector bindGroupLayoutEntries{}; bindGroupLayoutEntries.reserve(_gpuLayoutEntryObj->bindGroupLayoutEntries.size()); for (const auto &[bd, layoutEntry] : _gpuLayoutEntryObj->bindGroupLayoutEntries) { - if(checkInUse(static_cast(bd), bindingInUse, layoutEntry.sampler.type != WGPUSamplerBindingType_Undefined)) { + if (checkInUse(static_cast(bd), bindingInUse, layoutEntry.sampler.type != WGPUSamplerBindingType_Undefined)) { bindGroupLayoutEntries.emplace_back(layoutEntry); } } @@ -232,7 +232,7 @@ void CCWGPUDescriptorSetLayout::prepare(ccstd::set &bindingInUse, bool } else { WGPUBindGroupLayoutDescriptor descriptor = { .nextInChain = nullptr, - .label = "",//std::to_string(_hash).c_str(), + .label = "", //std::to_string(_hash).c_str(), .entryCount = entries.size(), .entries = entries.data(), }; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUDevice.h b/native/cocos/renderer/gfx-wgpu/WGPUDevice.h index e0691df45f..eeab70ad6e 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUDevice.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUDevice.h @@ -91,7 +91,7 @@ public: using Device::getSampler; using Device::initialize; - void frameSync() override {}; + void frameSync() override{}; Shader *createShader(const ShaderInfo &, const std::vector> &); diff --git a/native/cocos/renderer/gfx-wgpu/WGPUEMSImpl.cpp b/native/cocos/renderer/gfx-wgpu/WGPUEMSImpl.cpp index 354ac4f382..c5c3625c9d 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUEMSImpl.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUEMSImpl.cpp @@ -167,7 +167,7 @@ void CCWGPUDevice::copyBuffersToTexture(const emscripten::val& v, Texture* dst, return copyBuffersToTexture(buffers.data(), dst, regions.data(), regions.size()); } -void CCWGPUShader::reflectBinding(const emscripten::val &vals) { +void CCWGPUShader::reflectBinding(const emscripten::val& vals) { const std::vector& bindings = convertJSArrayToNumberVector(vals); _gpuShaderObject->bindings.emplace_back(bindings); } diff --git a/native/cocos/renderer/gfx-wgpu/WGPUQueue.cpp b/native/cocos/renderer/gfx-wgpu/WGPUQueue.cpp index c42bba1cde..5dce5bb73f 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUQueue.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUQueue.cpp @@ -92,7 +92,7 @@ void CCWGPUQueue::submit(CommandBuffer *const *cmdBuffs, uint32_t count) { _numInstances += cmdBuff->getNumInstances(); _numTriangles += cmdBuff->getNumTris(); - const_cast(cmdBuff)->reset(); + const_cast(cmdBuff)->reset(); } wgpuQueueSubmit(_gpuQueueObject->wgpuQueue, count, wgpuCmdBuffs.data()); diff --git a/native/cocos/renderer/gfx-wgpu/WGPUShader.cpp b/native/cocos/renderer/gfx-wgpu/WGPUShader.cpp index 9173e6d5c6..8b742c79bd 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUShader.cpp +++ b/native/cocos/renderer/gfx-wgpu/WGPUShader.cpp @@ -88,8 +88,8 @@ void CCWGPUShader::initialize(const ShaderInfo &info, const std::vector> &spirvs); - void initWithWGSL(const ShaderInfo& info); + void initWithWGSL(const ShaderInfo &info); protected: void doInit(const ShaderInfo &info) override; diff --git a/native/cocos/renderer/gfx-wgpu/WGPUTexture.h b/native/cocos/renderer/gfx-wgpu/WGPUTexture.h index 258c3dd44e..4faa9e13a0 100644 --- a/native/cocos/renderer/gfx-wgpu/WGPUTexture.h +++ b/native/cocos/renderer/gfx-wgpu/WGPUTexture.h @@ -63,7 +63,7 @@ public: inline auto getTextureSamples() const { return _info.samples; }; inline auto getTextureFlags() const { return _info.flags; }; - void* getPlaneView(uint32_t plane); + void *getPlaneView(uint32_t plane); protected: void doInit(const TextureInfo &info) override; diff --git a/native/cocos/renderer/pipeline/ClusterLightCulling.cpp b/native/cocos/renderer/pipeline/ClusterLightCulling.cpp index 4eff57a7aa..dd327f191d 100644 --- a/native/cocos/renderer/pipeline/ClusterLightCulling.cpp +++ b/native/cocos/renderer/pipeline/ClusterLightCulling.cpp @@ -32,10 +32,10 @@ #include "renderer/gfx-base/GFXDevice.h" #include "renderer/pipeline/RenderPipeline.h" #include "scene/Camera.h" -#include "scene/SphereLight.h" -#include "scene/SpotLight.h" #include "scene/PointLight.h" #include "scene/RangedDirectionalLight.h" +#include "scene/SphereLight.h" +#include "scene/SpotLight.h" namespace cc { namespace pipeline { diff --git a/native/cocos/renderer/pipeline/DebugView.cpp b/native/cocos/renderer/pipeline/DebugView.cpp index 33948e3753..663c1f35b4 100644 --- a/native/cocos/renderer/pipeline/DebugView.cpp +++ b/native/cocos/renderer/pipeline/DebugView.cpp @@ -23,9 +23,9 @@ ****************************************************************************/ #include "DebugView.h" -#include "custom/RenderInterfaceTypes.h" #include "RenderPipeline.h" #include "core/Root.h" +#include "custom/RenderInterfaceTypes.h" namespace cc { diff --git a/native/cocos/renderer/pipeline/DebugView.h b/native/cocos/renderer/pipeline/DebugView.h index 6fb4ba027a..240db0ca14 100644 --- a/native/cocos/renderer/pipeline/DebugView.h +++ b/native/cocos/renderer/pipeline/DebugView.h @@ -171,7 +171,7 @@ public: * @zh 获取指定的渲染组合调试模式是否开启。 * @param Specified composite type. */ - inline bool isCompositeModeEnabled (uint32_t val) const { + inline bool isCompositeModeEnabled(uint32_t val) const { uint32_t mode = _compositeModeValue & (1 << val); return mode != 0; } @@ -180,7 +180,7 @@ public: * @zh 开关指定的渲染组合调试模式。 * @param Specified composite type, enable or disable. */ - inline void enableCompositeMode (DebugViewCompositeType val, bool enable) { + inline void enableCompositeMode(DebugViewCompositeType val, bool enable) { enableCompositeModeValue(val, enable); updatePipeline(); } @@ -189,7 +189,7 @@ public: * @en Toggle all rendering composite debug mode. * @zh 开关所有的渲染组合调试模式。 */ - inline void enableAllCompositeMode (bool enable) { + inline void enableAllCompositeMode(bool enable) { enableAllCompositeModeValue(enable); updatePipeline(); } @@ -206,7 +206,7 @@ public: * @en Disable all debug view modes, reset to standard rendering mode. * @zh 关闭所有的渲染调试模式,恢复到正常渲染。 */ - void reset () { + void reset() { activate(); updatePipeline(); } @@ -234,7 +234,7 @@ private: } } - inline RenderingDebugViewType getType () const { + inline RenderingDebugViewType getType() const { if (_singleMode != DebugViewSingleType::NONE) { return RenderingDebugViewType::SINGLE; } else if (!_lightingWithAlbedo || _csmLayerColoration) { diff --git a/native/cocos/renderer/pipeline/Define.cpp b/native/cocos/renderer/pipeline/Define.cpp index ea09f2bf3b..4ecf023162 100644 --- a/native/cocos/renderer/pipeline/Define.cpp +++ b/native/cocos/renderer/pipeline/Define.cpp @@ -48,12 +48,12 @@ uint32_t localSet = static_cast(SetIndex::LOCAL); gfx::BindingMappingInfo bindingMappingInfo = { {GLOBAL_UBO_COUNT, 0, LOCAL_UBO_COUNT, 0}, // Uniform Buffer Counts {GLOBAL_SAMPLER_COUNT, 0, LOCAL_SAMPLER_COUNT, 0}, // Combined Sampler Texture Counts - {0, 0, 0, 0}, // Sampler Counts - {0, 0, 0, 0}, // Texture Counts - {0, 0, 0, 0}, // Storage Buffer Counts - {0, 0, LOCAL_STORAGE_IMAGE_COUNT, 0}, // Storage Image Counts - {0, 0, 0, 0}, // Subpass Input Counts - {0, 2, 1, 3}, // Set Order Indices + {0, 0, 0, 0}, // Sampler Counts + {0, 0, 0, 0}, // Texture Counts + {0, 0, 0, 0}, // Storage Buffer Counts + {0, 0, LOCAL_STORAGE_IMAGE_COUNT, 0}, // Storage Image Counts + {0, 0, 0, 0}, // Subpass Input Counts + {0, 2, 1, 3}, // Set Order Indices }; DescriptorSetLayoutInfos globalDescriptorSetLayout; diff --git a/native/cocos/renderer/pipeline/GeometryRenderer.cpp b/native/cocos/renderer/pipeline/GeometryRenderer.cpp index 8f7811cb4c..65373a074c 100644 --- a/native/cocos/renderer/pipeline/GeometryRenderer.cpp +++ b/native/cocos/renderer/pipeline/GeometryRenderer.cpp @@ -823,9 +823,9 @@ void GeometryRenderer::addBezier(const Vec3 &v0, const Vec3 &v1, const Vec3 &v2, void GeometryRenderer::addSpline(const geometry::Spline &spline, gfx::Color color, uint32_t index, float knotSize, uint32_t segments, bool depthTest, bool useTransform, const Mat4 &transform) { const auto numPoints = segments + 1; auto points = spline.getPoints(numPoints, index); - + if (useTransform) { - for (auto& point : points) { + for (auto &point : points) { point.transformMat4(transform); } } diff --git a/native/cocos/renderer/pipeline/InstancedBuffer.cpp b/native/cocos/renderer/pipeline/InstancedBuffer.cpp index a85291375a..92082ae149 100644 --- a/native/cocos/renderer/pipeline/InstancedBuffer.cpp +++ b/native/cocos/renderer/pipeline/InstancedBuffer.cpp @@ -67,8 +67,8 @@ void InstancedBuffer::merge(scene::SubModel *subModel, uint32_t passIdx, gfx::Sh auto *reflectionProbeCubemap = descriptorSet->getTexture(REFLECTIONPROBECUBEMAP::BINDING); auto *reflectionProbePlanarMap = descriptorSet->getTexture(REFLECTIONPROBEPLANARMAP::BINDING); gfx::Texture *reflectionProbeBlendCubemap = ENABLE_PROBE_BLEND - ? descriptorSet->getTexture(REFLECTIONPROBEBLENDCUBEMAP::BINDING) - : nullptr; + ? descriptorSet->getTexture(REFLECTIONPROBEBLENDCUBEMAP::BINDING) + : nullptr; const uint32_t reflectionProbeType = subModel->getReflectionProbeType(); auto *shader = shaderImplant; if (!shader) { diff --git a/native/cocos/renderer/pipeline/PipelineSceneData.cpp b/native/cocos/renderer/pipeline/PipelineSceneData.cpp index 3a0db2f82e..de63d3137f 100644 --- a/native/cocos/renderer/pipeline/PipelineSceneData.cpp +++ b/native/cocos/renderer/pipeline/PipelineSceneData.cpp @@ -35,11 +35,10 @@ #include "scene/Model.h" #include "scene/Octree.h" #include "scene/Pass.h" +#include "scene/PostSettings.h" #include "scene/Shadow.h" #include "scene/Skin.h" #include "scene/Skybox.h" -#include "scene/Model.h" -#include "scene/PostSettings.h" namespace cc { namespace pipeline { diff --git a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp index 8790911dca..746eba78e6 100644 --- a/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp +++ b/native/cocos/renderer/pipeline/RenderAdditiveLightQueue.cpp @@ -68,7 +68,9 @@ RenderAdditiveLightQueue::RenderAdditiveLightQueue(RenderPipeline *pipeline) : _ void RenderAdditiveLightQueue::recordCommandBuffer(gfx::Device *device, scene::Camera *camera, gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuffer) { const uint32_t offset = _pipeline->getPipelineUBO()->getCurrentCameraUBOOffset(); for (uint32_t i = 0; i < _instancedQueues.size(); ++i) { - if (!this->_instancedQueues[i]) { continue; } + if (!this->_instancedQueues[i]) { + continue; + } const auto *light = _instancedLightPass.lights[i]; _dynamicOffsets[0] = _instancedLightPass.dynamicOffsets[i]; auto *globalDescriptorSet = _pipeline->getGlobalDSManager()->getOrCreateDescriptorSet(light); @@ -503,7 +505,7 @@ bool RenderAdditiveLightQueue::getLightPassIndex(const scene::Model *model, ccst } ++k; } - lightPassIndices->push_back(static_cast(lightPassIndex)); + lightPassIndices->push_back(static_cast(lightPassIndex)); } return hasValidLightPass; diff --git a/native/cocos/renderer/pipeline/custom/LayoutGraphSerialization.cpp b/native/cocos/renderer/pipeline/custom/LayoutGraphSerialization.cpp index 8b168992a5..b7a52d9fa2 100644 --- a/native/cocos/renderer/pipeline/custom/LayoutGraphSerialization.cpp +++ b/native/cocos/renderer/pipeline/custom/LayoutGraphSerialization.cpp @@ -28,9 +28,9 @@ * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= */ // NOLINTBEGIN(misc-include-cleaner) +#include "cocos/renderer/pipeline/custom/LayoutGraphSerialization.h" #include "cocos/renderer/pipeline/custom/ArchiveTypes.h" #include "cocos/renderer/pipeline/custom/LayoutGraphGraphs.h" -#include "cocos/renderer/pipeline/custom/LayoutGraphSerialization.h" #include "cocos/renderer/pipeline/custom/LayoutGraphTypes.h" #include "cocos/renderer/pipeline/custom/RenderCommonSerialization.h" #include "cocos/renderer/pipeline/custom/details/Range.h" diff --git a/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.h b/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.h index acb5780ebe..15ff24fb2c 100644 --- a/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.h +++ b/native/cocos/renderer/pipeline/custom/LayoutGraphUtils.h @@ -68,7 +68,6 @@ void printLayoutGraphData( gfx::TextureType getTextureType(ResourceDimension dimension, uint32_t arraySize); ResourceDimension getResourceDimension(gfx::TextureType type); - } // namespace render } // namespace cc diff --git a/native/cocos/renderer/pipeline/custom/NativeExecutorRenderGraph.h b/native/cocos/renderer/pipeline/custom/NativeExecutorRenderGraph.h index 6f7d27e240..65bcaa37ca 100644 --- a/native/cocos/renderer/pipeline/custom/NativeExecutorRenderGraph.h +++ b/native/cocos/renderer/pipeline/custom/NativeExecutorRenderGraph.h @@ -23,11 +23,11 @@ ****************************************************************************/ #pragma once +#include #include "FGDispatcherTypes.h" #include "LayoutGraphTypes.h" #include "NativePipelineTypes.h" #include "RenderGraphTypes.h" -#include namespace cc { diff --git a/native/cocos/renderer/pipeline/custom/NativePipeline.cpp b/native/cocos/renderer/pipeline/custom/NativePipeline.cpp index e4f1ee7d4b..029f9a8f29 100644 --- a/native/cocos/renderer/pipeline/custom/NativePipeline.cpp +++ b/native/cocos/renderer/pipeline/custom/NativePipeline.cpp @@ -22,6 +22,7 @@ THE SOFTWARE. ****************************************************************************/ +#include "bindings/jswrapper/SeApi.h" // IWYU pragma: keep #include "cocos/renderer/pipeline/Define.h" #include "cocos/renderer/pipeline/PipelineSceneData.h" #include "cocos/renderer/pipeline/PipelineStateManager.h" @@ -30,19 +31,18 @@ #include "cocos/renderer/pipeline/custom/NativeBuiltinUtils.h" #include "cocos/renderer/pipeline/custom/NativePipelineTypes.h" #include "cocos/renderer/pipeline/custom/NativeRenderGraphUtils.h" +#include "cocos/renderer/pipeline/custom/NativeUtils.h" #include "cocos/renderer/pipeline/custom/RenderGraphGraphs.h" #include "cocos/renderer/pipeline/custom/RenderInterfaceTypes.h" #include "cocos/renderer/pipeline/custom/RenderingModule.h" #include "cocos/renderer/pipeline/custom/details/GslUtils.h" #include "cocos/renderer/pipeline/custom/details/Range.h" +#include "cocos/scene/DirectionalLight.h" #include "cocos/scene/ReflectionProbe.h" #include "cocos/scene/ReflectionProbeManager.h" #include "cocos/scene/RenderScene.h" #include "cocos/scene/RenderWindow.h" #include "cocos/scene/SpotLight.h" -#include "cocos/scene/DirectionalLight.h" -#include "bindings/jswrapper/SeApi.h" // IWYU pragma: keep -#include "cocos/renderer/pipeline/custom/NativeUtils.h" #if CC_USE_DEBUG_RENDERER #include "profiler/DebugRenderer.h" @@ -1319,7 +1319,7 @@ void buildRenderPipeline() { if (buildRPVal.isUndefined()) { auto *global = se::ScriptEngine::getInstance()->getGlobalObject(); se::Value jsbVal; - if(global->getProperty("jsb", &jsbVal) && jsbVal.isObject()) { + if (global->getProperty("jsb", &jsbVal) && jsbVal.isObject()) { jsbVal.toObject()->getProperty("buildRenderPipeline", &buildRPVal); } se::ScriptEngine::getInstance()->addBeforeCleanupHook([]() { @@ -1693,7 +1693,7 @@ void NativePipeline::setSampler(const ccstd::string &name, gfx::Sampler *sampler } void NativePipeline::setBuiltinCameraConstants(const scene::Camera *camera) { - const auto* scene = camera->getScene(); + const auto *scene = camera->getScene(); setCameraUBOValues( *camera, programLibrary->layoutGraph, diff --git a/native/cocos/renderer/pipeline/custom/NativeRenderQueue.cpp b/native/cocos/renderer/pipeline/custom/NativeRenderQueue.cpp index d6c8d3494e..c5a6d8c775 100644 --- a/native/cocos/renderer/pipeline/custom/NativeRenderQueue.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeRenderQueue.cpp @@ -196,18 +196,18 @@ void RenderInstancingQueue::add( } void RenderInstancingQueue::sort() { - const auto instancingCompare = [](const pipeline::InstancedBuffer* a, - const pipeline::InstancedBuffer* b) { - const auto& aSort = a->getSortRender(); - const auto& bSort = b->getSortRender(); + const auto instancingCompare = [](const pipeline::InstancedBuffer *a, + const pipeline::InstancedBuffer *b) { + const auto &aSort = a->getSortRender(); + const auto &bSort = b->getSortRender(); if (aSort.hash != bSort.hash) { return aSort.hash < bSort.hash; } return aSort.shaderID < bSort.shaderID; }; - + sortedBatches.reserve(instanceBuffers.size()); - for (const auto& buffer : instanceBuffers) { + for (const auto &buffer : instanceBuffers) { sortedBatches.emplace_back(buffer.get()); } std::sort(sortedBatches.begin(), sortedBatches.end(), instancingCompare); diff --git a/native/cocos/renderer/pipeline/custom/NativeSceneCulling.cpp b/native/cocos/renderer/pipeline/custom/NativeSceneCulling.cpp index 63355bb9aa..eb88080fbb 100644 --- a/native/cocos/renderer/pipeline/custom/NativeSceneCulling.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeSceneCulling.cpp @@ -671,7 +671,8 @@ void SceneCulling::fillRenderQueues() { } // not culled by light bounds return frustumCullingResults.at(frustomCulledResultID.value); - }(); + } + (); // skybox const auto* camera = nativeQueue.camera; diff --git a/native/cocos/renderer/pipeline/custom/NativeSetter.cpp b/native/cocos/renderer/pipeline/custom/NativeSetter.cpp index e52f93d278..ab2787c267 100644 --- a/native/cocos/renderer/pipeline/custom/NativeSetter.cpp +++ b/native/cocos/renderer/pipeline/custom/NativeSetter.cpp @@ -106,7 +106,7 @@ void NativeSetter::setMat4ArrayElem(const ccstd::string &name, const cc::Mat4 &m void NativeSetter::setBuiltinCameraConstants(const scene::Camera *camera) { auto &data = get(RenderGraph::DataTag{}, *renderGraph, nodeID); - const auto* scene = camera->getScene(); + const auto *scene = camera->getScene(); setCameraUBOValues( *camera, *layoutGraph, diff --git a/native/cocos/renderer/pipeline/custom/RenderCommonSerialization.cpp b/native/cocos/renderer/pipeline/custom/RenderCommonSerialization.cpp index fe44118768..9f03779392 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCommonSerialization.cpp +++ b/native/cocos/renderer/pipeline/custom/RenderCommonSerialization.cpp @@ -28,8 +28,8 @@ * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= */ // NOLINTBEGIN(misc-include-cleaner) -#include "cocos/renderer/pipeline/custom/ArchiveTypes.h" #include "cocos/renderer/pipeline/custom/RenderCommonSerialization.h" +#include "cocos/renderer/pipeline/custom/ArchiveTypes.h" #include "cocos/renderer/pipeline/custom/RenderCommonTypes.h" #include "cocos/renderer/pipeline/custom/details/SerializationUtils.h" diff --git a/native/cocos/renderer/pipeline/custom/details/GraphTypes.h b/native/cocos/renderer/pipeline/custom/details/GraphTypes.h index be4d087b5b..cf75232932 100644 --- a/native/cocos/renderer/pipeline/custom/details/GraphTypes.h +++ b/native/cocos/renderer/pipeline/custom/details/GraphTypes.h @@ -31,8 +31,8 @@ #include // IWYU pragma: export #include "cocos/base/memory/Memory.h" #include "cocos/base/std/container/list.h" -#include "cocos/base/std/container/string.h" // IWYU pragma: export -#include "cocos/base/std/variant.h" // IWYU pragma: export +#include "cocos/base/std/container/string.h" // IWYU pragma: export +#include "cocos/base/std/variant.h" // IWYU pragma: export #include "cocos/renderer/pipeline/custom/details/Overload.h" // IWYU pragma: export namespace boost { diff --git a/native/cocos/renderer/pipeline/custom/test/test.h b/native/cocos/renderer/pipeline/custom/test/test.h index 30badff0cb..b03edf5fea 100644 --- a/native/cocos/renderer/pipeline/custom/test/test.h +++ b/native/cocos/renderer/pipeline/custom/test/test.h @@ -103,7 +103,7 @@ static void fillTestGraph(const ViewInfo &rasterData, const ResourceInfo &rescIn auto addRasterNode = [&](const vector>> &subpasses, uint32_t count, uint32_t passID) { const ccstd::string name = "pass" + std::to_string(passID); const auto vertexID = add_vertex(renderGraph, RasterPassTag{}, name.c_str()); - auto& layoutName = get(RenderGraph::LayoutTag{}, renderGraph, vertexID); + auto &layoutName = get(RenderGraph::LayoutTag{}, renderGraph, vertexID); layoutName = "default"; renderGraph.sortedVertices.emplace_back(vertexID); @@ -265,131 +265,131 @@ static void fillTestGraph(const ViewInfo &rasterData, const ResourceInfo &rescIn fgDispatcher.run(); */ } -#define TEST_CASE_DEFINE \ - using namespace cc::render; \ - using cc::gfx::AccessFlagBit; \ - using cc::gfx::BarrierType; \ - using cc::gfx::Format; \ - using cc::gfx::MemoryAccessBit; \ - using cc::gfx::SampleCount; \ - using cc::gfx::ShaderStageFlagBit; \ - using cc::gfx::TextureFlagBit; \ - ResourceInfo resources = { \ - {"0", \ +#define TEST_CASE_DEFINE \ + using namespace cc::render; \ + using cc::gfx::AccessFlagBit; \ + using cc::gfx::BarrierType; \ + using cc::gfx::Format; \ + using cc::gfx::MemoryAccessBit; \ + using cc::gfx::SampleCount; \ + using cc::gfx::ShaderStageFlagBit; \ + using cc::gfx::TextureFlagBit; \ + ResourceInfo resources = { \ + {"0", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::MANAGED}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ - {"1", \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"1", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::MANAGED}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ - {"2", \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"2", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::MANAGED}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ - {"3", \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"3", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::MANAGED}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ - {"4", \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"4", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::MANAGED}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ - {"5", \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"5", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::MANAGED}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ - {"6", \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"6", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::MANAGED}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ - {"7", \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"7", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::MANAGED}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ - {"8", \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"8", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::MANAGED}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ - {"9", \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"9", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::MANAGED}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ - {"10", \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"10", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::MANAGED}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ - {"11", \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"11", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::MANAGED}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ - {"12", \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"12", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::MANAGED}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ - {"13", \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"13", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::MANAGED}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ - {"14", \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"14", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::MANAGED}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ - {"15", \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"15", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::MANAGED}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ - {"16", \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"16", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::MANAGED}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ - {"17", \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"17", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::MANAGED}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ - {"18", \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"18", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::MANAGED}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ - {"19", \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::MANAGED}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"19", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::EXTERNAL}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ - {"20", \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::EXTERNAL}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"20", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::EXTERNAL}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ - {"21", \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::EXTERNAL}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"21", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::EXTERNAL}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ - {"22", \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::EXTERNAL}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + {"22", \ {ResourceDimension::TEXTURE2D, 4, 960, 640, 1, 0, Format::RGBA8, SampleCount::X1, TextureFlagBit::NONE, \ - ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ - {ResourceResidency::BACKBUFFER}, \ - {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ + ResourceFlags::SAMPLED | ResourceFlags::COLOR_ATTACHMENT | ResourceFlags::INPUT_ATTACHMENT}, \ + {ResourceResidency::BACKBUFFER}, \ + {AccessFlagBit::FRAGMENT_SHADER_READ_TEXTURE | AccessFlagBit::COLOR_ATTACHMENT_WRITE}}, \ }; #define TEST_CASE_1 \ diff --git a/native/cocos/renderer/pipeline/xr/ar/ARBackground.cpp b/native/cocos/renderer/pipeline/xr/ar/ARBackground.cpp index 137ca30431..9dbc9a9b3d 100644 --- a/native/cocos/renderer/pipeline/xr/ar/ARBackground.cpp +++ b/native/cocos/renderer/pipeline/xr/ar/ARBackground.cpp @@ -283,12 +283,12 @@ void ARBackground::render(cc::scene::Camera *camera, gfx::RenderPass *renderPass #if CC_PLATFORM == CC_PLATFORM_ANDROID if (armodule->getTexInitFlag()) { gfx::SamplerInfo samplerInfo = { - gfx::Filter::LINEAR, - gfx::Filter::LINEAR, - gfx::Filter::NONE, - gfx::Address::CLAMP, - gfx::Address::CLAMP, - gfx::Address::CLAMP, + gfx::Filter::LINEAR, + gfx::Filter::LINEAR, + gfx::Filter::NONE, + gfx::Address::CLAMP, + gfx::Address::CLAMP, + gfx::Address::CLAMP, }; auto *sampler = _device->getSampler(samplerInfo); diff --git a/native/cocos/scene/Camera.cpp b/native/cocos/scene/Camera.cpp index f925d77ef0..a294b4a2af 100644 --- a/native/cocos/scene/Camera.cpp +++ b/native/cocos/scene/Camera.cpp @@ -67,8 +67,7 @@ const ccstd::vector Camera::SHUTTERS{1.0F, 1.0F / 2.0F, 1.0F / 4.0F, 1.0F const ccstd::vector Camera::ISOS{100.0F, 200.0F, 400.0F, 800.0F}; Camera::Camera(gfx::Device *device) -: _device(device) -, _cameraId(sCameraId++) { +: _device(device), _cameraId(sCameraId++) { _apertureValue = Camera::FSTOPS.at(static_cast(_aperture)); _shutterValue = Camera::SHUTTERS.at(static_cast(_shutter)); _isoValue = Camera::ISOS[static_cast(_iso)]; diff --git a/native/cocos/scene/Model.h b/native/cocos/scene/Model.h index ec33453305..238464900b 100644 --- a/native/cocos/scene/Model.h +++ b/native/cocos/scene/Model.h @@ -262,13 +262,13 @@ protected: Type _type{Type::DEFAULT}; Layers::Enum _visFlags{Layers::Enum::NONE}; - UseReflectionProbeType _reflectionProbeType{ UseReflectionProbeType::NONE }; + UseReflectionProbeType _reflectionProbeType{UseReflectionProbeType::NONE}; int32_t _tetrahedronIndex{-1}; uint32_t _descriptorSetCount{1}; uint32_t _priority{0}; uint32_t _updateStamp{0}; int32_t _reflectionProbeId{-1}; - int32_t _reflectionProbeBlendId{ -1 }; + int32_t _reflectionProbeBlendId{-1}; float _reflectionProbeBlendWeight{0.F}; OctreeNode *_octreeNode{nullptr}; diff --git a/native/cocos/scene/Pass.cpp b/native/cocos/scene/Pass.cpp index 6e4d60c3a0..83bdb0b424 100644 --- a/native/cocos/scene/Pass.cpp +++ b/native/cocos/scene/Pass.cpp @@ -129,8 +129,8 @@ void Pass::fillPipelineInfo(Pass *pass, const IPassInfoFull &info) { if (pass->_blendState.isA2C) { const bool passWantsMultisample = (info.rasterizerState.has_value() && info.rasterizerState.value().isMultisample.has_value() - ? info.rasterizerState.value().isMultisample.value() != 0 - : pass->_rs.isMultisample != 0); + ? info.rasterizerState.value().isMultisample.value() != 0 + : pass->_rs.isMultisample != 0); bool msaaDisabled = true; const auto *device = gfx::Device::getInstance(); diff --git a/native/cocos/scene/PointLight.cpp b/native/cocos/scene/PointLight.cpp index 099117189c..c141df5ccd 100644 --- a/native/cocos/scene/PointLight.cpp +++ b/native/cocos/scene/PointLight.cpp @@ -25,8 +25,8 @@ #include "scene/PointLight.h" #include "core/Root.h" #include "core/scene-graph/Node.h" -#include "renderer/pipeline/custom/RenderInterfaceTypes.h" #include "renderer/pipeline/PipelineSceneData.h" +#include "renderer/pipeline/custom/RenderInterfaceTypes.h" namespace cc { namespace scene { diff --git a/native/cocos/scene/PostSettings.cpp b/native/cocos/scene/PostSettings.cpp index b83bb044a5..f9ef0a2d86 100644 --- a/native/cocos/scene/PostSettings.cpp +++ b/native/cocos/scene/PostSettings.cpp @@ -59,14 +59,12 @@ void PostSettings::setToneMappingType(ToneMappingType toneMappingType) { } void PostSettings::updatePipeline() const { - Root *root = Root::getInstance(); auto *pipeline = root->getPipeline(); pipeline->setValue("CC_TONE_MAPPING_TYPE", static_cast(_toneMappingType)); - if (_activated) - { + if (_activated) { root->onGlobalPipelineStateChanged(); } } diff --git a/native/cocos/scene/PostSettings.h b/native/cocos/scene/PostSettings.h index f81d4106a2..9a3b05bd41 100644 --- a/native/cocos/scene/PostSettings.h +++ b/native/cocos/scene/PostSettings.h @@ -27,41 +27,41 @@ #include "base/RefCounted.h" namespace cc { - namespace scene { - enum class ToneMappingType { - DEFAULT = 0, - LINEAR = 1, - }; +namespace scene { +enum class ToneMappingType { + DEFAULT = 0, + LINEAR = 1, +}; - class PostSettings; - class PostSettingsInfo : public RefCounted { - public: - PostSettingsInfo() = default; - ~PostSettingsInfo() override = default; +class PostSettings; +class PostSettingsInfo : public RefCounted { +public: + PostSettingsInfo() = default; + ~PostSettingsInfo() override = default; - inline ToneMappingType getToneMappingType() const { return _toneMappingType; } - void setToneMappingType(ToneMappingType toneMappingType); + inline ToneMappingType getToneMappingType() const { return _toneMappingType; } + void setToneMappingType(ToneMappingType toneMappingType); - void activate(PostSettings *resource); - PostSettings *_resource{nullptr}; - ToneMappingType _toneMappingType{ ToneMappingType::DEFAULT }; - }; + void activate(PostSettings *resource); + PostSettings *_resource{nullptr}; + ToneMappingType _toneMappingType{ToneMappingType::DEFAULT}; +}; - class PostSettings final { - public: - PostSettings() = default; - ~PostSettings() = default; - void activate(); +class PostSettings final { +public: + PostSettings() = default; + ~PostSettings() = default; + void activate(); - void initialize(const PostSettingsInfo &postSettingsInfo); - inline ToneMappingType getToneMappingType() const { return _toneMappingType; } - void setToneMappingType(ToneMappingType toneMappingType); - private: - void updatePipeline() const; - bool _activated{ false }; - ToneMappingType _toneMappingType{ ToneMappingType::DEFAULT }; - }; + void initialize(const PostSettingsInfo &postSettingsInfo); + inline ToneMappingType getToneMappingType() const { return _toneMappingType; } + void setToneMappingType(ToneMappingType toneMappingType); +private: + void updatePipeline() const; + bool _activated{false}; + ToneMappingType _toneMappingType{ToneMappingType::DEFAULT}; +}; - }// namespace scene +} // namespace scene } // namespace cc diff --git a/native/cocos/scene/ReflectionProbe.cpp b/native/cocos/scene/ReflectionProbe.cpp index bc8f7f003a..b4fcacf70c 100644 --- a/native/cocos/scene/ReflectionProbe.cpp +++ b/native/cocos/scene/ReflectionProbe.cpp @@ -25,9 +25,9 @@ #include "scene/ReflectionProbe.h" #include "Define.h" #include "core/scene-graph/Scene.h" +#include "core/scene-graph/SceneGlobals.h" #include "math/Quaternion.h" #include "scene/ReflectionProbeManager.h" -#include "core/scene-graph/SceneGlobals.h" #include "scene/Skybox.h" namespace cc { namespace scene { @@ -144,7 +144,7 @@ void ReflectionProbe::transformReflectionCamera(const Camera* sourceCamera) { _camera->update(true); // Transform the plane from world space to reflection camera space use the inverse transpose matrix - Vec4 viewSpaceProbe{ _node->getUp().x, _node->getUp().y, _node->getUp().z, -Vec3::dot(_node->getUp(), _node->getWorldPosition())}; + Vec4 viewSpaceProbe{_node->getUp().x, _node->getUp().y, _node->getUp().z, -Vec3::dot(_node->getUp(), _node->getWorldPosition())}; Mat4 matView = _camera->getMatView(); matView.inverse(); matView.transpose(); diff --git a/native/cocos/scene/ReflectionProbeManager.h b/native/cocos/scene/ReflectionProbeManager.h index 88c8ba080b..3ef7867d6f 100644 --- a/native/cocos/scene/ReflectionProbeManager.h +++ b/native/cocos/scene/ReflectionProbeManager.h @@ -41,7 +41,8 @@ public: const ccstd::vector& getAllProbes() const { return _probes; } ReflectionProbe* getReflectionProbeById(int32_t probeId); int32_t getMaxProbeId(); -private: + +private: ccstd::vector _probes; }; diff --git a/native/cocos/scene/RenderScene.h b/native/cocos/scene/RenderScene.h index 109d892609..0a4d09b966 100644 --- a/native/cocos/scene/RenderScene.h +++ b/native/cocos/scene/RenderScene.h @@ -24,12 +24,12 @@ #pragma once +#include #include "base/Macros.h" #include "base/Ptr.h" #include "base/RefCounted.h" #include "base/std/container/string.h" #include "base/std/container/vector.h" -#include namespace cc { diff --git a/native/cocos/scene/Shadow.cpp b/native/cocos/scene/Shadow.cpp index a5495e6c44..51aa3ec757 100644 --- a/native/cocos/scene/Shadow.cpp +++ b/native/cocos/scene/Shadow.cpp @@ -24,10 +24,10 @@ #include "scene/Shadow.h" #include +#include "cocos/renderer/pipeline/custom/RenderInterfaceTypes.h" #include "core/Root.h" #include "core/scene-graph/Node.h" #include "scene/Pass.h" -#include "cocos/renderer/pipeline/custom/RenderInterfaceTypes.h" namespace cc { namespace scene { diff --git a/native/cocos/scene/raytracing/Description.h b/native/cocos/scene/raytracing/Description.h index f27bc268d7..02aa3573f1 100644 --- a/native/cocos/scene/raytracing/Description.h +++ b/native/cocos/scene/raytracing/Description.h @@ -23,20 +23,19 @@ ****************************************************************************/ #pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include #include +#include +#include +#include +#include +#include #include #include #include -#include +#include +#include +#include namespace cc { namespace scene { namespace raytracing { @@ -158,7 +157,6 @@ struct Texture { // std::string name; //}; - struct Skin { ccstd::vector joints; int skeleton; @@ -209,8 +207,6 @@ struct Entity { ccstd::string name; }; - - enum class RayTracingPrimitiveType : uint32_t { PER_INSTANCE, PER_MESH_PRIMITIVE, @@ -270,7 +266,6 @@ struct GpuVirtualAddressAndStride { uint64_t strideInBytes = 0; }; - struct RayTracingGeometryTrianglesDesc { uint64_t mTransform3x4 = 0; gfx::Format mIndexFormat = gfx::Format::R16UI; diff --git a/native/cocos/scene/raytracing/RayTracing.cpp b/native/cocos/scene/raytracing/RayTracing.cpp index 2487fd97c7..fb25cb7ee2 100644 --- a/native/cocos/scene/raytracing/RayTracing.cpp +++ b/native/cocos/scene/raytracing/RayTracing.cpp @@ -23,9 +23,9 @@ ****************************************************************************/ #include "RayTracing.h" -#include "cocos/scene/RenderScene.h" #include "cocos/core/Root.h" #include "cocos/scene/Pass.h" +#include "cocos/scene/RenderScene.h" namespace cc { namespace scene { namespace raytracing { @@ -82,7 +82,7 @@ void RayTracing::beforeRender() { _description->opaqueOrMaskInstanceIDs.emplace_back(_instanceNum); } addMaterial(pass); - } + } _instanceNum++; } } @@ -99,7 +99,7 @@ MeshPrim RayTracing::buildRayTracingMeshPrimitive(const IntrusivePtr& auto& meshes = _description->meshes; Mesh mesh{}; mesh.subModel = subModel; - + meshes.emplace_back(std::move(mesh)); MeshPrim prim{}; { @@ -197,8 +197,7 @@ void RayTracing::addMaterial(const IntrusivePtr& pass) { auto pbrBinding = pass->getBinding("pbrMap"); if (pbrBinding != -1) { const TextureInfo metallic{ - static_cast(_description->textures.size()) - }; + static_cast(_description->textures.size())}; pbrMetallic.metallicRoughnessTexture = metallic; pbrMetallic.metallicFactor = getPassUniformAsFloat(pass, "metallic"); pbrMetallic.roughnessFactor = getPassUniformAsFloat(pass, "roughness"); @@ -207,8 +206,7 @@ void RayTracing::addMaterial(const IntrusivePtr& pass) { auto albedoBinding = pass->getBinding("mainTexture"); if (albedoBinding != -1) { const TextureInfo baseColInfo{ - static_cast(_description->textures.size()) - }; + static_cast(_description->textures.size())}; pbrMetallic.baseColorTexture = baseColInfo; pbrMetallic.baseColorFactor = getPassUniformAsFloat(pass, "albedoScale"); addTexture(pass, "mainTexture", albedoBinding); @@ -218,8 +216,7 @@ void RayTracing::addMaterial(const IntrusivePtr& pass) { if (normalBinding != -1) { const MaterialNormalTextureInfo normalTexInfo{ static_cast(_description->textures.size()), - getPassUniformAsFloat(pass, "normalStrength") - }; + getPassUniformAsFloat(pass, "normalStrength")}; mat.normalTexture = normalTexInfo; addTexture(pass, "normalMap", normalBinding); } @@ -227,16 +224,14 @@ void RayTracing::addMaterial(const IntrusivePtr& pass) { if (occlusionBinding != -1) { const MaterialOcclusionTextureInfo occlusionTex{ static_cast(_description->textures.size()), - getPassUniformAsFloat(pass, "occlusion") - }; + getPassUniformAsFloat(pass, "occlusion")}; mat.occlusionTexture = occlusionTex; addTexture(pass, "occlusionMap", occlusionBinding); } auto emissiveBinding = pass->getBinding("emissiveMap"); if (emissiveBinding != -1) { const TextureInfo emissiveTexture{ - static_cast(_description->textures.size()) - }; + static_cast(_description->textures.size())}; mat.emissiveTexture = emissiveTexture; mat.emissiveFactor = ccstd::get(getPassUniform(pass, "emissiveScale")); addTexture(pass, "emissiveMap", emissiveBinding); @@ -251,7 +246,7 @@ void RayTracing::addMaterial(const IntrusivePtr& pass) { _description->materials.emplace_back(std::move(mat)); } -RayTracing::RayTracing(RenderScene* scene): _renderScene(scene), _description(ccnew Description()) {} +RayTracing::RayTracing(RenderScene* scene) : _renderScene(scene), _description(ccnew Description()) {} void RayTracing::setRenderScene(RenderScene* scene) { _renderScene = scene; _description = ccnew Description(); diff --git a/native/cocos/scene/raytracing/RayTracing.h b/native/cocos/scene/raytracing/RayTracing.h index 0e8b0ec207..016c98c30a 100644 --- a/native/cocos/scene/raytracing/RayTracing.h +++ b/native/cocos/scene/raytracing/RayTracing.h @@ -23,15 +23,15 @@ ****************************************************************************/ #pragma once +#include #include #include -#include -#include #include +#include #include "cocos/scene/raytracing/Def.h" namespace cc { namespace scene { - class RenderScene; +class RenderScene; namespace raytracing { class RayTracing : public RefCounted { @@ -39,7 +39,7 @@ public: explicit RayTracing(RenderScene* scene); ~RayTracing() override = default; // getter - inline const ccstd::vector& getTransforms() const { return _description->transforms; } + inline const ccstd::vector& getTransforms() const { return _description->transforms; } inline const ccstd::vector& getTransformPrev() const { return _description->transformPrev; } inline const ccstd::vector& getOpaqueOrMaskInstanceIDs() const { return _description->opaqueOrMaskInstanceIDs; } inline const gfx::Buffer* getInstanceBuffer() const { return _description->instanceBuffer.get(); } @@ -65,8 +65,7 @@ private: void addTexture(const IntrusivePtr& pass, const std::string& name, uint32_t binding); void addMaterial(const IntrusivePtr& pass); static MaterialProperty getPassUniform(const IntrusivePtr& pass, const std::string& name); - static float getPassUniformAsFloat(const IntrusivePtr& pass, const std::string& name); - + static float getPassUniformAsFloat(const IntrusivePtr& pass, const std::string& name); }; } // namespace raytracing } // namespace scene diff --git a/native/cocos/storage/local-storage/LocalStorage.cpp b/native/cocos/storage/local-storage/LocalStorage.cpp index 1aa2edd17e..9918747b83 100644 --- a/native/cocos/storage/local-storage/LocalStorage.cpp +++ b/native/cocos/storage/local-storage/LocalStorage.cpp @@ -39,8 +39,8 @@ #include #endif -#include "base/Macros.h" #include "base/Log.h" +#include "base/Macros.h" static int _initialized = 0; static sqlite3 *_db; diff --git a/native/cocos/ui/edit-box/EditBox-openharmony.cpp b/native/cocos/ui/edit-box/EditBox-openharmony.cpp index ee6f4ecfb2..7ec8673015 100644 --- a/native/cocos/ui/edit-box/EditBox-openharmony.cpp +++ b/native/cocos/ui/edit-box/EditBox-openharmony.cpp @@ -23,12 +23,12 @@ THE SOFTWARE. ****************************************************************************/ -#include "EditBox.h" #include "EditBox-openharmony.h" +#include "EditBox.h" #include "application/ApplicationManager.h" -#include "platform/openharmony/napi/NapiHelper.h" #include "bindings/jswrapper/SeApi.h" +#include "platform/openharmony/napi/NapiHelper.h" namespace cc { /************************************************************************* @@ -56,7 +56,7 @@ void getTextInputCallback() { void callJSFunc(const ccstd::string &type, const ccstd::string &text) { se::AutoHandleScope scope; getTextInputCallback(); - + se::ValueArray args; args.push_back(se::Value(type)); args.push_back(se::Value(text)); @@ -74,13 +74,13 @@ void EditBox::show(const EditBox::ShowInfo &showInfo) { args["defaultValue"] = Napi::String::New(env, showInfo.defaultValue); args["confirmType"] = Napi::String::New(env, showInfo.confirmType); args["inputType"] = Napi::String::New(env, showInfo.inputType); - + args["maxLength"] = Napi::Number::New(env, showInfo.maxLength); args["x"] = Napi::Number::New(env, showInfo.x); args["y"] = Napi::Number::New(env, showInfo.y); args["width"] = Napi::Number::New(env, showInfo.width); args["height"] = Napi::Number::New(env, showInfo.height); - + args["confirmHold"] = Napi::Boolean::New(env, showInfo.confirmHold); args["isMultiline"] = Napi::Boolean::New(env, showInfo.isMultiline); @@ -95,7 +95,7 @@ void EditBox::show(const EditBox::ShowInfo &showInfo) { args["underlineColor"] = Napi::Number::New(env, showInfo.underlineColor); args["textAlignment"] = Napi::Number::New(env, showInfo.textAlignment); - + NapiHelper::postMessageToUIThread("showEditBox", args); } @@ -128,7 +128,6 @@ void OpenHarmonyEditBox::napiOnTextChange(const Napi::CallbackInfo &info) { callJSFunc("input", buffer); } - void OpenHarmonyEditBox::napiOnConfirm(const Napi::CallbackInfo &info) { auto env = info.Env(); if (info.Length() != 1) { @@ -145,5 +144,3 @@ void OpenHarmonyEditBox::napiOnConfirm(const Napi::CallbackInfo &info) { } } // namespace cc - - diff --git a/native/cocos/ui/edit-box/EditBox-openharmony.h b/native/cocos/ui/edit-box/EditBox-openharmony.h index 775408ca04..7008552efd 100644 --- a/native/cocos/ui/edit-box/EditBox-openharmony.h +++ b/native/cocos/ui/edit-box/EditBox-openharmony.h @@ -34,14 +34,12 @@ public: static void napiOnComplete(const Napi::CallbackInfo &info); static void napiOnTextChange(const Napi::CallbackInfo &info); static void napiOnConfirm(const Napi::CallbackInfo &info); - static napi_value show(const std::string& inputMessage); + static napi_value show(const std::string &inputMessage); static napi_value hide(); + private: static napi_ref showEditBoxFunction; static napi_ref hideEditBoxFunction; - }; } // namespace cc - - diff --git a/native/cocos/ui/webview/WebViewImpl-openharmony.cpp b/native/cocos/ui/webview/WebViewImpl-openharmony.cpp index 9ef5452f93..f3211b5b4c 100644 --- a/native/cocos/ui/webview/WebViewImpl-openharmony.cpp +++ b/native/cocos/ui/webview/WebViewImpl-openharmony.cpp @@ -29,10 +29,10 @@ #include "WebView-inl.h" -#include "platform/FileUtils.h" -#include "platform/openharmony/napi/NapiHelper.h" #include "WebViewImpl-openharmony.h" #include "cocos/base/Log.h" +#include "platform/FileUtils.h" +#include "platform/openharmony/napi/NapiHelper.h" static const ccstd::string S_DEFAULT_BASE_URL = "file:///openharmony_asset/"; static const ccstd::string S_SD_ROOT_BASE_URL = "file://"; @@ -172,7 +172,7 @@ void WebViewImpl::goBack() { } void WebViewImpl::goForward() { - NapiHelper::postMessageToUIThread("goForward", Napi::Number::New(NapiHelper::getWorkerEnv(), static_cast(_viewTag))); + NapiHelper::postMessageToUIThread("goForward", Napi::Number::New(NapiHelper::getWorkerEnv(), static_cast(_viewTag))); } void WebViewImpl::setJavascriptInterfaceScheme(const ccstd::string &scheme) { @@ -284,30 +284,29 @@ static void getViewTagAndUrlFromCallbackInfo(const Napi::CallbackInfo &info, int void OpenHarmonyWebView::napiShouldStartLoading(const Napi::CallbackInfo &info) { int32_t viewTag = 0; ccstd::string url; - getViewTagAndUrlFromCallbackInfo(info, &viewTag, &url); + getViewTagAndUrlFromCallbackInfo(info, &viewTag, &url); WebViewImpl::shouldStartLoading(viewTag, url); } void OpenHarmonyWebView::napiFinishLoading(const Napi::CallbackInfo &info) { int32_t viewTag = 0; ccstd::string url; - getViewTagAndUrlFromCallbackInfo(info, &viewTag, &url); + getViewTagAndUrlFromCallbackInfo(info, &viewTag, &url); WebViewImpl::didFinishLoading(viewTag, url); } void OpenHarmonyWebView::napiFailLoading(const Napi::CallbackInfo &info) { int32_t viewTag = 0; ccstd::string url; - getViewTagAndUrlFromCallbackInfo(info, &viewTag, &url); + getViewTagAndUrlFromCallbackInfo(info, &viewTag, &url); WebViewImpl::didFailLoading(viewTag, url); } void OpenHarmonyWebView::napiJsCallback(const Napi::CallbackInfo &info) { int32_t viewTag = 0; ccstd::string url; - getViewTagAndUrlFromCallbackInfo(info, &viewTag, &url); + getViewTagAndUrlFromCallbackInfo(info, &viewTag, &url); WebViewImpl::onJsCallback(viewTag, url); } - } //namespace cc diff --git a/native/cocos/xr/XRRemotePreviewManager.cpp b/native/cocos/xr/XRRemotePreviewManager.cpp index 228fd44d46..99a0b5ebf3 100644 --- a/native/cocos/xr/XRRemotePreviewManager.cpp +++ b/native/cocos/xr/XRRemotePreviewManager.cpp @@ -317,7 +317,7 @@ void XRRemotePreviewManager::sendControllerKeyInfo(const ControllerInfo::AxisInf } void XRRemotePreviewManager::sendControllerKeyInfo(const ControllerInfo::TouchInfo &info) { -#if CC_USE_WEBSOCKET_SERVER + #if CC_USE_WEBSOCKET_SERVER if (_webSocketServer && _isConnectionChanged) { _isConnectionChanged = false; _wssConnections = _webSocketServer->getConnections(); @@ -340,7 +340,7 @@ void XRRemotePreviewManager::sendControllerKeyInfo(const ControllerInfo::TouchIn } } } -#endif + #endif } void XRRemotePreviewManager::resume() { diff --git a/native/extensions/assets-manager/AssetsManagerEx.cpp b/native/extensions/assets-manager/AssetsManagerEx.cpp index 9378541e40..32ec80a6a6 100644 --- a/native/extensions/assets-manager/AssetsManagerEx.cpp +++ b/native/extensions/assets-manager/AssetsManagerEx.cpp @@ -57,7 +57,7 @@ NS_CC_EXT_BEGIN const std::string AssetsManagerEx::VERSION_ID = "@version"; const std::string AssetsManagerEx::MANIFEST_ID = "@manifest"; -AssetsManagerEx* AssetsManagerEx::assetsManager = nullptr; +AssetsManagerEx *AssetsManagerEx::assetsManager = nullptr; // Implementation of AssetsManagerEx @@ -689,7 +689,7 @@ void AssetsManagerEx::prepareUpdateAsync(const PrepareUpdateFinishedCallback &cb _downloadResumed = false; _downloadedSize.clear(); _totalEnabled = false; - std::function prepareFinished = [this, cb](void * param) { + std::function prepareFinished = [this, cb](void *param) { CC_UNUSED_PARAM(param); _updateState = State::READY_TO_UPDATE; if (cb) { @@ -1159,8 +1159,7 @@ void AssetsManagerEx::queueDowload() { return; } - while (_currConcurrentTask < _maxConcurrentTask && !_queue.empty() && !_canceled) - { + while (_currConcurrentTask < _maxConcurrentTask && !_queue.empty() && !_canceled) { std::string key = _queue.back(); _queue.pop_back(); @@ -1192,19 +1191,16 @@ void AssetsManagerEx::onDownloadUnitsFinished() { } } -void AssetsManagerEx::cancelUpdate() -{ - if (_canceled) - { +void AssetsManagerEx::cancelUpdate() { + if (_canceled) { return; } _canceled = true; std::vector> tasks; - for (const auto& it : _downloadingTask) - { + for (const auto &it : _downloadingTask) { tasks.push_back(it.second); } - for (const auto& taskPtr : tasks) { + for (const auto &taskPtr : tasks) { _downloader->abort(taskPtr); // taskPtr 是 std::shared_ptr } _downloadingTask.clear(); diff --git a/native/tests/module-tests/math/test-math.cpp b/native/tests/module-tests/math/test-math.cpp index 3f507346b1..70bbe16380 100644 --- a/native/tests/module-tests/math/test-math.cpp +++ b/native/tests/module-tests/math/test-math.cpp @@ -1,7 +1,7 @@ +#include #include "cocos/math/Math.h" #include "math/Vec3.h" -#include int main(int argc, char **argv) { cc::Mat4 identity{}; diff --git a/native/tests/unit-test/src/math_mat4_test.cpp b/native/tests/unit-test/src/math_mat4_test.cpp index 10e7b4d1f1..221ff5b085 100644 --- a/native/tests/unit-test/src/math_mat4_test.cpp +++ b/native/tests/unit-test/src/math_mat4_test.cpp @@ -273,8 +273,7 @@ TEST(mathMat4Test, test5) { 11, 21, 31, 2, 12, 22, 32, 4, 13, 23, 33, 5, - 0, 0, 0, 1 - ); + 0, 0, 0, 1); matTranspose.transpose(); ExpectEq(matTranspose.m[1] == 12 && matTranspose.m[4] == 21 && matTranspose.m[7] == 0, true); @@ -283,15 +282,14 @@ TEST(mathMat4Test, test5) { cc::Mat4 a{1.111223F, 0.123454F, 0.384183F, 1.111222F, 3.123455F, 4.384183F, 5.111223F, 6.123455F, 2.384183F, 3.111224F, 4.123455F, 5.384183F, 6.111224F, 7.123456F, 8.384183F, 9.111224F}; cc::Mat4 b{1.111224F, 0.123455F, 0.384182F, 1.111223F, 3.123456F, 4.384184F, 5.111224F, 6.123456F, 2.384182F, 3.111223F, 4.123456F, 5.384184F, 6.111223F, 7.123455F, 8.384184F, 9.111223F}; ExpectEq(a.approxEquals(b), true); - + // toRTS: zero axis length const cc::Mat4 m( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, - 0.000002836869271050091, -64.9000015258789, 0, 1 - ); - + 0.000002836869271050091, -64.9000015258789, 0, 1); + cc::Quaternion q; cc::Vec3 t; cc::Vec3 s; diff --git a/native/tests/unit-test/src/node_test.cpp b/native/tests/unit-test/src/node_test.cpp index fd6d244292..9a49b4d7d8 100644 --- a/native/tests/unit-test/src/node_test.cpp +++ b/native/tests/unit-test/src/node_test.cpp @@ -24,8 +24,8 @@ ****************************************************************************/ //#include "core/Director.h" -#include "core/Root.h" #include "core/scene-graph/Node.h" +#include "core/Root.h" //#include "core/platform/event-manager/Events.h" //#include "core/scene-graph/SceneGraphModuleHeader.h" #include "gtest/gtest.h" @@ -118,8 +118,7 @@ TEST(NodeTest, setWorldScale000_and_rotation) { 2, 0, 0, 0, 0, 1.969615506024416, 0.34729635533386066, 0, 0, -0.34729635533386066, 1.969615506024416, 0, - 0, 0, 0, 1 - ))); + 0, 0, 0, 1))); son->setWorldScale(0, 0, 0); EXPECT_TRUE(son->getScale() == Vec3::ZERO); @@ -128,9 +127,8 @@ TEST(NodeTest, setWorldScale000_and_rotation) { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 1 - ))); - + 0, 0, 0, 1))); + son->setWorldScale(2, 2, 2); EXPECT_TRUE(son->getScale().approxEquals(Vec3::ONE)); EXPECT_TRUE(son->getWorldScale().approxEquals(Vec3(2.f, 2.f, 2.f))); @@ -138,8 +136,7 @@ TEST(NodeTest, setWorldScale000_and_rotation) { 2, 0, 0, 0, 0, 1.969615506024416, 0.34729635533386066, 0, 0, -0.34729635533386066, 1.969615506024416, 0, - 0, 0, 0, 1 - ))); + 0, 0, 0, 1))); son->setWorldScale(1, 1, 1); EXPECT_TRUE(son->getScale().approxEquals(Vec3(0.5f, 0.5f, 0.5f))); @@ -148,15 +145,14 @@ TEST(NodeTest, setWorldScale000_and_rotation) { 1, 0, 0, 0, 0, 0.984807753012208, 0.17364817766693033, 0, 0, -0.17364817766693033, 0.984807753012208, 0, - 0, 0, 0, 1 - ))); + 0, 0, 0, 1))); } TEST(NodeTest, setWorldScale0yz_and_rotation) { cc::IntrusivePtr parent(new Node()); - + parent->setScale(2, 2, 2); - + cc::IntrusivePtr son(new Node()); son->setRotationFromEuler(10, 10, 10); son->setParent(parent); @@ -167,9 +163,8 @@ TEST(NodeTest, setWorldScale0yz_and_rotation) { 1.9396926207859084, 0.3472963553338607, -0.3420201433256687, 0, -0.2765167096193736, 1.9396926207859084, 0.40141131793955337, 0, 0.40141131793955337, -0.3420201433256687, 1.9292203542855129, 0, - 0, 0, 0, 1 - ))); - + 0, 0, 0, 1))); + son->setWorldScale(0, 2, 2); EXPECT_TRUE(son->getScale().approxEquals(Vec3(0, 1, 1))); EXPECT_TRUE(son->getWorldScale().approxEquals(Vec3(0, 2, 2))); @@ -177,20 +172,19 @@ TEST(NodeTest, setWorldScale0yz_and_rotation) { 0, 0, 0, 0, -0.2765167096193736, 1.9396926207859084, 0.40141131793955337, 0, 0.40141131793955337, -0.3420201433256687, 1.9292203542855129, 0, - 0, 0, 0, 1 - ))); - + 0, 0, 0, 1))); + EXPECT_TRUE(son->getRotation().approxEquals(Quaternion(0.09406091491321403, 0.09406091491321403, 0.07892647901187543, 0.9879654343559627))); EXPECT_TRUE(son->getWorldRotation().approxEquals(Quaternion(0, 0, 0, 1))); // Could not decompose rotation in Mat4.toSRT since there is a axis is zero, so the rotation will be reset to unit quaternion. - + son->setRotationFromEuler(20, 20, 20); EXPECT_TRUE(son->getRotation().approxEquals(Quaternion(0.1981076317236749, 0.1981076317236749, 0.1387164571097902, 0.9498760324550678))); EXPECT_TRUE(son->getWorldRotation().approxEquals(Quaternion(0, 0, 0, 1))); - + son->setRotationFromEuler(10, 10, 10); EXPECT_TRUE(son->getRotation().approxEquals(Quaternion(0.09406091491321403, 0.09406091491321403, 0.07892647901187543, 0.9879654343559627))); EXPECT_TRUE(son->getWorldRotation().approxEquals(Quaternion(0, 0, 0, 1))); - + son->setWorldScale(1, 1, 1); EXPECT_TRUE(son->getScale().approxEquals(Vec3(0.5, 0.5, 0.5))); EXPECT_TRUE(son->getWorldScale().approxEquals(Vec3(1, 1, 1))); @@ -198,12 +192,11 @@ TEST(NodeTest, setWorldScale0yz_and_rotation) { 0.9698463103929542, 0.17364817766693036, -0.17101007166283436, 0, -0.1382583548096868, 0.9698463103929542, 0.20070565896977668, 0, 0.20070565896977668, -0.17101007166283436, 0.9646101771427564, 0, - 0, 0, 0, 1 - ))); - + 0, 0, 0, 1))); + EXPECT_TRUE(son->getRotation().approxEquals(Quaternion(0.09406091491321403, 0.09406091491321403, 0.07892647901187543, 0.9879654343559627))); EXPECT_TRUE(son->getWorldRotation().approxEquals(Quaternion(0.09406091491321403, 0.09406091491321403, 0.07892647901187543, 0.9879654343559627))); - + son->setWorldScale(2, 0, 0); EXPECT_TRUE(son->getScale().approxEquals(Vec3(1, 0, 0))); EXPECT_TRUE(son->getWorldScale().approxEquals(Vec3(2, 0, 0))); @@ -211,9 +204,8 @@ TEST(NodeTest, setWorldScale0yz_and_rotation) { 1.9396926207859084, 0.3472963553338607, -0.3420201433256687, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 1 - ))); - + 0, 0, 0, 1))); + son->setWorldScale(2, 2, 2); EXPECT_TRUE(son->getScale().approxEquals(Vec3(1, 1, 1))); EXPECT_TRUE(son->getWorldScale().approxEquals(Vec3(2, 2, 2))); @@ -221,9 +213,7 @@ TEST(NodeTest, setWorldScale0yz_and_rotation) { 1.9396926207859084, 0.3472963553338607, -0.3420201433256687, 0, -0.2765167096193736, 1.9396926207859084, 0.40141131793955337, 0, 0.40141131793955337, -0.3420201433256687, 1.9292203542855129, 0, - 0, 0, 0, 1 - ))); + 0, 0, 0, 1))); } } // namespace - diff --git a/native/tests/unit-test/src/scheduler_test.cpp b/native/tests/unit-test/src/scheduler_test.cpp index 769cbacb9e..e268b50a8d 100644 --- a/native/tests/unit-test/src/scheduler_test.cpp +++ b/native/tests/unit-test/src/scheduler_test.cpp @@ -21,9 +21,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include #include #include +#include #include "base/Scheduler.h" #include "utils.h" @@ -32,35 +32,35 @@ using namespace cc; TEST(schedulerTest, performInCocosThreadOrder) { auto scheduler = std::make_shared(); - + std::vector orderResult; - + for (int i = 0; i < 10; ++i) { - auto task = [&orderResult, i, scheduler](){ + auto task = [&orderResult, i, scheduler]() { orderResult.emplace_back(i); - + if (i == 5) { - scheduler->performFunctionInCocosThread([&orderResult](){ + scheduler->performFunctionInCocosThread([&orderResult]() { orderResult.emplace_back(10); }); - - scheduler->performFunctionInCocosThread([&orderResult](){ + + scheduler->performFunctionInCocosThread([&orderResult]() { orderResult.emplace_back(11); }); - - scheduler->performFunctionInCocosThread([&orderResult](){ + + scheduler->performFunctionInCocosThread([&orderResult]() { orderResult.emplace_back(12); }); - + std::this_thread::sleep_for(std::chrono::milliseconds(100)); } }; scheduler->performFunctionInCocosThread(task); } - + scheduler->runFunctionsToBePerformedInCocosThread(); scheduler->runFunctionsToBePerformedInCocosThread(); - + const std::vector expectedResult{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; EXPECT_EQ(orderResult, expectedResult); }